title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
OutOfMemoryError during test execution
<p>I'm trying to run unit and intergartion tests for jee wildfly application. During tests execution i'm getting stack overflow. I tried to increase memory but wihout success. In my opinion it looks like oom during package creation but i'm not sure.</p> <p>Can you help? I want also generate jacoco coverage.</p> <p>I'm using wildfly 10.</p> <pre><code>Running ......AddRemoveProjectTestCase Exception in thread "management-client-thread 1-2" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:3236) at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118) at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93) at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153) at org.jboss.as.protocol.StreamUtils.copyStream(StreamUtils.java:52) at org.jboss.as.controller.client.impl.InputStreamEntry$InMemoryEntry.initialize(InputStreamEntry.java:76) at org.jboss.as.controller.client.impl.AbstractModelControllerClient$ReadAttachmentInputStreamRequestHandler$1.execute(AbstractModelControllerClient.java:193) at org.jboss.as.protocol.mgmt.AbstractMessageHandler$2$1.doExecute(AbstractMessageHandler.java:283) at org.jboss.as.protocol.mgmt.AbstractMessageHandler$AsyncTaskRunner.run(AbstractMessageHandler.java:504) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at org.jboss.threads.JBossThread.run(JBossThread.java:122) </code></pre> <p>pom.xml</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; .............. &lt;packaging&gt;war&lt;/packaging&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;sonar.language&gt;java&lt;/sonar.language&gt; &lt;sonar.login&gt;admin&lt;/sonar.login&gt; &lt;sonar.password&gt;admin&lt;/sonar.password&gt; &lt;sonar.host.url&gt;http://sonar:9000/&lt;/sonar.host.url&gt; &lt;version.org.jboss.arquillian.graphene&gt;2.1.0.Alpha3&lt;/version.org.jboss.arquillian.graphene&gt; &lt;version.jacoco&gt;0.7.5.201505241946&lt;/version.jacoco&gt; &lt;version.arquillian_jacoco&gt;1.0.0.Alpha8&lt;/version.arquillian_jacoco&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;!-- http://mvnrepository.com/artifact/dom4j/dom4j --&gt; &lt;dependency&gt; &lt;groupId&gt;dom4j&lt;/groupId&gt; &lt;artifactId&gt;dom4j&lt;/artifactId&gt; &lt;version&gt;1.6.1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- for e2e tests only: start --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-logging&lt;/groupId&gt; &lt;artifactId&gt;commons-logging&lt;/artifactId&gt; &lt;version&gt;1.0.4&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.mockito&lt;/groupId&gt; &lt;artifactId&gt;mockito-all&lt;/artifactId&gt; &lt;version&gt;1.10.19&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-codec&lt;/groupId&gt; &lt;artifactId&gt;commons-codec&lt;/artifactId&gt; &lt;version&gt;1.3&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;xml-apis&lt;/groupId&gt; &lt;artifactId&gt;xml-apis&lt;/artifactId&gt; &lt;version&gt;1.4.01&lt;/version&gt; &lt;/dependency&gt; &lt;!-- for e2e tests only: stop --&gt; &lt;dependency&gt; &lt;groupId&gt;org.jsoup&lt;/groupId&gt; &lt;artifactId&gt;jsoup&lt;/artifactId&gt; &lt;version&gt;1.9.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi&lt;/artifactId&gt; &lt;version&gt;3.14&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi-ooxml&lt;/artifactId&gt; &lt;version&gt;3.14&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &lt;version&gt;7.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.logging&lt;/groupId&gt; &lt;artifactId&gt;jboss-logging&lt;/artifactId&gt; &lt;version&gt;3.1.4.GA&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.primefaces&lt;/groupId&gt; &lt;artifactId&gt;primefaces&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;3.6.8.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-commons-annotations&lt;/artifactId&gt; &lt;version&gt;3.2.0.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.jbossts&lt;/groupId&gt; &lt;artifactId&gt;jbossjta&lt;/artifactId&gt; &lt;version&gt;4.16.4.Final&lt;/version&gt; &lt;/dependency&gt; &lt;!-- unit tests --&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.12&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.arquillian.junit&lt;/groupId&gt; &lt;artifactId&gt;arquillian-junit-container&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- GUI tests --&gt; &lt;dependency&gt; &lt;groupId&gt;org.jacoco&lt;/groupId&gt; &lt;artifactId&gt;org.jacoco.core&lt;/artifactId&gt; &lt;version&gt;${version.jacoco}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.arquillian.extension&lt;/groupId&gt; &lt;artifactId&gt;arquillian-jacoco&lt;/artifactId&gt; &lt;version&gt;${version.arquillian_jacoco}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.wildfly&lt;/groupId&gt; &lt;artifactId&gt;wildfly-arquillian-container-remote&lt;/artifactId&gt; &lt;version&gt;8.2.1.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.arquillian.graphene&lt;/groupId&gt; &lt;artifactId&gt;graphene-webdriver&lt;/artifactId&gt; &lt;version&gt;${version.org.jboss.arquillian.graphene}&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.arquillian.extension&lt;/groupId&gt; &lt;artifactId&gt;arquillian-drone-webdriver-depchain&lt;/artifactId&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.shrinkwrap.resolver&lt;/groupId&gt; &lt;artifactId&gt;shrinkwrap-resolver-impl-maven&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.seleniumhq.selenium&lt;/groupId&gt; &lt;artifactId&gt;selenium-java&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.seleniumhq.webdriver&lt;/groupId&gt; &lt;artifactId&gt;webdriver-common&lt;/artifactId&gt; &lt;version&gt;0.9.7376&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.weld&lt;/groupId&gt; &lt;artifactId&gt;weld-core&lt;/artifactId&gt; &lt;version&gt;2.3.5.Final&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-core&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.arquillian&lt;/groupId&gt; &lt;artifactId&gt;arquillian-bom&lt;/artifactId&gt; &lt;version&gt;1.1.11.Final&lt;/version&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;type&gt;pom&lt;/type&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.arquillian.extension&lt;/groupId&gt; &lt;artifactId&gt;arquillian-drone-bom&lt;/artifactId&gt; &lt;version&gt;1.3.1.Final&lt;/version&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;type&gt;pom&lt;/type&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.arquillian.selenium&lt;/groupId&gt; &lt;artifactId&gt;selenium-bom&lt;/artifactId&gt; &lt;version&gt;2.53.0&lt;/version&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;type&gt;pom&lt;/type&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; &lt;build&gt; &lt;finalName&gt;${project.artifactId}&lt;/finalName&gt; &lt;testResources&gt; &lt;testResource&gt; &lt;directory&gt;src/test/resources&lt;/directory&gt; &lt;filtering&gt;true&lt;/filtering&gt; &lt;/testResource&gt; &lt;/testResources&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.15&lt;/version&gt; &lt;configuration&gt; &lt;argLine&gt;-Xms128m -Xmx4G -XX:MaxPermSize=2G&lt;/argLine&gt; &lt;!-- Sets the VM argument line used when unit tests are run. --&gt; &lt;argLine&gt;${surefireArgLine}&lt;/argLine&gt; &lt;!-- Skips unit tests if the value of skip.unit.tests property is true --&gt; &lt;skipTests&gt;${skip.unit.tests}&lt;/skipTests&gt; &lt;!-- Excludes integration tests when unit tests are run. --&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt; &lt;version&gt;2.15&lt;/version&gt; &lt;executions&gt; &lt;!-- Ensures that both integration-test and verify goals of the Failsafe Maven plugin are executed. --&gt; &lt;execution&gt; &lt;id&gt;integration-tests&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;integration-test&lt;/goal&gt; &lt;goal&gt;verify&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;!-- Sets the VM argument line used when integration tests are run. --&gt; &lt;argLine&gt;${failsafeArgLine}&lt;/argLine&gt; &lt;!-- Skips integration tests if the value of skip.integration.tests property is true --&gt; &lt;skipTests&gt;${skip.integration.tests}&lt;/skipTests&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;sonar-maven-plugin&lt;/artifactId&gt; &lt;version&gt;2.7.1&lt;/version&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.jacoco&lt;/groupId&gt; &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt; &lt;version&gt;${version.jacoco}&lt;/version&gt; &lt;executions&gt; &lt;!-- Prepares the property pointing to the JaCoCo runtime agent which is passed as VM argument when Maven the Surefire plugin is executed. --&gt; &lt;execution&gt; &lt;id&gt;pre-unit-test&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;prepare-agent&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;!-- Sets the path to the file which contains the execution data. --&gt; &lt;destFile&gt;${project.build.directory}/jacoco.exec&lt;/destFile&gt; &lt;!-- Sets the name of the property containing the settings for JaCoCo runtime agent. --&gt; &lt;propertyName&gt;surefireArgLine&lt;/propertyName&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;!-- Ensures that the code coverage report for unit tests is created after unit tests have been run. --&gt; &lt;execution&gt; &lt;id&gt;post-unit-test&lt;/id&gt; &lt;phase&gt;test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;report&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;!-- Sets the path to the file which contains the execution data. --&gt; &lt;dataFile&gt;${project.build.directory}/coverage-reports/jacoco-ut.exec&lt;/dataFile&gt; &lt;!-- Sets the output directory for the code coverage report. --&gt; &lt;outputDirectory&gt;${project.reporting.outputDirectory}/jacoco-ut&lt;/outputDirectory&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;pre-integration-test&lt;/id&gt; &lt;phase&gt;pre-integration-test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;prepare-agent&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;!-- Sets the path to the file which contains the execution data. --&gt; &lt;destFile&gt;${project.build.directory}/jacoco-it.exec&lt;/destFile&gt; &lt;!-- Sets the name of the property containing the settings for JaCoCo runtime agent. --&gt; &lt;propertyName&gt;failsafeArgLine&lt;/propertyName&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;!-- Ensures that the code coverage report for integration tests after integration tests have been run. --&gt; &lt;execution&gt; &lt;id&gt;post-integration-test&lt;/id&gt; &lt;phase&gt;post-integration-test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;report&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;!-- Sets the path to the file which contains the execution data. --&gt; &lt;dataFile&gt;${project.build.directory}/coverage-reports/jacoco-it.exec&lt;/dataFile&gt; &lt;!-- Sets the output directory for the code coverage report. --&gt; &lt;outputDirectory&gt;${project.reporting.outputDirectory}/jacoco-it&lt;/outputDirectory&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;!-- WildFly plugin to deploy the application --&gt; &lt;plugin&gt; &lt;groupId&gt;org.wildfly.plugins&lt;/groupId&gt; &lt;artifactId&gt;wildfly-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.0.2.Final&lt;/version&gt; &lt;configuration&gt; &lt;filename&gt;${project.build.finalName}.war&lt;/filename&gt; &lt;hostname&gt;wildfly&lt;/hostname&gt; &lt;port&gt;9990&lt;/port&gt; &lt;username&gt;user&lt;/username&gt; &lt;password&gt;password&lt;/password&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.1.1&lt;/version&gt; &lt;configuration&gt; &lt;archive&gt; &lt;manifestFile&gt;src/main/resources/META-INF/MANIFEST.MF&lt;/manifestFile&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.1&lt;/version&gt; &lt;configuration&gt; &lt;!-- enforce Java 8 --&gt; &lt;source&gt;1.8&lt;/source&gt; &lt;target&gt;1.8&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>arquillian.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;arquillian xmlns="http://www.jboss.org/arquillian-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.jboss.org/arquillian-1.0 http://www.jboss.org/schema/arquillian/arquillian-1.0.xsd"&gt; &lt;defaultProtocol type="Servlet 3.0" /&gt; &lt;extension qualifier="webdriver"&gt; &lt;property name="browser"&gt;chrome&lt;/property&gt; &lt;/extension&gt; &lt;container qualifier="widlfly-remote" default="true"&gt; &lt;configuration&gt; &lt;property name="javaVmArguments"&gt;-Xms512m -Xmx4G&lt;/property&gt; &lt;property name="managementAddress"&gt;wildfly&lt;/property&gt; &lt;property name="managementPort"&gt;9990&lt;/property&gt; &lt;property name="username"&gt;user&lt;/property&gt; &lt;property name="password"&gt;password&lt;/property&gt; &lt;/configuration&gt; &lt;protocol type="Servlet 3.0"&gt; &lt;property name="host"&gt;widfly&lt;/property&gt; &lt;property name="port"&gt;8080&lt;/property&gt; &lt;/protocol&gt; &lt;/container&gt; &lt;/arquillian&gt; </code></pre> <p>PS: On jenkins slave is see that used memeory is only 1G</p> <p><a href="http://i.stack.imgur.com/lqllH.png" rel="nofollow">test proces</a></p> <p><a href="http://i.stack.imgur.com/BiiRC.png" rel="nofollow">system monitor performance tab</a></p> <p>Still problem:</p> <p>Hi, i see that increasing memory don't fix the problem. Insufficient memory was not the reason of the problems. Now i need 6GB RAM and i have 47% of code coverage. So if memory will increase lineary i will need 12GB of free RAM to test my 40MB(with libraries and pictures) app. I think that there is something wrong with that. It looks like memory leak. </p> <p>Is it normal to have such big memory consumption in arquillian + jacoco configuration?</p>
2
String was not recognized as a valid DateTime on one PC
<p><strong>Language:</strong> C#, <strong>.Net framework:</strong> 4.5, <strong>method used:</strong> DateTime.ParseExact</p> <p>So in one of our projects we're using the following function to parse a string into a DateTime:</p> <pre><code>private DateTime FormatDate(string date, string format) { try { IFormatProvider culture = new CultureInfo("en-US", true); DateTime dt = DateTime.ParseExact(date, format, culture); return dt; } catch (Exception ex) { throw new Exception(ex.Message); } } </code></pre> <p>and calling it like this:</p> <pre><code>DateTime startDate = FormatDate("01/17/2016", "M/d/yyyy"); </code></pre> <p>On our 3 PCs, this code works perfectly when Date format on each PC is dd/MM/yyyy, but on 2 of the PCs, when their date format is dd-MMM-yy it produces a bug when trying to execute ParseExact:</p> <blockquote> <p>String was not recognized as a valid DateTime.</p> </blockquote> <p>While it keeps working on the third PC even when using the dd-MMM-yy format. I compared Date and Time settings on all 3 PCs, settings are all equal, the one difference is that on the 2 PCs we use Visual Studio 2013 while on the third Visual Studio 2015.</p> <p><strong>Exception details:</strong></p> <p>Message: String was not recognized as a valid DateTime.</p> <p>InnerException: No Inner Exception</p> <p>Stack: at System.DateTime.ParseExact(String s, String format, IFormatProvider provider) at AssetTracking.PopUpWindows.AddItem_Warranty.MakeReminder(TrackersDataContext atdc, Items ni, string itemId) in d:\Solutions\Trackers\Trackers\PopUpWindows\AddItem_Warranty.xaml.cs:line 807 at Trackers.PopUpWindows.AddItem_Warranty.&lt;>c__DisplayClass8.b__3() in d:\Solutions\Tackers\Trackers\PopUpWindows\AddItem_Warranty.xaml.cs:line 685</p> <p><strong>The question:</strong> I'm not sure, is the different IDE part of the problem? or what else can produce this bug on some PCs and not on others having the exact same date and time settings?</p>
2
Is it possible to have intellisense in VSCode show the return type?
<p>I've switched from MonoDevelop to VSCode for C# development for Unity3d. The intellisence provided by MonoDevelop IMO was more informative.</p> <p>As you type MonoDevelop gives you useful things like whether the item in the list is a method, property or primitive etc and also the return type. VSCode does not do this, here's an example of the as you type completion.</p> <p>//edit I cannot use Visual Studio as I'm using Mac OSX. Switching to Windows bootcamp just for Unity is not convenient or productive.</p> <p><strong>VSCode</strong></p> <p><img src="https://www.dropbox.com/s/3cdoame1y2xlghi/Screenshot%202016-07-07%2009.49.42.png?dl=1" alt="VSCode Completion"></p> <p><strong>MonoDevelop</strong></p> <p><a href="https://i.stack.imgur.com/sS7qP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sS7qP.png" alt="MD Completion"></a></p>
2
Why does an exception in an async Parallel.ForEach crash the application?
<p>Why does the following crash if run inside a console application instead of throwing an <code>AggregateException</code> and being caught by the outer <code>try/catch</code>?</p> <p>I've simplified the use case for the <code>await</code> for brevity, but in the relevant code I am indeed trying to execute an awaitable <code>Task</code> of importance.</p> <pre><code>var list = new List&lt;string&gt;() {"Error"}; try { Parallel.ForEach(list, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, async listEntry =&gt; { await Task.Delay(5000); throw new Exception("Exception"); }); } catch (Exception ex) { //never hits, the application crashes } Console.ReadLine(); </code></pre> <p>I note that the following does not cause the application to fail, and an exception is indeed caught, but I do not understand what's really going on as to what is fundamentally different about the two contexts:</p> <pre><code>var list = new List&lt;string&gt;() {"Error"}; try { Parallel.ForEach(list, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, listEntry =&gt; { throw new Exception("Exception"); }); } catch (Exception ex) { //exception is caught, application continues } Console.ReadLine(); </code></pre>
2
Is there a way to return an abstraction from a function without using new (for performance reasons)
<p>For example I have some function <code>pet_maker()</code> that creates and returns a <code>Cat</code> or a <code>Dog</code> as a base <code>Pet</code>. I want to call this function many many times, and do something with the <code>Pet</code> returned.</p> <p>Traditionally I would <code>new</code> the <code>Cat</code> or <code>Dog</code> in <code>pet_maker()</code> and return a pointer to it, however the <code>new</code> call is much slower than doing everything on the stack.</p> <p>Is there a neat way anyone can think of to return as an abstraction without having to do the new every time the function is called, or is there some other way that I can quickly create and return abstractions?</p>
2
Select particular fields after select_related() with only()
<p>I have 2 models connected with <code>OneToOneField</code>:</p> <pre class="lang-py prettyprint-override"><code>class Person(TimeStampedModel, StatusModel): name = models.CharField(max_length=300) slug = models.SlugField(max_length=300) class Card(TimeStampedModel, StatusModel): title = models.CharField(max_length=300) year = models.IntegerField() comment = models.TextField(blank=True) featured = models.BooleanField(default=False) person = models.OneToOneField(Person, on_delete=models.CASCADE) </code></pre> <p>I want to query only <code>name</code> and <code>title</code> fields form <code>Person</code> and <code>Card</code> models. </p> <p>I tried several approaches but none of them worked.</p> <p><strong>1st try</strong></p> <pre class="lang-py prettyprint-override"><code>Person.objects.filter(slug=slug).only('name', 'card__title') </code></pre> <p>but generated query doesn't include <code>card__title</code>:</p> <pre class="lang-sql prettyprint-override"><code>SELECT "core_person"."id", "core_person"."name" FROM "core_person" WHERE "core_person"."slug" = some-name </code></pre> <p><strong>2nd try</strong></p> <pre class="lang-py prettyprint-override"><code>Person.objects.filter(slug=slug).select_related('card').only('name') </code></pre> <p>but generated query includes all fields from <code>Card</code>:</p> <pre class="lang-sql prettyprint-override"><code>SELECT "core_person"."id", "core_person"."name", "core_card"."id", "core_card"."title", "core_card"."year", "core_card"."comment", "core_card"."featured" FROM "core_person" LEFT OUTER JOIN "core_card" ON ("core_person"."id" = "core_card"."person_id") WHERE "core_person"."slug" = some-name </code></pre> <p><strong>3rd try</strong></p> <pre class="lang-py prettyprint-override"><code>Person.objects.filter(slug=slug).select_related('card').only('name', 'card__title') </code></pre> <p>but it throws weird exception:</p> <p><code>django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'card'. Choices are: card</code></p> <p><strong>Desired result</strong></p> <p>Is there a way to receive a query like below not using <code>.values()</code>?</p> <pre class="lang-sql prettyprint-override"><code>SELECT "core_person"."id", "core_person"."name", "core_card"."id", "core_card"."title" FROM "core_person" LEFT OUTER JOIN "core_card" ON ("core_person"."id" = "core_card"."person_id") WHERE "core_person"."slug" = some-name </code></pre>
2
Java EE transaction rollback
<p>I have following ejb:</p> <pre><code>for (int i = 1; i &lt;= shopItem.getQuantity(); i++) { purchase = new Purchase(); purchase.setUser(user); // a lot of sets purchase.setPhoneNumber(order.getPhoneNumber()); try { financeEntityEjb.createPurchase(purchase); } catch (NotEnoughFundsException e) { throw new NotEnoughFundsExceptionWithRollback(e); // Making in rollable } } public void createPurchase(Purchase purchase) throws InputValidationException, NotEnoughFundsException { // a lot of calculations em.persist(purchase); em.flush(); /* Closing Order */ purchase.getOrder().setState(Order.State.PURCHASED); em.merge(purchase.getOrder()); } </code></pre> <p>My Exception class:</p> <pre><code>@ApplicationException(rollback = true) public class NotEnoughFundsExceptionWithRollback extends NotEnoughFundsException { public NotEnoughFundsExceptionWithRollback() { } public NotEnoughFundsExceptionWithRollback(Throwable e) { super(e); } public NotEnoughFundsExceptionWithRollback(String message, Throwable e) { super(message, e); } } </code></pre> <p>So I have problem that ejb rollbacks all em.persist(purchase); but ignores em.merge(purchase.getOrder());</p> <p>UPD: Loop is in purchaseEjb. and CreatePurchase method is on financeEjb</p>
2
What kind of sorcery is Maven doing to run this project, when I can't?
<p>I have a maven project with some library dependencies (.dll) (which I put in a "lib" folder). I can run the project without problems in Netbeans, but when I try to run the built .jar outside of Netbeans, I get the following error on loading the library:</p> <p><code>Can't load this .dll (machine code=0xbd) on a AMD 64-bit platform</code></p> <p>I only have <strong>one</strong> instance of Java installed on my computer, it should be the same JVM that Netbeans/Maven uses to run the project. So I can't understand how Netbeans/Maven is able to run this application on a different platform than me? I've tried looking at the command Netbeans executes (from the output) to run the project and I think it's this:</p> <pre><code>cd C:\Users\Birger\Workspace\myproject; "JAVA_HOME=C:\\Program Files\\Java\\jdk1.8.0_91" cmd /c "\"\"C:\\Program Files\\NetBeans 8.1\\java\\maven\\bin\\mvn.bat\" -Dexec.args=\"-Djava.library.path=lib\\ -classpath %classpath com.mysite.myproject.Main\" -Dexec.executable=\"C:\\Program Files\\Java\\jdk1.8.0_91\\bin\\java.exe\" -Dmaven.ext.class.path=\"C:\\Program Files\\NetBeans 8.1\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 org.codehaus.mojo:exec-maven-plugin:1.2.1:exec\"" </code></pre> <p>I tried these two commands</p> <pre><code>"C:\Program Files\Java\jdk1.8.0_91\jre\bin\java.exe" -Djava.library.path=lib\ -jar myproject-1.0-SNAPSHOT.jar "C:\Program Files\Java\jdk1.8.0_91\bin\java.exe" -Djava.library.path=lib\ -jar myproject-1.0-SNAPSHOT.jar </code></pre> <p>I added <code>System.out.println(System.getProperty("sun.arch.data.model"));</code> to get my application to print out the cpu architecture. It prints <code>64</code> in both occasions.</p> <p>Tried looking into the "mvn.bat" file in <code>C:\Program Files\NetBeans 8.1\java\maven\bin\mvn.bat</code> but I couldn't find any clues as to what Maven is doing to run my application.</p> <p>Can somebody help me on this one?</p> <p>Birger</p> <p><strong>EDIT</strong></p> <p>Here's the complete source code of my test project. My project's <code>pom.xml</code></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.mysite&lt;/groupId&gt; &lt;artifactId&gt;myproject&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;maven.compiler.source&gt;1.8&lt;/maven.compiler.source&gt; &lt;maven.compiler.target&gt;1.8&lt;/maven.compiler.target&gt; &lt;/properties&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;repo&lt;/id&gt; &lt;url&gt;file://${project.basedir}/temp-repo&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;jni4net&lt;/groupId&gt; &lt;artifactId&gt;jni4net.j&lt;/artifactId&gt; &lt;version&gt;0.8.8.0&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt; &lt;version&gt;2.10&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;copy&lt;/id&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy-dependencies&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt; ${project.build.directory}/lib &lt;/outputDirectory&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.2&lt;/version&gt; &lt;configuration&gt; &lt;archive&gt; &lt;manifest&gt; &lt;addClasspath&gt;true&lt;/addClasspath&gt; &lt;classpathPrefix&gt;lib/&lt;/classpathPrefix&gt; &lt;mainClass&gt;com.mysite.myproject.Main&lt;/mainClass&gt; &lt;/manifest&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-resources-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.1&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;copy-resources&lt;/id&gt; &lt;phase&gt;validate&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy-resources&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt;${project.build.directory}/lib&lt;/outputDirectory&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;lib&lt;/directory&gt; &lt;filtering&gt;true&lt;/filtering&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>My project's class</p> <pre><code>package com.mysite.myproject; import java.io.File; import java.io.IOException; import net.sf.jni4net.Bridge; public class Main { static { String libDir = System.getProperty("java.library.path"); System.loadLibrary("jni4net.n-0.8.8.0"); if (System.getProperty("sun.arch.data.model").equals("64")) { System.loadLibrary("jni4net.n.w64.v20-0.8.8.0"); System.loadLibrary("jni4net.n.w64.v40-0.8.8.0"); } else { System.loadLibrary("jni4net.n.w32.v20-0.8.8.0"); System.loadLibrary("jni4net.n.w32.v40-0.8.8.0"); } try { Bridge.init(new File(libDir)); System.out.println("Initialized!"); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new Main(); } public Main() { System.out.println("Hello world!"); } } </code></pre> <p>Netbeans output when running the project (added <code>--debug</code> option for verbose output):</p> <pre><code>cd C:\Users\Birger\Workspace\myproject; "JAVA_HOME=C:\\Program Files\\Java\\jdk1.8.0_91" cmd /c "\"\"C:\\Program Files\\NetBeans 8.1\\java\\maven\\bin\\mvn.bat\" -Dexec.args=\"-Djava.library.path=lib\\ -classpath %classpath com.mysite.myproject.Main\" -Dexec.executable=\"C:\\Program Files\\Java\\jdk1.8.0_91\\bin\\java.exe\" -Dmaven.ext.class.path=\"C:\\Program Files\\NetBeans 8.1\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 --debug org.codehaus.mojo:exec-maven-plugin:1.2.1:exec\"" Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts. C:\Program Files\Java\jdk1.8.0_91 Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 14:51:28+0100) Maven home: C:\Program Files\NetBeans 8.1\java\maven Java version: 1.8.0_91, vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk1.8.0_91\jre Default locale: en_US, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "dos" Populating class realm maven.ext Included C:\Program Files\NetBeans 8.1\java\maven-nblib\netbeans-eventspy.jar Error stacktraces are turned on. Reading global settings from C:\Program Files\NetBeans 8.1\java\maven\conf\settings.xml Reading user settings from C:\Users\Birger\.m2\settings.xml Using local repository at C:\Users\Birger\.m2\repository Using manager EnhancedLocalRepositoryManager with priority 10 for C:\Users\Birger\.m2\repository Scanning for projects... Extension realms for project com.mysite:myproject:jar:1.0-SNAPSHOT: (none) Looking up lifecyle mappings for packaging jar from ClassRealm[maven.ext, parent: ClassRealm[plexus.core, parent: null]] === REACTOR BUILD PLAN ================================================ Project: com.mysite:myproject:jar:1.0-SNAPSHOT Tasks: [org.codehaus.mojo:exec-maven-plugin:1.2.1:exec] Style: Regular ======================================================================= ------------------------------------------------------------------------ Building myproject 1.0-SNAPSHOT ------------------------------------------------------------------------ Lifecycle default -&gt; [validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy] Lifecycle clean -&gt; [pre-clean, clean, post-clean] Lifecycle site -&gt; [pre-site, site, post-site, site-deploy] === PROJECT BUILD PLAN ================================================ Project: com.mysite:myproject:1.0-SNAPSHOT Dependencies (collect): [] Dependencies (resolve): [test] Repositories (dependencies): [libs-release (http://artifactory.osc.no:8081/artifactory/libs-release/, releases), repo (file://C:\Users\Birger\Workspace\myproject/temp-repo, releases+snapshots), central (http://repo.maven.apache.org/maven2, releases)] Repositories (plugins) : [libs-release (http://artifactory.osc.no:8081/artifactory/libs-release/, releases), central (http://repo.maven.apache.org/maven2, releases)] ----------------------------------------------------------------------- Goal: org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) Style: Regular Configuration: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;basedir default-value="${basedir}"/&gt; &lt;classpathScope default-value="runtime"&gt;${exec.classpathScope}&lt;/classpathScope&gt; &lt;commandlineArgs&gt;${exec.args}&lt;/commandlineArgs&gt; &lt;executable&gt;${exec.executable}&lt;/executable&gt; &lt;longClasspath default-value="false"&gt;${exec.longClasspath}&lt;/longClasspath&gt; &lt;outputFile&gt;${exec.outputFile}&lt;/outputFile&gt; &lt;project default-value="${project}"/&gt; &lt;session default-value="${session}"/&gt; &lt;skip default-value="false"&gt;${skip}&lt;/skip&gt; &lt;sourceRoot&gt;${sourceRoot}&lt;/sourceRoot&gt; &lt;testSourceRoot&gt;${testSourceRoot}&lt;/testSourceRoot&gt; &lt;workingDirectory&gt;${exec.workingdir}&lt;/workingDirectory&gt; &lt;/configuration&gt; ======================================================================= com.mysite:myproject:jar:1.0-SNAPSHOT jni4net:jni4net.j:jar:0.8.8.0:compile --- exec-maven-plugin:1.2.1:exec (default-cli) @ myproject --- Created new class realm maven.api Importing foreign packages into class realm maven.api Imported: org.apache.maven.cli &lt; maven.ext Imported: org.codehaus.plexus.lifecycle &lt; maven.ext Imported: org.apache.maven.lifecycle &lt; maven.ext Imported: org.apache.maven.repository &lt; maven.ext Imported: org.codehaus.plexus.personality &lt; maven.ext Imported: org.apache.maven.usability &lt; maven.ext Imported: org.codehaus.plexus.configuration &lt; maven.ext Imported: org.sonatype.aether.version &lt; maven.ext Imported: org.sonatype.aether.* &lt; maven.ext Imported: org.sonatype.aether.artifact &lt; maven.ext Imported: org.apache.maven.* &lt; maven.ext Imported: org.apache.maven.project &lt; maven.ext Imported: org.sonatype.aether.repository &lt; maven.ext Imported: org.sonatype.aether.impl &lt; maven.ext Imported: org.apache.maven.exception &lt; maven.ext Imported: org.apache.maven.plugin &lt; maven.ext Imported: org.sonatype.aether.collection &lt; maven.ext Imported: org.codehaus.plexus.* &lt; maven.ext Imported: org.codehaus.plexus.logging &lt; maven.ext Imported: org.apache.maven.profiles &lt; maven.ext Imported: org.sonatype.aether.metadata &lt; maven.ext Imported: org.sonatype.aether.spi &lt; maven.ext Imported: org.codehaus.plexus.util.xml.pull.XmlPullParserException &lt; maven.ext Imported: org.apache.maven.wagon.* &lt; maven.ext Imported: org.sonatype.aether.graph &lt; maven.ext Imported: org.apache.maven.rtinfo &lt; maven.ext Imported: org.sonatype.aether.installation &lt; maven.ext Imported: org.apache.maven.monitor &lt; maven.ext Imported: org.sonatype.aether.transfer &lt; maven.ext Imported: org.codehaus.plexus.context &lt; maven.ext Imported: org.apache.maven.wagon.observers &lt; maven.ext Imported: org.apache.maven.wagon.resource &lt; maven.ext Imported: org.sonatype.aether.deployment &lt; maven.ext Imported: org.apache.maven.model &lt; maven.ext Imported: org.codehaus.plexus.util.xml.Xpp3Dom &lt; maven.ext Imported: org.apache.maven.artifact &lt; maven.ext Imported: org.apache.maven.toolchain &lt; maven.ext Imported: org.codehaus.plexus.util.xml.pull.XmlSerializer &lt; maven.ext Imported: org.apache.maven.settings &lt; maven.ext Imported: org.apache.maven.wagon.authorization &lt; maven.ext Imported: org.apache.maven.wagon.events &lt; maven.ext Imported: org.apache.maven.wagon.authentication &lt; maven.ext Imported: org.apache.maven.reporting &lt; maven.ext Imported: org.apache.maven.wagon.repository &lt; maven.ext Imported: org.apache.maven.configuration &lt; maven.ext Imported: org.codehaus.plexus.classworlds &lt; maven.ext Imported: org.codehaus.classworlds &lt; maven.ext Imported: org.codehaus.plexus.util.xml.pull.XmlPullParser &lt; maven.ext Imported: org.apache.maven.classrealm &lt; maven.ext Imported: org.sonatype.aether.resolution &lt; maven.ext Imported: org.apache.maven.execution &lt; maven.ext Imported: org.apache.maven.wagon.proxy &lt; maven.ext Imported: org.codehaus.plexus.container &lt; maven.ext Imported: org.codehaus.plexus.component &lt; maven.ext Populating class realm maven.api org.codehaus.mojo:exec-maven-plugin:jar:1.2.1: org.apache.maven:maven-toolchain:jar:1.0:compile org.apache.maven:maven-project:jar:2.0.6:compile org.apache.maven:maven-settings:jar:2.0.6:compile org.apache.maven:maven-profile:jar:2.0.6:compile org.apache.maven:maven-plugin-registry:jar:2.0.6:compile org.apache.maven:maven-model:jar:2.0.6:compile org.apache.maven:maven-artifact:jar:2.0.6:compile org.apache.maven:maven-artifact-manager:jar:2.0.6:compile org.apache.maven:maven-repository-metadata:jar:2.0.6:compile org.apache.maven:maven-core:jar:2.0.6:compile org.apache.maven:maven-plugin-parameter-documenter:jar:2.0.6:compile org.apache.maven.reporting:maven-reporting-api:jar:2.0.6:compile org.apache.maven.doxia:doxia-sink-api:jar:1.0-alpha-7:compile org.apache.maven:maven-error-diagnostics:jar:2.0.6:compile commons-cli:commons-cli:jar:1.0:compile org.apache.maven:maven-plugin-descriptor:jar:2.0.6:compile org.codehaus.plexus:plexus-interactivity-api:jar:1.0-alpha-4:compile org.apache.maven:maven-monitor:jar:2.0.6:compile classworlds:classworlds:jar:1.1:compile org.apache.maven:maven-plugin-api:jar:2.0.6:compile org.codehaus.plexus:plexus-utils:jar:2.0.5:compile org.codehaus.plexus:plexus-container-default:jar:1.0-alpha-9:compile junit:junit:jar:3.8.2:test (scope managed from compile) (version managed from 3.8.1) org.apache.commons:commons-exec:jar:1.1:compile Created new class realm plugin&gt;org.codehaus.mojo:exec-maven-plugin:1.2.1 Importing foreign packages into class realm plugin&gt;org.codehaus.mojo:exec-maven-plugin:1.2.1 Imported: &lt; maven.api Populating class realm plugin&gt;org.codehaus.mojo:exec-maven-plugin:1.2.1 Included: org.codehaus.mojo:exec-maven-plugin:jar:1.2.1 Included: org.apache.maven.reporting:maven-reporting-api:jar:2.0.6 Included: org.apache.maven.doxia:doxia-sink-api:jar:1.0-alpha-7 Included: commons-cli:commons-cli:jar:1.0 Included: org.codehaus.plexus:plexus-interactivity-api:jar:1.0-alpha-4 Included: org.codehaus.plexus:plexus-utils:jar:2.0.5 Included: org.apache.commons:commons-exec:jar:1.1 Excluded: org.apache.maven:maven-toolchain:jar:1.0 Excluded: org.apache.maven:maven-project:jar:2.0.6 Excluded: org.apache.maven:maven-settings:jar:2.0.6 Excluded: org.apache.maven:maven-profile:jar:2.0.6 Excluded: org.apache.maven:maven-plugin-registry:jar:2.0.6 Excluded: org.apache.maven:maven-model:jar:2.0.6 Excluded: org.apache.maven:maven-artifact:jar:2.0.6 Excluded: org.apache.maven:maven-artifact-manager:jar:2.0.6 Excluded: org.apache.maven:maven-repository-metadata:jar:2.0.6 Excluded: org.apache.maven:maven-core:jar:2.0.6 Excluded: org.apache.maven:maven-plugin-parameter-documenter:jar:2.0.6 Excluded: org.apache.maven:maven-error-diagnostics:jar:2.0.6 Excluded: org.apache.maven:maven-plugin-descriptor:jar:2.0.6 Excluded: org.apache.maven:maven-monitor:jar:2.0.6 Excluded: classworlds:classworlds:jar:1.1 Excluded: org.apache.maven:maven-plugin-api:jar:2.0.6 Excluded: org.codehaus.plexus:plexus-container-default:jar:1.0-alpha-9 Excluded: junit:junit:jar:3.8.2 Configuring mojo org.codehaus.mojo:exec-maven-plugin:1.2.1:exec from plugin realm ClassRealm[plugin&gt;org.codehaus.mojo:exec-maven-plugin:1.2.1, parent: sun.misc.Launcher$AppClassLoader@5c647e05] Configuring mojo 'org.codehaus.mojo:exec-maven-plugin:1.2.1:exec' with basic configurator --&gt; (f) basedir = C:\Users\Birger\Workspace\myproject (f) classpathScope = runtime (f) commandlineArgs = -Djava.library.path=lib\ -classpath %classpath com.mysite.myproject.Main (f) executable = C:\Program Files\Java\jdk1.8.0_91\bin\java.exe (f) longClasspath = false (f) project = MavenProject: com.mysite:myproject:1.0-SNAPSHOT @ C:\Users\Birger\Workspace\myproject\pom.xml (f) session = org.apache.maven.execution.MavenSession@2ef14fe (f) skip = false -- end configuration -- Collected project artifacts [jni4net:jni4net.j:jar:0.8.8.0:compile] Collected project classpath [C:\Users\Birger\Workspace\myproject\target\classes] dealing with jni4net:jni4net.j:jar:0.8.8.0:compile Toolchains are ignored, 'executable' parameter is set to C:\Program Files\Java\jdk1.8.0_91\bin\java.exe Executing command line: C:\Program Files\Java\jdk1.8.0_91\bin\java.exe -Djava.library.path=lib\ -classpath C:\Users\Birger\Workspace\myproject\target\classes;C:\Users\Birger\.m2\repository\jni4net\jni4net.j\0.8.8.0\jni4net.j-0.8.8.0.jar com.mysite.myproject.Main Initialized! Hello world! ------------------------------------------------------------------------ BUILD SUCCESS ------------------------------------------------------------------------ Total time: 1.360s Finished at: Fri Jul 08 09:26:48 CEST 2016 Final Memory: 5M/245M ------------------------------------------------------------------------ </code></pre> <p>Command-line output when trying to run my built .jar</p> <pre><code>C:\Users\Birger\Workspace\myproject\target&gt;"C:\Program Files\Java\jdk1.8.0_91\bin\java.exe" -Djava.library.path=lib\ -jar myproject-1.0-SNAPSHOT.jar Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Users\Birger\Workspace\myproject\target\lib\jni4net.n-0.8.8.0.dll: Can't load this .dll (machine code=0xbd) on a AMD 64-bit platform at java.lang.ClassLoader$NativeLibrary.load(Native Method) at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1941) at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1857) at java.lang.Runtime.loadLibrary0(Runtime.java:870) at java.lang.System.loadLibrary(System.java:1122) at com.mysite.myproject.Main.&lt;clinit&gt;(Main.java:11) </code></pre> <p><strong>EDIT2:</strong></p> <p>For anyone looking to reproduce this error, jni4net can be found <a href="http://jni4net.com/" rel="noreferrer">here</a>. I installed the .jar with this windows batch file:</p> <pre><code>set project_dir=YOURPROJECTDIRECTORYHERE set proxygen_dir=YOURPROXYGENINSTALLATIONDIRECTORYHERE set temp_repo_dir=%project_dir%\temp-repo call mvn install:install-file -DlocalRepositoryPath=%temp_repo_dir% -DcreateChecksum=true -Dpackaging=jar -Dfile=%proxygen_dir%\lib\jni4net.j-0.8.8.0.jar -DgroupId=jni4net -DartifactId=jni4net.j -Dversion=0.8.8.0 </code></pre> <p><strong>EDIT3:</strong></p> <p>I installed 32-bit JVM, and tried running the application with the following command:</p> <pre><code>"C:\Program Files (x86)\Java\jre1.8.0_91\bin\java.exe" -Djava.library.path=lib\ -jar myproject-1.0-SNAPSHOT.jar </code></pre> <p>Now I get:</p> <pre><code>Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Users\Birger\Workspace\myproject\target\lib\jni4net.n.w32.v20-0.8.8.0.dll: Can't load this .dll (machine code=0xbd) on a IA 32-bit platform at java.lang.ClassLoader$NativeLibrary.load(Native Method) at java.lang.ClassLoader.loadLibrary0(Unknown Source) at java.lang.ClassLoader.loadLibrary(Unknown Source) at java.lang.Runtime.loadLibrary0(Unknown Source) at java.lang.System.loadLibrary(Unknown Source) at com.mysite.myproject.Main.&lt;clinit&gt;(Main.java:19) </code></pre> <p>I'm getting quite desperate here (and a little frustrated with Java tbh)</p> <p><strong>EDIT4:</strong></p> <p>Tried these commands, also not working:</p> <pre><code>"C:\Program Files\Java\jdk1.8.0_91\bin\java" -Djava.library.path=lib\ -classpath C:\Users\Birger\Workspace\myproject\target\classes;C:\Users\Birger\.m2\repositor‌​y\jni4net\jni4net.j\0.8.8.0\jni4net.j-0.8.8.0.jar com.mysite.myproject.Main "C:\Program Files\Java\jdk1.8.0_91\bin\java" -Djava.library.path=lib\ -classpath classes;C:\Users\Birger\.m2\repositor‌​y\jni4net\jni4net.j\0.8.8.0\jni4net.j-0.8.8.0.jar com.mysite.myproject.Main "C:\Program Files\Java\jdk1.8.0_91\bin\java" -Djava.library.path=lib\ -classpath classes com.mysite.myproject.Main </code></pre>
2
How to store input given by user in html form in sql using php
<p>This is my PHP code.</p> <pre><code>&lt;html&gt;&lt;head&gt; &lt;title&gt;login.php&lt;/title&gt; &lt;link rel = "stylesheet" href="login-style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class = "container"&gt; &lt;div class = "message"&gt; &lt;?php define('DB_NAME','mydb'); define('DB_USER','root'); define('DB_PASSWORD',''); define('DB_HOST','127.0.0.1'); $link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD); if($link){ die('could not connect:'. mysql_error()); } $db_selected = mysql_select_db(DB_NAME,$link); if(!$db_selected){ die('can\'t use'.DB_NAME . ': ' . mysql_error()); } $value1 = $_POST['name']; $value2 = $_POST['password']; $sql = "INSERT INTO Account (username,password) VALUES ('$value1','$value2')"; if(!mysql_query($sql)) {die('ERROR'.mysql_error()); } mysql_close(); ?&gt; &lt;h1&gt;Thank you for logging in &lt;/h1&gt; &lt;form action = "form.html"&gt; &lt;p class ="submit"&gt; &lt;button type ="submit" &gt; GO TO FORM &lt;/button&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I want to store the data in MySQL but when I run the html code (which i have connected to this php code using action =" name of this file"), no entry is done in database I created, can you tell me what is done wrong and help me to correct it?</p> <pre><code>&lt;DOCTYPE! html&gt; &lt;html lang = "en-US"&gt; &lt;head&gt; &lt;meta charset = "UTF-8"&gt; &lt;title&gt;Sign-In&lt;/title&gt; &lt;link rel = "stylesheet" href ="style-sign.css"&gt; &lt;script type = "text/javascript"&gt; function validateForm(){ var x = document.forms["forma"]["login"].value; if(x == null || x == "") { alert("fill the field "); return false; } var y = document.forms["forma"]["password"].value; if( y == null || y == "") { alert("fill the field"); return false; } } &lt;/script&gt; &lt;/head&gt; &lt;body &gt; &lt;div class="container"&gt; &lt;div class="login"&gt; &lt;h1&gt;Login&lt;/h1&gt; &lt;form name = "forma" method="post" onsubmit="return validateForm()" action = "login.php"&gt; &lt;p&gt; &lt;input type="text" name="name" value="" placeholder="Username or Email"&gt; &lt;/p&gt; &lt;p&gt; &lt;input type="password" name="password" value="" placeholder="Password"&gt; &lt;/p&gt; &lt;p class="submit"&gt; &lt;input type="submit" name="commit" value="Login" &gt; &lt;/p&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>this is my html code which i have connected to this php file ,I am using xampp and using phpmyadmin , I am not getting any error and apache and mysql both are running </p> <p>help me with this problem </p>
2
NPE error in Android Studio
<p>I am getting the following error in Android Studio and I am unable to resolve it: </p> <pre><code>07-06 19:44:41.798 4491-4491/com.example.first_app D/AndroidRuntime: Shutting down VM 07-06 19:44:41.799 4491-4491/com.example.first_app E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.first_app, PID: 4491 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.first_app/com.example.first_app.welcome}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.view.View.toString()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.view.View.toString()' on a null object reference at com.example.first_app.welcome.onCreate(welcome.java:22) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  07-06 19:44:44.696 4491-4497/com.example.first_app W/art: Suspending all threads took: 46.612ms 07-06 19:44:46.517 4491-4491/com.example.first_app I/Process: Sending signal. PID: 4491 SIG: 9 </code></pre> <p>THIS IS THE ERROR I M INCURRING</p> <hr> <p>CODE FOR welcome.java</p> <pre><code>public class welcome extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome); TextView my_msg; String name; my_msg= (TextView)findViewById(R.id.textView3); name= "Welcome " +findViewById(R.id.textView2).toString(); my_msg.setText(name); } } </code></pre> <hr> <p>XML CODE FOR welcome.xml ...Please refer it..it only shows the message on screen "welcome Name"..the name is entered by user through activity_form.java</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:weightSum="1" android:orientation="vertical"&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="0dp" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Large Text" android:id="@+id/textView3" android:layout_gravity="center" android:layout_weight="1" /&gt; &lt;/LinearLayout&gt; </code></pre>
2
Add function into the scope of another function JavaScript
<p>I'm trying to get the example code below to work.<br> <strong>Edit (Trying to be more clear what the aim is):</strong></p> <p>I wan't to make all the functions and variables of the <code>obj</code> available in the functions <code>setup</code> and <code>draw</code> as they where globals. This is not for the browser. This is for Adobe ExtendScript so I can only use EcmaScript 3 and some polyfills. The <code>lib.js</code> file is provided by me and gets included <strong>before</strong> the the <code>user-script.js</code> file. The user has a reference what functions are availble and might use them within <code>setup</code> and <code>draw</code>. This is actually pretty similar to what <a href="https://github.com/processing/p5.js" rel="nofollow">P5.js</a> does but I'm are trying to achieve this for InDesign. We can of course call the <code>obj.foo()</code>. The aim is though to get rid of the <code>obj.</code> to give the user the possibility to just call <code>foo</code> and get the result of <code>obj.foo</code>. </p> <p>This is lib.js. It is just a small part of the library to illustrate what I have at hand. </p> <pre><code>var obj = { foo: function() { console.log('foo'); }, bah: function() { console.log('bah'); }, foobah:function(arg){ return arg*2; }, CONST:"Hello World", go:function(){ // looks in the global scope if there is // a setup and draw function and should patch them. if(typeof glob.setup === 'function'){ glob.setup(); }, if(typeof glob.draw === 'function'){ glob.draw(); } } }; </code></pre> <p>This could be the user-script.js. The structure we Provide is:</p> <ul> <li>#include for the lib</li> <li>function setup(){}</li> <li>function draw(){}</li> <li>obj.go() as execution of everything (might be removed later on) </li> </ul> <p>I can not tell the user to write more additional code into setup and draw. The part for the user should be so reduced he can write this by hand and does not need to use a boilerplate or something like this. </p> <pre><code>#include lib.js function setup() { foo(); // might be called or not console.log('in setup'); } function draw() { bah();// might be called or not console.log('in draw'); } obj.go() </code></pre> <hr> <p>Thanks to all your answers. I will review them and get back to report what was the final decision. All of them seem to solve the problem in different ways. I currently can't tell which is the "right" answer. Those we seemed be nearest to my question got an upvote from me.</p>
2
spark streaming checkpoint recovery is very very slow
<ul> <li>Goal: Read from Kinesis and store data in to S3 in Parquet format via spark streaming.</li> <li>Situation: Application runs fine initially, running batches of 1hour and the processing time is less than 30 minutes on average. For some reason lets say the application crashes, and we try to restart from checkpoint. The processing now takes forever and does not move forward. We tried to test out the same thing at batch interval of 1 minute, the processing runs fine and takes 1.2 minutes for batch to finish. When we recover from checkpoint it takes about 15 minutes for each batch.</li> <li>Notes: we are using s3 for checkpoints using 1 executor, with 19g mem &amp; 3 cores per executor</li> </ul> <p>Attaching the screenshots:</p> <p><strong>First Run - Before checkpoint Recovery</strong> <a href="https://i.stack.imgur.com/FJV9p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FJV9p.png" alt="Before checkpoint - Streaming Page"></a></p> <p><a href="https://i.stack.imgur.com/Hx5nV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Hx5nV.png" alt="Before checkpoint - Jobs Page"></a></p> <p><a href="https://i.stack.imgur.com/CVs9a.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CVs9a.png" alt="Before checkpoint - Jobs Page2"></a></p> <p><strong>Trying to Recover from checkpoint:</strong> <a href="https://i.stack.imgur.com/Jm41J.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Jm41J.png" alt="After checkpoint - Streaming Page"></a> <a href="https://i.stack.imgur.com/q8Fbp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/q8Fbp.png" alt="After checkpoint - Jobs Page"></a></p> <p><strong>Config.scala</strong></p> <pre><code>object Config { val sparkConf = new SparkConf val sc = new SparkContext(sparkConf) val sqlContext = new HiveContext(sc) val eventsS3Path = sc.hadoopConfiguration.get("eventsS3Path") val useIAMInstanceRole = sc.hadoopConfiguration.getBoolean("useIAMInstanceRole",true) val checkpointDirectory = sc.hadoopConfiguration.get("checkpointDirectory") // sc.hadoopConfiguration.set("spark.sql.parquet.output.committer.class","org.apache.spark.sql.parquet.DirectParquetOutputCommitter") DateTimeZone.setDefault(DateTimeZone.forID("America/Los_Angeles")) val numStreams = 2 def getSparkContext(): SparkContext = { this.sc } def getSqlContext(): HiveContext = { this.sqlContext } } </code></pre> <p><strong>S3Basin.scala</strong></p> <pre><code>object S3Basin { def main(args: Array[String]): Unit = { Kinesis.startStreaming(s3basinFunction _) } def s3basinFunction(streams : DStream[Array[Byte]]): Unit ={ streams.foreachRDD(jsonRDDRaw =&gt;{ println(s"Old partitions ${jsonRDDRaw.partitions.length}") val jsonRDD = jsonRDDRaw.coalesce(10,true) println(s"New partitions ${jsonRDD.partitions.length}") if(!jsonRDD.isEmpty()){ val sqlContext = SQLContext.getOrCreate(jsonRDD.context) sqlContext.read.json(jsonRDD.map(f=&gt;{ val str = new String(f) if(str.startsWith("{\"message\"")){ str.substring(11,str.indexOf("@version")-2) } else{ str } })).registerTempTable("events") sqlContext.sql( """ |select |to_date(from_utc_timestamp(from_unixtime(at), 'US/Pacific')) as event_date, |hour(from_utc_timestamp(from_unixtime(at), 'US/Pacific')) as event_hour, |* |from events """.stripMargin).coalesce(1).write.mode(SaveMode.Append).partitionBy("event_date", "event_hour","verb").parquet(Config.eventsS3Path) sqlContext.dropTempTable("events") } }) } } </code></pre> <p><strong>Kinesis.scala</strong></p> <pre><code>object Kinesis{ def functionToCreateContext(streamFunc: (DStream[Array[Byte]]) =&gt; Unit): StreamingContext = { val streamingContext = new StreamingContext(Config.sc, Minutes(Config.sc.hadoopConfiguration.getInt("kinesis.StreamingBatchDuration",1))) // new context streamingContext.checkpoint(Config.checkpointDirectory) // set checkpoint directory val sc = Config.getSparkContext var awsCredentails : BasicAWSCredentials = null val kinesisClient = if(Config.useIAMInstanceRole){ new AmazonKinesisClient() } else{ awsCredentails = new BasicAWSCredentials(sc.hadoopConfiguration.get("kinesis.awsAccessKeyId"),sc.hadoopConfiguration.get("kinesis.awsSecretAccessKey")) new AmazonKinesisClient(awsCredentails) } val endpointUrl = sc.hadoopConfiguration.get("kinesis.endpointUrl") val appName = sc.hadoopConfiguration.get("kinesis.appName") val streamName = sc.hadoopConfiguration.get("kinesis.streamName") kinesisClient.setEndpoint(endpointUrl) val numShards = kinesisClient.describeStream(streamName).getStreamDescription().getShards().size val batchInterval = Minutes(sc.hadoopConfiguration.getInt("kinesis.StreamingBatchDuration",1)) // Kinesis checkpoint interval is the interval at which the DynamoDB is updated with information // on sequence number of records that have been received. Same as batchInterval for this // example. val kinesisCheckpointInterval = batchInterval // Get the region name from the endpoint URL to save Kinesis Client Library metadata in // DynamoDB of the same region as the Kinesis stream val regionName = sc.hadoopConfiguration.get("kinesis.regionName") val kinesisStreams = (0 until Config.numStreams).map { i =&gt; println(s"creating stream for $i") if(Config.useIAMInstanceRole){ KinesisUtils.createStream(streamingContext, appName, streamName, endpointUrl, regionName, InitialPositionInStream.TRIM_HORIZON, kinesisCheckpointInterval, StorageLevel.MEMORY_AND_DISK_2) }else{ KinesisUtils.createStream(streamingContext, appName, streamName, endpointUrl, regionName, InitialPositionInStream.TRIM_HORIZON, kinesisCheckpointInterval, StorageLevel.MEMORY_AND_DISK_2,awsCredentails.getAWSAccessKeyId,awsCredentails.getAWSSecretKey) } } val unionStreams = streamingContext.union(kinesisStreams) streamFunc(unionStreams) streamingContext } def startStreaming(streamFunc: (DStream[Array[Byte]]) =&gt; Unit) = { val sc = Config.getSparkContext if(sc.defaultParallelism &lt; Config.numStreams+1){ throw new Exception(s"Number of shards = ${Config.numStreams} , number of processor = ${sc.defaultParallelism}") } val streamingContext = StreamingContext.getOrCreate(Config.checkpointDirectory, () =&gt; functionToCreateContext(streamFunc)) // sys.ShutdownHookThread { // println("Gracefully stopping Spark Streaming Application") // streamingContext.stop(true, true) // println("Application stopped greacefully") // } // streamingContext.start() streamingContext.awaitTermination() } } </code></pre> <p><strong>DAG</strong> <a href="https://i.stack.imgur.com/FPBL4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FPBL4.png" alt="DAG"></a></p> <p><a href="https://i.stack.imgur.com/pm1EC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pm1EC.png" alt="enter image description here"></a></p>
2
backslashes "\" added in JSON string for web service in swift
<p>In my project I need to send JSON object in web service API call. I have converted JSON from array.</p> <pre><code>do { let theJSONData = try NSJSONSerialization.dataWithJSONObject( param , options: NSJSONWritingOptions(rawValue: 0)) var theJSONText : String = String(data: theJSONData, encoding: NSASCIIStringEncoding)! print(theJSONText) theJSONText = theJSONText.stringByReplacingOccurrencesOfString("\\", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil) print(theJSONText) let newParam = ["ESignData":theJSONText] } catch let error as NSError { print(error) } </code></pre> <p>it print string correctly as</p> <pre><code>{"EntNum":"47","JobNo":"1737753","ClientID":"100","HospNo":"1","QAReason":"","DoctorNo":"1694","Action":"Sign"} {"EntNum":"47","JobNo":"1737753","ClientID":"100","HospNo":"1","QAReason":"","DoctorNo":"1694","Action":"Sign"} </code></pre> <p>Now When I try to send this <code>newParam</code> dictionary in API call, it contains "\" in string parameters of JSON string.</p> <pre><code>WebService.PostURL(mainLink, methodname: ESIGNTHISDOC, param: newParam, userName: AUTH_USERNAME, password: AUTH_PWD, CompletionHandler: { (success, response) in }) </code></pre> <p>And in that web service method I have print param.</p> <pre><code>Param = { ESignData = "{\"EntNum\":\"47\",\"JobNo\":\"1737753\",\"ClientID\":\"100\",\"HospNo\":\"1\",\"QAReason\":\"\",\"DoctorNo\":\"1694\",\"Action\":\"Sign\"}"; } </code></pre> <p>Now in this I know it is obvious in iOS because of " in string. Now the problem is that there are lots of APIs working in android app, and the API developer doesn't want to update his code according to us. </p> <p>I know this problem happens because of adding JSON string in dictionary as parameter. But I have not proper justification for that so if any proof will be also helpful for me to convince him.</p> <p>Any solution to convert the JSON string without backslash in iOS? I need to fix from my side if possible. Any help will be appreciate.</p> <p>EDIT : </p> <p>On server side it needs like</p> <pre><code>ESignData = {"EntNum":"47","JobNo":"1737753","ClientID":"100","HospNo":"1","QAReason":"","DoctorNo":"1694","Action":"Sign"} </code></pre> <p>If I pass this as parameter in POSTMAN than it gives success message. But not with our object with "\" in it.</p> <p>EDIT 2:</p> <p>Now printing the <code>newParam</code> dictionary:</p> <pre><code>print(newParam) print("-------------------------") print(newParam["ESignData"]) </code></pre> <p>And logs :</p> <pre><code>["ESignData": "{\"EntNum\":\"47\",\"JobNo\":\"1737754\",\"ClientID\":\"100\",\"HospNo\":\"1\",\"QAReason\":\"\",\"DoctorNo\":\"1694\",\"Action\":\"Sign\"}"] ------------------------- Optional("{\"EntNum\":\"47\",\"JobNo\":\"1737754\",\"ClientID\":\"100\",\"HospNo\":\"1\",\"QAReason\":\"\",\"DoctorNo\":\"1694\",\"Action\":\"Sign\"}") </code></pre> <p>And by debug :</p> <pre><code>Printing description of newParam: ▿ 1 elements ▿ [0] : 2 elements - .0 : "ESignData" - .1 : "{\"EntNum\":\"47\",\"JobNo\":\"1737754\",\"ClientID\":\"100\",\"HospNo\":\"1\",\"QAReason\":\"\",\"DoctorNo\":\"1694\",\"Action\":\"Sign\"}" </code></pre> <p>So it shows that it is in our dictionary. All the " are joined by \.</p>
2
Java8 Lambda Deserialization - ClassCastException
<p><code>ClassCastException</code> is thrown by Java8 upon deserializing a lambda when following conditions are met:</p> <ul> <li>Parent class has a method, reference to which is used to automatically create a <code>Serializable</code> lambda</li> <li>There are several child classes that extend it and there are several usages of above method as a method reference, but with different child classes</li> <li>After method reference is consumed it is serialized and the deserialized</li> <li>All method references are used within the same capturing class</li> </ul> <p>Tested on Oracle Java compiler and runtime versions 1.8.0_91. Please find test code on how to reproduce:</p> <pre><code>import java.io.*; /** * @author Max Myslyvtsev * @since 7/6/16 */ public class LambdaSerializationTest implements Serializable { static abstract class AbstractConverter implements Serializable { String convert(String input) { return doConvert(input); } abstract String doConvert(String input); } static class ConverterA extends AbstractConverter { @Override String doConvert(String input) { return input + "_A"; } } static class ConverterB extends AbstractConverter { @Override String doConvert(String input) { return input + "_B"; } } static class ConverterC extends AbstractConverter { @Override String doConvert(String input) { return input + "_C"; } } interface MyFunction&lt;T, R&gt; extends Serializable { R call(T var); } public static void main(String[] args) throws Exception { System.out.println(System.getProperty("java.version")); ConverterA converterA = new ConverterA(); ConverterB converterB = new ConverterB(); ConverterC converterC = new ConverterC(); giveFunction(converterA::convert); giveFunction(converterB::convert); giveFunction(converterC::convert); } private static void giveFunction(MyFunction&lt;String, String&gt; f) { f = serializeDeserialize(f); System.out.println(f.call("test")); } private static &lt;T&gt; T serializeDeserialize(T object) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(object); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); @SuppressWarnings("unchecked") T result = (T) ois.readObject(); return result; } catch (Exception e) { throw new RuntimeException(e); } } } </code></pre> <p>It gives following output:</p> <pre><code>1.8.0_91 test_A Exception in thread "main" java.lang.RuntimeException: java.io.IOException: unexpected exception type at LambdaSerializationTest.serializeDeserialize(LambdaSerializationTest.java:68) at LambdaSerializationTest.giveFunction(LambdaSerializationTest.java:52) at LambdaSerializationTest.main(LambdaSerializationTest.java:47) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) Caused by: java.io.IOException: unexpected exception type at java.io.ObjectStreamClass.throwMiscException(ObjectStreamClass.java:1582) at java.io.ObjectStreamClass.invokeReadResolve(ObjectStreamClass.java:1154) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1817) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373) at LambdaSerializationTest.serializeDeserialize(LambdaSerializationTest.java:65) ... 7 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at java.lang.invoke.SerializedLambda.readResolve(SerializedLambda.java:230) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at java.io.ObjectStreamClass.invokeReadResolve(ObjectStreamClass.java:1148) ... 11 more Caused by: java.lang.ClassCastException: LambdaSerializationTest$ConverterB cannot be cast to LambdaSerializationTest$ConverterA at LambdaSerializationTest.$deserializeLambda$(LambdaSerializationTest.java:7) ... 21 more </code></pre> <p>Upon decompiling this <code>$deserializeLambda$</code> method with CFR following code is revealed:</p> <pre><code>private static /* synthetic */ Object $deserializeLambda$(SerializedLambda lambda) { switch (lambda.getImplMethodName()) { case "convert": { if (lambda.getImplMethodKind() == 5 &amp;&amp; lambda.getFunctionalInterfaceClass().equals("LambdaSerializationTest$MyFunction") &amp;&amp; lambda.getFunctionalInterfaceMethodName().equals("call") &amp;&amp; lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") &amp;&amp; lambda.getImplClass().equals("LambdaSerializationTest$AbstractConverter") &amp;&amp; lambda.getImplMethodSignature().equals("(Ljava/lang/String;)Ljava/lang/String;")) { return (MyFunction&lt;String, String&gt;)LambdaMetafactory.altMetafactory(null, null, null, (Ljava/lang/Object;)Ljava/lang/Object;, convert(java.lang.String ), (Ljava/lang/String;)Ljava/lang/String;)((ConverterA)((ConverterA)lambda.getCapturedArg(0))); } if (lambda.getImplMethodKind() == 5 &amp;&amp; lambda.getFunctionalInterfaceClass().equals("LambdaSerializationTest$MyFunction") &amp;&amp; lambda.getFunctionalInterfaceMethodName().equals("call") &amp;&amp; lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") &amp;&amp; lambda.getImplClass().equals("LambdaSerializationTest$AbstractConverter") &amp;&amp; lambda.getImplMethodSignature().equals("(Ljava/lang/String;)Ljava/lang/String;")) { return (MyFunction&lt;String, String&gt;)LambdaMetafactory.altMetafactory(null, null, null, (Ljava/lang/Object;)Ljava/lang/Object;, convert(java.lang.String ), (Ljava/lang/String;)Ljava/lang/String;)((ConverterB)((ConverterB)lambda.getCapturedArg(0))); } if (lambda.getImplMethodKind() != 5 || !lambda.getFunctionalInterfaceClass().equals("LambdaSerializationTest$MyFunction") || !lambda.getFunctionalInterfaceMethodName().equals("call") || !lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") || !lambda.getImplClass().equals("LambdaSerializationTest$AbstractConverter") || !lambda.getImplMethodSignature().equals("(Ljava/lang/String;)Ljava/lang/String;")) break; return (MyFunction&lt;String, String&gt;)LambdaMetafactory.altMetafactory(null, null, null, (Ljava/lang/Object;)Ljava/lang/Object;, convert(java.lang.String ), (Ljava/lang/String;)Ljava/lang/String;)((ConverterC)((ConverterC)lambda.getCapturedArg(0))); } } throw new IllegalArgumentException("Invalid lambda deserialization"); } </code></pre> <p>So it appears that actual captured argument is not used to determine which exact lambda has to be deserialized. All 3 lambdas will satisfy 1st <code>if</code> condition and <code>ConverterA</code> will be assumed.</p> <p>When debugging we can observe that in runtime <code>lambda.getCapturedArg(0)</code> is of a correct type (<code>ConverterB</code> when exception is thrown) and also it worth noting that cast is not needed since method to be invoked is present in base <code>AbstractConverter</code> class.</p> <p>Is it expected behavior? If yes, what is recommended workaround?</p>
2
How to guarantee that equals() and hashCode() are in sync?
<p>We are writing a class which requires very complicated logic to compute equals() and hashCode(). Something along lines with:</p> <pre><code>@Getters @Setters @FieldDefaults(level=AccessLevel.PRIVATE) public class ExternalData { TypeEnum type; String data; List&lt;ExternalData&gt; children; } </code></pre> <p>We do not construct these objects, they are deserialized from XML from external complex system. There are 20+ types and depending on type data can be ignored, or processed with children, or processed without children and comparison of data for each type of node depend on type.</p> <p>We created equals() and hashCode() to reflect all those rules, but recently ran into an issue that hashCode got out of sync with equals causing equal objects to be added twice to a HashSet. I believe HashMap (and HashSet for that matter) are implemented this way in Java: <a href="https://en.wikipedia.org/wiki/Hash_table" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Hash_table</a> The implementation first put objects in buckets based on hashCode and then for each bucket checks equals. In unfortunate scenario where 2 equal object will go to different buckets they will never be compared by equals(). By "Out of sync" here I mean that they go into different buckets.</p> <p>What is the best way to make sure equals and hashCode do not get out of sync?</p> <p><strong>Edit</strong>: This question is different from <a href="https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java">What issues should be considered when overriding equals and hashCode in Java?</a> There they ask about generic guidance and the accepted answer does not apply in my situation. They say "make equals and hashCode consistent", here I'm asking how exactly do I do that.</p>
2
No response from PHP on AJAX request
<p>I am working on a simple signup page using jQuery and PHP using AJAX.</p> <p>Here is the script for making the ajax call:</p> <pre><code>&lt;script&gt; function submitForm(){ var data1=$('#regform').serialize(); $.ajax({ type:'POST', url:'signup.php', data:data1, success: function(response){ console.log(response); if(response==1) alert('taken'); else if(response==2) alert('registered'); else alert(response); } }); } &lt;/script&gt; </code></pre> <p>and the PHP script which responds to the call:</p> <p>signup.php:</p> <pre><code>&lt;?php require_once 'dbconnect.php'; if($_POST) { $user_name = $_POST['user_name']; $user_email = $_POST['user_email']; $user_password = $_POST['password']; try { $sth = $dbh-&gt;prepare(&quot;SELECT * FROM logindata WHERE email=:email&quot;); $sth-&gt;execute(array(&quot;:email&quot;=&gt;$user_email)); $count = $sth-&gt;rowCount(); if($count==0){ $sth = $dbh-&gt;prepare(&quot;INSERT INTO logindata(username,email,pass) VALUES(:uname, :email, :pass)&quot;); $sth-&gt;bindParam(&quot;:uname&quot;,$user_name); $sth-&gt;bindParam(&quot;:email&quot;,$user_email); $sth-&gt;bindParam(&quot;:pass&quot;,$user_password); if(!$sth-&gt;execute()) { echo &quot;3&quot;; } else { echo &quot;2&quot;; } } else{ echo &quot;1&quot;; } } catch(PDOException $e){ echo $e-&gt;getMessage(); } } ?&gt; </code></pre> <p>using PDO.</p> <p>dbconnect.php:</p> <pre><code>&lt;?php $dbhost='localhost'; $dbuser='root'; $dbpass=''; $dbname='ambitio'; try{ $dbh=new PDO(&quot;mysql:host={$dbhost};dbname={$dbname}&quot;,$dbuser,$dbpass); $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); } catch(PDOException $e){ echo $e-&gt;getMessage(); } ?&gt; </code></pre> <p><strong>Problem</strong></p> <p>Neither of the two responses are being returned to the jQuery ajax call. I checked with <code>console.log()</code> but nothing shows up in the browser. Data gets stored in the MySQL database (checked it) which means that <code>execute()</code> is working fine in PHP, but still no alert is shown in the browser. <code>1</code> does get returned in case <code>count</code> evaluates to <code>0</code>.</p> <p>Also, when I refresh the form without actually submitting the form, I get the error <code>POST 412 (Precondition Failed)</code> at the browser console.</p> <p><strong>Apache access log</strong></p> <pre><code>::1 - - [19/Jul/2016:23:51:55 +0530] &quot;GET /ambitio/css/bootstrap.css HTTP/1.1&quot; 304 - &quot;http://localhost/ambitio/signup.html&quot; &quot;Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36&quot; ::1 - - [19/Jul/2016:23:51:55 +0530] &quot;GET /ambitio/css/overboot.css HTTP/1.1&quot; 304 - &quot;http://localhost/ambitio/signup.html&quot; &quot;Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36&quot; ::1 - - [19/Jul/2016:23:51:55 +0530] &quot;GET /ambitio/css/font-awesome.css HTTP/1.1&quot; 304 - &quot;http://localhost/ambitio/signup.html&quot; &quot;Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36&quot; ::1 - - [19/Jul/2016:23:51:55 +0530] &quot;GET /ambitio/js/jquery.js HTTP/1.1&quot; 304 - &quot;http://localhost/ambitio/signup.html&quot; &quot;Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36&quot; ::1 - - [19/Jul/2016:23:51:55 +0530] &quot;GET /ambitio/js/bootstrap.js HTTP/1.1&quot; 304 - &quot;http://localhost/ambitio/signup.html&quot; &quot;Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36&quot; ::1 - - [20/Jul/2016:00:43:36 +0530] &quot;GET /ambitio/signup.html HTTP/1.1&quot; 200 1454 &quot;-&quot; &quot;Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36&quot; ::1 - - [20/Jul/2016:00:43:46 +0530] &quot;POST /ambitio/signup.html HTTP/1.1&quot; 200 1454 &quot;http://localhost/ambitio/signup.html&quot; &quot;Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36&quot; ::1 - - [20/Jul/2016:00:43:46 +0530] &quot;POST /ambitio/signup.php HTTP/1.1&quot; 200 1 &quot;http://localhost/ambitio/signup.html&quot; &quot;Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36&quot; </code></pre> <p><strong>Form HTML markup</strong></p> <pre><code>&lt;form method=&quot;post&quot; id=&quot;regform&quot; onSubmit=&quot;submitForm()&quot;&gt; &lt;input type=&quot;text&quot; placeholder=&quot;Username&quot; id=&quot;user_name&quot; name=&quot;user_name&quot; /&gt; &lt;input type=&quot;email&quot; placeholder=&quot;Email&quot; id=&quot;user_email&quot; name=&quot;user_email&quot; /&gt; &lt;input type=&quot;password&quot; placeholder=&quot;Password&quot; id=&quot;password&quot; name=&quot;password&quot; /&gt; &lt;input type=&quot;password&quot; placeholder=&quot;Retype password&quot; id=&quot;rpassword&quot; name=&quot;rpassword&quot; /&gt; &lt;input type=&quot;submit&quot; id=&quot;submit&quot;/&gt; &lt;/form&gt; </code></pre>
2
Can I just put async at the top level (service layer) in C#?
<p>I have a layered architecture and usually put things like try/catches, logging and now async at the top level service layer so my domain code and repositories are written synchronously and then I wrap the calls in my service layer with an await task.run so I can keep the Async naming and logic in one layer. Is this OK? Or is there a reason to have async in all the child methods / lower layers as well? Will it actually spawn more threads or still only be 1 async thread that does the magic?</p> <p>If there is no issue with this, I have one problem where in my repository I need to use HttpClient but it only has async methods forcing me to use async lower in my architecture where I don't want to. Is there a way to call these methods without await/async and then at a higher layer method (in my service layer) still wrap in a task.run without blocking? Basically I do not want any methods to be async in my repository and would rather them be in my service layer which makes calls to the repository and other domain methods.</p>
2
What happened to USB MTP gadget driver in mainline Linux kernel?
<p>I'm trying to make a embedded device work as a MTP device, using USB gadget driver.</p> <p>I know have Android switched from mass storage gadget to MTP gadget for quite a while, and found the <a href="https://android.googlesource.com/kernel/tegra/+/android-tegra3-grouper-3.1-jb-mr1-fr/drivers/usb/gadget/f_mtp.c" rel="nofollow">source code for MTP gadget driver</a> in a few Android repositories.</p> <p>However in the <a href="http://lxr.free-electrons.com/source/drivers/usb/gadget/function/" rel="nofollow">mainline kernel code</a> I didn't find that particular file, nor equivalents.</p> <p>But I did find <a href="http://comments.gmane.org/gmane.linux.usb.general/28697" rel="nofollow">patches for MTP gadget driver</a> submitted for RFC in 2010.</p> <p><strong>Question:</strong></p> <p>Why mainline kernel does not accept this patch, and doesn't provide any other implementation of MTP gadget, either, but Android kernel provides it?</p> <p>Is this because of technical difficulty or other reasons, like there is a better way to do it?</p> <p>If I want to enable USB MTP gadget on my devices(one with TI OMAP3730 SoC running 2.6.37 kernel and another with NXP/Freescale IMX6 SoC, running 3.14 kernel), which version of the MTP gadget shall I use for backport?</p>
1
Sensible group Id for individual project?
<p>What is a sensible choice of group Id for a maven project that does not fall under any company/organisation/website? I understand that the convention com.companyname.projectname is used in order to avoid namespace conflicts between projects, but how should I come up with a prefix for an individual project I am starting? </p>
1
set color of grouped stacked column in highcharts
<p>I have a requirement to set the color of stack column chart in relation with previous stack. Consider this fiddle. <a href="http://jsfiddle.net/0n7g4a1e/" rel="noreferrer">http://jsfiddle.net/0n7g4a1e/</a></p> <pre><code>series: [{ name: 'John', data: [5, 3, 4, 7, 2], stack: 'Actual' }, { name: 'John', data: [3, 4, 4, 2, 5], stack: 'Budget' }] </code></pre> <p>If Jane - Actual is light green, Jane - Budget should be dark green. This should be for all categories, Apple through bananas. similarly if John - Acutal is light blue, John - budget should be dark blue. </p> <p>How can this be done? I dont want to specify each point color, i am fine with automatic color that gets selected, just that the bugdet series should have a shade darker than the actual.</p> <p>Thanks.</p>
1
Animating an image to make it rotate in a circle
<p>I am working on image transforms, rotates, and keyframes, but I am having a bit of an issue trying to get an image to spin in a circle. I have it set to rotate 360deg and two keyframes 0 and 100. I am wanting the image to spin from the center point of the image, so it looks as if the loading circle is loading something.</p> <p>Right now it seems the image spins from the top-left corner.</p> <p>Does anyone see what I am doing wrong?</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#spinning-circle { animation-name: spinning-circle; animation-duration: 10s; animation-iteration-count: infinite; width: 40px; height: 40px; } @-webkit-keyframes spinning-circle { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="spinning-circle"&gt; &lt;img src="http://i.stack.imgur.com/WbNlQ.jpg"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
1
pandas, how to add columns to a multiindex column DataFrame
<p>This is my original DataFrame (with multiindex column):</p> <pre><code>In [72]:df Out[72]: a b x y x y 0 1.545293 -0.459270 0.899254 -1.010453 1 0.458760 0.275400 -0.190951 0.169195 2 -0.941817 1.109823 0.077953 -0.247074 3 1.790101 -1.643470 0.979625 -1.704657 4 -2.044814 -0.243726 -0.039724 0.600066 </code></pre> <p>and I have another DataFrame:</p> <pre><code>In [77]:df2 Out[77]: x y 0 -1.085869 -0.952949 1 0.601585 0.570050 2 0.328601 0.802610 3 -0.415952 -0.090088 4 0.757545 -0.736933 </code></pre> <p>how can I add <code>df2</code>'s columns to <code>df</code> to get a new DataFrame like this:</p> <pre><code>In [83]:df3 Out[83]: a b c x y x y x y 0 1.545293 -0.459270 0.899254 -1.010453 -1.085869 -0.952949 1 0.458760 0.275400 -0.190951 0.169195 0.601585 0.570050 2 -0.941817 1.109823 0.077953 -0.247074 0.328601 0.802610 3 1.790101 -1.643470 0.979625 -1.704657 -0.415952 -0.090088 4 -2.044814 -0.243726 -0.039724 0.600066 0.757545 -0.736933 </code></pre> <p>My current approach is to use a for loop:</p> <pre><code>for col in df2.columns: df['c', col] = df2[col] </code></pre> <p>is there any method to avoid the loop?</p>
1
Rails 5 Upgrade: No such middleware to insert after: ActionDispatch::ParamsParser (RuntimeError)
<p>I am upgrading an app from Rails 4.2 to Rails 5 beta1.1 in development. App worked well before upgrade. I have gone through the basic upgrade steps (updating Ruby, updating Rails, and related steps at:<a href="http://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html" rel="noreferrer">http://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html</a>). Gemfile has also been updated to latest Gems. </p> <p>When I run $ rails middleware or $ rails console or $ rails server I get the following error:</p> <pre><code>No such middleware to insert after: ActionDispatch::ParamsParser .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/actionpack/lib/action_dispatch/middleware/stack.rb:108:in `assert_index' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/actionpack/lib/action_dispatch/middleware/stack.rb:80:in `insert_after' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/configuration.rb:69:in `block in merge_into' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/configuration.rb:68:in `each' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/configuration.rb:68:in `merge_into' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/engine.rb:507:in `block in app' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/engine.rb:504:in `synchronize' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/engine.rb:504:in `app' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/application/finisher.rb:34:in `block in &lt;module:Finisher&gt;' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/initializable.rb:30:in `instance_exec' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/initializable.rb:30:in `run' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/initializable.rb:55:in `block in run_initializers' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/initializable.rb:54:in `run_initializers' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/application.rb:350:in `initialize!' .../config/environment.rb:5:in `&lt;top (required)&gt;' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/activesupport/lib/active_support/dependencies.rb:302:in `require' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/activesupport/lib/active_support/dependencies.rb:302:in `block in require' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/activesupport/lib/active_support/dependencies.rb:268:in `load_dependency' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/activesupport/lib/active_support/dependencies.rb:302:in `require' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/application.rb:326:in `require_environment!' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/application.rb:446:in `block in run_tasks_blocks' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/commands/rake_proxy.rb:13:in `block in run_rake_task' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/commands/rake_proxy.rb:10:in `run_rake_task' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/commands/commands_tasks.rb:51:in `run_command!' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/command.rb:20:in `run' .../.rvm/gems/ruby-2.3.0/bundler/gems/rails-dbf67b3a6f54/railties/lib/rails/commands.rb:19:in `&lt;top (required)&gt;' bin/rails:4:in `require' bin/rails:4:in `&lt;main&gt;' </code></pre> <p>This is related to fact that ActionDispatch::ParamsParser has been removed from Rails 5 beta middleware (<a href="https://github.com/rails/rails/commit/38d2bf5fd1f3e014f2397898d371c339baa627b1" rel="noreferrer">https://github.com/rails/rails/commit/38d2bf5fd1f3e014f2397898d371c339baa627b1</a>). But, in someway my app still seems to be looking for it.</p> <p>I have tried various things with ActionDispatch::ParamsParser in config/application.rb, such as deleting it, and, when that didn't work, I also tried adding it. Same error. Any way to get past this error?</p>
1
Integrating Sails Js with Angular 2
<p>I'm trying to integrate Angular 2 in a Sails Js application. I'm new to both. I have been following <a href="https://angular.io/docs/ts/latest/quickstart.html" rel="nofollow noreferrer">this</a> official tutorial here. It works fine in standalone mode with a static http server but when i try to integrate into sails app i get following problems:</p> <p>1 - How do i refer to angular2 js inside the local node_modules folder. Everytime i do, sails interprets it as a route and gives me a 404 for my scripts. For instance:</p> <p><code>&lt;script src="node_modules/angular2/dist/angular2.min.js"&gt;&lt;/script&gt;</code></p> <p>I was able to overcome above issue using cdnjs links for now but i would like to know a better/proper solution. </p> <p>2 - I added the <code>tsc</code> and <code>tsc -w</code> scripts to my package.json, but even with <code>sails lift --verbose</code> i do not get any output or error. Here is how I added the script to json file:</p> <pre><code>"scripts": { "tsc": "tsc", "tsc:w": "tsc -w", "debug": "node debug app.js", "start": "node app.js" } </code></pre> <p>In the end i had to install typescript with -g and compile manually. That worked, but again, it's expected to work with the scripts. It would be great to know what I'm missing.</p> <p>3 - After jumping through hoops to get rid of the above errors, when i lift the server again, it gives me more 404 error which seem to be coming from <code>system.src.js</code> and that I am unable to figure out. Please see the console screengrab below.</p> <p><a href="https://i.stack.imgur.com/Tf6Pn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tf6Pn.png" alt="enter image description here"></a></p> <p>I think I might be making a mistake setting up the angular application directories within sails. Just to make sure we cover everything, here is the directory structure I'm using. The sails app does not have anything in it yet. Which is why the below paths are just for angular related artifacts and assets.</p> <p>Within the assets folder:</p> <p>app</p> <p>│   ├── app.component.ts</p> <p>│   └── main.ts</p> <p>Of course the <code>.ts</code> files get compiled to js. </p> <p>In the sails views folder I have layout.ejs which has following contents:</p> <pre><code> . . . &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.34.2/es6-shim.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.17/system-polyfills.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.1/angular2-polyfills.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.17/system.src.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.7/rx.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.1/angular2.dev.js"&gt;&lt;/script&gt; &lt;script&gt; System.config({ packages: { app: { format: 'register', defaultExtension: 'js' } } }); System.import('/app/main') .then(null, console.error.bind(console)); &lt;/script&gt; . . . &lt;my-app&gt;Loading...&lt;/my-app&gt; </code></pre> <p>In addition to above files, I have also added the tsconfig in the sails root folder. </p> <p>I have followed the code and directory structure guidelines from the <a href="https://angular.io/docs/ts/latest/quickstart.html#!#final-structure" rel="nofollow noreferrer">official</a> quickstart tutorial. </p>
1
Why does my custom Ansible module fail?
<p>I am learning ansible so I wrote the most simple playbook and module I could think of, and it failed. </p> <p>My playbook</p> <pre><code>--- - hosts: demo tasks: - name: install demo action: install </code></pre> <p>My module</p> <pre><code>echo "changed=True msg=OK" </code></pre> <p>The following seems fine : </p> <ul> <li>bash script mode is 755</li> <li>playbook is linked to module correctly</li> </ul> <p>This is the output: </p> <pre><code>FAILED! =&gt; {"changed": false, "failed": true, "module_stderr": "", "module_stdout": "changed=True msg=OK\r\n", "msg": "MODULE FAILURE", "parsed": false} </code></pre> <p>What am I doing wrong? How can I make this work?</p>
1
How to change the jar filename when upload to artifactory via gradle
<p>I am using gradle in order to upload jar to artifactory. I managed to do it however I am trying to change the jar filename but it doesnt really let me.</p> <p>I am using shadowJar to package. this is how I do it:</p> <pre><code>apply plugin: 'java' apply plugin: 'maven' apply plugin: 'idea' apply plugin: 'maven-publish' apply plugin: 'com.github.johnrengelman.shadow' shadowJar { classifier = '' baseName = 'com.mycompany.app-all' manifest { attributes 'Main-Class': 'com.mycompany.app.main.starter' } } publishing { publications { mavenJava(MavenPublication) { from components.shadow groupId 'com.mycompany' artifactId "app" version "${build_version}" } } } </code></pre> <p>Now if build_version=2.1 than the dirs on artifactory will look like this:</p> <p><a href="http://repo.address:8081/artifactory/libs-release-local/com/mycompany/app/2.1/" rel="nofollow">http://repo.address:8081/artifactory/libs-release-local/com/mycompany/app/2.1/</a><strong>app-2.1.jar</strong></p> <p>I would like to keep the folder structure but change the jar filename(as defined in shadowJar)</p> <p>and to have it this way:</p> <p><a href="http://repo.address:8081/artifactory/libs-release-local/com/mycompany/app/2.1/" rel="nofollow">http://repo.address:8081/artifactory/libs-release-local/com/mycompany/app/2.1/</a><strong>com.mycompany.app-all.jar</strong></p> <p>any idea?</p>
1
ISO week number in VBScript or VBA
<p>How can I get the <a href="http://wikipedia.org/wiki/ISO_week_date" rel="nofollow">ISO week number</a> of some date in VBScript or VBA?</p>
1
Send Data from Server to Client Python 2.7
<p>I am trying to write a server that reads a .pdf file and sends the data to a client server.</p> <p>Here is a snip of my server program.</p> <pre><code>while True: # infinite loop to connect to a client client, address = server.accept() data = copyfile(path) data = str(data) client.send(data.encode('utf-8')) client.close() </code></pre> <p>Here is a clip of my client source code:</p> <pre><code>client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # assume my host and ports are correct client.connect((host, port)) data = client.recv(1024) s = data.decode('utf-8') print s client.close() </code></pre> <p>Here is the error I am gettting:</p> <p>client.send(message.encode('utf-8'))</p> <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 10: ordinal not in range(128)</p>
1
Can hibernate scan packages to create SessionFactory automatically?
<p>Can I configure Hibernate to scan packages automatically to create a <code>SessionFactory</code> from <code>@Entity</code> annotated beans ? </p> <p>Currently I am using </p> <pre><code>Configuration config = new Configuration() ; config.addAnnotatedClass(MyEntity.class); </code></pre> <p>I do not want to use <code>hibernate.cfg.xml</code> to configure mappings. </p> <p>Please note I want to achieve this in a plain Java project without using any Spring or such frameworks. </p> <p>Similar question have been answered using Spring before but I want to achieve it without using Spring or other frameworks. I am open to some simple library that does this. </p>
1
GreenRobot's eventbus can't see annotation, "no public methods"
<p>So, I found out about Green Robots' eventbus module. Followed the instructions on this page to try to get it working: <a href="http://greenrobot.org/eventbus/documentation/how-to-get-started/" rel="noreferrer">http://greenrobot.org/eventbus/documentation/how-to-get-started/</a></p> <p>Seems simple enough. </p> <p>I put in the appropriate code, but when run on device I get a crash: </p> <pre><code>org.greenrobot.eventbus.EventBusException: Subscriber class com.crowdlab.activities.LoadingActivity and its super classes have no public methods with the @Subscribe annotation. </code></pre> <p>The first few lines of my class look like this:</p> <pre><code>public class LoadingActivity extends BaseActivity implements AlertDialogButtonListener { AlertDialog mDialog = null; AlertDialog mPushDialog = null; @Subscribe public void onMessageEvent(MessageEvent event){ Toast.makeText(this, "From Loading "+event.message, Toast.LENGTH_SHORT).show(); } @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } . . . </code></pre> <p>It /seems/ the annotation is there. The compile happens without so much as a warning. I'm using version 3.0.0 as specified in the gradle file...</p> <p>So what could be wrong? (RTFM gratefully accepted, just tell where the FM with a relevant article is.)</p> <p>Thanks!</p> <p>-Ken</p>
1
Switch to a remote branch getting detached head
<p>Here is a list of all my branches:</p> <pre><code>$ git branch -a * temp remotes/heroku/master remotes/origin/dev remotes/origin/master </code></pre> <p>When I type <code>git checkout remotes/origin/master</code> to switch to my origin <code>master</code> branch, Git switches to a detached HEAD state. Why?</p>
1
Make tooltip content stay
<p>How do I make the information inside the tooltip stay still. For example, after the tooltip appears, how can I browse over with my mouse to click on a link inside. The tooltip disappears when no longer hovering over the word or image. I want it to stay in one place. </p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>a.tooltip {outline:none; } a.tooltip strong {line-height:30px;} a.tooltip:hover {text-decoration:none;} a.tooltip span { z-index:10;display:none; padding:14px 20px; margin-top:-30px; margin-left:28px; width:300px; line-height:16px; } a.tooltip:hover span{ display:inline; position:absolute; color:#111; border:1px solid #DCA; background:#fffAF0;} .callout {z-index:20;position:absolute;top:30px;border:0;left:-12px;} /*CSS3 extras*/ a.tooltip span { border-radius:4px; box-shadow: 5px 5px 8px #CCC; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!--First tooltip--&gt; &lt;a href="#" class="tooltip"&gt; Tooltip &lt;span&gt; &lt;img class="callout" src="cssttp/callout.gif" /&gt; &lt;strong&gt;Most Light-weight Tooltip&lt;/strong&gt;&lt;br /&gt; This is the easy-to-use Tooltip driven purely by CSS. &lt;/span&gt; &lt;/a&gt; &lt;!--Second tooltip--&gt; &lt;a href="#" class="tooltip"&gt; &lt;img src="/tooltip/css-tooltip-image.gif" /&gt; &lt;span&gt; &lt;img class="callout" src="cssttp/callout.gif" /&gt; &lt;img src="/tooltip/src/tooltips-cd2.jpg" style="float:right;" /&gt; &lt;strong&gt;CSS only Tooltip&lt;/strong&gt;&lt;br /&gt; Pure CSS popup tooltips with clean semantic XHTML. &lt;/span&gt; &lt;/a&gt;</code></pre> </div> </div> </p>
1
Doctrine DQL join tables
<p>for my API development I use apigility and <strong>doctrine</strong>. I'm currently programming an endpoint that users can like a post. Every post has an author. I have 2 tables with the following columns and example data inside:</p> <p><strong>Action</strong></p> <pre><code>id post_id user_id createdAt 1 10 1 0000-00-00 00:00:00 2 12 2 0000-00-00 00:00:00 3 13 3 0000-00-00 00:00:00 </code></pre> <p><em>(post_id = foreign key to post table)</em> <em>(user_id = source user which likes a post)</em></p> <p><strong>Post</strong></p> <pre><code>id user_id createdAt 10 62 0000-00-00 00:00:00 12 4 0000-00-00 00:00:00 13 4 0000-00-00 00:00:00 </code></pre> <p><em>(user_id = foreign key to user table)</em></p> <p><strong>What I need</strong></p> <p>I need the total_likes which an author (user_id) has. This can be queried over the Action table by joining the post table. I have already tried to create a DQL query for this:</p> <pre><code>// Get total likes an autor has received $queryBuilder-&gt;select('count(p)') -&gt;from('Db\Entity\Action', 'a') -&gt;leftJoin('p.post', 'p') -&gt;where('p.user = :user') -&gt;setParameter('user', $targetUser); $totalLikes = $queryBuilder-&gt;getQuery()-&gt;getSingleScalarResult(); </code></pre> <p>Which this query, I get the wrong number of total_likes:</p> <pre><code>{ "total_likes": "2" } </code></pre> <p>How do I have to correct this query that I get the correct count of likes of a user? With the example table data, the total_likes of user_id=62 should give me this back:</p> <pre><code>{ "total_likes": "1" } </code></pre>
1
Pandas df sum rows based on index column
<p>I have a Pandas df (See below), I want to sum the values based on the index column. My index column contains string values. See the example below, here I am trying to add Moving, Playing and Using Phone together as "Active Time" and sum their corresponding values, while keep the other index values as these are already are. Any suggestions, that how can I work with this type of scenario? </p> <pre><code>**Activity AverageTime** Moving 0.000804367 Playing 0.001191772 Stationary 0.320701558 Using Phone 0.594305473 Unknown 0.060697612 Idle 0.022299218 </code></pre>
1
Accordion inside Tabs Bootstrap
<p>So I have a tablist on my page, and inside of each tab, I need an accordion as I have a lot of information being outputted to the user. My issue is that when the page loads, the accordions aren't folded up. They're all expanded even though <code>aria-expanded</code> is set to <code>false</code>. When I click on the header to then close the section, it shows the animation it would play as if it was expanding. Click it again, and it closes. here's my test code:</p> <pre><code>&lt;ul class="nav nav-pills" role="tablist"&gt; &lt;li role="presentation" class="active"&gt;&lt;a href="#open" aria-controls="open" role="tab" data-toggle="tab"&gt;Open Tickets&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;br&gt; &lt;!--The Tab Contents--&gt; &lt;div class="tab-content"&gt; &lt;div role="tabpanel" class="tab-pane fade in active" id="open"&gt; &lt;div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"&gt; &lt;div class="panel panel-info"&gt; &lt;div class="panel-heading" role="tab" id="headingOne"&gt; &lt;span&gt; &lt;a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne"&gt;Info One&lt;/a&gt; &lt;/span&gt; &lt;/div&gt; &lt;div id="collapseOne" class="panel-collapse" role="tabpanel" aria-labelledby="headingOne"&gt; &lt;div class="panel-body"&gt; Content Here &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="panel panel-info"&gt; &lt;div class="panel-heading" role="tab" id="headingTwo"&gt; &lt;span&gt; &lt;a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"&gt;Info One&lt;/a&gt; &lt;/span&gt; &lt;/div&gt; &lt;div id="collapseTwo" class="panel-collapse" role="tabpanel" aria-labelledby="headingTwo"&gt; &lt;div class="panel-body"&gt; Content Here &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="panel panel-info"&gt; &lt;div class="panel-heading" role="tab" id="headingThree"&gt; &lt;span&gt; &lt;a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree"&gt;Info One&lt;/a&gt; &lt;/span&gt; &lt;/div&gt; &lt;div id="collapseThree" class="panel-collapse" role="tabpanel" aria-labelledby="headingThree"&gt; &lt;div class="panel-body"&gt; Content Here &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>So is it because it's an accordion nested within a tab Group, or is it something that I'm over looking.</p>
1
android: cannot resolve method sendMessage(androd.os.message)
<p>I am stuck when learning handlers. The following is my simple code:</p> <pre><code>public class MainActivity extends AppCompatActivity { Thread thread; public Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main); thread = new Thread(new MyThread()); thread.start(); handler=new Handler() { @Override public void close() { } @Override public void flush() { } @Override public void publish(LogRecord record) { } }; } class MyThread implements Runnable{ @Override public void run(){ Message message=Message.obtain(); for(int i=0;i&lt;10000;i++){ handler.sendMessage(message); } } } } </code></pre> <p>In the MyThread class, i was trying to type sendMessage after handler. but android studio does not show any such sendMessage option. still i typed it, then it shows in red. and says cannot resolve method. </p>
1
How to import .pl file on SWI PROLOG?
<p>I just downloaded the SWI PROLOG for mac, and for some reason there's no 'import' button in the menu bar. So, I was wondering if there's any way I could import the .pl file using code maybe, and how I can include the path of the .pl file in my code.</p> <p>Thank you in advance :)</p>
1
Angular 2 Inline Style with ngFor
<p>I am trying to have a dynamic height for a div tag like so:</p> <pre><code>&lt;div class="summary" *ngFor="let chart of chartCounts"&gt; &lt;div class="bar" [style.height]="{{chart.CSSBarHeight}}"&gt; &lt;div class="countLabel"&gt;{{chart.Count}}&lt;/div&gt; &lt;/div&gt; &lt;div class="barlabel"&gt;{{chart.DaysLeft}}&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I'm not having any luck getting anything to work for doing inline style this way. It throws an error on the console that says:</p> <pre><code>Potentially unhandled rejection [3] Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at column 0 in [{{chart.CSSBarHeight}}] in function AppComponent(http) {@150:61 ("ary" *ngFor="let chart of chartCounts"&gt; &lt;div class="bar" [ERROR -&gt;][style.height]="{{chart.CSSBarHeight}}"&gt; &lt;div class="): function AppComponent(http) {@150:61 </code></pre> <p>Anyone have an idea on what I am doing wrong and how to get the style to work in this scenario? The rest of what I am doing here is working great. I'd like to be able to set it as a percentage so after it finishes rendering it comes out to something like:</p> <pre><code>&lt;div class="bar" style="height:80%"&gt; </code></pre>
1
How to add TYPE to Object.assign using Typescript
<p>I have an array of typed objects - all objects are of type: TodoModel. When I filter them, to adjust the content on the UI, you have to create a new array and adjust the properties on the item that was changed for the filter to refilter in angular2. When I create the new array and add the changed object, the object is of no type, while the other 2 objects in the array are still of type: TodoModel. I can't figure out how to assign a type to the new object :( Thanks in advance for any help!</p> <p>Here is the code for the logic &amp; below I have a screen shot of the before and after for the mutated arrays:</p> <pre><code>case 'TOGGLE_TODO': const todo: ITodoModel = payload; const i = state.indexOf(todo); const status = todo.status == "started" ? "completed" : "started"; const toggledTodo:ITodoModel = Object.assign(&lt;ITodoModel&gt;{}, todo, {status}); state = [ //... = spread operator - bascially loops through the array ...state.slice(0,i), // check items before toggledTodo, // clicked item ...state.slice(i + 1) // check items after ]; console.log('toggle state'); console.log(state); return state; </code></pre> <p><img src="https://i.stack.imgur.com/clxER.png" alt="Picture of a Before and after array mutation"></p>
1
Using JavaScript/JQuery, can you sort a HTML table column (ascending/descending) based on the column’s <td> class names?
<p>I'm currently working on a web page to manage course data, which dynamically produces a HTML table via a combination of <em>XSLT (1.0)</em> and <em>JavaScript</em> (<a href="http://www.w3schools.com/xsl/xsl_client.asp" rel="nofollow noreferrer">on the client method</a>). The HTML table is then populated with live data supplied from an XML file.</p> <p><strong>The Table:</strong></p> <p>The HTML table contains four main columns (<em>Course</em>/<em>Location(s)</em>/<em>Credits</em>/<em>Date(s)</em>) and each row’s data relates to a <code>&lt;Courses&gt;</code> element in the XML File.</p> <p><a href="https://i.stack.imgur.com/PCdn5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PCdn5.jpg" alt="HTML Table Output"></a></p> <p>When the <strong>Date(s)</strong> column's <code>&lt;td&gt;</code> tags are constructed via XSLT (1.0), the XSLT code also makes a look-up in the XML stucture and works out the course's first available <code>&lt;UnitStartDate&gt;</code>, for example <em>Mechanical and Electrical Engineering</em> would be <em>3 Feb 2016</em>, as you can see from the figure above. </p> <p>This <code>&lt;UnitStartDate&gt;</code> is then interpreted into a YYYYMMDD format and assigned as a <strong>class name</strong> to the Date(s) <code>&lt;td&gt;</code> at run-time, so in our previous example, the class name would be <em>20160203</em>, translating to <code>&lt;td class="date 20160203"&gt;&lt;br/&gt;&lt;p&gt;3 Feb 2016&lt;/p&gt;&lt;p&gt;18 Feb 2016&lt;/p&gt;&lt;p&gt;24 Feb 2016&lt;/p&gt;&lt;br/&gt;&lt;/td&gt;</code> in our HTML markup.</p> <p>If no <code>&lt;UnitStartDate&gt;</code> exists, as is the case with the '<em>Leisure and Tourism</em>' course (Date TBC), <em>99999999</em> is assigned as the class name.</p> <p><strong>HTML:</strong></p> <pre><code>&lt;table class="upcomingcourses" border="1" style="width: 701px"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th width="45%"&gt;Course&lt;/th&gt; &lt;th width="15%"&gt;Location(s)&lt;/th&gt; &lt;th width="5%"&gt;Credits&lt;/th&gt; &lt;th width="35%"&gt;&lt;a href="javascript:sortTable()"&gt;Date(s)&lt;/a&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td class="centerTD"&gt; &lt;a href="/courses/business-studies.html"&gt;Business Studies&lt;/a&gt; &lt;/td&gt; &lt;td class="locations"&gt; &lt;br/&gt; &lt;p&gt;B7&lt;/p&gt; &lt;p&gt;G6&lt;/p&gt; &lt;br/&gt; &lt;/td&gt; &lt;td class="centerTD"&gt; &lt;p&gt;30&lt;/p&gt; &lt;/td&gt; &lt;td class="date 20160204"&gt; &lt;p&gt;4 Feb 2016&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="centerTD"&gt; &lt;a href="/courses/management-studies.html"&gt;Management Studies&lt;/a&gt; &lt;/td&gt; &lt;td class="locations"&gt; &lt;br/&gt; &lt;p&gt;D8&lt;/p&gt; &lt;p&gt;F2&lt;/p&gt; &lt;br/&gt; &lt;/td&gt; &lt;td class="centerTD"&gt; &lt;p&gt;15&lt;/p&gt; &lt;/td&gt; &lt;td class="date 20160101"&gt; &lt;br/&gt; &lt;p&gt;e-Learning: Jan-Feb 2016&lt;/p&gt; &lt;p&gt;8-12 Feb 2016&lt;/p&gt; &lt;p&gt;Presentation: 9 Mar 2016&lt;/p&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="centerTD"&gt; &lt;a href="/courses/leisure-tourism.html"&gt;Leisure and Tourism&lt;/a&gt; &lt;/td&gt; &lt;td class="locations"&gt; &lt;br/&gt; &lt;p&gt;C5&lt;/p&gt; &lt;br/&gt; &lt;/td&gt; &lt;td class="centerTD"&gt; &lt;p&gt;15&lt;/p&gt; &lt;p&gt;20&lt;/p&gt; &lt;/td&gt; &lt;td class="date 99999999"&gt; &lt;p&gt;TBC&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="centerTD"&gt; &lt;a href="/courses/mechanical-electrical-eng.html"&gt;Mechanical and Electrical Engineering&lt;/a&gt; &lt;/td&gt; &lt;td class="locations"&gt; &lt;br/&gt; &lt;p&gt;A3 Workshop&lt;/p&gt; &lt;br/&gt; &lt;/td&gt; &lt;td class="centerTD"&gt; &lt;p&gt;15&lt;/p&gt; &lt;/td&gt; &lt;td class="date 20160203"&gt; &lt;br/&gt; &lt;p&gt;3 Feb 2016&lt;/p&gt; &lt;p&gt;18 Feb 2016&lt;/p&gt; &lt;p&gt;24 Feb 2016&lt;/p&gt; &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><strong>The Question:</strong></p> <p>So, with all that background information out the way, what would I actually like to achieve? Well, I eventually want to be able to sort each of the four main table columns (ascending/descending) via JavaScript or JQuery (I'm open to both options). </p> <p>The first three columns from left-to-right (<em>Course</em>/<em>Location(s)</em> and <em>Credits</em>) are straightforward enough, but for the fourth column, <em>Date(s)</em>, I really want to be able to <strong>sort the column in order (largest number to lowest and vice-versa) based on my 'date' class name (YYYYMMDD)</strong>. This sorting process would be triggered by clicking the link in the Date(s) <code>&lt;th&gt;</code> (<code>sortTable()</code> function).</p> <p>As you can see from the <em>Mechanical and Electrical Engineering</em> cell, its not just straightforward dates that are always included (details on e-Learning etc.).</p> <p>Could this <code>ClassName</code> sort approach be achieved using JavaScript?</p> <p>With a sort of the earliest dates (Class Names) to the latest, I would expect to see the following:</p> <p><a href="https://i.stack.imgur.com/gkK9G.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gkK9G.jpg" alt="enter image description here"></a></p> <p><strong>Earliest:</strong> <code>&lt;td class="date 20160101"&gt;&lt;br/&gt;&lt;p&gt;e-Learning: Jan-Feb 2016&lt;/p&gt;&lt;p&gt;8-12 Feb 2016&lt;/p&gt;&lt;p&gt;Presentation: 9 Mar 2016&lt;/p&gt;&lt;br/&gt;&lt;/td&gt;</code></p> <p><code>&lt;td class="date 20160203"&gt;&lt;br/&gt;&lt;p&gt;3 Feb 2016&lt;/p&gt;&lt;p&gt;18 Feb 2016&lt;/p&gt;&lt;p&gt;24 Feb 2016&lt;/p&gt;&lt;br/&gt;&lt;/td&gt;</code></p> <p><code>&lt;td class="date 20160204"&gt;&lt;p&gt;4 Feb 2016&lt;/p&gt;&lt;/td&gt;</code></p> <p><strong>Latest:</strong> <code>&lt;td class="date 99999999"&gt;&lt;p&gt;TBC&lt;/p&gt;&lt;/td&gt;</code></p> <p><hr> Thanks in advance everybody.</p>
1
Laravel 5.1 detach with where
<p>I want detach without some records </p> <p>my role_user table is id | role_id | user_id</p> <pre><code>&lt;?php $user-&gt;roles()-&gt;detach(); ?&gt; </code></pre> <p>I don't want detach all records some records need (I mean find solution to where clause inside detach() ). How can I do this? Thank you. </p>
1
How to check if a woocommerce product has any category assigned to it?
<p>I am creating a custom plugin where related products are fetched as per the tags assigned to a product. I am facing an issue. When i run a loop it gives me a warning message. What i want to check is that if the particular product has any category assigned to it. How can i check if any category has been assigned to a woocommerce product. Please help me. Thanks in advance. </p> <p><strong>my custom code</strong> </p> <pre><code>while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); global $product; global $post; $feat_image = wp_get_attachment_url( get_post_thumbnail_id($loop-&gt;post-&gt;ID) ); $terms200 = get_the_terms( $loop-&gt;post-&gt;ID, 'product_cat' ); // if(!empty($terms200) || $terms200!='' || $terms200!=null){ if (get_category($loop-&gt;post-&gt;ID)-&gt;category_count != 0){ $content.='&lt;li class="product-small grid1 grid-normal"&gt;'; $content.='&lt;div class="inner-wrap"&gt;'; $content.='&lt;a href="'.get_the_permalink($loop-&gt;post-&gt;ID).'"&gt;'; $content.='&lt;div class="product-image hover_fade_in_back"&gt;'; $content.='&lt;div class="front-image"&gt;'; $content.='&lt;img src="'.$feat_image.'" class="attachment-shop_catalog wp-post-image" style="width:247px !important;height:300px !important;" /&gt;'; $content.='&lt;/div&gt;'; $content.='&lt;/div&gt;'; $content.='&lt;/a&gt;'; $content .='&lt;div class="info style-grid1"&gt;'; $content .='&lt;div class="text-center"&gt;'; $count=1; foreach ( @$terms200 as $term ) { if($count==1){ $content.='&lt;h5 class="category"&gt;&lt;a href="'.get_site_url().'/?product_cat='.$term-&gt;slug.'" rel="tag"&gt;'.$term-&gt;name.'&lt;/a&gt;&lt;/h5&gt;'; $content.='&lt;div class="tx-div small"&gt;&lt;/div&gt;'; } $count++; } $content .='&lt;a href="'.get_the_permalink($loop-&gt;post-&gt;ID).'"&gt;&lt;p class="name"&gt;'.$loop-&gt;post-&gt;post_title.'&lt;/p&gt;&lt;/a&gt;'; if ( $price_html = $product-&gt;get_price_html() ) : $content .='&lt;span class="price"&gt;&lt;span class="amount"&gt;'.$price_html.'&lt;/span&gt;&lt;/span&gt;'; endif; $content.='&lt;div class="mycustomcartbuttonbox"&gt;[add_to_cart id="'.$loop-&gt;post-&gt;ID.'"]&lt;/div&gt;'; $content .='&lt;/div&gt;'; $content .='&lt;/div&gt;'; $content.='&lt;/div&gt;'; $content.='&lt;/li&gt;'; echo do_shortcode($content); } endwhile; </code></pre>
1
Angular/Ionic app shows blank page and no error in the console
<p>I am trying to get my simple app working. I wanted to separate controller files, but I always get blank page and no errors in the browser console. App project structue:</p> <pre><code>www - app |-controllers |--controllers.js |--mainController.js |--newListController.js |-services |--listService.js |-app.js |-index.html -templates |--main.html |--new-list.html </code></pre> <p>My <strong>www/index.html</strong>:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"&gt; &lt;title&gt;&lt;/title&gt; &lt;link href="lib/ionic/css/ionic.css" rel="stylesheet"&gt; &lt;link href="css/style.css" rel="stylesheet"&gt; &lt;!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above &lt;link href="css/ionic.app.css" rel="stylesheet"&gt; --&gt; &lt;!-- ionic/angularjs js --&gt; &lt;script src="lib/ionic/js/ionic.bundle.js"&gt;&lt;/script&gt; &lt;!-- cordova script (this will be a 404 during development) --&gt; &lt;script src="cordova.js"&gt;&lt;/script&gt; &lt;!-- your app's js --&gt; &lt;script src="app/app.js"&gt;&lt;/script&gt; &lt;script src="app/controllers/controllers.js"&gt;&lt;/script&gt; &lt;script src="app/controllers/newListController.js"&gt;&lt;/script&gt; &lt;script src="app/services/listService.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-app="testapp"&gt; &lt;!-- The nav bar that will be updated as we navigate between views. --&gt; &lt;ion-nav-bar class="bar-dark"&gt; &lt;ion-nav-back-button&gt; &lt;/ion-nav-back-button&gt; &lt;/ion-nav-bar&gt; &lt;ion-nav-view&gt;&lt;/ion-nav-view&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>www/app/app.js</strong>:</p> <pre><code>angular.module('testapp', ['ionic', 'testapp.controllers', 'testapp.services']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { if (window.cordova &amp;&amp; window.cordova.plugins &amp;&amp; window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); }) .config(function($stateProvider, $urlRouterProvider) { $stateProvider // setup an abstract state for the tabs directive .state('tab', { url: '/tab', abstract: true, templateUrl: 'templates/main.html' }) // Each tab has its own nav history stack: .state('tab.new_list', { url: '/new_list', views: { 'tab-dash': { templateUrl: 'templates/new-list.html', controller: 'NewListCtrl' } } }); // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/new_list'); }); </code></pre> <p><strong>www/app/controllers.js</strong>:</p> <pre><code>angular.module('testapp.controllers', []); </code></pre> <p><strong>www/app/newListController.js</strong>:</p> <pre><code>angular.module('testapp.controllers') .controller('NewListCtrl', function($scope) { alert('aa'); // **its not being executed!!!** }); </code></pre> <p><strong>www/templates/main.html</strong>:</p> <pre><code>&lt;!-- Create tabs with an icon and label, using the tabs-positive style. Each tab's child &lt;ion-nav-view&gt; directive will have its own navigation history that also transitions its views in and out. --&gt; &lt;ion-tabs class="tabs-icon-top tabs-color-active-positive"&gt; &lt;!-- Dashboard Tab --&gt; &lt;ion-tab title="Status" icon-off="ion-ios-pulse" icon-on="ion-ios-pulse-strong" href="#/tab/dash"&gt; &lt;ion-nav-view name="tab-dash"&gt;&lt;/ion-nav-view&gt; &lt;/ion-tab&gt; &lt;!-- Chats Tab --&gt; &lt;ion-tab title="Chats" icon-off="ion-ios-chatboxes-outline" icon-on="ion-ios-chatboxes" href="#/tab/chats"&gt; &lt;ion-nav-view name="tab-chats"&gt;&lt;/ion-nav-view&gt; &lt;/ion-tab&gt; &lt;!-- Account Tab --&gt; &lt;ion-tab title="Account" icon-off="ion-ios-gear-outline" icon-on="ion-ios-gear" href="#/tab/account"&gt; &lt;ion-nav-view name="tab-account"&gt;&lt;/ion-nav-view&gt; &lt;/ion-tab&gt; &lt;/ion-tabs&gt; </code></pre> <p><strong>www/templates/new-list.html</strong>:</p> <pre><code>&lt;ion-view view-title="Dashboard"&gt; &lt;ion-content class="padding"&gt; &lt;h2&gt;Welcome to Ionic&lt;/h2&gt; &lt;p&gt; This is the Ionic starter for tabs-based apps. For other starters and ready-made templates, check out the &lt;a href="http://market.ionic.io/starters" target="_blank"&gt;Ionic Market&lt;/a&gt;. &lt;/p&gt; &lt;p&gt; To edit the content of each tab, edit the corresponding template file in &lt;code&gt;www/templates/&lt;/code&gt;. This template is &lt;code&gt;www/templates/tab-dash.html&lt;/code&gt; &lt;/p&gt; &lt;p&gt; If you need help with your app, join the Ionic Community on the &lt;a href="http://forum.ionicframework.com" target="_blank"&gt;Ionic Forum&lt;/a&gt;. Make sure to &lt;a href="http://twitter.com/ionicframework" target="_blank"&gt;follow us&lt;/a&gt; on Twitter to get important updates and announcements for Ionic developers. &lt;/p&gt; &lt;p&gt; For help sending push notifications, join the &lt;a href="https://apps.ionic.io/signup" target="_blank"&gt;Ionic Platform&lt;/a&gt; and check out &lt;a href="http://docs.ionic.io/docs/push-overview" target="_blank"&gt;Ionic Push&lt;/a&gt;. We also have other services available. &lt;/p&gt; &lt;/ion-content&gt; &lt;/ion-view&gt; </code></pre> <p>Any idea what should I fix there? Console is not displaying anything.</p>
1
One channel - one queue in RabbitMQ?
<p>So far for a single queue in RabbitMQ I have used a single channel But now I have multiple queues created dynamically, so do I have to create a <strong>new</strong> channel for <strong>each</strong> queue or one channel can be to receive/send messages from/to different queues?</p> <pre><code> # consuming for ch in items: channel1 = rconn.channel() channel1.queue_declare(queue=itm) channel1.basic_consume(some_callback, queue=itm, no_ack=True) channel1.start_consuming() # publishing for ch in items: # .... channel1.basic_publish(exchange="", routing_key=itm, body="fdsfds") </code></pre>
1
How to change the date format of the correlated date?
<p>I'm capturing the date in one request so that I can send the captured date as the parameter to next request. But in the next request the date should be sent with different format. In order to send the date I need to modify the date format how can do that?</p>
1
Error Java Jersey: NotAuthorizedException: HTTP 401 Unauthorized
<p>I'm trying to make a call to a XML file API, but I get this error.</p> <p>I easily can open the .xml file on the browser by using only the URL.</p> <p>Can anyone help me, please?</p> <pre><code>private ArrayList&lt;Weather&gt; weatherList = new ArrayList&lt;&gt;(); public String load(String city) { ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config); WebTarget target = client.target(getBaseURI()); return target.path("data/2.5/weather?q="+city+"&amp;mode=xml&amp;appid=[API_KEY]").request().accept(MediaType.TEXT_XML).get(String.class); } public URI getBaseURI() { return UriBuilder.fromUri("http://api.openweathermap.org").build(); } </code></pre> <p>PS: Well, I haven't used this:</p> <pre><code>HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password); client.register(feature); </code></pre> <p>Because the call doesn't need any privileges (no username and password).</p> <p>Thanks.</p>
1
redux reducer returned undefined handling
<p>My reducers like:</p> <pre><code>const initialState = [ { fname: null, lname: false, } ] export default function login(state = initialState, action) { switch (action.type) { case LOGIN: console.log("actions") console.log(action) console.log("reducers") return [{ fname: action.fname, lname: action.lname, }] default: return state } } </code></pre> <p>Here I am getting action object with <code>fname</code> and <code>lname</code> but this is giving me error saying .. <code>Uncaught Error: Reducer "login" returned undefined handling "LOGIN". To ignore an action, you must explicitly return the previous state.</code></p> <p>Why I am getting this error ?</p>
1
Delphi: Setting connection timeout for TIdHttpServer
<p>Using TIdHTTPServer (Indy 10.6), i want set a connection timeout for close slow or inactive client (client are common browser) and close all zombie connection after 60 seconds of inactivity. I have found Socket.ReadTimeout in TIdContext.Connection. Is this the right way? TIdHTTPServer already perform this (it seem have infinite timeout)?</p> <pre><code>WebServer := TIdHTTPServer.Create(nil); WebServer.SessionState := false; WebServer.KeepAlive := false; WebServer.OnCommandGet := CustomOnCommandGet; procedure CustomOnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo; begin AContext.Connection.Socket.ReadTimeout := 60000; AResponseInfo.ContentStream := TFileStream.Create('C:/file.zip', fmOpenRead or fmShareCompat); end; </code></pre>
1
Insufficient permission to view NetSuite Subsidiaries
<p>I am using SuiteTalk web services and trying to use <code>SubsidiarySearch</code> to retrieve all Subsidiary records:</p> <pre><code> SubsidiarySearchBasic srch = new SubsidiarySearchBasic(); srch.setIsInactive(new SearchBooleanField(false)); SearchResult res = stub.search(srch); </code></pre> <p>I login using a customized role based on NetSuite's standard "System Administrator" role, with various extra permissions added. In particular, this role has "Subsidiaries" permissions set to "Full". However, the above code returns the following status, using this Java code:</p> <pre><code>Type=ERROR Code=INSUFFICIENT_PERMISSION Detail=Permission Violation: The subsidiary restrictions on your role prevent you from seeing this record. </code></pre> <p>The above code succeeds when I use the standard "Administrator" role (internal id "3") but I would like to use a customized role. What permissions do I need for a successful result?</p>
1
How to set separate LaunchScreen storyboards for different targets in Xcode
<p>I have an Xcode project with multiple targets. Basically each target is a customized version of my app for different clients. I've tried customizing the Launch Screen File based on user defined fields in each target's build settings and then using that variable in the info.plist to determine which Launch Screen. I'd prefer to maintain one info.plist using user defined build settings if possible.</p>
1
Hiding code in jupiter in R
<p>I would like to try to produce reports (pdf and probably html) in jupyter using R kernel. However, I would like to hide code in two ways, depending on audience:</p> <ol> <li>all code cells</li> <li>some code cells</li> </ol> <p>When I have looked for this I found answers for python kernel. Is there a way to this in R (no python code)?</p>
1
Three.js usage with stencil buffer
<p>I can't get the following to draw the scene into the shape created as a stencil mask. Instead the code just seems to render the stencil itself as a black object.</p> <p><a href="http://signaturefloors.dev.flooradvisor.com.au/productapp/floor_align.php" rel="nofollow">http://signaturefloors.dev.flooradvisor.com.au/productapp/floor_align.php</a></p> <p>My render function is:</p> <pre><code>var gl = floor_align.renderer.domElement.getContext('webgl') || floor_align.renderer.domElement.getContext('experimental-webgl'); gl.clearStencil(0); gl.clear(gl.STENCIL_BUFFER_BIT); gl.enable(gl.STENCIL_TEST); gl.stencilFunc(gl.ALWAYS, 1, 1); gl.stencilOp(gl.KEEP, gl.REPLACE, gl.REPLACE); gl.colorMask(0, 0, 0, 0); // Floor Mask (Create a stencil that we render the next pass into) floor_align.renderer.render(floor_align.maskScene, floor_align.maskCamera); gl.colorMask(1, 1, 1, 1); gl.stencilFunc(gl.NOTEQUAL, 1, 1); gl.stencilOp(gl.KEEP, gl.REPLACE, gl.REPLACE); // Render a floor pass floor_align.renderer.render(floor_align.scene, floor_align.camera); gl.disable(gl.STENCIL_TEST); </code></pre> <p>The renderer has <code>autoClear = false</code>;</p>
1
How to config minified React+ReactDOM with Webpack
<p>After too many unsuccessful trials my question is: <strong>What is the proper way to setup Webpack</strong> so that:</p> <ol> <li>Use react.min.js + react-dom.min.js - not the npm installed sources</li> <li>Don't parse/com them again, just bundle with my own components.</li> <li>"React" and "ReactDOM" variables can be used from all .jsx files. </li> </ol> <p>The tutorials and guides I found didn't work - or maybe I did some errors. Usually I got error in browser developer tools about missing variable React.</p> <p>My aim is just to save parsing/bundling time. Now I parse React from scratch every time I bundle my app. And it takes tens of seconds on a slowish computer. In watch mode it is faster, but I find I'm doing unnecessary work.</p> <p>Any ideas with recent React versions?</p>
1
Color elements given an array of colors
<p>How do I assign this array of colors to a bunch of divs?</p> <pre><code>var colors = ['#2d335b', '#535b2d', '#494949', '#d7d7d7', '9ad4ce']; </code></pre> <p>I know I can do it by randomly selecting colors from my array like this:</p> <pre><code>var random_color = colors[Math.floor(Math.random() * colors.length)]; $("div").css('background-color', random_color); </code></pre> <p>But it's using a lot of the same colors in order and I need them spread out more. How can I assign them in order starting from the 1st color in the array to last and then back to first?</p>
1
How to display the elements of a returned list in Roxygen?
<p>I can do this easily with input parameters by having multiple lines of <code>@param</code> by doing as such:</p> <pre><code>#' @param var1 This is for x #' @param var2 This is for y #' @param var3 This is for Z </code></pre> <p>But how do you do that for the elements of a list you are returning. I want to include the names of each element and a description about them. Chaining together <code>@return</code> or <code>@param</code> does not have the same behavior. What is the appropriate tag?</p> <pre><code>#' @return A list with the following elements: #' @something element1 Contains x #' @something element2 Contains y #' @something element3 Contains z </code></pre> <p>The package <code>samr</code> has the exact markdown formatting I'm looking for:</p> <p><a href="https://i.stack.imgur.com/IzvII.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IzvII.png" alt="enter image description here"></a></p>
1
linux command to find files and replace with another file
<p>I'm looking for a linux command to search a folder directory and it's subfolders for a file by name and replace all of them with a copy of another file. Any idea? </p>
1
Hue: oozie parameters
<p>I want to pass 2 parameters to my Hiveql script in oozie, my script:</p> <pre><code>ALTER TABLE default.otarie_appsession ADD IF NOT EXISTS PARTITION ( insert_date=${dt},hr=${hr} ); </code></pre> <p>My Oozie workflow :</p> <p><a href="https://i.stack.imgur.com/VGWIo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VGWIo.png" alt="enter image description here"></a></p> <p>When i send the job it ask for parameter values, so i put:</p> <p><a href="https://i.stack.imgur.com/hHvoz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hHvoz.png" alt="enter image description here"></a></p> <p>And this is the error:</p> <pre><code>2016-02-05 18:41:55,460 WARN org.apache.oozie.action.hadoop.HiveActionExecutor: SERVER[DVS1VM65] USER[root] GROUP[-] TOKEN[] APP[My_Workflow] JOB[0000290-160122145737153-oozie-oozi-W] ACTION[0000290-160122145737153-oozie-oozi-W@hive-a586] Launcher ERROR, reason: Main class [org.apache.oozie.action.hadoop.HiveMain], exit code [40000] </code></pre> <p>This is the XML of the workflow:</p> <pre><code>&lt;workflow-app name="My_Workflow" xmlns="uri:oozie:workflow:0.5"&gt; &lt;start to="hive-a586"/&gt; &lt;kill name="Kill"&gt; &lt;message&gt;L&amp;#39;action a échoué, message d&amp;#39;erreur[${wf:errorMessage(wf:lastErrorNode())}]&lt;/message&gt; &lt;/kill&gt; &lt;action name="hive-a586"&gt; &lt;hive xmlns="uri:oozie:hive-action:0.2"&gt; &lt;job-tracker&gt;${jobTracker}&lt;/job-tracker&gt; &lt;name-node&gt;${nameNode}&lt;/name-node&gt; &lt;job-xml&gt;/user/oozie/some_scripts/hive-site.xml&lt;/job-xml&gt; &lt;script&gt;/user/oozie/some_scripts/addpart.hql&lt;/script&gt; &lt;param&gt;hr=&lt;/param&gt; &lt;param&gt;dt=&lt;/param&gt; &lt;/hive&gt; &lt;ok to="End"/&gt; &lt;error to="Kill"/&gt; &lt;/action&gt; &lt;end name="End"/&gt; &lt;/workflow-app&gt; </code></pre> <p>When i remove all parmeters and use hard coded value, the script works fine, so its clear that i have problem to pass parameters. And my final goal is to pass current date and hour.</p> <p>Thank you.</p>
1
How to truncate big table in postgresql having size greater than 5231MB?
<p>Already tried delete and truncate but it took ever long time. Also tried to find out any lock process is there on that table using the below query</p> <pre><code>SELECT bl.pid AS blocked_pid, a.usename AS blocked_user, kl.pid AS blocking_pid, ka.usename AS blocking_user, a.current_query AS blocked_statement FROM pg_catalog.pg_locks bl JOIN pg_catalog.pg_stat_activity a ON a.procpid = bl.pid JOIN pg_catalog.pg_locks kl ON kl.transactionid = bl.transactionid AND kl.pid != bl.pid JOIN pg_catalog.pg_stat_activity ka ON ka.procpid = kl.pid WHERE NOT bl.GRANTED; </code></pre> <p>which doesn't return any row</p>
1
Django Rest Framework : Nested Serializer Dynamic Model Fields
<p>I have defined serializers like below. I'm using a <a href="https://stackoverflow.com/questions/23643204/django-rest-framework-dynamically-return-subset-of-fields">mixin</a> to change the display fields on the fly.</p> <pre><code>class SerializerTwo(serializers.ModelSerializer): class Meta: model = Two fields = ('name', 'contact_number') class SerializerOne(DynamicFieldsModelSerializer, serializers.ModelSerializer): another_field = SerializerTwo() class Meta: lookup_field = 'uuid' model = One fields = ('status', 'another_field',) </code></pre> <p>Now what I want to do is, dynamically pass(on the fly) what all fields will be used from SerializerTwo, as I'm doing for SerializerOne.</p> <p>The way I'm doing it for SerializerOne is:</p> <pre><code># where fields=('status') SerializerOne(queryset, fields=fields) </code></pre> <p>Is there a way, using which I can add fields from SerializerTwo to the above Serializer initialization.</p> <pre><code># where fields=('status', 'name') name from SerializerTwo # the double underscore notation does not work here for fields, so another_field__name cannot be used as well SerializerOne(queryset, fields=fields) </code></pre>
1
Directory showing up as a grey folder on github, but not tracking its content. Why?
<p>I have a directory "ui-kit" that shows up on github as a grey folder. It's not clickable.</p> <p><a href="https://i.stack.imgur.com/zwWJ5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zwWJ5.png" alt="Github screenshot"></a></p> <p>Here is the whole content of .gitignore:</p> <pre><code># Fleetwit docs uploads/* .env *.prj *.pui # Logs logs *.log #Node node_modules # ========================= # Operating System Files # ========================= # OSX # ========================= .DS_Store .AppleDouble .LSOverride # Thumbnails ._* # Files that might appear on external disk .Spotlight-V100 .Trashes # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk # Windows # ========================= # Windows image file caches Thumbs.db ehthumbs.db # Folder config file Desktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Windows Installer files *.cab *.msi *.msm *.msp # Windows shortcuts *.lnk </code></pre> <p>I tried to check why it's being ignored using <code>git check-ignore --verbose ui-kit</code> but it doesn't return anything. I tried various syntaxes of <code>git add</code> without success.</p> <p>The directory used to be its own repository, but was moved inside the current project and all the original git files and directories removed.</p> <p>Here is the content of that directory:</p> <p><a href="https://i.stack.imgur.com/5cCqC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5cCqC.png" alt="enter image description here"></a></p> <p>Why is the icon grey on github? How do I keep track of the content?</p>
1
JavaFX Login with FXML
<p>I did a simple login window with Eclipse (Main.java, application.css, Login.fxml) How can I add a listener on the 2 buttons?</p> <p>Main.java</p> <pre><code>package application; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import javafx.scene.Parent; import javafx.scene.Scene; public class Main extends Application { @Override public void start(Stage primaryStage) { try { Parent root = FXMLLoader.load(getClass().getResource("Login.fxml")); Scene scene = new Scene(root,350,150); scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.setTitle("LOGIN"); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } } </code></pre> <p>Login.fxml</p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?import javafx.scene.layout.GridPane?&gt; &lt;?import java.lang.*?&gt; &lt;?import java.util.*?&gt; &lt;?import javafx.scene.*?&gt; &lt;?import javafx.geometry.*?&gt; &lt;?import javafx.scene.control.*?&gt; &lt;?import javafx.scene.text.*?&gt; &lt;?import javafx.scene.layout.*?&gt; &lt;?import javafx.scene.control.PasswordField?&gt; &lt;?import javafx.scene.layout.HBox?&gt; &lt;GridPane xmlns:fx="http://javafx.com/fxml/1" hgap="10" vgap="10"&gt; &lt;padding&gt; &lt;Insets top="10" right="10" bottom="10" left="10"/&gt; &lt;/padding&gt; &lt;children&gt; &lt;Label text="Username:" GridPane.columnIndex="0" GridPane.rowIndex="0" GridPane.halignment="RIGHT" /&gt; &lt;Label text="Password:" GridPane.columnIndex="0" GridPane.rowIndex="1" GridPane.halignment="RIGHT" /&gt; &lt;TextField GridPane.columnIndex="1" GridPane.rowIndex="0"/&gt; &lt;PasswordField GridPane.columnIndex="1" GridPane.rowIndex="1" /&gt; &lt;HBox GridPane.columnIndex="0" GridPane.rowIndex="2" GridPane.columnSpan="2" alignment="CENTER" spacing="10"&gt; &lt;children&gt; &lt;Button text="Login" /&gt; &lt;Button text="Annulla" /&gt; &lt;/children&gt; &lt;/HBox&gt; &lt;/children&gt; &lt;/GridPane&gt; </code></pre> <p>application.css</p> <pre><code>/* JavaFX CSS - Leave this comment until you have at least create one rule which uses -fx-Property */ .label { -fx-text-fill: rgb(255,0,0); -fx-font-weight: bold; -fx-font-style: italic; } </code></pre> <p>I need to get username e password and connect to a database</p>
1
angular 2 ajax call getting error "EXCEPTION: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"
<p>I'm creating app using angular2 and i need to get weather from yahoo weather. I try to do it using http get method but it's give me a error.</p> <pre><code>import {Component,OnInit,} from "angular2/core"; import {Http} from "angular2/http"; import 'rxjs/add/operator/map'; @Component({ templateUrl:'app/contact/contact.html', }) export class ContactComponent{ constructor (private http: Http) {} public url:string= "http://weather.yahooapis.com/forecastjson?w=2295424"; ngOnInit(url:string) { return this.http.get(url).map(res =&gt; { return res.json(); }).subscribe((response) =&gt; { console.log(response) }); } } </code></pre> <p>Error I get is</p> <blockquote> <p>EXCEPTION: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data</p> </blockquote> <p>can anyone help me with this?.</p>
1
How to link react-native-vector-icons to project
<p>I am getting a build error with the react-native-icons. I did the linking command from the installation instructions from their github site. the message said the icons were already linked to the project.</p> <blockquote> <p>Ld /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/NativeStarter.app/NativeStarter normal x86_64 cd /Users/rsanchez/Development/NativeStarter.git/ios export IPHONEOS_DEPLOYMENT_TARGET=7.0 export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator9.2.sdk -L/Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator -F/Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator -filelist /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Intermediates/NativeStarter.build/Debug-iphonesimulator/NativeStarter.build/Objects-normal/x86_64/NativeStarter.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -mios-simulator-version-min=7.0 -Xlinker -objc_abi_version -Xlinker 2 -ObjC -fobjc-arc -fobjc-link-runtime -lRNVectorIcons /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libReact.a /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libRCTActionSheet.a /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libRCTGeolocation.a /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libRCTImage.a /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libRCTLinking.a /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libRCTNetwork.a /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libRCTSettings.a /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libRCTText.a /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libRCTVibration.a /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/libRCTWebSocket.a -Xlinker -dependency_info -Xlinker /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Intermediates/NativeStarter.build/Debug-iphonesimulator/NativeStarter.build/Objects-normal/x86_64/NativeStarter_dependency_info.dat -o /Users/rsanchez/Library/Developer/Xcode/DerivedData/NativeStarter-ddtqngxgxoergggtejjrwdqafazh/Build/Products/Debug-iphonesimulator/NativeStarter.app/NativeStarter</p> <p>ld: library not found for -lRNVectorIcons clang: error: linker command failed with exit code 1 (use -v to see invocation)</p> </blockquote>
1
Plot a graph point to point python
<p>I wonder if there is some way to plot a waveform point to point at a certain rate through the matplotlib so that the graph appears slowly in the window. Or another method to graph appears at a certain speed in the window and not all the points simultaneously. I've been tried this but I can only plot a section of points at a time </p> <pre><code>import numpy as np import matplotlib.pyplot as plt import time x = np.arange(0,5,0.001) y = np.sin(2*np.pi*x) ind_i = 0 ind_f = 300 while ind_f &lt;= len(x): xtemp = x[ind_i:ind_f] ytemp = y[ind_i:ind_f] plt.hold(True) plt.plot(xtemp,ytemp) plt.show() time.sleep(1) ind_i = ind_f ind_f = ind_f + 300 </code></pre>
1
OpenLayers 3 get WKT Polygon string
<p>I have an openlayers 3 map where I can draw Polygon.</p> <p>I would have returned the WKT String that rapresent the drawed polygon.</p> <p>How Can I do it?</p> <p>JSFiddle Code <a href="http://jsfiddle.net/michelejs/3zawt33b/7/" rel="nofollow">http://jsfiddle.net/michelejs/3zawt33b/7/</a></p> <p>Here my map:</p> <pre><code>map = new ol.Map({ target: 'map', layers: [raster,vector], view: new ol.View({ center: ol.proj.fromLonLat([11.249367, 43.774298]), zoom: 15 }) }); </code></pre> <p>Here the intaractions that help me to draw the polygon:</p> <pre><code>function addInteraction() { var ct = 0; draw = new ol.interaction.Draw({ source: source, type: 'Polygon', geometryFunction: function (c, g) { if (goog.isDef(g)) { g.setCoordinates(c); } else { g = new ol.geom.Polygon(c); } if (c[0].length &gt; ct) { console.log('click coord : ' + c[0][c[0].length - 1]); var coord = c[0][c[0].length - 1]; $('div#coordinate').html( $('div#coordinate').html() + "&lt;p&gt;" + ( Number(coord[0]).toFixed(2) ) + " - " + ( Number(coord[1]).toFixed(2) ) + "&lt;/p&gt;" ); coordinates.push(coord); ct = c[0].length; } else { console.log('move coord : ' + c[0][c[0].length - 1]); } return g; } }); draw.on('drawend', function(e) { isin = e; checkIfIn(); lastFeature = e.feature; //write WKT Polygon Code in div#getAsWK }) draw.on('drawstart', function (e) { source.clear(); }); map.addInteraction(draw); } map.addInteraction(draw); </code></pre>
1
How to serialize all nulls to empty strings using Json.Net
<p>I would like to serialize all nulls from string and nullable types to empty strings. I looked into using a custom <code>JsonConverter</code> but properties with nulls are not passed into the converter. I looked into using a contract resolver and value provider but it won't let me set the value of an <code>int?</code> to an empty string. What seems most promising is using a custom <code>JsonWriter</code> that overrides the <code>WriteNull</code> method, but when I instantiate that in the converter's <code>WriteJson</code> method, it doesn't write anything out.</p> <pre><code>public class NullJsonWriter : JsonTextWriter { public NullJsonWriter(TextWriter writer) : base(writer) { } public override void WriteNull() { base.WriteValue(string.Empty); } } public class GamesJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(IEnumerable&lt;IGame&gt;).IsAssignableFrom(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer = new NullJsonWriter(new StringWriter(new StringBuilder())); writer.WriteStartObject(); if (typeof (IEnumerable).IsAssignableFrom(value.GetType())) { var list = (IEnumerable&lt;IGame&gt;)value; if (!list.Any()) { writer.WriteEndObject(); return; } var properties = list.First().GetType().GetProperties(); PropertyInfo gameId = null; foreach (var prop in properties) { if (prop.Name == "GameId") { gameId = prop; break; } } for (int i = 0; i &lt; list.Count(); i++) { writer.WritePropertyName(string.Format("{0}", gameId.GetValue(list.ElementAt(i)))); serializer.Serialize(writer, list.ElementAt(i)); } } writer.WriteEndObject(); } </code></pre> <p>I can see JSON text in the <code>StringBuilder</code> of the writer but it doesn't actually get written out to my webpage.</p>
1
How can I stub a controller helper method in a view spec with RSpec 3.4?
<p>I'm testing a view with <strong>RSpec</strong> (3.4 on <strong>Rails</strong> 4.2.5). And I use the <strong>decent_exposure</strong> gem in my CRUD controller. <strong>decent_exposure</strong> makes it easy to define named methods that are made available to my views and which memoize the resultant values.</p> <p>But I don't understand how I can stub these methods in a view spec. I tried do it according to the RSpec documentation, but it raises an error.</p> <p>Why doesn't it work? How can I stub the method <code>article</code> in the view?</p> <p>My controller</p> <pre><code>class Account::ArticlesController &lt; Account::BaseController expose(:articles) { current_user.articles } expose(:article, attributes: :article_params) # POST /account/articles # POST /account/articles.json def create respond_to do |format| if article.save format.html { redirect_to account_article_url(article), notice: 'Article was successfully created.' } format.json { render :show, status: :created, location: account_article_url(article) } else format.html { render :new } format.json { render json: article.errors, status: :unprocessable_entity } end end end # PATCH/PUT /account/articles/1 # PATCH/PUT /account/articles/1.json def update respond_to do |format| if article.update(article_params) format.html { redirect_to account_article_url(article), notice: 'Article was successfully updated.' } format.json { render :show, status: :ok, location: account_article_url(article) } else format.html { render :edit } format.json { render json: article.errors, status: :unprocessable_entity } end end end # DELETE /account/articles/1 # DELETE /account/articles/1.json def destroy respond_to do |format| if article.destroy format.html { redirect_to account_articles_url, notice: 'Article was successfully destroyed.' } format.json { head :no_content } else format.html { redirect_to account_articles_url, notice: 'Article was not destroyed.' } format.json { render json: article.errors, status: :unprocessable_entity } end end end private def article_params params.require(:article).permit(:title, :announce, :content, :is_published, :published_at) end end </code></pre> <p>And I have a view spec</p> <pre><code>require 'rails_helper' RSpec.describe 'account/articles/new', type: :view do before do allow(view).to receive(:article).and_return(build(:article)) end it 'renders new article form' do render expect(rendered).to match %Q{form[action=#{account_articles_path}][method=post]} end end </code></pre> <p>But it raises an error</p> <pre><code>Failures: 1) account/articles/new renders new article form Failure/Error: allow(view).to receive(:article).and_return(build(:article)) #&lt;#&lt;Class:0x007fe85c2c7620&gt;:0x007fe85d161208 @_routes=nil, @_config={}, @view_renderer=#&lt;ActionView::Renderer:0x007fe85d1613c0 @lookup_context=#&lt;ActionView::LookupContext:0x007fe85d1615a0 @details_key=nil, @details={:locale=&gt;[:en], :formats=&gt;[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=&gt;[], :handlers=&gt;[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}, @skip_default_locale=false, @cache=true, @prefixes=["", "account/articles"], @rendered_format=nil, @view_paths=#&lt;ActionView::PathSet:0x007fe85d1614d8 @paths=[#&lt;ActionView::OptimizedFileSystemResolver:0x007fe85d37fb48 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#&lt;ActionView::Resolver::Cache:0x007fe85d37fb20 @data=#&lt;ActionView::Resolver::Cache::SmallCache:0x007fe85d37faf8 @backend={}, @default_proc=#&lt;Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)&gt;&gt;&gt;, @path="/Users/et/Documents/projects/test-blog/app/views"&gt;, #&lt;ActionView::OptimizedFileSystemResolver:0x007fe85d37feb8 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#&lt;ActionView::Resolver::Cache:0x007fe85d37fe90 @data=#&lt;ActionView::Resolver::Cache::SmallCache:0x007fe85d37fe68 @backend={}, @default_proc=#&lt;Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)&gt;&gt;&gt;, @path="/Users/et/.rvm/gems/ruby-2.2.2/gems/devise-3.5.3/app/views"&gt;]&gt;&gt;&gt;, @request=#&lt;ActionController::TestRequest:0x007fe85c35e048 @env={"rack.version"=&gt;[1, 3], "rack.input"=&gt;#&lt;StringIO:0x007fe85f87eca0&gt;, "rack.errors"=&gt;#&lt;StringIO:0x007fe85f87ed40&gt;, "rack.multithread"=&gt;true, "rack.multiprocess"=&gt;true, "rack.run_once"=&gt;false, "REQUEST_METHOD"=&gt;"GET", "SERVER_NAME"=&gt;"example.org", "SERVER_PORT"=&gt;"80", "QUERY_STRING"=&gt;"", "rack.url_scheme"=&gt;"http", "HTTPS"=&gt;"off", "SCRIPT_NAME"=&gt;"", "CONTENT_LENGTH"=&gt;"0", "HTTP_HOST"=&gt;"test.host", "REMOTE_ADDR"=&gt;"0.0.0.0", "HTTP_USER_AGENT"=&gt;"Rails Testing", "action_dispatch.routes"=&gt;#&lt;ActionDispatch::Routing::RouteSet:0x007fe85c6713e8&gt;, "action_dispatch.parameter_filter"=&gt;[:password], "action_dispatch.redirect_filter"=&gt;[], "action_dispatch.secret_token"=&gt;nil, "action_dispatch.secret_key_base"=&gt;"eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", "action_dispatch.show_exceptions"=&gt;false, "action_dispatch.show_detailed_exceptions"=&gt;true, "action_dispatch.logger"=&gt;#&lt;ActiveSupport::Logger:0x007fe85d32d528 @progname=nil, @level=0, @default_formatter=#&lt;Logger::Formatter:0x007fe85d32d4b0 @datetime_format=nil&gt;, @formatter=#&lt;ActiveSupport::Logger::SimpleFormatter:0x007fe85d2fc928 @datetime_format=nil&gt;, @logdev=#&lt;Logger::LogDevice:0x007fe85d32d460 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#&lt;File:/Users/et/Documents/projects/test-blog/log/test.log&gt;, @mutex=#&lt;Logger::LogDevice::LogDeviceMutex:0x007fe85d32d438 @mon_owner=nil, @mon_count=0, @mon_mutex=#&lt;Mutex:0x007fe85d32d3e8&gt;&gt;&gt;&gt;, "action_dispatch.backtrace_cleaner"=&gt;#&lt;Rails::BacktraceCleaner:0x007fe85c2f4aa8 @filters=[#&lt;Proc:0x007fe85c2f4878@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:14&gt;, #&lt;Proc:0x007fe85c2f4850@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:15&gt;, #&lt;Proc:0x007fe85c2f47d8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:16&gt;, #&lt;Proc:0x007fe85c2f5750@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:29&gt;], @silencers=[#&lt;Proc:0x007fe85c2f59a8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:19&gt;], @root="/Users/et/Documents/projects/test-blog/"&gt;, "action_dispatch.key_generator"=&gt;#&lt;ActiveSupport::CachingKeyGenerator:0x007fe85f4cc580 @key_generator=#&lt;ActiveSupport::KeyGenerator:0x007fe85f4cc5a8 @secret="eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", @iterations=1000&gt;, @cache_keys=#&lt;ThreadSafe::Cache:0x007fe85f4cc558 @backend={"signed_global_ids64"=&gt;"0\xF4/#*5\xF2\x0F\xB2\x101\v~\xC5\x89\xFF\xDB\x11\xCB(U\xFA\xF87\x13Evz:\xAD\xD6\xA3r\x96\x9A\x82\x17\x84\tR\xF2A\xADV\x85u?^N\xBCT\x84\x10\x11\xD9\xC9&gt;n\xA1\f\x06\xAAuU"}, @default_proc=nil&gt;&gt;, "action_dispatch.http_auth_salt"=&gt;"http authentication", "action_dispatch.signed_cookie_salt"=&gt;"signed cookie", "action_dispatch.encrypted_cookie_salt"=&gt;"encrypted cookie", "action_dispatch.encrypted_signed_cookie_salt"=&gt;"signed encrypted cookie", "action_dispatch.cookies_serializer"=&gt;:json, "action_dispatch.cookies_digest"=&gt;nil, "rack.session"=&gt;{}, "rack.session.options"=&gt;{:key=&gt;"rack.session", :path=&gt;"/", :domain=&gt;nil, :expire_after=&gt;nil, :secure=&gt;false, :httponly=&gt;true, :defer=&gt;false, :renew=&gt;false, :sidbits=&gt;128, :cookie_only=&gt;true, :secure_random=&gt;SecureRandom, :id=&gt;"8a8b5f8906289bb00109022394af0832"}, "action_dispatch.request.path_parameters"=&gt;{:controller=&gt;"account/articles", :action=&gt;"new"}}, @filtered_parameters=nil, @filtered_env=nil, @filtered_path=nil, @protocol=nil, @port=nil, @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil, @uuid=nil&gt;, @response=#&lt;ActionController::TestResponse:0x007fe85c2cf0a0 @mon_owner=nil, @mon_count=0, @mon_mutex=#&lt;Mutex:0x007fe85c2cef38&gt;, @stream=#&lt;ActionDispatch::Response::Buffer:0x007fe85c2cedd0 @response=#&lt;ActionController::TestResponse:0x007fe85c2cf0a0 ...&gt;, @buf=[], @closed=false&gt;, @header={"X-Frame-Options"=&gt;"SAMEORIGIN", "X-XSS-Protection"=&gt;"1; mode=block", "X-Content-Type-Options"=&gt;"nosniff"}, @status=200, @sending_file=false, @blank=false, @cv=#&lt;MonitorMixin::ConditionVariable:0x007fe85c2ced58 @monitor=#&lt;ActionController::TestResponse:0x007fe85c2cf0a0 ...&gt;, @cond=#&lt;Thread::ConditionVariable:0x007fe85c2ced30&gt;&gt;, @committed=false, @sending=false, @sent=false, @content_type=nil, @charset=nil, @cache_control={}, @etag=nil&gt;, @params={}, @_assigns={"request"=&gt;#&lt;ActionController::TestRequest:0x007fe85c35e048 @env={"rack.version"=&gt;[1, 3], "rack.input"=&gt;#&lt;StringIO:0x007fe85f87eca0&gt;, "rack.errors"=&gt;#&lt;StringIO:0x007fe85f87ed40&gt;, "rack.multithread"=&gt;true, "rack.multiprocess"=&gt;true, "rack.run_once"=&gt;false, "REQUEST_METHOD"=&gt;"GET", "SERVER_NAME"=&gt;"example.org", "SERVER_PORT"=&gt;"80", "QUERY_STRING"=&gt;"", "rack.url_scheme"=&gt;"http", "HTTPS"=&gt;"off", "SCRIPT_NAME"=&gt;"", "CONTENT_LENGTH"=&gt;"0", "HTTP_HOST"=&gt;"test.host", "REMOTE_ADDR"=&gt;"0.0.0.0", "HTTP_USER_AGENT"=&gt;"Rails Testing", "action_dispatch.routes"=&gt;#&lt;ActionDispatch::Routing::RouteSet:0x007fe85c6713e8&gt;, "action_dispatch.parameter_filter"=&gt;[:password], "action_dispatch.redirect_filter"=&gt;[], "action_dispatch.secret_token"=&gt;nil, "action_dispatch.secret_key_base"=&gt;"eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", "action_dispatch.show_exceptions"=&gt;false, "action_dispatch.show_detailed_exceptions"=&gt;true, "action_dispatch.logger"=&gt;#&lt;ActiveSupport::Logger:0x007fe85d32d528 @progname=nil, @level=0, @default_formatter=#&lt;Logger::Formatter:0x007fe85d32d4b0 @datetime_format=nil&gt;, @formatter=#&lt;ActiveSupport::Logger::SimpleFormatter:0x007fe85d2fc928 @datetime_format=nil&gt;, @logdev=#&lt;Logger::LogDevice:0x007fe85d32d460 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#&lt;File:/Users/et/Documents/projects/test-blog/log/test.log&gt;, @mutex=#&lt;Logger::LogDevice::LogDeviceMutex:0x007fe85d32d438 @mon_owner=nil, @mon_count=0, @mon_mutex=#&lt;Mutex:0x007fe85d32d3e8&gt;&gt;&gt;&gt;, "action_dispatch.backtrace_cleaner"=&gt;#&lt;Rails::BacktraceCleaner:0x007fe85c2f4aa8 @filters=[#&lt;Proc:0x007fe85c2f4878@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:14&gt;, #&lt;Proc:0x007fe85c2f4850@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:15&gt;, #&lt;Proc:0x007fe85c2f47d8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:16&gt;, #&lt;Proc:0x007fe85c2f5750@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:29&gt;], @silencers=[#&lt;Proc:0x007fe85c2f59a8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:19&gt;], @root="/Users/et/Documents/projects/test-blog/"&gt;, "action_dispatch.key_generator"=&gt;#&lt;ActiveSupport::CachingKeyGenerator:0x007fe85f4cc580 @key_generator=#&lt;ActiveSupport::KeyGenerator:0x007fe85f4cc5a8 @secret="eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", @iterations=1000&gt;, @cache_keys=#&lt;ThreadSafe::Cache:0x007fe85f4cc558 @backend={"signed_global_ids64"=&gt;"0\xF4/#*5\xF2\x0F\xB2\x101\v~\xC5\x89\xFF\xDB\x11\xCB(U\xFA\xF87\x13Evz:\xAD\xD6\xA3r\x96\x9A\x82\x17\x84\tR\xF2A\xADV\x85u?^N\xBCT\x84\x10\x11\xD9\xC9&gt;n\xA1\f\x06\xAAuU"}, @default_proc=nil&gt;&gt;, "action_dispatch.http_auth_salt"=&gt;"http authentication", "action_dispatch.signed_cookie_salt"=&gt;"signed cookie", "action_dispatch.encrypted_cookie_salt"=&gt;"encrypted cookie", "action_dispatch.encrypted_signed_cookie_salt"=&gt;"signed encrypted cookie", "action_dispatch.cookies_serializer"=&gt;:json, "action_dispatch.cookies_digest"=&gt;nil, "rack.session"=&gt;{}, "rack.session.options"=&gt;{:key=&gt;"rack.session", :path=&gt;"/", :domain=&gt;nil, :expire_after=&gt;nil, :secure=&gt;false, :httponly=&gt;true, :defer=&gt;false, :renew=&gt;false, :sidbits=&gt;128, :cookie_only=&gt;true, :secure_random=&gt;SecureRandom, :id=&gt;"8a8b5f8906289bb00109022394af0832"}, "action_dispatch.request.path_parameters"=&gt;{:controller=&gt;"account/articles", :action=&gt;"new"}}, @filtered_parameters=nil, @filtered_env=nil, @filtered_path=nil, @protocol=nil, @port=nil, @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil, @uuid=nil&gt;, "response"=&gt;#&lt;ActionController::TestResponse:0x007fe85c2cf0a0 @mon_owner=nil, @mon_count=0, @mon_mutex=#&lt;Mutex:0x007fe85c2cef38&gt;, @stream=#&lt;ActionDispatch::Response::Buffer:0x007fe85c2cedd0 @response=#&lt;ActionController::TestResponse:0x007fe85c2cf0a0 ...&gt;, @buf=[], @closed=false&gt;, @header={"X-Frame-Options"=&gt;"SAMEORIGIN", "X-XSS-Protection"=&gt;"1; mode=block", "X-Content-Type-Options"=&gt;"nosniff"}, @status=200, @sending_file=false, @blank=false, @cv=#&lt;MonitorMixin::ConditionVariable:0x007fe85c2ced58 @monitor=#&lt;ActionController::TestResponse:0x007fe85c2cf0a0 ...&gt;, @cond=#&lt;Thread::ConditionVariable:0x007fe85c2ced30&gt;&gt;, @committed=false, @sending=false, @sent=false, @content_type=nil, @charset=nil, @cache_control={}, @etag=nil&gt;, "params"=&gt;{}}, @_controller=#&lt;ActionView::TestCase::TestController:0x007fe85c35e200 @_action_has_layout=true, @_routes=nil, @_headers={"Content-Type"=&gt;"text/html"}, @_status=200, @_request=nil, @_response=nil, @request=#&lt;ActionController::TestRequest:0x007fe85c35e048 @env={"rack.version"=&gt;[1, 3], "rack.input"=&gt;#&lt;StringIO:0x007fe85f87eca0&gt;, "rack.errors"=&gt;#&lt;StringIO:0x007fe85f87ed40&gt;, "rack.multithread"=&gt;true, "rack.multiprocess"=&gt;true, "rack.run_once"=&gt;false, "REQUEST_METHOD"=&gt;"GET", "SERVER_NAME"=&gt;"example.org", "SERVER_PORT"=&gt;"80", "QUERY_STRING"=&gt;"", "rack.url_scheme"=&gt;"http", "HTTPS"=&gt;"off", "SCRIPT_NAME"=&gt;"", "CONTENT_LENGTH"=&gt;"0", "HTTP_HOST"=&gt;"test.host", "REMOTE_ADDR"=&gt;"0.0.0.0", "HTTP_USER_AGENT"=&gt;"Rails Testing", "action_dispatch.routes"=&gt;#&lt;ActionDispatch::Routing::RouteSet:0x007fe85c6713e8&gt;, "action_dispatch.parameter_filter"=&gt;[:password], "action_dispatch.redirect_filter"=&gt;[], "action_dispatch.secret_token"=&gt;nil, "action_dispatch.secret_key_base"=&gt;"eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", "action_dispatch.show_exceptions"=&gt;false, "action_dispatch.show_detailed_exceptions"=&gt;true, "action_dispatch.logger"=&gt;#&lt;ActiveSupport::Logger:0x007fe85d32d528 @progname=nil, @level=0, @default_formatter=#&lt;Logger::Formatter:0x007fe85d32d4b0 @datetime_format=nil&gt;, @formatter=#&lt;ActiveSupport::Logger::SimpleFormatter:0x007fe85d2fc928 @datetime_format=nil&gt;, @logdev=#&lt;Logger::LogDevice:0x007fe85d32d460 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#&lt;File:/Users/et/Documents/projects/test-blog/log/test.log&gt;, @mutex=#&lt;Logger::LogDevice::LogDeviceMutex:0x007fe85d32d438 @mon_owner=nil, @mon_count=0, @mon_mutex=#&lt;Mutex:0x007fe85d32d3e8&gt;&gt;&gt;&gt;, "action_dispatch.backtrace_cleaner"=&gt;#&lt;Rails::BacktraceCleaner:0x007fe85c2f4aa8 @filters=[#&lt;Proc:0x007fe85c2f4878@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:14&gt;, #&lt;Proc:0x007fe85c2f4850@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:15&gt;, #&lt;Proc:0x007fe85c2f47d8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:16&gt;, #&lt;Proc:0x007fe85c2f5750@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:29&gt;], @silencers=[#&lt;Proc:0x007fe85c2f59a8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:19&gt;], @root="/Users/et/Documents/projects/test-blog/"&gt;, "action_dispatch.key_generator"=&gt;#&lt;ActiveSupport::CachingKeyGenerator:0x007fe85f4cc580 @key_generator=#&lt;ActiveSupport::KeyGenerator:0x007fe85f4cc5a8 @secret="eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", @iterations=1000&gt;, @cache_keys=#&lt;ThreadSafe::Cache:0x007fe85f4cc558 @backend={"signed_global_ids64"=&gt;"0\xF4/#*5\xF2\x0F\xB2\x101\v~\xC5\x89\xFF\xDB\x11\xCB(U\xFA\xF87\x13Evz:\xAD\xD6\xA3r\x96\x9A\x82\x17\x84\tR\xF2A\xADV\x85u?^N\xBCT\x84\x10\x11\xD9\xC9&gt;n\xA1\f\x06\xAAuU"}, @default_proc=nil&gt;&gt;, "action_dispatch.http_auth_salt"=&gt;"http authentication", "action_dispatch.signed_cookie_salt"=&gt;"signed cookie", "action_dispatch.encrypted_cookie_salt"=&gt;"encrypted cookie", "action_dispatch.encrypted_signed_cookie_salt"=&gt;"signed encrypted cookie", "action_dispatch.cookies_serializer"=&gt;:json, "action_dispatch.cookies_digest"=&gt;nil, "rack.session"=&gt;{}, "rack.session.options"=&gt;{:key=&gt;"rack.session", :path=&gt;"/", :domain=&gt;nil, :expire_after=&gt;nil, :secure=&gt;false, :httponly=&gt;true, :defer=&gt;false, :renew=&gt;false, :sidbits=&gt;128, :cookie_only=&gt;true, :secure_random=&gt;SecureRandom, :id=&gt;"8a8b5f8906289bb00109022394af0832"}, "action_dispatch.request.path_parameters"=&gt;{:controller=&gt;"account/articles", :action=&gt;"new"}}, @filtered_parameters=nil, @filtered_env=nil, @filtered_path=nil, @protocol=nil, @port=nil, @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil, @uuid=nil&gt;, @response=#&lt;ActionController::TestResponse:0x007fe85c2cf0a0 @mon_owner=nil, @mon_count=0, @mon_mutex=#&lt;Mutex:0x007fe85c2cef38&gt;, @stream=#&lt;ActionDispatch::Response::Buffer:0x007fe85c2cedd0 @response=#&lt;ActionController::TestResponse:0x007fe85c2cf0a0 ...&gt;, @buf=[], @closed=false&gt;, @header={"X-Frame-Options"=&gt;"SAMEORIGIN", "X-XSS-Protection"=&gt;"1; mode=block", "X-Content-Type-Options"=&gt;"nosniff"}, @status=200, @sending_file=false, @blank=false, @cv=#&lt;MonitorMixin::ConditionVariable:0x007fe85c2ced58 @monitor=#&lt;ActionController::TestResponse:0x007fe85c2cf0a0 ...&gt;, @cond=#&lt;Thread::ConditionVariable:0x007fe85c2ced30&gt;&gt;, @committed=false, @sending=false, @sent=false, @content_type=nil, @charset=nil, @cache_control={}, @etag=nil&gt;, @params={}, @_view_context_class=#&lt;Class:0x007fe85c2c7620&gt;, @_lookup_context=#&lt;ActionView::LookupContext:0x007fe85d1615a0 @details_key=nil, @details={:locale=&gt;[:en], :formats=&gt;[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=&gt;[], :handlers=&gt;[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}, @skip_default_locale=false, @cache=true, @prefixes=["", "account/articles"], @rendered_format=nil, @view_paths=#&lt;ActionView::PathSet:0x007fe85d1614d8 @paths=[#&lt;ActionView::OptimizedFileSystemResolver:0x007fe85d37fb48 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#&lt;ActionView::Resolver::Cache:0x007fe85d37fb20 @data=#&lt;ActionView::Resolver::Cache::SmallCache:0x007fe85d37faf8 @backend={}, @default_proc=#&lt;Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)&gt;&gt;&gt;, @path="/Users/et/Documents/projects/test-blog/app/views"&gt;, #&lt;ActionView::OptimizedFileSystemResolver:0x007fe85d37feb8 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#&lt;ActionView::Resolver::Cache:0x007fe85d37fe90 @data=#&lt;ActionView::Resolver::Cache::SmallCache:0x007fe85d37fe68 @backend={}, @default_proc=#&lt;Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)&gt;&gt;&gt;, @path="/Users/et/.rvm/gems/ruby-2.2.2/gems/devise-3.5.3/app/views"&gt;]&gt;&gt;, @_view_renderer=#&lt;ActionView::Renderer:0x007fe85d1613c0 @lookup_context=#&lt;ActionView::LookupContext:0x007fe85d1615a0 @details_key=nil, @details={:locale=&gt;[:en], :formats=&gt;[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=&gt;[], :handlers=&gt;[:erb, :builder, :raw, :ruby, :coffee, :jbuilder, :haml]}, @skip_default_locale=false, @cache=true, @prefixes=["", "account/articles"], @rendered_format=nil, @view_paths=#&lt;ActionView::PathSet:0x007fe85d1614d8 @paths=[#&lt;ActionView::OptimizedFileSystemResolver:0x007fe85d37fb48 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#&lt;ActionView::Resolver::Cache:0x007fe85d37fb20 @data=#&lt;ActionView::Resolver::Cache::SmallCache:0x007fe85d37faf8 @backend={}, @default_proc=#&lt;Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)&gt;&gt;&gt;, @path="/Users/et/Documents/projects/test-blog/app/views"&gt;, #&lt;ActionView::OptimizedFileSystemResolver:0x007fe85d37feb8 @pattern=":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", @cache=#&lt;ActionView::Resolver::Cache:0x007fe85d37fe90 @data=#&lt;ActionView::Resolver::Cache::SmallCache:0x007fe85d37fe68 @backend={}, @default_proc=#&lt;Proc:0x007fe85f071198@/Users/et/.rvm/gems/ruby-2.2.2/gems/actionview-4.2.5/lib/action_view/template/resolver.rb:49 (lambda)&gt;&gt;&gt;, @path="/Users/et/.rvm/gems/ruby-2.2.2/gems/devise-3.5.3/app/views"&gt;]&gt;&gt;&gt;, @_config={}&gt;, @_request=#&lt;ActionController::TestRequest:0x007fe85c35e048 @env={"rack.version"=&gt;[1, 3], "rack.input"=&gt;#&lt;StringIO:0x007fe85f87eca0&gt;, "rack.errors"=&gt;#&lt;StringIO:0x007fe85f87ed40&gt;, "rack.multithread"=&gt;true, "rack.multiprocess"=&gt;true, "rack.run_once"=&gt;false, "REQUEST_METHOD"=&gt;"GET", "SERVER_NAME"=&gt;"example.org", "SERVER_PORT"=&gt;"80", "QUERY_STRING"=&gt;"", "rack.url_scheme"=&gt;"http", "HTTPS"=&gt;"off", "SCRIPT_NAME"=&gt;"", "CONTENT_LENGTH"=&gt;"0", "HTTP_HOST"=&gt;"test.host", "REMOTE_ADDR"=&gt;"0.0.0.0", "HTTP_USER_AGENT"=&gt;"Rails Testing", "action_dispatch.routes"=&gt;#&lt;ActionDispatch::Routing::RouteSet:0x007fe85c6713e8&gt;, "action_dispatch.parameter_filter"=&gt;[:password], "action_dispatch.redirect_filter"=&gt;[], "action_dispatch.secret_token"=&gt;nil, "action_dispatch.secret_key_base"=&gt;"eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", "action_dispatch.show_exceptions"=&gt;false, "action_dispatch.show_detailed_exceptions"=&gt;true, "action_dispatch.logger"=&gt;#&lt;ActiveSupport::Logger:0x007fe85d32d528 @progname=nil, @level=0, @default_formatter=#&lt;Logger::Formatter:0x007fe85d32d4b0 @datetime_format=nil&gt;, @formatter=#&lt;ActiveSupport::Logger::SimpleFormatter:0x007fe85d2fc928 @datetime_format=nil&gt;, @logdev=#&lt;Logger::LogDevice:0x007fe85d32d460 @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#&lt;File:/Users/et/Documents/projects/test-blog/log/test.log&gt;, @mutex=#&lt;Logger::LogDevice::LogDeviceMutex:0x007fe85d32d438 @mon_owner=nil, @mon_count=0, @mon_mutex=#&lt;Mutex:0x007fe85d32d3e8&gt;&gt;&gt;&gt;, "action_dispatch.backtrace_cleaner"=&gt;#&lt;Rails::BacktraceCleaner:0x007fe85c2f4aa8 @filters=[#&lt;Proc:0x007fe85c2f4878@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:14&gt;, #&lt;Proc:0x007fe85c2f4850@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:15&gt;, #&lt;Proc:0x007fe85c2f47d8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:16&gt;, #&lt;Proc:0x007fe85c2f5750@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:29&gt;], @silencers=[#&lt;Proc:0x007fe85c2f59a8@/Users/et/.rvm/gems/ruby-2.2.2/gems/railties-4.2.5/lib/rails/backtrace_cleaner.rb:19&gt;], @root="/Users/et/Documents/projects/test-blog/"&gt;, "action_dispatch.key_generator"=&gt;#&lt;ActiveSupport::CachingKeyGenerator:0x007fe85f4cc580 @key_generator=#&lt;ActiveSupport::KeyGenerator:0x007fe85f4cc5a8 @secret="eb526d7f4b0c06b367225a0d32ba8b3c3287ea6d6de798961e6fe33b975d44c2cd3ae9f314f0b96c73029f052d4670bc5a4db850ffc6a73586043089f57bdb3b", @iterations=1000&gt;, @cache_keys=#&lt;ThreadSafe::Cache:0x007fe85f4cc558 @backend={"signed_global_ids64"=&gt;"0\xF4/#*5\xF2\x0F\xB2\x101\v~\xC5\x89\xFF\xDB\x11\xCB(U\xFA\xF87\x13Evz:\xAD\xD6\xA3r\x96\x9A\x82\x17\x84\tR\xF2A\xADV\x85u?^N\xBCT\x84\x10\x11\xD9\xC9&gt;n\xA1\f\x06\xAAuU"}, @default_proc=nil&gt;&gt;, "action_dispatch.http_auth_salt"=&gt;"http authentication", "action_dispatch.signed_cookie_salt"=&gt;"signed cookie", "action_dispatch.encrypted_cookie_salt"=&gt;"encrypted cookie", "action_dispatch.encrypted_signed_cookie_salt"=&gt;"signed encrypted cookie", "action_dispatch.cookies_serializer"=&gt;:json, "action_dispatch.cookies_digest"=&gt;nil, "rack.session"=&gt;{}, "rack.session.options"=&gt;{:key=&gt;"rack.session", :path=&gt;"/", :domain=&gt;nil, :expire_after=&gt;nil, :secure=&gt;false, :httponly=&gt;true, :defer=&gt;false, :renew=&gt;false, :sidbits=&gt;128, :cookie_only=&gt;true, :secure_random=&gt;SecureRandom, :id=&gt;"8a8b5f8906289bb00109022394af0832"}, "action_dispatch.request.path_parameters"=&gt;{:controller=&gt;"account/articles", :action=&gt;"new"}}, @filtered_parameters=nil, @filtered_env=nil, @filtered_path=nil, @protocol=nil, @port=nil, @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil, @uuid=nil&gt;, @view_flow=#&lt;ActionView::OutputFlow:0x007fe85a962d88 @content={}&gt;, @output_buffer="", @virtual_path=nil, @rendered_views=#&lt;ActionView::TestCase::Behavior::RenderedViewsCollection:0x007fe85a962b30 @rendered_views={}&gt;&gt; does not implement: article # ./spec/views/account/articles/new.html.haml_spec.rb:6:in `block (2 levels) in &lt;top (required)&gt;' Finished in 1.11 seconds (files took 6.26 seconds to load) 1 example, 1 failure Failed examples: rspec ./spec/views/account/articles/new.html.haml_spec.rb:9 # account/articles/new renders new article form </code></pre>
1
How do I write to a memory-mapped address in Rust?
<p>I'm trying to make "Blinky" for STM32F1xx in Rust. I know that there are libs for it, but I want to make my own "lib" for learning purposes.</p> <p>I can access STM32's "registers" by their addresses like this in C:</p> <pre class="lang-c prettyprint-override"><code>*(uint32_t*)(0x40021000 + 0x018) |= 0x10; *(uint32_t*)(0x40011000 + 0x004) |= 0x33; *(uint32_t*)(0x40011000 + 0x004) &amp;= ~0xCC; *(uint32_t*)(0x40011000 + 0x10) |= 0x300; while(1) {} </code></pre> <p>This writes some bits to the <code>RCC_APB2ENR</code> register to enable clocking of port C, configures pins and enables LEDs on my Discovery.</p> <p>I need to re-write this it in Rust, to make consts, fns and start writing nice Rusty code. Is it possible in Rust without FFI calling C code? Can I achieve this with the <code>asm!</code> macro?</p>
1
SailsJS user access levels and roles
<p>I am using what I have learnt <a href="https://ericswann.wordpress.com/2015/04/24/nozus-js-1-intro-to-sails-with-passport-and-jwt-json-web-token-auth/comment-page-1/" rel="nofollow">here</a> to build a user authentication system. Essentially it is using passport local auth.</p> <p>How would I add users access levels and roles to SailsJS? For example I would like access levels (canWriteAll, canWriteOwn, canRead) with user roles that these are assigned to (admin, contributor, user...etc..).</p>
1
Filter non-existing GenericForeignKey objects in Django queryset
<p>I have a simple model with a generic foreign key:</p> <pre><code>class Generic(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') </code></pre> <p>I would like to filter all entries in this table that have <strong>non-null</strong> <code>content_object</code>'s, i.e. filter out all instances of <code>Generic</code> whose <strong>content objects no longer exist</strong>:</p> <pre><code>Generic.objects.filter(~Q(content_object=None)) </code></pre> <p>This doesn't work, giving the exception:</p> <blockquote> <p>django.core.exceptions.FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation.</p> </blockquote> <p>Adding <code>GenericRelation</code> to the referenced content type models makes no difference. </p> <p>Any help on how to achieve this would be appreciated, many thanks.</p> <p>EDIT: I realise I could cascade the delete, however this is not an option in my situation (I wish to retain the data).</p>
1
How to embed VLC media player to Android Application?
<p>I have a video streaming Camera (from RTSP) and I cannot play its stream on my regular videoview in android. So i need to embed vlc player in to my app.Any one knows proper steps to integrate vlc player to my app..?</p> <p>I already saw this link <a href="https://stackoverflow.com/questions/22073970/how-to-embed-vlc-media-player-to-my-android-app">How to embed VLC media player to my Android App</a> , It was not work properly for me</p>
1
BabylonJs scene background image
<p>I have quite new to <code>BabylonJs</code> and im currently Learning by doing. </p> <p>I am trying to insert an image as the background for my scene:</p> <p><a href="https://i.stack.imgur.com/ZSef6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZSef6.jpg" alt="enter image description here"></a></p> <p>However ive looked all over the internet and no where is it described how i insert an image as a background?</p> <p>if needed here is my code:</p> <pre><code> // Global variables var canvas, engine, scene, camera,assetsManger; var CHATROOMS = []; var CHATCLIENTS = []; /* * Load the scene when the canvas is fully loaded */ document.addEventListener("DOMContentLoaded", function () { if (BABYLON.Engine.isSupported()) { initScene(); initGame(); } }, false); /** * Creates a new BABYLON Engine and initialize the scene */ function initScene() { // Get canvas canvas = document.getElementById("chatCanvas"); // Create babylon engine engine = new BABYLON.Engine(canvas, true); // Create scene scene = new BABYLON.Scene(engine); assetsManger = new BABYLON.AssetsManager(scene); // Create the camera camera = new BABYLON.TargetCamera("camera", new BABYLON.Vector3(0,4,-10), scene); camera.setTarget(new BABYLON.Vector3(0,0,0)); camera.attachControl(canvas); // Create light var light = new BABYLON.PointLight("light", new BABYLON.Vector3(0,5,-5), scene); engine.runRenderLoop(function () { scene.render(); }); } function initGame() { } </code></pre> <p>using the below code<a href="https://i.stack.imgur.com/MGZlN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MGZlN.jpg" alt="enter image description here"></a>:</p>
1
How to generate a customized checker board matrix as fast as possible?
<p>I need a function that creates a checker board matrix with <code>M</code> rows and <code>N</code> columns of <code>P*Q</code> rectangles. I modified the third solution from <a href="http://matlabtricks.com/post-31/three-ways-to-generate-a-checkerboard-matrix" rel="nofollow">here</a> to get that:</p> <pre><code>function [I] = mycheckerboard(M, N, P, Q) nr = M*P; nc = N*Q; i = floor(mod((0:(nc-1))/Q, 2)); j = floor(mod((0:(nr-1))/P, 2))'; r = repmat(i, [nr 1]); c = repmat(j, [1 nc]); I = xor(r, c); </code></pre> <p>it works with no problem:</p> <pre><code>I=mycheckerboard(2, 3, 4, 3) I = 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 0 0 0 1 1 1 </code></pre> <p>But it's not fast enough since there are lots of calls of this function in a single run. Is there a faster way to get the result? How can I remove floating point divisions and/or calls of the <code>floor</code> function?</p>
1
Conversion is ambiguous. Standard implicit conversion could not choose cast operator
<p>I have a custom type described as </p> <pre><code>struct A { double dbl_; bool boo_; operator double() const { return dbl_; } //operator bool() const { return boo_; } }; </code></pre> <p>And now I want to cast it to simple types. When <code>operator bool()</code> is undefined <code>a</code> can be implicitly converted to any simple type int, unsigned, float, etc. But with <code>operator bool()</code> conversion is ambiguous.</p> <pre><code>A a; cout &lt;&lt; (double) a &lt;&lt; endl; cout &lt;&lt; (float) a &lt;&lt; endl; //error: conversion from 'A' to 'float' is ambiguous; candidates are: A::operator bool() const; A::operator double() const cout &lt;&lt; (int) a &lt;&lt; endl; // the same cout &lt;&lt; (char) a &lt;&lt; endl; // the same return 0; </code></pre> <p>Runnable code on <a href="http://cpp.sh/3scp" rel="nofollow noreferrer">cpp.sh</a> </p> <p><strong>I know a few ways to fix that:</strong> </p> <p>1.add type conversion operators for <strong>all</strong> the expected types.</p> <pre><code> operator int() const { return (int)dbl_; } // and so on... </code></pre> <p>This looks like bad practice.</p> <p>2.use <em><a href="https://stackoverflow.com/questions/35242266/how-to-restrict-typenames-in-template">template with restricted types</a></em>. </p> <pre><code>template&lt;class T, class...&gt; struct is_any_of: std::false_type{}; template&lt;class T, class Head, class... Tail&gt; struct is_any_of&lt;T, Head, Tail...&gt; : std::conditional&lt; std::is_same&lt;T, Head&gt;::value, std::true_type, is_any_of&lt;T, Tail...&gt; &gt;::type {}; template&lt; class T, class = typename std::enable_if&lt;is_any_of&lt;T, int, float, unsigned, double&gt;::value&gt;::type &gt; operator T() const { if(type_ != Type::NUMBER) throw Node::Exception("not is number"); return dbl_; } </code></pre> <p>3.Hold <code>bool</code> value in <code>dbl_</code>, because only one of them is used. Not cool, as for me.</p> <p>May be a more refined solution exists? Like</p> <pre><code>operator bool() const no_implicit_conversation_to_other_types_specifier { return boo_; } </code></pre> <p>The question is at most theory of C++.</p> <p><strong>Upd.</strong> no_implicit_conversation_to_other_types_specifier is <code>explicit</code></p> <pre><code>explicit operator bool() const { return boo_; } </code></pre> <h2><a href="http://cpp.sh/4l4iv" rel="nofollow noreferrer">Run</a>.</h2>
1
Caching Jar dependencies for Maven-based Docker builds
<p>I'm building a Docker image from this Dockerfile:</p> <pre><code>FROM maven:3.3.3-jdk-8 MAINTAINER Mickael BARON ADD pom.xml /work/pom.xml WORKDIR /work RUN mvn dependency:go-offline --fail-never ADD ["src", "/work/src"] RUN ["mvn", "package"] </code></pre> <p>With this Dockerfile, I force to download the dependencies before packaging my Java project. Thus, I don't have to redownload the dependencies every time I changed a file from my src directory.</p> <p>But, there is a problem and this problem is depending on the version of Maven (base image). In fact, the dependencies are downloaded but they are not persisted into the ~/.m2 directory of the container. It's empty. Thus, when I change some source file all the dependencies are redownloaded.</p> <p>However, I noticed that if I change the version of Maven from the base image (for example <code>FROM maven:3.2.5-jdk-8</code>), it works.</p> <p>Very strange, isn't it?</p>
1
Table thumbnail_kvstore doesn't exist
<p>I can't get the thumbnail displayed in my template. I get this error:</p> <blockquote> <p>django.db.utils.ProgrammingError: (1146, "Table 'ia_website.thumbnail_kvstore' doesn't exist")</p> </blockquote> <ul> <li>Installed sorl_thumbnail-12.3</li> <li>I'm using MariaDB 10.1.11</li> <li>I have no migration that are not executed</li> <li>I can see the image if I don't use the 'thumbnail' tag</li> </ul> <p>Here is what I did</p> <ul> <li><p>In settings.py:</p> <pre><code>INSTALLED_APPS = [ ... 'sorl.thumbnail', ] THUMBNAIL_DEBUG = TRUE </code></pre></li> <li><p>In models.py</p> <pre><code>import sorl ... image = sorl.thumbnail.ImageField(upload_to='thumbnails', null=True) </code></pre></li> <li><p>In my template</p> <pre><code>{% thumbnail content.image "237x110" as im %} &lt;img src="{{ im.url }}"&gt; {% endthumbnail %} </code></pre></li> </ul>
1
How do I tell which version of Xcode/which SDK built an xcarchive?
<p>I have <code>xcarchives</code> for the various releases of my product, but I haven't been keeping track of which version of Xcode I built them with and with which SDK. How can I check?</p>
1
How to provide a document preview as a thumbnail independent of file type
<p>In gmail when a file is sent as an attachment to an email, the recipient(s) can see a small portion of the contents of the file before even hovering over it. Now I'm very curius and in fact interested in implementing this in my own application. I've tried inspect element but couldn't quite get how they do this. Ok, with images I can somewhat understand how it's done. But how about pdf, word or excel document? Do they take a snapshot of some portion of the file and store it along with the attachment to later show it inside a container? Has anyone been able to do this? Is just html and css enough?</p>
1
Error while parsing JSON babel failure
<p>When I run gulp I get error while parsing JSON:</p> <pre><code>Syntax Error 'C:\Path\main.js' Error while parsing JSON at: 98 text: '{\r\n "development": </code></pre> <p>"text" is truncated in the command line. I tried piping the output to a file and that failed because the error did not showup in the file:</p> <p>Powershell cmd</p> <p><code>gulp | Out-File C:\temp.txt -width 120</code></p> <p>package.json</p> <pre><code>{ "name": "helloreact", "version": "1.0.0", "description": "", "main": "main.js", "dependencies": { "babel": "^6.5.1", "babel-plugin-react-transform": "^2.0.0", "babel-preset-react": "^6.3.13", "babelify": "^7.2.0", "bootstrap": "^3.3.5", "flux": "^2.0.3", "gulp": "^3.9.0", "gulp-concat": "^2.6.0", "gulp-connect": "^2.2.0", "gulp-eslint": "^1.1.1", "gulp-open": "^1.0.0", "gulp-sourcemaps": "^1.6.0", "jquery": "^2.1.4", "jquery-csv": "^0.8.1", "lodash": "^4.0.1", "object-assign": "^4.0.1", "react": "^0.13.3", "react-router": "^0.13.3", "react-tools": "^0.10.0", "react-transform": "0.0.3", "reactify": "^1.1.1", "redbox-react": "^1.2.2", "toastr": "^2.1.0", "vinyl-source-stream": "^1.1.0" }, "devDependencies": {}, "scripts": { "test": "echo \"Error: no test specified\" &amp;&amp; exit 1" }, "author": "", "license": "ISC" } </code></pre> <p>.babelrc</p> <pre><code>{ "env": { "development": { "plugins": ["react-transform"], } } } } </code></pre> <p>My gulp task uses <code>babelify</code></p> <pre><code>gulp.task('js', function(){ browserify(config.paths.mainJs, { debug: true }) .transform(babel, {presets: ["react"]}) .transform(reactify) .bundle() .on('error', console.error.bind(console)) .pipe(source('bundle.js')) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(sourcemaps.write('./'))//TODO: not sure if this syntax is correct .pipe(gulp.dest(config.paths.dist + '/scripts')) .pipe(connect.reload()) }); </code></pre>
1
Does RISC-V mandate two's complement or one's complement signedness, or is it implementation-determined?
<p>I have looked through the ISA spec and searched the internet for the answer to this, but I could not find it.</p> <p>In the RISC-V ISA, should negative numbers be represented with one's complement or two's complement? Or, is this decision left to implementors?</p> <p>The reason I ask is that I am writing an RV32I simulator, and this would affect how I store negative numbers in the simulated memory, for example.</p>
1
Angular2 RouterLink in child component is expecting route to be defined in parent component
<p>I am using two components one is parent component and the second one is child component in its template. Now in child component I have defined a route and placed a router outlet and a router link in child component's template. So that when I click on this link it should update the contents at its own router outlet but its giving the following error and is searching for a route to be defined in its parent component:</p> <pre><code>EXCEPTION: Component "ParentComponent" has no route config.in[['ChildRoute'] in ChildComponent@2: 26] </code></pre> <p>The components are:</p> <pre><code>@Component({ selector: 'parent-cmp', template: '&lt;child-cmp&gt;&lt;/child-cmp&gt;', directives: [ ROUTER_DIRECTIVES, ChildComponent ] }) export class ParentComponent { } @Component({ selector: 'child-cmp', template: ` &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;a [routerLink]="['ChildRoute']"&gt;Edit&lt;/a&gt; `, directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ { path: '/edit', name: 'ChildRoute', component: ChildEditComponent } ]) export class ChildComponent { } </code></pre> <p>Assuming the imports are correct, I haven't mentioned here for brevity.</p>
1
VBA - Remove Seconds from NOW function
<p>I have something that notify me an hour before it happens. For that, I use the NOW function in VBA as I need it to check for the Date as well.</p> <p>The problem is the script runs every 20 seconds so I can't have it consider seconds for the NOW function.</p> <p>Is there a way to remove those? To have only like (DAY,MONTH,YEAR,HOUR,MINUTE)?</p> <p>Something along those lines:</p> <pre><code> MyLimit = NOW(DAY,MONTH,YEAR,HOUR,MINUTE) For Each FormulaCell In FormulaRange.Cells With FormulaCell If .Value = MyLimit Then Call Notify </code></pre> <p>Here is the script in which I attempt to detect the date and time.</p> <pre><code>Option Explicit Public Function AutoRun() Application.OnTime Now + TimeValue("00:00:20"), "TaskTracker2" End Function Public Sub TaskTracker2() Dim FormulaCell As Range Dim FormulaRange As Range Dim NotSentMsg As String Dim MyMsg As String Dim SentMsg As String Dim SendTo As String Dim CCTo As String Dim BCCTo As String Dim MyLimit As Date NotSentMsg = "Not Sent" SentMsg = "Sent" SendTo = Range("D2") CCTo = Range("E2") BCCTo = Range("F2") MyLimit = Format((Now), "DD/MM/YYYY HH:MM") Set FormulaRange = Range("E5:E35") On Error GoTo EndMacro: For Each FormulaCell In FormulaRange.Cells With FormulaCell If .Value = MyLimit Then MyMsg = SentMsg If .Offset(0, 1).Value = NotSentMsg Then strTO = SendTo strCC = CCTo strBCC = BCCTo strSub = "[Task Manager] Reminder that you need to: " &amp; Cells(FormulaCell.Row, "A").Value strBody = "Hello Sir, " &amp; vbNewLine &amp; vbNewLine &amp; _ "This email is to notify that you that your task : " &amp; Cells(FormulaCell.Row, "A").Value &amp; " with the following note: " &amp; Cells(FormulaCell.Row, "B").Value &amp; " is nearing its Due Date." &amp; vbNewLine &amp; "It would be wise to complete this task before it expires!" &amp; _ vbNewLine &amp; vbNewLine &amp; "Truly yours," &amp; vbNewLine &amp; "Task Manager" If sendMail(strTO, strSub, strBody, strCC) = True Then MyMsg = SentMsg End If Else MyMsg = NotSentMsg End If Application.EnableEvents = False .Offset(0, 1).Value = MyMsg Application.EnableEvents = True End With Next FormulaCell AutoRun ExitMacro: Exit Sub EndMacro: Application.EnableEvents = True MsgBox "Some Error occurred." _ &amp; vbLf &amp; Err.Number _ &amp; vbLf &amp; Err.Description End Sub </code></pre>
1
how to set dropdown values using ajax call in spring mvc
<p>I am beginner to ajax and spring mvc.I have got data from my database(mongodb) using ajax call.I want to know how to set dropdown values from ajax object.</p> <pre><code> home.jsp &lt;select class="form-control" id="list1value"&gt; &lt;c:forEach items="${???}" var="item"&gt; &lt;option value="${item. pri-ID}"&gt;${item.uniID}&lt;/option&gt; &lt;/c:forEach&gt; &lt;/select&gt; &lt;script type="text/javascript" &gt; $(document).ready(function() { $('#id').on('change', function() { var value = $(this).val(); $.ajax({ type: "GET", url: "list", data: "id=" +value, success: function(data) { alert(data); console.log(data); $('#list1value').val(data.cusID); $('#list1value').val(data.uniID); } }); }) }) &lt;/script&gt; </code></pre> <p>my data object is { "cusID" : "14345", "uniID" : "123999", "Name" : "wName", "pri-ID" : "11335" }</p> <p>how to write code in <strong></strong> part to assign option values??</p>
1
Upload dynamic number of files with okHttp3
<p>How to manage upload of dynamic number of files with <a href="http://square.github.io/okhttp/">OkHttp</a> v3, I have already implemented with older version of OkHttp which was <code>compile 'com.squareup.okhttp:okhttp:2.6.0'</code></p> <blockquote> <p>There are some changes in class Form and Multipart bodies are now modeled. They've replaced the opaque FormEncodingBuilder with the more powerful FormBody and FormBody.Builder combo. Similarly they've upgraded MultipartBuilder into MultipartBody, MultipartBody.Part, and MultipartBody.Builder. </p> </blockquote> <p>below code is of older version</p> <pre><code>final MediaType MEDIA_TYPE = MediaType.parse(AppConstant.arrImages.get(i).getMediaType()); //If you can have multiple file types, set it in ArrayList MultipartBuilder buildernew = new MultipartBuilder() .type(MultipartBuilder.FORM) .addFormDataPart("title", title); //Here you can add the fix number of data. for (int i = 0; i &lt; AppConstants.arrImages.size(); i++) { //loop to add dynamic number of files. File f = new File(FILE_PATH,TEMP_FILE_NAME + i + ".png"); if (f.exists()) { buildernew.addFormDataPart(TEMP_FILE_NAME + i, TEMP_FILE_NAME + i + FILE_EXTENSION, RequestBody.create(MEDIA_TYPE, f)); } } RequestBody requestBody = buildernew.build(); //Build the object of MultipartBuilder and get object of RequestBody. </code></pre> <p>But now for <code>OkHttp</code> <code>&lt;version&gt;3.0.1&lt;/version&gt;</code> code implementation for file upload is something like below code(<a href="https://github.com/square/okhttp/wiki/Recipes">source</a>)</p> <pre><code>RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("title", "Square Logo") .addFormDataPart("image", "logo-square.png", RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))) .build(); </code></pre> <p>I tried the same logic with <code>MultipartBody</code> but didn't found any fruitful solution. Or do I need to implement same <code>if else</code> for different cases.(Which is not feasible) </p>
1
How Exclude some files from Eclipse Java EE Web Application project Deployment Assembly
<p>As described into question title, I've an Eclipse Java EE Web Application project. Into WebContent folder I've some files and subfolder in which there are .DS_store OsX system files that cause some problem because they are always included when I export into war file.</p> <p>I know that there is a way for excluding a file or folder but only into src folder, not into WebContent!</p> <p>Any ideas?</p> <p>Regards</p>
1
SharePoint Online InfoPath: Amount of Data that was Returned by Connection has Exceeded the Maximum Limit
<p>In SharePoint Online, an InfoPath form is displaying this error: </p> <p>"The amount of data that was returned by connection has exceeded the maximum limit that was configured by server administrator."</p> <p>It is easy to increase the maximum limit in SharePoint On-premise, as explained here: </p> <p><a href="https://stackoverflow.com/questions/29790083/the-amount-of-data-that-was-returned-by-a-data-connection-has-exceeded-the-maxim">The amount of data that was returned by a data connection has exceeded the maximum limit that was configured by the server administrator</a> </p> <p>However, I am working in SharePoint Online, and there is no option to do this. I cannot find any PowerShell cmdlets, either. </p> <p>Does anyone know if it is simply impossible to increase the maximum limit (Data Connection Response Size)? If so, what can I do in my form to stop this from happening? </p> <p>Thanks</p>
1
How to use flask-migrate with other declarative_bases
<p>I'm trying to implement python-social-auth in Flask. I've ironed out tons of kinks whilst trying to interpret about 4 tutorials and a full Flask-book at the same time, and feel I've reached sort of an impasse with Flask-migrate.</p> <p>I'm currently using the following code to create the tables necessary for python-social-auth to function in a flask-sqlalchemy environment.</p> <pre class="lang-py prettyprint-override"><code>from social.apps.flask_app.default import models models.PSABase.metadata.create_all(db.engine) </code></pre> <p>Now, they're obviously using some form of their own Base, not related to my actual db-object. This in turn causes Flask-Migrate to completely miss out on these tables and remove them in migrations. Now, obviously I can remove these db-drops from every removal, but I can imagine it being one of those things that at one point is going to get forgotten about and all of a sudden I have no OAuth-ties anymore. </p> <p>I've gotten this solution to work with the usage (and modification) of the manage.py-command syncdb as suggested by <a href="https://github.com/omab/python-social-auth/blob/master/examples/flask_example/manage.py" rel="nofollow noreferrer">the python-social-auth Flask example</a></p> <p>Miguel Grinberg, the author of Flask-Migrate replies <a href="https://github.com/miguelgrinberg/Flask-Migrate/issues/85" rel="nofollow noreferrer">here</a> to an issue that seems to very closely resemble mine.</p> <p>The closest I could find on stack overflow was <a href="https://stackoverflow.com/questions/23868301/flask-migrate-multiple-models-py">this</a>, but it doesn't shed too much light on the entire thing for me, and the answer was never accepted (and I can't get it to work, I have tried a few times)</p> <p>For reference, here is my manage.py:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python from flask.ext.script import Server, Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from app import app, db manager = Manager(app) manager.add_command('runserver', Server()) manager.add_command('shell', Shell(make_context=lambda: { 'app': app, 'db_session': db.session })) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) @manager.command def syncdb(): from social.apps.flask_app.default import models models.PSABase.metadata.create_all(db.engine) db.create_all() if __name__ == '__main__': manager.run() </code></pre> <p>And to clarify, the db init / migrate / upgrade commands only create my user table (and the migration one obviously), but not the social auth ones, while the syncdb command works for the python-social-auth tables.</p> <p>I understand from the github response that this isn't supported by Flask-Migrate, but I'm wondering if there's a way to fiddle in the PSABase-tables so they are picked up by the db-object sent into Migrate.</p> <p>Any suggestions welcome.</p> <p>(Also, first-time poster. I feel I've done a lot of research and tried quite a few solutions before I finally came here to post. If I've missed something obvious in the guidelines of SO, don't hesitate to point that out to me in a private message and I'll happily oblige)</p>
1
How to set jenkins log level from maven?
<p>I am running Jenkins from source using <code>mvn jenkins-dev:run</code>. It seems to be logging at the DEBUG level making page load very slow. How do I change the log level of Jenkins. I have tried the usual util.logging properties file, but I can't get it working.</p>
1
Using variables in a node.js mysql-node query
<p>I am running a mysql query with WHERE, I would like to include my input prompt variable, input how would I go about doing so? my current query is like so, </p> <pre><code>var connect = connection.query('SELECT url FROM Sonic_url WHERE name=' + input //&lt;where I'm confused , function(err, rows, fields) { </code></pre>
1
How to draw bar chart using Plotly Offline mode in python?
<p>I have some features and values like:</p> <pre><code>food 3.4 service 4.2 environment 4.3 </code></pre> <p>and I want to draw a bar chart using Plotly offline mode (not registering and authenticating). So far I have the code for drawing a scattered line using Plotly's offline mode:</p> <pre><code>import plotly print (plotly.__version__) from plotly.graph_objs import Scatter, Layout plotly.offline.plot({ "data": [ Scatter(x=[1, 2, 3, 4], y=[4, 1, 3, 7]) ], "layout": Layout( title="hello world" ) }) </code></pre> <p>This code opens an HTML page and draws a scattered line. How to modify it so it draws a bar chart?</p>
1
"Error while finalizing cipher" when decrypting a file
<p>I get "error while finalizing cipher" whenever I want to decrypt a file I encrypted before.</p> <p>For testing purposes, I've just copypasted Pero's code from <a href="https://stackoverflow.com/questions/28115035/encrypting-files-with-aes-on-android">here</a>.</p> <p>All I've changed is removed the salt and replaced it with my md5 function. Before that I've tried it with the salt and it gave me the same error :(</p> <p>In that other question, the problem seems to be solved somehow, but he didn't further elaborate on that, it was just something with the salt that I didn't even use.</p> <pre><code>public static void encrypt(String path, String password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(path); FileOutputStream fos = new FileOutputStream(path.concat(".scrypt")); byte[] key = md5(password).getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key,16); SecretKeySpec sks = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); CipherOutputStream cos = new CipherOutputStream(fos, cipher); int b; byte[] d = new byte[8]; while((b = fis.read(d)) != -1) { cos.write(d, 0, b); } cos.flush(); cos.close(); fis.close(); } public static void decrypt(String path, String password) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(path); FileOutputStream fos = new FileOutputStream(path.replace(".scrypt", "")); byte[] key = md5(password).getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key,16); SecretKeySpec sks = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); CipherInputStream cis = new CipherInputStream(fis, cipher); int b; byte[] d = new byte[8]; while((b = cis.read(d)) != -1) { fos.write(d, 0, b); } fos.flush(); fos.close(); cis.close(); } </code></pre> <p>md5() is equivalent to php's md5()</p> <p>Would be awesome if someone could help me, I searched for a solution for hours :(</p>
1
YouTube channel subscribe for Android
<p>I am using the YouTube API within my app. Users can log in with their Google+ account. I would like the user to be able to subscribe to certain YouTube channels.</p> <p>There seems to be something for web here: <a href="https://developers.google.com/youtube/subscribe/" rel="noreferrer">https://developers.google.com/youtube/subscribe/</a></p> <p>But I can't find something suited to Android. Am I missing something from the documentation or is there a workaround?</p>
1
Use Simple HTML DOM Parser to JSON?
<p>I'm trying to group each of the elements of a scraped website, convert it into a json element but it doesn't seem to be working. </p> <pre><code>&lt;?php // Include the php dom parser include_once 'simple_html_dom.php'; header('Content-type: application/json'); // Create DOM from URL or file $html = file_get_html('urlhere'); foreach($html-&gt;find('hr ul') as $ul) { foreach($ul-&gt;find('div.product') as $li) $data[$count]['products'][]['li']= $li-&gt;innertext; $count++; } echo json_encode($data); ?&gt; </code></pre> <p>This returns </p> <pre><code>{"":{"products":[{"li":" &lt;a class=\"th\" href=\"\/products\/56942-haters-crewneck-sweatshirt\"&gt; &lt;div style=\"background-image:url('http:\/\/s0.merchdirect.com\/images\/15814\/v600_B_AltApparel_Crew.png');\"&gt; &lt;img src=\"http:\/\/s0.com\/images\/6398\/product-image-placeholder-600.png\"&gt; &lt;\/div&gt; &lt;\/a&gt; &lt;div class=\"panel panel-info\" style=\"display: none;\"&gt; &lt;div class=\"name\"&gt; &lt;a href=\"\/products\/56942-haters-crewneck-sweatshirt\"&gt; Haters Crewneck Sweatshirt &lt;\/a&gt; &lt;\/div&gt; &lt;div class=\"subtitle\"&gt; $60.00 &lt;\/div&gt; &lt;\/div&gt; "} </code></pre> <p>When I'm actually hoping to achieve:</p> <pre><code>{"products":[{ "link":"/products/56942-haters-crewneck-sweatshirt", "image":"http://s0.com/images/15814/v600_B_AltApparel_Crew.png", "name":"Haters Crewneck Sweatshirt", "subtitle":"60.00"} ]} </code></pre> <p>How do I get rid of all of the redundant information and probably name each element in the reformatted json?</p> <p>Thanks! </p>
1
mongoDB: get field value of an array object
<p>I want to get the value of the field <code>30</code> in the object (in the array <code>test</code>) with the id <code>ePce6fBAHx9KeKjuM</code>.</p> <pre><code>{ "_id" : "nAwt3b76c24mZfqxz", "title" : "test", "test" : [ { "4" : false, "15" : false, "30" : false, "75" : true, "id" : "ePce6fBAHx9KeKjuM" } ] } </code></pre> <p>So this result would be <code>false</code></p> <p>I tried something like</p> <pre><code>var result = Collection.findOne({_id: 'nAwt3b76c24mZfqxz'}).test; </code></pre> <p>But this would give me the complete array. But I need the selected object and only a selected field of this object (ie. <code>30</code>).</p>
1
Auto-update (calculate) the Excel sheet when a cell is changed
<p>I am using Excel 2010 and I want that the Excel sheet will be updated (calculated) automatically when the value of a cell (<code>Range("B7")</code>) is changed (The <code>Range("B7")</code> is a drop-down list). I am trying to use the intersect-target method like:</p> <pre><code>Private Sub Worksheet_Change(ByVal target As Range) If Not Intersect(target, Range("B7")) Is Nothing Then ActiveSheet.Calculate End If End Sub </code></pre> <p>I have two questions about this:</p> <p>Does it matter if I put this Private Sub under any module? Or am I supposed to write it in the exact sheet under the Microsoft Excel -object menu in VBA?</p> <p>The second question is how I can make this work? The sheet doesn't update (calculate) automatically when I change the <code>Range("B7")</code>. It only updates when I save the Excel file.</p>
1
Nodejs electron: focusOut event?
<p>I'm toying around with electron, the framework used for the atom text editor, but I'm having a little trouble finding a basic feature. I'm working on a little system tray gui that I want to pop up in that respective corner of the screen. When you click elsewhere on the screen, not on my window, I would like for the window to hide itself. For that, I would normally use a focusOut event callback or something similar. Does that event exist in electron, because all I've found is the focus event.</p>
1
Hadoop inode to path
<p>I used the 'hdfs oiv' command to read the fsimage into a xml file. </p> <pre><code>hdfs oiv -p XML -i /../dfs/nn/current/fsimage_0000000003132155181 -o fsimage.out </code></pre> <p>Based on my understanding, fsimage is supposed to store the "blockmap" like how the files got broken into blocks, and where each block is storing. However, here is how a record <code>inode</code> looks like in the output file. </p> <pre><code>&lt;inode&gt; &lt;id&gt;37749299&lt;/id&gt; &lt;type&gt;FILE&lt;/type&gt; &lt;name&gt;a4467282506298f8-e21f864f16b2e7c1_468511729_data.0.&lt;/name&gt; &lt;replication&gt;3&lt;/replication&gt; &lt;mtime&gt;1442259468957&lt;/mtime&gt; &lt;atime&gt;1454539092207&lt;/atime&gt; &lt;perferredBlockSize&gt;134217728&lt;/perferredBlockSize&gt; &lt;permission&gt;impala:hive:rw-r--r--&lt;/permission&gt; &lt;blocks&gt; &lt;block&gt; &lt;id&gt;1108336288&lt;/id&gt; &lt;genstamp&gt;35940487&lt;/genstamp&gt; &lt;numBytes&gt;16187048&lt;/numBytes&gt; &lt;/block&gt; &lt;/blocks&gt; &lt;/inode&gt; </code></pre> <p>However, I was expecting something like, hdfs path to a file, how that file got broken down into smaller pieces and where each piece has been stored (like which machine, which local fs path...etc...)</p> <p>Is there a mapping anywhere on the name server containing: </p> <ol> <li>the HDFS path to inode mapping </li> <li>the blockid to local file system path / disk location mapping? </li> </ol>
1
Spread multiple columns [tidyr]
<p>I would like to spread data over multiple columns using <code>tidyr</code>.</p> <pre><code> dat &lt;- data.frame(ID = rep(1,10), col1 = LETTERS[seq(1,10)], col2 = c(letters[seq(1,8)],NA,NA), col3 = c(rep(NA,8),"5",NA), col4 = c(rep(NA,8),NA,"value")) </code></pre> <p>The expected outcome is:</p> <pre><code>Out &lt;- data.frame(t(c(1,letters[seq(1,8)],"5","value")),row.names=NULL) colnames(Out) &lt;- c("ID",LETTERS[seq(1,10)]) </code></pre> <p>I came up with:</p> <pre><code>a &lt;- dat %&gt;% gather(variable, value, -(ID:col1)) %&gt;% unite(temp, col1, variable) %&gt;% spread(temp, value) a[,-which(is.na(a))] </code></pre> <p>which is clumsy and also changes the column names. Is there a better solution for this?</p>
1
Windows equivalent of Linux JQ tool command
<p>I have a linux jq command </p> <pre><code> jq -r '."FOO-BAR"[] | .foo+ " " + .bar[]' </code></pre> <p>What would be equivalent of this in Windows shell syntax? I have tried this and I get a compile error </p> <pre><code> jq -r "."FOO-BAR"[] | .foo+ " " + .bar[]" </code></pre>
1
Javafx create rectangles in a loop
<p>I am learning Javafx and am having trouble getting my for loop to create a new rectangle on each iteration. When I run the program it creates one rectangle at the top left position and that is it. My goal is to create a grid of rectangles based on the amount of columns, rows, pixels wide, and pixels tall specified. Everything is tested to work besides the creation of rectangles.</p> <pre><code>for(int i = 0; i &lt; columns; ++i) {//Iterate through columns for(int j = 0; j &lt; rows; ++j) {//Iterate through rows Color choice = chooseColor(rectColors); //Method that chooses a color rect = new Rectangle(horizontal*j, vertical*i, horizontal, vertical); //Create a new rectangle(PosY,PosX,width,height) rect.setStroke(choice); //Give rectangles an outline so I can see rectangles root.getChildren().add(rect); //Add Rectangle to board } } </code></pre> <p>I am trying to figure out why the rectangles aren't being created. Any help would be greatly appreciated.</p>
1