texts
sequence
tags
sequence
[ "ReactNative Android app crash. Error while updating property padding in shadow node of type: RCTView", "This is the error I get\n\nFew things are bugging me here.\nThis crash is happening at random times, in development, and when the app is built for production.\nI found out that problem might be because values for properties like padding and margin are set as strings rather than integers. This is not a problem in my case, because all of them are set as integers.\nI was thinking that it might be an SVG problem, but they don't have any inline style set that would cause this. Or maybe it could be something else with SVG images.\nContent is loaded from WordPress using react-native-render-html but I don't think that this could be the problem.\nI am using "react-native": "0.63.3",\nIf anyone could help me out it would be great :)" ]
[ "android", "css", "reactjs", "react-native", "mobile" ]
[ "Angular.forEach does not return the last item in object", "var items = [];\n\n //angular.forEach(localStorage, function(value, key){\n // items.push({\n // 'id' : key,\n // 'text' : value\n // });\n // console.log(value);\n //});\n for(var key in localStorage){\n if(localStorage.hasOwnProperty(key)){\n //console.log(localStorage[row]);\n items.push({\n 'id' : key,\n 'text' : localStorage[key]\n });\n }\n }\n return items;\n\n\nThe commented code returns array of two elements, while simple \"for in\" loop return all the values form the localStorage object (actually there are three items).\n\nI don't get why the hell angular.forEach does not iterate the last item in object? \n\nEverything should be ok according to the docs\nhttps://docs.angularjs.org/api/ng/function/angular.forEach" ]
[ "javascript", "angularjs", "loops", "foreach" ]
[ "How to get a Handle of the Navbar from a view controller inside a container view", "I have a container view embedded in a view controller. The container is used to display different view controllers. How can I change the title or add a button to the navigation bar in the parent? \n\nThanks!" ]
[ "ios", "objective-c", "uinavigationbar", "ioc-container", "parentviewcontroller" ]
[ "Named elements in a FlowDocument from a ResourceDictionary", "I have a FlowDocument (a template for a report I need to produce) stored as a resource. This seems to work well but if I name the elements I can't get a reference to them with FindName().\n\nHere is the resource dictionary:\n\n<ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <FlowDocument x:Key=\"ReportStructure\">\n <Paragraph Name=\"ClientAddressParagraph\" />\n </FlowDocument>\n</ResourceDictionary>\n\n\nAnd here is my code:\n\nDim _ReportResources = New ResourceDictionary() With {.Source = New Uri(\"/Reports/Statement.xaml\", UriKind.Relative)}\nDim _FlowDocument As FlowDocument = _ReportResources.Item(\"ReportStructure\")\nDim _Paragraph As Paragraph = _FlowDocument.FindName(\"ClientAddressParagraph\")\n\n' _Paragraph is Nothing (null) at this point.\n\n\nAny ideas? Do I need to do some kind of initialisation on the flow document so that it registers the names of named elements?" ]
[ "wpf", "flowdocument", "resourcedictionary" ]
[ "Ansible, \"cisco.ios.ios_ospf_interfaces\": How can I get this plugin?", "I'm running Ansible version 2.9.14 and I've already downloaded the "cisco.ios" Ansible collection. However, when I look in my directory, "ansible_collections/cisco/ios/plugins/modules" I don't seem to have a .py file for ios_ospf_interfaces. Consequently when I include a task in a playbook that references this module the task produces an error.\nI tried to install the cisco.ios collection again, but my system reported it already had this collection and didn't do anything further. So how can I get this particular module on my system?\nThanks!\nExisting Ansible Modules On My System" ]
[ "ansible" ]
[ "Dynamic & Complex rowspan in HTML table", "Link to JSFiddle\n\nHere is my JSON format\n\n{\n \"result\": {\n \"buildname1\": [{\n \"table1\": [\"xxx\",\"yyy\"]\n }, {\n \"table2\": [\"xxx\",\"yyy\"]\n }, {\n \"table3\": [\"xxx\",\"yyy\"]\n }],\n \"buildname2\": [{\n \"table1\": [\"xxx\",\"yyy\"]\n }, {\n \"table2\": [\"xxx\",\"yyy\"]\n }, {\n \"table3\": [\"xxx\",\"yyy\"]\n }]\n },\n \"Build sets\": \"yyy\",\n \"destinationPath\": \"xxx\",\n \"status\": 1\n}\n\n\nThis is the function which I am using to dynamically create the table.\n\nfunction generateTable(data){ //data is the parsed JSON Object from an ajax request\n $(\"#test-table tbody\").empty();//Empty the table first\n if(data.result != null){\n $.each(data.result,function(key,value){\n var buildName =\"<tr><td rowspan='\"+value.length+\"'>\"+key+\"<span class='cyan darken-1 white-text badge'>\"+value.length+\" base tables</span></td>\";\n var baseTable =\"\";\n for(i=0;i<value.length;i++){\n if( i == 0 ){\n for(var k in value[0]){\n baseTable =\"<td rowspan='\"+value[0][k].length+\"'>\"+k+\"</td></tr>\";\n }\n }\n else{\n for(var key in value[i]){\n baseTable = baseTable + \"<tr><td rowspan='\"+value[i][key].length+\"'>\"+key+\"</td></tr>\";\n }\n }\n }\n $(\"#test-table\").append(buildName + baseTable);\n });\n }\n}\n\n\nHere is what I am trying to achieve\n\n\n\nHTML \n\n<table id=\"test-table\" class=\"bordered responsive-table\">\n <thead>\n <tr>\n <th>Build Name</th><th>Base Table</th><th>Query List</th>\n </tr>\n </thead>\n</table>\n\n\nQuestion : \n\nI successfully created the first two columns(though somewhat ugly, thought I can refine it later), I'm stuck at the third column. The code I posted creates the first two columns correctly but the logic for the rowspan within the rowspan(third column) seems to elude me. Please guide me." ]
[ "javascript", "jquery", "html" ]
[ "Canonical reference on JVM internals for programmer/developers", "The title captures my question fairly well. I'm wondering if there is a good resource or leaping-off point for questions about how a JVM (not just HotSpot, but that's obviously the place to start) implements or handles a specific functionality? I'm not looking for the stuff that's in the JLS or JVM Spec -- I know to go there first. \n\nFor example: When trying to understand performance issues, we often get into conversations not about what the spec says, but what contemporary best-practices look like in practical implementations. For example, there is some urban mythology that says \"final classes perform better in Java because the JVM can inline or otherwise optimize such things.\" Is there a general resource we can turn to in order to evaluate these claims that float around?\n\nI offer an answer to my own question, with HotSpot-specific references. What about other vendors' offerings? Specifics to small JVMs? Multi-core specifics? Platforms specifics, if they make a difference? Specifics to other JVM languages?\n\nJust to head off a couple of potential complaints: 1) This isn't about looking for premature optimizations (and in fact, better understanding of the platform should dissuade a better educated developer!); and 2) I know Java programmers are supposed to focus on nice, portable, run-anywhere code, but for many of us the platform specifics end up mattering!\n\nThis was inspired by some helpful comments on a specific question by Thorbjørn Ravn Andersen. I'm happy to collect some other more helpful examples beyond the one I cite above, to motivate why folks might want these kinds of resources.\n\nSome interesting related questions on SO: Tail-call optimization in JVM, Killer JVM features, optimizations that are going to be useless tomorrow, Differences between JVM implementations.\n\nEdited to Add: I'll award the answer either to the best individual reference mentioned, or to someone who provides a pointer to a website (perhaps built in response to this question) that best concentrates/catalogs JVM implementation wisdom and the practical consequences on client languages and developers." ]
[ "java", "jvm", "jvm-languages" ]
[ "Override html page template for a specific sphinx document", "I'm implementing a documentation using Sphinx (https://github.com/fridge-project/dbal-docs) & would like to override the html page of a specific document. My interest is to override all directory indexes to not only show a simple ul.\n\nI have read the Sphinx documentation but I don't find something interesting about my issue... Does someone know a workaround?" ]
[ "python-sphinx" ]
[ "How to disable background execution of Adobe AIR app on Android?", "I am developing a couple of Adobe AIR apps for Android.\nAn issue I encounter is that execution of the app continues when the app is in the background, for instance when the user presses the device's home button.\nThe framerate drops to about 2 fps, but audio and timers just continue.\n\nI need the app/script execution to pause when not activated. I don't want timers, audio, timelines etc to continue. Pausing/resuming them all myself on Event.DEACTIVATE/Event.ACTIVATE is not really feasible, due to the complexity and structure of the apps.\n\nI have tried explicitly setting 'NativeApplication.nativeApplication.executeInBackground = false', with no effect.\nThere is nothing in my manifest xml that does anything with background execution.\n\nI am using Adobe AIR 16.0.\nI have tested on Samsung Galaxy Note 10.1 2014, Samsung Galaxy S4, which both run Android 4.4+\n\nOn stackoverflow I see a number of questions asking the opposite, so this behaviour seems odd.\n\nThanks!" ]
[ "android", "actionscript-3", "flash", "air" ]
[ "Optimal sequence to brute force solve a keypad code lock", "Possible Duplicate:\n Need help in building efficient exhaustive search algorithm \n\n\n\n\nImagine that you must open a locked door by inputting the correct 4-digit code on a keypad. After every keypress the lock evaluates the sequence of the last 4 digits inputted, i.e. by entering 123456 you have evaluated 3 codes: 1234, 2345 and 3456.\n\n\nWhat is the shortest sequence of keypresses to evaluate all 10^4 different combinations?\nIs there a method for traversing the entire space easy enough for a human to follow?\n\n\nI have pondered this from time to time since a friend of mine had to brute force such a lock, to not having to spend the night outdoors in wintertime.\n\n\n\nMy feeble attempts at wrapping my head around it\n\nWith a code of length L=4 digits and an \"alphabet\" of digits of size D=10 the length of the optimal sequence cannot be shorter than D^L + L - 1. In simulations of smaller size than [L,D] = [4,10] I have obtained optimal results by semi-randomly searching the space. However I do not know if a solution exists for an arbitrary [L,D] pair and would not be able to remember the solution if I ever had to use it.\n\nLessons learned so far\n\nWhen planning to spend the night at a friends house in another town, be sure to not arrive at 1 am if that person is going out to party and won't hear her cell phone." ]
[ "algorithm" ]
[ "what is mean of 'apply from' in gradle?", "When I run this gradle task\n\n-Pcons=value anyTask --stacktrace --info --debug\n\n\nIt executes the build.gradle file. And this file contains the line\n\napply from:\"another.gradle\"\n\n\nIn this scenario when I run anyTask, does all the code in another.gradle work? Or is it just accessible?" ]
[ "java", "eclipse", "gradle" ]
[ "Map a xml payload to different POJO objects", "Currently i am developing webservices using CXF framework. This webservices will do my DB operations by making a call to my DAO layer. I know by default CXF is using JAXB for databinding.\nFor example if i wants to create a new person i am having my webservice like follows.\n\npublic Response createPerson(CreatePersonRequest request)\n{\n\n// Call to hibernate DAO class\npersonDao.create()\n}\n\n\nHere CreatePersonRequest is my DTO class(JAXB annotated) , before i make a call to my DAO class i wants to convert my DTO class object to Hibernate Entity object. I wants to populate my hibernate entity object based on the XML i received from my webservice. But the XML i am receiving here will fit into CreatePersonRequest not to my Person entity object.Because my XML root tag will be not other than this my properties for both classes are same. In short i wants to populate Two different type of POJO objects for the same XML payload.Is there anyway to achieve this one using JAXB ? Please help me." ]
[ "data-binding", "jaxb" ]
[ "Parsing with XStream - empty tags and collections", "I am using XStream to convert XML into domain objects, and have come by a problem. Omitting a few details, the XML looks like this :\n\n<airport>\n <flights>\n <flight>.....</flight>\n <flight>.....</flight>\n <flight>.....</flight>\n </flights>\n</airport>\n\n\nThere can be 0 to N flight elements. The flight elements themselves contain other elements. I have created classes for airport, flights, and flight and registered them with the xstream.alias function.\n\nxstream = new XStream();\nxstream.alias(\"airport\", AirportPojo.class);\nxstream.alias(\"flights\", FlightsPojo.class);\nxstream.alias(\"flight\", FlightPojo.class);\nxstream.useAttributeFor(AirportPojo.class, \"flights\");\nxstream.addImplicitCollection(FlightsPojo.class, \"flights\", FlightPojo.class);\nAirportPojo airportPojo = (AirportPojo) xstream.fromXML(xml);\n\n\nSo, after converting, this gives me an AirportPojo object containing a FlightsPojo object, containing a collection of FlightPojo objects. However, when there are 0 flight elements it seems that the collection of FlightPojos is null. I would expect (and prefer) the list to be initialized but with zero elements in it. How could I accomplish this? Bear in mind that I cannot use annotations as this is a legacy project." ]
[ "java", "xml-parsing", "xstream" ]
[ "Window sized using sizeHint, but woud like it to still be adjustable by the user after", "I am using Python and PySide to create a GUI with a dynamic amount of widgets. I am using sizeHint right now to calculate the size of the window. It works pretty well, but the window is a fixed size when generated. I would like the user to be able to be able to adjust the GUI window on a case by case basis after the sizeHint does the initial calculation. Thanks.\n #window.setMinimumWidth(1125)\n\n #window.setFixedWidth(740)\n\n #window.setMinimumHeight(800)\n\n #window.setFixedHeight(200)\n\n window.setFixedSize(grid_layout.sizeHint())\n\n window.setFixedWidth(3500)\n\n window.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n\n window.show()" ]
[ "python", "pyside" ]
[ "Is it possible to add custom attributes to drools rules?", "We are going to be implementing a rules engine using Drools for a customer, and one of the requirements is to be able to say that a rule is associated with a particular legal requirement.\n\nFor instance, the law says that a driving licence can only be issued to someone 18 or over, so we have:\n\nrule \"Driving Licence: Age >= 18\"\n when\n $applicant: Applicant(age < 18)\n $application: Application()\n then \n $application.setValid(false);\nend\n\n\nor for the calculation of a tax total\n\nrule \"Tax: Top bracket\"\n when\n $return: Return(income > 44000)\n then \n $application.setTopBracket(true);\nend\n\n\nor similar.\n\nOne solution would be to have the legal requirement in the name:\n\nrule \"Driving Licence: Age >= 18: Section 103 RTA 1988\"\n\n\nThe question: what would be the best way of achieving this? Is the name the only way? Is there a way to add a custom attribute to a rule? If so, can it be mandatory? I could also use comments, but I would prefer to avoid that.\n\nIt would be nice if in the rule trace we could see the trace of these attributes as well, but that isn't vital.\n\nPlease note that I don't want to change the rule logic, I just want to be able to say 'This rule comes from this law'. The decision of the rule is not important. I do not wish to change the setValid setter." ]
[ "java", "jboss", "drools" ]
[ "pandas resample by a specific date", "I try to resample weekly data to 4W basis but with arbitrary start week, however, the base option doesnot do the work.\nFor example:\nindex = pd.date_range('1/1/2020', periods=14, freq='W')\nseries = pd.Series(range(14), index=index) \nprint(series) \n2020-01-05 0\n2020-01-12 1\n2020-01-19 2\n2020-01-26 3\n2020-02-02 4\n2020-02-09 5\n2020-02-16 6\n2020-02-23 7\n2020-03-01 8\n2020-03-08 9\n2020-03-15 10\n2020-03-22 11\n2020-03-29 12\n2020-04-05 13 \n\ndefault 4W bin by pandas:\nprint(series.resample('4W', label='left').sum()) \n2019-12-08 0\n2020-01-05 10\n2020-02-02 26\n2020-03-01 42\n2020-03-29 13\nFreq: 4W-SUN, dtype: int64\n\nWhat I need is the sum of 4 weeks from 1/19 to 2/9, instead of the default bin by pandas above." ]
[ "python", "pandas", "base" ]
[ "trying to crop bitmap using mask throws IllegalArgumentException:", "I am using following code \n\npublic void cropSelection(){\n Bitmap bitmap = annotationBitmap.copy(annotationBitmap.getConfig(), true);\n Canvas canvas = new Canvas(bitmap);\n Paint p = new Paint();\n // p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.XOR));\n canvas.drawBitmap(imageBitmap, 0, 0, p); // this line throws error\n imageBitmap = bitmap;\n}\n\n\nMore surprisingly when I am using the same line canvas.drawBitmap(imageBitmap, 0, 0, p) inside onDraw() it does not throw any error. It works well.\n\nStacktrace\n\n2020-01-17 11:20:07.815 21388-21388/com.mayank.picturemagic E/AndroidRuntime: FATAL EXCEPTION: main\nProcess: com.mayank.picturemagic, PID: 21388\njava.lang.IllegalArgumentException: Software rendering doesn't support hardware bitmaps\n at android.graphics.BaseCanvas.onHwBitmapInSwMode(BaseCanvas.java:550)\n at android.graphics.BaseCanvas.throwIfHwBitmapInSwMode(BaseCanvas.java:557)\n at android.graphics.BaseCanvas.throwIfCannotDraw(BaseCanvas.java:69)\n at android.graphics.BaseCanvas.drawBitmap(BaseCanvas.java:109)\n at android.graphics.Canvas.drawBitmap(Canvas.java:1456)\n at com.mayank.picturemagic.MainView.cropSelection(MainView.java:434)\n at com.mayank.picturemagic.k$6.onClick(k.java:330)\n at android.view.View.performClick(View.java:6608)\n at android.view.View.performClickInternal(View.java:6585)\n at android.view.View.access$3100(View.java:785)\n at android.view.View$PerformClick.run(View.java:25921)\n at android.os.Handler.handleCallback(Handler.java:873)\n at android.os.Handler.dispatchMessage(Handler.java:99)\n at android.os.Looper.loop(Looper.java:201)\n at android.app.ActivityThread.main(ActivityThread.java:6810)\n at java.lang.reflect.Method.invoke(Native Method)\n at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)\n at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)" ]
[ "android", "canvas", "bitmap", "android-custom-view" ]
[ "crash on NSString stringWithFormat", "I have a line code that creates a NSString like below, \n\nNSString *paramString = [NSString stringWithFormat:@\"?user_id=%@&x=%@&y=%@\",_selectedID, _selectedX,[MyModel shared].currentUser.userID];\n\n\nI do get crash report as below :\n\ncrash in :\nThread 0 crashed:\nlibobjc.dylib objc_msgSend + 16\nCoreFoundation _NSDescriptionWithLocaleFunc + 68\nCoreFoundation _CFStringAppendFormatCore + 6004\nCoreFoundation _CFStringCreateWithFormatAndArgumentsAux + 116\nFoundation [NSPlaceholderString initWithFormat:locale:arguments] + 160\n\n\nuserID in currentUser is a NSString.\n_selectdID and _selectedX are both NSStrings passed from VC1 --> VC2 ---> VC3. In VC2 and VC3, both are declared as @property(nonatomic,assign).\n\nHowever this crash only occurs for around 1% of users and all of them are on iOS 7.1.1 as per crash report.\n\nI tried to simulate it with no luck. Is it because of memory is released ? Is there any to simulate this?" ]
[ "ios", "objective-c" ]
[ "I've created my first language in Irony, now how do I get it into Visual Studio 2010?", "I tried following this, but I get an error at the end of the wizard. I'm not sure it's compatible with 2010. I'm watching this video on Ook, but I'm not sure how to tie it in with Irony. I think Irony's already done a lot of the grunt work for me, I just don't know how to get it to play nicely with ITaggerProvider and the 100 other interfaces VS exposes. How do I do that?" ]
[ "visual-studio-2010", "irony" ]
[ "Remove Python from usr/local/bin - 2 versions installed", "Somehow i have 2 versions of Python 2 installed. The one installed in usr/local/bin is Python 2.7.13 and the one in usr/bin is Python 2.7.6 - i want to keep the 2.6 version and remove the other one.\n\nHow do i remove the other one safely ? \n\nOutput of which python\n/usr/local/bin/python\n\nAlso, the symlink points to python2.7 in the usr/local/bin itself.\n\nEDIT: The other version is not 2.6 but 2.7.6, which should be the default version installed." ]
[ "python", "ubuntu" ]
[ "Import script in sub directory not working... Blender Add-On", "I have a folder structure like this:\nC: \n|_Blueprint\n│ main.py\n│\n└───toolbox\n blueprint_tools.py\n\nWhen I run this code in Blender's scripting text page:\nfrom toolbox.blueprint_tools import dimension, array, modify\n\nI get an error in the console\n\nTraceback (most recent call last):\n File "\\main.py", line 20, in <module>\nModuleNotFoundError: No module named 'toolbox'\nError: Python script failed, check the message in the system console\n\n\n\nI swear, when I run this code (on other projects) outside of Blender this structure and code runs fine. But I get an error when running this script in Blender for testing out my Add-On.\nIf I compile the Blueprint folder into a .zip and install it everything works fine.... ??\nI'm lost, could anyone please help me.\nIf I run the code like this: (added a . before toolbox for CWD)\nfrom .toolbox.blueprint_tools import dimension, array, modify\n\n\nTraceback (most recent call last):\n File "\\main.py", line 20, in <module>\nImportError: attempted relative import with no known parent package\nError: Python script failed, check the message in the system console" ]
[ "python-3.x", "import", "blender", "init" ]
[ "How to remove the first column from all files and replace?", "I have several tab-delimited files, e.g. the file looks like this:\n\nA213<TAB>foo bar<TAB>sentence\nA123<TAB>bar foo<TAB>sentence\nB84521<TAB>abc hello<TAB>world\nC984<TAB>def word<TAB>hello\n\n\nI need it to remove the first column and the substitute the tabs with |||, the output should look as such:\n\nfoo bar ||| sentence\nbar foo ||| sentence\nabc hello ||| world\ndef word ||| hello\n\n\nI've tried the following but it didn't work:\n\n$ cut -f2,3 file.txt | sed 's/<TAB>/\\s|||\\s/g'" ]
[ "unix", "sed", "cut", "tab-delimited" ]
[ "How to encode a video with subtitles to a hls streaming with subtitles on azure media services", "Having a mp4 video and its vtt subtitle file, how can I encode this video to a h264 multiple bitrate adaptative streaming including subtitles?\nHow I have to include caption files in the encoding process?" ]
[ "http-live-streaming", "azure-media-services", "webvtt" ]
[ "Sequelize association with one foreign key", "I have a database that was originally created with Django that was setup for a single foreign key association, here is the JSON dump.\n\nNow this would be mapped as:\n\nexport const Category = sequelize.define(\n 'category',\n {\n name: { type: Sequelize.STRING, unique: true },\n },\n {\n timestamps: false,\n tableName: 'ingredients_category',\n }\n);\n\nexport const Ingredient = sequelize.define(\n 'ingredient',\n {\n name: { type: Sequelize.STRING, unique: true },\n notes: { type: Sequelize.TEXT, defaultValue: '' },\n category_id: {\n type: Sequelize.INTEGER,\n references: {\n model: Category,\n key: 'id',\n },\n },\n },\n {\n timestamps: false,\n tableName: 'ingredients_ingredient',\n }\n);\n\nCategory.belongsToMany(Ingredient, {\n foreignKey: 'category_id',\n constraints: false,\n through: 'ingredient_category',\n});\nIngredient.hasOne(Category, {\n // foreignKey: 'ingredientId',\n constraints: false,\n});\n\n\nNow sequelize complains that it is missing a foreign key on the Category model, but while there is only a single category on an ingredient the categories are not restricted to that one ingredient. Can someone help me to make sense of this association?\n\nUPDATE: For the final answer it was just an incorrect association setup:\n\nexport const Category = sequelize.define(\n 'category',\n {\n name: { type: Sequelize.STRING, unique: true },\n },\n {\n timestamps: false,\n tableName: 'ingredients_category',\n }\n);\n\nexport const Ingredient = sequelize.define(\n 'ingredient',\n {\n name: { type: Sequelize.STRING, unique: true },\n notes: { type: Sequelize.TEXT, defaultValue: '' },\n },\n {\n timestamps: false,\n tableName: 'ingredients_ingredient',\n }\n);\n\nCategory.hasMany(Ingredient, {\n foreignKey: 'category_id',\n});\nIngredient.belongsTo(Category, {\n foreignKey: 'category_id',\n});" ]
[ "javascript", "sqlite", "sequelize.js" ]
[ "Bad allocation with list", "I have this virtual method:\n\nconst string& my_class::to_string() const\n{\n string str(this->name + string(\" \"));\n\n if(!this->children.empty())\n {\n for(const std::shared_ptr<base_class> e : this->children)\n str.append(e.get()->to_string());\n }\n\n return str;\n}\n\n\nWhere children is a std::list<std::shared_ptr<base_class>>, and my_class inherits base_class. But, after the first recursive call (of my_class::to_string), and after I return this child str, i get a bad allocation.\n\nWhy?" ]
[ "c++", "c++11", "shared-ptr", "bad-alloc" ]
[ "Migration from GCM to FCM effects on current porduction apps", "I have an android app working on production environment and I don't know how to migrate from GCM to FCM. I don't have a copy of an old GCM app to explore the process. So, my concern is: If I try to upload the existing app to firebase and create a new firebase project, would my living GCM project can be affected and as a result would doing this make my app stop supporting my users to use GCM service? \n\nAny help Appreciated,\nAyshine" ]
[ "android", "migration", "google-cloud-messaging" ]
[ "Authentication cookie not being read when using [Authorize] attribute", "I need help configuring my asp.net application using cookie authentication. This is what my configuration looks like:\n\npublic void ConfigureAuth(IAppBuilder app)\n{\n app.CreatePerOwinContext(ApplicationDbContext.Create);\n app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);\n\n app.UseCookieAuthentication(new CookieAuthenticationOptions()\n {\n AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,\n CookieSecure = CookieSecureOption.SameAsRequest,\n });\n\n app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);\n\n PublicClientId = \"self\";\n OAuthOptions = new OAuthAuthorizationServerOptions\n {\n TokenEndpointPath = new PathString(\"/Token\"),\n Provider = new ApplicationOAuthProvider(PublicClientId),\n AuthorizeEndpointPath = new PathString(\"/api/Account/ExternalLogin\"),\n AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),\n AllowInsecureHttp = true\n };\n\n app.UseOAuthBearerTokens(OAuthOptions);\n}\n\n\nMy login api route is:\n\n[Route(\"Login\")]\n[HttpPost]\n[AllowAnonymous]\npublic IHttpActionResult Login(RegisterBindingModel model)\n{\n var user = UserManager.Find(model.Username, model.Password);\n\n if (user != null)\n {\n Authentication.SignOut();\n var identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);\n identity.AddClaim(new Claim(ClaimTypes.Role, \"IsAdmin\"));\n Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);\n\n return Ok(\"Success\");\n }\n\n return Ok();\n}\n\n\nCalling login returns a cookie named .AspNet.ApplicationCookie but when I call the logout action:\n\n[Route(\"Logout\")]\n[HttpPost]\npublic IHttpActionResult Logout()\n{ \n Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);\n return Ok();\n}\n\n\nI get the following error: Authorization has been denied for this request\n\nWhat am I doing wrong?\n\nNote: I decorated the controller with the [Authorize] attribute" ]
[ "c#", "asp.net", "asp.net-mvc", "owin", "owin-middleware" ]
[ "I'm doing codeacademy to learn some python, and I keep getting an error asking me if I've created a function called plane_ride_cost", "I'm doing codeacademy to learn some python, and I keep getting an error asking me if I've created a function called plane_ride_cost.\n\n#As you can see by the code below, I have in fact declared the function. \ndef plane_ride_cost(city):\n if city == \"Charlotte\":\n fee = 183\n elif city == \"Tampa\":\n fee = 220\n elif city == \"Pittsburgh\":\n fee = 222\n elif city == \"Los Angeles\":\n fee = 475\n return fee" ]
[ "python" ]
[ "Array data only renders to HTML table every second event, otherwise undefined", "// Relevant code: \n\nconst searchBtn = document.getElementById(\"search-btn\");\nconst input = document.getElementById(\"input\");\nconst leftTable = document.querySelector(\"#left-table\");\nlet url = \"https://api.github.com/search/repositories?q=?\";\nlet tagsUrl;\nlet dataArr;\nlet names = [];\nlet language = [];\nlet latestTag = [];\nlet tableDataArr = [names, language, latestTag];\n\n// Fetch first 2 items for repos containing user query\nfunction search(newURL) {\n fetch(newURL, {\n headers: {\n \"Authorization\": \"xxxx\" \n }\n })\n .then(resp => {\n return resp.json();\n })\n .then(data => {\n dataArr = data.items.slice(0, 2);\n return extractData();\n });\n input.value = \"\"; \n}\n\n// Extract necessary values from returned object (language, name, latest tag) and push to corresponding arrays\nfunction extractData() {\n dataArr.forEach(i => {\n names.push(i.full_name);\n language.push(i.language);\n fetch(i.tags_url)\n .then(resp => {\n return resp.json();\n })\n .then(resp => {\n if (resp[0]) {\n latestTag.push(resp[0].name);\n } else {\n latestTag.push(\" \");\n }\n return console.log(tableDataArr);\n });\n // getLatestTag(i.tags_url);\n });\n renderData();\n}\n\n// Render array data to HTML table\nfunction renderData() {\n tableDataArr[0].forEach((i, j) => {\n let newRow = document.createElement(\"tr\");\n newRow.className = \"row\";\n newRow.innerHTML = `<td class='cell'>${i}</td>\n <td class='cell'>${tableDataArr[1][j]}</td>\n <td class='cell'>${tableDataArr[2][j]}</td>\n <td class='cell'><button class='add-btn'>Add</button></td>`;\n leftTable.appendChild(newRow);\n });\n}\n\n// User input event listeners\nsearchBtn.addEventListener(\"click\", () => {\n search(url + input.value);\n});\n\ninput.addEventListener(\"keyup\", e => {\n if (e.keyCode === 13) {\n search(url + input.value);\n }\n});\n\n\nI need the contents from each array inside tableDataArr to render to a HTML table after an event listener fires. The contents from tableDataArr[0] and tableDataArr[1] are rendering every time with no issue. \n\nBut, the contents from tableDataArr[2] render undefined with the first call, then render properly the next call, then undefined and so on with this alternating pattern between undefined and the data. What is going on here?" ]
[ "javascript", "html", "arrays", "json", "dom" ]
[ "Where is the missing operator in the SAS MIN function?", "I'm just starting out in SAS and have run into some troubles. I want to get the number of observations from two data sets and assign those values to existing global macro variables. Then I want to find the smaller of the two. This is my attempt so far:\n\n%GLOBAL nBlue = 0;\n%GLOBAL nRed = 0;\n\n%MACRO GetArmySizes(redData=, blueData=);\n/* Takes in 2 Army Datasets, and outputs their respective sizes to nBlue and nRed */\n\n data _Null_;\n set &blueData nobs=j;\n if _N_ =2 then stop;\n No_of_obs=j;\n call symput(\"nBlue\",j);\n run;\n\n data _Null_;\n set &redData nobs=j;\n if _N_ =2 then stop;\n No_of_obs=j;\n call symput(\"nRed\",j);\n run;\n %put &nBlue;\n %put &nRed;\n%MEND;\n\n%put &nBlue; /* outputs 70 here */\n%put &nRed; /* outputs 100 here */\n\n%put %EVAL(min(1,5));\n\n%GetArmySizes(redData=redTeam1, blueData=blueTeam); /* outputs 70\\n100 here */\n\n%put &nBlue; /* outputs 70 here */\n%put &nRed; /* outputs 100 here */\n\n%MACRO PrepareOneVOneArmies(redData=,numRed=,blueData=,numBlue=);\n/* Takes in two army data sets and their sizes, and outputs two new army\n data sets with the same number of observations */\n\n %let smallArmy = %eval(min(&numRed,&numBlue));\n %put &smallArmy;\n\n %local numOneVOne;\n %let numOneVOne = %eval(&smallArmy-%Eval(&nBlue - &nRed));\n %put &numOneVOne;\n\n data redOneVOne; set &redData (obs=&numOneVOne);\n run;\n\n data blueOneVOne; set &blueData (obs=&numOneVOne);\n run;\n%MEND;\n\n%PrepareOneVOneArmies(redData=redTeam1,numRed=&nRed,blueData=blueTeam,numBlue=&nBlue); \n/* stops executing when program gets to %let smallArmy =... */\n\n\nredTeam1 is a data set with 100 observations, blueTeam has 70 observations.\n\nI now run into the problem where whenever I call the function \"Min\" I get:\n\n\n \"ERROR: Required operator not found in expression: min(1,5)\"\n\n\nor\n\n\n \"ERROR: Required operator not found in expression: min(100,70)\"\n\n\nWhat am I missing? \n\n\"Min\" seems like a simple enough function. Also, if it matters, I am using the University edition of SAS." ]
[ "sas", "min" ]
[ "jsonp being sent as GET", "I opened another post last week because my elastic search was not returning accurate results see, ElasticSearch post\n\nBasically what was happening was that when I am using jsonp, the request is not actually being sent as a GET request instead of a POST request. Below is the jsonp request. When I use json, it actually gets sent as a POST. \n\n amplify.request.define(\"searchPostRequest\", \"ajax\", {\n url: \"http://leServer:9200/people/person/_search\",\n type: \"POST\",\n dataType: 'jsonp',\n contentType: 'application/json'\n });\n\n\nAnyone know how I can force jsonp to be sent as a POST request?" ]
[ "jquery", "ajax", "elasticsearch" ]
[ "Is it possible to change object types in MongoDB?", "When I uploaded a CSV file to MongoDB, one of the objects I chose as a number, but they came out to be Doubles. This later caused some issues and I don't want to reupload the CSV file. Is there an easy way to change Doubles into Int64s for one data type in Python3?" ]
[ "python", "python-3.x", "mongodb", "integer" ]
[ "HTML web app referencing geojson stored in Firebase", "I'm currently developing a web app that will need to read data from a geojson file and then write that data onto a map, creating a heatmap. I currently am able to run the app locally when I reference the geojson in the following block of code:\nmap.on('load', function() {\n map.addLayer({\n id: 'collisions',\n type: 'circle',\n source: {\n type: 'geojson',\n data: 'demostation.json'\n },\n\nRun locally, the heatmap is created with no issue. However, when I try to change data: 'demonstration.json' to data: 'url' there is no heatmap created.\nI have uploaded the json file that I want to read to my Firebase storage files. How do I go about reading this stored file so that my web app can work globally? Thanks!" ]
[ "html", "firebase", "web-applications", "heatmap" ]
[ "I increased the number of channels from 7 to 8 in my CNN but results deteriorate, why?", "My input images have 8 channels and my output (label) has 1 channel and my CNN in keras is like below:\n\ndef set_model(ks1=5, ks2=5, nf1=64, nf2=1):\n model = Sequential()\n model.add(Conv2D(nf1, padding=\"same\", kernel_size=(ks1, ks1), \n activation='relu', input_shape=(62, 62, 8)))\n model.add(Conv2D(nf2, padding=\"same\", kernel_size=(ks2, ks2), \n activation='relu'))\n model.compile(loss=keras.losses.binary_crossentropy,\n optimizer=keras.optimizers.Adadelta())\n return model\n\n\nBelow is the summary of the model implemented above:\n\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_1 (Conv2D) (None, 62, 62, 64) 12864 \n_________________________________________________________________\nconv2d_2 (Conv2D) (None, 62, 62, 1) 1601 \n=================================================================\nTotal params: 14,465\nTrainable params: 14,465\nNon-trainable params: 0\n_________________________________________________________________\n\n\nAnd by another question, I asked here (How to have a 3D filter for Conv2D in Keras?) I am convinced that every channel has their own set of weights. Now, my question is why when I add another channel and increase them 7 to 8, why the results deteriorate?\n\nPrediction accuracy index with 7 channels:\n\n\nPrediction accuracy index with 8 channels:\n\n\nI also standardized all 8 channels into values between 0 and 1.\n\none of the predictions with 7 channels:\n\n\n\none of the predictions with 8 channels:" ]
[ "neural-network", "keras", "conv-neural-network" ]
[ "Everything after a Greek letter is empty in my database", "I'm encountering what I'm sure is an encoding error but I can't seem to find the weak link in my logic. In particular, when trying to insert a Greek lambda into my database, the cell is blank after the lambda.\n\nThe process:\n\nBefore any html is printed, I'm doing:\n\nheader('Content-Type: text/html; charset=utf-8');\n\n\nNext, I'm connecting using PDO:\n\n$dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['dbname'] . ';charset=utf8';\n $options = array(\n PDO::ATTR_EMULATE_PREPARES => false, \n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION\n );\n try {\n $dbh = new PDO($dsn, $config['username'], $config['password'], $options);\n $dbh->exec(\"SET NAMES utf8\");\n $dbh->exec(\"SET FOREIGN_KEY_CHECKS = 1\");\n\n\nWhen I do \n\n\n SHOW FULL COLUMNS FROM my_table\n\n\nI can see that the collation is utf8_general_ci.\nWhen I do:\n\n\n echo mb_detect_encoding($data_to_be_entered);\n\n\nI get UTF-8\n\nWhen I echo out $data_to_be_entered into the console right before I insert it into the database, I see: (=23)\n\nHowever, in my database, I just see ( as the entry." ]
[ "php", "mysql", "pdo", "encoding", "character-encoding" ]
[ "Wordpress Redirect to 404", "If I try to use link like http://site_name/post_name/546/, I would be redirected to http://site_name/post_name/. Is there any way to make redirect to 404 page in this case (only if last part of url contains numbers)?" ]
[ "wordpress", "redirect" ]
[ "Running a go program on Android?", "I have a go library that i want to run on android and use its methods in my android app. I could write the whole android app in go to make it easier to use this dependency. Is this possible? If so, how?" ]
[ "android", "go" ]
[ "CRA environment variables from public subfolder", "Create React App documentation states that you can reference environment variables in the HTML, but only in the public/index.html file.\nI need to do the same but in a public/MY_SUB_FOLDER/index.html file.\nIs it possible? If so, how do I do it?" ]
[ "environment-variables", "create-react-app" ]
[ "How to keep attributes from two different tables synchronized in RoR?", "What I want is to be able to easily be able to find the team name associated with a membership without having to send another request to the database. My plan was to just add a team_name attribute to the Memberships table, but I can't think of a way to have this new attribute stay in sync with the name attribute in the Teams table. In other words, I want it to be the case that, if the owner of a team changes the team's name, then all memberships to that team will be updated (with the new team name) as well.\n\nHere is what my setup looks like. I've fairly new to Rails. \n\n/app/models/membership.rb\n\nclass Membership < ActiveRecord::Base\n belongs_to :user\n belongs_to :team\nend\n\n\n/app/models/team.rb\n\nclass Membership < ActiveRecord::Base\n belongs_to :user\n belongs_to :team\nend\n\n\n/app/db/schema.rb\n\nActiveRecord::Schema.define(version: 20161022002620) do\n\n create_table \"memberships\", force: :cascade do |t|\n t.integer \"user_id\"\n t.integer \"team_id\"\n t.datetime \"created_at\"\n t.datetime \"updated_at\"\n end\n\n create_table \"teams\", force: :cascade do |t|\n t.string \"name\"\n t.integer \"user_id\"\n end\nend\n\n\nIf there is a better way to achieve what I am asking, then please let me know as well." ]
[ "ruby-on-rails", "ruby", "data-structures", "synchronization", "rails-activerecord" ]
[ "Object c property dealloc, which one is correct?", "Possible Duplicate:\n Dealloc method in iOS and setting objects to nil \n\n\n\n\nAs to property dealloc in object c, i have seen different kinds of forms. Which of following is best/correct\n\n//Kind1:\n- (void)dealloc\n{\n [_property release];\n [super dealloc];\n}\n\n//Kind2:\n- (void)dealloc\n{\n self.property = nil;\n [super dealloc];\n}\n\n//Kind3:\n- (void)dealloc\n{\n [_property release]; _property = nil;\n [super dealloc];\n}" ]
[ "iphone", "objective-c", "ios", "ipad", "properties" ]
[ "How could a LinkedHashMap fail to find an entry produced by an iterator?", "Under what circumstances given a correct implementation of hashCode and equals() can the following code return false?\n\nmyLinkedHashMap.containsKey(myLinkedHashMap.keySet().iterator().next())" ]
[ "java", "equals", "hashcode" ]
[ "How to convert YAML list to a string array in Java?", "I have a YAML configuration file have the below list:\n\nname:\n - string1\n - string2\n - string3\n\n\nI am reading the configuration file as follows:\n\nYaml = _yml = new Yaml();\nInputStream in = Resources.getResources(\"myconfigfile.yml\").opendStream();\n\nMap cfg_map = (Map) yaml.load(in);\nin.close();\n\nString[] values = cfg_map.get(\"name\");\n\n\nHere in this line String[] values = cfg_map.get(\"name\"); gives me the object. How can I convert it to the String array? \n\nI tried with cfg_map.get(\"name\").toString().split(\"\\n\") but it didn't work." ]
[ "java", "yaml", "snakeyaml" ]
[ "How to set text align and indentation in codemirror editor as it always start in the middle?", "I have problems using CodeMirror. When I typed my codes in the textarea, it will start in the middle and not at the most left even after going to next line.\nMust I modify the CSS?\n\nJSP:\n\n<script>\nvar editor = CodeMirror.fromTextArea(document.getElementById(\"myTextArea\"), {\nmode:\"javascript\",\nlineNumbers: true,\nautofocus: true\n});\neditor.setSize(500,680);\n</script>\n\n\nhttps://i.stack.imgur.com/wvhVZ.jpg" ]
[ "java", "css", "jsp", "codemirror" ]
[ "DrawText doesn't add ellipsis to the end of a text in MFC", "I have a simple MFC application in which I'm trying to add ellipsis to the end of a string.\n\nHere's my code:\n\nvoid CMFCApplication1Dlg::OnPaint()\n{\n if (IsIconic())\n {\n CPaintDC dc(this); // device context for painting\n\n SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);\n\n // Center icon in client rectangle\n int cxIcon = GetSystemMetrics(SM_CXICON);\n int cyIcon = GetSystemMetrics(SM_CYICON);\n CRect rect;\n GetClientRect(&rect);\n int x = (rect.Width() - cxIcon + 1) / 2;\n int y = (rect.Height() - cyIcon + 1) / 2;\n\n // Draw the icon\n dc.DrawIcon(x, y, m_hIcon);\n }\n else\n {\n CPaintDC dc(this); // device context for painting\n\n CRect rect;\n rect.top = 0;\n rect.bottom = 100;\n rect.left = 0;\n rect.right = 100;\n dc.DrawText(_T(\"This is a very very long text that should span accross multiple lines and have elipsis at the end\"), -1, &rect, DT_WORDBREAK | DT_MODIFYSTRING | DT_END_ELLIPSIS);\n\n CDialogEx::OnPaint();\n }\n }\n\n\nThis is what I get:\n\n\n\nI was expecting ellipsis to be added to the end of the string. What am I doing wrong?" ]
[ "c++", "mfc" ]
[ "Binding events via $.Ajax won't show on the calendar", "I've to do maintenance on an existing MVC app which is using an old version of FullCalendar (we're talking of 1.6.4).\nAs the latest commit, the view was passing the data as View's load via Model so the event where loaded in this way:\n\n $('#divAgenda').fullCalendar({\n header: {\n left: 'prev,next today',\n center: 'title',\n right: ''\n },\n editable: false,\n disableDragging: true,\n events: eventsJson, \n eventClick: function (calEvent, jsEvent, view) {\n eventDetail(calEvent.IdsEventi, calEvent.tipo, calEvent.start);\n },\n\nfunction EventsJsonFunc() {\n var events = '<%= Html.Raw(Model.EventiJson) %>';\n\n return jQuery.parseJSON(events);\n}\n\n\nNow I've moved the loading at a ComboBox event change (since I've to filter the data I need to show) as\n\nvar dropdownlist = $('#divAgendaFilter').kendoComboBox({\n dataTextField: \"text\",\n dataValueField: \"value\",\n dataSource: data,\n\n select: function (e) {\n if (e.item) {\n var dataItem = this.dataItem(e.item.index());\n\n $.ajax({\n url: '<%= Url.Action(\"LoadData\", \"Agenda\")%>',\n type: \"GET\",\n dataType: \"json\",\n data: {\n userId: '<%= Request.QueryString[\"userId\"] == null ? string.Empty : Request.QueryString[\"userId\"].ToString() %>',\n selectedFilter: dataItem.value\n },\n success: function (data) {\n var calendar = $('#divAgenda').data(\"fullCalendar\");\n\n // var items = jQuery.parseJSON(data);\n calendar.events=data;\n debugger;\n\n }\n });\n }\n\n\nIn data I've got the events but after assigning them nothing happens... what am I doing wrong?" ]
[ "javascript", "asp.net-mvc", "fullcalendar" ]
[ "Ivy Configuration Help", "I've read the Ivy docs and a few other tutorials but am now trying to actually use it in a project for the first time and I am immediately presented with some roadblocks.\n\n\nFor the practice, I would like to write all my own config (XML) files. Not sure where to put ivy.xml, ivyconf.xml or ivy-settings.xml: do I put them in the same directory as my build.xml?\nBesides ivy.xml, ivyconf.xml and ivy-settings.xml, are there any other config files that I should know about? Where do I place those?\nIs the IvyDE just a graphical Eclipse plugin that graphically edits ivyconf.xml or does it edit other files?\n\n\nThanks for any input - it's been surprisingly difficult finding good info on this amazing tool!" ]
[ "apache", "configuration", "ivy" ]
[ "PDFBox - Losing Checkbox selection on \"Save as\" functionality of Dynamically filled PDF form", "I have an issue regarding a dynamically filled PDF form losing checkbox selection on using the Saves As functionality\n\nI am describing the workflow which we are using currently to fill the PDF and subsequent issues.\n\n\nWe are receiving the PDF template created through \"Adobe InDesign\" from a 3rd party vendor.\nWe are using \"Apache PDFBox 1.8.X' utility to read the PDF form and fill in all the required fields .. including checkboxes and radio buttons.\nOnce the Filled up PDF is generated through PDFbox, the PDF opens in a new browser window. All the selections are visible correctly as desired.\n\n\nScenario 1 > If i just save the generated PDF through save button on the browser , the PDF is saved correctly & all the checkbox selections are retained.\nAlso, when using Acrobar Pro to inspect the form fields, the check box fields are identified correctly.\n\nScenario 2 ( Having issue ) > In case of using \"Save As\" either on the browser Or \"Save As\" on the previously saved PDF on disk, on saving .. The checkboxes which were selected before displayed without the selections. Also , the previously filled Check Box is also not recognized as a Form Field. Instead the checkbox is almost like a normal image / text almost .\n\nOn a related note , i found that i am able to view the checkbox selection when i open the \"Save As\" pdf it within Internet Explorer or another PDF utility other than Adobe Acrobat XI . It seems to be an issue with PDFBox & Adobe Acrobat XI.\n\nAny help would be very much appreciated." ]
[ "java", "pdfbox", "acrobat" ]
[ "Load image from webUrl at ImageView in ExpandableListView in android", "In my project i am using google webService in which i am quering different query like-- hospital, cinema hall, resort etc. and get result in json format .\nFrom json i get so many data like Name, lat, lng, imageUrl, Web url in respective query. And i am manupulating these data and showing it in my Expandable listView. I am able to do show all data but when i am loading image on ImageView it is showing some mismatch. For loading image, I am using ImageLoader, FileCache, MemoryCache and Utils java class.\nBasically question is i have http web url for image and now i want to show it on my ImageView at Expandable listView, and i am not properly perform it. Please any buddy help." ]
[ "android", "android-listview", "expandablelistview", "android-imageview", "image-load" ]
[ "MySQLi connect withtout specifying a database", "I am using many database and I would like to know if its possible to connect with mysqli and specify the database after : example\n\n$mysqli = new mysqli(\"localhost\", \"user\", \"password\", \"database\");\n$req = $mysqli->query(\"SELECT * FROM `table` WHERE id = '1' \");\n\n\nWould become \n\n$mysqli = new mysqli(\"localhost\", \"user\", \"password\");\n$req = $mysqli->query(\"SELECT * FROM `database`.`table` WHERE id = '1' \");\n\n\nI could add $mysqli->select_db(\"database\"); but if there is a way to use the query above, I'd like to know how to do. Thank you !" ]
[ "php", "database", "pdo", "mysqli" ]
[ "Multiple versions of COM object on same server", "I maintain a large ASP classic web site (no budget to convert to ASP.NET). It uses COM objects, written in C#. I need to run multiple sites (Production, UAT, QA) on the one web server. \n\nI would like to be able to have each site run different versions of the code base. That would mean having a separate version of the same COM object per site. \n\nHowever, it looks like COM objects get registered in the server's registry, with no support for separate versions.\n\nHow can I use different version of the same COM object with my site running on the same web server?" ]
[ "asp-classic", "com" ]
[ "connect c++ object signal to QML signal handler with enum parameter", "I have the following c++ plugin code:\n\nclass NetworkManager : public QObject\n{\nQ_OBJECT\n\n...\nenum WIFIStat{\n STAT_NOTINITED,\n STAT_INITED\n};\nQ_ENUM(WIFIStat)\n\n Q_PROPERTY(WIFIStat wifiStatus READ wifiStatus NOTIFY wifiStatusChanged)\n\n\nand i want to connect to a signal handler in QML:\n\nsignal wifiStatusChanged(WIFIStat wifiStatus);\n\nonWifiStatusChanged: {\n console.log(wifiStatus)\n}\n\nComponent.onCompleted: {\n network_manager.wifiStatusChanged.connect(wifiStatusChanged);\n}\n\n\nbut i'm getting the follwing error:\n\nInvalid signal parameter type: WIFIStat\n\n\nHow can i define the enum NetworkManager::WIFIStat type parameter int the handler function?" ]
[ "c++", "qt", "qml" ]
[ "AWS EMR - how to increase php memory_limit", "I am running a job on aws emr which fails with error 'PHP Fatal error: Allowed memory size of 134217728 bytes exhausted'\n\nI tried with adding a bootstrap action script\n\n#!/usr/bin/php\n<?php\nini_set('memory_limit', '2048M');\n?>\n\n\nusing\nMaster: m1.large\nCore: m3.xlarge\n\nbut it is not increasing memory limit and I still received same error.\n\nhow can I increase php memory limit in AWS EMR.\n\nThanks" ]
[ "php", "amazon-web-services", "emr" ]
[ "Use Something like Rails Generator for PHP Development", "I want to create a command line based tool for PHP Development. \n\nIt should do something quite similar based on what the rails generator does as well as integrate with rake, as the rake tasks for the DB should also be available. \n\nOr is there a ruby framework that allows to build such generators?" ]
[ "php", "ruby-on-rails", "ruby", "rake", "generator" ]
[ "Multipeer Connectivity Doesn't Work When Wi-Fi is Switched Off", "I'm developing a simple Multipeer Connectivity application that sends Strings between devices. When the Wi-Fi in Settings is switched on, even if the device is not connected to a network, the communication works well (the string can be passed between devices successfully). But when i attempt to go to settings and switch Wi-Fi off (Bluetooth still on), the device even fails to find other peers, let alone sending data. But if i don't switch Wi-Fi off from settings but instead do it only from the Control Center (the menu when you slide upwards) the connection works well again. I tried encryptionPreference both none and required, but the result is the same.\n\nMy setup code if required:\n\nsession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .none)\nadvertiser = MCNearbyServiceAdvertiser (peer: peerID, discoveryInfo: nil, serviceType: SERVICE_NAME)\nbrowser = MCNearbyServiceBrowser(peer: peerID, serviceType: SERVICE_NAME)\n\n\nIs this an expected behavior or am i doing something wrong? Thanks in advance." ]
[ "ios", "objective-c", "swift", "multipeer-connectivity" ]
[ "Data Deletion With iCloud Core Data Sync", "I have a deployed iCloud-enabled iOS 8 app which syncs a Core Data model. The app deals with evaluating investment properties and records information about the property such as repairs. \n\nI recently received a complaint from a user who entered in 29 repairs for a property only to have them disappear 48 hours later. \n\nThere is no mechanism for deleting model objects in my app that doesn’t involve explicit permission from the user. I don’t believe that the user accidentally deleted 29 objects which is why I am suspicious that a faulty iCloud sync may have had something to do with this. \n\nThe user described that they enter the information on their i-Cloud enabled iPad, but also use their iCloud-enabled iPhone to view the synced data. If the sync used the iPhone data to overwrite the iPad data, the objects could be deleted. \n\nIs anyone aware of such an issue with iCloud? Does anyone have other general ideas on what the issue may be?" ]
[ "ios", "core-data", "icloud", "icloud-api" ]
[ "What is the best approach to find and store all pair distances in a weighted tree?", "What is the best approach to find and store all pair distances in a weighted tree?\n\nMy current approach is to run bfs on every node. But obviously this approach approach suffers from large complexity. Can we improve it further ?" ]
[ "algorithm", "graph" ]
[ "DotNet Core 2 Console Application Configuration", "The Core 1.x configuration has been answered here\n\nASP.NET Core configuration for .NET Core console application\n\nUnfortunately the Core 2.0.0 API and architecture has changed slightly and by the looks of this article that it uses Dependency Injection on the Startup class now (on a WebAPI based project) which is allot simpler.\n\nBut I am not sure how to do that on a Console application as there is no underlying DI. When I try to use the following code none of the methods exist on the new 2.0.0 \n\nvar builder = new ConfigurationBuilder()\n .AddJsonFile($\"appsettings.json\", true, true) -ERROR\n .AddJsonFile($\"appsettings.{environmentName}.json\", true, true) -ERROR\n .AddEnvironmentVariables(); -ERROR\n\n\nDoes any body know how to add appsettings.json into the ConfigurationBuilder?" ]
[ ".net-core-2.0" ]
[ "SQL Server & XML: how can I get an xml attribute from sql table?", "I have a table like this:\n\ncreate table product \n(\n id integer, \n category varchar(50), \n quantity integer, \n techdata varchar(100), \n cost_price float\n);\n\ninsert into product \nvalues (1, 'window', 2, '<Data w=\"1000\" h=\"1000\"/>', 100.56),\n (2, 'door', 1, '<Data w=\"900\" h=\"1800\"/>', 96.12),\n (3, 'window', 20, '<Data w=\"750\" h=\"300\"/>', 152.5),\n (4, 'door', 100, '<Data w=\"1046\" h=\"2046\"/>', 46.74),\n (5, 'window', 1, null, null);\n\n\nI have to select all 'w' and 'h' attribute values from those rows. I've tried this solution but it doesn't work.\n\nSELECT \n t.p.value('(@w)[1]', 'VARCHAR(50)') AS width,\n t.p.value('(@h)[1]', 'VARCHAR(50)') AS height\nFROM \n product \nCROSS APPLY \n techdata.nodes('/Data') t(p)\n\n\nAny hint for proper solution?" ]
[ "sql", "sql-server", "xml" ]
[ "Bootstrap EC2 Instance at launch to install awslogs", "I'm trying to implement the following Script into a Launchtemplate to launch EC2 Instances with awslogs installed and ready:\n\n UserData:\n \"Fn::Base64\": !Sub >-\n #!/bin/bash -xe\n yum install -y aws-cfn-bootstrap\n /opt/aws/bin/cfn-init -v --region ${AWS::Region} --stack ${AWS::StackName} --resource BastionHostLaunchtemplate --region ${AWS::Region}\n # Install the CloudWatch Logs agent\n yum -y install awslogs\n service awslogs start\n chkconfig awslogs on\n\n\nBut when I connect to the instance afterwards via SSH and check I get this:\n\n [ec2-user@ip-172-16-47-249 ~]$ sudo service awslogsd status\n Redirecting to /bin/systemctl status awslogsd.service\n Unit awslogsd.service could not be found.\n [ec2-user@ip-172-16-47-249 ~]$\n\n\nHow can I bootstrap the EC2 Instances correctly?\n\nmerci A" ]
[ "amazon-cloudformation" ]
[ "How to remove years in csv chart", "I write a python program to convert csv files into charts.\nIt shows 1900 in the chart but I don't need it.\nPlease help me check where is the problem.\nThanks.\n\nimport csv\nfrom matplotlib import pyplot as plt\nfrom datetime import datetime\nfilename='/home/pi/env_watcher/temp/env_report.csv'\nwith open(filename) as f:\n reader=csv.reader(f)\n header_row=next(reader)\n dates,ttemps,ctemps,thumis,chumis=[],[],[],[],[]\n for row in reader:\n current_date=datetime.strptime(row[0],'%b %d %H:%M:%S')\n dates.append(current_date)\n ttemp=float(row[1])\n ttemps.append(ttemp)\n ctemp=float(row[2])\n ctemps.append(ctemp)\n thumi=float(row[3])\n thumis.append(thumi)\n chumi=float(row[4])\n chumis.append(chumi)\n\nfig=plt.figure(dpi=128,figsize=(10,6))\nplt.plot(dates,thumis,c='red',alpha=0.5)\nplt.plot(dates,chumis,c='blue',alpha=0.5)\nplt.title('Weekly Humidity',fontsize=24)\nplt.xlabel('',fontsize=16)\nplt.ylabel('Humidity(%)',fontsize=16)\nplt.tick_params(axis='both',which='major',labelsize=16)\nfig.autofmt_xdate()\nplt.savefig(\"/home/pi/env_watcher/temp/env_humi.png\")\nplt.show()\n\n\ncsv file content is as follows\n......\nAug 25 05:10:13,30,26.8,70,45.0\nAug 25 05:20:13,30,26.8,70,44.8\nAug 25 05:30:15,30,26.8,70,45.5\nAug 25 05:40:13,30,26.8,70,45.5\nAug 25 05:50:13,30,26.9,70,46.1\nAug 25 06:00:13,30,26.9,70,46.3\nAug 25 06:10:13,30,26.9,70,46.8\nAug 25 06:20:13,30,26.9,70,46.8\n......\n\nOutput:" ]
[ "python", "python-3.x", "csv", "datetime", "matplotlib" ]
[ "Use of PUSH and POPD in windows batch script", "I have a requirement where I need to run a batch script which would compile a custom module and then come back to the project's root location and run the project.\n\nFor this, I have written something like below\n\nSET curDir=%~dp0\nPUSHD %curDir%\necho %curDir%\ncd modules\\custom-module\nyarn build\nPOPD\necho %CD%\nyarn start\n\n\nbut after the yarn build command, it stays in the modules\\custom-module directory." ]
[ "windows", "batch-file" ]
[ "How to build a Linq Query Dynamically", "I have see a few old post but cannot figure out how to achieve this, Please help with an example.\n\nI am running a query on a DataTable to group all the columns. The number columns will only be known as runtime hence I need to build the query dynamically.\n\nvar newGroup = from row in dataTable.AsEnumerable() \ngroup row by new { ID = row.Field<string>(\"column1\"), group1 = row.Field<string>(\"column2\") };\n\n\nI need to build the above query dynamically for n number of columns. \n\nPlease explain how can I build the ParameterExpression by looping over the columns list and build a Lambda expression." ]
[ "c#", ".net", "linq" ]
[ "Is there a way to disable popup blocker in Safari using Javascript?", "I know this is a very vague question. But in my current application, I need to download the xls file from ajax response. So I used \"window.location\", and it worked out perfectly in chrome, firefox and IE.\n\nBut safari is throwing an error \"resource interpreted as document but transferred with mime type 'application/vnd.ms-excel'\". For this I have changed the code little bit from \"window.location\" to \"window.open('url','_blank')\". It solved the mime type error. But when popup blocker is enabled in safari, it is not even prompting the user to give permission to open popup. But all other browsers did that.\n\nSo my question is! Is there any possibility that, I can turn off the popup blocker in safari either using javascript or jQuery (I Know we cannot override the browser settings using the js or jQuery)? Or at-least can we know weather pop-up blocker is enabled or not?" ]
[ "javascript", "jquery", "safari", "mime-types", "mime" ]
[ "Reverse engineering: Extract images/sprite sheet from apk", "I'm learning about game development and I'm trying to extract some resources from some games that I love to play, I'm doing this just to learn more about sprites and resource organization.\nThe problem is every game I extract the images come with some kind of problem, sometimes just doesn't open and other times I can open the image but I see just some pixels.\n\nIs there any resource protection used in the apk market? Is there any way to extract and see these sprite sheet?\n\nJust remember I'm doing this just for the PURPOSE OF LEARNING and I will not use it in any of my games or projects!\n\nThanks for any help and have a nice day guys :)." ]
[ "android", "apk", "sprite", "reverse-engineering", "sprite-sheet" ]
[ "Access OneDrive Personal via Microsoft Graph API - Token issues", "I am looking into using the Microsoft Graph API with personal OneDrive (logging in via a hotmail account and not an organisation account!).\n\nI want to create a Microsoft Graph client instance and consume the Microsoft Graph API with use-cases such as this\n\nvar expandValue = this.clientType == ClientType.Consumer\n ? \"thumbnails,children($expand=thumbnails)\"\n : \"thumbnails,children\";\n\nfolder = await this.graphClient.Me.Drive.Root.Request().Expand(expandValue).GetAsync();\n\n\nTo retrieve the access token I am using the code grant flow approach as described within this article.\n\nThe authorize endpoint being used\n\n\n https://login.microsoftonline.com/common/oauth2/v2.0/authorize\n\n\nThe token endpoint being used\n\n\n https://login.microsoftonline.com/common/oauth2/v2.0/token\n\n\nThe scope being used\n\n\n files.readwrite.all offline_access\n\n\nLogging in with a hotmail account is returning a non JWT token\n\nThis is the first part of this token\n\n\n EwBgA8l6BAAUO9chh8cJscQLmU+LSWpbnr0vmwwAAcGxJjYeNNkhw+sJQb2zJ\n\n\nWhen trying to use this token to create a Microsoft Graph service client instance and consume requests such as the ones shown above, I am getting this error\n\n\n Code: InvalidAuthenticationToken\n Message: CompactToken parsing failed with error code: 8004920A\n Inner error:\n AdditionalData:\n request-id: 3f472759-9718-47fb-8da0-df1646bb2fe8\n date: 2020-05-19T16:42:44\n ClientRequestId: 3f472759-9718-47fb-8da0-df1646bb2fe8\n\n\nI tried setting the Azure AD App registration \"signInAudience\" parameter in the manifest to both \"AzureADAndPersonalMicrosoftAccount\" and \"PersonalMicrosoftAccount\". The former returns the token as shown above which then fails when sending the request, while when using the latter sign in audience, the token is simply not retrieved and a \"Bad request\" error with literally no extra info is returned. \n\nEverything works fine when I login with my organisation account. It shows my personal folders within my organization's OneDrive for Business account.\n\nAdditionally, if I instead use the below line, I can view my organisation's OneDrive for business shared folders too (just by removing the .Me from after graphClient)\n\nfolder = await this.graphClient.Drive.Root.Request().Expand(expandValue).GetAsync();\n\n\nThis article supposedly describes retrieving a bearer token for Microsoft account cases, which I eventually presumed was what I needed. \n\nThe authorize endpoint being used\n\n\n https://login.live.com/oauth20_authorize.srf\n\n\nThe token endpoint being used\n\n\n https://login.live.com/oauth20_token.srf\n\n\nThe scope being used\n\n\n onedrive.readwrite offline_access\n\n\nUsing this approach still returns the same type of token, so this literally left me within the same situation.\n\nI also noticed that the approach within the latter article is discouraged and that in fact the approach of article 1 is suggested! So I simply wasted some more of my time :)\n\nWhat kind of service/API has to be used for personal OneDrive access (via a hotmail account) ? What kind of token am I getting and what can I use it for? What could I be doing wrong here?" ]
[ "azure", "oauth-2.0", "microsoft-graph-api", "onedrive", "hotmail" ]
[ "Textarea won't clear after clearing attached model in angularjs", "I have a textarea attached to a $scope variable called newNoteText. The html is:\n\n<textarea spellcheck=\"true\" \n ng-model=\"newNoteText\"></textarea>\n\n\nThere's also a button that saves the typed note.\n\n<button type=\"button\" class=\"btn btn-default\" \n ng-click=\"btnPost_clicked(newNoteText)\">Post\n</button>\n\n\nHere's the controller function btnPost_clicked:\n\n $scope.btnPost_clicked = function(newNoteText) {\n $scope.addNote(newNoteText);\n $scope.newNoteText = '';\n }\n\n\nI confirmed via console.log that $scope.newNoteText is being reset to an empty string. But the textarea still holds the old text." ]
[ "javascript", "angularjs" ]
[ "encoding of backslash in pythons pyautogui", "I am trying write a python script that runs an external program automatically by clicking buttons and give keyboard input (usually file paths) with pyautogui.\nNow if I try use the funktion pyautogui.typewriter(filepath) it always types the backslashes as questionmarks.\nThis minimal example:\n\npyautogui.typewrite('\\\\')\n\n\nreturns simply ?\n\nNow, if I change my keyboard layout in the system settings to english, it correctly returns \\\n\nMy default layout is german, and I cant really change that because this messes up the later stages of the program due to wrong date formats.\nAny ideas how to solve this problem?" ]
[ "python", "string", "encoding", "pyautogui" ]
[ "How to check if a COM component (EXE/DLL file) is registered or not (using .NET)?", "How do I check if a COM component (EXE/DLL file) is registered or not using .NET?" ]
[ "c#", ".net", "com" ]
[ "Error in streaming-analytic service in Bluemix", "I followed this tutorial to use the streaming-analytic service in Bluemix to interface with message-hub: https://developer.ibm.com/bluemix/2015/10/16/streaming-analytics-message-hub-2/?cm_mc_uid=45284031179414585919178&cm_mc_sid_50200000=1464112496\n\nI am getting an error: \n\n\n Caused by: org.apache.kafka.common.KafkaException:\n javax.security.auth.login.LoginException: unable to find LoginModule\n class: com.ibm.messagehub.login.MessageHubLoginModule\n\n\nThanks" ]
[ "java", "apache-kafka", "ibm-cloud", "message-hub" ]
[ "Hibernate: how to insert foreign key id to a table", "I am new to Hibernate and I am trying to save List<AuditScope> auditScopes from Audit entity using Hibernate. Audit entity has One-to-Many relationship with AuditScope entity, Audit can have many AuditScope. I am using saveAll() method to batch insert auditScopes instead of saving one by one through a loop. Unforunately, I have to loop auditScopes just to set each AuditScope's auditId(FK) manually instead of automatically. What I want is to batch insert them without looping and manually setting auditId. I am sorry my code is not good. Thank you very much.\n\nHere are my classes:\n\n@Entity\n@Table(name=\"audit\")\npublic class Audit {\n@Id\n@GeneratedValue(strategy=GenerationType.SEQUENCE, generator=\"audit_gen\")\n@SequenceGenerator(name=\"audit_gen\")\n@Getter @Setter private int auditId;\n@Getter @Setter private String auditName;\n@Transient @Getter @Setter private List<AuditScope> auditScopes;\n}\n\n@Entity\n@Table(name=\"auditScope\")\npublic class AuditScope {\n@Id\n@GeneratedValue(strategy=GenerationType.SEQUENCE, generator=\"auditScope_gen\")\n@SequenceGenerator(name=\"auditScope_gen\")\n@Getter @Setter private int auditScopeId;\n@Getter @Setter private int auditId; //FK\n@Getter @Setter private String scope;\n}\n\n\nHere's my insertAudit() method\n\npublic void insertAudit(Audit audit){\n //Save Audit first to get auditId\n Audit theAudit = auditRepository.save(audit);\n\n //Loop audit.getAuditScopes() to manually set auditId\n for(AuditScope scope : audit.getAuditScopes()){\n scope.setAuditId(theAudit.getAuditId());\n }\n\n //Save all AuditScope with set auditId\n auditScopeRepository.saveAll(audit.getAuditScopes());\n\n /*\n Expected result\n auditRepository.save(audit);\n auditScopeRepository.saveAll(audit.getAuditScopes());\n */\n\n}" ]
[ "java", "hibernate" ]
[ "align center a UL with only images", "I have a <ul> with 6 images, no text. I can't seem to make it be in the center of the page. This is my code.\n\nCSS\n\n.logos{ \n margin:0 auto; \n text-align:center;\n display:table;\n float: left;\n}\n\n\nHTML \n\n<div class=\"logos\" style=\"margin:0 auto;\">\n <ul class=\"logos\">\n <li class=\"logos\"> <img src=\"imgs/logo1.gif\"> </li>\n <li class=\"logos\"> <img src=\"imgs/logo2.gif\"> </li>\n <li class=\"logos\"> <img src=\"imgs/logo3.gif\"> </li>\n <li class=\"logos\"> <img src=\"imgs/logo4.gif\"> </li>\n <li class=\"logos\"> <img src=\"imgs/logo5.gif\"> </li>\n <li class=\"logos\"> <img src=\"imgs/logo6.gif\"> </li>\n </ul>\n</div>" ]
[ "html", "css", "image", "alignment", "html-lists" ]
[ "How to ensure that my workitems are running parallel?", "CL_DEVICE_NAME = GeForce GT 630\n\nCL_DEVICE_TYPE = CL_DEVICE_TYPE_GPU\n\nCL_PLATFORM_NAME : NVIDIA CUDA\n\nsize_t global_item_size = 8;\nsize_t local_item_size = 1;\nclEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_item_size, &local_item_size, 0, NULL, NULL);\n\n\nHere, printing in the kernel is not allowed. Hence, how to ensure that all my 8 cores are running in parallel? \n\nExtra info (regarding my question): for kernel, i am passing input and and output array of 8X8 size as a buffer. According to workitem number, i am solving that row and saving the result in output buffer. and after that i am reading the result.\n\nIf i am running AMD platform SDK, where i add print statement in kernel by\n\n#pragma OPENCL EXTENSION cl_amd_printf : enable\n\n\nhence i can see clearly, if i am using 4 core machine, my first 4 cores are running parallel and then rest will run in parallel, which shows it is solving maximum 4 in parallel.\n\nBut, how can i see the same for my CL_DEVICE_TYPE_GPU?\n\nAny help/pointers/suggestions will be appreciated." ]
[ "parallel-processing", "opencl" ]
[ "How to do a proper setup for CLI of PHP", "On a windows machine, I know that I have to add \"c:\\path\\to\\php\" into the PATH environment variable. In order that PHP to work from CLI, the cmd window needs to be reopened.\n\nI know that this step is necessary only once, but I'm curios to know if there is a way to have PHP known to cmd window without reopening it." ]
[ "php", "cmd", "command-line-interface" ]
[ "Double Array display in jade", "I have this array setup: \n\nvar threads = [\"one\", \"two\", \"three\"]\nvar data = [\n [11,21,31],\n [12,22,32],\n [13,23,33],\n ]\n\n\nand I want it in html like this:\n\none two three\n11 21 31\n12 22 32\n12 23 33\n\n\nRight now I pass the array with nodejs (Express) to my layout.jade\n\n table\n thead\n each val in {threads}\n +tablethread(val)\n tbody\n -for (var i = 0; i < {data}.length; i++) {\n tr\n -for (var o = 0; o < {data[i]}.length; o++) {\n +tableval(data[i][o])\n\n\nCan someone help me to get the arrays rendered right?\n(the mixins are also defined on the top of layout.jade)\n\n mixin tableval(val)\n td= val\n mixin tablethread(name)\n th= name\n\n\nI get this error right now: SyntaxError: Unexpected token (146:22)" ]
[ "arrays", "node.js", "pug" ]
[ "HTML5 tags like(autofocus,required,type=\"email\" do not work in IE9", "I'm using the html 5 tags like header,section,nav,article,autofocus,required, input type=\"email\" and pattern.\n\ni noticed that autofocus,type=\"email\" and pattern do not work and i already use eric css reset and \n\n<!--[if lt IE 9]>\n<script src=\"http://html5shiv.googlecode.com/svn/trunk/html5.js\"></script>\n<![endif]-->" ]
[ "css", "html", "internet-explorer", "cross-browser" ]
[ "NHibernate: Criteria expression to retrieve non-null one-to-one associated class", "I have two classes that are associated with a one-to-one mapping:\n\n<class name=\"Employee\" table=\"Employees\">\n ...\n <one-to-one name=\"Address\" class=\"AddressInfo\">\n ...\n</class>\n\n\nI would like to use a criteria expression to get only Employees where the the associated Address class is not null, something like this (which I know doesn't work):\n\nIList employeesWithAddresses = sess.CreateCriteria(typeof(Employee))\n .Add( Expression.IsNotNull(\"Address\") )\n .List();\n\n\nI guess this is either a really difficult question or almost no one has tried to do this?" ]
[ "c#", "nhibernate", "orm" ]
[ "Is it possible to skip a save but not throw an error with a Rails validation", "The question sums it up. Is it possible to have a custom validation respond by simply not saving a record, rather than throwing an error? As far as I know, the only way to write a custom validation is by invoking an error like this:\n\ndef at_least_one_attribute_has_changed\n if no_changes?\n errors[:base] << I18n.t(\"activerecord.errors.messages.we_did_not_detect_any_changes\")\n end\nend\n\n\nPerhaps there's a gentler method? Some mystical skip_save call that I'm unfamiliar with?" ]
[ "ruby-on-rails", "validation", "save" ]
[ "Search a keyword from an array in an input string and Print them", "I have been doing this since almost past few days but still unable to get a required output.\nWell I have an array say\n wordlist[]={\"One\",\"Two\",\"Three\",\"Four\",\"Five\"};\nand then i take input from the user.\n\nString input=\"I have three no, four strings\";\n\n\nNow what i want to do is perform a search operation on the string to check for the words available in the array wordlist[];\nLike in the above example input string contains the words three and four that are present in the array.\nso it should be able to print those words from array available in the string, and if no words from the wordlist[] are available then it should print \"No Match Found\".\n\nHere's My code i'm struck with this.\nPlease\n\nimport java.util.regex.*;\nimport java.io.*;\nclass StringSearch{\n public static void main(String ...v)throws IOException{\n BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));\n String wordlist[]={\"one\",\"two\",\"three\",\"four\",\"five\"};\n String input=cin.readLine();\n int i,j;\n boolean found;\n Pattern pat;\n Matcher mat;\n Pattern spliter=Pattern.compile(\"[ ,.!]\");\n String ip[]=spliter.split(input);\n System.out.println(ip[2]);\n for(i=0; i<wordlist.length;i++){\n for(j=0;j<ip.length;j++){\n pat=Pattern.compile(\"\\b\"+ip[j]+\"\\b\");\n mat=pat.matcher(wordlist[i]);\n if(){\n // No Idea What to write here\n }\n }\n }\n\n\n }\n}" ]
[ "java", "regex", "string", "search", "string-search" ]
[ "all the names are not fetching from arraylist", "Json file show on arraylist, I want to show all the names from the arraylist from the json file.\n\ntry { \n JSONArray root = new JSONArray(json);\n\n for (int i = 0; i < root.length(); i++) \n {\n JSONObject att = (JSONObject) root.getJSONObject(i);\n name = att.getString(\"nm\");\n list.add(name);\n\n }\n for(int i = 0; i<root.length(); i++){\n Log.i(\"name\", name);\n }\n}catch (JSONException e) {\n e.printStackTrace();\n}" ]
[ "json", "arraylist" ]
[ "QtUdpSocket still listening on port after closing MainWindow", "I have a QWidget (udpWidget) instantiated in a QMainWindow (udpMainWindow). I am creating udpMainWindow from another QMainWindow\n\nThere is some ValueError exception occurring (which I am going to fix).\nWhen I close the window of udpMainWindow, I can no longer do a bind to the port until I close the entire program. I understand I need to fix the exception that is occurring, however I don't understand why after closing the udpMainWindow that the resource (0.0.0.0:12345) is still listening.\n\nclass udpWidget(QtGui.QWidget):\n def __init__(self, parent):\n super(udpWidget, self).__init__(parent)\n self.listenSocket=QtNetwork.QtUdpSocket()\n ...\n\n def do_something(self) \n self.listenSocket.bind(12345)\n ...\n #Some Exception Occurs\n\n self.listenSocket.close()\n\n def destroy(self, destroyWindow, destroySubWindows):\n self.listenSocket.close()\n\n def closeEvent(self, event):\n self.listenSocket.close()\n event.accept()\n\nclass udpMainWindow(QtGui.QMainWindow):\n def __init__(self, parent):\n super(udpMainWindow, self).__init__(parent)\n myUdpWidget=udpWidget(self)\n myButton.clicked.connect(myUdpWidget.do_something)\n\n\nEdit 1:\n\nHere is a fully functional example. When you start listening on the \"UDP Main Window\" using the PushButton, then close using the 'X' button, the port doesn't free up. Then when you attempt to listen with the \"Main Main Window\" it fails to bind because it is still in use.\n\nSteps to reproduce problem:\n\n\nRun Program\nClick \"Listen to port 12345\" on \"UDP Main Window\"\n*Click \"Listen to port 12345\" on \"Main Main Window\" *(this just confirms that the port is busy, not necessary to reproduce problem.\nClick 'x' to close \"UDP Main Window\"\nClick \"Listen to port 12345\" on \"Main Main Window\" This will now fail to connect.\n\n\nThe Code\n\nfrom PySide import QtGui, QtCore, QtNetwork\n\nclass udpWidget(QtGui.QWidget):\n def __init__(self, parent):\n super(udpWidget, self).__init__(parent)\n self.listenSocket=QtNetwork.QUdpSocket()\n #bindResult=self.listenSocket.bind(12345)\n\n @QtCore.Slot()\n def start_listening(self):\n bindResult=self.listenSocket.bind(12345)\n print \"binding: {}\".format(bindResult)\n raise ValueError(\"invalid Number\") #Simulate exception occuring.\n self.listenSocket.close()\n\n\n def destroy(self, destroyWindow, destroySubWindows):\n print \"udpWidget.destroy called\"\n self.listenSocket.close()\n\n def closeEvent(self, event):\n print \"udpWidget.closeEvent called\"\n self.listenSocket.close()\n event.accept()\n\nclass udpMainWindow(QtGui.QMainWindow):\n def __init__(self, parent):\n super(udpMainWindow, self).__init__(parent)\n self.setWindowTitle(\"UDP Main Window\")\n self.myUdpWidget=udpWidget(self)\n btn = QtGui.QPushButton(\"Listen to port 12345\")\n btn.clicked.connect(self.myUdpWidget.start_listening)\n self.setCentralWidget(btn)\n\n def closeEvent(self, event):\n print \"udpMainWindow.closeEvent called\"\n #self.myUdpWidget.listenSocket.close()\n\n\nclass mainMainWindow(QtGui.QMainWindow):\n def __init__(self, parent):\n super(mainMainWindow, self).__init__(parent)\n self.setWindowTitle(\"Main Main Window\")\n myUdpMainWindow = udpMainWindow(self)\n myUdpMainWindow.show()\n self.listenSocket=QtNetwork.QUdpSocket()\n btn = QtGui.QPushButton(\"Listen to port 12345\")\n btn.clicked.connect(self.connect_udp)\n self.setCentralWidget(btn)\n\n @QtCore.Slot()\n def connect_udp(self):\n bindResult=self.listenSocket.bind(12345)\n print \"binding: {}\".format(bindResult)\n\n\n\nif __name__==\"__main__\":\n myApp = QtGui.QApplication([])\n myMainMainWindow = mainMainWindow(None)\n myMainMainWindow.show()\n myApp.exec_()" ]
[ "python", "python-2.7", "pyside" ]
[ "Sliding image 4x4 with GridLayout", "I want ask about sliding image puzzle.\nbelow is code for slide to left or right.\nbut I have a problem.\n\n if (i + 1 < imageviews.size) {\n if (imageviews[i + 1]!!.drawable == null) {\n mGridLayout.removeView(imageviews[i + 1])\n mGridLayout.addView(imageviews[i + 1], i)\n val temp = imageviews[i + 1]\n imageviews[i + 1] = imageviews[i]\n imageviews[i] = temp\n }\n }\n if (i - 1 >= 0) {\n if (imageviews[i - 1]!!.drawable == null) {\n mGridLayout.removeView(imageviews[i - 1])\n mGridLayout.addView(imageviews[i - 1], i)\n val temp = imageviews[i - 1]\n imageviews[i - 1] = imageviews[i]\n imageviews[i] = temp\n }\n }\n\n\nbefore do anything:" ]
[ "android", "arrays", "android-imageview", "android-gridlayout" ]
[ "Uncaught Error in try catch block", "I am trying to write \"universal\" function to execute SQL query and return JSON and handle error within. And during process there is something I don't understand - why try catch block doesn't handle error. (Later I will improve logic - question is NOT about that, but purely about error handling).\n\nHere is my code:\n\npublic\nfunction sqlToJSON($query, $type = array(), $params = array())\n{\n try {\n $data = array();\n $stmt = $this->mysqli->prepare($query);\n if (count($type) > 0 && count($params) > 0) {\n call_user_func_array(array($stmt, \"bind_param\"), array_merge(array($type), $params));\n }\n $stmt->execute();\n $result = $stmt->get_result();\n while ($row = $result->fetch_assoc()) {\n $data[] = $row;\n }\n $stmt->free_result();\n $stmt->close();\n return array('result' => 'success', 'error' => null, 'data' => $data);\n } catch (Exception $e) {\n $this->sqlError = 'Caught exception: ' . $e->getMessage();\n return array('result' => 'failed', 'error' => $e->getMessage(), 'data' => null);\n }\n}\n\n\nHow I call this function:\n\n $q = 'INSERT INTO receivers (receiver_name, owner) VALUES (UPPER(?), ?)';\n $params = array(&$receiverName, &$clientEmail);\n $this->sqlToJSON($q, 'ss', $params);\n\n\nThis gives following expected error:\n\nUncaught Error: Call to a member function fetch_assoc() on boolean in ...\n\n\nWhat I don't understand why catch block is not executed in this case?" ]
[ "php", "mysql" ]
[ "Material.io web with webpack error \"Can't find stylesheet to import\"", "I tried using matrial.io with webpack, just as described in material.io's getting started with the following configurations:\n\nwebpack.config.js --> exactly like example\n\nconst autoprefixer = require('autoprefixer');\n\nmodule.exports = {\n entry: ['./app.scss'],\n mode: 'development',\n module: {\n rules: [\n {\n test: /\\.scss$/,\n use: [\n {\n loader: 'file-loader',\n options: {\n name: 'bundle.css',\n },\n },\n {loader: 'extract-loader'},\n {loader: 'css-loader'},\n {\n loader: 'postcss-loader',\n options: {\n plugins: () => [autoprefixer()]\n }\n },\n {\n loader: 'sass-loader',\n options: {\n sassOptions: {\n implementation: require('sass'),\n includePaths: ['./node_modules'],\n },\n },\n }\n ],\n },\n ],\n },\n};\n\n\napp.scss --> exactly like the example\n\n@use \"~@material/ripple\";\n\n.test {\n @include ripple.surface;\n @include ripple.radius-bounded;\n @include ripple.states;\n}\n\n\npackage.json\n\n{\n \"private\": true,\n \"scripts\": {\n \"build\": \"webpack --config=webpack.config.js\"\n },\n \"devDependencies\": {\n \"autoprefixer\": \"^9.7.4\",\n \"css-loader\": \"^3.4.2\",\n \"extract-loader\": \"^5.0.1\",\n \"file-loader\": \"^6.0.0\",\n \"postcss-loader\": \"^3.0.0\",\n \"sass\": \"^1.15.2\",\n \"sass-loader\": \"^7.1.0\",\n \"webpack\": \"^4.42.0\",\n \"webpack-cli\": \"^3.3.11\"\n },\n \"dependencies\": {\n \"material-components-web\": \"^4.0.0\"\n }\n}\n\n\nHowever, when I run npm run build I get the following error:\n\nERROR in ./app.scss\nModule build failed (from ./node_modules/sass-loader/dist/cjs.js):\n\n@use \"~@material/ripple\";\n^\n Can't find stylesheet to import.\n ╷\n1 │ @use \"~@material/ripple\";\n │ ^^^^^^^^^^^^^^^^^^^^^^^^\n ╵\n stdin 1:1 root stylesheet\n in /path-to-file/app.scss (line 1, column 1)\n @ multi ./app.scss main[0]\n\n\nI also tried gulp but I was getting the same error.\n\nAny idea how I can make it work?\n\nI also created a repo for that. You can clone:\nhttps://github.com/nazari-dev/material.io" ]
[ "webpack", "sass", "material-components-web" ]
[ "How do you make a function that divides fractions into simplest form python", "I am taking a class and i'm confused. It would really help if you could guide me through the proccess of this and tell me what I am doing wrong. I have an error that has to do with the parentheses since theres nothing in them. I am a newbie so i'm sorry.\n\ndef FractionDivider(a,b,c,d):\n n = ()\n d = ()\n n2 = ()\n d2 = ()\n print int(float(n)/d), int(float(n2)/d2)\n return float (n)/d / (n2)/d2" ]
[ "python", "python-2.7", "parentheses" ]
[ "What is the Maybe type and how does it work?", "I am just starting to program in Haskell, and I came across the following definition:\n\ncalculate :: Float -> Float -> Maybe Float" ]
[ "haskell", "maybe" ]
[ "Receiving ssh-key warning inside a Visual-Studio-Code dev-container when pulling/pushing to private Github repo", "I have been developing inside a container with visual-studio-code on Windows 10 with the Remote - Containers plugin. I used this guide to setup my ssh-agent and add my git credentials from windows 10 to the environment inside the container. But when I try to push or pull from a private repo github in that environment I receive the following error.\nagent key RSA SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX+64 returned incorrect signature type\nThis does not seem to affect my ability to access my private repo on github, but the warning still seems like something I should be taking seriously. I am still able to use git on windows 10 without getting any errors. This only occurs if I use visual studio's remote-containers plugin with my Dockerfile, otherwise I'm not able to access the private repo at all due to my git credentials not being added to the container.\nI've looked at some other SO questions here and here and tried the regenerating my ssh-key using openssh on the windows side which did not seem to fix the problem. I've been using node:12.18-alpine3.12 as my base image and I've been installing openssh in my Dockerfile using\napk update && apk upgrade && apk add --no-cache openssh\nso I'm assuming openssh should be a recent enough version.\nI think this might be a plugin issue with vscode? I don't really know." ]
[ "windows", "git", "docker", "visual-studio-code", "ssh-keys" ]
[ "How to send localStorage keys from Chrome Extension to localhost?", "Hello im creating a chrome extension, and I save data (username, avtarUrl etc) in localStorage but i want to share/send this data in the localStorage of my localhost too.\n\nHow can i do that ?" ]
[ "javascript", "reactjs", "google-chrome-extension" ]
[ "jquery issue calling on a class for a hover over plug in", "This script is supposed to have text move up from below the image when the users mouse hovers over the image. I do not believe that the jQuery is calling on the class properly and that is why it is not working. I have included code from the jquery plugin as well as the section of html that is supposed to work with this plug in. If you have any questions for me please do not hesitate to ask I will be waiting for a response, I just started using jQuery today and am enjoying it when things work, but have been searching for an answer for some time now and am just baffled with why I can not figure this out. \n\n <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js\"></script>\n <script>\n\n $(function(){\n $(' #d1').contenthover({\n overlay_width:300,\n overlay_height:150,\n effect:'slide',\n slide_direction:'bottom',\n overlay_x_position:'center',\n overlay_y_position:'bottom',\n overlay_background:'#000',\n overlay_opacity:0.8\n });\n });\n\n </script>\n\n\n\n\n <section id=\"s-explore\">\n\n <div class=\"pagebreak\"><span>The Lifestyle</span> <i class=\"down\"><</i></div>\n\n <div class=\"wrapper layout\">\n\n <div class=\"col\">\n <div class=\"media\">\n <img id=\"d1\" src=\"images/main.png\" />\n <div class=\"contenthover\">\n <h3>Lorem ipsum dolor</h3>\n <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames</p>\n <p><a href=\"#\" class=\"mybutton\">Lorem ipsum</a></p>\n </div>\n </div>\n\n <div class=\"body\">\n <h1>Vestibulum</h1>\n <h2>quis<br />Vestibulum</h2>\n </div>\n </div>\n\n\n\n\nWorking code:\n\n <!DOCTYPE HTML>\n <html>\n <head>\n\n <link href=\"hover-content-style.css\" rel=\"stylesheet\" type=\"text/css\" />\n\n <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js\"></script>\n\n <script>\n\n $(function(){\n\n\n $('#d1').contenthover({\n overlay_width:300,\n overlay_height:150,\n effect:'slide',\n slide_direction:'bottom',\n overlay_x_position:'center',\n overlay_y_position:'bottom',\n overlay_background:'#000',\n overlay_opacity:0.8\n });\n\n });\n\n </script>\n\n <title>JQuery slide on top of image - animation</title>\n\n </head>\n\n <body>\n <img id=\"d1\" src=\"images/vito_red.png\" width=\"318\" height=\"269\" />\n <div class=\"contenthover\">\n <h3>Lorem ipsum dolor</h3>\n <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum pulvinar ante quis augue lobortis volutpat. </p>\n <p><a href=\"#\" class=\"mybutton\">Lorem ipsum</a></p>\n </div>\n\n <script src=\"hoverslide.js\"></script>\n\n </body>" ]
[ "jquery", "html", "css" ]
[ "Dynamically calculate padding-left", "Here's a sample division:\n\n<div style=\"padding:0 0 0 30px; background:url(http://www.google.com/help/hc/images/sidewiki_157505_comment_bubble.gif) left center no-repeat;\">some text</div>\n\n\nI wonder how I can calculate the padding-left:30px dynamically so that any icon I choose the padding-left value changes according to the image width.\n\nAny help is appreciated!" ]
[ "javascript" ]
[ "Integrating Android project with CircleCi, only test against one build variant with connectedAndroidTest command?", "I'm battling against CircleCi at the moment, so many issues as I am new to it. Right now my app takes 20 minutes to build, because it's builds every productFlavour we have. In my circle.yml file I have the following command:\n\n- ./gradlew --stacktrace connectedAndroidTest:\n timeout: 1200\n\n\nThe full circle.yml file starts the emulator and does a clean build of one of our productFlavours, called test. I can easily ensure only this productFlavour is built by running the following command:\n\n - ./gradlew clean assembleTestDebug -PdisablePreDex\n\n\nThis takes about 1 minute to build. My issue is now with the connectedAndroidTest command which then goes on to build all of our build variants with all build types (release and debug), then runs our test against them, this is very time consuming. Hence why our build times take 20 minutes.\n\nIs there a way I can tell the connectedAndroidTest command in my circle.yml file to only run against TestDebug?\n\nI tried adding the build variant to the end (connectedAndroidTestTestDebug) but this caused the following exception on CircleCi:\n\n'connectedAndroidTestTestDebug' not found in root project 'my_project'.\n\n\nWould appreciate any advice on the matter, from my experience, CircleCi has been a big pain to set up, I'm in contact with their support staff but they are in different timezones which is not ideal so progress in slow. I'm hoping someone who has set up an Android project on CircleCi with unit tests has figured out a way to only run them against one productFlavour/Build variant.\n\nThanks in advance for any advice!" ]
[ "android", "gradle", "continuous-integration", "circleci" ]
[ "Toggle child nodes on checking checkboxes", "I am making this recursive listview where I am trying to show/hide the child components if the parent checkbox is toggled. I did something wrong here that I can't make it work anymore. The problem seems to be with the argument of onClick() function in the input tag. I am new in React and can't find out how to fix this problem. Can I get some help on how to do that?\n\nexport default class MyList extends Component {\n constructor(props) {\n super(props);\n this.state = {\n visible: true\n };\n }\n\n toggle = () => {\n this.setState(\n {visible: !this.state.visible}\n );\n };\n\n render() {\n var style;\n if (!this.state.visible) {\n style = {display: \"none\"};\n }\n\n var node = this.props.data;\n return(\n <div>\n <ul style={style}>\n {\n Object.keys(this.props.data).map(function(key){\n return (\n <li key={key}><input type=\"checkbox\" onClick={MyList.toggle}/>\n <label>{key}</label> :\n {typeof node[key] === 'object' ? <MyList data = {node[key]} /> : node[key]}\n </li>\n );\n })\n }\n </ul>\n </div>\n );\n }\n}" ]
[ "javascript", "reactjs" ]
[ "Getting records from database and displaying one by one?", "I am using an Access database and I have an interface where users can delete and add records.\n\nBut I also have another aspect of my application where I need to display records one by one by binding them to a repeater, and for this I use a dataview and rowfilter. Originally I used the id field to indicate which row to display, incrementing it by one each time, but since users are able to delete records it doesn't work anymore since ids can jump and don't increment by one.\n\nIs there anyway for me to do something that is like dbDataView.table.row(i) and increment i each time so that I can count through the records and not the ids?" ]
[ "asp.net", "ms-access", "data-binding", "dataset", "dataview" ]
[ "Get desired output in textbox from serial port scale", "i have develop application for getting weight from weigh Bridge machine using C#.Net. i am trying lot of ways but, doesn't read correct data format weight from weigh bridge machine. i am getting output like \n\n\n 00000001Kg00000001B00000001B00000001B00000001B00000001B00000001B00000001B\n\n\ncontinuously get from serial port.i want to get weight from weigh bridge machine my code is listed below:\n\n private void Form1_Load(object sender, EventArgs e)\n {\n string[] portNames = SerialPort.GetPortNames(); \n foreach (var portName in portNames)\n {\n comboBox1.Items.Add(portName); \n }\n comboBox1.SelectedIndex = 0; \n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n if (_serialPort != null && _serialPort.IsOpen)\n _serialPort.Close();\n if (_serialPort != null)\n _serialPort.Dispose();\n\n _serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);\n _serialPort.DataReceived += SerialPortOnDataReceived;\n _serialPort.Open();\n textBox1.Text = \"Listening on \" + _serialPort.PortName + \"...\\r\\n\"; \n }\n private delegate void Closure();\n private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)\n {\n if (InvokeRequired)\n BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));\n else\n {\n int dataLength = _serialPort.BytesToRead;\n byte[] data = new byte[dataLength];\n int nbrDataRead = _serialPort.Read(data, 0, dataLength);\n if (nbrDataRead == 0)\n return;\n string str = System.Text.Encoding.UTF8.GetString(data);\n textBox1.Text += str.ToString();\n }\n }\n\n\nhow could i get right weight for save it into my database? in Order to get the right weight it must be like \n\n\n 00000001Kg\n\n\nat real time and change itself according to weigh scale weight." ]
[ "c#", ".net" ]
[ "CanCan issues with Rails", "I am having a issue with an owner on my rails application not being able to access my Map controller create and show methods using the CanCanCan gem for permissions control.\n\nHere is my ability model with the current config:\n\nclass Ability\ninclude CanCan::Ability\n\ndef initialize(user)\n\n if user.role.name == 'owner'\n\n can :manage, Map, venue_id: user.company.venues.pluck(:id)\n\n end\nend\n\n\nOutput from user.company.venues.pluck(:id):\n\n Company Load (0.3ms) SELECT `companies`.* FROM `companies` WHERE `companies`.`id` = 4 LIMIT 1\n (0.4ms) SELECT `venues`.`id` FROM `venues` WHERE `venues`.`company_id` = 4\n => [1] \n\n\nHere is my Maps Controller Code:\n\nclass MapsController < ApplicationController\n before_action :authenticate_user!\n respond_to :html, :json\n load_and_authorize_resource\n\n def index\n respond_with(@maps)\n end\n\n def new\n respond_with(@maps)\n end\n\n def create\n @map = Map.create(map_params)\n if @map.save\n respond_to do |format|\n flash[:notice] = t('floors.created')\n format.json\n end\n else\n flash[:alert] = t('floors.error')\n end\n end\n\n def show\n respond_with(@map)\n end\n\n def edit\n\n end\n\n def update\n\n end\n\n def map_params\n params.require(:map).permit(:alias, :venue_id, :map)\n end\n\nend\n\n\nMaps belong to venues and has a venue_id. I can get Maps in the Maps index partial on my venue page:\n\n\nBut when I try to create a Map or go to the Map show page I get a CanCan access denied error:\n\n\nAny ideas on why CanCanCan would allow me to view the Maps index but get access denied when creating or viewing the Map show controller." ]
[ "ruby-on-rails", "ruby", "cancancan" ]
[ "Offer to change the default search engine for the omnibar", "I'm looking to offer the user (inside my Chrome Extension) the option to change their Omnibox default search engine. \n\nSadly, I've been unable to find any documentation on how to do something like this. Has anyone does this before successfully?" ]
[ "google-chrome-extension", "omnibox" ]
[ "Why the UI thread is getting blocked?", "In the below code I am trying to run a thread when a button is clicked. In the button listener I create a new thread and run it...but at run time, when the button is pressed, the button itself freezes and the app does not respond and I receive ANR dialog. Moreover, when the socket is connected successfully even the TexView \n\nmtvStatus.setText(\"RFC-SOCKET CONNECTED\");\n\n\ndisplays nothing.\n\nPlease let me know why this is happening.\n\nbutton listener:\n\nthis.mbtnConnect.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n BluetoothSocket rfcSocket = mSPPCtrl.rfcConnect();\n if (rfcSocket.isConnected()) {\n mtvStatus.setText(\"RFC-SOCKET CONNECTED\");\n\n Thread rx = new Thread(new RxRun(rfcSocket));\n rx.run();\n\n } else {\n mtvStatus.setText(\"RFC-SOCKET NOT CONNECTED\");\n }\n\n }\n });\n\n\nrunnable class\n\nprivate class RxRun implements Runnable {\n\n private BluetoothSocket mRFCSocket = null;\n private OutputStream mRFCOS = null;\n private InputStream mRFCIS = null;\n\n public RxRun(BluetoothSocket rfcSocket) {\n this.mRFCSocket = rfcSocket;\n\n try {\n this.mRFCOS = rfcSocket.getOutputStream();\n } catch (IOException e) {\n e.printStackTrace();\n }\n try {\n this.mRFCIS = rfcSocket.getInputStream();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void run() {\n try {\n this.mRFCOS.write(DIRON.getBytes());\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n while (this.mRFCSocket.isConnected()) {\n try {\n int readBytes = this.mRFCIS.read(new byte[5120]);\n Log.d(TAG, CSubTag.bullet(\"RxRun\", \"readBytes:\" + readBytes));\n //mtvRx.setText(\"\"+readBytes);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n }\n}" ]
[ "java", "android", "multithreading", "ui-thread" ]
[ "How to split observations in Stata", "I've been trying to make the following transformation in my Stata dataset:\n\nNumber, Cluster and Rating are my three variables. All values are strings.\n\nDo you have any Stata-specific suggestions?\n\nThank you!" ]
[ "split", "stata" ]
[ "Generate a random string with n digits number (except 0 at begin) in Ruby", "Someone can teach me how to generate a random string with n digits number.\n\nEx: n=3, myString = \"001\" or \"002\" or ... \"999\" (except number 0 at begin)\n\np/s: I am using Ruby 1.8.7" ]
[ "ruby-on-rails", "ruby" ]
[ "In Android, how can I programmatically set an AutoCompleteTextView at the start of an activity? (Java)", "I'm using the AutoCompleteTextView as an ExposedDropdownMenu per the Google Material Guidelines. First I would like to state that I am able to successfully set the AutoCompleteTextView's text value programmatically by waiting ~300ms after the onCreate() function is called, with the proper values inside of the dropdown suggestion menu. However, when I set the AutoCompleteTextView's text programmatically beforehand (e.g. inside of the onCreate() w/o delay), a weird issue arises where the dropdown menu of the AutoCompleteTextView is empty for some reason (and no it's not because of filtering).\n\nNOTE: I have modified this code from my original source code to make it easier to understand and less complex. It has not been tested and may have errors.\n\nprivate String[] VALUES = new String[]{\"val1\", \"val2\", \"val3\", \"val4\"};\n\nprotected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n ArrayAdapter<String> adapter = new ArrayAdapter<>(mainActivity.getApplicationContext(), R.layout.dropdown_menu_popup_item, VALUES);\n\n AutoCompleteTextView autoCompleteTextView = findViewById(R.id.auto_complete_text_view);\n autoCompleteTextView.setAdapter(adapter);\n autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {\n //Do something here when item is selected\n });\n\n //Here I want to set the text value to something in onCreate()\n //without having to wait a random amount of time\n autoCompleteTextView.setText(\"val3\", false);\n}\n\n\nThis results in the AutoCompleteTextView's dropdown menu only containing \"val3\" and no other values from the adapter. At first glance it looks like it's filtering but it's not (note that the filter boolean is set to false). The list only contains \"val3\". However if I wait ~300ms or so, then it works as expected.\n\nprivate String[] VALUES = new String[]{\"val1\", \"val2\", \"val3\", \"val4\"};\n\nprotected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n ArrayAdapter<String> adapter = new ArrayAdapter<>(mainActivity.getApplicationContext(), R.layout.dropdown_menu_popup_item, VALUES);\n\n AutoCompleteTextView autoCompleteTextView = findViewById(R.id.auto_complete_text_view);\n autoCompleteTextView.setAdapter(adapter);\n autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {\n //Do something here when item is selected\n });\n\n new AsyncTaskThatWaits300ms().execute();\n}\n\nprivate static class WaitForAutoCompleteTextViews extends AsyncTask<String, Void, Boolean> {\n\n private ProgressDialog dialog = new ProgressDialog(MainActivity.this);\n\n @Override\n protected void onPreExecute() {\n if (dialog != null) {\n this.dialog.setMessage(\"Waiting 300ms...\");\n this.dialog.show();\n }\n }\n\n @Override\n protected Boolean doInBackground(final String... args) {\n try {\n //Do something\n Thread.sleep(300);\n return true;\n } catch (Exception e) {\n Log.e(TAG, \"doInBackground error: \", e);\n return false;\n }\n }\n\n @Override\n protected void onPostExecute(final Boolean success) {\n if (dialog != null) {\n if (dialog.isShowing()) {\n dialog.dismiss();\n }\n }\n //If I set it here, the text will display with the correct values in the dropdown list, instead of only \"val3\".\n autoCompleteTextView.setText(\"val3\", false);\n }\n}" ]
[ "android", "autocompletetextview" ]
[ "Sql select statement not working WPF", "I'm working on a WPF where i have an sql statement to connect to the database.The statement is to search for First_Quater which it does but when i change to Second_Quater (which is not in the data base yet) It will give me the First_quater figuers. I can not get it to add just the First_Quater up in the column.\n\nI have tryed so much and searched the internet but I'm still at a loss.\nThank you for your help.\n\nSqlConnection con = new SqlConnection(\"Data Source=; Initial Catalog=; Integrated Security=True; Trusted_Connection=yes\");\n con.Open();\n\n String comboquery = (@\"SELECT * FROM [taxi_comm] WHERE First_Quarter = '\" + checkedListBox1.SelectedItem + \"'\");\n SqlCommand cmd = new SqlCommand(comboquery, con);\n SqlDataReader dr = cmd.ExecuteReader();\n\n\n\n\n double sum = 0;\n for (int i = 0; i < gvDisplay.Rows.Count; ++i)\n {\n\n\n switch (checkedListBox1.SelectedItem.ToString().Trim())\n {\n case \"First Quarter\":\n\n foreach (string s in checkedListBox1.CheckedItems)\n {\n\n sum += Convert.ToInt32(gvDisplay.Rows[i].Cells[10].Value);\n txtTotalGST.Text = sum.ToString(); \n }\n MessageBox.Show(\"Its feb\");\n break;\n case \"Second Quarter\":\n\n foreach (string st in checkedListBox1.CheckedItems)\n {\n sum += Convert.ToInt32(gvDisplay.Rows[i].Cells[10].Value);\n txtTotalGST.Text = sum.ToString();\n MessageBox.Show(\"You have reached the second quarter\");\n }\n\n break;" ]
[ "c#", "sql", "wpf" ]