texts
list
tags
list
[ "about java, String.replaceAll", "I've been trying to solve this problem, i did a research a little about the replaceAll method and it seems that it uses a regular expression. But i never heard of any regular expression that contains '.' character. This is the code i've been using:\n\nSystem.out.println(parsed[1]);\nmyStatus = parsed[1].replaceAll(\"...\", \" \");\nSystem.out.println(\"new: \" + myStatus);\nstatus.setText(myStatus);\n\n\nOutput result is:\n\nold...string\nnew:" ]
[ "java", "string", "replaceall" ]
[ "Uploading Retina Images to Google Adwords", "I would like to upload retina versions of my Google Adwords display ads (at twice the size) for my campaign, is this possible, and if so, how/where do I upload the retina-sized files?" ]
[ "google-ads-api" ]
[ "android ndk debug trap", "In NDK (Only-native-C++) applications what is the correct way to set a programmatic debug trap? I mean stopping the application with possiblity to examine call stack, variables, etc.\nFor instance, under WIN32 debug trap in my GameEngine is declared as\n\n#define DIE() __asm{ int 3 }\n\n\nand for iOS it's\n\n# if TARGET_IPHONE_SIMULATOR\n# define DIE() {__asm__(\"int3\");}\n# else\n# define DIE() {__asm__(\"trap\");}\n# endif\n\n\nWhat would be a correct one for an Android NDK application?" ]
[ "android", "debugging", "android-ndk" ]
[ "What is the correct alternative to resetting a mock after setup in Mockito?", "I'm new to unit testing and trying to learn the proper style. I like to setup the object that I am testing so that I can test it as if it were in use instead of only testing a newly constructed object. I can't test removing things from an object that is empty, as many objects are when constructed.\n\nTake the following for an example where ObservedList is being tested and ListListener is a necessary class that is being mocked.\n\npublic final class ObservedListTest {\n private ListListener<Integer> listener;\n private ObservedList<Integer> list;\n @BeforeMethod public void setup() {\n listener = mock(ListListener.class);\n list = new ObservedList<Integer>(listener);\n list.addAll(Arrays.asList(1,2,3));\n reset(listener);\n }\n @Test public void addFirst() {\n list.add(0, -1);\n verify(listener).listEdited(list, 0, 1, Collections.<Integer>emptyList());\n verifyNoMoreInteractions(listener);\n }\n @Test void addAtEnd() {\n list.add(9);\n verify(listener).listEdited(list, 3, 4, Collections.<Integer>emptyList());\n verifyNoMoreInteractions(listener);\n }\n @Test void removeMiddle() {\n list.remove(Integer.valueOf(2));\n verify(listener).listEdited(list, 1, 1, Collections.singletonList(2));\n verifyNoMoreInteractions(listener);\n }\n}\n\n\nAs a novice this seems to work well to me, but I know that it's bad practice because it uses the reset method. I call reset because I don't want the actual tests to get confused due to interactions that happened in the setup.\n\nThe javadoc for reset doesn't even get around to telling you what the method does because it is so busy telling you that you shouldn't use it. Ordinarily I'd simply take that advice and avoid reset by removing my setup method and adjusting my tests to look more like this:\n\n @Test void removeMiddle() {\n listener = mock(ListListener.class);\n list = new ObservedList<Integer>(listener);\n list.addAll(Arrays.asList(1,2,3));\n list.remove(Integer.valueOf(2));\n InOrder inOrder = inOrder(listener);\n inOrder.verify(listener).listEdited(list, 0, 3,\n Collections.<Integer>emptyList());\n inOrder.verify(listener).listEdited(list, 1, 1,\n Collections.singletonList(2));\n verifyNoMoreInteractions(listener);\n }\n\n\nThis also seems to work well to me. The problem is that the documentation for the reset method says:\n\n\n Instead of reset() please consider writing simple, small and focused\n test methods over lengthy, over-specified tests.\n\n\nI respect that Mockito is designed to encourage good style in unit tests and I want to learn from it, but I'm having a hard time sorting out what message it is trying to send me. When I eliminate reset from my tests, my tests get complex, longer and less focused, so obviously I'm doing it wrong.\n\nWhat does doing it right look like?" ]
[ "java", "unit-testing", "mocking", "mockito" ]
[ "How does Android support library work with target SDK level?", "I understand that I can use support libraries to add elements that aren't natively available. However, does the newest SDK version (Lollipop, for example) use these support libraries as well, or does it use native elements? E.g. if I run the app on a Lollipop device, will it use native or support elements? I'm asking because, when editing source code (in Android Studio), I'm only editing one version of the file, I can't, for example, chose to create one file for ICS, and other for Lollipop, so how does the system know which elements to use?" ]
[ "android", "android-studio", "android-support-library", "android-appcompat" ]
[ "React Native - Image Semi Circle (using CSS)", "I have a circular image, which I need to show in Semi Circle using React Native like as shown in attached file. Please help with the CSS." ]
[ "css", "image", "react-native", "geometry" ]
[ "Adjust opus bit rate in Mozilla Firefox - WebRTC", "I just read an article from this link: https://developer.mozilla.org/en-US/docs/Web/Media/Formats/WebRTC_codecs\nI want to know if there's a way on how to manually or programmatically adjust the default 48 kbps to 8 kbps? I am currently working on WebRTC and I need to use the narrowband (NB) for my webphone.\n\nAnother article: https://hacks.mozilla.org/2012/07/firefox-beta-15-supports-the-new-opus-audio-format/" ]
[ "webrtc", "mozilla", "opus" ]
[ "Portal to another component", "I've found this example on official site which describes how to use portal. In this example is being created new 'root' div for modals with use of ReactDOM.createPortal(). Is there a way to teleport component to another component (not just different root).\n\nIt might not be done with portal - I just thought it might be useful for this solution\n\n\n\nI am trying to 'extend' Navigation with button which has logic dependency on MyComponentA or MyComponentB (different button, different behaviour directed by different component but placed in DOM of navigation).\n\nThis is simplified example of what I am trying to achieve:\n\nApp\n\nThis is root component of my application which includes Navigation, MyComponentA and MyComponentB\n\nclass App extends React.Component {\n render() {\n return (\n <Navigation/>\n <MyComponentA/>\n <MyComponentB/>\n );\n }\n}\n\n\nNavigation\n\nThis is component where I want to place output of portal.\n\nclass Navigation extends React.Component {\n render() {\n return (\n <OutputOfPortal>\n {/* I want to teleport something here from another component */}\n </OutputOfPortal>\n );\n }\n}\n\n\nMyComponentA\n\nThis is component where I want to place source for portal. Same situation as for MyComponentB but with different content.\n\nclass MyComponentA extends React.Component {\n render() {\n return (\n {/* Another code */}\n <InputOfPortal>\n {/* I want to teleport something from here to navigation */}\n <button onClick={this.functionInThisComponent}> click me </button>\n </InputOfPortal>\n {/* Another code */}\n );\n }\n}" ]
[ "javascript", "reactjs" ]
[ "How to make hr tag extend the full width of screen", "I'm trying to have a div that has a max width for all its child elements except for hr, so it will extend the full width of the screen. This is what I have right now that's not working:\n\n#content :not(hr){\n margin-left: auto;\n margin-right: auto;\n max-width: 250px;\n}\n\n#content hr{\n height: 1px;\n color: #d3d3d3;\n}\n#container{\n min-height:100%;\n height: auto !important;\n height: 100%;\n margin: 0 auto -138px;\n}\n\n\nAnd in the html:\n\n<html>\n <body>\n <div id=\"container\">\n <div id=\"header\">...</div>\n <div id=\"content\">\n ...\n <hr />\n ...\n </div>\n </div>\n </body>\n</html>" ]
[ "html", "css" ]
[ "Adding dummy variables in panel linear model (regression) in R", "I have a categorical independent variable (with options of \"yes\" or \"no\") that I want to add to my panel linear model. According to the \n answer here: After generating dummy variables?, the lm function automatically creates dummy variables for you for categorical variables.\n\nDoes this mean that creating dummy variables through i.e. dummy.data.frame is unnecessary, and I can just add in my variable in the plm function and it will automatically be treated like a dummy variable (even if the data is not numerical)? And is this the same for the plm function?\n\nAlso, I don't have much data to begin with. Would it hurt if I manually turned the data into numbers (i.e. \"yes\"=1, \"no\"=0) without creating a dummy variable?" ]
[ "r", "linear-regression", "dummy-variable" ]
[ "Python 'ValueError: object arrays are not supported ' when calculating single value decomposition", "I have a numpy array:\nmatrix = array([[0,\n array([0.05385944, 0.05419472, 0.05453447])],\n [1,\n array([0.05385944, 0.05419472, 0.05453447])],\n [2,\n array([0.05385944, 0.05419472, 0.05453447])].... , \n dtype=object)\n\nI a trying to calculate the singular value decomposition using scipy.linalg like:\nfrom scipy.linalg import svd\nU, s, VT = svd(matrix)\n\nBut this gives me a value error\nValueError: object arrays are not supported\n\nI think the issue comes from my matrix having the object datatype, but I have no idea how to fix this." ]
[ "python", "numpy", "valueerror", "svd" ]
[ "jQuery to fade entire website content, to reveal background image", "I've got a site with a full size background image. I'm looking to include a button or link titled \"Show background photo\", or something like that. Once clicked the entire page would fade out leaving the background image visible, and in the center another link/ button would fade in saying \"Show Page Content\". Once clicked, would fade back in the website content.\n\nHope this makes sense. I've found a good example: http://ines-papert.de/en/home\nI know I could steal the code from that site, but that would be cheating, nor would I understand it.\n\nI'm a novice with jQuery, and am unsure where to start with the code. Many Thanks in advance." ]
[ "jquery" ]
[ "nested form has_one not setting form attributes rails 4", "I have three models namely \"Employee::TaxSettingBatch\", \"Employee::HousingLoanInterest\", \"Employee::InvestmentBankDetail\". these models are related to each other as follows \n\nclass Employee::TaxSettingBatch\n include Mongoid::Document\n has_one :housing_loan_interest, class_name: Employee::HousingLoanInterest'\n accepts_nested_attributes_for :housing_loan_interest, allow_destroy: true\nend\n\nclass Employee::HousingLoanInterest\n include Mongoid::Document\n field :property_type, type: String \n belongs_to :employee_tax_setting_batch, class_name: 'Employee::TaxSettingBatch' \n has_many :investment_bank_details, class_name: 'Employee::InvestmentBankDetail'\n accepts_nested_attributes_for :investment_bank_details, allow_destroy: true\nend\n\n\nThe problem is that when I am trying to save the data I am getting below error. \n\nProblem:\n Attempted to set a value for 'employee_housing_loan_interest' which is not allowed on the model Employee::TaxSettingBatch.\n\nMy parameters are: \n\n{\"utf8\"=>\"✓\",\n \"_method\"=>\"patch\",\n \"authenticity_token\"=>\"Afig1spGvAgNX9bj7VEwRLO6FvTVH+ZOtNDBpEHY+LF4c10yn0KUHAlOn5oB/isfOwQF/VHjIcT7Etm2t0MHfA==\",\n \"section\"=>\"housing_loan_info\",\n \"employee_tax_setting_batch\"=>\n {\"employee_housing_loan_interest\"=>\n {\"property_type\"=>\"Self occupied property\",\n \"_destroy\"=>\"false\",\n \"investment_bank_details_attributes\"=>\n {\"1545132357997\"=>\n {\"loan_type\"=>\"Self\",\n \"construction_completion_month_and_year\"=>\"jan 200\",\n \"lender_bank_name\"=>\"hdfc\",\n \"lender_pan_number\"=>\"bcopp15\",\n \"loan_interest_details_attributes\"=>\n {\"0\"=>{\"component\"=>\"Pre EMI Amount\", \"declared_amount\"=>\"2\", \"verified_amount\"=>\"3\", \"remarks\"=>\"\"},\n \"1\"=>{\"component\"=>\"Interest Repayment amount\", \"declared_amount\"=>\"2\", \"verified_amount\"=>\"3\", \"remarks\"=>\"\"}}}}}},\n \"disallowed_amount\"=>\"\",\n \"controller\"=>\"employee/tax_setting_batches\",\n \"action\"=>\"update\",\n \"company_id\"=>\"55532e18517569120b7b0000\",\n \"employee_id\"=>\"55532e18517569120b7c0000\",\n \"tax_setting_id\"=>\"5bfe84d8c142e30aa0000125\",\n \"id\"=>\"5c0f9676c142e309980002cb\"}\n\n\nParameters for \"employee_housing_loan_interest\" are not getting send as \"employee_housing_loan_interest_attributes\" that is why I am getting this issue. Help me!\n\nMy form :\n\n<%= nested_form_for @tax_setting_batch, url: company_employee_tax_setting_tax_setting_batch_path(@company, @employee, @tax_setting, @tax_setting_batch), html: {id: 'form-80c-details', class: 'form-horizontal'}, remote:true,:authenticity_token=> true do |f| %>\n <%= f.fields_for @tax_setting_batch.housing_loan_interest.nil? ? @tax_setting_batch.build_housing_loan_interest : @tax_setting_batch.housing_loan_interest , :wrapper => false do |form| %>" ]
[ "ruby-on-rails", "nested-forms" ]
[ "jquery ajax post method to post the json data to particular url and retrieve in particular webservice", "I have ajax request to post data to asmx webservice, how will i post multiple data values as json data to that url \n\n $.ajax(\n {\n type:\"POST\",\n url:\"AjaxService.asmx/CheckUserNameAvailability\",\n data:\"{\\\"userName\\\":\\\"\" + userName + \"\\\"}\",\n dataType:\"json\",\n contentType:\"application/json\",\n success: function(response) \n {\n if(response.d == true) \n {\n $(\"#display\").text(\"username is available and updated to database\");\n $(\"#display\").css(\"background-color\",\"lightgreen\");\n }\n else\n {\n $(\"#display\").text(\"username is already taken\");\n $(\"#display\").css(\"background-color\",\"red\");\n }\n }\n });\n\n\nThis is the particular webservice code where i retrieve the username ,how can i retrieve many values passed from that paticular url ,for example i have to retrieve username ,password, email,phoneno etc... \n\n public class AjaxService : System.Web.Services.WebService\n {\n [WebMethod]\n public bool CheckUserNameAvailability(string userName)\n {\n List<String> userNames = new List<string>() { \"azamsharp\", \"johndoe\", \"marykate\", \"alexlowe\", \"scottgu\" };\n\n var user = (from u in userNames\n where u.ToLower().Equals(userName.ToLower())\n select u).SingleOrDefault<String>();\n\n return String.IsNullOrEmpty(user) ? true : false; \n\n }\n\n }\n}" ]
[ "c#", "asp.net", "json", "jquery" ]
[ "Pass Powershell Variables to MySQL", "I am using SimplySQL (https://github.com/mithrandyr/SimplySql) to access MySQL from Powershell. I have a script which gets me yesterday's sunrise and sunset times. What I am attempting to do next is pass those variables into the mysql script to pull a corresponding column of values from between those hours. However, I am missing something.\nSunrise/Sunset:\n$yesDate = (Get-Date).AddDays(-1) | Get-Date -Format "yyyy-MM-dd"\n$daylight = (Invoke-RestMethod "https://api.sunrise-sunset.org/json?lat=35.608237&lng=-78.647497&formatted=0&date=$esDate").results\n$sunrise = ($daylight.Sunrise | Get-Date -Format "HH:mm:ss")\n$sunset = ($daylight.Sunset | Get-Date -Format "HH:mm:ss")\n\nMySQL query:\nCD "C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin"\nOpen-MySqlConnection -UserName xxxxxxx -Password -Database xxxxxxxx\nInvoke-SqlQuery -Query "select LogDateTime, UVindex from `monthly_new` where LogDateTime between (curdate()) - interval 1 day and (curdate())"\nClose-SqlConnection\n\nRight now, running each separately sets the variables, and returns all values from 12am to 11:59pm yesterday. But if I try to integrate the $sunrise and $sunset variables into the mysql query, it has no idea what is going on. It could be just a simple syntax issue, but I am not sure." ]
[ "mysql", "powershell" ]
[ "How to call forms from another class?", "I want to call a chart from another class. The code of the chart is this:\n\npublic partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n\n chart1.Series[\"S1\"].Points.AddXY(0, 0, 10);\n chart1.Series[\"S1\"].Points.AddXY(0, 0, 10);\n\n }\n\n}\n\n\nand I want to call this chart from another different class, I tried that:\n\nForm1 chart1 = new Form1();\nchart1.Show();\n\n\nThanks!" ]
[ "c#", "visual-studio", "winforms" ]
[ "Module uninstall clean-up", "Is there a hook that I can implement in my module so that I can run some clean up code when my module is uninstalled. I create a number of variables using variable_set() and I would like to delete these variables when the module is uninstalled." ]
[ "drupal", "drupal-6", "drupal-modules" ]
[ "Creating text file into C++ addon of node.js", "I want to know how i can create file and append data inside it in c++ addon (.cc) file of node.js ??\n\nI have used below code to do same, but not able to find file \"data.txt\" in my ubuntu machine(reason behind it may be below code is not correct way to create file, but strange i haven't received any error/warning at compile time).\n\nFILE * pFileTXT;\n\npFileTXT = fopen (\"data.txt\",\"a+\");\n\nconst char * c = localReq->strResponse.c_str();\n\nfprintf(pFileTXT,c);\n\nfclose (pFileTXT);" ]
[ "c++", "node.js", "add-on" ]
[ "Choosing game model design", "I need help designing a game where characters\nhave universal actions(sit, jump, etc.) or same across all characters; roughly 50 animations\nunique attack patterns(different attacks) roughly 6 animations per character\nitem usage attacks(same across all characters) roughly 4 animations per item which could scale to 500+\nWhat would be the best way to design this? I use blender for animations. And I just started a week ago.\nI’m thinking of using either one model for everything and limiting actions or to create multiple and import those separately. Any help is appreciated!\nEdit: also considering optimization since I don’t want lag to incur; making a mmo like game." ]
[ "game-engine", "godot" ]
[ "Fixing shift key on emacs for mac", "I'm currently sshing from my mac to a CentOS box, where I run emacs. For whatever reason, the shift key doesn't seem to work when issuing a keyboard sequence. I suspect the wrong key code is being sent.\n\nFor example, I've remapped my help command to the following:\n\n(global-set-key (kbd \"C-?\") 'help-command)\n\n\nExecuting this keyboard sequence in a typescript file reveals that it's invoking the delete-backward-char command, which is a compiled Lisp function from simple.el. (In order to even check what command the keyboard sequence was executing, I had to temporarily remap help to C-o.)\n\nSimilarly, I have the following key binding set up for typescript mode\n\n(setq tss-popup-help-key \"C-:\")\n\n\nLikewise, it looks like the SHIFT key hasn't registered because I get the following definition in the help manual when I reverse lookup the sequence:\n\n; runs the command typescript-insert-and-indent, which is an\ninteractive compiled Lisp function in `typescript.el'.\n\nIt is bound to ,, ;, ), (, }, {.\n\n(typescript-insert-and-indent KEY)\n\n\nIn other words, emacs registers the colon as a semi-colon.\n\nThis is a recurring problem with keyboard sequences that require me to use a SHIFT key. How do I get the SHIFT key to work properly when working on emacs through a mac?\n\nFor the record, when I use Emacs for OSX, the shift key works great." ]
[ "macos", "emacs", "emacs24" ]
[ "Push view controller with custom page curl animation", "I want page curl like animation when I push another view. I don't need the default one.\nCan I push view with custom animation? I have image sequence.\nHow can we do that? Help me, please!" ]
[ "iphone" ]
[ "Convert string to UNIX timestamp", "I'm trying to convert the string 11/24/2011 @ 01:15pm to a UNIX timestamp. The format is m-d-Y @ h:ia\n\nI can't seem to get strtotime to work with the string. Is there a way to reverse the data function? Is my only choice to create a new non-default php function to convert the string?\n\nThe server is running CentOS 5, Apache 2.2 and PHP 5.2.17." ]
[ "php", "date", "time", "strtotime", "unix-timestamp" ]
[ "Entity Framework Code First with Repository Pattern and lazy loading?", "Consider the following simple example:\n\npublic class Employee\n{\n public int Id { get; set; }\n public string Name { get; set; }\n ... other employee properties ...\n public virtual ICollection<Sale> Sales { get; set; } \n}\n\npublic class Sale\n{\n public int Id { get; set; }\n public int EmployeeId { get; set; }\n public DateTime DateSold { get; set; }\n ... other sale properties ...\n public virtual Employee Employee { get; set; }\n}\n\npublic class SampleContext: DbContext\n{\n public DbSet<Employee> Employees { get; set; }\n public DbSet<Sale> Sales { get; set; }\n}\n\n\nI create a repository that uses the above entity framework context to return employees by id:\n\npublic interface IRepository\n{\n Employee EmployeeById(int id);\n}\n\n\nMy question is in regards to populating and returning employee sales. In the vast majority of use cases, the code requesting a particular person only needs the sales for a given day. How should I handle that? Do I extend the Employee class to some EmployeeWithDailySales object?\n\nI can't use lazy loading in the calling function as the DbContext reference does not exist once I return from the repository class. Does that mean I am doing something incorrect to begin with? Is my idea of the repository itself flawed?\n\nI could preload the employee's sales when I initially populate the Employee object but that would likely result in many unneeded records in most situations.\n\nAny advice is greatly appreciated. I am still trying to get a clear understanding of how to use these patterns and frameworks correctly." ]
[ "asp.net-mvc-3", "entity-framework", "design-patterns", "ef-code-first", "repository-pattern" ]
[ "method is executing before ajax call getting completed", "I am trying to call a method after all ajax calls gets completed but some reason the method id getting triggered before one of the ajax call is getting completed. i tried to keep the method in ajax complete section and using $.when() and async:false but i am getting same result. I don't know if its because i am using jsonp ?\n\nMy jquery version is 1.11.0\n\nBelow is my code\n\nfunction getBBTrending() {\n bbProductD = [];\n jQuery.ajax({\n type: \"GET\",\n url: \"crazycalls/getbbtrending.php\",\n // cache must be true\n cache: true,\n crossDomain: true,\n success: function (data) {\n bbTrending = data.results;\n for (var i = 0; i < 4; i++) {\n getProductdetails(bbTrending[i].productLink);\n }\n },\n dataType: 'json'\n });\n}\n\nfunction getProductdetails(pLink) {\n jQuery.ajax({\n type: \"GET\",\n url: pLink,\n // cache must be true\n cache: true,\n crossDomain: true,\n success: function (data) {\n pushArray(bbProductD, data);\n },\n dataType: 'jsonp'\n });\n}\n\n\n\n\nfunction pushArray(array1,data1)\n{\n array1.push(data1);\n}\n\n// this function is executing before pushArray(array1,data1)\njQuery( document ).ajaxStop(function() {\n displayProducts(bbProductD);\n})\nfunction displayProducts(bbProductD)\n{\n jQuery(\"#bbButtongroup\").show();\n var rProducts = bbProductD; \n var rating;\n var html = ['<div class=\"row\">']\n for (var i = 0; i < rProducts.length; i++)\n {\n var entry = rProducts[i];\n var title = entry.name\n var Tnail = entry.image;\n var sPrice = entry.salePrice;\n var rPrice = entry.regularPrice;\n var hcode = '<div class=\"col-sm-6 col-md-4\"><div class=\"thumbnail\"><img style=\"height: 200px; width: 100%; display: block;\" src=\\\" '+ Tnail + '\\\" alt=\"...\"><div class=\"caption\"><h3 style=\"font-size: 14px;\">'+ title +'</h3><p><span class=\"label label-info\"> Regular Price : '+ rPrice +'</span></p><p><span style=\"float: right;\" class=\"label label-info\">Sale Price :'+ sPrice +'</span></p><p><a href=\\\"' + entry.url + '\\\" class=\"btn btn-primary\" role=\"button\">Buy</a><a href=\"#\" class=\"btn btn-default\" role=\"button\">View</a></p></div></div></div>';\n html.push(hcode);\n }\n html.push('</div>');\n document.getElementById('pContainer').innerHTML = html.join('');\n}\n\n\nthis is how i added using $.when\n\njQuery.when( { getBBTrending(),getProductdetails()}).done(function() {\n displayProducts(bbProductD);\n});\n\n\nany advice?" ]
[ "javascript", "jquery", "ajax" ]
[ "Invalid file path exception", "My application throws an exception - java.io.FileNotFoundException: Invalid file path. Not sure why. I've read the questions and answers about the theme but no one could help me.\n\nHere is the code:\n\n String userhome = System.getProperty(\"user.home\");\n String filename = null;\n File rdp = null;\n for (int item = 0; item < darab; item++) {\n filename = toValidFileName(ProgramList.get(item).getP_name());\n filename += \".rdp\";\n rdp = new File(userhome, filename);\n try {\n JFrame panel;\n panel = new JFrame();\n panel.setSize(400, 10);\n panel.setLocation(300, 400);\n panel.setTitle(\"Saving \" + rdp.getAbsolutePath());\n\n try (FileOutputStream fstr = new FileOutputStream(rdp)) {\n panel.setVisible(true);\n char c;\n for (int j = 0; j < 2336; j++) {\n c = ProgramList.get(item).p_body.charAt(j);\n fstr.write(c);\n }\n fstr.flush();\n fstr.close();\n panel.setVisible(false);\n }\n\n } catch (IOException ioe) {\n JOptionPane.showMessageDialog(this,\n ioe.getMessage(), \"Save rdp file\", JOptionPane.ERROR_MESSAGE);\n System.err.println(ioe.getMessage() + \" : \"+ rdp.getAbsoluteFile());\n }\n }\n\n\nAnd the result:\nInvalid file path : C:\\Users\\LiPI\\CosmicLd.rdp\n\ntoValidFilename() is remove the forbidden characters from the (KORG RADIAS) program name to create a valid file name.\n\nI've not found my fault :(\nThe destination directory is not read only, the user has the necessary privilegs. When I view the file.canWrite() after the line:\n rdp = new File (userhome, filename); \nit's always false.\nWhat did I do wrong?\nThanks!" ]
[ "java", "java-7", "netbeans-8.2" ]
[ "Support for em-dash in Windows file paths using StgOpenStorage()", "I had a customer reporting problems with a file in a specific path. Debugging some old Windows code, I have found that the code in question that fails is a call to StgOpenStorage(). The path in question that fails has an em-dash. If I take this em-dash out by renaming the file, then the call to StgOpenStorage() succeeds.\n\nSo my question is this: is this a known limitation with this function? Are there likely to be other Windows SDK functions that fail with special characters like em-dash? I noticed there is a call to mbstowcs() prior to calling this function, which makes me wonder if the problem is due to the code-page mapping the em-dash character incorrectly. The wchar path looks okay in the Visual Studio debugger prior to the call, so it seems weird that the function would fail on a path that the system allows." ]
[ "visual-c++", "windows-7-x64", "ole" ]
[ "Node-Red function editor dialogs not updating when I type", "I can't see what I am typing or pasting into some Node-Red text boxes when editing nodes. For example, the Function property of the function node or the Body property of the comment node. \n\nIf I Ok the unseen edits and then double-click the node again, I can see that my edits were made.\n\nI can see what I am typing into other properties such as the Name of the function node or the Title of the comment node.\n\nI notice that this behaviour affects multi-line text boxes rather than single-line text boxes." ]
[ "node.js", "raspberry-pi", "node-red" ]
[ "How to alter an empty URL in CodeIgniter?", "I want to redirect my webpage from mysite.com/en/home, whereas the URI is mysite.com.\n\nI tried a lot of things with routes.php, none of those worked:\n\n$route['(:any)/'] = 'pages/view/$1/home';\n$route[''] = 'home';\n$route[''] = 'en';\n\n\nIs this only obtainable by .htaccess? And if so, how can I do it so that it only affects mysite.com, or mysite.com/en queries.\n\nSince the other URL's are like mysite.com/en/about , I don't want to mess them into mysite.com/en/home/about\n\np.s.\n\nI have the following rule to convert mysite.com/x/y to mysite.com/index.php/x/y : \n\nRewriteEngine on\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule .* index.php/$0 [PT,L] \n\n\ncould it be the case that this rule is conflicting with others?\n\nThanks for any help.\n\nEdit:\n\nOk, to try Diego Camacho's answer, I created an empty CI project, set the base url in config.php, then made the -only- two rules in routes.php as these: \n\n$route['(:any)'] = 'Site';\n$route['default_controller'] = \"pages/view\";\n\n\nand added this function to pages.php (controller):\n\n public function view($arg)\n{\n if(!$arg)\n {\n echo \"no argument\";\n }\n else\n {\n echo \"argument = $arg\";\n }\n}\n\n\nSo now, I expect it to work like this:\n\nhttp://localhost/ci/index.php/ -> no argument\nhttp://localhost/ci/index.php/abc -> arg = abc\n\nbut instead, it returns these:\n\nhttp://localhost/ci/index.php/ -> \n\n\n A PHP Error was encountered\n \n Severity: Warning\n \n Message: Missing argument 1 for Pages::view()\n \n Filename: controllers/pages.php\n \n Line Number: 26\n \n A PHP Error was encountered\n \n Severity: Notice\n \n Message: Undefined variable: arg\n \n Filename: controllers/pages.php\n \n Line Number: 28\n \n no argument\n\n\nhttp://localhost/ci/index.php/abc\n\n\n\n 404 Page Not Found\n \n The page you requested was not found.\n\n\nWhat am I doing wrong here ?" ]
[ "php", ".htaccess", "codeigniter", "redirect", "url-rewriting" ]
[ "Path functions available to Jelly script?", "I'd like to be able to do things like separate the directory and file name from a full path in Hudson/Jenkins's jelly script. \n\nFor example if I have /dir1/dir2/dir3/file.ext I'd like to (in jelly script) get access to /dir1/dir2/dir3 and file.ext.\n\nAre the java io functions like getPath() and getName() available to jelly script?" ]
[ "hudson", "jenkins", "jelly" ]
[ "javascript regex multiple queries", "I have a whole array of regexp queries to make recursively going through the string in order.\n\nIs there a way I can do it all with 1 call such as (doesn't work)?\n\nstr.replace(/query1|query2|query3|query4|...|[0-9]+|[^]/,\n \"reslt1|reslt2|reslt3|reslt4|...|procNumb|procChar\");\n\n\nIt need only work in Firefox. Right now I'm stuck with:\n\nstr.replace(... ,function(a,b,c){if (a==\"query1\") return \"reslt1\"; ..............});\n\n\nThanks!\n\nEdit: Sorry if confusing. Goal:\n\nBefore: \"query1query3x123query2\"\nAfter: \"reslt1reslt3procChar(x)procNumb(123)reslt2\"\n\nThe main thing is I need I to process the string 1 fragment at a time recursively, so I think I must use a super-query like that to match any, or not use regexes at all. I just wonder if there's a way to automatically pair the results to the queries when using lots of pipes. I am not so familiar with javascript regex but I couldn't find anything on mdc unfortunately." ]
[ "javascript", "regex" ]
[ "How to distinguish a bool from a z3 expression?", "I read z3 expressions from an input file in Python. Then later in my code I call __deepcopy__() on them.\n\nThe problem is that sometimes the input z3 expression is True or False, then Python gets confused and thinks they are bool and refuses to call __deepcopy__(). \nThe error message is \n\nAttributeError: 'bool' object has no attribute '__deepcopy__'\n\nHow can I distinguish between bool and z3 expressions in this case?" ]
[ "python", "python-2.7", "z3", "z3py" ]
[ "connect two different clients to the same server with envoy proxy", "I am new to Envoy Proxy and am trying to understand how it works.\nI want to try to develop this scenario:\nTwo different clients, A and B (probably websocket), when client B connects, A is already connected.\nIn the Envoy I have a cluster of microservices.\nIs there a way to tell envoy, or whatever, to have B connect to the same server as A?\nCould it be a solution to create a route for A (random server) and one for B that uses some identifier (token, id issued by the random server to A) to point the connection to the same server?\nThanks" ]
[ "websocket", "cloud", "envoyproxy" ]
[ "WooCommerce - Show ex. VAT/incl. VAT label", "In my WooCommerce store I have setup taxes for all European countries, but for all other countries there a no taxes. So I have made one tax line with a wilcard \"*\" for all other countries with 0 percent tax.\n\nFuther more we also have business customers (custom user role) which also are eligible to get 0 tax (handled by another plugin).\n\nThe prices shows the correct price, but it is important for us to have a label show with the product that shows if the price is \"incl. VAT\" or \"Ex. VAT\"?\n\nHave tried almost all settings, snippets I could find etc., but can not find a solution :(\n\nAnyone who can help with that?\n\nThanks in advance" ]
[ "wordpress", "woocommerce" ]
[ "ng-cookie and Theme Switcher", "I'm trying to add cookie in my controller that switch thems .\nhere is my code : \n\nCommon.css is my default css for every user\n\n\nHeaderCtrl.js \n\nmyApp.controller('headerCtrl', function ($scope, $cookieStore) {\n var currentTheme = $cookieStore.get(\"App/Common/Style/Common/common.css\");\n\n $scope.changeTheme = function (theme) {\n if (!currentTheme) {\n $scope.currentTheme = \"App/Common/Style/Common/common.css\";\n }\n else if(theme === 'red'){\n $scope.currentTheme = \"App/Common/Style/Switcher/styleRed.css\";\n } else if (theme === 'common') {\n\n $scope.currentTheme = \"App/Common/Style/Switcher/common.css\";\n\n } \n $cookieStore.put(\"App/Common/Style/Common/common.css\", $scope.currentTheme);\n };\n\n\n}); \n\n\nHTML \n\n<link ng-href=\"{{currentTheme}}\" rel=\"stylesheet\" /> \n\n\nUPDATE\nthat's the fiddle i got idea from .\n\nit change my themes, but cookie not working .\nam i missing something ?" ]
[ "javascript", "angularjs", "cookies" ]
[ "Is there any limit that application state can store ??", "Is there any limit that application state in asp.net can store ?? \nAm trying to know the limit so that I can avoid any slow on my application performance." ]
[ "c#", "asp.net" ]
[ "Redactor: Make dropdown menu look like an actual dropdown", "Imperavi's WYSIWYG jQuery editor - Redactor - is a wonderful piece of code with clear documentation. However in some cases it lacks configurability.\n\nI am trying to add a dropdown menu. Their documentation demonstrates how to do precisely this, but the end result is just a square button with an image. I would like to make the dropdown \"button\" look like an actual dropdown menu (like a selector). Would this be possible without any deep hacks?" ]
[ "redactor" ]
[ "getting error while removing duplicates from csv using pandas", "My csv file is on this link:\nhttps://drive.google.com/file/d/1Pac9-YLAtc7iaN0qEuiBOpYYf9ZPDDaL/view?usp=sharing\nI want to remove the duplicate from the csv by checking length of genres against each artist ID. If an artist have 2 records in csv (e.g., ed sheeran's id 6eUKZXaKkcviH0Ku9w2n3V have 2 records one record have 1 genres while row#5 have 5 genres so i want to keep the row which has largest genres length)\nI'm using this script for now:\nimport pandas\nimport ast\n\n\ndf = pandas.read_csv('39K.csv', encoding='latin-1')\n\ndf['lst_len'] = df['genres'].map(lambda x: len(ast.literal_eval(str(x))))\nprint(df['lst_len'][0])\n\ndf = df.sort_values('lst_len', ascending=False)\n\n# Drop duplicates, preserving first (longest) list by ID\ndf = df.drop_duplicates(subset='ID')\n\n\n# Remove extra column that we introduced, write to file\ndf = df.drop('lst_len', axis=1)\ndf.to_csv('clean_39K.csv', index=False)\n\nbut this script works for 500 record (may be i have illusion that size of records matters),\nbut when I run this script for my largest file 39K.csv I'm getting this error:\nTraceback (most recent call last):\n******* error in line 5, in <module>....\n df['lst_len'] = df['genres'].map(lambda x: len(list(x)))\n df['lst_len'] = df['genres'].map(lambda x: len(list(x)))\nTypeError: 'float' object is not iterable\n\nPlease point me where i am doing wrong?\nThanks" ]
[ "python", "pandas", "csv" ]
[ "How do I restrict Nativescript to compile for x86_64 only?", "How do I restrict 'tns build ios' to compile for x86_64 only?\n\nIt currently attempts to build my app for both i386 and x86_64. (ARCHS and VALID_ARCHS).\n\nThis fails to link plugins that where compiled for x86_64 and arm64 only." ]
[ "nativescript", "nativescript-cli" ]
[ "Error Using seeElement() In PhantomJS", "I'm using Codeception to test my Yii2 application.\n\nI switched from the default PhpBrowser into PhantomJS 2 as PhpBrowser can't handle native javascript popup such as 'confirm()' for acceptance testing.\n\nso I change my acceptance.suite.yml configuration into this:\n\nclass_name: AcceptanceTester\nmodules:\n enabled:\n - WebDriver\n - tests\\codeception\\_support\\FixtureHelper\n config:\n WebDriver:\n url: http://www.lppm.local\n browser: firefox\n window_size: 1366x768\n restart: true\n\n\nand this is my test script:\n\n<?php\nuse \\tests\\codeception\\_pages\\PeriodPage;\n\n$I = new AcceptanceTester\\AdminSteps($scenario);\n$I->wantTo('Ensure that period access right is working fine');\n\n$I->amGoingTo('Go to period main page');\nPeriodPage::openBy($I);\n$I->expectTo('See Action Buttons in grid view');\n$I->seeElement('.glyphicon-trash');\n$I->seeElement('.glyphicon-pencil');\n\n$I->amGoingTo('Create a new period');\n$I->click(PeriodPage::$create_button);\n$I->seeInCurrentUrl('period/create');\n$I->fillField('input[name=\"Period[name]\"]', 'New Period');\n$I->fillField('input[name=\"Period[start_date]\"]', '2014-01-01');\n$I->fillField('input[name=\"Period[end_date]\"]', '2014-08-01');\n$I->click('Create');\n\n$I->expectTo('Redirected to the new period detail page');\n$I->seeInCurrentUrl('period/view');\n$period_url = $I->grabFromCurrentUrl();\n\n\n$I->wantTo('Ensure period access right is working fine for normal user');\n$normal_user = $I->haveFriend('Normal User');\n$normal_user->does(function(\\AcceptanceTester\\GuestSteps $I) use ($period_url, $scenario){\n $I->login('user', 'user');\n $I->see('User, '.dropdown-toggle');\n $I->wantTo('Ensure that no action button is available in view page');\n $I->amOnPage($period_url);\n $I->dontSee('.btn');\n\n $I->wantTo('Ensure that no action button is available in index page');\n PeriodPage::openBy($I);\n $I->dontSee(PeriodPage::$create_button);\n $I->dontSeeElement('.glyphicon-trash');\n $I->dontSeeElement('.glyphicon-pencil');\n});\n\n\nbut I get this error when I run the script with PhantomJS enabled:\n\n\n There was 1 failure:\n \n --------- 1) Failed to ensure that period access right is working fine in PeriodAccessRightCept\n (/var/www/lppm/tests/codeception/acceptance/PeriodAccessRightCept.php)\n Couldn't see element \".glyphicon-trash\": Failed asserting that an\n array is not empty.\n\n\nthis script is working fine when I use PhpBrowser" ]
[ "php", "phantomjs", "yii2", "codeception", "acceptance-testing" ]
[ "GWT, disable autoclose MenuBar when clicking on MenuItem?", "I want to if it is possible to disable the auto-close MenuBar when I click on a MenuItem?\nI have several MenuItem that are like checkboxes, so I can check more than one MenuItem and don't want my menu close everytime I checked one.\n\nThanks." ]
[ "gwt", "menuitem", "menubar", "auto-close" ]
[ "User control JQuery Issue", "I've created a user control which is very basic, It's a asp.net text box with JQuery autocomplete functionality attached. This is all defined in the aspx page not programatically.\n\n<link href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js\"></script>\n <script type=\"text/jscript\" src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js\"></script>\n\n\n <script type=\"text/jscript\" >\n\n\n $(function() {\n\n $(\".tb\").autocomplete({\n\n source: [ <%=GetAutoCompleteData%> ],\n\n });\n\n});\n </script>\n\n\n <asp:TextBox ID=\"TBAUTO\" class=\"tb\" runat=\"server\"></asp:TextBox>\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Search\" onclick=\"Button1_Click\"></asp:Button>\n\n\nThis works perfectly well when one control is on a page. However when i add another they both seem to have the same data which shouldn't be the case.\n\nWhen i check what is rendered to the page it's as i expect but they both contain the same data when the auto complete functionality kicks in\n\nThis is what is rendered to the page \n\n\nAny help would be appreciated." ]
[ "jquery", "sharepoint", "sharepoint-2010", "user-controls" ]
[ "Which is better option OpenXml or Microsft.Office.Interop.Excel to read excel file in c#?", "I am using .NET 4.6 framework and I have to read multi sheets predefined templated excel workbook in asp.net/c# code and I know two way to solve the problem using either DocumentFormat.OpenXml.dll or Microsoft.Office.Interop.Excel.dll assembly. \n\nBut I am in confusion which one to use as I don't have expert knowledge to decide.\nMy questions are; \nWhat are the pros and cons using them in a solution? \nIs there one better than another?\nCould you please explain so that I could pick one?" ]
[ "c#", "asp.net", "openxml" ]
[ "How can I clip a UILabel during animation?", "I am animating a UILabel over a custom button. I want it to appear as though the UILabel is \"rolling onto\" the button from the right.\n\nMy plan is to position the label 50 pixels to the right of the button, begin animation, move it to its correct position, and commit animation. However, throughout the animation I want to clip the label to the frame of the button, so that you only see the piece of the label that overlaps the button and nothing hanging over to the right.\n\nWhat's the best way to do this?\n\nThanks." ]
[ "iphone", "animation", "uilabel" ]
[ "WebService endpoint did not deploy on jboss eap 6", "I have two application servers: one for internal testing (let's call it INT), second one is used for production testing (PRD). INT runs CentOS 6, PRD runs RHEL 6. Both servers also run Jboss EAP 6.2. On this jboss I'm deploying EAR application with a WebService packaged in a war.\n\nProblem is: WebService endpoint does not deploy on PRD. No problems on INT. Ear successfully deploys on both servers, endpoint is available on INT, but not on PRD, no errors in server.log both on PRD and INT, PRD server.log suggests, that it has not even tried to deploy the WebService.\n\nWhat I have tried:\n\n\nTo eliminate problems with configuration I copied over whole jboss instance (jboss + configuration + deployments + work directories, configuration was adopted - IPs, usernames and password, veirifed with diff) from INT to PRD - no change.\nLater I also copied over the jre (PRD is running jdk1.7.0_65, INT is running jre1.7.0_67) - also no change.\nTo help me analyse possible issues I created a simple WebService (New Netbeans Web project from wizard, no libraries added, then I added a WebService, also from Wizard) - this project deployed on INT with no issues, WebService was available and working. On PRD it deployed, posted no errors, but the webService was not available - according to the jboss web console it wasn't even started. Checking for wsdl returned 404.\n\n\nBeacuse of my company's policies I can not post the generated application and server logs." ]
[ "java", "web-services", "jboss" ]
[ "Allow custom HTML attributes in TinyMCE in EPiServer", "EPiServer only: \n\nOur clients are trying to add custom attributes to a div-tag in the TinyMCE editor - they switch to HTML mode, makes the changes and save the page. Then the attributes are removed. Washing HTML like this is standard behaviour of TinyMCE, and it is possible to configure it to allow custom tag attributes.\n\nMy question is how do I configure TinyMCE in EPiServer to allow custom HTML attributes? I don't see where I would be able to hook into the inititialization of TinyMCE. And adding div to the list of \"safe\" tags in episerver.config doesn't see to work either (see uiSafeHtmlTags).\n\nExample:\n\n<div class=\"fb-like\" data-href=\"http://oursite\" data-send=\"false\"></div>\n\n\nBecomes just \n\n<div class=\"fb-like\"></div>\n\n\nFrom the TinyMCE documentation, on how to add custom attributes to tags: http://www.tinymce.com/wiki.php/Configuration:extended_valid_elements" ]
[ "asp.net", "tinymce", "episerver" ]
[ "sublime text doesn't proceed my code after cin. what should I do?", "all\n\nI'm pretty new to programming and I'm currently teaching myself C++ with sublime text editor. I'm having a problem where the code does not proceed after I input something through cin. For example,\n\n#include <iostream>\nusing namespace std;\n\nint main() {\n string password = \"password\";\n cout << \"Enter your password: \" << flush;\n\n string input;\n cin >> input;\n\n if(input == password) {\n cout << \"Password accepted.\" << endl;\n } else {\n cout << \"Access denied.\" << endl;\n }\n return 0;\n}\n\n\nAfter I put my input, it doesn't cout anything such as \"password accepted\" or \"access denied\". Does anyone know how to solve this problem and make it work? Thanks." ]
[ "c++" ]
[ "Want to extract the QR value from firebase database but the snapshot prints nil", "I want to extract the QR value which is on firebase database QR Values->year->month->day->QR : value\n \n\nfunc GetQR() {\n let date = getDate()\n\n let year = String(describing: date.year)\n let month = String(describing:date.month)\n let day = String(describing:date.day)\n\n ref = Database.database().reference().child(\"QR Values\").child(year).child(month).child(day)\n ref.observeSingleEvent(of: .value, with: { (snapshot) in\n\n // Get user value\n let value = snapshot.value as? String\n\n\n print(value)\n\n })\n { (error) in\n print(error.localizedDescription)\n }\n\n }\n\n\nThe printed snapshot is nil." ]
[ "ios", "swift", "firebase", "firebase-realtime-database" ]
[ "ORA-01008: not all variables bound with bcrypt in Node.js", "So, I'm trying to encrypt the lastname ( just for testing) and it doesn't work.\n\nHere is my code:\n\nfunction getEmployeeFromRec(req) {\n\n let employee;\n bcrypt.hash(req.body.lastname, 10, (err, hash) => {\n employee = {\n id: req.body.id,\n firstname: req.body.firstname,\n lastname: hash,\n datebirth: req.body.datebirth,\n }\n });\n return employee;\n}\n\n\nThis is my SQL statement code:\n\nconst createSql =\n `insert into sys.test_table (\n id,\n firstname,\n lastname,\n datebirth\n ) values (\n :id,\n :firstname,\n :lastname,\n :datebirth\n )`;\n\nasync function create(emp) {\n const employee = Object.assign({}, emp);\n\n const result = await database.simpleExecute(createSql, employee);\n\n return employee;\n}\n\n\nSimpleExecute() is doing the SqlStatement wih the data I put in it.\n\nHere is my post code:\n\nasync function post(req, res, next) {\n try {\n let employee = getEmployeeFromRec(req);\n\n employee = await employees.create(employee);\n\n res.status(201).json(employee);\n } catch (err) {\n next(err);\n }\n}\n\n\nI am a beginner so if you could give me also some new tips to learn, I would be grateful.\nThis is my first tutorial I worked with:\nhttps://jsao.io/2018/03/creating-a-rest-api-with-node-js-and-oracle-database/\n\nEDIT:\nI found the solution, thanks to nopassport1 for helping!\n\nThe new code:\n\nfunction getEmployeeFromRec(req) {\n\n var employee;\n\n let hash = bcrypt.hashSync(req.body.lastname, 10);\n\n employee = {\n id: req.body.id,\n firstname: req.body.firstname,\n lastname: hash,\n datebirth: req.body.datebirth,\n };\n return employee;\n}" ]
[ "node.js", "oracle" ]
[ "How do I search google from within my game", "I am trying to use google search in my game. I'd like to find out the number of results a specific search query returns.\n\nCurrently I am opening a URL with a search query. However the way google works is by loading the page and then streaming in the search results. Unity believes the page has fully loaded and then returns the results too soon.\n\nBelow is my code\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing System;\nusing UnityEngine.UI;\n\npublic class SearchWeb: MonoBehaviour {\n\n // I call this method to start the search from an input field\n public void Search(InputField _inputField) {\n StartCoroutine(GetHtml(_inputField.text.ToString(), ShowResults));\n }\n\n // This is my callBack that will post results in the console\n public void ShowResults(int _results, string _searchQuery) {\n Debug.Log(\"searching for \" + _searchQuery + \" results in \" + _results + \" results.\");\n }\n\n // This method is responsible for recieving the HTML from a search query\n // \n IEnumerator GetHtml(string _searchQuery, Action < int, string > _callback) {\n // White space in the a google search will return an error from google\n _searchQuery = _searchQuery.Replace(\" \", \"+\");\n // The URL to send\n string url = \"https://www.google.com/search?sclient=psy-ab&btnG=Search&q=\" + _searchQuery.ToString();\n WWW wwwHTML = new WWW(url);\n Debug.Log(\"Attempting to search \" + url);\n yield\n return wwwHTML;\n // Process the returned HTML, get useful information out of it\n int _results = GetResults(wwwHTML.text.ToString());\n // Send it back\n _callback(_results, _searchQuery);\n yield\n return null;\n }\n\n // This method is incomplete but would eventually return the number of results my search query found\n private int GetResults(string _html) {\n Debug.Log(_html);\n // Here I can tell by looking in the console if the returned html includes the search results\n // At the moment it doesn't\n\n int _startIndex = 0;\n int _results = 0;\n\n // looking for this <div id=\"resultStats\"> where the search results are placed\n if (_html.IndexOf(\"<div id=\\\"resultStats\\\">\", System.StringComparison.Ordinal) > 0) {\n _startIndex = _html.IndexOf(\"<div id=\\\"resultStats\\\">\", System.StringComparison.Ordinal);\n // TODO - Finish this stuff\n }\n // TODO - For now I'm just debugging to see if I've found where the result stats may be\n _results = _startIndex;\n return _results;\n }\n}\n\n\nIt currently returns html which doesnt contain any search results" ]
[ "c#", "unity3d" ]
[ "Unable to access the WebCam", "(function ($) {\n\n var webcam = {\n\n "extern": null, // external select token to support jQuery dialogs\n "append": true, // append object instead of overwriting\n\n "width": 320,\n "height": 240,\n\n "mode": "callback", // callback | save | stream\n\n "swffile": "../Webcam_Plugin/jscam_canvas_only.swf",\n "quality": 85,\n\n "debug": function () {},\n "onCapture": function () {},\n "onTick": function () {},\n "onSave": function () {},\n "onLoad": function () {}\n };\n\n window["webcam"] = webcam;\n\n $["fn"]["webcam"] = function(options) {\n\n if (typeof options === "object") {\n for (var ndx in webcam) {\n if (options[ndx] !== undefined) {\n webcam[ndx] = options[ndx];\n }\n }\n }\n\n var source = '<object id="XwebcamXobjectX" type="application/x-shockwave-flash" data="'+webcam["swffile"]+'" width="'+webcam["width"]+'" height="'+webcam["height"]+'"><param name="movie" value="'+webcam["swffile"]+'" /><param name="FlashVars" value="mode='+webcam["mode"]+'&quality='+webcam["quality"]+'" /><param name="allowScriptAccess" value="always" /></object>';\n\n if (null !== webcam["extern"]) {\n $(webcam["extern"])[webcam["append"] ? "append" : "html"](source);\n } else {\n this[webcam["append"] ? "append" : "html"](source);\n }\n\n var run = 3;\n (_register = function() {\n var cam = document.getElementById('XwebcamXobjectX');\n\n if (cam && cam["capture"] !== undefined) {\n\n /* Simple callback methods are not allowed :-/ */\n webcam["capture"] = function(x) {\n try {\n return cam["capture"](x);\n } catch(e) {}\n }\n webcam["save"] = function(x) {\n try {\n return cam["save"](x);\n } catch(e) {}\n }\n webcam["setCamera"] = function(x) {\n try {\n return cam["setCamera"](x);\n } catch(e) {}\n }\n webcam["getCameraList"] = function() {\n try {\n return cam["getCameraList"]();\n } catch(e) {}\n }\n webcam["pauseCamera"] = function() {\n try {\n return cam["pauseCamera"]();\n } catch(e) {}\n } \n webcam["resumeCamera"] = function() {\n try {\n return cam["resumeCamera"]();\n } catch(e) {}\n }\n webcam["onLoad"]();\n } else if (0 == run) {\n webcam["debug"]("error", "Flash movie not yet registered!");\n } else {\n /* Flash interface not ready yet */\n run--;\n window.setTimeout(_register, 1000 * (4 - run));\n }\n })();\n }\n\n})(jQuery);\n\nAbove is the function which I've used in order to access the webcam of the system. It work fine when i use it on localhost but the problem arises when the same is put on the server and then accessed through intranet.\nI'm unable to find the reason to fix it. Kindly help me with the same.\n\n\n\nThe first two images are the ones when i use my code on localhost. It works fine as i'm able to access the webcam.\nProblem statement:\nThe last image is the one where I try to do the same through server. The webcam opens by the images is completely wiped out. Only a white screen appears and even if I capture the photo through webcam, the white image is only saved on server instead of a proper original image." ]
[ "asp.net", ".net", "webcam", "webcam-capture", "jquery-webcam-plugin" ]
[ "Is it bad practice to bind a view directly to a service property?", "I have a chat service: \n\n@Injectable({\n providedIn: 'root'\n})\nexport class ChatService { \n private state: ChatState = {\n loading: true,\n unseenMessages: false,\n chatGroups: []\n };\n\n getState(){\n return this.state; \n }\n\n .... \n}\n\n\nNow I want to use the \"unseenMessages\" parameter to make badge in my main nav: \n\nexport class MainNavComponent implements OnInit {\n chat: ChatState;\n\n constructor(private chatService: ChatService) {}\n\n ngOnInit() {\n this.chat = this.chatService.getState();\n }\n}\n\n\nNote that this.chat is now a reference to exact same object instance as in the service, so now I can use it is my view like: \n\n <div class=\"chat\" (click)=\"onChat()\">\n <img *ngIf=\"!chat.loading\" src=\"...\"/>\n <div *ngIf=\"chat.unseenMessages\" class=\"batch\"></div>\n <div *ngIf=\"chat.loading\" class=\"la-ball-clip-rotate la-sm \">\n <div></div>\n </div>\n </div>\n\n\nAnd still keep change detection etc. intact. So when I change the state inside the service, the view will update accordingly. \n\nI know that Angular is big on observables, so my question is if this way is bad practice? Are there any down sides compared to observables in this scenario?\n\nOne problem I have at the moment that might relate to this is, that when I clear the \"unseenMessages\" flag inside the service, I get a \"ExpressionChangedAfterItHasBeenCheckedError\". in the MainNacComponent. There's of course ways of fixing this, but it led me to, that it might be bad practice." ]
[ "angular", "rxjs" ]
[ "How to show tag inside the tag", "I am building an app with Ionic, in which some codes are associated with some images, Now, in my post, which are from database, contains any of those codes, replace the particular code with the respective image in the <p> tag.\n\nFor example: in my post if (#mountain#) is found then the respective image associated with (#mountain#) is shown instead of the code." ]
[ "html", "ionic-framework" ]
[ "Cannot open port 8153 on amazon ec2 instance", "I am trying the free tier on amazon ec2 and have a red hat 64bit instance set up with Go Server running on port 8153.\nI disabled IPTables and switched SELINUX to permissive and then added 8153 to amazon security policy and restarted the instance. However when I try to access the port on my browser outside of the instance I cant connect. The port is open according to netstat and nmap and when I run curl command on the instance it works.\n\nIs this a problem with free tier instances?\n\nEDIT: Weird thing is if I install a web server like nginx on it and open port 80 on security policy I can access it fine on any browser but not anything apart from web server. Even installed tomcat and cant access it either." ]
[ "amazon-ec2", "port" ]
[ "How to restrict excel from taking its default time format", "I am exporting data to excel sheet. I have a field called totalWorkingHours as string which holds the hours and minutes as \"hh:mm\" e.g. \"119:20\". However excel reads this as a timestamp and adds seconds to it: \"119:20:00\". I want to remove the seconds and the value should be displayed as \"119:20\" only. \n\nFollowing code returns the Memory Stream which is then exported to excel:\n\n public static MemoryStream GetCSV(string[] fieldsToExpose, DataTable data)\n {\n MemoryStream stream = new MemoryStream();\n\n using (var writer = new StreamWriter(stream))\n {\n for (int i = 0; i < fieldsToExpose.Length; i++)\n {\n if (i != 0) { writer.Write(\",\"); }\n writer.Write(\"\\\"\");\n writer.Write(fieldsToExpose[i].Replace(\"\\\"\", \"\\\"\\\"\"));\n writer.Write(\"\\\"\");\n }\n writer.Write(\"\\n\");\n\n foreach (DataRow row in data.Rows)\n {\n for (int i = 0; i < fieldsToExpose.Length; i++)\n {\n if (i != 0) { writer.Write(\",\"); }\n writer.Write(\"\\\"\");\n\n if (row[fieldsToExpose[i]].GetType() == typeof(DateTime))\n {\n var Val = (DateTime)row[fieldsToExpose[i]];\n string output = Val.ToString(\"dd-MMM-yyyy hh:mm\");\n if (Val.TimeOfDay == new TimeSpan(0, 0, 0))\n {\n output = Val.ToString(\"dd-MMM-yyyy\");\n }\n writer.Write(output.Replace(\"\\\"\", \"\\\"\\\"\"));\n }\n else\n {\n writer.Write(row[fieldsToExpose[i]].ToString().Replace(\"\\\"\", \"\\\"\\\"\"));\n }\n writer.Write(\"\\\"\");\n }\n writer.Write(\"\\n\");\n }\n }\n return stream;\n }" ]
[ "c#", "excel" ]
[ "SQL search with like", "I,m trying to make a query for this table which it have the following columns.\n\nfrom , to, Range with values like \n\n1, 100, A: \n101,200, B: \n201,300, C:\n\n\nThe columns are integer.\n\na user is going to give a number and I have to get on which rate is. Let say, the user send 105, I know that with a query I can get that it is on range B. But the problem is that sometimes users do not know the complete number that is going to be sent. Let say they only know the first two digits of the number, something like 10. I have to return all the possibilities that could involve l0. Let say, 10-101-1001-10001. The problem is that If I use LIKE I will not receive all the values because I do not have them in a column. \n\nAny ideas how i can do this?" ]
[ "sql" ]
[ "Javascript, design function to reference itself", "Given:\n\nmyChart = new ganttChart(\"chart1\");\n\nfunction ganttChart(gContainerID) {\n\n this.variable1 = \"lol\";\n this.variable2 = \"hai dere\";\n this.variable3 = \"cometishian\";\n\n....\n this.gContainer = document.getElementById(gContainerID);\n this.gContainer.innerHTML += \"<div id=\\\"gBar\" + i + \n \"\\\" class=\\\"gBar\\\" onmousedown=\\\"gInitBarDrag(this)\\\">Hello</div>\";\n....\n}\n\n\nHow would I make the function gInitBarDrag() defined inside the ganttChart class? I don't want an exterior standalone function as it needs to reference things inside the object.\n\nSo for example, the function would be able to reference variable1/2/3 which are defined in a specific instance of the ganttChart object (you can have multiple chart objects).\n\nHope that makes sense! EG:\n\nfunction ganttChart(gContainerID) {\n\n this.variable1 = \"lol\";\n this.variable2 = \"hai dere\";\n this.variable3 = \"cometishian\";\n\n....\n this.gContainer.innerHTML += \"<div id=\\\"gBar\" + i + \n \"\\\" class=\\\"gBar\\\" onmousedown=\\\"gInitBarDrag(this)\\\">Hello</div>\";\n....\n\n gInitBarDrag = function(thisGanttObject)\n {\n alert(thisGanttObject.variable2);\n // This line wont work because it doesn't know what ganttChart to reference!\n }\n\n}" ]
[ "javascript", "function", "object" ]
[ "hosts file (Windows) works incorrectly in some browsers", "When i add this to hosts file:\n 192.168.1.10 example.com\nGoogle Chrome works as expected and opens page at 192.168.1.10.\nPing shows correct ip address.\nHowever Firefox and another Chromium-based browser is unable to connect." ]
[ "hosts" ]
[ "WebStorm: using Emmet to quickly convert px to em", "Can't figure out how to do an inline calculation to quickly convert px to em when using WebStorm 11 IDE. (Mac OSX 10.11.3)\n\nFor example, within a css file:\n\nmb24/16\n\nwith Emmet, and when using Sublime Text 3, you can press Command + Shift + Y and it will quickly do the inline calculation:\n\nmb24/16 then becomes mb1.5\n\nI've been trying to figure out how to do this in WebStorm, but for the life of me I can't find the answer." ]
[ "css", "webstorm", "emmet" ]
[ "Swift - Extension UIView inside of UIViewController", "My intention is whenever the user tries to use the button without having all the fields filled in, to have the screen shake. \n\nFollowing error appears:\n\n\n Value of type 'AddViewController' has no member 'shake'\n\n\nAddViewController is of class UIViewController, but changing the extensions class won't work either. \n\n... else {\n self.shake()\n }\n\n\nextension UIView {\n func shake() {\n let animation = CAKeyframeAnimation(keyPath: \"transform.translation.x\")\n animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)\n animation.duration = 0.6\n animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]\n layer.add(animation, forKey: \"shake\")\n }\n}" ]
[ "ios", "swift", "xcode" ]
[ "how to get ordered queries in mysql", "I have 2 tables, animal and people, I am making a query using UNION to get a combined list of both tables, but I want every 4 animals I look 1 person, that is:\n\nResults:\n\n*animal 1\nanimal 2\nanimal 3\nanimal 4*\n**person 1**\n*animal 5\nanimal 6\nanimal 7\nanimal 8*\n**person 2**\netc...\n\n\nIs there any way to do it?\n\nPlease help me!" ]
[ "mysql", "sql" ]
[ "Node.js testing RESTful API (vows.js?)", "I could really do with some advice on testing a RESTful api I created in node.js. There are a plethora of frameworks out there and I am at a loss. My testing knowledge isn't good enough generally which is why I am trying to write these tests. I've tried vows.js which seems nice but I couldn't work out how to incorporate the testing of my API, I need some sort of client. An example of a simple post to test a login system is all I need to get going." ]
[ "testing", "node.js", "vows" ]
[ "Do I need a custom converter for this?", "From viewing the source code that this code makes it looks like itemValue generate the value based on the objects toString() method. So bean.question.categories can't be an arraylist containing categories....at least it does not work. Do I need to make my own converter in order to have this working? \n\n<h:selectManyMenu value=\"#{bean.question.categories}\" id=\"questionCategories\">\n <f:selectItems value=\"#{categoryValuesManager.categories}\" var=\"category\"\n itemValue=\"#{category}\" itemLabel=\"#{category.description}\"/>\n</h:selectManyMenu>\n\n\nThe question entity also has a bi-directional many-to-many relationship with the category entity and it gives me headace!\n Because; when making a new question instance the categoriesproperty of that instance is null, right? So I need to assign a empty ArrayList<Category> to it. Then, do I need to loop over each item in that arraylist and assign an arraylist with the one question instance on the category side too?" ]
[ "java", "jsf", "jakarta-ee" ]
[ "Why won't my readline advance to the next line?", "Whenever my methods are supposed to be advancing to the next line in a txt file that I am importing, they instead decide to continuously use the same line instead of advancing to the next line in the document.\n\nDUMMY = 9999\n\ndef readMaster():\n #opens the customers file, sets a variable to whatever line we are on\n infile=open(\"customers.txt\", 'r')\n line=infile.readline()[:-1]\n\n#checks if entered ID is valid. If it is, return their name and balance. if not, return garbage.\n if line!=(\"\"):\n masterID,masterName,balance=line.split(\",\")\n return int(masterID),masterName,int(balance)\n else:\n masterID=DUMMY\n return masterID,\"\",0\n infile.close()\n\n\n def readTransaction():\n #opens the transactions files\n infile=open(\"transactions.txt\",\"r\")\n\n #scans through the transactions file. If Item ID is found, return that line\n #if it isn't, return garbage variables.\n line=infile.readline()[:-1]\n if line!=(\"\"):\n itemID,itemName,cost=line.split(\",\")\n return int(itemID),itemName,int(cost)\n\n else:\n itemID=DUMMY\n return itemID,\"\",0\n infile.close()\n\ndef updateRecords():\n\n #creates a new file for us to write to.\n outfile = open(\"new_master.txt\", 'w')\n\n #pulls in any values we need for calculation\n\n masterID,masterName,balance = readMaster()\n itemID,itemName,cost=readTransaction()\n\n #checks to see if the customer's ID matches the ID of the service purchased. To avoid printing multiple lines\n #per person, we use a while loop to continue adding to the balance until the customer didn't buy the next item.\n #Then, asks for the next line in the transaction text.\n\n if int(itemID)==int(masterID):\n while int(itemID)==int(masterID):\n balance = balance+cost\n\n return int(itemID),itemName,int(cost)\n\n # Since the customers.txt and transactions.txt files are both sorted numerically, we check to see\n # if one is greater than the other. If it is, that means a customer didn't make any purchases, so we\n # print that person's line from customers.txt without updating it\n\n elif itemID>masterID:\n print(masterID+\",\"+masterName+\",\"+balance,file =outfile)\n\n\n # If we don't find any transactions for something, an error is printed.\n\n else:\n print(\"No record for item\",itemID)\n\n\n print(masterID + \",\" + masterName + \",\" + balance, file=outfile)\n\n itemID,itemName,cost=readTransaction()\n\n #Then, we print the customer's ID, name, and new balance to the new text file\n\n print (masterID+\",\"+masterName+\",\"+balance,file = outfile)\n\n\nCustomers.txt\n\n207,Ann Wyeth,120\n215,David Fisher,89\n412,Deb Washington,75\n609,Lily Ahn,110\n610,Dottie Sturgis, 39\n1984,Leslie Jackson,109\n1989,Taylor Grandview,55\n1999,Roger Nelson,65\n2112,Lee Geddy,99\n5150,Valerie Edwards,45\n7800,John Bongiovi,160\n\n\ntransactions.txt\n\n207,Formal Styling,55\n207,Partial Highlights,65\n215,Haircut,29\n610,Formal Styling,55\n610,Accent Highlights,50\n1999,Clipper Cut,19\n2112,Haircut with Shampoo,39\n5150,Haircut with Styling,45\n5150,Partial Highlights,65\n5150,Treatments,29\n6792,Coloring,150\n7800,Haircut,29" ]
[ "python", "readline" ]
[ "Why does Windows sometimes use a critical section and sometimes use an atomic list for the heap lock?", "I encountered a problem where during a parallelized operation, I get a severe performance issue on certain machines. For example, the code below scales well on a 2 chip machine with 8 cores each, but scales poorly on a 2 chip machine with 10 cores each.\n\nThe profiler indicates cache misses for the machine with 2x10 cores and indicates calls to the Windows RtlEnterCriticalSection. Most time here is spent on malloc/free. For the 2x8 core machine, most time is spent on the std::rand (the bare matrix matrix product is just to introduce some dummy number crunching).\n\nFor the 2x8 core machine, I don't get any cache misses at all, and I also dont' see calls to RtlEnterCriticalSection. Instead I see calls to RtlInterlockedPopSList which looks like Windows is using atomics to manage the heap lock. The question is why would it use the critical section on the other machine which is highly inefficient for multi-threading?\n\n std::vector> futures;\n for (auto iii = 0; iii != 40; iii++) {\n futures.push_back(std::async([]() {\n for (auto i = 0; i != 100000 / 40; i++) {\n const int size = 10;\n for (auto k = 0; k != size * size; k++) {\n double* matrix1 = (double*)malloc(100 * sizeof(double));\n double* matrix2 = (double*)malloc(100 * sizeof(double));\n double* matrix3 = (double*)malloc(100 * sizeof(double));\n\n for (auto i = 0; i != size; i++) {\n for (auto j = 0; j != size; j++) {\n matrix1[i * size + j] = std::rand() / RAND_MAX;\n matrix2[i * size + j] = std::rand() / RAND_MAX;\n }\n }\n\n for (auto i = 0; i != size; i++) {\n for (auto j = 0; j != size; j++) {\n double sum = 0.0;\n for (auto k = 0; k != size; k++) {\n sum += matrix1[i * size + k] * matrix2[k * size + j];\n }\n matrix3[i * size + j] = sum;\n }\n }\n free(matrix1);\n free(matrix2);\n free(matrix3);\n }\n }\n }));\n }\n for (auto& entry : futures)\n entry.wait();" ]
[ "c++", "windows", "multithreading" ]
[ "handle unreal numbers, jump to catch", "I have this piece of code that is supposed to calculate the root of f(x) = ln(x+1)+1 using Secant Method.\nHaving input xold1 = 0; xold2 = 1;\n\ndo {\n try {\n iteration++;\n fxold1 = Math.log(xold1+1)+1;\n fxold2 = Math.log(xold2+1)+1;\n xnew = xold2 - (fxold2 * (xold2 - xold1))/(fxold2 - fxold1);\n\n //Show iterations and results \n System.out.println(\"Iteration: \" + iteration + \"; x = \" + xnew);\n\n diff = Math.abs(xnew-xold1);\n\n //Replace old variables with new ones\n xold2 = xold1;\n xold1 = xnew; \n } catch(Exception e) {\n System.out.println(\"No solution for this starting point.\"); \n }\n } while(diff > 0.00001);\n\n\nOutput:\n\n Iteration: 1; x = -1.4426950408889634\n Iteration: 2; x = NaN\n\n\nDoing the maths on the paper, the second iteration gives an imaginary number: 0.185125859 + 3.14159265 i. So, the idea was that the program was supposed to jump to catch. why it didn't do so and what I should do to do it? Thank you!" ]
[ "java", "math", "try-catch" ]
[ "Can I have a type that's both, covariant and contravariant, i.e. fully fungible/changeable with sub and super types?", "Can I have a type (for now forgetting its semantics) that can be covariant as well as contravariant?\n\nfor example:\n\npublic interface Foo<in out T>\n{\n void DoFooWith(T arg);\n}\n\n\nOff to Eric Lippert's blog for the meat and potatoes of variance in C# 4.0 as there's little else anywhere that covers adequate ground on the subject.\n\n\n\nI tried it out anyway, not only does it not allow that, but it tells me I am missing the whole point. I need to understand the link between read-only, write-only and variance.\n\nI guess I got some more reading to do.\n\nBut any short, epiphany inducing answers are welcome, meanwhile." ]
[ "c#-4.0", "covariance", "contravariance", "variance" ]
[ "Testing Workflow when working on the Tensorflow source code", "When developing with the tensorflow code base, it seems that the workflow is\n\n\nMake code changes\nRun bazel build\nBuild pip package\npip install pip package\nTest changes\n\n\nThis is clunky. Are there any tricks for compiling and testing changes within the source tree? Something like setting one's PYTHONPATH\n\nI'm aware that tensorflow doesn't allow importing from within the source tree. For e.g.\n\n\nWhat does it mean to import TensorFlow from source directory?" ]
[ "tensorflow" ]
[ "Access non-default calendar events through google-java-api in Android", "I would like our app users to be able to access the non-default calendar events in their Google calendar. We can access the events in their default calendar just fine, but we would like to include the events from their other calendars as well. I found a post on the google support forums that says:\n\n\"To get a feed from another calendar, you have to specify its ID in the URL. The IDs for other calendars (= other than the main/default one), you have to go to the calendars Settings section (look at the box entitled \"my calendars\" on the left side of the screen), click on \"settings\", and then on the link of your other calendar. Then, scroll to the page-bottom, and copy/paste the URL you get by clicking on the orange \"XML\" button, on the \"private address\" line.\"\n\nIs there a better way to do this? Would I actually have to have our app users follow these procedures to manually enter the URL for their non-default Google calendars so that we can retrieve them? We are using the google-api-java-client to access the users Google calendar." ]
[ "android", "google-calendar-api", "google-api-java-client" ]
[ "Conditioning on multiple rows in a column in Teradata", "Suppose I have a table that looks like this:\n\nid attribute\n1 football\n1 NFL\n1 ball\n2 football\n2 autograph\n2 nfl\n2 blah\n2 NFL\n\nI would like to get a list of distinct ids where the attribute column contains the terms "football", "NFL", and "ball". So 1 would be included, but 2 would not. What's the most elegant/efficient way to do this in Terdata?\nThe number of attributes can vary for each id, and terms can repeat. For example, NFL appears twice for id 2." ]
[ "sql", "teradata" ]
[ "It is possible to pick an attribute \"height\" in Javascript?", "I just want to use a height in an image set up in CSS, then catch this gradation in JS and scale the width to the height x2.25.\nIs it possible?" ]
[ "javascript", "css", "attributes", "scale" ]
[ "Why global variable behaves differently in different methods?", "Goal:\n\nMake global array of string (dictionary) given that size can be computed only in function load().\nPrint dictionary on the screen with function print().\n\nMy approach:\nCreate global pointer to string, create array of strings in load() and assign local array to global pointer.\nProblem:\nIf I try to print global array (and local as well) inside load(), everything's fine, but in case of printing with print(), segfault occurs somewhere in the end of array. GDB and valgrind outputs seem cryptic to me. I give up. What's wrong?\nSource and dictionary are here.\nCode:\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n// length of the longest word in dictionary\n#define LENGTH 45\n// dictionary file\n#define DICTIONARY "large"\n\n// prototypes\nvoid load(const char* dictionary);\nvoid print(void);\n\n// global dictionary size\nint dict_size = 0;\n// global dictionary\nchar **global_dict;\n\nint main(void)\n{\n load(DICTIONARY);\n print();\n return 0; \n}\n\n/**\n * Loads dictionary into memory.\n */\nvoid load(const char* dictionary)\n{\n // open dictionary file\n FILE *dict_file = fopen(dictionary, "r"); \n \n // compute size of dictionary\n for (int c = fgetc(dict_file); c != EOF; c = fgetc(dict_file))\n {\n // look for '\\n' (one '\\n' means one word)\n if (c == '\\n')\n {\n dict_size++;\n }\n }\n \n // return to beginning of file\n fseek(dict_file, 0, SEEK_SET);\n \n // local array\n char *dict[dict_size];\n \n // variables for reading\n int word_length = 0;\n int dict_index = 0;\n char word[LENGTH + 1]; \n \n // iteration over characters\n for (int c = fgetc(dict_file); c != EOF; c = fgetc(dict_file))\n {\n // allow only letters\n if (c != '\\n')\n {\n // append character to word\n word[word_length] = c;\n word_length++;\n }\n // if c = \\n and some letters're already in the word\n else if (word_length > 0)\n {\n // terminate current word\n word[word_length] = '\\0';\n \n //write word to local dictionary\n dict[dict_index] = malloc(word_length + 1);\n strcpy(dict[dict_index], word);\n dict_index++;\n \n // prepare for next word\n word_length = 0;\n }\n }\n \n // make local dictioinary global\n global_dict = dict;\n}\n\n/**\n * Prints dictionary.\n */\nvoid print(void)\n{\n for (int i = 0; i < dict_size; i++)\n printf("%s %p\\n", global_dict[i], global_dict[i]);\n}" ]
[ "c", "arrays", "string", "variables", "segmentation-fault" ]
[ "PHP - file_get_contents skip style and script", "I am trying to pull a html of a site,\n\nI am using file_get_contents($url).\n\nWhen I run file_get_contents then its takes too much time pull html of host site,\nCan I skip style, scripts and images ?\n\nI think then it will take less time to pull html of that site." ]
[ "php", "file-get-contents" ]
[ "Android kernel and init.rc", "We built android kernel for wandboard. Now, we must add some files and change init.rc to start service for that files(driver for touchscreen). With the help of adb we pulled init.rc and edited, later pushed back. However, after reboot init.rc remains unchanged, so we cant start service for our driver.\n\nHow can we accomplish writing init.rc?\n\nList of boot partition:\n\nboot\n\n\nAs you can see, there is no initrd directory or file\n\nWith regards" ]
[ "android", "android-kernel" ]
[ "does randomForest [R] not accept logical variable as response, but accept it as predictor?", "Hi I'm using randomForest in R and it doesn't accept logical variable as response (Y), but seems to accept it as predictor (X). I'm a little surprised b/c I thought logical is essentially 2-class factor... \n\nMy question is: is it true that randomForest accepts logical as predictor, but not as response? Why is it like this?\nDoes other common models (glmnet, svm, ...) accept logical variables?\n\nAny explanation/discussion is appreciated. Thanks\n\nN = 100\n\ndata1 = data.frame(age = sample(1:80, N, replace=T),\n sex = sample(c('M', 'F'), N, replace=T),\n veteran = sample(c(T, F), N, replace=T),\n exercise = sample(c(T, F), N, replace=T))\n\nsapply(data1, class)\n# age sex veteran exercise \n# \"integer\" \"factor\" \"logical\" \"logical\" \n\n# this doesnt work b/c exercise is logical\nrf = randomForest(exercise ~ ., data = data1, importance = T)\n# Warning message:\n# In randomForest.default(m, y, ...) :\n# The response has five or fewer unique values. Are you sure you want to do regression?\n\n# this works, and veteran and exercise (logical) work as predictors\nrf = randomForest(sex ~ ., data = data1, importance = T)\nimportance(rf)\n# F M MeanDecreaseAccuracy MeanDecreaseGini\n# age -2.0214486 -7.584637 -6.242150 6.956147\n# veteran 4.6509542 3.168551 4.605862 1.846428\n# exercise -0.1205806 -6.226174 -3.924871 1.013030\n\n# convert it to factor and it works\nrf = randomForest(as.factor(exercise) ~ ., data = data1, importance = T)" ]
[ "r", "random-forest" ]
[ "How can I loop through the first 'n' rows in a grid view.", "I have a question about if there is a better more efficient way to do what I want to accomplish:\n\nWhat I want to do is loop through the rows in a grid view and check the check boxes for the first 100 records.\n\nFor this I came up with the solution below:\n\nint limit = 0;\nint max = 100;\nforeach (GridViewRow gvr in GridView1.Rows)\n{\n limit++;\n if (gvr.RowType == DataControlRowType.DataRow && limit <= max)\n {\n CheckBox cb = (CheckBox)gvr.FindControl(\"chkSelect\");\n cb.Checked = true;\n }\n}\n\n\nI am wondering if this is the best way of doing this or if there is an easier/quicker way to do accomplish the same task.\n\nThanks for any help." ]
[ "c#", "asp.net" ]
[ "concatenate two database columns into one resultset column", "I use the following SQL to concatenate several database columns from one table into one column in the result set:\n\nSELECT (field1 + '' + field2 + '' + field3) FROM table1\n\nWhen one of the fields is null I got null result for the whole concatenation expression. How can I overcome this?\n\nThe database is MS SQL Server 2008. By the way, is this the best way to concatenate database columns? Is there any standard SQL doing this?" ]
[ "sql", "sql-server-2008", "concatenation" ]
[ "How to correctly use wx.SingleChoice in Python", "Im quite new in python and I would like to show a SingleChoiceDialog box with a list of strings from an sqlite query but I do something wrong and the list in the box shows just the last of the value of the variable list.\n\nThe query:\n\n sql = u\"select person.name from person\"\n c.execute(sql)\n for row in c.execute(sql):\n z = list(row)\n\n\nThe Dialog box:\n\n def whatusr(parent=None, message='', default_value=''):\n dlg = wx.SingleChoiceDialog(\n self, \"Who?\", 'The Caption',\n z,\n wx.CHOICEDLG_STYLE\n )\n if dlg.ShowModal() == wx.ID_OK:\n print 'You selected: %s\\n' % dlg.GetStringSelection()\n dlg.Destroy()\n\n\nWhen I run this, the Dialog box shows just the last value of the list and not all the list.\nI think this is because the Dialog box wants me to have an other form of list.\nMy list z = list(row) outputs the value as: [a], [b], [c], .. but the Dialog box is probably expecting the value in this form: [a,b,c, ..]. Can someone help me? Thanks." ]
[ "python", "wxpython" ]
[ "How to handle properly shortcut \"Ctrl+O\" for opening files on a web-page in Firefox?", "I'm working on porting some js code that works correctly in Chrome to Firefox. I have a following function for reading files from a file system:\n\nfunction chooseFilesToOpen() {\n var fileInput = document.createElement('input');\n fileInput.type = 'file';\n fileInput.multiple = true;\n fileInput.addEventListener('change', function() {\n openFiles(fileInput.files);\n });\n\n fileInput.click();\n}\n\n\nThe function is bound to a button on a page ($('#open-button').click(chooseFilesToOpen)) and to Ctrl+O shortcut (there's a switch statement for different keys). The function is invoked in both cases, upon Ctrl+O and a button click, but a file browsing dialog appears only in the latter. When I debug it, the dialog pops up when fileInput.click() is executed. The same statement seems to do nothing when the function is called from a keypress event handler. So, the question is how to make it work for both actions and in both browsers?" ]
[ "javascript", "firefox", "javascript-events" ]
[ "DB2 SQL Query to get the List of Employees whose Managers are changed in the past", "Can somone please help me with a DB2 SQL Query to get the List of Employees whose Managers are changed in the past ?\nSample Data (Same employee Table has ACTIVE and HISTORY Data)\nEMP_ID EMP-FN EMP-LN MANAGER-ID STATUS\n1986 SMITH JASON 2011 ACT\n1986 ALLEN WARD 2023 ACT\n1986 CLARK SCOTT 2038 ACT\n1986 SMITH JASON 2038 HIST\n\nResult Expected\nEMP_ID EMP-FN EMP-LN CURRENT-MANAGER-ID PRIOR-MANAGER-ID \n1986 SMITH JASON 2011 2038\n\nThanks\nCB" ]
[ "sql" ]
[ "How to see the query plan for a CONSTRUCT query?", "I am looking for information about the query plan for CONSTRUCT queries.\nI know that I could use onto:explain for select queries according to\nhttps://graphdb.ontotext.com/documentation/standard/explain-plan.html\nbut I would like to evaluate the time spent in building the template part of a CONSTRUCT query with variables\nfrom the select part\nIf not possible, at least to know the sequence, I mean, I guess first the select part is computed and later, the values obtained are used to populated the template part, is it correct my guess about the sequence to compute a CONSTRUCT query?\nThanks" ]
[ "graphdb" ]
[ "Calculating hand values in Blackjack", "I am implementing a little Black Jack game in C# and I have the following problem calculating the player's hand value. Aces may have a value of 1 or 11 based on the player's hand. If the player has three cards and one ace, then if the sum of the cards is <= 10 the ace will have value of 11, otherwise it will have a value of 1.\n\nNow lets assume I do not know how many aces the player has got and the game is implemented giving the possibility to the dealer to use more than one deck of cards. The user may have in one hand even 5, 6, 7, 8... aces.\n\nWhat is the best way (possibly using Linq) to evaluate all the aces the player has got to get the closest combination to 21 (in addition to the other cards)?\n\nI know the players' cards and I want to calculate their values, using the aces to reach the closest value to 21." ]
[ "c#", "blackjack" ]
[ "Java inheritance, anonymous inner class instance member, android callback method", "I'm doing this in the context of Android, but my problem is understanding Java. I'm somewhat new to both, so hopefully I'm using the correct terminology here.\n\nI've got a number of sub-classes inheriting/extending from my super class (an Android Activity extension) called SuperActivity. I've also defined another class type called Network (which is an Android Service). In my superclass I'm defining an anonymous inner class that implements an (Android) interface called ServiceConnection. That interface specifies (and therefore I'm defining) methods that will be called by the Android system. I have to pass an instance of that anonymous, ServiceConnection-implementing inner class of mine to a method called bindService(), so that the methods inside that anonymous, inner class can be called later.\n\nAs I mentioned, I'm subclassing that super-class that defines the anonymous inner class. The methods in that anonymous inner class have to set an instance variable in the subclass instance; that instance variable I need to set is here called mNetwork.\n\nIn the superclass:\n\npublic class SuperActivity extends Activity {\n protected Network mNetwork;\n\n protected ServiceConnection mConnection = new ServiceConnection() {\n @Override\n public void onServiceConnected(ComponentName name, IBinder service) {\n mNetwork = ((Network.NetworkBinder)service).getService();\n }\n }\n\n void bindNetwork() {\n bindService( new Intent(this, Network.class), mConnection, Context.BIND_AUTO_CREATE);\n }\n}\n\n\nSo I create my subclass and call its bindNetwork() method. and apparently the anonymous inner class assigned to mConnection is not an instance member of my subclass, since after the OnServiceConnected() method defined in the anonymous inner class is called, the subclass's instance member called mNetwork is null.\n\nFurther, if I take that mConnection variable holding the anonymous inner class and call getClass().getName() on it or toString() on it, it shows itself to be an inner class of my superclass, and not of the subclass.\n\nObviously I'm not understanding something about java inheritance. I want to have a number of subclasses, each with its own mNetwork variable set by the method inside the anonymous inner class. I don't want to cut and past the definition of the anonymous inner class into each subclass. There's got to be a way. What am I doing wrong?" ]
[ "java", "inheritance", "subclass", "instance-variables" ]
[ "How to delete content in sparse files?", "I'm writing a program, which write some contents in a sparse file.\nSay, I create the file by\nfd = open(filepath, O_RDWR | O_CREAT | O_EXCL, 0644);\nassert(fd != -1);\nint s = ftruncate(fd, len);\n\nlen is very large, but the actual content may only takes several kbs.\nThen I do memory mapped IO on this file. How do I ensure contents are deleted from this file, so that temporary stuff is not stored, and the actual storage is still "sparse"?\nThanks for any suggestions." ]
[ "c", "mmap", "sparse-file" ]
[ "Rhomobile doesn't make deploy", "I'm trying to develop an application using RhoMobile, specifically using the Rhostudio 2.0. But every time I try to use the simulator, there is an error: \n\n rake aborted!\nNo such process\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/gems/1.9.1/gems/rhodes-3.5.1.13/platform/android/build/android_tools.rb:359:in `kill'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/gems/1.9.1/gems/rhodes-3.5.1.13/platform/android/build/android_tools.rb:359:in `rescue in load_app_and_run'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/gems/1.9.1/gems/rhodes-3.5.1.13/platform/android/build/android_tools.rb:347:in `load_app_and_run'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/gems/1.9.1/gems/rhodes-3.5.1.13/platform/android/build/android.rake:1987:in `block (3 levels) in <top (required)>'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:205:in `call'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:205:in `block in execute'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:200:in `each'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:200:in `execute'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:158:in `block in invoke_with_call_chain'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:151:in `invoke_with_call_chain'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:176:in `block in invoke_prerequisites'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:174:in `each'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:174:in `invoke_prerequisites'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:157:in `block in invoke_with_call_chain'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:151:in `invoke_with_call_chain'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/task.rb:144:in `invoke'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/application.rb:116:in `invoke_task'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/application.rb:94:in `block (2 levels) in top_level'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/application.rb:94:in `each'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/application.rb:94:in `block in top_level'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/application.rb:88:in `top_level'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/application.rb:66:in `block in run'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/application.rb:133:in `standard_exception_handling'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/lib/ruby/1.9.1/rake/application.rb:63:in `run'\nC:/MotorolaRhoMobileSuite2.2.1.13/ruby/bin/rake:32:in `<main>'\nTasks: TOP => run:android => run:android:emulator\nKilling adb server\nStarting adb server again\nLoading package...\nCMD: C:/Users/Sebastian/Desktop/android-sdk-windows/platform-tools/adb.exe -e install -r C:/Users/Sebastian/workspace/RhoMobileApplication2/bin/target/android/RhoMobileApplication2-debug.apk \nRET: 1\nError in build application. Build is terminated.\n\n\nI have looked up this thread Ruby on Rails Rake assets:precompile error, but I still have the problem. \n\nI really hope you could help me,\n\nThanks" ]
[ "android", "compiler-errors", "rhomobile" ]
[ "DB2 unique constraint, unique indexes and performance", "I have a table that requires two rows to be unique. They are likely to be joined regularly so I probably need an index on these rows.\n\nI checked the Infocenter on the Unique constraint and on the Unique Index.\n\nI'm wondering about the difference and the performance impact. Both seem to create an index. The unique index allows one null value. Are there other important differences?\n\nDo these indexes improve query performance or are they just enforcing uniqueness? Should I add an additional index for performance reasons or will be the unique index be good enough? Unfortunately I don't have enough test data yet for trying it out yet." ]
[ "sql", "indexing", "db2", "unique", "unique-constraint" ]
[ "Correctly formatted multidimensional array from php file not parsing in jquery ajax function", "I am attempting to create an online Bible for a ministry site I am working on. It allows the user to select a book of the Bible, which, in turn, populates the chapters div using jQuery, upon which when a chapter is clicked, it is supposed to populate the actual chapter using jQuery. \n\nThe book click works fine and populates the related chapters, but the chapter click does nothing. \n\n\n\nHere is the Html\n\n/* showBibleWrap\n ------------------------------------------------------ */\n echo '<div class=\"showBibleWrap\">';\n\n # bible books\n echo '<div class=\"bibleBooks\">'; \n echo file_get_contents($level.'core/bible/data/books-of-the-bible.dat');\n echo '</div>';\n\n # bible chapters\n echo '<div class=\"bibleChapters\"></div>';\n\n # show bible results\n echo '<div class=\"bibleResults\"></div>';\n\n echo '</div>';\n\n\nThe Html included on books-of-the-bible.dat\n\n<div class=\"gChapters\" data-theBook=\"Genesis\" data-chapterCt=\"50\">Genesis</div>\n<div class=\"gChapters\" data-theBook=\"Exodus\" data-chapterCt=\"40\">Exodus</div>...\n\n\nOn the click of .gChapters uses jQuery to appends the chapters to the DOM based on the data-chapterCt=\"50\" attribute.\n\njQuery - this works fine\n\n$(\".gChapters\").click(function(){\n var whichBook = $(this).attr(\"data-theBook\");\n var ct = $(this).attr(\"data-chapterCt\");\n\n $('.bibleChapters').html('');\n\n for (i = 0; i < ct; i++) {\n var ii = i + 1;\n $('.bibleChapters').append('<div class=\"chapters\" data-book=\"'+whichBook+'\" data-chapter=\"'+ii+'\">'+ii);\n }\n\n});\n\n\nThe script is supposed to append the related chapter to .bibleResults on the click of .chapters using jQuery Ajax but this does not work.\n\nThe jQuery\n\n$(\".chapters\").click(function(){\n var whichBook = $(this).attr(\"data-book\");\n var chapter = $(this).attr(\"data-chapter\");\n $('.bibleResults').html('');\n\n $.ajax({\n type:\"POST\",\n url:siteURL + 'core/bible/parse-verses.php',\n data: {whichBook:whichBook, chapter:chapter} ,\n success: function (JSONObject) {\n\n $.each(JSONObject, function(k,item){ \n $('.bibleResults').append('<p class=\"verseWrap\"><b>['+item.book_name+' '+item.chapter_id+':'+item.this_verse_id+']</b> '+item.verse); \n }); \n }\n });\n});\n\n\nThe parse-verses.php file\n\n$level = '../../'; \n include($level.'inc/ini.php');\n\n $whichBook = $_POST['whichBook'];\n $chapter = $_POST['chapter'];\n\n $selectqup = $db->prepare(\"SELECT * FROM verses_of_bible WHERE book_name=:THENAME AND chapter_id=:CHAP\");\n $selectqup->bindValue(':THENAME',$whichBook,PDO::PARAM_INT); \n $selectqup->bindValue(':CHAP',$chapter,PDO::PARAM_INT);\n $selectqup->execute();\n\n $verses = array();\n\n while($row = $selectqup->fetch(PDO::FETCH_ASSOC)){$verses[] = $row;}\n\n header('Content-type: application/json');\n echo json_encode($verses);\n\n\nI have tested the json_encode($verses); and it renders a correct json multidimensional array.\n\njson array\n\n[{\"verse_id\":\"7129\",\"testament\":\"Old\",\"book_id\":\"8\",\"book_name\":\"Ruth\",\"chapter_id\":\"1\",\"this_verse_id\":\"1\",\"verse\":\" Now it came to pass in the days when the judges ruled, that there was a famine in the land. And a certain man of Beth-lehem-judah went to sojourn in the country of Moab, he, and his wife, and his two sons.\"},{\"verse_id\":\"7130\",\"testament\":\"Old\",\"book_id\":\"8\",\"book_name\":\"Ruth\",\"chapter_id\":\"1\",\"this_verse_id\":\"2\",\"verse\":\" And the name of the man [was] Elimelech, and the name of his wife Naomi, and the name of his two sons Mahlon and Chilion, Ephrathites of Beth-lehem-judah. And they came into the country of Moab, and continued there.\"},...\n\n\nI have been on this for two days... I have researched to the point of confusion... whatever you can do to assist is much appreciated." ]
[ "php", "jquery", "arrays" ]
[ "Drop data from DataFrame because of insufficient values", "I'm trying to sum the total monthly amount by the code below, \n\nmonth_sum = df.groupby(([df['Year'], df['Month']]))['amount'].agg(np.sum)\n\n\nBut I need to drop those data or change the sum result to NaN if they do not contain enough days' data(eg: only 10 groups of data for January). \n\nI only know I can drop data by dp.drop(), which drop data according to column \ncharacteristics...And I cannot use it in this situation. Can anyone show me how to do that?" ]
[ "python", "python-3.x", "pandas" ]
[ "How to store switch locations during max-pooling layer", "I am implementing the article https://arxiv.org/abs/1311.2901 by Zeiler and Fergus on visualizing and understanding convolutional Networks. To be able reflect hidden layers back to the image space we need deconvolution kernels, rectified linear functions and switch locations. I couldn't find how to store switch locations during max-pooling. I would be glad if you can explain how to do it in pytorch or tensorflow. Thanks in advance." ]
[ "python-3.x", "conv-neural-network", "pytorch" ]
[ "How to use conditional if statements in Jinja 2?", "So I am new to Django and can use some help.\nI have used a for loop to display a list from my database. But I want to add an if statement such that, if the user input matches my database item, only then it should be displayed. Take a look :\n\n{%for inc in all_items%}\n <ul> \n {#I want to add an if statement here, if user input == inc_element#}\n <li><p>{{inc.item_name}}<p></li>\n </ul>\n <hr>\n{%endfor%}\n\n\nI know I 'd have to use HTML forums for taking user input. But how do I match it in if statement. Help would be appreciated." ]
[ "python", "django", "django-templates", "jinja2" ]
[ "Meteor showing [object Object] after creating Meteor.Router.add()", "I'm following this tutorial to learn Meteor. After adding the first JS code, I'm getting [object Object] on my browser. I've followed everything as explained (except for some names that I have changed, but I haven't used any reserved words), but I cannot see anything else. This part is in the first 4 minutes. This is how my files look:\n\ndemonstration.js:\n\nCalEvents = new Meteor.Collection('calevents');\nSession.setDefault('editing_calevent', null);\nSession.setDefault('showEditEvent', false);\nMeteor.Router.add({\n '/':'home',\n '/calendar':'calendar' \n})\n\n\ncalendar.html:\n\n<template name=\"calendar\">\n <div id=\"calendar\">\n Hello world! Now at calendar.\n </div>\n</template>\n\n\nhome.html:\n\n<template name=\"home\">\n <div class=\"hero-unit\">\n <p>Manage your calendar</p>\n <p><a class=\"btn btn-primary btn-large\">Learn more</a></p>\n </div> \n</template>\n\n\ndemonstration.html:\n\n<head>\n <title>Calendar app</title>\n</head>\n\n<body>\n {{>menu}}\n <div class=\"container-fluid\">\n <div class=\"row-fluid\"> \n {{renderPage}}\n </div>\n </div>\n</body>\n\n\nI suspect it has something to do with the Meteor.Router.add() line, because the little I did prior to adding this worked. I have tried changing the page to show on '/' to other pages that contained a simple text, but it didn't work.\n\nEdit to add: I am working thru Nitrous.io and I installed Meteorite prior to adding the router package.\n\nThanks in advance.\n\nPS: I have searched in here and on Google but I haven't been able to find any answer to this question. If there is one, kindly point me to the right address." ]
[ "javascript", "meteor", "router" ]
[ "can't insert russian text into mysql database", "When I'm trying to insert russian text into MySQL database it inserts it like:\nг???????????? ?? ????????\nРісѓрїр°ріс‹рї р° с‹рір°рї\n\nSo, I have two pages: registration.php and addUser.php. In each of them\n\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n\n\nDatabase consist of 11 tables, each table has collation: utf8_general_ci, type: MyISAM. Each field in every table has Collation: utf8_general_ci.\n\nWhen I'm writing to database directly in phpMyAdmin and then show this data to web-page. In English and Russian - all OK.\n\nBut when I'm full my form with personal data on registration.php and then going to addUser.php - all russian characters displayed like I wrote upper - on page and in database too.\n\n function AddNewUser($Name, $Surname, $FatherName, $Email, $Password, $Phone, $DegreeID, $RankID, \n$Organization, $Department, $Country, $City, $Address, $Job)\n{\n //fetch data from database for dropdown lists\n //connect to db or die)\n $db = mysql_connect($GLOBALS[\"gl_kussdbName\"], $GLOBALS[\"gl_kussUserName\"], $GLOBALS[\"gl_kussPassword\"] ) or die (\"Unable to connect\");\n\n //to prevenr ????? symbols in unicode - utf-8 coding\n mysql_query(\"SET NAMES 'UTF8'\");\n\n //select database\n mysql_select_db($GLOBALS[\"gl_kussDatabase\"], $db);\n $sql = \"INSERT INTO UserDetails (\nUserFirstName,\nUserLastName,\nUserFatherName,\nUserEmail,\nUserPassword,\nUserPhone,\nUserAcadDegreeID,\nUserAcadRankID,\nUserOrganization,\nUserDepartment,\nUserCountry,\nUserCity,\nUserAddress,\nUserPosition) \nVALUES(\n'\".$Name.\"',\n'\".$Surname.\"',\n'\".$FatherName.\"',\n'\".$Email.\"',\n'\".$Password.\"',\n'\".$Phone.\"',\n'\".$DegreeID.\"',\n'\".$RankID.\"',\n'\".$Organization.\"',\n'\".$Department.\"',\n'\".$Country.\"',\n'\".$City.\"',\n'\".$Address.\"',\n'\".$Job.\"'\n);\";\n //execute SQL-query\n $result = mysql_query($sql, $db);\n if (!$result) \n {\n die('Invalid query: ' . mysql_error());\n }\n //close database = very inportant\n mysql_close($db);\n\n}\n?>\n\n\nThere also such information in phpMyAdmin:\n\nauto increment increment 1\nauto increment offset 1\nautocommit ON\nautomatic sp privileges ON\nback log 50\nbasedir \\usr\\local\\mysql-5.1\\\nbig tables OFF\nbinlog cache size 32,768\nbinlog format STATEMENT\nbulk insert buffer size 8,388,608\ncharacter set client utf8\n(Global value) cp1251\ncharacter set connection utf8\n(Global value) cp1251\ncharacter set database cp1251\ncharacter set filesystem binary\ncharacter set results utf8\n(Global value) cp1251\ncharacter set server cp1251\ncharacter set system utf8\ncharacter sets dir \\usr\\local\\mysql-5.1\\share\\charsets\\\ncollation connection utf8_general_ci\n(Global value) cp1251_general_ci\ncollation database cp1251_general_ci\ncollation server cp1251_general_ci\ncompletion type 0\nconcurrent insert 1\n\n\nSo I need to properly show, save and select russian text from database. Thanx!\n connect timeout 10\n datadir \\usr\\local\\mysql-5.1\\data\\" ]
[ "php", "mysql", "unicode", "utf-8" ]
[ "Saving and recalling an image with a placeholder image as default in android", "I currently have a questionnaire, where each question is added dynamically in a db, which the app then receives for instructions. When it uses the camera, it sets the image just fine, using the code:\n\nvoid setResponse(Bitmap image) {\n captureButton.setImageBitmap(image);\n}\n\n\nSimple enough, right? When I click update, to save it to the sqlite db, I save it as a base64 string using this:\n\nString getResponse() {\n String response = \"\";\n try \n {\n Bitmap bitmap = Bitmap.createBitmap(captureButton.getDrawingCache());\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);\n byte[] image = stream.toByteArray();\n response = Base64.encodeToString(image, 0);\n } \n catch (Exception e) \n { \n Log.e(\"Capture image error\", e.getMessage());\n e.printStackTrace();\n }\n return response;\n}\n\n\nAnd then when I go back into the questionnaire, if it has data already, it just loads it up using this:\n\nvoid setResponse(String response) {\n byte[] decodedString = Base64.decode(response, Base64.DEFAULT);\n Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);\n captureButton.setImageBitmap(decodedByte);\n}\n\n\nI currently have pretty much the same system for signatures using the gestureOverlayView. But for this, I have a placeholder image defined in the CameraQuestionView.xml file:\n\n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:src=\"@drawable/placeholder\"\n android:id=\"@+id/cameraQuestionCaptureButton\"/>\n\n\nBut for some reason, when loading back up, the placeholder image is displayed instead of the saved image in the db. I tried invalidating the view, but that didn't work either. \n\nThanks!" ]
[ "android", "image", "view", "bitmap", "camera" ]
[ "Weird UITableView behavior after expand/collapse the last cell", "What I want to achieve is that: cell can expand/collapse when clicking on the label inside of it. The cell size should be remembered so that when the user scrolls back to the cell, it should be the size it is used to be. I setup the cell using Auto Layout with all the views assigned height constraint. When the user clicks on the label, I change the cell height by changing the label's height constraint:\n\nfunc triggerExpandCollapse(_ cell: UITableViewCell) {\n guard let cell = cell as? ActivityTableViewCell, let indexPath = self.activitiesTableView.indexPath(for: cell) else { return }\n\n if !self.expandedCellIndex.insert(indexPath.row).inserted {\n self.expandedCellIndex.remove(indexPath.row)\n cell.descLabelHeightConstraint.constant = 60\n }\n else {\n cell.descLabelHeightConstraint.constant = cell.descLabel.intrinsicContentSize.height\n }\n\n self.activitiesTableView.beginUpdates()\n self.activitiesTableView.endUpdates()\n}\n\n\nAnd also config the cell's height before returning every cell:\n\nfunc tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: Constants.TableViewCellID.activity, for: indexPath)\n guard let activityCell = cell as? ActivityTableViewCell else {\n return cell\n }\n\n activityCell.delegate = self\n if self.expandedCellIndex.contains(indexPath.row) {\n activityCell.descLabelHeightConstraint.constant = activityCell.descLabel.intrinsicContentSize.height\n }\n else {\n activityCell.descLabelHeightConstraint.constant = 60\n }\n activityCell.layoutIfNeeded()\n return activityCell\n}\n\n\nI also enable auto layout by:\n\nself.activitiesTableView.rowHeight = UITableViewAutomaticDimension\nself.activitiesTableView.estimatedRowHeight = 1000\n\n\nSo far the cells can expand/collapse with normal scroll behavior except the last one! When I expand the last one and scroll up, the activitiesTableView looks \"jumping\" a short distance. Detail can refer to the video\n\nI have no idea how to debug right now. Does anyone have some ideas about it? Thanks." ]
[ "ios", "swift", "uitableview" ]
[ "Updating multiple docs with different values", "My Node/Mongo db has a doc with the following data in a collection called 'prices':\n\n [ { _id: 1, price : 10 }, {_id: 2, price : 15 }, {_id: 3, price : 12 }]\n\n\n...and so on. I now receive an updated doc from a remote site that that looks like this:\n\n [ { _id: 1, price : 12 }, {_id: 3, price : 15 }, { _id: 5, price: 20 } ] (some new some updated).\n\n\nHow can I change my data to:\n\n\nupdate exiting records \ninsert the new records.\n\n\nThank you in advance." ]
[ "node.js", "mongodb" ]
[ "Spring data JPA throwing java.lang.ArrayIndexOutOfBoundsException: X [Kotlin]", "One of the attributes of an Entity was an inline class (an experimental feature at the time of this question). And when running a spring boot application I was getting a java.lang.ArrayIndexOutOfBoundsException: 3 which made no sense to me.\n\nTurns out 3 was the number indicating the position of the attribute in my entity.\n\n@Entity\n@Table(name = \"my_entity_table\")\nclass MyEntity(\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n var id: Long = 0,\n\n @Column(name = \"some_field\")\n val someField: Int = 2,\n\n @Column(name = \"a_second_field\")\n val aSecondField: ASecondField\n)\n\ninline class ASecondField(val value: String)\n\n\nAnd this was part of the stacktrace:\n\norg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myEntityRepository': Invocation of init method failed; nested exception is java.lang.ArrayIndexOutOfBoundsException: 3\n\n\n...\n\nCaused by: java.lang.ArrayIndexOutOfBoundsException: 3\n at org.springframework.data.mapping.model.PreferredConstructorDiscoverer$Discoverers.buildPreferredConstructor(PreferredConstructorDiscoverer.java:221)\n at org.springframework.data.mapping.model.PreferredConstructorDiscoverer$Discoverers.access$200(PreferredConstructorDiscoverer.java:89)\n at org.springframework.data.mapping.model.PreferredConstructorDiscoverer$Discoverers$2.lambda$discover$0(PreferredConstructorDiscoverer.java:161)\n\n..." ]
[ "jpa", "kotlin", "spring-data-jpa" ]
[ "What does \"this\" refer to (when iterating through a collection)", "I'm trying to reach a collection instance with the this keyword, when iterating through its models. Here is my test code:\n\nmyModel = Backbone.Model.extend({\n\n url: 'model.com'\n}); \n\nmyCollection = Backbone.Collection.extend({\n\n model: myModel,\n url: 'collection.com',\n\n iterateAll: function(){\n this.each(function(item){\n console.log(this.url);\n console.log(item.url);\n });\n }\n});\n\nmod = new myModel();\ncol = new myCollection(mod);\n\ncol.iterateAll();\n\n\nThis code outputs:\n\nundefined\nmodel.com\n\n\nHow can I reference the collection correctly when using this.url? I want the output to read collection.com not undefined." ]
[ "backbone.js", "foreach", "underscore.js" ]
[ "Adding a prefix to certain column names", "I have a problem very similar to this one: Adding a prefix to column names.\nI want to add a prefix to the column name - the only difference is, that I dont want to add the prefix to every column I have. Here the same minimum, reproducible example as in the question mentioned above: \n\nm2 <- cbind(1,1:4)\ncolnames(m2) <- c(\"x\",\"Y\")\n\n\nResulting in:\n\n x Y\n[1,] 1 1\n[2,] 1 2\n[3,] 1 3\n[4,] 1 4\n\n\nThe code for adding a prefix \"Sub\" to both columns would look like this (as suggested by the user A5C1D2H2I1M1N2O1R2T1):\n\ncolnames(m2) <- paste(\"Sub\", colnames(m2), sep = \"_\")\n\n\nResulting in:\n\n Sub_x Sub_Y\n[1,] 1 1\n[2,] 1 2\n[3,] 1 3\n[4,] 1 4\n\n\nHow can I add a prefix \"Sub\" only to the first column? I tried the following: \n\ncolnames(m2[,1]) <- paste(\"Sub\", colnames(m2[,1]), sep = \"_\")\n\n\nResult of the code: No Warning, no error but no prefix as well. Any suggestions? Besides base r any suggestions using dplyr are appreciated as well. Please let me know if you need any further information. Thanks in advance." ]
[ "r", "dplyr" ]
[ "Spring Session 1.1.x incompatible with Spring-JMS 3.2.x", "I am trying to configure spring session 1.1.1 with my spring 3.2.18 based application. Following are dependencies \n\ncompile group: 'org.springframework', name: 'spring-context', version: 3.2.18\n ....\ncompile group: 'org.springframework.integration', name: 'spring-integration-jms', version: '2.0.3.RELEASE'\ncompile group: 'org.springframework', name: 'spring-jms', version: 3.2.18\ncompile group: 'org.springframework.security', name: 'spring-security-core', version: 3.1.4.RELEASE\ncompile group: 'org.springframework.session', name: 'spring-session-data-redis', version: '1.1.1.RELEASE'\ncompile (group: 'org.apache.commons', name: 'commons-pool2', version: '2.4.2'){\n force = true\n }\n\n\nFollowing are Spring session configurations in code.\n\n@Configuration\n@EnableRedisHttpSession\npublic class ApplicationConfiguration {\n\n @Bean\n public JedisConnectionFactory connectionFactory() {\n return new JedisConnectionFactory();\n }\n\n @Bean\n public JmsTemplate jmsTemplate() {\n JmsTemplate jmsTemplate = new JmsTemplate();\n jmsTemplate.setConnectionFactory(connectionFactory());\n return jmsTemplate;\n }\n}\n\npublic class SpringSessionInitializer extends AbstractHttpSessionApplicationInitializer {\n public SpringSessionInitializer() {\n super(ApplicationConfiguration.class);\n }\n}\n\n\nI am getting following exception. \n\nCaused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.jms.core.JmsTemplate com.emaratech.v2015.messaging.configuration.MessagingConfiguration$DevelopmentConfiguration.jmsTemplate()] threw exception; nested exception is java.lang.ClassCastException: org.springframework.data.redis.connection.jedis.JedisConnectionFactory incompatible with javax.jms.ConnectionFactory\n\n\nThat indicates provide JedisConnectionFactory is not compatible with JMS ConnectionFactory. Can you suggest which spring session and Jedis version is compatible with Spring JMS verion 3.2.18? What other configuration will be required to configure it successfully?" ]
[ "java", "spring", "spring-jms", "spring-session" ]
[ "window.onbeforeunload - Only show warning when not submitting form", "I am using window.onbeforeunload to prevent the user from navigating away after changing values on a form. This is working fine, except it also shows the warning when the user submits the form (not desired).\n\nHow can I do this without showing the warning when the form submits?\n\nCurrent code:\n\nvar formHasChanged = false;\n\n$(document).on('change', 'form.confirm-navigation-form input, form.confirm-navigation-form select, form.confirm-navigation-form textarea', function (e) {\n formHasChanged = true;\n});\n\n$(document).ready(function () {\n window.onbeforeunload = function (e) {\n if (formHasChanged) {\n var message = \"You have not saved your changes.\", e = e || window.event;\n if (e) {\n e.returnValue = message;\n }\n return message;\n }\n }\n});" ]
[ "javascript", "jquery", "onbeforeunload" ]
[ "WordPress pagination for sitemap", "How to make pagination in WordPress for wp_list_pages or any wordpress filters for page_list.\n\n$args = array(\n 'before' => '<ul><li>' . __( 'Pages:' ),\n 'after' => '</li></ul>',\n 'link_before' => '',\n 'link_after' => '',\n 'next_or_number' => 'number',\n 'separator' => '</li><li>',\n 'nextpagelink' => __( 'Next page' ),\n 'previouspagelink' => __( 'Previous page' ),\n 'pagelink' => '%',\n 'echo' => 0\n);\n\nreturn wp_list_pages($args);\n\n\nI have this code. How to properly change it for pagination?" ]
[ "php", "wordpress", "pagination" ]