texts
sequence | tags
sequence |
---|---|
[
"Javascript not loading in browser",
"Im a beginner programmer and im experiencing some issues loading javascript code on my browser. Are there any errors in my code? or could it be an issue with my computer. If it helps: im using OS Sierra, Google Chrome, Atom editor. \n\nThanks!!\n\nHTML code:\n\n<!DOCTYPE html>\n\n<html>\n <head>\n\n </head>\n\n <body>\n <title>A* Algorithm</title>\n\n <h1>This is the A* pathfinding algorithm</h1>\n <script src =\"astar.js\"> </script>\n\n </body>\n\n\n</html>\n\n\nJavascript code:\n\nvar cols = 5;\nvar rows = 5;\nvar grid = new Array(cols);\n\nfunction setup() {\n createCanvas(400, 400);\n console.log(\"A*\");\n\n for (var i = 0; i < cols; i++) {\n grid[i] = new Array(rows);\n }\n\n for (var i = 0; i < cols; i++) {\n for (var j = 0; i < row; j++) {\n grid[i][j] = new Spot();\n }\n }\n\n console.log(grid);\n}\n\nfunction draw () {\n background(0);\n}"
] | [
"javascript",
"html"
] |
[
"Run R script in Django",
"I'm building a site which contains lot of optimization work and all those work are done in R language. I'm building whole site on Django. Is there any way I can connect both R code and Django or what should I do here ?\nI tried installing rpy2 which works fine in python but in Django I'm getting a error:\n File "F:\\django-app\\restapi\\views.py", line 25, in <module>\n import rpy2.robjects as robjects\n File "F:\\django-app\\venv\\lib\\site-packages\\rpy2\\robjects\\__init__.py", line 19, in <module>\n from rpy2.robjects.robject import RObjectMixin, RObject\n File "F:\\django-app\\venv\\lib\\site-packages\\rpy2\\robjects\\robject.py", line 6, in <module>\n rpy2.rinterface.initr()\n File "F:\\django-app\\venv\\lib\\site-packages\\rpy2\\rinterface\\__init__.py", line 208, in initr\n initr(r_preservehash=r_preservehash)\n RuntimeError: R_USER not defined.\n\nwhat's the best option to do this. Is there any thing I'm missing here?"
] | [
"python",
"r",
"python-3.x",
"django",
"django-views"
] |
[
"Problems with JPanel layouting",
"My GUI looks like this: \n\n\n\nmy gui\n\nand should look like this: \n\n\nsolution\nand this is my code for layout:\n\npublic void initComponents(){\n\n setTitle(\"GUI-Design\");\n setSize(800, 600);\n\n setLayout(new BorderLayout());\n top = new JPanel();\n mid = new JPanel();\n bottom = new JPanel();\n add(top, BorderLayout.NORTH);\n add(mid, BorderLayout.CENTER);\n add(bottom, BorderLayout.SOUTH);\n\n\n //TOP Start\n top.setLayout(new BorderLayout());\n JLabel label = new JLabel(\"Informatik/Technik\", JLabel.CENTER);\n ImageIcon img = new ImageIcon(this.getClass().getResource(\"/images/Logo.jpg\"));\n JLabel image = new JLabel(\"\",img, JLabel.CENTER);\n top.setBackground(Color.WHITE);\n top.add(label, BorderLayout.WEST);\n top.add(image, BorderLayout.EAST);\n //TOP END\n //MID Start\n mid.setLayout(new GridBagLayout());\n GridBagConstraints c = new GridBagConstraints();\n c.fill = GridBagConstraints.HORIZONTAL;\n......\n\n}\n\n\nhow can I take the huge gap away in the center and in the bottum ?"
] | [
"java",
"swing",
"layout",
"jframe",
"jpanel"
] |
[
"How do I send data into a Code Igniter Controller index method?",
"I tried to encode the ID of a journal in the URL of my Code Igniter application and the retrieve it in my controller. My end goal is to access the page http://mysite.com/journal/3 and get to access a page containing details about the journal with ID 3.\n\nIn my journal.php controller file, I have\n\n<?php\nif (!defined('BASEPATH'))\n exit('No direct script access allowed');\n\nclass Journal extends Controller {\n public function index($journalId) {\n $data['journalId'] = $journalId;\n $this->view->load('journalPage', $data);\n }\n}\n?>\n\n\nIn my journalPage.php view file, I have\n\nThis event has ID <?= $journalId ?>.\n\n\nI wrote this rule in my routes.php file.\n\n$route['journal/(:num)'] = 'journal/$1';\n\n\nHere is the .htaccess file in my html public folder.\n\n<IfModule mod_rewrite.c>\nOptions +FollowSymLinks\nRewriteEngine on\nRewriteBase /\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^(.*)$ index.php?$1 [QSA,L]\n</IfModule>\n\n\nHowever, when I go to mysite.com/journal/3, I get a 404 error. Why?"
] | [
"codeigniter",
"codeigniter-url"
] |
[
"multiple specific ips to alternate domain",
"I am NOOB. I am attempting to redirect specific IP addresses using htaccess to a different domain. Those ip addresses are of people copying what I type to describe stuff and put it on their site within a few hours. I want them to just see static site B while everyone else sees dynamic site A.\nThe code below is redirecting to cat.com which I used earlier as a test to redirect, which seemed to be working. But then I changed it to dog.com but but it is still redirecting me to cat.com. I had put a # symbol in front of the old rewriterule so it should not be in play anymore. I also checked the redirects in cpanel. This is a subdomain I am working with, not the main domain on the account. This htaccess file added only 68.14.155.149 to the redirects section nothing else.\n\n<Files 403.shtml>\norder allow,deny\nallow from all\n</Files>\n# -- MOD: Forbid Cross Site Scripting in query\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteCond %{QUERY_STRING} ^.*(allow_url_include|auto_prepend_file).* [NC]\nRewriteRule ^(.*)$ - [F,L]\n</IfModule>\n# -- END MOD: Forbid Cross Site Scripting in query\ndeny from 180.76.5.0/24\ndeny from 198.23.76.220\n\nOptions +FollowSymLinks\n\nRewriteEngine On\nRewriteBase /\nRewriteCond %{REMOTE_ADDR} ^38\\.100\\.121\\.65$ [OR]\nRewriteCond %{REMOTE_ADDR} ^206\\.141\\.173\\.244$ [OR]\nRewriteCond %{REMOTE_ADDR} ^68\\.14\\.15\\0.24$\nRewriteRule ^(.*)$ http://www.dog.com/$1 [L,R=301]\n#RewriteRule ^(.*)$ http://www.cat.com/$1 [L,R=301]\n\n<IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteBase /\n\nRewriteRule ^About\\-us\\.php$ About\\-Me\\.php [R=301,NE,QSA,L]\n</IfModule>\n#RVS END REDIRECT PAGE"
] | [
".htaccess",
"redirect",
"ip"
] |
[
"Add prefix to each element of array of strings",
"Is there a quick way to add a string prefix to each element in array of strings?"
] | [
"objective-c"
] |
[
"Getting started Java with Linux OS",
"I know this is very basic question, but these days I have done all my Java programs on Windows OS. But now I like to go with Linux.\nHow JDK and all be installed in Linux OS?\n\nI am using Ubuntu 10.04 LTS."
] | [
"java",
"linux"
] |
[
"Static object of class?",
"I am actually not really aware if you can declare a class and then use a static instance it among several objects of the same class. More specifically:\n\nclass State {\n public:\n State();\n static CustomNumberDist normal_dist;\n private:\n int id; \n};\n\n\nSo every instance of State should contain the same instance of CustomNumberDist. I compiles but I am wondering if it is valid or I may run into problems later on."
] | [
"c++"
] |
[
"mysql sleeping processes",
"I have a PHP script that connects to MySQL does some operations and ends.\n\nAt the end there is a mysqli_close($link); statement.\n\nStill I have sleeping processes for that user in MySQL process-list and can't figure out where from?\n\nAs far as I know as soon as the PHP script ends it should close the connection even without a mysqli_close at the end (but there is one).\n\nSo where are those sleeping processes from on that user?\n\nIf I restart httpd they all die."
] | [
"php",
"mysql"
] |
[
"Setting a value via an interface in go",
"In the following example, I'd like to call the setvalue() of the b object via an interface procedure.\n\nI'd like to use an interface because I need to insert different kinds of objects in a list, possibly very big, each obeying a common interface.\n\nHowever the compiler complains with the following error :\n\n\n ./tests.go:27:6: cannot use newbox(3) (type box) as type container in assignment:\n box does not implement container (setValue method has pointer receiver)\n\n\nProbably I have to define the interface differently, but how?\n\nI know I could transform the setvalue procedure in a function, returning the updated box, but since the object can be very large, and he procedure will be called several times, i'd like to pass the object via a pointer.\n\nReally isn't there a way to define an interface method that receive the calling structure via a pointer?\n\npackage main\n\nimport \"fmt\"\n\ntype container interface {\n setValue (val int)\n}\n\n//--------------------------------------\n// box is a kind of container\n\ntype box struct {\n value int\n}\n\nfunc newbox (x int) box {\n return box {x}\n}\n\nfunc (cnt *box) setValue(val int) {\n (*cnt).value = val\n}\n\n\n// -----------------------------------------------\n\nfunc main() {\n var b container = newbox(3) // HERE IS THE ERROR\n fmt.Printf(\"%v\\n\",b)\n b.setValue(5)\n fmt.Printf(\"%v\\n\",b)\n}"
] | [
"pointers",
"go",
"methods",
"interface"
] |
[
"javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure only in server",
"I am trying to make an HTTP GET petition from Java in Oracle Sql Developer.\n\nIn my computer all works fine.\n\nThe only thing that doesn't work is when I access https subdomains it gives an SSLHandshakeException error (for example if I access https://www.example.com it works, but if I access https://subdomain.example.com it fails)\n\nWhat I did then was to add the certificate in Java caches and then it worked.\n\nHowever when I do it on the server, to do it from SQL Developer using PL / SQL calling a Java function, it fails, and I have done the same thing with the certificate.\n\nWhat I do not know is if you are referencing cacerts in the Java of sql developer, since in my machine if I had to refer to this (-Djavax.net.ssl.keyStore = C: \\ Oracle \\ Middleware \\ Oracle_Home \\ oracle_common \\ jdk \\ jre \\ lib \\ security \\ cacerts)\n\nIf I do in the Java code this keeps giving error:\n\nSystem.setProperty (\"javax.net.ssl.trustStore\", \"/path/jdk/jdk6/lib/security/cacerts.jks\");\n\n\nHow can I know if it is taking the certificates?\n\nMy machine: Java 1.7 and 1.8 works\nServer: Java 1.6 does not work\n\nGreetings and thanks"
] | [
"java",
"oracle",
"ssl",
"sslhandshakeexception"
] |
[
"graphLookup StartWith Object instead of Array",
"today a i read about the $graphLookup feature and i was totaly impressed about this (for me) new feature.\nCurrently i solve these type of problems with eval and now i gonna transfer these functions to $graphLookup.\n\nOne of these functions is \"getAllSubFolders()\". And now i got in some troubles, because my\nconnectFromField is a object, rather than being an array (as in the mongoDB documentation examples).\n\nTo unterstand this better:\n\nFolder documents are structured like this:\n\n{\n \"_id\" : ObjectId(\"58286a66d43ee415567ab4c8\"),\n \"Children\" : {\n \"File_58286ce0d43ee415567ab4e5\" : \"58286ce0d43ee415567ab4e5\",\n \"Folder_5829d284d43ee41fa74f7e50\" : \"5829d284d43ee41fa74f7e50\",\n },\n \"UserID\": \"1\"\n ...\n}\n\n\nNow as i mentioned, i need a aggregation pipeline (with $graphLookup?) which will give me all subfolders back.\nAny ideas how to solve this?\n\nTo be more specific: My current problem is startWith. I need something like:\n\ndb.folders.aggregate( [\n{ $match : { \"UserID\" : \"1\" } },\n {\n $graphLookup: {\n from: \"folders\",\n startWith: \"getObjectValues($Children)\", //returns an array with the object values\n connectFromField: \"getObjectValues($Children)\", // not sure about this\n connectToField: \"_id\",\n as: \"sub_folders\"\n }\n }\n]);\n\n\nPS: Nice but not needed would be if we search only for Children which has Folder_ in the key. I don't know if there's a possibility to filter it.\n\nOk, so our origin document looks like this:\n{ \n \"_id\" : ObjectId(\"581bae37d43ee401131d8293\"), \n \"UserID\" : \"37\", \n \"Children\" : {\n \"File_581bb4abd43ee401131d82a0\" : \"581bb4abd43ee401131d82a0\", \n \"Folder_581bc233d43ee401131d82b8\" : \"581bc233d43ee401131d82b8\", \n ...\n }\n}\nNow we need an query that return this document:\n{ \n \"_id\" : ObjectId(\"581bc233d43ee401131d82b8\"), \n \"Children\" : {\n \"Folder_5826034c0c0a1c005d64f921\" : \"5826034c0c0a1c005d64f921\"\n }, \n}\nbut also the child folder with the id 5826034c0c0a1c005d64f921.\n{ \n \"_id\" : ObjectId(\"5826034c0c0a1c005d64f921\"), \n \"Children\" : {\n \"Folder_593032743f54cc0078025802\" : \"593032743f54cc0078025802\"\n }\n}\n... recursive, down to the last element (until the object children contains no more folders)\n\n\nOverall the result should like this:\n\n{\n \"_id\" : ObjectId(\"581bc233d43ee401131d82b8\"),\n \"Children\" : {\n \"Folder_5826034c0c0a1c005d64f921\" : \"5826034c0c0a1c005d64f921\"\n }, \n},\n{\n \"_id\" : ObjectId(\"5826034c0c0a1c005d64f921\"),\n \"Children\" : {\n \"Folder_593032743f54cc0078025802\" : \"593032743f54cc0078025802\"\n }\n},"
] | [
"mongodb",
"mongodb-query",
"aggregation-framework"
] |
[
"Wait for redux props in componentDidMount",
"I want to load something from my API endpoint in componentDidMount, but that needs to have something else from the redux store passed into it.\n\nThing is, it seem that componentDidMount gets fired before the props are populated from redux, so the jwt auth token isn't in the redux state yet, and I get a 401 error.\n\nHow can I get the code to wait for the redux state to be loaded, then call the function, or have it loop every, lets say 500ms, until the props are identified?\n\nIf there's some place other than componentDidMount I should put it I'm open to suggestions."
] | [
"reactjs",
"redux",
"jwt"
] |
[
"Redirect .jpeg files to .php files",
"I'm trying to make some image optimizations and so I want every requested .jpeg images to be redirected to my transformer.php file for the conversion and then the transformed will the be sent to the client. The actual problem is that I've been using my .htaccess rewrite rule to make that redirect possible but it doesn't seem to get that file... The chrome response keeps saying \"This request has no response data available\", whereas I've some mock data written in the file.\n\nMy rewrite rule:\n\nRewriteEngine On\nRewriteBase /\nRewriteRule (.*)\\.jpeg$ /img/transformer.php [L]\n\n\nI don't know why it isn't working. Glad if you could help. Thank you!"
] | [
"php",
".htaccess"
] |
[
"Changed Android Project name now not working at all",
"I've just changed my Android project name via \n\n\n -res -> values -> strings.xml (changed app name)\n \n -Right clicked on project -> refactored -> renamed\n\n\nNow nothing is working, error codes on every line. This is my final year project and I think I have ruined it.\nAny ideas on how to get it working again? \nIve tried the above 2 steps again but renaming it back to what it was before with no success.\n\nPlease help"
] | [
"android"
] |
[
"Export Excel chart and then Delete the file",
"I am using C# to export an Excel chart and then delete the exported file at a later stage in the program. \n\nHowever, I get the error \"The process cannot access the file 's:\\VS Programs\\Contouring_rev\\contouring_dem.bmp' because it is being used by another process.\" error. \n\nHere is my code;\n\nchartPage.Export(@\"s:\\\\VS Programs\\\\Contouring_rev\\\\contouring_dem.bmp\", \"BMP\", misValue);\n.\n.\n.\nif (File.Exists(@\"s:\\\\VS Programs\\\\Contouring_rev\\\\contouring_dem.bmp\"))\n{\n File.Delete(@\"s:\\\\VS Programs\\\\Contouring_rev\\\\contouring_dem.bmp\");\n}"
] | [
"c#",
"excel",
"export",
"delete-file"
] |
[
"Convert milliseconds into hours and plot",
"I'm trying to convert an array of milliseconds and its respective data. However I want to do so in hours and minutes. \n\nMillis = [60000 120000 180000 240000....]\nPower = [ 12 14 12 13 14 ...]\n\n\nI've set it up so the data records every minute, hence the 60000 millis (= 1 minimte). I am trying to plot time on the x axis and power on the y. I would like to have the x axis displayed in hours and minutes with each respective power data corresponding to its respective time.\n\nI've tried this\n\nfor i=2:length(Millis)\nConv2Min(i) = Millis(i) / 60000;\nTime(i) = startTime + Conv2Min(i);\nif (Time(i-1) > Time(i) + 60)\nTime(i) + 100;\nend\n\nend\ns = num2str(Time);\n\n\nThis in attempt to turn the milliseconds into hours starting at 08:00 and once 60 minutes have past going to 09:00, the problem is plotting this. I get a gap between 08:59 and 09:00. I also cannot maintain the 0=initial 0."
] | [
"matlab",
"plot",
"time-series",
"datetime-conversion"
] |
[
"Replace text for every nth instance in a line",
"I wish to replace every 6th instance of a space with a character "+" in a given line :\n\nNow is the Time for All Good Men to Come to the Aid of their Country. How much wood could a wood chuck chuck?\n\nAttempting:\nsed "s/ /+/6;P;D" text.txt\nWhich yields:\n\nNow is the Time for All+Good Men to Come to the Aid of their Country. How much wood could a wood chuck chuck?\n\nI desire:\n\nNow is the Time for All+Good Men to Come to the+Aid of their Country. How much+wood could a wood chuck chuck?\n\nI can deal with insert if replace won't work."
] | [
"bash",
"loops",
"sed"
] |
[
"String and Vec not found in this scope",
"I have following code in decl_storage!\nGroup get(fn group): map hasher(blake2_128_concat) u128 => Vec<u128>;\nVoteStatus get(fn vote_status): map hasher(blake2_128_concat) (u128, u128, String) => bool;\n\nNeither its accepts String, nor Vec<u128>, it says not found in this scope.\nUpdate:\nFixed the Vec part by importing\nuse sp_std::vec::Vec;\n\nHow can I import string?? Unable to use str?\nWill I use Vec<u8>? Link"
] | [
"substrate"
] |
[
"How to Send Variable to Parent Controller from Directive without Isolate Scope",
"How to watch variable from directive in controller AngularJS?\nI have a component with controller and directive\nIn my directive I'm listening for scroll and returning true if element is in view or false if it is not.\nI want to be able to accesss my boolChangeClass variable in the controller so that I can call my function only if it is true.\nMy question is how can I access boolChangeClass in controller?\n 'use strict';\n \n angular.module('myModule')\n .component('myComponent', {\n template: `\n <div class="component" inview ng-class="{min: boolChangeClass}">\n </div>\n `,\n \n controller: function ($scope) {\n let $ctrl = this;\n\n let func = () => {console.log('my function')}\n\n $scope.$watch('boolChangeClass', func);\n }\n })\n .directive('inview', ($window) => {\n return function(scope, element, attrs) {\n angular.element($window).bind("scroll", function() {\n let rect = element[0].getBoundingClientRect();\n scope.boolChangeClass = rect.bottom > 0 &&\n rect.right > 0 &&\n rect.left < (window.innerWidth || document.documentElement.clientWidth) &&\n rect.top < (window.innerHeight || document.documentElement.clientHeight)\n scope.$apply();\n });\n };\n })"
] | [
"angularjs",
"angularjs-directive",
"angularjs-components"
] |
[
"Java recursive binary search throwing out of bounds exception?",
"Hey, I have been asked to write a recursive binary search for my data structure class in university, but i'm having a slight problem. When i search for a number that is out of bounds (over 10 in this case) it throws an out of bounds exception. I understand why it's doing it, due to the array not having >10 spaces, but i don't know how to work around it. Any ideas? \n\nThe array that im searching is an ordered array 1 - 10 (index 0 - 9).\n\n public int recursiveBinarySearch(int[] anArray, int searchedNumber, int min, int max) {\n\n if (min > max)\n {\n System.out.println(searchedNumber + \" is not present in tha array.\");\n //return -1 to show that the value has not been found\n return -1;\n }\n // find the centre of the array\n int centre = (min + max) / 2;\n\n if (anArray[centre] == searchedNumber)\n {\n System.out.println(searchedNumber + \" was found at index \" + centre);\n return centre;\n }\n\n if (anArray[centre] < searchedNumber)\n {\n return recursiveBinarySearch(anArray, searchedNumber, centre+1, max);\n }\n\n return recursiveBinarySearch(anArray, searchedNumber, min, centre-1);\n\n }"
] | [
"java",
"search",
"recursion",
"binary"
] |
[
"Desktop save with WScript.Shell and date as file name",
"I am trying to have a file save to desktop without a path and can't get it to save using today's date. I am using the following code:\nSub SavetoDesktop() \nDim Path As String\nPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\\"\nActiveWorkbook.SaveAs Path & Format(Now(), "DD-MMM-YYYY"), xls\nEnd Sub"
] | [
"vba",
"file",
"save"
] |
[
"sysmalloc assertion failed in c",
"I have use malloc() many time in my program. It works perfectly most of the time but for some inputdoes works, and gdb prompt the following error:\n\nError:\n\n my_program: malloc.c:2394: sysmalloc: Assertion `(old_top==initial_top \n (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse \n (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.\n Aborted\n\n\nThe portion of code is:\n\n uint8_t *hex_b;\n if((hex_b = malloc(len_b))==NULL)\n {\n fprintf(stderr,\" Malloc Failed\\n\");\n }\n\n\nBut It works ,when i change the code as:\n\nuint8_t hex_b[len_b];"
] | [
"c",
"memory-management",
"memory-leaks",
"malloc"
] |
[
"To run in a time window until midnight",
"I have an AirFlow scheduler that I want to run at 13 until midnight from Monday to Saturday. I wrote an expression like this:\n\n0 13-0 * * 1-6\n\n\nWhile trying to validate this in crontab.guru for example I get an error since 0 is smaller than 13:\n\n\n https://crontab.guru/\n\n\nDoes anyone know how can I write a valid cron-expression for this type of schedule?"
] | [
"cron",
"airflow-scheduler"
] |
[
"Match opposite of regular expression",
"I have a quick question about Regular Expressions.\nCan I specify a pattern and have everything else that doesnt fit the pattern to be matched?\nFor example, anything that does not fit into this pattern: HT\\d{4}, I want to consider a match."
] | [
"regex"
] |
[
"jQuery AJAX error handling How to separate returned error messages into individual li's",
"Working with some data returned from a database. All data is returned in a table, in one td specifically. The mark up of the returned data is as such\n\n<table border=1>\n <tr>\n <td>Field Name</td>\n <td>Field Value</td>\n </tr>\n <tr>\n <td>SuccessFlag</td>\n <td>False</td>\n </tr>\n <tr>\n <td>ResponseMessage</td>\n <td>Invalid email address, Invalid User Name, etc., etc</td>\n </tr>\n</table>\n\n\nin my error handling, I'm able to get to the 6th td and show the error no problem. \n\nsuccess: function(data) {\n var answer = $(data).find(\"td:eq(3)\").text();\n var message = $(data).find(\"td:eq(5)\").text();\n if (answer===\"True\") {\n $(\"#bottomContent\").load(\"page.php #div\");\n } else {\n $('#processing').hide();\n $('input[type=\"text\"], input[type=\"password\"]').val(\"\");\n $('#messageBox').show().html('<ul><li>' + message + '</li></ul>');\n }\n }\n\n\nUnfortunately, it would output all of the contents in one li. I would like to figure out how to split them at the ',' and create an individual li for each item after the split."
] | [
"jquery"
] |
[
"Is it possible to create an on-the-fly (soft) dblink in postgresql",
"Wondering if it is possible to create a dblink in postgresql that is not saved as an object in the db, but rather it is an in-memory object during the session of a function or running code? Then use it to connect and do queries.\n\nNew to postgresql and not sure how to search for this.\n\nAny examples on how to do this?"
] | [
"postgresql",
"dblink"
] |
[
"NSManagedObject setValue problem (Core Data)",
"I wish to edit an existing record in core data. At the moment, I have this code, but it creates a new record (and inserts the correct data into the correct column):\n\nNSManagedObjectContext *context = [[NSApp delegate] managedObjectContext];\nNSManagedObject *instrument = nil;\n\n\n\ninstrument = [NSEntityDescription insertNewObjectForEntityForName: @\"Instrument\"\n inManagedObjectContext: context];\n\n[instrument setValue:[NSNumber numberWithInt:quantityInStockInstruments] \n forKey: @\"quantity\"];\n\n\nThe result will look like this:\n\nInstrument | Value | Quantity\n\nViolin | £25 | 9\n\n | | 8 <<< This is the new record that is created, instead of setting the\n quantity of violin from '9' to '8'\n\n\nI want the program to edit the quantity column of the currently highlighted row, (which in this case is the 'violin' row. How would I do this?"
] | [
"cocoa",
"core-data",
"setvalue"
] |
[
"Tesseract 3.03: 'boxchar.lo' is not a valid libtool object",
"I have been trying to compile Tesseract 3.03 rc1 these days. I have tried Cygwin, MinGW+MSYS, MSYS2+MinGW-w64. And now I am using the Xubuntu 15.04.\n\nThe 3.03 rc1 source is downloaded from here.\n\nI have successfully compiled the tesseract with make install.\n\nBut when I trying to compile the training tools with make training, I see the following error:\n\n\n\nAnyone could shed some light on this?? I am kind of out of clue now.\n\n(BTW, I see someone mentioned the tesseract 3.04. But I can only find the 3.03 rc1 at google's location. Anyone know where the 3.04 is?)"
] | [
"gcc",
"tesseract",
"autotools",
"libtool"
] |
[
"Ploting bianary (presence/absence) data with ggplot2 geom_point()",
"Trying to plot presence/absence data with geom_point() ggplot.\nCol1 Col2 Col3\nName Case 1\nName Case2 0\nName Case3 1\nName2 Case 1\nName2 Case2 0\nName2 Case3 1\n\nI tried:\nlibrary(ggplot2)\nlibrary(dplyr)\n\nplot <- df %>%\n ggplot(aes(x=Col2, y=Col1, fill = Col3, size = 7)) +\n geom_point() +\n theme(axis.text.x = element_text(angle = 90, hjust = .1, vjust=0.5))\n\nAnd it just turns out that all of the spaces are filled in::"
] | [
"r",
"ggplot2",
"dplyr",
"tidyverse"
] |
[
"Called itself (function) inside for loop, and it changes local variable",
"def findPair(students, Robert):\n #...\n if len(students) == 2:\n #do something\n return\n else:\n for friend in friendsOfRobert:\n print(students)\n leftStudents = removePairFromStudents(students, friend, Robert)\n if len(leftStudents) != 0:\n findPair(leftStudents, leftStudents[0])\n return\n\n\nI don't quite understand why students is modified as it loops inside for. It is not even global variable. The following is just to help you see the structure of the code. \n\n\n... part : find friendsOfRobert from students\nfor loop\n\n(1) suppose one friend and Robert was paired.\n\n(2) leftStudent: Remove the friend and Robert from students\n\n(3) Repeat findPair but this time without the friend and Robert. The next equivalent of Robert is randomly selected (leftStudents[0]) \n\n\nOn the side note, I solved the issue by remembering the pair previously removed, and rebuilding the original students set each time (with code below) before it dives into the next loop. \n\nif len(students) == 2:\n if len(justPaired) != 0:\n students.append(justPaired[0])\n students.append(justPaired[1])\n # do something\n return\n\n\nedit : removed unnecessary example"
] | [
"python",
"python-3.x"
] |
[
"converting sequences to lex order",
"I have a function that generates binary sequences with a fixed number of 1's (the rest are 0's). I need a function that takes a sequences and returns the position of that sequence in lexicographic order. For example, the 10 sequences of length 5 with 3 1's are\n\n0 0 1 1 1\n0 1 0 1 1\n0 1 1 0 1\n0 1 1 1 0\n1 0 0 1 1\n1 0 1 0 1\n1 0 1 1 0\n1 1 0 0 1\n1 1 0 1 0\n1 1 1 0 0\n\n\nI need a function that takes, for example 0 1 1 0 1 and returns 3 since it's the third in the list.\n\nThe only thing I can think of, which is way too inefficient, is to generate all of the sequences (easy), store them (takes too much space), then search for the given sequence in the list (too slow), and return its position. Is there a faster way to do this? Some easy trick that I don't see?"
] | [
"algorithm",
"sequences"
] |
[
"Extract a list of all methods from JavaDoc",
"I have some package of javadoc, and I want to extract a list of all methods doumented inside. somethong like:\n\npath=\"C:\\Doc\\idex.html\"; \n\nList<String> listMethods=ExtractAPI(path);\n\n\nI don't mind the language to do it, but I guess that java has a builtin features for it.\n\nI tried reading the javadoc doumntation:\n\nhttp://docs.oracle.com/javase/1.5.0/docs/guide/javadoc/doclet/overview.html\n\nBut couldn't understand clear enough if it is possible, and if yes how exactly to do it.\n\nThanks!"
] | [
"java",
"javadoc"
] |
[
"Java: getClass() breaks out of method?",
"I have a line of code followed by a for loop that makes a call to getClass().\n\nClass<?> type = track.getClass();\nfor (Field field : getAllFields(type)) {\n //do stuff\n}\n\n\nI set breakpoints on the first line and another on the header of the for loop. During a debug, the first line is hit, but after hitting continue (in the NetBeans debugger), the for loop never gets hit. I also placed breakpoints further down in the method, but they were not hit either. I'm unsure what's happening in the first line that breaks out of the method. If anyone could offer some advice, I'd be grateful.\n\nThanks."
] | [
"java",
"debugging"
] |
[
"R expanding out a data.table",
"I've the following situation. A data.table that looks as follows\n\nx = data.table(\n id1 = c('a','b','c'),\n id2 = c('x','y','x'),\n val = c(0.2,0.3,0.5))\n\n\nI have two other data tables that give a mapping between the values in id1 and id2 which look like the following\n\nid1.dt = data.table(\n id1 = c('a','a','a','b','b','c'),\n fid = c('1232','3224','3434','234','231','332')\n)\n\n\nand\n\nid2.dt = data.table(\n id2 = c('x','x','y','y'),\n fid = c('334','443','344','24')\n)\n\n\nWhat I would like to be able to do is to expand out the above data.table x by preserving the values column such that I get a full cross join but by using the fid column. So the expected final table is\n\nid1 id2 val\n1232 334 0.2\n1232 443 0.2\n3224 334 0.2\n3224 443 0.2\n3434 334 0.2\n3434 443 0.2\n...\n\n\nBasically, for each row in x I want to take all fid values of id1 and id2 from the other two tables and preserve the val value. I've tried using CJ but didn't get far with it. Any help appreciated."
] | [
"r",
"merge",
"data.table"
] |
[
"Heroku doesn't delete database when I remove it on server (Django app)",
"I logged in to my app's directory in Heroku's server:\n\nHeroku run bash -app appname\n\n\nThen I deleted my database:\n\nRm -r dev.db\n\n\nHowever when I try to sync my database it doesn't create new tables. And when I go to the production site, it still has all database contents and lets me log in, etc.\n\nAny insight into what I'm doing wrong? I want to completely recreate the database.\n\nNote: I have a Django app\n\nUpdate: Here are my database settings\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\", # Add \"postgresql_psycopg2\", \"postgresql\", \"mysql\", \"sqlite3\" or \"oracle\".\n \"NAME\": PROJECT_ROOT + os.sep + \"dev.db\", # Or path to database file if using sqlite3.\n \"USER\": \"\", # Not used with sqlite3.\n \"PASSWORD\": \"\", # Not used with sqlite3.\n \"HOST\": \"\", # Set to empty string for localhost. Not used with sqlite3.\n \"PORT\": \"\", # Set to empty string for default. Not used with sqlite3.\n }\n}\n\n\nthen I have this injection code for Heroku:\n\nimport dj_database_url\nDATABASES = {'default': dj_database_url.config(default='postgres://localhost')}"
] | [
"django",
"heroku"
] |
[
"Cassandra insert preparedStatement or mapper?",
"We are doing inserts of a few millions records in 1 time in a Cassandra 3.0 database. Question is : what has best performance: using the mapper (annotating our object 'JPA' style) or using a prepared statement, which will only be prepared once and then bind for every insert. \nI read here that the mapper does an implicit prepared statement in the background so performance should not differ. But I don't understand where he should keep that prepared statement? Or is it done for every insert, which would take away the advantage of doing a prepared statement. So question : mapper (jpa style) or preparedStatement (JDBC style :-) ) ?"
] | [
"performance",
"cassandra",
"prepared-statement",
"cassandra-3.0",
"mapper"
] |
[
"Obtaining client IP Address through ALUI Portal Gateway",
"Currently using Oracle/BEA/Plumtree ALUI Portal 6.1, and am trying to display a client's IP Address. Problem is that since this content is being gatewayed, the portal server's address is coming up when I call\n\n<%= request.getRemoteAddr() %> (<%= request.getRemoteHost() %>)\n\n\nI am pretty much doing the java equivalent of this link, and it's not working correctly. Uncertain if there is something somewhere in the IDK, or if there's a configuration setting that needs to change."
] | [
"oracle",
"ip-address",
"portal",
"oracleportal",
"plumtree"
] |
[
"Android Bitmap snap to grid",
"Does anyone know if there is a simple way to make images snap to grid when dragging a bitmap?\n\nAt the moment I can touch a bitmap and move it smoothly around the screen. I want to be able to make it snap to an invisible grid whilst you are dragging."
] | [
"java",
"android"
] |
[
"On building a head tracker for your head mounted display using your android mobile phone",
"My goal is to code a headtracker for my head mounted display using my android phone. The movement is transferred to mouse movement, which in turn is used inside pc games. I want to mount my android phone to the back of the head-tracker, so it will be fixed to the back of my head. The y-axis is facing upwards, the x-axis is facing to the right when looking straight ahead, that means when you look at my back head, you see the mobile phone display.\n\n\n\nDue to mechanics of this setup there is an angle between the y-axis and the gravity-axis, so the mobile phone is tilted slightly away from the back of the head when looking straight forward. Also it is slightly rotated around the z-axis and might be rotating while moving around the z-axis within an angle of about 5 to 10°.\n\nMy phone does not have a gyroscope. I used \n\npublic void onSensorChanged(SensorEvent event)\n{\n // alpha is calculated as t / (t + dT)\n // with t, the low-pass filter's time-constant\n // and dT, the event delivery rate\n\n final float alpha = 0.8;\n\n gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];\n gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];\n gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];\n\n linear_acceleration[0] = event.values[0] - gravity[0];\n linear_acceleration[1] = event.values[1] - gravity[1];\n linear_acceleration[2] = event.values[2] - gravity[2];\n}\n\n\nwhich works better than just using raw data from the accelerometer. I just used 0.8 as alpha, do I need to adjust it according to t / (t + dT)? So how to get t and dT then?\n\nUsing this setup, tilting the head up and down works - with some refinement here and there - well. \n\nBut moving left and right turns out to be an issue. Also moving diagonal from left-down to right-up and mirrored. Or moving in circles.\n\nComing from the basic mathematics and not my error description, which code do you suggest to make this work?"
] | [
"android",
"accelerometer",
"gravity"
] |
[
".NET Publish not yielding same results as manual copy",
"I am using Visual Studio 2008 .NET and trying to use the 'Publish' option from the context menu when I right-click on the project file. Ideally, this would deploy only the files needed to run the project. I have selected to delete all files before I deploy, include the App_Data folder and only the file needed to run the project. My project has several .dlls from other projects that are properly referenced.\n\nMy issue is the following...if I manually copy the entire project from my local drive to the application server I don't run into any issues, however, if I use the 'Publish' option I can get the application to run on the app server but I eventually run into a Forms Authentication Error. I have checked the account referenced in the error from the EventViewer and that account is db_owner in the database and has not been locked out.\n\nI am quite perplexed....any ideas?\n\nIt appears this only happens when I select the option to include only files needed to run the application. If I publish ALL files I don't have the error."
] | [
".net",
"deployment",
"publish"
] |
[
"How to check files associated with some label in perforce are synced or not?",
"I have a perforce label with which i am retrieving files associated with it as follows:\n\np4 files @my_label_name\n\n\nthis command retrieves me the list of files against the label \"my_label_name\".Now, i want to check that these files in my workspace are synced to latest or not.How shall i do it?\nI searched on net and got a command as:\n\np4 sync -n -m 1\n\n\nbut with this command whole workspace is checked weather its up to date or not but i am only interested about status of the files associated with label of my wish. So, kindly suggest how can i have this."
] | [
"python",
"perforce"
] |
[
"jQuery/JS infinite timed loop",
"I am trying to create a series of clicks on different elements on screen at different times. I can easily do this using the setTimeout function, but I need to make this an infinite loop!?\n\nHere is a snippet of how I am currently handling the code. \n\nsetTimeout(function () {jQuery('.CR_1').trigger('click');}, 1000);\nsetTimeout(function () {jQuery('.CR_1').trigger('click');}, 5000);\nsetTimeout(function () {jQuery('.CR_2').trigger('click');}, 5500);\n\n\nAny ideas on how I can make this work?\n\nEDIT: Let me a little more clear. I am trying to run the set of functions in the same order over and over. The setInterval worked perfectly. I am super sorry for any confusion. \n\n setInterval ( \"flips ()\", 12000 );\n\n\nfunction flips (){\n setTimeout(function () {jQuery('.CR_1').trigger('click');}, 1000);\n setTimeout(function () {jQuery('.CR_1').trigger('click');}, 5000);\n setTimeout(function () {jQuery('.CR_2').trigger('click');}, 5500);\n\n }"
] | [
"javascript",
"jquery"
] |
[
"If the application is closed and i receive the push notification, how detect the tap on notification and go to a specific controller?",
"I have an iOS application in which I am using the push notification to notify the user when the correct answer is posted. If the application is open and if I click on the notification it goes to the specified controller. But if the application is closed and if I receive the notification it does not goes to the specified controller.\n\n-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo\n{\n NSLog(@\"User Info %@\",userInfo);\n NSString* alertValue = [[userInfo valueForKey:@\"aps\"] valueForKey:@\"badge\"];\n NSLog(@\"my message-- %@\",alertValue);\n int badgeValue= [alertValue intValue];\n\n// NSNumber *identifierString = [[[userInfo valueForKey:@\"aps\"]valueForKey:@\"details\"]valueForKey:@\"identifire\"];\n// NSLog(@\"identifierString %@\",identifierString);\n NSString *alertMessage = [[userInfo valueForKey:@\"aps\"] valueForKey:@\"alert\"];\n NSLog(@\"ALertMessage %@\",alertMessage);\n if ([alertMessage isEqualToString:@\"New answer added.\"]) {\n [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeValue];\n// [[NSUserDefaults standardUserDefaults] setObject:[[[[userInfo valueForKey:@\"aps\"] valueForKey:@\"details\"] objectAtIndex:0]valueForKey:@\"question\"]forKey:@\"notificationQuestion\"];\n// [[NSUserDefaults standardUserDefaults] setObject:[[[[userInfo valueForKey:@\"aps\"] valueForKey:@\"details\"] objectAtIndex:0]valueForKey:@\"user_image\"]forKey:@\"notificationImage\"];\n// NSLog(@\"Image %@\",[[NSUserDefaults standardUserDefaults]valueForKey:@\"notificationQuestion\"]);\n\n\n NSLog(@\"User Information %@\",userInfo);\n NSLog(@\"User Details %@\",[[userInfo valueForKey:@\"aps\"] valueForKey:@\"details\"]);\n // NSLog(@\"User Details 1%@\",[[[userInfo valueForKey:@\"aps\"] valueForKey:@\"details\"] objectAtIndex:0]);\n // NSLog(@\"User Details 1%@\",[[[[userInfo valueForKey:@\"aps\"] valueForKey:@\"details\"] objectAtIndex:0]valueForKey:@\"question\"]);\n pushDictonary = [[userInfo valueForKey:@\"aps\"] valueForKey:@\"details\"];\n\n\n }\n\n\n //NSArray *pushDetails = [[userInfo valueForKey:@\"aps\"] valueForKey:@\"details\"];\n // NSLog(@\"Push Details %@\",pushDetails);\n if (application.applicationState == UIApplicationStateActive ) {\n\n// UILocalNotification *localNotification = [[UILocalNotification alloc] init];\n// localNotification.userInfo = userInfo;\n// localNotification.soundName = UILocalNotificationDefaultSoundName;\n// localNotification.alertBody = [[userInfo valueForKey:@\"aps\"] valueForKey:@\"alert\"];\n// localNotification.fireDate = [NSDate date];\n if ([alertMessage isEqualToString:@\"New answer added.\"])\n {\n [self createNotificationViewwithUserDictionary:userInfo];\n\n }\n\n\n }\n else if (application.applicationState == UIApplicationStateBackground)\n {\n NSLog(@\"YES\");\n }\n else if (application.applicationState == UIApplicationStateInactive)\n {\n NSLog(@\"YES\");\n if ([alertMessage isEqualToString:@\"New answer added.\"])\n [self pushdetailsViewController];\n }\n\n\nFor going to the controller :\n\n -(void)pushdetailsViewController\n{\n\n UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@\"Main\" bundle: nil];\n QPYourQuestionController *controller = (QPYourQuestionController*)[mainStoryboard instantiateViewControllerWithIdentifier: @\"yourQuestion\"];\n [[QPCommonClass initializeUserDefaults]setObject:[pushDictonary valueForKey:@\"question_id\"] forKey:@\"currentquestionID\"];\n NSLog(@\"Dictionary %@\",pushDictonary);\n\n UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;\n [navigationController pushViewController:controller animated:YES];\n\n\n\n}"
] | [
"ios",
"objective-c",
"apple-push-notifications",
"xcode7.3",
"ios9.3"
] |
[
"Why won't .save() use the data I tell it too",
"Ok so this may be kind of odd, but hear me out.\n first thing, this question is related to my issue.\n\nIn a nutshell. I am trying to make Mongo entries, everything is communicating, but my model.save() only save id and version.\n\nThe difference in what I am trying to do is that I don't want what to send any data.\n\nI want to send a GET request, and I want the server to generate the initial data entry. That entry just being a timestamp and a boolean.\nSo my code looks like this\n\n const CLOCK_IN = (req ,res ) => {\n\n const TimeCard = new TimeCardModel({\n startTime: new Date.now(),\n clockedIn: true\n })\n TimeCard.save()\n .then(res => {\n res.json(TimeCard.toJSON())\n })\n .catch(err => {\n res.json(err)\n })\n }\n\n\nSo what they say in the first question. Is that the object is empty because the function can't read the data. So do I need to write up some code that will make the data I want before I call the entry saving function? Or is there something else that I'm missing?"
] | [
"javascript",
"mongoose",
"backend"
] |
[
"angular 5 with angularjs in iframe",
"Hi I build a wrapper with angular 5 that contains side navigation header and iframe as a content .\nin the side navigation I'm navigate to a specific URL in app in angularjs or angular 5 (until will finish the migration) and the URL is bind to iframe SRC.\nThe problem is that in the first time the app in the iframe takes to long to render... Anybody know how to prerender or fetching the apps for better performance?"
] | [
"angular",
"performance",
"iframe"
] |
[
"Taking a preexisting Google map and importing into Android",
"I am creating an app for a state trail, this trail is ~200 miles long and has a hundred or so attractions along the way. Here is the preexisting map with all the venues and attractions layed out: https://www.google.com/maps/d/u/0/viewer?mid=z5cNDCbZgqkg.kReB3k9EGYyI\n\nTo save time, I want to embed this map into the app. Is there a way to do it using the Google API or should I just use a Web view?\n\nThanks in advance for any assistance!"
] | [
"android",
"google-maps"
] |
[
"Extract Single Data From JSON URL for Dashing Dashboard",
"I am trying to show the \"sgv\" value on a Dashing / Smashing dashboard widget. Ultimately I would also like to show the \"direction\" value as well. I am running into problems pulling that precise value down which changes every 3 to 5 minutes. I have already been able to mirror the exact string using the following:\n\nrequire 'net/http'\nrequire 'rest-client'\nrequire 'json'\n\nurl = \"https://dnarnianbg.herokuapp.com/api/v1/entries/current.json\"\nresponse = RestClient.get(url)\nJSON.parse(response)\n\n# :first_in sets how long it takes before the job is first run. In this case, it is run immediately\ncurrent_nightscout = 0\n\nSCHEDULER.every '5m' do \n last_nightscout = current_nightscout\n current_nightscout = response\n\n send_event('nightscout', { current: current_nightscout, last: last_nightscout })\n end\n\n\nI have also searched the archives several times. I don't wish to write this to a file like this one shows and the duplicate question has been deleted or moved. \n\nI realize that the JSON.parse(response) is just going to parse out whatever I tell it the response equals, but I don't know how to get that response to equal SGV. Maybe the solution isn't in the RestClient, but that is where I am lost.\n\nHere is the JSON URL: http://dnarnianbg.herokuapp.com/api/v1/entries/current.json\n\nEDIT: The output of that link is something like this:\n\n[{\"_id\":\"5ba295ddb8a1ee0aede71822\",\"sgv\":87,\"date\":1537381813000,\"dateString\":\"2018-09-19T18:30:13.000Z\",\"trend\":4,\"direction\":\"Flat\",\"device\":\"share2\",\"type\":\"sgv\"}]"
] | [
"json",
"ruby",
"rest-client",
"dashing"
] |
[
"compare a character with double quotes \" in windows batch",
"I want to compare a single character with double quotes \" in a in windows batch file.\n\n@echo off\nsetlocal EnableDelayedExpansion\nset var=before\nfor /f %%a in (zen.csv) do (\n set var=%%a\n echo !var:~-1!\n IF \"!var:~-1!\"==\"\"\"\" (\n @echo found\n )\n)\npause\n\n\nthe result is like:\n\n0\n1\n\"\n\"\n\"\n0\n1\n2\n\n\nAs you can see, the batch did not output the \"found\". How to compare a character with double quotes?"
] | [
"windows",
"batch-file",
"string-comparison",
"double-quotes"
] |
[
"Is there a way to transfer the values of an array from method to method without using return?",
"I'm stuck on a Java coding assignment. I'm supposed to create three methods (askInfo, copyInfo, and setArray) for an existing program that lets the user input numbers into an array, and then organizes and prints that array. AskInfo receives the array as a parameter, asks for the index values from the user, and returns the amount of inputted numbers as int. CopyInfo copies the values into a new array with a length of the returned amount of numbers, and setArray sorts the numbers. \n\nMy problem is that, according to the assignment, askInfo is only supposed to return the amount of inputted numbers. Thus it leaves the values of the array printed with it inside the method, making copyInfo unable to retrieve those values and copy them into the second array. How would you suggest I get past this problem without the ability to edit the main method? \n\nMain method:\n\n int[] tempArray = new int[100];\n System.out.println(\"Type in numbers. Type zero to quit.\");\n int amountOfNumbers = askInfo(tempArray);\n\n int[] realArray = new int[amountOfNumbers];\n copyInfo(realArray, tempArray);\n\n setArray(realArray);\n\n printArray(realArray);\n\n\nMy code:\n\npublic static int askInfo (int[] tempArray) { //asks for numbers and assigns them to tempArray, returns the length of realArray\n int count = 0;\n Scanner reader = new Scanner(System.in);\n for (int i =0;i<tempArray.length;i++){\n System.out.print((i+1)+\". number: \");\n tempArray[i] = reader.nextInt();\n count++;\n if (tempArray[i] == 0) //stops asking for values if user inputs 0\n return count;\n }\n return count;\n }\n\npublic static int[] copyInfo (int[] realArray, int[] tempArray) { //copies tempArray's values to realArray\n for (int i=0; i<realArray.length;i++){\n realArray[i] = tempArray[i];\n }\n return realArray;\n}\n\npublic static int[] setArray (int[] realArray) { //sorts realArray from largest value to smallest\n for (int i=0;i<realArray.length;i++){\n for (int j=i+1;j<realArray.length;j++){\n if (realArray[i]<realArray[j]){\n int tmp = realArray[i];\n realArray[i] = realArray[j];\n realArray[j] = tmp;\n }\n }\n }\n return realArray; \n}\n\n\nRight now the program does compile, but the values of the arrays realArray and tempArray get outside of the askInfo method are null. Keep in mind that I cannot edit the main method - I can only edit the three methods I wrote."
] | [
"java"
] |
[
"Dynamically remove select option value using href - jquery",
"I am having a list of users with delete hyperlink assume\n\n<a href=\"#\" onclick=\"delete(id)\">Delete</a>\n\n\nAnd i have a combo box at the top to filter specific user using user id.\n\nThe delete action will performed with ajax and it reloads the content. The content gets reloaded but the combo box contains the deleted id. Is there any way to clear it using jquery."
] | [
"javascript",
"jquery"
] |
[
"F# function calling syntax confusion",
"I have a piece of code:\n\nlinks\n |> Seq.map (fun x -> x.GetAttributeValue (\"href\", \"no url\"))\n\n\nWhich I wanted to rewrite to:\n\nlinks\n |> Seq.map (fun x -> (x.GetAttributeValue \"href\" \"no url\"))\n\n\nBut the F# compiler doesn't seem to like that. I was under the impression that these two function calls were interchangeable:\n\nf (a, b)\n(f a b)\n\n\nThe error that I get is:\n\n\n The member or object constructor 'GetAttributeValue' taking 2 arguments are not accessible from this code location. All accessible versions of method 'GetAttributeValue' take 2 arguments.\n\n\nWhich seems amusing, as it seems to indicate that it needs what I'm giving it. What am I missing here?"
] | [
"f#"
] |
[
"how to update a variable inside a runnable?",
"the mobile variable changes based on the data traffic.\ni have a button called reset.\ni want the mobile variable to be set to 0 when the reset button is pressed .\nif i try to change it, it says it needs to be declared final(which can't be done, since it is always going to change)\nif i set mobile to global, it needs to be outside runnable and hence doesn't get updated.\nplease suggest a solution.\n\npublic Runnable runnable = new Runnable() {\n public void run() {\n\n float mobile = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();\n Button reset =(Button) findViewById(R.id.buttonset);\n\n reset.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n //what to do here\n }\n });\n\n float total = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();\n tvDataUsageWiFi.setText(\"\" + (total - mobile) / 1024000 + \" Mb\");\n tvDataUsageMobile.setText(\"\" + mobile / 1024000 + \" Mb\");\n tvDataUsageTotal.setText(\"\" + total / 1024000 + \" Mb\");\n if (dataUsageTotalLast != total) {\n dataUsageTotalLast = total;\n updateAdapter();\n }\n handler.postDelayed(runnable, 5000);\n }\n};"
] | [
"java",
"android",
"variables",
"runnable"
] |
[
"Getting connection closed error when trying to read response from FitNesse REST URI",
"Have you run into this problem? I run code remarkably similar to that from a this previous question, When in nUnitTest mode and the URI includes \"/?test&format=xml\" the nUnit test fails with and IOException, \"Unable to read data from the transport connection: The connection is closed.\"\n\nHowever the Fiddler trace that was running at the time shows the very xml I expected.\n\nI've recreated the request headers exactly (almost) as they are sent when sent through the browser.\n\nFinally, if I leave off the \"/?test&format=xml\" from the URI, I get the html I would have otherwise expected.\n\nSOURCE CODE:\n\n public virtual bool Run()\n {\n var request = CreateRequest();\n var response = GetResponse(request);\n var responseString = ReadResponse(response);\n this.SetResults(responseString);\n return this.IsSuccessful;\n }\n\n protected internal virtual HttpWebRequest CreateRequest()\n {\n var address = TestConfig.Address;\n\n var request = (HttpWebRequest)WebRequest.Create(address);\n\n request.Accept = \"*/*\";\n request.UseDefaultCredentials = true;\n request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);\n\n return request;\n }\n\n protected internal virtual HttpWebResponse GetResponse(HttpWebRequest request)\n {\n var response = (HttpWebResponse) request.GetResponse();\n\n return response;\n }\n\n protected internal virtual string ReadResponse(HttpWebResponse response)\n {\n var stream = response.GetResponseStream();\n var responseString = ReadResponse(stream);\n\n stream.Close();\n response.Close();\n\n return responseString;\n }\n\n protected internal virtual string ReadResponse(Stream stream)\n {\n var reader = new StreamReader(stream);\n var responseString = reader.ReadToEnd();\n return responseString;\n }"
] | [
"c#",
".net",
"rest",
"fitnesse"
] |
[
"multiple Orchard CMS blog autoroute",
"Lets say I have 2 blogs: BlogOne and BlogTwo. I want the autoroute to be the same text as the blog name: mysite.com./blogone/article... or mysite.com/blogtwo/article...\n\nHow can I do that in the autoroute settings? My current setting is hardcoded: blogOne/{Content.Slug}"
] | [
"orchardcms",
"orchardcms-1.6"
] |
[
"jscript for toggling a hamburger menu not working",
"I am trying to fix some stuff left over by the front-end developer and I am not expert in javascript (not at all).\nOn our staging system we use a hamburger menu and for reasons unknown to me while the hamburger menu toggles perfectly on opening, upon first closing it doesn't revert back from an "X" to the "Hamburger" subsequent changes instead work flawlessly just that the state is inverted ("X" where there should be a hamburger and hamburger where there should be an "X").\nSo I did it half right (but only half :D).\nMy rather not beautyful code:\n<script type="text/javascript">\nvar headerMobile = document.getElementsByClassName('header-mobile')[0];\nvar openMobileMenuTrigger = document.getElementById('open-mobile-menu'); \nvar closeMobileMenuTrigger = document.getElementById('close-mobile-menu'); \nvar mobileMainMenu = document.getElementById('header-mobile_menu'); \nvar submenus = document.getElementsByClassName('header-mobile_submenu');\nvar openMobileSubMenuTriggers = document.getElementsByClassName('open-mobile-submenu');\nvar closeMobileSubMenuTriggers = document.getElementsByClassName('close-mobile-submenu'); \nvar hamburgerHeader = document.getElementById('open-mobile-menu'); \nvar openSearchTrigger = document.getElementById('open-search-field')\nfunction toggleHamburger(){\n if (hamburgerHeader.classList.contains('is-active')){\n hamburgerHeader.classList.remove('is-active'); \n } else {\n hamburgerHeader.classList.add('is-active');\n }\n \n}\n\nfunction toggleMobileMenu(){\n\n if(mobileMainMenu.classList.contains('is-active') !== true){\n if (openSearchTrigger)\n {openSearchTrigger.classList.remove('is-active')}\n mobileMainMenu.classList.add('is-active'); \n headerMobile.classList.add('is-active'); //remove shadow\n document.getElementsByTagName('html')[0].classList.add('noscroll')// no scroll for html\n document.getElementsByTagName('body')[0].classList.add('noscroll')// no scroll for body\n } else {\n \n setTimeout(\n function(){\n // headerMobile.classList.remove('is-active'); // NO MORE SHADOW IF WE KEEP ACTIVE SEARCH MENU\n for (var i = submenus.length - 1; i >= 0; i--) {\n submenus[i].classList.remove('is-active');\n }\n }, \n 400 \n )\n if(openSearchTrigger){\n openSearchTrigger.classList.add('is-active')\n }\n hamburgerHeader.classList.remove('is-active')\n mobileMainMenu.classList.remove('is-active')\n document.getElementsByTagName('html')[0].classList.remove('noscroll')// no scroll for html\n document.getElementsByTagName('body')[0].classList.remove('noscroll')// no scroll for body\n }\n}\n\nfunction openMobileSubmenu(event){\n var submenuId = event.currentTarget.getAttribute('data-submenu');\n document.getElementById('header-mobile_submenu-' + submenuId).classList.add('is-active'); \n}\n\nfunction closeMobileSubmenu(){\n for (var i = submenus.length - 1; i >= 0; i--) {\n submenus[i].classList.remove('is-active'); \n }\n}\n\nif (openSearchTrigger){\n openSearchTrigger.addEventListener('click', toggleMobileMenu);\n}\n\nopenMobileMenuTrigger.addEventListener('click', toggleMobileMenu);\n// closeMobileMenuTrigger.addEventListener('click', closeMobileMenu);\n\nhamburgerHeader.addEventListener('click', toggleHamburger); \n\nfor (var i = openMobileSubMenuTriggers.length - 1; i >= 0; i--) {\n openMobileSubMenuTriggers[i].addEventListener('click', openMobileSubmenu); \n}\nfor (var i = closeMobileSubMenuTriggers.length - 1; i >= 0; i--) {\n closeMobileSubMenuTriggers[i].addEventListener('click', closeMobileSubmenu);\n}"
] | [
"javascript",
"html",
"frontend"
] |
[
"Google Smart Home Action not showing up in \"Explore All Actions\"",
"I created a Google Smart Home Action, but it has not been submitted for public. Previously I was able to view it in https://assistant.google.com/explore/?hl=en-US. However, as of today it does not show up anymore. I did not change any configurations to it."
] | [
"actions-on-google",
"google-smart-home"
] |
[
"How do I show an old FB app review submission?",
"Last year we submitted a Facebook app for review and our use of user_likes was approved as an item. I didn't keep a record of the text I used to describe how we use user_likes. Now I need to submit a very similar app for a different customer. Is there a way to dig up the old approval form contents?"
] | [
"facebook",
"facebook-graph-api",
"facebook-graph-api-v2.2"
] |
[
"What's the most brilliant use of templates you've ever encountered?",
"We all know the usual use of templates to design containers and we all know that you can do things with templates that will make your head spin.\n\nWhen I first encoutered static polymorphism I was really struck on what you can do with templates. It's obvious that templates are useful for more than for designing containers. I bought Andrei's \"Modern C+ Design\" but sadly haven't yet found the time or concentration to read it but I'm sure it offers a wealth of brilliant uses of templates.\n\nIMHO this is also a very clever use of templates.\n\nWhat's the most ingenious use of templates you've ever encountered?"
] | [
"c++",
"templates"
] |
[
"Converting a JApplet to .exe",
"I have a small (Swing) JApplet that runs perfectly in Eclipse: it contains a label, two buttons and a menu, with minimum user interaction (when choosing a menu item, the color of the container changes).\nI converted this to a .jar: \n\n\nI right clicked the class name (Sw3.java)\nSelected \"Export\", then \"Java\", then \"JAR file\"\nNext, I chose current project name as resource to export, doubled clicked the \"Default package\" underneath it, selected desired class name from the list of classes in the right (Sw3.java)\nNext, I ticked \"Export generated class files and resources\", selected the export destination as \"JAR file\" and placed it in \"Documents\" under the name \"Sw3.jar\". I also selected \"Compress the contents of the JAR file\".\nIn the next screen I checked \"Export class file with compile errors\" and \"Export class file with compile warnings\" \n\n\nI heard the right way to obtain an exe file is to convert a .jar into .exe so I used the \"Launch4j\" application with the .jar obtained previously:\n\n\nIn the \"Basic\" panel: specified OUTPUT FILE: C:\\Users\\jerry\\Documents\\Sw3.exe and the JAR file: C:\\Users\\jerry\\Documents\\Sw3.jar. \nProcess priority NORMAL\nHeader type: GUI\nMIN JRE Version: 1.0.0 \nI pressed the \"wheel\" and chose Project.xml and got a succesful confirmation message.\n\n\nI have JRE installed, so the .exe should work, but it doesn't work. What did I do wrong? I would start by investigating if the .JAR was correctly obtained, is that a good approach and how would I check that? Thank you!\n\nPS: Upon being advised to use JFrame instead of JApplet, I did that and still nothing happens when I double click the .exe in order to open it. This makes me suspect there is something wrong in the steps I described."
] | [
"java",
"eclipse"
] |
[
"Wtforms escaping value argument containing backbone js template while rendering field",
"I am using Flask, WTForms and Backbone.js to create my app. I am working with Backbonejs for first time.\n\nI have created a Backbone js template to display data and its corresponding form.\n\n <%= my_field1 %>\n <%= my_field2 %>\n <form>\n <input type=\"text\" value=\"<%= my_field1 %>\"/>\n <input type=\"text\" value=\"<%= my_field2 %>\"/>\n </form>\n\n\nI am using WTForms and Jinja2 to render my form. To give initial value I am doing this\n\n {{ field1(value=\"<%= my_field1 %>\") | safe }}\n {{ field1(value=\"<%= my_field1 %>\") | safe }}\n\n\nThis is a source of problem as <% is escaped while rendering. How can I stop wtforms/jinja from escaping this?"
] | [
"backbone.js",
"flask",
"underscore.js",
"jinja2",
"wtforms"
] |
[
"Falling into a catch clause in CIL",
"For a try block in CIL, I'm aware that you can enter a catch handler by throwing an exception in the protected block such as:\n\ntry {\n newobj Exception\n throw\n leave EX1\n} catch {\n pop\n ldstr \"catchblock\"\n call WriteLine\n} finally {\n ldstr \"finallyblock\"\n call WriteLine\n}\n\nEX1: \n\n\nthe throw statement will transfer control to the catch clause, which \npops off the exception.\n\nMy concern(/curiosity) is whether this could be optimized so execution goes \nto the catch block not through a throw, but by \"falling\" into it via increment the PC. Something like this:\n\ntry {\n newobj Exception\n} catch {\n pop\n ldstr \"catchblock\"\n call WriteLine\n} finally {\n ldstr \"finallyblock\"\n call WriteLine\n}\n\nEX1: \n\n\nIs this valid CIL? Is it possible to get to a catch handler block without using a throw statement?"
] | [
"c#",
"cil"
] |
[
"Image Extraction : uri is too long",
"I am working on Image Extraction Software from A WebPage . have created a function \n\n public static void GetAllImages()\n {\n\n WebClient x = new WebClient();\n string source = x.DownloadString(@\"http://www.bbc.com\");\n\n var document = new HtmlWeb().Load(source);\n var urls = document.DocumentNode.Descendants(\"img\")\n .Select(e => e.GetAttributeValue(\"src\", null))\n .Where(s => !String.IsNullOrEmpty(s));\n\n document.Load(source);\n\n\n }\n\n\nIt says \"Uri is too long \" ..\n\nI tried to use Uri.EscapeDataString .. But not getting idea where to put it \n\nAny Help would be appreciated"
] | [
"c#",
"uri",
"image-extraction"
] |
[
"why spring boot not use application.properties in test resources first?",
"I have a special properties file in test resources directory\n\n└── test\n ├── java\n │ └── com\n │ └── inter3i\n │ ├── dao\n │ │ └── FooMapperTest.java\n └── resources\n └── application.properties\n\n\nin this application.properties file I specify the MySQL URL. \n\nspring.datasource.url=jdbc:mysql://139.224.xxx.xxx/foo?useSSL=false\n\n\nthen I execute a test\n\nmvn test -Dtest=com.foo.reportapi.dao.FooMapperTest\n\n\nbut it is failed because\n\norg.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure\n\nThe last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.\n at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:289) ~[spring-jdbc-4.3.10.RELEASE.jar:4.3.10.RELEASE]\n\n\nbut actually the MySQL URK is OK, why does it have this error? From wireshark I know it actually connected to another URL\n\nspring.datasource.url=jdbc:mysql://192.168.0.25/foo\n\n\nwhich configured in application-default.properties\n\nsrc\n├── main\n│ └── resources\n│ ├── application-default.properties\n\n\nSo why is it so counterintuitive? I think test classes should use application.properties in test resources first.\n\nIn addition I have to use wireshark to find which URL it is connecting to, how could I get Spring Boot to output MySQL URL info explicitly?"
] | [
"spring-boot"
] |
[
"Exporting Data Table to Excel using OLEDB throws too many fields defined error",
"We have a data table with 2500 columns and 2000 rows. When we try to export using OLEDB i am getting an error \"too many fields defined\". I cant use Excel Inter op, since it consumes more time. Is there any other way to fix this issue\n\nusing (OleDbConnection con = new OleDbConnection(\"Provider=Microsoft.ACE.OLEDB.12.0;\" + \"Data Source=\" + fileName + \";\" + \"Extended Properties=\" + \"\\\"\" + \"Excel 8.0;HDR=NO;\" + \"\\\"\"))\n {\n con.Open();\n OleDbCommand cmdInsert;\n if (createTable || !File.Exists(fileName))\n {\n sql = \"CREATE TABLE \" + tableName + \" (\";\n for (int i = 0; i < tbl.Columns.Count; i++)\n {\n sql += \"[\" + tbl.Columns[i].ColumnName + \"]\";\n if (i + 1 == tbl.Columns.Count) //Here we decide should we close insert command or appebd another create column command\n sql += \" \" + GetColumnType(tbl.Columns[i]) + \")\"; //Close insert\n else\n sql += \" \" + GetColumnType(tbl.Columns[i]) + \",\"; //there is more columns to add\n }\n }\n if (!String.IsNullOrEmpty(sql))\n {\n cmdInsert = new OleDbCommand(sql, con);\n cmdInsert.ExecuteNonQuery();\n }\n foreach (DataRow row in tbl.Rows)\n {\n //Dodati parametre na comandu\n string values = \"(\";\n for (int i = 0; i < tbl.Columns.Count; i++)\n {\n if (i + 1 == tbl.Columns.Count)\n {\n if (tbl.Columns[i].DataType == System.Type.GetType(\"System.Decimal\") ||\n tbl.Columns[i].DataType == System.Type.GetType(\"System.Int64\") ||\n tbl.Columns[i].DataType == System.Type.GetType(\"System.Double\"))\n values += String.IsNullOrEmpty(row[i].ToString()) ? \"0)\" : Convert.ToDecimal(row[i]).ToString(\"#0.00\", _infoEn) + \")\";\n else\n values += \"'\" + System.Security.SecurityElement.Escape(row[i].ToString()) + \"')\";\n\n //values += \"'\" + \"test\" + \"')\";\n }\n else\n {\n if (tbl.Columns[i].DataType == System.Type.GetType(\"System.Decimal\") ||\n tbl.Columns[i].DataType == System.Type.GetType(\"System.Int64\") ||\n tbl.Columns[i].DataType == System.Type.GetType(\"System.Double\"))\n values += String.IsNullOrEmpty(row[i].ToString()) ? \"0,\" : Convert.ToDecimal(row[i]).ToString(\"#0.00\", _infoEn) + \",\";\n else\n values += \"'\" + System.Security.SecurityElement.Escape(row[i].ToString()) + \"',\";\n\n //values += \"'\" + \"test\" + \"',\";\n }\n }\n string sqlInsert = String.Format(\"Insert into [{0}$] VALUES {1}\", tableName, values);\n cmdInsert = new OleDbCommand(sqlInsert, con);\n\n cmdInsert.ExecuteNonQuery();\n }\n }"
] | [
"c#",
".net",
"oledb"
] |
[
"Is Locking this instance method required",
"For the question that I have probably I need more convincing answer to implement in my solution. I am not sure whether my understanding is correct. Following are the implementation details:\n\nIn a class, in the main method, where the class object C is created to call an instance method that takes integer as a parameter:\n\npublic <AnyClass> MyMethod(int classVar)\n{\n return new <AnyClass>(classVar);\n // Can have more implementation, using the parameter passed\n}\n\n\nIn the main, I want this method to be called on the multiple threads, using the same class object, the parameter would be the value supplied by for loop that starts the threads to execute. Now in memory we are executing same method, does this needs any kind of locking. In my view No, I have tested, but I am not sure in theory why, wouldn't different threads mess up with each other's parameter value, in my implementation it doesn't seems the case.\n\nOnly thing I cannot guarantee, is which thread access and returns first as that would not be in the order, but if I do not care about it, is this implementation correct.\n\nPlease note, this is an attempt to describe the issue in a stand alone manner, I have similar implementation as part of a complex project.\n\nAny suggestions / pointers would be great. Please let me know if you need a clarification."
] | [
"c#",
".net",
"multithreading"
] |
[
"Android phonegap application goes blank",
"I am developing a android phonegap application. I am facing strange issue on my Asus tab (android version 4.3). If I go to home screen of the phone when the app is running and then open my app from running apps, I get a blank white screen. The text and images appears when I tap on the screen. Issue is only on Asus andoird 4.3. I tried same thing on a galaxy note3 neo android version 4.4.2 and it works fine (on returning to the app from recently opened apps, the app loads correctly).\n\nWhat can be the issue?"
] | [
"android",
"html",
"cordova"
] |
[
"sqlQuery string wtih Ajax",
"I'm trying to do an Ajax call with a query string however I got halfway through now stuck on what to do, I'm trying to update a SQL table with javascript sortable function. once the item has moved up or down then I pass through the ajax and get it to update in the SQL. (well that what I'm trying to do anyway)\nWas wondering if you guys can help.\n\n\r\n\r\n <script>\r\n $(\"#tableBody\").sortable({\r\n connectWith: \"#tableBody\",\r\n update: function (event, ui) {\r\n // this.id = #tableBody\r\n // ui.item = Dragged item\r\n console.log(ui.item.attr(\"data-id\"));\r\n console.log(ui.item.attr(\"data-prod-id\"));\r\n console.log(ui.item.index());\r\n $.get('shop_prod_options_update_sort_order.aspx?id=' + id + '&prodid=' + prodid + '&sortorder=' + sortorder);\r\n }\r\n });\r\n </script>\r\n<Script Language=\"VB\" RunAt=\"Server\">\r\n\r\n Dim intOptionId As Integer = 1\r\n Dim intProdId As Integer = 1\r\n Dim intNewSortOrder As Integer = 0\r\n Dim intOldSortOrder As Integer = 0\r\n\r\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\r\n\r\n If IsNumeric(Request.QueryString(\"id\")) Then\r\n intOptionId = Val(Request.QueryString(\"id\"))\r\n End If\r\n\r\n If Request.QueryString(\"sortorder\") = \"sortorder\" Then\r\n intOptionId = True\r\n Else\r\n intOptionId = False\r\n End If\r\n\r\n If Not IsPostBack Then\r\n\r\n UpdateList()\r\n\r\n End If\r\n\r\n End Sub\r\n\r\n Private Sub UpdateList()\r\n\r\n Dim connDBConnection As SqlConnection = Nothing\r\n Dim commDBCommand As SqlCommand\r\n Dim strSQLQuery As String = \"\"\r\n\r\n '''''''''''''''''''''''''''''''\r\n Try\r\n\r\n strSQLQuery = \"SELECT option_order FROM shop_option WHERE option_id = @option_id\"\r\n Using connConnnection As New SqlConnection(Database.GetDatabaseConnString)\r\n connConnnection.Open()\r\n Using commCommand As New SqlCommand(strSQLQuery,connConnnection)\r\n commCommand.Parameters.AddWithValue(\"@option_id\", intOptionId)\r\n intOldSortOrder = commCommand.ExecuteScalar()\r\n End Using\r\n End Using\r\n\r\n\r\n If intOldSortOrder>intNewSortOrder Then\r\n strSQLQuery = \"UPDATE option_order FROM shop_option WHERE option_id = @option_id\", intOptionId\r\n strSQLQuery += \"SET option_order = option_order + 1 FROM shop_option WHERE option_id = @option_id\", intOptionId\r\n Else\r\n strSQLQuery = \"UPDATE option_order FROM shop_option WHERE option_id = @option_id;\", intOptionId\r\n strSQLQuery += \"SET option_order = option_order - 1 FROM shop_option WHERE option_id = @option_id\", intOptionId\r\n End If\r\n\r\n Using connConnnection As New SqlConnection(Database.GetDatabaseConnString)\r\n connConnnection.Open()\r\n Using commCommand As New SqlCommand(strSQLQuery,connConnnection)\r\n commCommand.Parameters.AddWithValue(\"@option_id\", intOptionId)\r\n intOldSortOrder = commCommand.ExecuteScalar()\r\n End Using\r\n End Using\r\n\r\n\r\n Catch ex As Exception\r\n\r\n Finally\r\n Database.Disconnect(connDBConnection)\r\n End Try\r\n\r\n End Sub\r\n</script>\r\n\r\n\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n <head id=\"Head1\" runat=\"server\">\r\n \r\n </head>\r\n\r\n <body>\r\n <form id=\"form1\" runat=\"server\">\r\n \r\n <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" />\r\n \r\n \r\n </form>\r\n </body>\r\n</html>"
] | [
"javascript",
"sql",
"ajax",
"vb.net"
] |
[
"How to save base64 image using node js?",
"I am saving the base64 image using nodejs, it save my image at exact path, but show me the error.\n\nPlease help me to find the error.\n\n\n\nHere is my code\n\nvar express = require('express');\nvar router = express.Router();\n\nconst fs = require('fs');\nconst mime = require('mime');\n\n\nconst path = './uploads';\n\nrouter.post('/register', (req, res, next) => {\n const base64Image = req.body.image;\n\n const matches = base64Image.match(/^data:([A-Za-z-+\\/]+);base64,(.+)$/);\n response = {};\n if (matches.length !== 3) {\n return new Error('Invalid input String');\n }\n\n response.type = matches[1];\n response.data = new Buffer(matches[2]);\n let decodedImg = response;\n let imageBuffer = decodedImg.data;\n let type = decodedImg.type;\n let extension = mime.extension(type);\n let fileName = 'image.' + extension;\n\n try {\n fs.writeFileSync(path + '/' + fileName, imageBuffer, 'utf8');\n return res.send({ status: 'success' });\n } catch (e) {\n next(e);\n }\n\n return;\n\n});\n\nmodule.exports = router;\n\n\n\nAny solution appreciated!"
] | [
"node.js",
"express"
] |
[
"Drupal 8 multiple sub domains using same Database and different design",
"Requirement is multiple sub domains using same Database and different design\nFor example my main site URL is www.mysite.com.\nMy requirement is\nwww.sub1.mysite.com\n www.sub2.mysite.com\n www.sub3.mysite.com\n\nI also tried Drupal Domain\n\nI am using drupal 8.6.\n\nHow can I achieve this requirement."
] | [
"drupal",
"subdomain",
"drupal-multi-domain"
] |
[
"Running java jar outside eclipse requiring files in bin dir",
"I'm developing using eclipse and I'm using an API that requires files to be in the /bin directory (which path does that mean in java I don't know). I exported my app as a jar and put the required files in the same directory as the jar file, but when I run the app using Terminal, the app is not able to locate the files. I'm unable to understand this paths issue.\n\nI'm running the app with this command: \n\njava -jar app.jar\n\n\nI also changed the terminal directory into the directory that contains the jar file and I tried with:\n\njava -cp . -jar app.jar\n\n\nThat didn't work.\n\nEdit:\nThe error is that the application is not able to locate the required files. In Eclipse I had to put the files in the /bin dir in order for the API to locate them.\n\nHere's the full exception:\n\nException in thread \"main\" java.io.IOException: failed to find resource /cmu/arktweetnlp/50mpaths2\n at cmu.arktweetnlp.util.BasicFileIO.getResourceReader(BasicFileIO.java:233)\n at cmu.arktweetnlp.impl.features.WordClusterPaths.<init>(WordClusterPaths.java:29)\n at cmu.arktweetnlp.impl.features.FeatureExtractor.initializeFeatureExtractors(FeatureExtractor.java:146)\n at cmu.arktweetnlp.impl.features.FeatureExtractor.<init>(FeatureExtractor.java:30)\n at cmu.arktweetnlp.Tagger.loadModel(Tagger.java:39)\n at com.POSTest.main(POSTest.java:22)\n\n\nTerminal content:\n\nMacBook-Pro:ArabicTwitterEye ma$ ls\nCSVArabicTwitterEye.jar log resources\ncmu profiles tweets.csv\nMacBook-Pro:ArabicTwitterEye ma$ \n\n\nHere's the simple java code:\n\npublic static void main(String[] args) {\n Tagger tagger = new Tagger();\n String modelFilename = \"model.20120919\";\n\n System.out.println( \"Loading model ...\" );\n try {\n tagger.loadModel(modelFilename);\n } catch (IOException e) {\n e.printStackTrace();\n }\n System.out.println( \"Done loading model.\" );\n }\n\n\nHere's the source code from the API:\n\npublic class WordClusterPaths implements FeatureExtractorInterface {\n\n /** TODO this should be moved into config somehow **/\n public static String clusterResourceName = \"/cmu/arktweetnlp/50mpaths2\";\n\n public static HashMap<String,String> wordToPath;\n\n public WordClusterPaths() throws IOException {\n// log.info(\"Loading clusters\");\n\n //read in paths file\n BufferedReader bReader = BasicFileIO.getResourceReader(clusterResourceName);\n String[] splitline = new String[3];\n String line=BasicFileIO.getLine(bReader);\n wordToPath = new HashMap<String,String>(); \n while(line != null){\n splitline = line.split(\"\\\\t\");\n wordToPath.put(splitline[1], splitline[0]);\n line = BasicFileIO.getLine(bReader);\n } \n// log.info(\"Finished loading clusters\");\n }\n\n\nAlso check this:\n\npublic static BufferedReader getResourceReader(String resourceName) throws IOException {\n assert resourceName.startsWith(\"/\") : \"Absolute path needed for resource\";\n\n InputStream stream = BasicFileIO.class.getResourceAsStream(resourceName);\n if (stream == null) throw new IOException(\"failed to find resource \" + resourceName);\n //read in paths file\n BufferedReader bReader = new BufferedReader(new InputStreamReader(\n stream, Charset.forName(\"UTF-8\")));\n return bReader;\n }"
] | [
"java",
"eclipse"
] |
[
"Time event was sent?",
"In JavaFx, is there any reliable way to know at what time an event was posted ? \n\nAnd since this question is too short for stackoverflow, I elaborate somwhat. In asychronous event systems, which I believe javafx is, events get posted on a queue and then at a later stage handled. The time between posting and handling is unknown, allthough it is estimated to be small. Nevertheless, there are no guarantees that this time is indeed small. Therefor I would really like to know whether it is possible to know the time of posting the event. E.g: when the user actually clicked the button (as opposed to when the program looks at it)."
] | [
"javafx"
] |
[
"Pattern to continuously listen to AWS SQS messages",
"I have a simple class named QueueService with some methods that wrap the methods from the AWS SQS SDK for Java. For example:\n\npublic ArrayList<Hashtable<String, String>> receiveMessages(String queueURL) {\n List<Message> messages = this.sqsClient.receiveMessage(queueURL).getMessages();\n\n ArrayList<Hashtable<String, String>> resultList = new ArrayList<Hashtable<String, String>>();\n for(Message message : messages) {\n Hashtable<String, String> resultItem = new Hashtable<String, String>();\n resultItem.put(\"MessageId\", message.getMessageId());\n resultItem.put(\"ReceiptHandle\", message.getReceiptHandle());\n resultItem.put(\"Body\", message.getBody());\n resultList.add(resultItem);\n }\n return resultList;\n }\n\n\nI have another another class named App that has a main and creates an instace of the QueueService. \n\nI looking for a \"pattern\" to make the main in App to listen for new messages in the queue. Right now I have a while(true) loop where I call the receiveMessagesmethod:\n\nwhile(true) {\n messages = queueService.receiveMessages(queueURL); \n for(Hashtable<String, String> message: messages) {\n String receiptHandle = message.get(\"ReceiptHandle\");\n String messageBody = message.get(\"MessageBody\");\n System.out.println(messageBody);\n queueService.deleteMessage(queueURL, receiptHandle);\n }\n }\n\n\nIs this the correct way? Should I use the async message receive method in SQS SDK?"
] | [
"java",
"amazon-web-services",
"sdk",
"amazon-sqs"
] |
[
"Pull one file from Git without having to clone the entire repository",
"I have a Git repository named \"test\" inside which I have four files and sub-directory named \"test2\". \n\nSo the path would be /test2/file.txt \n\nI would like to pull (remotely) just the sub-directory with all of its content (/test2/file.txt) without cloning \"test\". Is this possible?"
] | [
"git"
] |
[
"DNN 7 - SMTP Test in host settings work, but can't send emails in contact forms",
"All the sites on this DNN installation stopped sending emails yesterday. When you try and test SMTP in host settings, it sends the test email without any issues.\n\nAt first I thought my IP might be blacklisted, but then surely the SMTP test would also fail?"
] | [
"dotnetnuke",
"dotnetnuke-7"
] |
[
"Race: callbacks and removing callbacks during unload of kext in OSX",
"There doesn't appear to be synchronization between establishing/removing callbacks (e.g. kauth_unlisten_scope) and the callbacks themselves (in the xnu codebase, yes, I know, it's dated). This puts the burden of tracking/draining callbacks and synchronizing with calls on the extension itself. But this is problematic as well in that there is a window in noting that a thread has exited the callback AND actually returning out of the extension code.\n\nIs there any pattern that gives a correct avoidance of this race? Or, is there any documentation from Apple that indicates they've synchronized this correctly?"
] | [
"macos",
"kernel",
"xnu",
"kernel-extension"
] |
[
"Generate XML from schema",
"I have a large XSD file and I must build a valid XML.\nThe problem is that I don't have a demo XML, and I'm new to XML so I would like to know if it's possible to generate a sample file with random data according to the specifications.\n\nIf you know a tool, a tutorial or something that could help me to start in the right way..."
] | [
"xml",
"xsd",
"schema"
] |
[
"how to add Upload Progress bar to files upload in Angular6",
"I used this code to upload files in Angular 6.\n\nEverything works fine but I need to add the progress bar to the code. After searching from stackoverflow, I saw this code below but being new to angular or angular6 I do not know how to integrate it or make the progress bar works with the angular form submission.\n\nthis.uploader.onProgressItem = (progress: any) => { \n console.log(progress['progress']); \n};\n\nthis.uploader.onSuccessItem = (progress: any) => {\n console.log('I receive the response file posted in API'); \n};\n\n\nProgress Bar in ng2-file-upload in Angular 6\n\nBelow is the code\n\napp.component.ts:\n\nimport { Component, OnInit } from '@angular/core';\nimport { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';\n\nconst URL = 'http://localhost:3000/api/upload';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent implements OnInit {\n title = 'app';\n\n public uploader: FileUploader = new FileUploader({ url: URL, itemAlias: 'photo' });\n\n ngOnInit() {\n this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };\n this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {\n console.log('ImageUpload:uploaded:', item, status, response);\n alert('File uploaded successfully');\n };\n }\n}\n\n\napp.component.html:\n\n<input type=\"file\" name=\"photo\" ng2FileSelect [uploader]=\"uploader\" />\n<button type=\"button\" class=\"btn btn-success btn-s\"\n (click)=\"uploader.uploadAll()\" \n [disabled]=\"!uploader.getNotUploadedItems().length\" >\n Upload an Image \n</button>"
] | [
"javascript",
"angular"
] |
[
"Performing Arbitrarily Large Bit Rotations on an Integer",
"I am trying to perform very large bit rotations on non-negative 16-bit integers in Python, however it is very slow. I tried optimizing the process by shifting it by the modulo of 16, but it leaves a bunch of zeros at the end of it. Is there any way to fix this? Can we truncate the binary to a 16 bit window? Are there any other methods to improve performance? I can not use any external libraries.\n\nAn example of the operation is 23748 >> 8857328954.\n\nHere is an example of some code I tried:\n\nx = 35233\ny = 738337234 % 16\nx >> y"
] | [
"python",
"optimization",
"bit-manipulation",
"bit-shift"
] |
[
"Material-UI: ListItem onClick not called",
"I am working with React and Material-UI. I am trying to display a list and call a function when one of the items of the list is clicked. \nThe code below is a simplified version of my code, but it should contain all the lines concerning the issue.\nThe onClick function is apparently never called. What am I missing?\n\nApp.js:\n\nimport React, { Component } from 'react';\nimport './App.css';\nimport Grid from '@material-ui/core/Grid';\nimport Map from './Map.js';\n\nclass App extends Component {\n\n render() {\n\n return (\n <div >\n <Grid container spacing={24}>\n <Grid item xs={3}>\n Column text\n </Grid>\n <Grid item xs={9}>\n <Map/>\n </Grid>\n\n </Grid>\n </div>\n\n );\n }\n}\n\nexport default App;\n\n\nMap.js:\n\nimport React from 'react';\nimport List from '@material-ui/core/List';\nimport ListItem from '@material-ui/core/ListItem';\nimport ListItemText from '@material-ui/core/ListItemText';\n\n\nclass Map extends React.Component {\n\n constructor(props) {\n super(props);\n\n this.state = {\n sensorsList: {\n isLoaded: false,\n data: null,\n },\n };\n }\n\n componentDidMount() {\n // retrieve list of sensors\n fetch(\"https://api-of-things.plenar.io/api/sensors?size=10000\")\n .then(res => res.json())\n .then(\n (result) => {\n this.setState({\n sensorsList: {\n isLoaded: true,\n data: Object.keys(result.data).map(key => result.data[key].path),\n }\n });\n },\n // Note: it's important to handle errors here\n // instead of a catch() block so that we don't swallow\n // exceptions from actual bugs in components.\n (error) => {\n this.setState({\n error\n });\n }\n )\n }\n\n selectSensor(name) {\n console.log(name);\n }\n\n _renderSensorsList() {\n const {sensorsList} = this.state;\n\n return sensorsList.isLoaded && (\n <div style={{\n position: 'absolute', \n zIndex: 1, \n pointerEvents: 'none', \n right: 10, \n top: 10,\n backgroundColor: 'white',\n }}>\n\n <List component=\"nav\">\n { sensorsList.data.map(key => \n <ListItem button key={key} onClick={() => this.selectSensor(\"ciao\")} >\n <ListItemText primary={key} />\n </ListItem>\n )}\n </List>\n\n </div>\n );\n }\n\n render() {\n const {sensorsList, selectedSensor} = this.state;\n\n return (\n <div>\n { this._renderSensorsList() }\n </div>\n );\n }\n}\n\nexport default Map;"
] | [
"reactjs",
"list",
"onclick",
"material-ui",
"listitem"
] |
[
"\"Cannot resolve symbol 'WifiNetworkSpecifier'\"",
"I have an error \"Cannot resolve symbol 'WifiNetworkSpecifier'\". Import is not found, path in the documentation dont exist.\nI tried to rebuild project, invalidate caches.\nWhat should i do?"
] | [
"android",
"android-studio"
] |
[
"How to use scala.None from Java code",
"Possible Duplicate:\n Accessing scala.None from Java \n\n\n\n\nIn Java you can create an instance of Some using the constructor, i.e. new Some(value), but None has no partner class. How do you pass None to a Scala function from Java?"
] | [
"java",
"scala",
"singleton",
"scala-java-interop"
] |
[
"signtool fails to find certificate on Windows 10, due to private key filter",
"I am the developer of UniversalADBDriver, a tool that creates a self signed Android USB driver on the user's computer.\n\nSource code of installer and setup package:\nhttps://github.com/koush/UniversalAdbDriver\n\nThe tool generates a keypair and adds a certificate to the user's key store, then signs the driver files. This worked fine until Windows 10, where it inexplicably stopped working. I ran the command line manually:\n\nThe following certificates were considered:\n Issued to: UniversalADB\n Issued by: UniversalADB\n Expires: Fri Aug 25 17:00:00 2017\n SHA1 hash: C8701DF4CDC7DD75813400AD2B3B4C2EFDA4E662\n\nAfter EKU filter, 1 certs were left.\nAfter expiry filter, 1 certs were left.\nAfter Private Key filter, 0 certs were left.\nSignTool Error: No certificates were found that met all the given criteria.\n\n\nOn Windows 10, the certificate is being filtered out by the \"Private Key filter\". No idea what that is, no documentation anywhere on it.\n\nUPDATE\n\nI've discovered that neither makecert.exe or X509Store.add can write certificates/keys to the Current User store when invoked through the installer on Windows 10. However, the certificates in the Local Machine store are placed correctly. I'm not sure why that is. So basically, the private key is not being placed in the store properly so the signature fails. Running the same steps manually on the command line works. I still need to figure out why the private key is not being persisted in the store however."
] | [
"windows",
"driver-signing"
] |
[
"What are the specifics of \"allocated\" in a PHP out of memory error",
"Note: There are a number of questions dealing with the \"out of memory\" error message, but I haven't seen an answer to the specifics of the \"allocated\" definition. \n\nIn any stat, you have to know what is being measured. What does \"allocated\" measure specifically?\n\nMy client's hosting package supposedly has 256MB of PHP memory, based on the php.ini setting. The webhost does allow up to 256MB.\n\nExample: Fatal error: Out of memory (allocated 118489088) (tried to allocate 64\nbytes) in\n/htdocs/www/wp-content/plugins/all-in-one-event-calendar/vendor/lessphp/lessc.inc.php\non line 293\n\nDoes allocated mean the memory for all PHP functions or just for the particular process that is throwing the error?"
] | [
"php",
"memory"
] |
[
"Apache Log Format adds quotes and backslash",
"In httpd.conf I've set the LogFormat to: \n\nLogFormat \"%t %{client-ip}i \\\"%{X-Forwarded-For}i\\\" %l %u \\\"%r\\\" %>s %b \\\"%{Referer}i\\\" \\\"%{User-Agent}i\\\" sessid=%{SESSID}C **guid=%{guid}C** req_guid=%{X-Hcom-Info}o\" netscaler\n\n\nThe problem is with the way the guid cookie value gets logged: \nguid=\\\"357ceacc-d2fb-458d-bc53-c6d1384d47dd:1107014198\\\"\n\nIt adds \\\" \\\" around the guid - maybe because of the :1107014198 part. \n\nHow do i get apache to log the guid as:\nguid=357ceacc-d2fb-458d-bc53-c6d1384d47dd:1107014198\ni.e with out the \\\" \\\""
] | [
"apache",
"logging"
] |
[
"Getting 'access denied' when trying to access an airport RSS feed",
"I'm trying to access an airport RSS feed using the curl library in C. Whenever I try to access it, though, I get access denied error. The following is the code I'm using. It's almost identical to the example code at https://curl.haxx.se/libcurl/c/simple.html:\n\n#include <stdio.h>\n#include <curl/curl.h>\n\nint main(int argc, char **argv)\n{\n CURL *curl;\n CURLcode res;\n char *feed_addr = \"http://w1.weather.gov/xml/current_obs/KUCP.rss\";\n //airport not in the state I live\n\n curl = curl_easy_init();\n if(curl) {\n curl_easy_setopt(curl, CURLOPT_URL, feed_addr);\n\n curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);\n\n // Perform the request, res will get the return code\n res = curl_easy_perform(curl);\n // Check for errors\n if(res != CURLE_OK) {\n fprintf(stderr, \"curl_easy_perform() failed: %s\\n\",curl_easy_strerror(res));\n }\n\n // always cleanup\n curl_easy_cleanup(curl);\n }\n return 0;\n}\n\n\nI've tried this with other websites besides weather.gov (google, youtube, mit.edu) and they all work just fine. But when I tried this, even with other airport RSS feeds (which can be found at http://w1.weather.gov/xml/current_obs/seek.php?state=pa&Find=Find), I get the same access denied error. I also get the same error when I set feed_addr to any weather.gov page. \n\nTo make this stranger, when I tried to access the feed using Python3's urllib.request module, it worked just fine. I can also access it just fine with Google Chrome. So I can rule out the idea that it doesn't want me accessing the feed.\n\nIs there something that I'm missing? Is there a way to get the feed via the curl library? Or is there a way using a different library?"
] | [
"c",
"curl",
"rss",
"libcurl"
] |
[
"how to test if all values in a two dimensional array are empty with php",
"i have a situation where in oder to save data from a form to the session i have to check if the $errors array which stores errors genarated by the checks done on the form data is empty.\n\nthe problem is the array is an associative array an when i use the 'empty function' to test if the array is empty it always returns flase even when all the values in the array are empty, what can i do to check if the associative array is empty, below is my code\n\nsession_start();\n\n// define errors array \n$errors = array(\n'name' => \"\",\n'username' => \"\",\n'age' => \"\");\n\n// check and sanitize form data\nif (isset($_POST[\"name\"]) and empty($_POST[\"name\"])) {\n $errors['name'] = \"your name is needed\";\n }else{\n $_POST['name'] = test_input($_POST['name']);\n if(!preg_match(\"/^[a-zA-Zéèàêâùïüë.',_ ]+$/\",$_POST['name'])) {\n $errors['name'] = \"only letters and white spaces accepted\";\n }else{\n $validator++; \n }\n }\n\n if (isset($_POST[\"username\"]) and empty($_POST[\"username\"])) {\n $errors['username'] = \"your username is needed\";\n }else{\n $_POST['username'] = test_input($_POST['username']);\n if(!preg_match(\"/^[a-zA-Zéèàêâùïüë.',_ ]+$/\",$_POST['username'])) {\n $errors['username'] = \"only letters and white spaces accepted\";\n }else{\n $validator++; \n }\n }\n\n if (isset($_POST[\"age\"]) and empty($_POST[\"age\"])) {\n $errors['age'] = \"age is needed\";\n }else{\n $_POST['age'] = test_input($_POST['age']);\n if(!preg_match(\"/^[1-90]+$/\",$_POST['age'])) {\n $errors['age'] = \"only numbers accepted\";\n }else{\n $validator++; \n }\n }\n// check if data is correct and save to session\nif(empty($errors)){\n // save data in session \n $_SESSION['name'] = $_POST['name'];\n $_SESSION['username'] = $_POST['username'];\n $_SESSION['age'] = $_POST[\"age\"];\n}else{\n session_destroy();\n header(\"location :index.php\");\n}`"
] | [
"php",
"arrays"
] |
[
"Creating a virtual environment is not working with Python 3.8 on Windows using built-in venv",
"I have tried creating a 'venv' in both Python 3.7 and 3.8 with the same result. The command I am using is\n\npython3.8 -m venv C:\\Users\\xxxxxx\\PycharmProjects\\TestVenv\\venv\n\nI get an error in the output\nError: [WinError 2] The system cannot find the file specified\n\nThe directories you would expect to see are created, however, that 'activate.bat' script and many of the usual scripts seen in the Scripts directory are not created.\n\n Directory: C:\\Users\\xxxxxx\\PycharmProjects\\TestVenv\\venv\n\n\n Mode LastWriteTime Length Name\n ---- ------------- ------ ----\n d----- 28/11/2019 04:46 Include\n d----- 28/11/2019 04:46 Lib\n d----- 28/11/2019 04:46 Scripts\n -a---- 28/11/2019 04:46 122 pyvenv.cfg\n\n\nThe contents of the Scripts directory are:\n\n Directory: C:\\Users\\xxxxxx\\PycharmProjects\\TestVenv\\venv\\Scripts\n\n\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 28/11/2019 04:46 416840 python.exe\n-a---- 28/11/2019 04:46 415816 pythonw.exe\n\n\nOf course, this means I cannot activate my virtual environment. I am not sure if it is relevant, but I am running this in a VDI. I have local admin privileges and my colleagues, with the same privilges and set-ups, are able to get their virtual environments working.\n\nEDIT:\n\nFIXED\n\nFixed by uninstalling an Anaconda installation I had. Not sure why this was clashing with my standard Python installation."
] | [
"python",
"python-3.x",
"python-venv"
] |
[
"Bidirectional Map in .NET",
"Is there a .NET data structure I could use for bidirectional lookup?\n\nHere's the problem: Serialization. My object contains a field which points to one of 10 predefined static objects. When writing to the file, I write a single character representing which of the 10 objects is being referenced. At this point, I need a lookup datastructure which will allow me to get the character code based on the object being referenced. When deserializing, I need to do the reverse. I can think of a lot of other places where I could use such a data structure."
] | [
".net",
"data-structures",
"collections",
"containers"
] |
[
"compiling sendmmsg get undefined reference to `sendmmsg'?",
"I tried to compile the following code witch send multiple massages using sendmmsg() in c, but it gives me a compiler error \" undefined reference to `sendmmsg' \". I tried to google it, but not found any result!\n\nI got the code from this page: http://manpages.courier-mta.org/htmlman2/sendmmsg.2.html\n\nand I need more resources about recvmmsg() to read.\n\n#define _GNU_SOURCE\n#include < netinet/ip.h>\n#include < stdio.h>\n#include < stdlib.h>\n#include < string.h>\n#include < sys/types.h>\n#include < sys/socket.h>\n\nint\nmain(void)\n{\n int sockfd;\n struct sockaddr_in sa;\n struct mmsghdr msg[2];\n struct iovec msg1[2], msg2;\n int retval;\n\n sockfd = socket(AF_INET, SOCK_DGRAM, 0);\n if (sockfd == .1) {\n perror(\"socket()\");\n exit(EXIT_FAILURE);\n }\n\n sa.sin_family = AF_INET;\n sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n sa.sin_port = htons(1234);\n if (connect(sockfd, (struct sockaddr *) &sa, sizeof(sa)) == .1) {\n perror(\"connect()\");\n exit(EXIT_FAILURE);\n }\n\n memset(msg1, 0, sizeof(msg1));\n msg1[0].iov_base = \"one\";\n msg1[0].iov_len = 3;\n msg1[1].iov_base = \"two\";\n msg1[1].iov_len = 3;\n\n memset(&msg2, 0, sizeof(msg2));\n msg2.iov_base = \"three\";\n msg2.iov_len = 5;\n\n memset(msg, 0, sizeof(msg));\n msg[0].msg_hdr.msg_iov = msg1;\n msg[0].msg_hdr.msg_iovlen = 2;\n\n msg[1].msg_hdr.msg_iov = &msg2;\n msg[1].msg_hdr.msg_iovlen = 1;\n\n retval = sendmmsg(sockfd, msg, 2, 0);\n if (retval == .1)\n perror(\"sendmmsg()\");\n else\n printf(\"%d messages sent\\n\", retval);\n\n exit(0);\n}"
] | [
"c"
] |
[
"Rails route clash when using scopes and localization / i18n",
"In order to internationalize my app I would like to have named routes like 'hello_path' automatically translated to '/en/hello' or '/fr/bonjour\" depending on the current I18n.locale. But I encounter a problem (name clash?):\n\nMy routes are:\n\nLostInTranslation::Application.routes.draw do\n root :to => 'home#index' \n scope '/:locale' do\n constraints :locale => 'fr' do\n get 'bonjour' => 'home#hello', :as => 'hello'\n end\n constraints :locale => 'en' do\n get 'hello' => 'home#hello', :as => 'hello'\n end\n end\nend\n\n\nAnd in the ApplicationController I set the locale and pass it to the default url options:\n\nclass ApplicationController < ActionController::Base\n protect_from_forgery\n\n before_filter :set_locale\n\n private\n\n def default_url_options(options={})\n options.merge({ :locale => I18n.locale })\n end\n\n def set_locale\n if params[:locale] and I18n.available_locales.include?(params[:locale].to_sym)\n I18n.locale = params[:locale]\n else\n I18n.locale = I18n.default_locale\n end\n end\nend\n\n\nBut when in a view I use <%= link_to t('hello'), hello_path %> I get this error:\n\nNo route matches {:controller=>\"home\", :locale=>:fr, :action=>\"hello\"}\n\n\nYet rake routes says it is declared:\n\n root / {:action=>\"index\", :controller=>\"home\"}\nhello GET /:locale/bonjour(.:format) {:locale=>\"fr\", :action=>\"hello\", :controller=>\"home\"}\nhello GET /:locale/hello(.:format) {:locale=>\"en\", :action=>\"hello\", :controller=>\"home\"}\n\n\nWould you have any clue about why it's not working or another way to achieve this? I am aware of the i18n_routing gem, but it works by declaring localized routes with different names (en_hello and fr_hello in this example).\n\nThanks!"
] | [
"ruby-on-rails",
"internationalization",
"routes"
] |
[
"How to change the set color in a for loop?",
"My circles change color, but while the smallest one always remains red, the largest does not remain blue. Whenever I attempt to change my code from what it is now, all circles become the same color, and just change shade when the slider is moved. I would like there to just be more shades in between the red and blue as the slider increases. Could you please explain the changes I need to make? I understand everything I'm doing, except the color changing part. \n\npublic class SliderLab1 extends JFrame {\nJSlider slider;\nGPanel graphicsPanel;\n\npublic SliderLab1() {\n super(\"Slider/Shapes Demo\");\n setDefaultCloseOperation(\n JFrame.EXIT_ON_CLOSE );\n\n JPanel outerPanel = new JPanel();\n graphicsPanel = new GPanel(); //for shapes\n JPanel sliderPanel = new JPanel();\n\n setup(sliderPanel);\n\n outerPanel.add(graphicsPanel);\n outerPanel.add(sliderPanel);\n add(outerPanel);\n pack();\n setVisible(true);\n}\n\nprivate void setup(JPanel p) {\n slider = new JSlider(\n JSlider.VERTICAL,4,20,8);\n slider.setMinorTickSpacing(1);\n slider.setMajorTickSpacing(4);\n slider.setPaintTicks(true);\n slider.setPaintLabels(true);\n slider.addChangeListener( new SLstn() );\n\n p.add(slider);\n}\n\nprivate class SLstn implements ChangeListener {\n public void stateChanged(ChangeEvent e) {\n int x = slider.getValue();\n System.out.println(x);\n graphicsPanel.setCount(x);\n graphicsPanel.repaint();\n }\n}\n\nprivate class GPanel extends JPanel {\n int count = 8;\n int size = 400;\n int stepSize = (int)size/count;\n\n public GPanel() {\n setPreferredSize(\n new Dimension(size,size));\n setBackground(Color.BLACK);\n }\n\n public void setCount(int n) {\n count=n;\n stepSize = (int)size/count;\n }\n public void paint(Graphics g) {\n super.paint(g);\n Graphics2D g2d = (Graphics2D)g; \n g2d.setStroke(new BasicStroke(3) ); \n\n for(int i = count; i>=0; i--){\n Color myC = new Color(((255/stepSize)*(stepSize-i)), 0, (255/stepSize)*i );\n g.setColor(myC);\n\n\n for (int j = 0; j <= count; j++) {\n g.drawOval(0,(size-(stepSize*i)),stepSize*i,stepSize*i);\n g.fillOval(0,(size-(stepSize*i)),stepSize*i,stepSize*i); \n }\n\n }\n\n }\n\n}\n\npublic static void main(String[] args) {\n new SliderLab1();\n}\n}"
] | [
"java",
"colors",
"draw",
"fill"
] |
[
"Distinct selection with CouchDB and elasticsearch",
"I have this CouchDB/elasticsearch setup. CouchDB as a storage, elasticsearch for search.\n\nI need to execute this query,\n\nselect distinct name from table\n\n\nin this \"table\"\n\n[\n {name:'david' ... more data},\n {name:'david' ... more data},\n {name:'alex' ... more data}\n {name:'alex' ... more data}\n]\n\n\nto get this:\n\n ['david', 'alex']\n\n\nor this:\n\n [\n {name:'david'},\n {name:'alex'}\n ]\n\n\nor in whatever form but the result of a distinct query.\n\nUsing CouchDB it can be done by this:\n\n// map\nfunction(doc) {\n emit(doc.name);\n}\n\n// reduce\nfunction(keys, values) {\n return null;\n}\n\n\nBut I want to use elasticsearch to do it. There is some info on the web but is not clear.\n\nCan someone point me in the right direction to achieve what I want?"
] | [
"couchdb",
"elasticsearch"
] |
[
"how to exit a sensitivity process upon a condition being met",
"I have code that checks for a reset or a clock and if there is a clock it does some operations on 'buff'. I want to make it so that once 'buff' is equal to 'key', it will exit the process. How can I accomplish this? \n\nPROCESS (clock, reset)\n BEGIN\n IF(reset = '1') THEN\n buff <= (others => '0'); -- set buffer to 0\n op <= (others => '0'); -- set output to 0\n ELSIF(clock'EVENT AND clock = '1') THEN\n op <= ip; --output displays what was inputted\n buff(31 downto 8) <= buff (23 downto 0); --shift least significant 24 bits\n buff(7 downto 0) <= ip; --set empty 8 bits to input\n IF (buff = key) THEN\n success <= '1'; --once buff = key, output a green light\n ELSE \n success <= '0';\n END IF;\n END IF;\n END PROCESS;"
] | [
"process",
"vhdl",
"conditional-statements"
] |
[
"React Router v4 - Nested Routes are not working",
"These are my main routes in Router.js\n\nconst Routes = () => {\n return ( \n <Switch>\n <Route path=\"/\" exact component={HomePage} />\n <Route path=\"/dashboard\" component={Dashboard} />\n </Switch>\n );\n}\n\n\nAnd these are my nested routes under the homepage. Right now Dashboard and HomePage is working but Forget-Password and Sign-up are not working. I can only see WHITE BLANK PAGE WITHOUT ERROR.\n\nrender() {\n const {match} = this.props;\n return (\n <div className=\"container home-grid\">\n <div className=\"featured\">\n <Featured />\n </div>\n <div className=\"home-forms\">\n <div className=\"logo\">\n <Logo />\n </div>\n <TransitionGroup className=\"route-page\">\n <CSSTransition\n key={location.pathname}\n timeout={{ enter: 800, exit: 800 }}\n classNames=\"page\"\n >\n <section className=\"route-section\">\n <Switch>\n <Route exact path={match.path} component={SignIn}/>\n <Route path={`${match.path}forgot-password`} component={ForgotPassword} />\n\n\n </Switch>\n </section>\n </CSSTransition>\n </TransitionGroup>\n <div className=\"footer-text\">\n <Text specialClass=\"footer\"></Text>\n </div>\n </div>\n </div>\n )\n}\n\n\nSign in is rendering but other routes are not. What am I doing wrong?"
] | [
"javascript",
"reactjs",
"react-router"
] |
[
"XSLT: How to ensure that a multi-mode identity template does not override all imported match templates?",
"I am writing an XSLT transformation that should largely leave the structure of the input XML unchanged, but add a few attributes and change a few element names.\n\nTo achieve this, I have an identity template, which ensures that all nodes which are not matched by another template (with a higher priority) will be retained as-is.\n\n\n\n<!-- Identity template: leaves in place nodes not matched by a more specific template. -->\n<xsl:template mode=\"#all\" priority=\"2\" match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates mode=\"#current\" select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n\n\nI am performing a multipass transformation of the input document, with each pass using a different mode. To avoid duplication of the identity template across all these modes, I have therefore set its mode to #all.\n\nThe issue arises when I want to import a few templates with match attributes I want to be applied in this stylesheet. The algorithm XSLT uses to decide which template with a match attribute to apply when calling <xsl:apply-templates> is:\n\n\nmode\nmatch\nimport precedence\npriority\n(declaration order)\n\n\nSince the identity template has mode=\"#all\" and match=\"@*|node()\", it will match all modes and all node types. Then, the property next in line to determine which template will be applied is the template's import precedence.\nHowever, since imported templates always have a lower import precedence than local templates, this identity template will always trump any imported template, thus rendering importing templates with match attributes a futile endeavour.\n\nMy question is: what is the most suitable way around this? I.e. How to ensure that a multi-mode identity template does not override all imported match templates?\n\nI have two proposed solutions, but neither are entirely satisfactory to me:\n\n\nchange the value of the identity template's mode attribute to explicitly list all modes used, e.g. mode=\"#default mode1 mode2 mode3\". I find this problematic in the sense that I now need to remember to update this attribute value every time I alter the modes in use (e.g. add or rename a mode). It would also involve keeping track of all the modes used in the imported stylesheet, or alternatively another identity template in the imported stylesheet for those modes.\nuse <xsl:include> instead of <xsl:import> to fetch the relevant external templates. This would probably work in my specific case, but I don't like it as a general solution, as these XSLT elements have different semantics and work in different ways, and this is likely not what I want as my web of XSLT stylesheets grows in complexity."
] | [
"xslt",
"xslt-2.0"
] |
[
"app:/EncycloPDF.swf - who/what is it?",
"Trying to do some detective work on a stats log. 43% of hits come from referrer app:/EncycloPDF.swf\n\nA typical log entry is 178.146.205.174 - - [29/Jan/2011:23:50:37 -0800] \"GET /filename.pdf HTTP/1.1\" 200 86571 \"app:/EncycloPDF.swf\" \"Mozilla/5.0 (Windows; U; en-US) AppleWebKit/531.9 (KHTML, like Gecko) AdobeAIR/2.5.1\"\n\nThis one happens to be googlebot crawl-66-249-67-204.googlebot.com but they are from all over the world.\n\nThe real question is whether someone is poaching content for some sort of app.\n\nCan't find any reference to EncycloPDF.swf anywhere, but I bet someone here knows the answer.\n\nThanks in advance"
] | [
"web-crawler",
"bots",
"statistics"
] |
[
"Combining multiple repositories of multiple projects into a single repository of an over-arching solution in Visual Studio 2010?",
"Suppose I have two Visual Studio 2010 projects, both in the same solution. \n\nOne project is a dll library for performing task x. And the other is a Windows Forms GUI Frontend for that library.\n\nLet's also suppose that I started developing both these projects using two different mercurial repositories, (one for each project).\n\nSuppose I wanted to combine these two repositories into one repository of the overarching solution of both projects (without losing any of my commit messages).\n\nWould this be possible (or even for that matter a good idea?)"
] | [
"visual-studio-2010",
"mercurial",
"repository",
"multiple-repositories"
] |
[
"How to comparing dates from different timezones",
"From Facebook Graph API I retrieve events which have the start_time set as string with the following format: \"2012-10-12T23:30:00+0200\". When location is specified it returns also the event object contains also the timezone (e.g.: \"Europe/Rome\").\nI simply would like to check which events are upcoming (newer than \"now\").\n\nI wonder if there is a way to do so without using pytz, which is not installed by default in Django. For deployment, the more portable the solution is the better."
] | [
"python",
"django",
"facebook-graph-api"
] |
[
"Use CMFCEditBrowseCtrl to select a file?",
"I am unsure if CMFCEditBrowseCtrl is really designed for this, but I want to employ it as a way to let the user choose a file from a dialog, rather than manually have a button whose handler creates a CFileDialog.\n\nThe issue I'm having is I want to call an event handler when a file is chosen, but I don't know what event to catch. I tried to use ON_EN_CHANGE but this crashed my program - I clicked the button, and before the open-files window appeared, I got I got a weird popup \"invalid file choice ??????????\" (or similar, I don't have the code here) and when I clicked OK the application ended.\n\nIs this a valid use of the control, and if so what would a minimal sample look like?"
] | [
"mfc"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.