texts
sequence | tags
sequence |
---|---|
[
"KeyError: Frozen Tensorflow Model to UFF graph",
"I have trained a custom CNN model with Tensorflow Estimator API. I have successfully Frozen the graph, but the conversion to UFF fails and throws following error:\n\n'KeyError: u'IteratorGetNext:1'\n\n\nThe code to do the said conversion:\n\nfrozen_graph_filename = \"Frozen_model.pb\"\nTMP_UFF_FILENAME = \"output.uff\"\noutput_name = \"sigmoid\"\n\nuff_model = uff.from_tensorflow_frozen_model(\n frozen_file=frozen_graph_filename,\n output_nodes=[output_name],\n output_filename=TMP_UFF_FILENAME,\n text=False,\n)\n\n\nThe names of the nodes in the graph are,\n\nprefix/OneShotIterator\nprefix/IteratorGetNext\nprefix/Reshape/shape\nprefix/Reshape\nprefix/Reshape_1/shape\nprefix/Reshape_1\nprefix/conv1/kernel\nprefix/conv1/bias\n.\n.\n.\nprefix/logits/MatMul\nprefix/logits/BiasAdd\nprefix/sigmoid\n\n\nSo is there a way to remove the first two Iterator nodes? They are useless outside of the training context. I have also used tf.graph_util.remove_training_nodes but it does not alleviate the problem I am facing."
] | [
"python",
"tensorflow",
"protocol-buffers",
"tensorrt"
] |
[
"Jenkins \"Job status\" shows success even if it has failed",
"cd /app/jenkins/aws/Microservices/ABC-services\necho \"Pushing JAR file to S3\"\naws deploy push --application-name DocumentStore --s3-location s3://${Bucket_name}/ABC.zip --ignore-hidden-files\n\necho \"Creating deployment using AWS code deploy\"\ndeployid=$(aws deploy create-deployment --application-name DocumentStore --file-exists-behavior OVERWRITE --deployment-config-name CodeDeployDefault.AllAtOnce --deployment-group-name ABCgrp--s3-location bucket=${Bucket_name},bundleType=zip,key=ABC.zip)\n\nstat=$(aws deploy get-deployment --deployment-id ${deployid} --query 'deploymentInfo.status' --output text)\nwhile [ \"$stat\" != \"Succeeded\" ]\ndo\n echo \"Deployment status $stat\"\n sleep 2m\n stat=$(aws deploy get-deployment --deployment-id ${deployid} --query 'deploymentInfo.status' --output text)\n exit 0\ndone\necho \"Deployment status $stat\"\n\nwhile [ \"$stat\" != \"Failed\" ]\ndo\necho \"Deployment status $stat\"\n sleep 2m\n stat=$(aws deploy get-deployment --deployment-id ${deployid} --query 'deploymentInfo.status' --output text)\n exit 1\ndone\necho \"Deployment status $stat\"\n\n\n\n\nEven when its failing still jenkins job is exiting with success. When it failed Jenkins job has to be fail & when its success it should be success. \n\nCould you please help me on this?\n\nNote: Success condition is working fine only failed condition not working."
] | [
"bash",
"jenkins",
"amazon-s3"
] |
[
"How/where does Python look for modules?",
"I am completely new to Python and wanted to use py2neo and tornado module.\n\nIn order to do that I ran setup.py for both modules and placed them into folders\n\nC:\\Python32\\modules\\py2neo\n\n\nand\n\nC:\\Python32\\modules\\tornado\n\n\nIn the main program I guess these lines tell the interpreter where to look for files:\n\nimport sys\nsys.path.append(r'C:\\Python32\\modules')\n\n\n\n# Import Neo4j modules\nfrom py2neo import neo4j, cypher\n\n\nReading the book I also added environmental variable (in Windows 7)\n\nPYTHONPATH = C:\\Python32\\modules;C:\\Python32\\modules\\tornado;C:\\Python32\\modules\\py2neo\n\n\nEdit\n\nNow I figured out that Python Shell has to be restarted in order to load modified PYTHONPATH variable\n In case the variable value is PYTHONPATH = C:\\Python32\\modules\nand the program contains the line \n\nfrom py2neo import neo4j, cypher\n\n\nthen the following lines are useless:\n\nimport sys\nsys.path.append(r'C:\\Python32\\modules')\n\n\nWhen I run the program however I get the following error:\n\nTraceback (most recent call last):\n File \"C:\\...\\Python Projects\\HelloPython\\HelloPython\\Hellopy2neo.py\", line 15, in <module>\n from py2neo import neo4j, cypher\n File \"C:\\Python32\\modules\\py2neo\\neo4j.py\", line 38, in <module>\n import rest, batch, cypher\nImportError: No module named rest\n\n\nIn the file neo4j.py there are the following lines:\n\ntry:\n import json\nexcept ImportError:\n import simplejson as json\ntry:\n from urllib.parse import quote\nexcept ImportError:\n from urllib import quote\ntry:\n from . import rest, batch, cypher\nexcept ImportError:\n import rest, batch, cypher #line38\n\n\nand rest.py file is located in folder C:\\Python32\\modules\\py2neo so I don't know why I get the error \n\n\n ImportError: No module named rest\n\n\nEdit2:\n\nTrying to import the py2neo directoy in Python Shell and list modules I get:\n\n>>> import py2neo\n>>> [name for name in dir(py2neo) if name[0] != '_']\n['rest']\n\n\nI guess there are some unneccesary imports as well and would be very thankful if anyone explained, which imports should be added and excluded (in PYTHONPATH and scripts) in order the program to run without errors."
] | [
"python"
] |
[
"How to trigger SonarQube runs of existing Jenkins jobs only once a day",
"Sonar recommends publishing jobs be run only once a day. We have ~100 existing maven builds triggered by every code checkin (many times a day). How can I re-use the existing job definitions to publish only once a day?"
] | [
"jenkins",
"sonarqube"
] |
[
"TypeError: window() missing 2 required positional arguments: 'timeColumn' and 'windowDuration' Explicitly there though",
"I have the titled error coming through for the window() method. Yet I even tried putting these in explicitly as seen below. (I was getting the error before I tried this and our code demo showed it working with out the explicit call.)\nThis is in Spark - Python on Databricks. Does anyone have any ideas?\nThe schema for the Date column is created with this:\nStructField('Date', TimestampType(), True), \\\n\nThis following code makes the dataframe going into the problematic line:\ncountFifaStaticHash = staticFIFAdf.withColumn('Hashtags', f.explode(f.split('Hashtags',',')))\n\nHere is a short sample of what the above looks like when .show() is run:\nenter image description here\nstaticCountedHash = countFifaStaticHash.groupBy(f.window(timeColumn="Date", windowDuration="60 minutes", slideDuration="30 minutes"), 'Hashtags').agg(f.count('Hashtags').alias('Hash_ct')).filter(f.col('Hash_ct')>100).orderBy(f.window().asc(),f.col('Hash_ct').desc())\nstaticCountedHash.show()"
] | [
"python",
"pyspark",
"apache-spark-sql"
] |
[
"python 2.7: Why does IPython Notebook throw an error for non-ascii character?",
"I'm working on IPython notebook on OS X. My source code consist entirely of ascii characters. But compiler reports to me that I'm using non-ascii character. The source code looks like:\n\n%%file Sierpinski_triangle.py\n\nfrom turtle import *\n\nreset()\ntracer(False)\n\ns = 'A+B+A−B−A−B−A+B+A'\n\nl_angle = 60\nr_angle = 60\nfor c in s:\n if c == 'A' or c == 'B':\n forward(10)\n elif c == '+':\n left(l_angle)\n #l_angle = l_angle * -1\n elif c == '-':\n right(r_angle)\n #r_angle = r_angle * -1\ndone()\n\n\n\n\nFile \"Sierpinski_triangle.py\", line 7\nSyntaxError: Non-ASCII character '\\xe2' in file Sierpinski_triangle.py on line 7, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details\n\n\nThank you in advance!"
] | [
"python",
"ipython"
] |
[
"How to Get and filter Data attribute of all parents in a nested list, till a target (div) of html element?",
"I've a nested (UL->LI->UL-LI..) list. On any clicked node, I'm using ParentsUntil() to find all the parents till a certain ancestor element. \n\nIn each nested element's data attribute (data-weight:), there is number that represent weight. \n\nI want to sum/aggregate total weight till the parent. These numbers (Areas) are in the data-area field of each item. \n\n<ul class=\"level-1 yes\" data-weight=\"12\" data-weight-total=\"0\">\n <li class=\"item-i\" data-weight=\"22\" >I</li>\n <li class=\"item-ii\" data-weight=\"4\" data-weight-total=\"0\">II\n <ul class=\"level-2 yes\" data-weight=\"12\">\n <li class=\"item-a\" data-weight=\"1.4\">A</li>\n <li class=\"item-b\" data-weight=\"128\" data-weight-total=\"0\">B\n <ul class=\"level-3\" data-weight=\"63\" data-weight-total=\"0\">\n <li class=\"item-1\" data-weight=\"54\">1</li>\n <li class=\"item-2\" data-weight=\"23\">2</li>\n <li class=\"item-3\" data-weight=\"107\">3</li>\n </ul>\n </li>\n <li class=\"item-c\" data-weight=\"231\">C</li>\n </ul>\n </li>\n <li class=\"item-iii\">III</li>\n</ul>\n\n\n\n $( \"li.item-2\" )\n .parentsUntil( $( \"ul.level-1\" ), \".yes\" );\n\n\nIn the list above, \n\n\nHow can I get the an array/list of them items from the clicked item\nto the parent item with their data-weight [key,value]? for e.g. $VarArrayCargoVessel\nAnd as I traverse up, How can I sum/total weights (data-weight-total) of each/nested list and populate\\fill-in the data-weight-total? I have zero's right now, because I dont know how to insert/write into a array value"
] | [
"javascript",
"jquery",
"html",
"nested-lists",
"parents"
] |
[
"Save values from FOR loop for further analysis",
"How do I save the values from the For Loop from the following code? When I pint the variable \"lm5\", it has a total of two values. When I tried to save it to a new variable, it only shows the last value. \n\nIdeally, I would like to save the lm5,lm10,lm20 for another round of IF statement analysis. Could you please advise how to proceed? Thanks in advance!\n\neven<-c(2,4)\n\nfor( i in even){\n m5<-rollmean(test[,i],5,fill=NA)\n m10<-rollmean(test[,i],10,fill=NA)\n m20<-rollmean(test[,i],20,fill=NA)\n lm5<-tail(m5[!is.na(m5)],1)\n print(lm5)\n}"
] | [
"r"
] |
[
"x86-64 Intel Syntax for rel8 immediate operand?",
"The first form of JMP in x86-64 is:\n\nOpcode Instruction Description\nEB cb JMP rel8 Jump short, RIP = RIP + 8-bit displacement sign\n\n\nSo for example JMP rel8=-2 is eb fe. fe is a one byte signed 2s-compliment -2.\n\nHow do I express this rel8 immediate in Intel syntax?\n\nI tried the following:\n\ntest.s:\n\n.intel_syntax noprefix\n.global _start\n_start:\n jmp -2\n\n\nCompile with:\n\n$ gcc -nostdlib test.s\n$ objdump -d -M intel\n\n\nBut I get:\n\n e9 00 00 00 00 jmp 5 <_start+0x5>\n\n\nNot eb fe as desired.\n\n(More generally, where is Intel syntax documented? I couldn't find anything in the Intel manual about it. The Intel manual explains how to encode operands, but it doesn't give the syntax of the assembly language.)\n\nUpdate:\n\nSolution is:\n\n.intel_syntax noprefix\n.global _start\n_start:\n jmp .\n\n\n. must represent address of current instruction. Assembling it and disassembling gives:\n\n4000d4: eb fe jmp 4000d4 <_start>\n\n\neb fe as desired. RIP-relative addressing is in terms of the next instruction, so the assembler must adjust for the size of the current instruction for you."
] | [
"assembly",
"x86",
"x86-64",
"gnu-assembler",
"intel-syntax"
] |
[
"MySQL database resultset with values as close to a number \"x\" as possible",
"Im trying to get a result set that contains the 10 values that are closest to, in this case, the number 3.\n\nI have a database that has values in a column named rated which can be 1,2,3,4 or 5. What im trying to do is query the database and return the first 10 rows that have the values closest to 3. The values can be above 3 or below 3. I should note that these values in the rated column are floats.\n\nI then need to sort these rows in order so that rows with value of 3 are first and then the row with lowest offset (+/-) from 3.\n\nIs there any SQL query that can return atleast the result set of values closest to 3 ? or am i going to have to return the whole db and sort it myself?\n\nTo get the first 10 rows with highest value down i used the statement \n\nSELECT * FROM tabs ORDER BY 5 DESC LIMIT 10\";\n\n\n5 refers to the column rated\n\nIs there some way to modify this to do what i want ? \nThanks"
] | [
"mysql",
"limit"
] |
[
"Angular/Angular2 get headers from ActivatedRoute",
"I have an Angular app hosted within an IFrame. I have to retrieve some user details that are passed from the application hosting the IFrame e.g. userId=12345.\n\nIs there a way to retrieve header details from Activated route or similar?"
] | [
"angularjs",
"angular",
"typescript",
"routes",
"http-headers"
] |
[
"vbscript issue for removing trusted site",
"I have a script to add the trusted sites to IE.\n\nConst HKEY_CURRENT_USER = &H80000001\n\nstrComputer = \".\"\nSet objReg=GetObject(\"winmgmts:\\\\\" & strComputer & \"\\root\\default:StdRegProv\")\n\nstrKeyPath = \"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\\" _\n & \"ZoneMap\\Domains\\\" & \"https://www.google.com\"\n\nobjReg.CreateKey HKEY_CURRENT_USER, strKeyPath\n\nstrValueName = \"*\"\n\ndwValue = 2\n\nobjReg.SetDWORDValue HKEY_CURRENT_USER, strKeyPath, strValueName, dwValue\n\n\nThe trusted sites are added successfully. But there is a problem here....\nI am not able to remove the trusted sites added through the script which is a serious problem\n\nThanks in advance."
] | [
"vbscript"
] |
[
"This IP, site or mobile application is not authorized to use this API key",
"I am using https://maps.googleapis.com/maps/api/geocode/json? link with server key and user IP to find the latitude and longitude of any address, when I'm trying I find the error as\n\nI have a server access key from google and I have put my server's IP address in the their white list.\n\nThe URL that I am trying to access via PHP CURL is:\n\n\n https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true&key=XXXXXXXXXXXX\n\n\nThe result that I am getting:\n\nArray ([error_message] => This IP, site or mobile application is not authorized to use this API key. [results] => Array ( ) [status] => REQUEST_DENIED)\n\n\nIs there anything that I need to configure.The geocoding API is also switched on."
] | [
"google-api",
"google-places-api"
] |
[
"using a portable int",
"gcc c99 MS2005/2008\n\nI have started program that will be compiled on linux/windows. \n\nThe program will be compiled on linux using gcc 4.4.1 c99. And on windows the compiler will be either MS 2005/2008. And this I cannot change.\n\nI am using SCons to create the build files. However, the reason I choose c99 as I can use the stdint.h so my integers would be compatible between different architectures i.e. x86_32 and 64 bit. using int32_t so it will compile without any problem on both 32 and 64 bit machines.\n\nHowever, I have just discovered that c99 isn't used for ms compilers. Only c89. However, c89 doesn't have the stdint.t.\n\nI am wondering what is the best way to make the integer portable among different compilers running on either 32 or 64.\n\nMany thanks for any advice,"
] | [
"c"
] |
[
"failure with Ant Android: getType tag",
"I'm building my Android project using ant (on Hudson). I'm running into an error on the Android build.xml file line 388:\n\n<echo level=\"info\">Project Name: ${ant.project.name}</echo>\n<gettype projectTypeOut=\"project.type\" />\n\n\nThis was running before, but some update broke it, and I can't seem to figure out how. The AndroidManifest was updated and a new package was added (in the wrong place, actually).\n\nI'm going from this correct output:\n\n[echo] Project Name: <Application Name>\n[gettype] Project Type: Application\n\n\nTo this error\n\n<filepath>/workspace/android_build_files/android-sdk-linux/tools/ant/build.xml:388: org.xml.sax.SAXParseException: The content of elements must consist of well-formed character data or markup.\nat com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:239)\nat com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)\nat com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:468)\nat com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:515)\nat com.android.ant.GetTypeTask.execute(GetTypeTask.java:85)\nat org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)\nat sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)\nat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\nat java.lang.reflect.Method.invoke(Method.java:597)\nat org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)\nat org.apache.tools.ant.Task.perform(Task.java:348)\nat org.apache.tools.ant.Target.execute(Target.java:392)\nat org.apache.tools.ant.Target.performTasks(Target.java:413)\nat org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)\nat org.apache.tools.ant.Project.executeTarget(Project.java:1368)\nat org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)\nat org.apache.tools.ant.Project.executeTargets(Project.java:1251)\nat org.apache.tools.ant.Main.runBuild(Main.java:811)\nat org.apache.tools.ant.Main.startAnt(Main.java:217)\nat org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)\nat org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)\n--------------- linked to ------------------\njavax.xml.xpath.XPathExpressionException\nat com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:473)\nat com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:515)\nat com.android.ant.GetTypeTask.execute(GetTypeTask.java:85)\nat org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)\nat sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)\nat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\nat java.lang.reflect.Method.invoke(Method.java:597)\nat org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)\nat org.apache.tools.ant.Task.perform(Task.java:348)\nat org.apache.tools.ant.Target.execute(Target.java:392)\nat org.apache.tools.ant.Target.performTasks(Target.java:413)\nat org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)\nat org.apache.tools.ant.Project.executeTarget(Project.java:1368)\nat org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)\nat org.apache.tools.ant.Project.executeTargets(Project.java:1251)\nat org.apache.tools.ant.Main.runBuild(Main.java:811)\nat org.apache.tools.ant.Main.startAnt(Main.java:217)\nat org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)\nat org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)\nCaused by: org.xml.sax.SAXParseException: The content of elements must consist of well-formed character data or markup.\nat com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:239)\nat com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)\nat com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:468)\n... 18 more"
] | [
"android",
"ant",
"build.xml"
] |
[
"Call a function only if a value is neither null nor undefined",
"When a button is clicked I check if something exists in a localstorage key as such:\n\nvar a = localStorage.getItem('foo');\nif (typeof a != 'undefined') {\n // Function\n}\n\n\nbut if the key doesn't exists at all, it return null. How can I call if not undefined and not null do function, else return true(?) or continue?"
] | [
"jquery",
"null",
"local-storage",
"undefined"
] |
[
"What is simplified in ECMAScript 5 date format compared to ISO 8601",
"ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ\n — https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15\n\n\nSo what exactly is the difference between the two formats? What do I have to be careful about? I noticed that ISO 8601 states that the T can be substituted by a space. What else is \"simplified\"?\n\nTo be very specific: This question is about the standard. Browser behavior is interesting, but not the main focus of this question."
] | [
"javascript",
"datetime",
"ecmascript-5",
"iso8601"
] |
[
"Value from suggestion box some time get selected sometime not",
"Snapshot:\n\nCode trials:\nWebElement orderno=driver.findElementById("Order_Number"); orderno.sendKeys(orderNum);\n\nWebElement duedate=driver.findElementByXPath("//*[@id="cust_Terms"]"); action.moveToElement(duedate).click().sendKeys(Keys.ARROW_UP).sendKeys(Keys.ARROW_UP).sendKeys(Keys.ARROW_UP).sendKeys(Keys.ARROW_UP).sendKeys(Keys.ARROW_UP).sendKeys(Keys.ARROW_UP).click().build().perform();\n\nWebElement salepr=driver.findElementById("SalesPersonIndex"); salepr.clear(); action.moveToElement(salepr).click().sendKeys(saleprsn).click().build().perform();\n\nWebElement productcode=driver.findElementById("Project_code"); action.moveToElement(productcode).click().sendKeys(procode).click().build().perform();\n\nThread.sleep(3000); WebElement slctItem = driver.findElementById("selectItem"); action.moveToElement(slctItem).click().build().perform();\n\nThread.sleep(3000); WebElement popitem = driver.findElementByXPath("//*[@id="ItemIndex"]"); popitem.click(); action.click(popitem).sendKeys(itmName);Thread.sleep(3000); action.sendKeys(Keys.ENTER).build().perform();\n\n/* for (WebElement we : Itemauto) { System.out.println("Item Values are = " + we.getText()); if (we.getText().equalsIgnoreCase(itmName)); we.click(); break; }*/\n\ndriver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS) ; WebElement selectitem=driver.findElement(By.linkText("Select")); action.moveToElement(selectitem).doubleClick().build().perform();\n\nThread.sleep(2000); WebElement custnote=driver.findElementByXPath("//*[@id="Customer_Notes"]"); custnote.clear(); action.moveToElement(custnote).click().sendKeys(note).build().perform();\n\nThread.sleep(1000); WebElement submit =driver.findElementByXPath("//*[@id="btnsaveinvoice"]"); submit.click();\n\nWebElement goback=driver.findElementByXPath("//*[@id="goback"]"); goback.click();"
] | [
"selenium-webdriver",
"automated-tests"
] |
[
"ModuleNotFoundError: No module named 'django.utils.six'",
"HTTP GET /admin/ 500 [0.00, 127.0.0.1:51425]\nTraceback (most recent call last):\n File \"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\lib\\site-packages\\daphne\\http_protocol.py\", line 180, in process\n \"server\": self.server_addr,\nModuleNotFoundError: No module named 'django.utils.six'\n\nInstalled Django 3. Django.utils.six is no longer supported. Thoughts?"
] | [
"python",
"django",
"daphne"
] |
[
"Converting TZ timestamp string to a given format in UTC using spark and scala",
"I have a column called lastModified with String as given below that represents time in GMT.\n\"2019-06-24T15:36:16.000Z\"\n\nI want to format this string to the format yyyy-MM-dd HH:mm:ss in spark using scala. To achieve this, I created a dataframe with a new column \"ConvertedTS\".\nwhich gives incorrect time.\n\nMachine from where I am running this is in America/New_York timezone.\n\ndf.withColumn(\"ConvertedTS\", date_format(to_utc_timestamp(to_timestamp(col(\"lastModified\"), \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\"), \"America/New_York\"), \"yyyy-MM-dd HH:MM:SS\").cast(StringType))\n\n\nI am basically looking for formatting the result of below statement in yyyy-MM-dd HH:mm:ss\n\ndf.withColumn(\"LastModifiedTS\", col(\"lastModified\"))\n\n\nOne of the ways that is currently working for me is udf but as udfs are not recommended, I was looking for more of a direct expression that I can use.\n\nval convertToTimestamp = (logTimestamp: String) => {\n println(\"logTimeStamp: \" + logTimestamp)\n var newDate = \"\"\n try {\n val sourceFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSSXXX\")\n sourceFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"))\n val convertedDate = sourceFormat.parse(logTimestamp)\n val destFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\")\n destFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"))\n newDate = destFormat.format(convertedDate)\n println(\"newDate: \" + newDate)\n } catch {\n case e: Exception => e.printStackTrace()\n }\n newDate\n }\n\n //register for sql\n EdlSparkObjects.sparkSession.sqlContext.udf.register(\"convertToTimestamp\", convertToTimestamp)\n\n // register for scala\n def convertToTimestampUDF = udf(convertToTimestamp)\n df.withColumn(\"LastModifiedTS\", convertToTimestampUDF(col(\"lastModified\")))\n\n\nThanks for help and guidance."
] | [
"scala",
"apache-spark",
"dataframe",
"apache-spark-sql",
"user-defined-functions"
] |
[
"Query to check if many-to-many relation exists",
"I have one of these moments when something seems so simple but I just can't seem to find the right query. I am looking for a query that checks if a certain many-to-many relation already exists. Consider the following table:\n\n\n +---------+---------+\n | feed_id | coll_id |\n +---------+---------+\n | 1 | 1 |\n | 1 | 2 |\n | 1 | 3 |\n +---------+---------+\n\n\nIt's a table from a many to many relation between a table 'feeds' and a table 'collections'.\n\nI need a query that checks if a feed already exists that has collections 1 and 2, and ONLY 1 and 2. If there is, I would need its feed_id.\n\nIn the above table this feed does not exist.\n\nA more generic description of the query would be: find a feed that contains all of the coll_id's, and that the feed doesn't contain any other collections. This would mean the following for the example above:\n\n\nmaking sure that coll_id is IN(1,2)\nmaking sure that a COUNT(*) WHERE feed_id = 1 would return 2 (the number of coll_id's)\n\n\nWhat's problematic in step 2 is that I don't have the value of the feed_id available in my sub query.\n\nOr am I completely on the wrong track?\n\nAny help would be much appreciated!"
] | [
"mysql"
] |
[
"Make a GET request to Yesmail using JavaScript",
"I'm trying to make a GET request to the Yesmail API and return the data associated to a email marketing campaign based on a message ID that right now is hard coded but would eventually be passed. Right now I keep getting a 401 (Unauthenticated). I have been using the \"Sample Request Header\" but I'm still missing something. Am I structuring the headers correctly? Am I passing the correct parameters at all?\n\nfunction doFetch(ev) {\n // this needs to be HTTPS\n let uri = 'https://api.test.yesmail.com/v2/reports/master-events/message_id_here';\n\n let h = new Headers();\n let encoded = window.btoa('my_key_here');\n h.append('Accept', 'application/json');\n h.append('Api-key', 'encoded');\n h.append('Api-User', 'my_username_here');\n h.append('Content-Type', 'application/json; charset=utf-8');\n h.append('Connection', 'keep-alive');\n\n let req = new Request(uri, {\n method: 'GET',\n headers: h,\n mode: 'cors'\n });\n // credentials: 'include' means a different domain.\n // credentials: 'same-origin' means the same domain.\n\n fetch(req)\n .then( (response)=>{\n if(response.ok){\n return response.json();\n }else{\n throw new Error('BAD HTTP stuff');\n }\n })\n .then( (jsonData) =>{\n console.log(jsonData);\n p.textContent = JSON.stringify(jsonData, null, 4);\n })\n .catch( (err) =>{\n console.log('ERROR:', err.message);\n });\n}"
] | [
"javascript",
"fetch-api",
"get-request"
] |
[
"Unable to get the dropdown to close using jquery",
"Here is the fiddle containing all the code:\nhttps://jsfiddle.net/rajat_bansal/rtapaew5/1/\n\nHere is my jquery part which is causing problems:-\n\n$(document).ready(function(e) {\n\n $(\".sub-handle\").click(function() {\n if(!$(this).hasClass('showing-sub')){ //class doesnt exists so add it and open dropdowns giving specific backgrounds\n $(this).find(\".submenu\").addClass('showing-sub');\n $(this).addClass(\"sidebarElementDivOnClick\");\n $(this).find(\"a\").addClass(\"outerMenuItem\");\n }\n else{ \n $(this).find(\".submenu\").removeClass(\"showing-sub\");\n }\n });\n\n $(\".innerMenuItem\").click(function(){\n $(this).toggleClass(\"innerMenuItemOnClick\");\n });\n }); \n\n\nFrom what I see, its not letting me remove the class. I guess its something minor. Im very new to jquery. Any help with explanation would be greatly appreciated.\nThanks!"
] | [
"jquery",
"html",
"css",
"web"
] |
[
"Recording audio from the microphone in Windows Phone 7 Series",
"I'm wondering if anyone has any code samples or links to documentation that demonstrate how to capture audio from the device's microphone on the new Windows Phone Series 7. I've recently downloaded the Windows Phone SDK CTP for Visual Studio 2010 and I'm struggling to find any supporting documentation that might help.\n\nThanks,\n\nRichard."
] | [
"windows-phone-7"
] |
[
"Clicking multiple items on one page using selenium",
"My main purpose is to go to this specific website, to click each of the products, have enough time to scrape the data from the clicked product, then go back to click another product from the page until all the products are clicked through and scraped (The scraping code I have not included). \n\nMy code opens up chrome to redirect to my desired website, generates a list of links to click by class_name. This is the part I am stuck on, I would believe I need a for-loop to iterate through the list of links to click and go back to the original. But, I can't figure out why this won't work. \n\nHere is my code: \n\nimport csv\nimport time\nfrom selenium import webdriver\nimport selenium.webdriver.chrome.service as service\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.vatainc.com/infusion/adult-infusion.html?limit=all\"\nservice = service.Service('path to chromedriver')\nservice.start()\ncapabilities = {'chrome.binary': 'path to chrome'}\ndriver = webdriver.Remote(service.service_url, capabilities)\ndriver.get(url)\ntime.sleep(2)\nlinks = driver.find_elements_by_class_name('product-name')\n\n\nfor link in links:\n link.click()\n driver.back()\n link.click()"
] | [
"python",
"selenium",
"beautifulsoup"
] |
[
"In PyParsing, how to specify one or more lines which do not start with a certain string?",
"I'm trying to parse some fields from a multi-line file, of which I'm only interested in some lines, while others I would like to skip. Here is an example of something similar to what I'm trying to do:\n\nfrom pyparsing import *\n\nstring = \"field1: 5\\nfoo\\nbar\\nfield2: 42\"\n\nvalue1 = Word(nums)(\"value1\")\nvalue2 = Word(nums)(\"value2\")\nnot_field2 = Regex(r\"^(?!field2:).*$\")\n\nexpression = \"field1:\" + value1 + LineEnd() + OneOrMore(not_field2)+ \"field2:\" + value2 + LineEnd()\n\ntokens = expression.parseString(string)\n\nprint tokens[\"value1\"]\nprint tokens[\"value2\"]\n\n\nwhere the Regex for a line not starting with field2: is adapted from Regular expression for a string that does not start with a sequence. However, running this example script gives a\n\npyparsing.ParseException: Expected Re:('^(?!field2:).*$') (at char 10), (line:2, col:1)\n\n\nI would like the value2 to end up as 42, regardless of the number of lines (foo\\n and bar\\n in this case). How can I achieve that?"
] | [
"python",
"pyparsing"
] |
[
"Python join all combinations of elements within each list",
"I have a list of tuples each with two elements: [('1','11'),('2','22'),('3','33'),...n]\n\nHow would I find all the combinations of each tuple with only selecting one element of the tuple at a time? \n\nThe example results: \n\n\n \n [[1,2,3],[11,2,3],[11,2,3],[11,22,33],[11,2,33],[11,22,3],[1,22,3],[1,22,33],[1,2,33]]`\n \n\n\nitertools.combinations gives me all combinations but does not preserve selecting only one element from each tuple. \n\nThanks!"
] | [
"python"
] |
[
"Can't access the object properties in child page Bootstrap Tab",
"I've bumped into a strange situation with ui bootraps Tab that i cannot access the object properties though it shows full content correctly.\n\nController fixtureLiveFormation: \n\n $scope.statsTabs = [\n { heading: 'Team Stats', route: 'livematch.teamstats', template: '/App/Main/views/dulieu1trandau/report_teamstats.html', active: true },\n { heading: 'Player Stats', route: 'livematch.playerstats', template: '/App/Main/views/dulieu1trandau/report_playerstats.html' }\n ];\n $scope.changeTab = function (route) {\n switch (route) {\n case 'livematch.teamstats': \n break;\n case 'livematch.playerstats':\ndataService.getleagueplayerstats($scope.pagingInfo).then(function (data) {\n $scope.playerStats = _.filter(data.results, function (item) { return item.PlayerId == 90 }); \n }); \n break;\n <tabset>\n\n\nView:\n\n<section ng-controller=\"fixtureLiveFormation\">\n <tab ng-repeat=\"t in statsTabs\" heading=\"{{t.heading}}\" active=\"t.active\" disabled=\"t.disabled\" ng-click=\"changeTab(t.route)\">\n <div ng-include=\"t.template\"></div>\n </tab>\n </tabset>\n</section>\n\n\nOn report_playerstats.html\n\n <div class=\"table-responsive\">\n {{playerStats.Name}} => show nothing but\n\n{{playerStats}} -> show \n\n[{\"PlayerId\":90,\"TeamOwnerId\":4,\"Name\":\"Aaron Ramsey\",\"Team\":\"Arsenal\"...}]\n</div>\n\n\nWhy it could happen that way, please give me some advise.\n\nThanks."
] | [
"angularjs",
"angular-ui-bootstrap"
] |
[
"How to get the size of an embedded image / swf?",
"Normally if you were loading an image from a URL you would do the following:\n\nm_image = new Image();\nm_image.addEventListener(Event.COMPLETE, image_completeHandler, false, 0, true);\nm_image.source = \"http://www.example.com/image.jpg\";\n\nprivate function image_completeHandler(event:Event):void\n{\n // Image content has now loaded, we need to wait for it to validate it's size\n m_image.addEventListener(FlexEvent.UPDATE_COMPLETE, image_updateCompleteHandler, false, 0, true);\n}\n\nprivate function image_updateCompleteHandler(event:FlexEvent):void\n{\n // Do stuff with width / height\n}\n\n\nBut, if you set the source to an embedded image class, the complete event doesn't appear to fire. So my question is, how can you get the width / height of an embedded image / swf?"
] | [
"actionscript-3",
"size",
"flex3"
] |
[
"Elasticsearch Nest 6 deserializes object enabled=false as null",
"One of the fields in my elastic index is always deserialized as null by Nest. The index I am using has the following structure: \n\n\"myIndex\": {\n \"myMapping\": {\n \"name\": {default properties},\n \"guid\": {\"type\": \"keyword\"},\n \"myDisabledField\": {\n \"type\": \"object\",\n \"enabled\": false\n }\n }\n }\n\n\nWhen I try a search against this index using Nest 6.x, it always returns \"myDisabledField\" as null. However, if I make the same request in kibana it shows \"myDisabledField\" in the _source. For example, the kibana query: \n\nGET myIndex/_search\n{\n \"query\": {\n \"query_string\": {\n \"query\": \"sample query\"\n }\n }\n}\n\n\nwould return the following: \n\n{\n \"hits\": [\n { \n \"_index\": \"myIndex\",\n \"_source\": {\n \"name\": \"some_name\",\n \"guid\": \"some_guid\",\n \"myDisabledField\": {\n \"field1\": \"value1\",\n \"field2\": \"value2\",\n ... etc\n }\n }\n }\n ]\n}\n\n\nHowever, the C#/Nest query: \n\nvar result = _elasticClient.Search<T>(\n s => s\n .Query(\n q => q\n .QueryString(\n qs => qs\n .Query(\"sample query\")\n )\n )\n);\n\nreturn result.Documents.ToList();\n\n\nReturns something like:\n\n[\n \"MyObject\": {\n \"Name\": \"some_name\",\n \"Guid\": \"some_guid\",\n \"MyDisabledField\": null\n }\n]\n\n\n\"MyObject\" in this case is the POCO that I used to populate this index. How do I get Nest to fill \"MyDisabledField\" with the data stored in the _source? Is there some sort of setting needed to deserialize objects, or fields with the setting enabled=false?\n\nBy the way I used the DefaultMappingFor connection setting to map to the correct index for my type. This is the documentation on the enabled property I used"
] | [
"elasticsearch",
"nest"
] |
[
"PHP Mail script not getting form data",
"Trying to create a contact form on a website, the code for the form is shown below:\n\n <form name=\"contact_form\" method=\"POST\" action=\"send_email.php\">\n <ul id=\"contact_form\">\n <li>\n <input required type=\"text\" name=\"name\" class=\"field_style field_split\" placeholder=\"Your Name\">\n <input required type=\"email\" name=\"email\" class=\"field_style field_split\" placeholder=\"Your Email\">\n </li>\n <li>\n <select required name=\"subject\" class=\"field_style field_full\">\n <option value=\"General Enquiry\">General Enquiry</option>\n <option value=\"Coaching Enquiry\">Coaching Enquiry</option>\n <option value=\"Other\">Other</option>\n </select>\n </li>\n <li>\n <textarea required name=\"message\" class=\"field_style\" placeholder=\"Message\"></textarea>\n </li>\n <li>\n <input id=\"submit_contact\" name=\"submit\" type=\"submit\" value=\"Send Email\">\n </li>\n </ul>\n </form>\n\n\nThis form should send an email with the information from the form fields, but it is failing to get the data from the fields when the user presses Submit.\n\nHere is the send_email.php (with the recipient email replaced):\n\n<?php\n$to = \"[email protected]\";\n\nif(isset($_POST[\"from\"])){ $from = $_POST[\"from\"];}else{echo \"from not set.\";}\nif(isset($_POST[\"name\"])){ $name = $_POST[\"name\"];}else{echo \"name not set.\";}\nif(isset($_POST[\"subject\"])){ $subject = $_POST[\"subject\"];}else{echo \"subject not set.\";}\nif(isset($_POST[\"message\"])){ $message = $_POST[\"message\"];}else{echo \"message not set.\";}\n\nif(mail($to, $subject, $message))\n{\n header(\"Location: #\");\n}else{\n echo \"Error: \";\n print_r(error_get_last());\n}\n?>\n\n\nAnd it returns the following message:\n\nfrom not set.\nname not set.\nsubject not set.\nmessage not set.\nError: Array ( [type] => 8 [message] => Undefined variable: message [file] => /home/u884620714/public_html/send_email.php [line] => 14 )\n\n\nAnyone have any ideas, because I'm new to PHP and don't understand why the data is not fetched from the form.\n\nThanks for the help in advance."
] | [
"php",
"html",
"forms",
"email"
] |
[
"jq add value of a key in nested array and given to a new key",
"I have a stream of JSON arrays like this\n\n[{\"id\":\"AQ\",\"Count\":0}]\n[{\"id\":\"AR\",\"Count\":1},{\"id\":\"AR\",\"Count\":3},{\"id\":\"AR\",\"Count\":13},\n{\"id\":\"AR\",\"Count\":12},{\"id\":\"AR\",\"Count\":5}]\n[{\"id\":\"AS\",\"Count\":0}]\n\n\nI want to use jq to get a new json like this\n\n{\"id\":\"AQ\",\"Count\":0}\n{\"id\":\"AR\",\"Count\":34}\n{\"id\":\"AS\",\"Count\":0}\n\n\n34=1+3+13+12+5 which are in the second array.\nI don't know how to describe it in detail. But the basic idea is shown in my example. \nI use bash and prefer to use jq to solve this problem. Thank you!"
] | [
"json",
"bash",
"addition",
"jq",
"ndjson"
] |
[
"PostgreSQL - How to use wildcard in string condition",
"I have a string: A%A\n\nI want to find all string same start with A%A in database.\n\nExample:\n\nAABCD - false\nAABCE - false\nAA%BC - true\n\n\nI use the sql statement:\n\nSelect * from Tabel where Column like 'AA%B%'\n\n\nBut the result are:\n\nAABCD\nAABCE\nAA%BC\n\n\nBecause the string include wildcard '%' and postgres select wrong.\n\nPlease suggest me a solution"
] | [
"postgresql",
"wildcard",
"sql-like"
] |
[
"Smartphone Memory Configuration",
"Smart-phones have built in ROM and RAM separately. Also a few phones has virtual memory support too. I would like to know what these memories are basically used for. I understand that RAM is available to user processes. But why do they have a big chunk of ROM?\n\nE.g. The wiki page for Droid Incredible says\n\n\n512 MB DDR RAM\n1 GB ROM (748 MB free to user) - what's this free to user?\nplus 8 GB moviNAND - typically used for data storage"
] | [
"iphone",
"android",
"memory",
"smartphone"
] |
[
"Multi-tenancy in Golang",
"I'm currently writing a service in Go where I need to deal with multiple tenants. I have settled on using the one database, shared-tables approach using a 'tenant_id' decriminator for tenant separation.\n\nThe service is structured like this:\n\ngRPC server -> gRPC Handlers -\n \\_ Managers (SQL)\n /\nHTTP/JSON server -> Handlers -\n\n\nTwo servers, one gRPC (administration) and one HTTP/JSON (public API), each running in their own go-routine and with their own respective handlers that can make use of the functionality of the different managers. The managers (lets call one 'inventory-manager'), all lives in different root-level packages. These are as far as I understand it my domain entities.\n\nIn this regard I have some questions:\n\n\nI cannot find any ORM for Go that supports multiple tenants out there. Is writing my own on top of perhaps the sqlx package a valid option?\nOther services in the future will require multi-tenant support too, so I guess I would have to create some library/package anyway.\nToday, I resolve the tenants by using a ResolveTenantBySubdomain middleware for the public API server. I then place the resolved tenant id in a context value that is sent with the call to the manager. Inside the different methods in the manager, I get the tenant id from the context value. This is then used with every SQL query/exec calls or returns a error if missing or invalid tenant id. Should I even use context for this purpose?\nResolving the tenant on the gRPC server, I believe I have to use the UnaryInterceptor function for middleware handling. Since the gRPC \nAPI interface will only be accessed by other backend services, i guess resolving by subdomain is unneccessary here. But how should I embed the tenant id? In the header? \n\n\nReally hope I'm asking the right questions.\nRegards, Karl."
] | [
"sql",
"go",
"multi-tenant"
] |
[
"Key Event Handling using Tkinter in Python",
"check the following link out :\n\n[PyObjC Key Event Handling Question] Key Events Handling using PyObjC in Mac OS X\n\nThis was my initial question. I somehow managed to find a built-in plugin to solve the Key Event Management, but using Python. It is called Tkinter.\n\nfrom Tkinter import *\n\nroot = Tk()\ndef screenshot(*ignore): os.system(\"screencapture -s %s\" % check_snapshot) \nroot.bind('<Return>', greet)\nroot.mainloop( )\n\n\nOn pressing return (enter) key, it would successfully call screenshot function, and it would work.\n\nNow, what I am looking for is, whenever I press combination of keys, like Command+Shift+4, the above function should be call.\n\nThis should be done in the same manner for Command+Shift+3 and Command+Shift+5 as well.\n\nThis should be done by checking which combination of keys are pressed, and accordingly, their respective screenshot functions should be called.\n\nAlso, this app shortcuts shouldn't be just relied on this app's window or frame, the window / frame of this window shouldn't be visible, yet, the shortcuts should work and trigger their respective functions.\n\nroot.withdraw()\n\n\nThis is the built-in function which hides the Tkinter window, but then, I am unable to invoke any of the functions. These functions only work on Tkinter window, or else, keys shortcuts don't work.\n\nAny help would be appreciated."
] | [
"python",
"event-handling",
"tkinter",
"keyboard-shortcuts",
"keyevent"
] |
[
"Why Enumerable doesn't inherits from IEnumerable",
"I'm very confused about this issue and can't understand it.In the Enumerable Documentation, I read this:\n\n\n that implement System.Collections.Generic.IEnumerable\n\n\nand some methods like Select() return IEnumerable<TSource> that we can use from other methods like Where() after using that.for example:\n\nnames.Select(name => name).Where(name => name.Length > 3 );\n\n\nbut Enumerable doesn't inherit from IEnumerable<T> and IEnumerable<T> doesn't contain Select(),Where() and etc too...\n\nhave i wrong ?\nor exists any reason for this?"
] | [
"c#",
"linq",
"ienumerable",
"enumerable"
] |
[
"ActionBarSherlock - Share Content icon issue",
"I am using ActionBarSherlock and have implemented ShareActionProvider.\n\nWhen a user selects an app to share content with, eg Twitter, the actionbar displays a Twitter icon next to the Share button icon. This stays there forever.\n\nDoes anybody know how to disable the application icon from appearing next to the Share button?"
] | [
"java",
"android",
"android-actionbar",
"actionbarsherlock"
] |
[
"Create a wrapper for java.sql.Connection that works with JDBC 3 and 4",
"Is there some hack to create a wrapper for java.sql.Connection which works with JDBC 3 and 4 (Sun added a couple of methods and new types to the interface for JDBC 4) without resorting to something which patches the source at compile time?\n\nMy use case is that I need to generate a library which works with Java 5 and 6 and I'd really like to avoid creating two versions of it."
] | [
"java",
"jdbc",
"connection"
] |
[
"How to compile GCC on macOS Catalina?",
"I am trying to compile GCC9 on macOS Catalina. The closest tutorial I've found is this one.\n\nThe tutorial states:\n\nIn order to build GCC install the required header files in the old location:\n\n1 cd /Library/Developer/CommandLineTools/Packages/\n2 open .\n\n\nCommand 1 doesn't work because my file structure is as follows:\n\n - Users/user/Library/Developer/Xcode\n - Users/user/Library/Developer/XCTestDevices\n - /Library/Developer/CommandLineTools/SDKs/\n- /Library/Developer/CommandLineTools/Library/\n\n\nThe package directory is not available.\n\nAlso, as can be seen, the Library/Developer path associated with my user has no CommandlineTools, while that directly on Macintosh HD does.\n\nShould I run the above commands from root /? Or should the CommandLineTools also be available directly to my user?"
] | [
"macos",
"gcc"
] |
[
"How to store jwt token so that redirecting to other subdomain doesn't require the credentials",
"How to store jwt token so that redirecting to other subdomains doesn't require the credentials. I am storing it in a cookie, but on iPhone, it is not working. It is asking for passwords when redirects to other subdomains.\nfunction saveJWT(jwtKey, jwtValue) {\n let days;\n if(!days) {\n days = 365* 20;\n }\n const date = new Date();\n date.setTime(date.getTime() + (days* 24 * 60 * 60 * 1000));\n console.log(date)\n\n const expires = ';expires' + date.toUTCString();\n console.log(expires)\n const prodCookie = jwtKey+ "=" +jwtValue+ expires + \n ";domain=.cerebry.co;path=/"\nconst devCookie = jwtKey+ "=" +jwtValue+ expires + "; path=/ "\n\nif(location.hostname === "localhost"){\n document.cookie = devCookie;\n}\nelse {\n document.cookie = prodCookie;\n}\n\n}"
] | [
"javascript",
"reactjs",
"iphone",
"cookies",
"preact"
] |
[
"Casting derived class to base class keeps knowledge of derived when using generics",
"I have a weird scenario that I can't seem to wrap my head around. I have the following base class:\n\npublic class Note\n{\n public Guid Id { get; set; }\n public string SenderId { get; set; }\n ...\n}\n\n\nWhich is then derived by the following class:\n\npublic class NoteAttachment : Note\n{\n public string FileType { get; set; }\n public string MD5 { get; set; }\n ...\n}\n\n\nI use these classes to communicate with a server, through a generic wrapper:\n\npublic class DataRequest<T> : DataRequest\n{\n public T Data { get; set; }\n}\n\npublic class DataRequest\n{\n public string SomeField { get; set; }\n public string AnotherField { get; set; }\n}\n\n\nSo I have a NoteAttachment sent to the method, but I need to wrap a Note object to send to the server. So I have the following extension method:\n\n public static DataRequest<T> GetDataRequest<T>(this T data)\n {\n DataRequest<T> dataRequest = new DataRequest<T>\n {\n SomeField = \"Some Value\",\n AnotherField = \"AnotherValue\",\n Data = data\n };\n\n return dataRequest;\n }\n\n\nNow the problem. Calling the extension method in the following way works fine, however even though the DataRequest type is DataRequest<Note>, the Data field is of type NoteAttachment.\n\nvar noteAttachment = new NoteAttachment();\n\n...\n\nNote note = (Note)noteAttachment;\n\nvar dataRequest = note.GetDataRequest();\n\nDebug.WriteLine(dataRequest.GetType()); //MyProject.DataRequest`1[MyProject.Note]\nDebug.WriteLine(dataRequest.Data.GetType()); //MyProject.NoteAttachment <--WHY?!\n\n\nWhat am I doing wrong?"
] | [
"c#",
".net",
"generics",
"inheritance"
] |
[
"Why is this JLabel continuously repainting?",
"I've got an item that appears to continuously repaint when it exists, causing the CPU to spike whenever it is in any of my windows. It directly inherits from a JLabel, and unlike the other JLabels on the screen, it has a red background and a border. I have NO idea why it would be different enough to continuously repaint. The callstack looks like this:\n\nThread [AWT-EventQueue-1] (Suspended (breakpoint at line 260 in sItem)) \n sItem.paint(Graphics) line: 260 \n sItem(JComponent).paintToOffscreen(Graphics, int, int, int, int, int, int) line: 5124 \n RepaintManager$PaintManager.paintDoubleBuffered(JComponent, Image, Graphics, int, int, int, int) line: 1475 \n RepaintManager$PaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1406 \n RepaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1220 \n sItem(JComponent)._paintImmediately(int, int, int, int) line: 5072 \n sItem(JComponent).paintImmediately(int, int, int, int) line: 4882 \n RepaintManager.paintDirtyRegions(Map<Component,Rectangle>) line: 803 \n RepaintManager.paintDirtyRegions() line: 714 \n RepaintManager.seqPaintDirtyRegions() line: 694 [local variables unavailable] \n SystemEventQueueUtilities$ComponentWorkRequest.run() line: 128 \n InvocationEvent.dispatch() line: 209 \n summitEventQueue(EventQueue).dispatchEvent(AWTEvent) line: 597 \n summitEventQueue(SummitHackableEventQueue).dispatchEvent(AWTEvent) line: 26 \n summitEventQueue.dispatchEvent(AWTEvent) line: 62 \n EventDispatchThread.pumpOneEventForFilters(int) line: 269 \n EventDispatchThread.pumpEventsForFilter(int, Conditional, EventFilter) line: 184 \n EventDispatchThread.pumpEventsForHierarchy(int, Conditional, Component) line: 174 \n EventDispatchThread.pumpEvents(int, Conditional) line: 169 \n EventDispatchThread.pumpEvents(Conditional) line: 161 \n EventDispatchThread.run() line: 122 [local variables unavailable] \n\n\nIt basically just continually hits that over and over again as fast as I can press continue. The code that is \"unique\" to this particular label looks approximately like this:\n\nbgColor = OurColors.clrWindowTextAlert;\ntextColor = Color.white;\nsetBackground(bgColor);\nsetOpaque(true);\nsetSize(150, getHeight());\nBorder border_warning = BorderFactory.createCompoundBorder(\n BorderFactory.createMatteBorder(1, 1, 1, 1, OurColors.clrXBoxBorder),\n Global.border_left_margin);\nsetBorder(border_warning);\n\n\nIt obviously does more, but that particular block only exists for these labels that are causing the spike/continuous repaint.\n\nAny ideas why it would keep repainting this particular label?"
] | [
"java",
"swing",
"paint"
] |
[
"Rails: Oracle constraint violation",
"I'm doing maintenance work on a Rails site that I inherited; it's driven by an Oracle database, and I've got access to both development and production installations of the site (each with its own Oracle DB). I'm running into an Oracle error when trying to insert data on the production site, but not the dev site:\n\nActiveRecord::StatementInvalid (OCIError: ORA-00001: unique constraint (DATABASE_NAME.PK_REGISTRATION_OWNERSHIP) violated: INSERT INTO registration_ownerships (updated_at, company_ownership_id, created_by, updated_by, registration_id, created_at) VALUES ('2006-05-04 16:30:47', 3, NULL, NULL, 2920, '2006-05-04 16:30:47')):\n/usr/local/lib/ruby/gems/1.8/gems/activerecord-oracle-adapter-1.0.0.9250/lib/active_record/connection_adapters/oracle_adapter.rb:221:in `execute'\napp/controllers/vendors_controller.rb:94:in `create'\n\n\nAs far as I can tell (I'm using Navicat as an Oracle client), the DB schema for the dev site is identical to that of the live site. I'm not an Oracle expert; can anyone shed light on why I'd be getting the error in one installation and not the other?\n\nIncidentally, both dev and production registration_ownerships tables are populated with lots of data, including duplicate entries for country_ownership_id (driven by index PK_REGISTRATION_OWNERSHIP). Please let me know if you need more information to troubleshoot. I'm sorry I haven't given more already, but I just wasn't sure which details would be helpful.\n\nUPDATE: I've tried dropping the constraint on the production server but it had no effect; I didn't want to drop the index as well because I'm not sure what the consequences might be and I don't want to make production less stable than it already is. \n\nCuriously, I tried executing by hand the SQL that was throwing an error, and Oracle accepted the insert statement (though I had to wrap the dates in to_date() calls with string literals to get around an \"ORA-01861: literal does not match format string\" error). What might be going on here?"
] | [
"ruby-on-rails",
"oracle",
"constraints",
"ora-00001"
] |
[
"Why does my font look different?",
"I am using the CGF Locust Resistance Font that I got from dafont.com This is how the font is supposed to look: http://www.dafont.com/cgf-locust-resistance.font and this is how it looks on my webpage: https://postimg.org/image/r2a1xcxun/\n\nAs you can see the letters look more squashed in, particularly noticeable on the \"F\" , \"A\" and \"E\". Here is my CSS and HTML code. Anybody have any idea why it is like this? \n\nHTML:\n\n<html>\n<head>\n <meta charset=\"UTF-8\">\n <title>Gears Of War</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"index.css\">\n</head>\n<header>\n <h1>GEARS OF WAR</h1>\n</header>\n<body>\n <?php\n // put your code here\n ?>\n</body>\n</html>\n\n\nCSS:\n\nbody {\nbackground-color: #1a1a1a;\n}\n\nheader {\nfont-family: CGF Locust Resistance;\nletter-spacing: 30px;\ntext-align: center;\nfont-size: 28px;\ncolor: lightgray;\ntext-shadow:\n-1.5px -1.5px 0 black, \n 1.5px -1.5px 0 black,\n-1.5px 1.5px 0 black,\n 1.5px 1.5px 0 black;\n}\n\n\nFont face declaration:\n\n@font-face {\nfont-family: cgf_locust_resistanceregular;\nsrc: url('Downloads/cgf_locust_resistance-webfont.woff2') format('woff2'),\n url('Downloads/cgf_locust_resistance-webfont.woff') format('woff');\nfont-weight: normal;\nfont-style: normal;\n\n}"
] | [
"html",
"css"
] |
[
"Can't get connection with AD from Java",
"I'm trying retrieve some information from MS AD: members of the specific branch, department names, positions, etc.\n\nI used a lot of examples, including Apache Directory LDAP API and UnboundID, but I can't get the connection with AD.\n\nRDNs:\n\nC:\\Users\\Aleksey> whoami /fqdn\n CN=my common name here,\n OU=my organization unit here,\n OU=organization unit 2 here,\n OU=organization unit 1 here,\n OU=main organization unit here,\n DC=.my domain here,\n DC=domain 2 here,\n DC=main domain here\n\n\nFor searching, I use the following filter:\n\npublic class LdapRetriever {\n public static void main (String[] args) {\n Hashtable env = new Hashtable();\n\n env.put(Context.INITIAL_CONTEXT_FACTORY, \n \"com.sun.jndi.ldap.LdapCtxFactory\");\n env.put(Context.PROVIDER_URL, \"ldap://\" + \n \"ip of domain controller here\" + \":389\");\n env.put(Context.SECURITY_AUTHENTICATION, \"simple\");\n // Also I try to use the following SECURITY_PRINCIPAL: \n // my login only, my domain\\ my login\n env.put(Context.SECURITY_PRINCIPAL, \"my login here\" + \"@\" + \n \"my domain here.domain 2 here.main domain here\");\n env.put(Context.SECURITY_CREDENTIALS, \"my password here\");\n\n try { \n DirContext ctx = new InitialLdapContext(env,null);\n String returnedAtts[]={\"sn\",\"title\",\"department\",\"givenName\"};\n\n SearchControls searchCtls = new SearchControls(); \n searchCtls.setReturningAttributes(returnedAtts); \n searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);\n\n String searchFilter = \"(&(objectClass=user)(cn=*))\";\n String searchBase = \n \"DC=my domain here,DC=domain 2 here,DC=main domain here\";\n\n NamingEnumeration answer = ctx.search(searchBase, \n searchFilter, searchCtls);\n ...\n\n\nWhen I create the directory context by using data from the env I get an exception:\n\nException in thread \"main\" javax.naming.AuthenticationException: \n[LDAP: error code 49 - 80090308: LdapErr: DSID-0C090334, comment:\nAcceptSecurityContext error, data 531, vece\n\n\nIf the password is not specified, I get the following exception:\n\nProblem searching directory: \njavax.naming.NamingException:[LDAP:error code 1 - 00000000: \nLdapErr: DSID-0C090627, comment: \nIn order to perform this operation a successful bind must be completed \non the connection., data 0, vece]; remaining name \n'DC=my domain here,DC=domain 2 here,DC=main domain here'\n\n\nI have verified that my account is not locked.\n\nAccording the list of common active directory LDAP bind errors:\n\n\n525 user not found \n52e invalid credentials \n530 not permitted to logon at this time\n531 not permitted to logon at this workstation\n532 password expired \n533 account disabled \n701 account expired \n773 user must reset password \n775 user account locked\n\n\n\nIn my case it means: \"not permitted to logon at this workstation\", but with the same credentials I can logon to the domain.\n\nWhat could be the reason?"
] | [
"java",
"active-directory",
"ldap"
] |
[
"Chrome Extension Development Instagram Loading Event",
"I recently started developing some minor Chrome Extensions for fun. I am currently working on a \"Download Now\" extension for Instagram that lets you download an Instagram image with a single click on a download button with the value \"Get\" placed in the post header.\n\nAs you can see in the screenshot below the button appears as expected.\n\n\n\nBut when I scroll down the point where it loads new posts, the button does not appear.\n\n\n\nMy question for now is, how can I predict the loading event so the button is gonna appear on the posts that are loading?\n\nMy jQuery looks like this so far,\n\njQuery(document).ready(function() {\n jQuery(window).load(function() {\n var location = jQuery('._s6yvg');\n jQuery(location).each(function() {\n var image = jQuery(this).parent().find('div > div > div > div > img').attr('src');\n jQuery('<a class=\"get-button\" href=\"' + image + '\">Get</a>').appendTo(this);\n });\n });\n});\n\n\nIf you need more information about the extension just let me know, I think I got the most important written. I am sorry for the bad language. I'm not a native speaker.\n\nThanks in advance."
] | [
"javascript",
"jquery",
"google-chrome",
"instagram"
] |
[
"Address book implementation not working",
"I am using XCode 4.2 to develop a function to add a contact to the address book , here is my code\n\n ABAddressBookRef *iPhoneAddressBook = ABAddressBookCreate();\n ABRecordRef contact = ABPersonCreate();\n\n //add infos\n ABRecordSetValue(contact, kABPersonFirstNameProperty,(__bridge_retained CFStringRef)firstName, nil);\n ABRecordSetValue(contact, kABPersonLastNameProperty,(__bridge_retained CFStringRef)lastName, nil);\n ABRecordSetValue(contact, kABPersonOrganizationProperty, (__bridge_retained CFStringRef)organization, nil);\n ABRecordSetValue(contact, kABPersonJobTitleProperty, (__bridge_retained CFStringRef)title, nil);\n\n\n ABMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiRealPropertyType);\n\n\n ABMultiValueAddValueAndLabel(multiPhone, (__bridge_retained CFStringRef)workTel, kABPersonPhoneMainLabel, NULL);\n ABMultiValueAddValueAndLabel(multiPhone, (__bridge_retained CFStringRef)workFax, kABPersonPhoneWorkFAXLabel, NULL);\n\n ABRecordSetValue(contact, kABPersonPhoneProperty, multiPhone, nil);\n CFRelease(multiPhone);\n\n ABMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);\n\n ABMultiValueAddValueAndLabel(multiEmail, (__bridge_retained CFStringRef)email, kABWorkLabel, NULL);\n\n ABRecordSetValue(contact, kABPersonEmailProperty, multiEmail, nil);\n\n CFRelease(multiEmail);\n// address\n\nABMultiValueRef multiAddress =ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);\nNSMutableDictionary *addressDict = [[NSMutableDictionary alloc]init];\n[addressDict setObject:address forKey:(NSString *) kABPersonAddressStreetKey];\n[addressDict setObject:city forKey:(NSString *) kABPersonAddressCityKey];\n[addressDict setObject:province forKey:(NSString *) kABPersonAddressStateKey];\n[addressDict setObject:postalCode forKey:(NSString *) kABPersonAddressZIPKey];\n[addressDict setObject:address forKey:(NSString *) kABPersonAddressCountryKey];\n\nABMultiValueAddValueAndLabel(multiAddress, (__bridge_retained CFStringRef)addressDict, kABWorkLabel, NULL);\nABRecordSetValue(contact, kABPersonAddressProperty, multiAddress, NULL);\n\n\nCFRelease(multiAddress);\n\nABMultiValueRef multiURL =ABMultiValueCreateMutable(kABMultiRealPropertyType);\nABMultiValueAddValueAndLabel(multiURL, (__bridge_retained CFStringRef)link, kABPersonURLProperty, NULL);\nCFRelease(multiURL);\n\n\n\n ABAddressBookAddRecord(iPhoneAddressBook, contact, nil);\n\n BOOL didAdd = ABAddressBookSave(iPhoneAddressBook, nil);\n\n CFRelease(contact);\n CFRelease(iPhoneAddressBook);\n\n //notifying the user that it was stored in his address book\n if (didAdd) {\n\n\n UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@\"Confirmation\" \n message:@\"Contact Info successfully added to the Address Book\" \n delegate:self \n cancelButtonTitle:@\"OK\" \n otherButtonTitles:nil];\n [alert show];\n }\n\n\nthe program compiles and but it stops at this line :\n\nABMultiValueAddValueAndLabel(multiPhone, (__bridge_retained CFStringRef)workTel, kABPersonPhoneMainLabel, NULL);\n\n\nI get this error (in green)\n\nThread 1\n\n\nany clue ? what is wrong in the code ?"
] | [
"iphone",
"objective-c",
"ios",
"addressbook"
] |
[
"Flex/Bison not evaluating properly",
"For some reason or another, bison doesn't want to do any evaluation. Compilation of all files goes smoothly and the program runs. When I enter the expression 4+5 and press return, it creates tokens for 4 + 5 respectively. I can even put in some printf into the places where bison recognizes the attributes of each token including the plus (43).\n\nHowever the program never evaluates this production expr '+' term { $$ = $1 + $3; }. It's simply never called at least to my knowledge and even if it was this production assign '\\n' { printf(\"%d\\n\", $1); } never prints out the value. Upon ^D to quit, it fires void yyerror(const char *).\n\nAny help on this matter is much appreciated. Thanks!\n\n//FLEX\n%{\n //#include <stdio.h>\n #include \"y.tab.h\"\n%}\n\n%option noyywrap\n\nletter [A-Za-z]\ndigit [0-9]\nspace [ \\t]\n\nvar {letter}\nint {digit}+\nws {space}+\n\n%%\n\n{var} { yylval = (int)yytext[0]; return VAR; }\n{int} { yylval = atoi(yytext); return CONST; }\n{ws} { }\n. { return (int)yytext[0]; }\n\n%%\n\n/* nothing */\n\n\n.\n\n//BISON\n%{\n\n//INCLUDE\n//#include <ctype.h>\n\n//DEFINE\n#define YYDEBUG 1\n\n//PROTOTYPE\nvoid yyerror(const char *);\nvoid print_welcome();\nint get_val(int);\nvoid set_val(int, int);\n\n%}\n\n%token CONST\n%token VAR\n\n%%\n\nsession\n : { print_welcome(); }\n eval\n ;\n\neval\n : eval line\n |\n ;\n\nline\n : assign '\\n' { printf(\"%d\\n\", $1); }\n ;\n\nassign\n : VAR '=' expr { set_val($1, $3); $$ = $3; }\n | expr { $$ = $1; }\n ;\n\nexpr\n : expr '+' term { $$ = $1 + $3; }\n | expr '-' term { $$ = $1 - $3; }\n | term { $$ = $1; }\n ;\n\nterm\n : term '*' factor { $$ = $1 * $3; }\n | term '/' factor { $$ = $1 / $3; }\n | term '%' factor { $$ = $1 % $3; }\n | factor { $$ = $1; }\n ;\n\nfactor\n : '(' expr ')' { $$ = $2; }\n | CONST { $$ = $1; }\n | VAR { $$ = get_val($1); }\n ;\n\n%%\n\nvoid yyerror(const char * s)\n{\n fprintf(stderr, \"%s\\n\", s);\n}\n\nvoid print_welcome()\n{\n printf(\"Welcome to the Simple Expression Evaluator.\\n\");\n printf(\"Enter one expression per line, end with ^D\\n\\n\");\n}\n\nstatic int val_tab[26];\n\nint get_val(int var)\n{\n return val_tab[var - 'A'];\n}\n\nvoid set_val(int var, int val)\n{\n val_tab[var - 'A'] = val;\n}\n\n\n.\n\n//MAIN\n\n//PROTOTYPE\nint yyparse();\n\nint main()\n{\n extern int yydebug;\n yydebug = 0;\n yyparse();\n return 0;\n}"
] | [
"c++",
"c",
"bison",
"flex-lexer"
] |
[
"How does one create a Play Module?",
"The Play framework documentation is kind of weak when it comes to module creation.\n\n\nHow does one creates a Module ?\nI've read that large applications could be split across several modules, how ?\nWhat can/can't be done with a module ? (any access to low level api ?)\nCan a play module expose abstract JPA classes ?\nWhat's the best way to package a module ?\nHow to deploy/distribute a play module ?\n\n\nI think you get the idea... tell us all about Modules using the Playframework."
] | [
"java",
"playframework"
] |
[
"Populating mxml with JSON data containing urls",
"I just started learning Flex today. I faced a problem. I have some JSON data returned from my webservice, like this:\n\n[{\"id\":\"34\",\"url\":\"im3.png\",\"uid\":\"1\",\"pr\":\"1\"},{\"id\":\"33\",\"url\":\"im2.jpg\",\"uid\":\"1\",\"pr\":\"0\"},{\"id\":\"32\",\"url\":\"im1.jpg\",\"uid\":\"1\",\"pr\":\"1\"}]\n\nI can decode it and store in array which populates my DataGrid.\n\n<mx:DataGrid id=\"prGallery\" left=\"25\" right=\"25\" top=\"25\" bottom=\"25\" dataProvider=\"{prDB}\">\n\nprDB is intialized \"on load\". \n\nEverything works fine but... I would like to display images out of those URLs (images are stored on my server under xxxxx.xx/url. \n\nStoring tags like <img src=\"xxxxx.xx/url\"/> obviously doesn't work. So here come my questions:\n\n\nFirstly, is it a good idea to use DataGrid for displaying images? (Even though I couldn't see the result I think it's not.)\nWhat other component should I use in order to populate it with unknown number of records. (rows contain both text and image)."
] | [
"json",
"actionscript-3",
"apache-flex",
"datagrid",
"mxml"
] |
[
"How can I use the 3dconnexion spacemouse mouse in Pythons vtk",
"I am reading an stl file and simply showing it on the Screen (and adding some results later). The turning and handling of the object is not really smooth.\n\nIt would be cool to get the 3dconnexion spacemouse to work in order to manipulate the objekt. Is it possible? How?\n\nWhat do I have to add to the interactor?\n\nThank you for help\n\nOkapi\n\nimport vtk\n\nclass VtkStl:\n\ndef __init__(self, filename):\n self.filename = filename\n self.vtkActor = vtk.vtkActor()\n\ndef addStl(self):\n reader = vtk.vtkSTLReader()\n reader.SetFileName(self.filename)\n mapper = vtk.vtkPolyDataMapper()\n if vtk.VTK_MAJOR_VERSION <= 5:\n mapper.SetInput(reader.GetOutput())\n else:\n mapper.SetInputConnection(reader.GetOutputPort()) \n self.vtkActor.SetMapper(mapper)\n\nBock_stl=VtkStl('d:\\trial.stl') \nBock_stl.addStl()\n\n# Renderer\nrenderer = vtk.vtkRenderer()\nrenderer.AddActor(Bock_stl.vtkActor)\n\nrenderer.SetBackground(.2, .3, .4)\nrenderer.ResetCamera()\n\n# Render Window\nrenderWindow = vtk.vtkRenderWindow()\nrenderWindow.AddRenderer(renderer)\n\n# Interactor\nrenderWindowInteractor = vtk.vtkRenderWindowInteractor()\nrenderWindowInteractor.SetRenderWindow(renderWindow)\n\n# Begin Interaction\nrenderWindow.Render()\nrenderWindowInteractor.Start()\n\ndel renderWindow, renderWindowInteractor\n\n\nThank you for your help."
] | [
"python",
"mouse",
"vtk"
] |
[
"File Monitor Archiver Powershell",
"I have written some PowerShell that checks for new files and when a new file is created it runs an action.\n\nThe action is to check the filename and check for a previous version, if there is a previous version move the previous version to an archive folder. The previous version is defined as such:\n\nfilename structure: xxxx-xxxx-xx.pdf\n\nFirst xxxx can be any amount of characters + numbers.\n\nSecond xxxx can be any amount of characters + numbers.\n\nThird part is only ever numerical 00 to 99 e.g. 01 02 03\n\nSo if I drop in file 85080-00-02.pdf and 85080-00-01.pdf exists it will move the latter file to the archive folder, now this is all working OK with the code I have at the moment.\n\nThis system is going to be used by standard engineering staff so I need to ensure all user error is catered for. When I run my code with characters in the 3rd part e.g. 85080-00-0t (imagine someone accidently typed a t instead of a 5, don't ask me how but I know it will happen) it will just stop working.\n\n\nWhy don't I see any errors anywhere? If I put a Write-Host in the code, I can see it display in ISE the output but I don't see any errors for when the above happens.\nHow do I get this to work correctly? I can tell the error is because my code is trying to -1 from a string and that’s obviously causing it problem.\n\n\nSo how can I say: \n\nIf $olddw = any number from 00 - 99 carry on with code, else do nothing.\n\n# Enter the root folder you want to monitor\n$folder = **FOLDER LOCATION**\n$archivefolder = **ARCHIVE FOLDER LOCATION**\n\n# Enter the log file location\n$log = **LOG LOCATION**\n\n# You can enter a wildcard filter here. \n$filter = '*.*'\n$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{\n IncludeSubdirectories = $false;\n NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'\n}\n\n#New file ObjectEvent\nRegister-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { \n #Get new filename and create log\n $name = $Event.SourceEventArgs.Name \n $changeType = $Event.SourceEventArgs.ChangeType \n $timeStamp = $Event.TimeGenerated \n Out-File -FilePath $log -Append -InputObject \"The file '$name' was $changeType at $timeStamp\"\n\n #Set old filename \n $oldname = $name.Substring(0, $name.Length-4)\n $olddw = \"{0:D2}\" -f (($oldname.Substring($oldname.Length - 2)) - 1)\n $oldfilename = ($oldname.Substring(0, $oldname.Length-2) + $olddw + \".pdf\")\n $oldfilelocation = ($folder + $oldfilename)\n\n #Check if old filename exists if so move it to archive folder\n $FileExists = Test-Path $oldfilelocation\n if ($FileExists -eq $true) {\n Move-Item $oldfilelocation $archivefolder\n Out-File -FilePath $log -Append -InputObject \"The file '$oldfilename' was Archived at $timeStamp\"\n } else {\n # do nothing\n }\n}\n\n#To view current ObjectEvent's\n#Get-EventSubscriber\n\n#To stop current ObjectEvent\n#Unregister-Event FileCreated"
] | [
"powershell",
"filesystemwatcher"
] |
[
"Load markers dynamically while the page is loading",
"is it possible to initialise a google map and then load the pins dynamically on it?\nWhat I would like is a map where....as soon as the data is available, its marker pops up.\nI am on a situation where the data come quite slowely so...it would me nice to give a feedback showing this partial results while the rest of the data come.\n\nThanks in advance."
] | [
"javascript",
"html",
"google-maps",
"maps"
] |
[
"How to tell CPAN about path to make and cc",
"Running Perl 5.10 CPAN on Solaris with opencsw.org packages, Makefile.PL from packages can't find the correct path and cc (gcc). \n\nI found the path to make and set it to gmake, but I can't find any setting for cc.\n\nI thought I once set this in CPAN/Config.pm (or with o config ...) but can no longer find any setting and don't have enough patience to wade through the thicket to figure out where such a basic thing gets set.\n\nDoes anyone know?"
] | [
"perl",
"cpan",
"solaris-10"
] |
[
"How to move username/passwords out of spring-security-context.xml?",
"I am using Spring Security in one of my project. The web-app requires the user to login. Hence I have added few usernames and passwords in the spring-security-context.xml file as follows:\n\n<authentication-manager>\n <authentication-provider>\n <user-service>\n <user name=\"user_1\" password=\"password_1\" authorities=\"ROLE_USER\" />\n <user name=\"user_2\" password=\"password_2\" authorities=\"ROLE_USER\" />\n </user-service>\n </authentication-provider>\n</authentication-manager>\n\n\nMy question is, how to move these username-password pairs to a different file (like some properties file) instead of keeping them in spring-security-context.xml? And how to read that file properties file?"
] | [
"spring",
"spring-mvc",
"spring-security"
] |
[
"Delete files except those whose name matches a string",
"I'm trying to delete all files (include subdir) in a directory but only files which not match specific file name: \"equipe\" \"match\" \"express\"\n\nI'm trying to do it with this command\n\nfind . -type f '!' -exec grep -q \"equipe\" {} \\; -exec echo rm {} \\;\n\n\n\nThat doesn't work. It echos files with \"equipe\" inside\nHow can I do it with multiple strings? (\"equipe\" \"match\" \"express\")"
] | [
"bash",
"grep",
"find"
] |
[
"C++ messagebox with TCHAR and string concatenation",
"Can somebody please tell me how I can output szFileName in a messagebox?\n\nMy attempt below does not work\n\n//Retrieve the path to the data.dat in the same dir as our app.dll is located\n\nTCHAR szFileName[MAX_PATH+1];\nGetModuleFileName(_Module.m_hInst, szFileName, MAX_PATH+1);\nStrCpy(PathFindFileName(szFileName), _T(\"data.dat\"));\n\nFILE *file =fopen(szFileName,\"rb\");\nif (file)\n{\n fseek( file,iFirstByteToReadPos, SEEK_SET);\n fread(bytes,sizeof(unsigned char), iLenCompressedBytes, file);\n fclose(file);\n}\nelse\n{\n MessageBox(NULL, szFileName + \" not found\", NULL, MB_OK);\n DebugBreak();\n}"
] | [
"c++",
"messagebox"
] |
[
"Isn't the http module of nodejs capable of receiving / sending the whole request / response at once?",
"I am learning to http module of nodejs. I found a section in the documentation that says:\n\n\n The interface is careful to never buffer entire requests or responses\n\n\nDoes it means that this module is not capable of receiving / sending the whole request / response at once and it receives / sends in chunks instead?"
] | [
"node.js",
"http",
"nodejs-stream"
] |
[
"List vs Arrays in a generated proxy class in c#",
"I have a WCF service and when I generated the client proxy class with svcutil it changed my list properties to arrays. is there an option to ensure that I maintain the Lists without modifying the generated class in C#?\n\n//The object in the service…\n\n[System.CodeDom.Compiler.GeneratedCodeAttribute(\"svcutil\", \"3.0.4506.2152\")]\n[System.SerializableAttribute()]\n[System.Diagnostics.DebuggerStepThroughAttribute()]\n[System.ComponentModel.DesignerCategoryAttribute(\"code\")]\n[System.Xml.Serialization.XmlTypeAttribute(Namespace = \"http://brax.com/data/Query\")]\npublic partial class PayloadType\n{\n private List<PersonType> personBasedQueryField;\n private List<LocationType> locationBasedQueryField;\n\n\n//Generated class...\n\n[System.CodeDom.Compiler.GeneratedCodeAttribute(\"svcutil\", \"3.0.4506.2152\")]\n[System.SerializableAttribute()]\n[System.Diagnostics.DebuggerStepThroughAttribute()]\n[System.ComponentModel.DesignerCategoryAttribute(\"code\")]\n[System.Xml.Serialization.XmlTypeAttribute(Namespace = \"http://brax.com/data/Query\")]\npublic partial class PayloadType\n{\n private PersonType[] personBasedQueryField;\n private LocationType[] locationBasedQueryField;"
] | [
"c#",
"wcf"
] |
[
"SQL Query with single quotes",
"getting Error while executing this query , because column text may contain text with single quotes also. How can i use this query w/o any error\nMy code is\n\npublic bool updateCMStable(int id, string columnName, string columnText)\n{\n try\n {\n string sql = \"UPDATE CMStable SET \" + columnName + \n \"='\" + columnText + \"' WHERE cmsID=\" + id;\n int i = SqlHelper.ExecuteNonQuery(Connection.ConnectionString,\n CommandType.Text,\n sql);\n if (i > 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n catch (Exception ee)\n {\n throw ee;\n }\n}"
] | [
"c#",
".net",
"sql",
"database"
] |
[
"SQL Server Online browser/editor",
"Could anyone suggest any software which I could deploy on IIS7 and access SQL Server online. I mean browse databases, edit records and etc. It's like Microsoft SQL Server Management Studio but online version."
] | [
"sql",
"sql-server",
"tsql",
"sql-server-2008"
] |
[
"Using lead with dplyr to compute the difference between two time stamps",
"I want to find the difference between two time stamps based on finding the time stamp in one column based on a condition, \"Start\", and then finding the time stamp for the first row that meets another condition in that same column, \"Stop\". Basically we used a program to \"start\" a behavior and \"stop\" a behavior so we could calculate the duration of the behavior. \n\nI've tried adapting the code found in this post: subtract value from previous row by group\n\nbut I can't figure out how to get the lead to work on meeting a condition in upcoming rows for the same column. It's complicated by the fact that there can be \"event\" behaviors that have a \"start\" but no \"stop\". Example data frame.\n\nData\nBehavior Modifier_1 Time_relative_s \nBodyLength Start 122.11 \nGrowl Start 129.70\nBody Length Stop 132.26 \nBody Length Start 157.79 \nBody Length Stop 258.85 \nBody Length Start 270.12 \nBark Start 272.26\nGrowl Start 275.68\nBody Length Stop 295.37\n\n\nand I want this:\n\nBehavior Modifier_1 Time_relative_s diff \nBodyLength Start 122.11 10.15\nGrowl Start 129.70 \nBody Length Stop 132.26 \nBody Length Start 157.79 101.06 \nBody Length Stop 258.85 \nBody Length Start 270.12 25.25 \nBark Start 272.26\nGrowl Start 275.68\nBody Length Stop 295.37\n\n\nI've tried using dplyr pipes:\n\ntest<-u%>%\n filter(Modifier_1 %in% c(\"Start\",\"Stop\")) %>%\n arrange(Time_Relative_s) %>%\n mutate(diff = lead(Time_Relative_s, default = first(Time_Relative_s==\"Stop\")-Time-Relative_s)\n\n\nBut I must not be using lead right because this just returns the Time_Relative_s for me in the diff column. Any suggestions? Thanks for the help!"
] | [
"r",
"dplyr",
"lead"
] |
[
"Elasticsearch + django: Unknown mimetype, unable to deserialize: text/html",
"I have browsed for this error on Stackoverflow and elsewhere, but nothing helps.\nI have installed django-elasticsearch-dsl and added it to my INSTALLED_APPS. In my settings, I have:\nELASTICSEARCH_DSL={\n 'default': {\n 'hosts': 'localhost:9200'\n },\n}\n\nNext, I have a 'documents.py' file where the logic for Elastic search resides.\nWhen I try running python manage.py search_index --rebuild, I get this error:\n\nelasticsearch.exceptions.SerializationError: Unknown mimetype, unable to deserialize: text/html\n\nI don't know if I understand correctly how to run the ES server. I have tried to run the local server on port 9200 but the issue persists."
] | [
"django",
"elasticsearch"
] |
[
"Angular 9 - How to refresh form page after HttpClient POST?",
"I have an Angular 9 application and am having some trouble getting my page to refresh after a HttpClient POST request.\n\nHere is my form and form component:\n\n<form #myForm=\"ngForm\" (ngSubmit)=\"save(myForm)\">\n <button type=\"submit\" class=\"btn btn-success submit-button\">\n Submit\n </button>\n</form>\n\n----------------------------------------------------------\n\n@Component({\n selector: 'my-form',\n templateUrl: './my-form.component.html',\n})\nexport class MyFormComponent implements OnInit {\n constructor(private apiService: APIService, private ngZone: NgZone, private router: Router) {}\n\n ngOnInit() {}\n\n save(myForm: NgForm) {\n this.apiService.addSomething(myForm.value).subscribe((res) => {\n // Not sure what to do here to get the page to reload.\n });\n }\n}\n\n\nI have tried doing a this.apiService.getSomething() call (which is the REST endpoint for getting all the things). I have tried doing something like this.ngZone.run(() => this.router.navigate('/')) that I saw in a different question here on SO but that didn't work either.\n\nAny help would be greatly appreciated.\n\nFor good measure, here is my api service:\n\n@Injectable({\n providedIn: 'root',\n})\nexport class APIService {\n private SERVER_URL = 'http://localhost:8080';\n\n constructor(private httpClient: HttpClient) {}\n\n httpOptions = {\n headers: new HttpHeaders({\n 'Content-Type': 'application/json',\n }),\n };\n\n // Get all the things\n public getAllThings() {\n return this.httpClient.get(this.SERVER_URL + '/things').pipe(catchError(this.handleError));\n }\n\n // Add a thing\n public addSomething(thing: ThingType) { \n return this.httpClient\n .post(this.SERVER_URL + '/things', submission, this.httpOptions)\n .pipe(catchError(this.handleError));\n }\n}\n\n\nEdit: My goal is to show a success message (perhaps, near the submit button) indicating that the form has been submitted and to clear the form out."
] | [
"angular"
] |
[
"packaging maven project with external jar",
"I've been trying to make a runnable jar from my project (in Intellij IDEA) which has a dependency to an oracle (driver -> ojdbc6) jar. When I package the project with all of the dependencies, the only one what will be excluded is the jar. Which means my db queries are going to fail when I run it.\nI've found several similar questions*, but I've failed the execution of them, because I don't know the groupid and artifact id of the oracle's jar.\n\n*like this one: build maven project with propriatery libraries included\n\np.s.: the jar wad added through the IDEA's feature (project structure -> modules), and with this solution the project could run without failure. The problem starts with the packaging."
] | [
"maven",
"intellij-idea",
"jar"
] |
[
"what is wrong with this partially applied function attempt?",
"I am trying to write a partially applied function. I thought the below would work but it doesn't. Grateful for any help.\n\nscala> def doSth(f: => Unit) { f }\ndoSth: (f: => Unit)Unit\n\nscala> def sth() = { println (\"Hi there\") }\nsth: ()Unit\n\nscala> doSth(sth)\nHi there\n\nscala> val b = sth _\nb: () => Unit = <function0>\n\nscala> doSth(b)\n<console>:11: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses\n doSth(b)\n ^\n\n\nThanks!"
] | [
"scala"
] |
[
"How to install phpmyadmin to mysql instance",
"I have created mysql instance from google cloud,\nI will like to use database via phpmyadmin\nto create tables, import from old sql.\n\nCan I install phpmyadmin under deployed mysql google cloud,\nOr I have to have phpmyadmin or third party software which I can install to my computer to access sql created under google cloud."
] | [
"sql",
"phpmyadmin",
"google-cloud-sql"
] |
[
"ImageView source load from another class",
"sorry for the question but i'm newbie in Android,\nI want to change the source of a ImageView calling another class, but the application closes.\n\nThe source code:\n\npublic class JugarActivity extends Activity {\n\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_jugar);\n int nivel = 1;\n\n Niveles crearnivel = new Niveles();\n crearnivel.CrearNivel(nivel);\n\n}\n\n@Override\npublic boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.activity_jugar, menu);\n return true;\n}\n\n}\n\n\nThe class:\n\npublic class Niveles extends JugarActivity {\nImageView pregunta = (ImageView) findViewById(R.id.imagePregunta);\nImageView respuestaA = (ImageView) findViewById(R.id.imageRespuesta1);\nImageView respuestaB = (ImageView) findViewById(R.id.imageRespuesta2);\nImageView respuestaC = (ImageView) findViewById(R.id.imageRespuesta3);\nImageView respuestaD = (ImageView) findViewById(R.id.imageRespuesta4);\n\npublic void CrearNivel(int nivel) {\n if(nivel == 1) {\n pregunta.setImageResource(R.drawable.pregunta1); \n respuestaA.setImageResource(R.drawable.pregunta1_a); \n respuestaB.setImageResource(R.drawable.pregunta1_b); \n respuestaC.setImageResource(R.drawable.pregunta1_c); \n respuestaD.setImageResource(R.drawable.pregunta1_d); \n }\n}\n}\n\n\nWhat's wrong? \nThanks"
] | [
"android",
"class",
"imageview",
"extend"
] |
[
"Best type for IP-address in Hibernate Entity?",
"What is the best type for storing IP-addresses in a database using Hibernate?\n\nI though Byte[] or String, but is there a better way, or what do you use?\n\n @Column(name = \"range_from\", nullable = false)\n public Byte[] getRangeFrom() {\n return rangeFrom;\n }\n public void setRangeFrom(Byte[] rangeFrom) {\n this.rangeFrom = rangeFrom;\n }"
] | [
"hibernate",
"ip-address",
"entity"
] |
[
"Classification of time series - how to train one model using data from multiple location?",
"I have data sources from weather sensors around multiple locations. I am trying to classify whether a certain event is occurring (simple binary classification). \nI have labeled data (1 mil. samples for each location - 15 minutes interval).\n\nI assume that the event that i try to classify is very simple (many patterns occur in same ways on all locations)\n\nI would like to make one model for all locations but also with the ability to generalize for the next locations that will be added. \n\nRight now i am using simple BiLSTM network and the data is pre-processed with a rolling window like this:\n\n def create_dataset(self, dataset, look_back=1):\n dataX, dataY = [], []\n for i in range(len(dataset) - look_back - 1):\n a = dataset[i:(i + look_back), :]\n dataX.append(a)\n dataY.append(dataset[i + look_back, 0])\n return np.array(dataX), np.array(dataY)\n\n\nMy first thought is to pre-process each location with rolling window, concatenate all the data into one training set and shuffle before each epoch.\n\nDo you think it is a good approach ? Can you suggest a better one ? Am I missing something ?\n\nThanks in advance.\n\nEDIT: I don't want to tell my model during the training the exact location because in the future when i would like to predict the event at a new location the current training would be biased towards some location."
] | [
"python",
"neural-network",
"time-series"
] |
[
"Colour patterns or functions, pyxplot",
"I'm using a program called pyxplot and I'm doing some colourmaps.\nTo specify the colors, I can use RGB, HSB or CMYK patterns using\n\nset colourmap ( rgb<r>:<g>:<b> |\n hsb<h>:<s>:<b> |\n cmyk<c>:<m>:<y>:<k> )\n\n\nAll values goes from 0 to 1 and that specifies a color for the f(x,y) = c1 function.\nFor example, I can do \n\n set colourmap rgb(c1):(0):(0)\n\n\nand it gives me a colourmap from white to red (red for values of c1 that are 1, white for 0)\nI want to know if someone has an idea to form some color patterns (or if someone has some reference) like the 'jet' of Matlab of this page http://www.mathworks.com/help/techdoc/ref/colormapeditor.html\nBecause I try to combine colors but i can't get nice patterns.\n\nI could do \n\n set colourmap hsb(0.5*c1+0.1):(1):(1)\n\n\nand it gives me from orange to blue on hsb range of colours, but, what if I want other colours in the range?"
] | [
"plot",
"rgb",
"cmyk",
"hsb",
"pyxplot"
] |
[
"Get a date and show it even after midnight for about 2 hours",
"I should be able to get the first Wednesday of each month, I can do it easily using: \n\n$firstWedNextMonth = date ('d-m-Y', strtotime('first wednesday of next month'));\necho \"The first wed of next month is: \".$firstWedNextMonth;\n\n\nHowever, considering that the first Wednesday of next month is March 6th, the system must show this date until 3:00:00 on Thursday March 7th, at 3:00:01 instead it must indicate Wednesday, April 3rd. I do not know how to do it. Thank you"
] | [
"php"
] |
[
"Get all face colors without plotting the chart on Jupyter notebooks",
"I am trying to plot the following values using a moving average approach but I am having some issues getting the right facecolor.\ndifference = [-9.11476554e-03, 6.96440932e-01, 1.55848671e+00, 2.49302039e+00,\n 1.78664413e+00, 9.21715740e-01, -9.06779211e-02, 3.85599550e-01,\n 7.62364171e-01, 8.43788498e-01, 3.65637016e-01, -3.09278853e-02,\n -3.94263747e-02, -3.99640149e-01, -3.77036512e-01, -9.38614302e-01,\n -9.44227778e-01, -7.56399423e-01, -1.91719761e-01, 1.74602851e-01,\n -1.75804630e-01, -7.88096542e-01, -8.65569748e-01, -9.52364646e-01,\n -3.29532285e-01, -2.49750018e-01, -2.03776029e-03, 3.40896487e-01,\n -1.04289662e-01, -1.11517509e-01, 5.84315453e-02, 1.21235574e+00,\n 1.35715932e+00, 1.42280158e+00, 1.24305359e+00, 1.10727093e+00,\n 5.28615206e-01, -2.11163359e-02, -4.20183478e-01, -4.22867124e-01,\n 9.57720715e-02, 4.81484548e-01, 1.26236096e+00, 1.38971651e+00,\n 1.40270113e+00, 6.00938954e-01, -2.46022101e-02, -2.70847276e-02,\n -3.32089611e-03, -1.54348517e-01]\n\nFirst I make a scatter plot using these values and then length.\nfig, ax = plt.subplots(figsize=(13, 8))\nplt.style.use("ggplot")\n\ncmap_name = 'inferno'\nscat = ax.scatter(range(len(difference)), difference, c=difference, cmap=cmap_name)\n\n\nThen, I want the facecolors to draw a lines chart with the moving average:\ncolors = scat.get_facecolors()\nax.plot([0, len(difference)], [0,0], color='dodgerblue', zorder=1, linestyle="-.")\nfor num, (x0, x1, col) in enumerate(zip(difference[:-1], difference[1:], colors)):\n ax.plot([num, num+1], [x0, x1], color=col, zorder=2)\nscat.set_alpha(0)\n\nI am using Jupyter Notebooks and if I run these 2 pieces of code in two individual cells it works decently and I get my output.\n\nHowever If I combine in one cell, colors have only one element.\nfig, ax = plt.subplots(figsize=(13, 8))\nplt.style.use("ggplot")\n\ncmap_name = 'inferno'\nscat = ax.scatter(range(len(difference)), difference, c=difference, cmap=cmap_name)\n\ncolors = scat.get_facecolors()\n\nax.plot([0, len(difference)], [0,0], color='dodgerblue', zorder=1, linestyle="-.")\nfor num, (x0, x1, col) in enumerate(zip(difference[:-1], difference[1:], colors)):\n ax.plot([num, num+1], [x0, x1], color=col, zorder=2)\nscat.set_alpha(0)\n\nAnd colors:\n[[0.20392157, 0.54117647, 0.74117647, 1. ]]\n\nand the chart looks like this:\n\nIs there any way to get all the facecolors without plotting everything and get it afterwards?\nThank you"
] | [
"python",
"matplotlib",
"jupyter-notebook"
] |
[
"Create a parabolic trajectory with fixed angle",
"I'm trying to throw an arrow in my XNA game, but I'm having a hard time trying to realize a good parabola.\n\nWhat I need:\n\n\nThe more you hold Enter stronger the arrow goes.\nThe arrow angle will be always the same, 45 degrees.\n\n\nThis is what I have already have:\n\nprivate float velocityHeld = 1f;\nprotected override void Update(GameTime gameTime)\n{\n\n if (Keyboard.GetState().IsKeyDown(Keys.Enter) && !released)\n {\n timeHeld += velocityHeld;\n holding = true;\n }\n else\n {\n if (holding)\n {\n released = true;\n holding = false;\n lastTimeHeld = timeHeld;\n }\n }\n\n\n if (released && timeHeld > 0)\n {\n float alpha = MathHelper.ToRadians(45f);\n double vy = timeHeld * Math.Sin(alpha);\n double vx = timeHeld * Math.Cos(alpha);\n\n ShadowPosition.Y -= (int)vy;\n ShadowPosition.X += (int)vx;\n timeHeld -= velocityHeld;\n }\n else\n {\n released = false;\n }\n}\n\n\nMy question is, what do I need to do to make the arrow to go bottom as it loses velocity (timeHeld) to make a perfect parabola?"
] | [
"c#",
"algorithm",
"xna",
"game-physics",
"projectile"
] |
[
"SQL: Left join for employee ID",
"I am very new to SQL, but after researching this issue I have been unable to find an answer which works for me.\n\nTL-DR:\nI am trying to bring in the approver name and approval status to a query which shows unposted journals. Since I am already bringing in the 'Created_by' name I need to match to the user id table twice but with a different column.\n\nThe GL_JE_BATCHES gives me the workflow and approver_id fields, and essentially I want to add these two columns into my existing report. With the complication of looking up the approver_id against a username table and bringing in the name rather than the id.\n\nHere's my code so far:\n\n`select distinct hdr.JE_BATCH_ID,\nhdr.JE_HEADER_ID,\nusr.description Preparer,\nhdr.CREATED_BY, hdr.CREATION_DATE,\ngjb.approver_employee_id,\n\nDECODE (gjb.approval_status_code, \n'A', 'Approved',\n'I', 'In Process',\n'J', 'Rejected',\n'R', 'Required',\n'V', 'Validation Failed',\n'Z', 'N/A') Workflow_Status\n\nfrom gl.GL_JE_HEADERS hdr, apps.fnd_user usr, GL.GL_Ledgers ldg\n\nleft join gl.GL_JE_BATCHES gjb ON hdr.JE_BATCH_ID = gjb.JE_BATCH_ID\n\nwhere 1=1\n and hdr.created_by = usr.user_id\n and hdr.Ledger_ID = ldg.Ledger_ID\n and hdr.PERIOD_NAME = 'MAY-17'\n --and hdr.JE_BATCH_ID = gjb.JE_BATCH_ID\n and hdr.STATUS = 'U' \n\n\nWhen running this code i get the following error:\n\n\n ORA-00904: \"HDR\".\"JE_BATCH_ID\": invalid identifier\n 00904. 00000 - \"%s: invalid identifier\"\n *Cause:\n *Action:\n Error at Line: 14 Column: 35\n\n\nAny assistance gratefully received.\n\nOwen"
] | [
"sql",
"oracle11g"
] |
[
"Node https.Agent in browser",
"Part of my npm module (typescript) is using axios to make web requests. One of the possible endpoints is using certificates for authentication. For this scenario I'm passing new https.Agent to axios to send the certificates info. All is working fine if the module is used from within Node app.\nThe problem is if I try and use my module in browser environment. When in browser https module do not exists and I'm unable to use my module.\n\nIs there any way to use https module in the browser?\nIf not - can https be bundled within my module somehow? Do I have to use some bundler in this case (like Rollup) to build the typescript module?"
] | [
"node.js",
"typescript",
"npm"
] |
[
"How to increase text size on graphs? [Using text(...) command]",
"I have some texts on my graphs in MATLAB, and I want to increase size of the text. Do you know how to do that?\n\nThis is the line that I've used to add the text:\n\nfigure(1);\nplot(x1, t, x2, t);\nxlabel(Time);\nylabel(data); \ntext(1, 1, ['Error:' (x2-x1)'m/s']);"
] | [
"matlab",
"graph",
"matlab-figure"
] |
[
"ipython will not work even after reinstalling",
"Im trying very hard to get ipython notebook to work. I got it working in terminal, but I can't get it to work in my browser. \n\nWhen I type ipython notebook in terminal, it says -bash: ipython: command not found\n\n MacBook-Air:~ me$ sudo easy_install https://github.com/ipython/ipython/tarball/master\n Downloading https://github.com/ipython/ipython/tarball/master\n error: None\n MacBook-Air:~ me$ ipython\n -bash: ipython: command not found\n\n\nIm really unsure why this is happening."
] | [
"ipython"
] |
[
"How to specify the number of threads in python's \"threading\" module",
"I am new to python multi threading programming. But to run my function in a reasonable time, I have to use it. \nIn an online tutorial, I found this basic code:\n\nimport threading\n\n def f(id):\n print (\"thread function:\",id)\n return\n\n for i in range(3):\n t = threading.Thread(target=f, args=(i,))\n t.start()\n\n\nThe output I got is:\n\nthread function: 0\nthread function: 1\nthread function: 2\n\n\nIn my actual program, I have parameters, which are a line to be read from a local file. I want to pass it to the target function. The target function performs some task, then writes results to a local file too. \n\nMy questions:\n1) How can I specify the number of threads in the above code?\n\n2) Is there any problem in making the target function writes results to a file? Can the multiple threads write at the same time? Are there any precautions to take to avoid mistakes?"
] | [
"python",
"python-3.x",
"multithreading",
"python-multithreading"
] |
[
"Different gearman libraries for any language",
"I'm working on making a presentation about gearman, and wondering if anyone knows any examples for languages other than PHP for registering functions.\n\nBasically I'm looking for an equilivant in any language of the following:\n\n$gm = new GearmanWorker();\n$gm->addFunction('reverse', function(GearmanJob $job){\n return strrev($job->workload());\n});\nwhile(1){ $gm->work(); }\n\n\nThanks in advance!"
] | [
"java",
"php",
"c",
"linux",
"gearman"
] |
[
"Oracle Partition Pruning with bind variables",
"I have a large (150m+ row) table, which is partitioned into quarters using a DATE partition key.\n\nWhen I query the table using something like...\n\nSELECT *\nFROM LARGE_TABLE\nWHERE THE_PARTITION_DATE >= TO_DATE('1/1/2009', 'DD/MM/YYYY')\nAND THE_PARTITION_DATE < TO_DATE('1/4/2009', 'DD/MM/YYYY');\n\n\n... partition pruning works correctly... the optomiser is able to realise that it only needs to look at a single partition (in this case Q1 2009). EXPLAIN PLAN shows \"PARTITION RANGE SINGLE\"\n\nHowever, when I move this query to PL/SQL and pass in the same dates as variables, the plan is showing as \"PARTITION RANGE (ITERATOR)\"... the optomiser is unable to understand that it only needs to look at the single partiiton (presumably because it doesn't have the actual values when it's evaluating the plan).\n\nThe only workaround I've found round so far is to code an EXECUTE IMMEDIATE including the dates in the SQL string so that the partition pruning works correctly. \n\nIs there a better way?"
] | [
"sql",
"performance",
"oracle",
"partitioning"
] |
[
"Multiarch Build System",
"I am trying to understand the multiarch Makefile based build system found in opensource projects such as linux kernel, glibc and so on. In all of these projects the source code is organized as C/C++ modules(e.g. filesystem, networking, logging) etc, generic headers such as include/ and then arch specific directory tree (arch/{x86,mips,arm}) etc. I want to understand how to layout of such projects is formed what specific language constructs and techniques are used to map the highlevel C routines to their arch specific implementations. I had tried to look around on the internet and didn't find information covering exactly this subject or introducing how to layout and design the Makefiles, organize C and assembly so that the build system correctly creates the build.\nFor a concrete example, lets consider the glibc, which utilizes a macro HP_TIMING_NOW whose implementation differs for different architectures (x86_64, powerpc...).\nI do understand that the whole build system works through invoking make recursively but may understanding of this process is superficial and I am looking for some concrete explanation in the form of resources or answers to cover this subject.\nThanks in advance"
] | [
"gcc",
"linux-kernel",
"gnu-make"
] |
[
"Subbing home page total different to theme on WordPress Genesis Child Theme",
"I'm about to do this on a Genesis child theme. I really tried picking a theme my client liked, but out of the blue with the project nearly finished they sprung their own artwork on me and want it for the homepage. So I had the site nearly up, and she sent me her own artwork that she wants to be the homepage. It's a full page and would have a different background than the rest of the site, no sidebars or widgeted areas, just three buttons.\n\nHere is the solution I've found for this.\n\nHow to integrate a custom landing page on wordpress?\n\nWill I need to add this solution back in with every upgrade?"
] | [
"wordpress"
] |
[
"parse data in twisted dataReceived",
"I'm working on a Sonos controller Kivy app (running on RPi). The sonos side of things is using node.js. My kivy app currently sends a http request to get the state of sonos (volume, station, song, etc) then updates the labels and images. This is working well, but I'd like to used twisted instead. As a starting point, I'm running the sample Echo Server app found in the kivy docs (https://kivy.org/docs/guide/other-frameworks.html). When I run it, dataReceived correctly gets the current status info on a Sonos state change. This is awesome. Unfortunately, the data is a mix of text and json. I'm wondering if there is a way to parse the json that's returned. Here's data\n\n\n content-type: application/json content-length: 1570 host:\n localhost:8000 connection: close\n \n { \"type\": \"mute-change\", \"data\": {\n \"uuid\": \"RINCON_000000000000001400\",\n \"previousMute\": true,\n \"previousMute\": false,\n \"roomName\": \"Office\" } }\n\n\nInstead of using dataReceived, is there a better way? I've been looking for a way just get the json (body) without all the header info, but havent found much that has worked.\n\nTIA"
] | [
"json",
"node.js",
"kivy",
"twisted"
] |
[
"Datagrid Scrollbar not showing",
"I'm writing a smart device application for a Windows CE 6.0 Device on VS 2008 with Compact Framework 3.5. I am using a dataGrid (Not dataGridView) to get data from a Database.\n\nI'm having problems with my dataGrid's scrollbar. When I run the application on the VS Emulator the vertical scrollbar is visible but when I deploy it onto the actual device and try, then it isn't visible and I'm not able to see all the rows.\n\nCould someone please help. Thanks :)"
] | [
"c#",
"visual-studio-2008",
"datagrid",
"compact-framework",
"smart-device"
] |
[
"Debugging APL code: how to use `@`(index) and `⊢` (right tack) together?",
"I am attempting to read Aaron Hsu's thesis on A data parallel compiler hosted on the GPU, where I have landed at some APL code I am unable to fix. I've attached both a screenshot of the offending page (page number 74 as per the thesis numbering on the bottom):\nThe transcribed code is as follows:\nd ← 0 1 2 3 1 2 3 3 4 1 2 3 4 5 6 5 5 6 3 4 5 6 5 5 6 3 4\n\nThis makes sense: create an array named d.\n⍳≢d\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27\n\nThis too makes sense. Count the number of elements in d and create a sequence of\nthat length.\n⍉↑d,¨⍳≢d\n0 1 2 3 1 2 3 3 4 1 2 3 4 5 6 5 5 6 3 4 5 6 5 5 6 3 4\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27\n\nThis is slightly challenging, but let me break it down:\n\nzip the sequence ⍳≢d = 1..27 with the d array using the ,¨ idiom, which zips the two arrays using a catenation.\n\nThen, split into two rows using ↑ and transpose to get columns using ⍉\n\n\nNow the biggie:\n(⍳≢d)@(d,¨⍳≢d)⊢7 27⍴' '\nINDEX ERROR\n (⍳≢d)@(d,¨⍳≢d)⊢7 27⍴' '\n\nAttempting to break it down:\n\n⍳≢d counts number of elements in d\n(d,¨⍳≢d) creates an array of pairs (d, index of d)\n7 27⍴' ' creates a 7 x 27 grid: presumably 7 because that's the max value of d + 1, for indexing reasons.\nNow I'm flummoxed about how the use of ⊢ works: as far as I know, it just ignores everything to the left! So I'm missing something about the parsing of this expression.\n\nI presume it is parsed as:\n(⍳≢d)@((d,¨⍳≢d)⊢(7 27⍴' '))\n\nwhich according to me should be evaluated as:\n(⍳≢d)@((d,¨⍳≢d)⊢(7 27⍴' '))\n= (⍳≢d)@((7 27⍴' ')) [using a⊢b = b]\n= not the right thing\n\n\nAs I was writing this down, I managed to fix the bug by sheer luck: if we increment d to be d + 1 so we are 1-indexed, the bug no longer manifests:\nd ← d + 1\nd\n1 2 3 4 2 3 4 4 5 2 3 4 5 6 7 6 6 7 4 5 6 7 6 6 7 4 5\n\nthen:\n(⍳≢d)@(d,¨⍳≢d)⊢7 27⍴' '\n1 \n 2 5 10 \n 3 6 11 \n 4 7 8 12 19 26 \n 9 13 20 27\n 14 16 17 21 23 24 \n 15 18 22 25 \n\nHowever, I still don't understand how this works! I presume the context will be useful\nfor others attempting to leave the thesis, so I'm going to leave the rest of it up.\nPlease explain what (⍳≢d)@(d,¨⍳≢d)⊢7 27⍴' ' does!\nI've attached the raw screenshot to make sure I didn't miss something:"
] | [
"parsing",
"apl",
"dyalog"
] |
[
"How to check if app has been loaded from Google Play or \"unknown source\"",
"Is there a way for an android application to check if it has been installed straight from Google Play (ex-Android Market) or manually installed from some other source?"
] | [
"android",
"google-play"
] |
[
"How do I install the dependencies I need for MySQL::Slurp?",
"I am trying to install the mysqlslurp utility found in MySQL::Slurp.\n\nI found that it requires Moose and therefore I installed that package too.\n\nBut I am still not able to use the mysqlslurp command. I get an error:\n\nCan't locate Moose.pm in @INC (@INC contains: /usr/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi \n.....\n\nBEGIN failed--compilation aborted at /usr/bin/mysqlslurp line 4."
] | [
"mysql",
"perl",
"moose"
] |
[
"Call many object's methods in parallel in python",
"I have two classes. One called algorithm and the other called Chain. In algorithm, I create multiple chains, which are going to be a sequence of sampled values. I want to run the sampling in parallel at the chain level.\n\nIn other words, the algorithm class instantiates n chains and I want to run the _sample method, which belongs to the Chain class, for each of the chains in parallel within the algorithm class. \n\nBelow is a sample code that attempts what I would like to do.\n\nI have seen a similar questions here: Apply a method to a list of objects in parallel using multi-processing, but as shown in the function _sample_chains_parallel_worker, this method does not work for my case (I am guessing it is because of the nested class structure). \n\nQuestion 1: Why does this not work for this case?\n\nThe method in _sample_chains_parallel also does not even run in parallel.\n\nQuestion 2: Why?\n\nQuestion 3: How do I sample each of these chains in parallel?\n\nimport time\nimport multiprocessing\n\nclass Chain():\n\n def __init__(self):\n self.thetas = []\n\n def _sample(self):\n for i in range(3):\n time.sleep(1)\n self.thetas.append(i)\n\n def clear_thetas(self):\n self.thetas = []\n\nclass algorithm():\n\n def __init__(self, n=3):\n self.n = n\n self.chains = []\n\n def _init_chains(self):\n for _ in range(self.n):\n self.chains.append(Chain())\n\n def _sample_chains(self):\n for chain in self.chains:\n chain.clear_thetas()\n chain._sample()\n\n def _sample_chains_parallel(self):\n pool = multiprocessing.Pool(processes=self.n)\n for chain in self.chains:\n chain.clear_thetas()\n pool.apply_async(chain._sample())\n pool.close()\n pool.join()\n\n def _sample_chains_parallel_worker(self):\n\n def worker(obj):\n obj._sample()\n\n pool = multiprocessing.Pool(processes=self.n)\n pool.map(worker, self.chains)\n\n pool.close()\n pool.join()\n\n\nif __name__==\"__main__\":\n import time\n\n alg = algorithm()\n alg._init_chains()\n\n start = time.time()\n alg._sample_chains()\n end = time.time()\n print \"sequential\", end - start\n\n start = time.time()\n alg._sample_chains_parallel()\n end = time.time()\n print \"parallel\", end - start\n\n start = time.time()\n alg._sample_chains_parallel_worker()\n end = time.time()\n print \"parallel, map and worker\", end - start"
] | [
"python",
"class",
"multiprocessing"
] |
[
".NET MenuItem.IsSubmenuOpen = true only works the first time",
"I have a ContextMenu with some sub-menus that have items (MenuItem) that can be selected. When the ContextMenu is opened, I want to recursively open the currently selected item. So, I have the following code:\n\n protected override void OnOpened( RoutedEventArgs e ) {\n base.OnOpened( e );\n OpenCurrentSubMenu( Items );\n }\n\n private static bool OpenCurrentSubMenu( ItemCollection itemCollection ) {\n foreach (MenuItem item in itemCollection) {\n if (item.IsChecked) {\n return true;\n }\n else if( OpenCurrentSubMenu( item.Items ) ) {\n item.IsSubmenuOpen = true;\n return true;\n }\n }\n return false;\n }\n\n\nI also have some other code that ensures that only one item is checked.\n\nThis seems to work great the first time I select an item in a sub-menu. When I re-open the ContextMenu, the open sub-menus cascade open to the selected item:\n\n\n\nHowever, when I leave the context menu, and re-open it a second time, the selected menu does NOT open:\n\n\n\nDoes anyone know why and how to fix it?"
] | [
"c#",
".net",
"contextmenu",
"submenu"
] |
[
"Configuring a project for Entity Framework 4.3, SQL Server Compact 4, and WPF",
"This StackOverflow post mentions the EntityFramework.SqlServerCompact NuGet package, but it seems to suggest that it's for web-based projects. So how should I configure a WPF project to use EF and SQLCE?"
] | [
"wpf",
"entity-framework",
"sql-server-ce"
] |
[
"Oozie - How to postpone a workflow until another one completes",
"I have a bundle that runs several coordinators.\nWhile one (and specific one) of these coordinators runs (a daily time-scheduled workflow), no other one has to start. Is there a way to postpone or cancel all other coordinators until this one completes ?\n\nExample: \n\n\nC1: Runs once a day at 06:00. Has to run alone!\nC2: Runs every 15 minutes (and take about 5 mins to complete)\nC3: Runs once a day at 04:00 (and could take more than 2 hours to complete)\n\n\nWhat I need is:\n\n\nC1 starts only if C2 & C3 are not running, else wait for its completion to start\nC2 starts only if C1 is not running, else cancel itself\n\n\nIf it's not possible, is there a workaround ?"
] | [
"oozie",
"oozie-coordinator",
"oozie-workflow"
] |
[
"Multiple frame movements in java",
"I have many frames. When I move from frame to frame making one invisible and the other visible the screen becomes blank. This means that the next frame opens after a delay. Is there any way to resolve this? \nHere is my code:\n\nf.setVisible(false);\nMyFrame1 f1=new MyFrame1();\nf1.setVisible(true); \n\n\nf is the object of my first frame,\n\nf1 is the object of my second frame."
] | [
"java",
"jframe"
] |
[
"Do we have a detailed whitepaper available for Snowflake which includes in depth explanation on the architecture choices?",
"Do we have a detailed whitepaper available for Snowflake which includes in depth explanation on the architecture choices? Similar to how Google BigQuery has the Dremel whitepaper.\nSynapse, Snowflake, BigQuery and RedShift are very similar in their architecture. I am trying to do a detailed analysis on the subtle differences in their architectures and features."
] | [
"snowflake-cloud-data-platform"
] |
[
"Same PNG file rendered by webgl in 2d is NOT as smoothly as canvas2d",
"When I tried to load the same PNG file into the canvas via both canvas.getContext('2d') and canvas.getContext('webgl'), found that compared with canvas2d, the PNG file rendered by webgl is NOT as smoothly as it rendered by canvas2d in detail. Is this caused by the GPU interpolation between points or texture setting/uploading issue? Any settings which could make the webgl version exactly the same as canvas 2d performs?\n\n let FSHADER_SOURCE = `\n precision mediump float;\n\n uniform sampler2D u_image0; \n varying vec2 v_texCoord;\n\n void main() {\n vec4 color0 = texture2D(u_image0, v_texCoord);\n gl_FragColor = color0;\n }\n `\n\n let texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.img);"
] | [
"javascript",
"canvas",
"webgl"
] |
[
"Anyone use CFAllocatorSetDefault succesfully in an iPhone app?",
"I wish to replace the default CFAllocator in my iPhone app with my own implementation. I want to control the memory allocated by the UIWebView since it seems to hold on to so much memory after loading a website and that memory still lingers around when the UIWebView is released.\n\nAfter I call CFAllocatorSetDefault I get an EXC_BREAKPOINT exception when the next allocation occurs.\n\nThe exception seems to happen inside of a call to CFRetain (done in the simulator but the same thing happens on a device):\n\nCoreFoundation`CFRetain:\n0x1c089b0: pushl %ebp\n0x1c089b1: movl %esp, %ebp\n0x1c089b3: pushl %edi\n0x1c089b4: pushl %esi\n0x1c089b5: subl $16, %esp\n0x1c089b8: calll 0x1c089bd ; CFRetain + 13\n0x1c089bd: popl %edi\n0x1c089be: movl 8(%ebp), %esi\n0x1c089c1: testl %esi, %esi\n0x1c089c3: jne 0x1c089db ; CFRetain + 43\n0x1c089c5: int3 \n0x1c089c6: calll 0x1d66a00 ; symbol stub for: getpid <- EXC_BREAKPOINT (code=EXC_I386_BPT subcode=0x0)\n0x1c089cb: movl %eax, (%esp)\n0x1c089ce: movl $9, 4(%esp)\n0x1c089d6: calll 0x1d66a4e ; symbol stub for: kill\n0x1c089db: movl (%esi), %eax\n0x1c089dd: testl %eax, %eax\n0x1c089df: je 0x1c08a17 ; CFRetain + 103\n0x1c089e1: cmpl 1838519(%edi), %eax\n0x1c089e7: je 0x1c08a17 ; CFRetain + 103\n0x1c089e9: movl 4(%esi), %ecx\n0x1c089ec: shrl $8, %ecx\n0x1c089ef: andl $1023, %ecx\n0x1c089f5: cmpl 1834423(%edi,%ecx,4), %eax\n0x1c089fc: je 0x1c08a17 ; CFRetain + 103\n0x1c089fe: movl 1766575(%edi), %eax\n0x1c08a04: movl %eax, 4(%esp)\n0x1c08a08: movl %esi, (%esp)\n0x1c08a0b: calll 0x1d665c8 ; symbol stub for: objc_msgSend"
] | [
"iphone",
"ios",
"memory-management",
"uiwebview",
"core-foundation"
] |
[
"Can't share open graph with Android Facebook SDK 4",
"Code:\n\nString imgURL = mShareParams.getImageURL();\nimgURL = imgURL.substring(0, imgURL.lastIndexOf(\"/\"));\nShareOpenGraphObject object = new ShareOpenGraphObject.Builder().putString(\"og:type\", \"article\").putString(\"fb:app_id\",mContext.getString(R.string.facebook_app_id)).putString(\"og:url\", mShareParams.getUrl()).putString(\"og:title\", mShareParams.getContentTitle()).putString(\"og:image\", imgURL).putString(\"og:image:type\", \"png\").build();\nShareOpenGraphAction action = new ShareOpenGraphAction.Builder().setActionType(\"og.likes\").putObject(\"article\", object).build();\nShareOpenGraphContent content = new ShareOpenGraphContent.Builder() .setPreviewPropertyName(\"article\").setAction(action).build();\nif (ShareDialog.canShow(ShareLinkContent.class)) {\n ShareDialog.show((Activity)mContext, content);\n}\n\n\nResult:\n\n\n Action Requires At Least One Reference:The action you're trying to publish is invalid because it does not specify any reference objects.At least one of the following properties must be specified:object."
] | [
"android",
"facebook-opengraph"
] |
[
"unable to fill the div element height to fit screen?",
"i tried a lot, but can't make the div to fit the screen when i zoom in the browser by ctrl+'-' , don't know why height:100% in style to div.style doesn't work\n\n\r\n\r\ndiv.left {\r\n width: 100px;\r\n height: 100%;\r\n background-color: #ff0000;\r\n}\r\n<div class=\"left\" id=\"left_panel\">\r\n hello\r\n</div>"
] | [
"html",
"css"
] |
[
"How can we determine when the \"last\" worker process/thread is finished in Go?",
"I'll use a hacky inefficient prime number finder to make this question a little more concrete.\n\nLet's say our main function fires off a bunch of \"worker\" goroutines. They will report their results to a single channnel which prints them. But not every worker will report something so we can't use a counter to know when the last job is finished. Or is there a way?\n\nFor the concrete example, here, main fires off goroutines to check whether the values 2...1000 are prime (yeah I know it is inefficient).\n\npackage main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\nfunc main() {\n c := make(chan int)\n go func () {\n for {\n fmt.Print(\" \", <- c)\n }\n }()\n for n := 2; n < 1000; n++ {\n go printIfPrime(n, c)\n }\n time.Sleep(2 * time.Second) // <---- THIS FEELS WRONG\n}\n\nfunc printIfPrime(n int, channel chan int) {\n for d := 2; d * d <= n; d++ {\n if n % d == 0 {\n return\n }\n }\n channel <- n\n}\n\n\nMy problem is that I don't know how to reliably stop it at the right time. I tried adding a sleep at the end of main and it works (but it might take too long, and this is no way to write concurrent code!). I would like to know if there was a way to send a stop signal through a channel or something so main can stop at the right time. \n\nThe trick here is that I don't know how many worker responses there will be.\n\nIs this impossible or is there a cool trick?\n\n(If there's an answer for this prime example, great. I can probably generalize. Or maybe not. Maybe this is app specific?)"
] | [
"go",
"concurrency"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.