id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
6,706,485
How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?
<p>I'm developing game app and using Symfony 2.0. I have many AJAX requests to the backend. And more responses is converting entity to JSON. For example: </p> <pre><code>class DefaultController extends Controller { public function launchAction() { $user = $this-&gt;getDoctrine() -&gt;getRepository('UserBundle:User') -&gt;find($id); // encode user to json format $userDataAsJson = $this-&gt;encodeUserDataToJson($user); return array( 'userDataAsJson' =&gt; $userDataAsJson ); } private function encodeUserDataToJson(User $user) { $userData = array( 'id' =&gt; $user-&gt;getId(), 'profile' =&gt; array( 'nickname' =&gt; $user-&gt;getProfile()-&gt;getNickname() ) ); $jsonEncoder = new JsonEncoder(); return $jsonEncoder-&gt;encode($userData, $format = 'json'); } } </code></pre> <p>And all my controllers do the same thing: get an entity and encode some of its fields to JSON. I know that I can use normalizers and encode all entitities. But what if an entity has cycled links to other entity? Or the entities graph is very big? Do you have any suggestions? </p> <p>I think about some encoding schema for entities... or using <code>NormalizableInterface</code> to avoid cycling..,</p>
8,491,954
13
0
null
2011-07-15 11:41:32.043 UTC
42
2021-07-23 11:37:20.777 UTC
2013-06-16 17:09:55.717 UTC
null
1,553,481
null
191,490
null
1
95
ajax|doctrine|doctrine-orm|symfony
133,178
<p>Another option is to use the <a href="https://github.com/schmittjoh/JMSSerializerBundle/blob/master/Resources/doc/index.rst" rel="noreferrer">JMSSerializerBundle</a>. In your controller you then do </p> <pre><code>$serializer = $this-&gt;container-&gt;get('serializer'); $reports = $serializer-&gt;serialize($doctrineobject, 'json'); return new Response($reports); // should be $reports as $doctrineobject is not serialized </code></pre> <p>You can configure how the serialization is done by using annotations in the entity class. See the documentation in the link above. For example, here's how you would exclude linked entities:</p> <pre><code> /** * Iddp\RorBundle\Entity\Report * * @ORM\Table() * @ORM\Entity(repositoryClass="Iddp\RorBundle\Entity\ReportRepository") * @ExclusionPolicy("None") */ .... /** * @ORM\ManyToOne(targetEntity="Client", inversedBy="reports") * @ORM\JoinColumn(name="client_id", referencedColumnName="id") * @Exclude */ protected $client; </code></pre>
41,274,829
PHP error: "The zip extension and unzip command are both missing, skipping."
<p>When I run a <code>composer update</code> I get this error message:</p> <pre><code>Loading composer repositories with package information Updating dependencies (including require-dev) Failed to download psr/log from dist: The zip extension and unzip command are both missing, skipping. The php.ini used by your command-line PHP is: /etc/php/7.0/cli/php.ini Now trying to download from source </code></pre> <p>What do I need to do to enable the zip and unzip commands so that composer can download dependencies?</p>
41,274,856
17
1
null
2016-12-22 02:13:26.69 UTC
31
2022-09-12 16:23:21.583 UTC
null
null
null
null
2,884,981
null
1
196
php|composer-php
195,010
<p>Depending on your flavour of Linux and PHP version these may vary. </p> <pre><code>(sudo) yum install zip unzip php-zip (sudo) apt install zip unzip php-zip </code></pre> <p>This is a very commonly asked question, you'll be able to find more useful info in the aether by searching <code>&lt;distro&gt; php &lt;version&gt; zip extension</code>. </p>
15,713,167
ReSharper "Cannot resolve symbol" even when project builds
<p><strong>My Tools:</strong></p> <p><strong>Visual Studio 2012 Ultimate + Update 1</strong></p> <p><strong>ReSharper v7.1.25.234</strong></p> <p><strong>My Solution Build Status:</strong> <em>Build Successfully</em></p> <p>But when I install ReSharper and ReSharper code analysis is enable, many keywords of my code are red with this error:</p> <p><strong>"Cannot resolve symbol XXX"</strong></p> <p><img src="https://i.stack.imgur.com/mtS8B.jpg" alt="Enter image description here"></p> <hr> <p>Another picture of my project >></p> <p><strong>The ReSharper “CANNOT RESOLVE SYMBOL” errors are everywhere, but my project build process is successfully, and it works correctly.</strong></p> <p><img src="https://i.stack.imgur.com/IUkrX.jpg" alt="Enter image description here"></p> <p><strong>Additional Note:</strong> If I disable ReSharper Code Analysis, my project will be Normal, but I want to use ReSharper code analysis.</p> <hr> <p><strong>I tried</strong> ReSharper → <em>Options</em> → <em>General</em> → <em>Clear Cache</em>. But I still have this problem!</p> <hr> <ul> <li><p>One month ago, I got these errors when I uninstalled Visual Studio 2012 RC and installed VS 2012 RTM.</p></li> <li><p>I've already uninstalled and installed ReSharper again. But I have this problem yet!</p></li> <li><p>My solution has five projects >> two loaded projects (main project + resource project) and three unloaded projects</p></li> </ul> <hr> <p><strong>I realize that my Visual Studio also has bigger problems</strong> <a href="https://stackoverflow.com/questions/15746529/mvc-website-package-updating-error-loading-type-library-dll-exception-from-h">(More information on Stack&nbsp;Overflow)</a></p> <ul> <li><p>I can't add any reference to my projects (even inside new solutions and new projects)</p></li> <li><p>I can't install any package (by "Packet Manager Console" or Manage NuGet Package)</p></li> <li><p>I can't update any package (by "Packet Manager Console" or Manage NuGet Package)</p></li> </ul> <p><strong>I've done a lot of suggestions (of myself and others)</strong></p> <ul> <li><p>Re-resister some DLL files</p></li> <li><p>Using some windows and registry repair tools</p></li> <li><p>Remove ReSharper</p></li> <li><p>Repair Visual Studio</p></li> <li><p>and...</p></li> </ul> <p>But I could not solve it.</p> <p><strong>I'm thinking of installing a new Windows</strong> :(</p> <hr> <p><strong>What is wrong, and how can I fix it?</strong></p>
26,902,315
40
12
null
2013-03-29 23:45:48.82 UTC
91
2022-06-13 16:20:48.457 UTC
2018-11-26 16:54:13.247 UTC
null
1,741,690
null
1,474,613
null
1
529
c#|asp.net-mvc|visual-studio-2012|resharper-7.1
168,130
<p>I tested <strong>ALL</strong> of the other answers in this page <em>(before writing this answer)</em> such as:</p> <blockquote> <ol> <li><p>VS -&gt; Tools -&gt; Options -&gt; ReSharper <strong>Suspend</strong> button and <strong>Resume</strong></p> </li> <li><p><strong>Clear ReSharper cache</strong></p> </li> <li><p>And others</p> </li> </ol> </blockquote> <p>But unfortunately none of them solved my problem. Maybe my problem was complicated than your problem. I said about them in my <em>EDITs</em> in the question, then the following answer was correct solution <strong>for me</strong> but <strong>maybe other answers solve your problem. please test them first.</strong></p> <p><strong>I was forced</strong> to reinstall my OS and use a newer version of my tools. :(</p> <p>Now i use VS 2013 + R# v8 and when i have any problem with my resharper i just try the following instruction and <strong>it solve my problems</strong>:</p> <blockquote> <p>VS -&gt; Tools -&gt; Options -&gt; ReSharper Suspend button and Resume</p> </blockquote>
15,531,261
Accessing "this" in Clojurescript
<p>Is there a way to access the "this" object in clojurescript?</p> <p>I am <a href="https://stackoverflow.com/questions/15530791/in-jquey-how-do-i-pass-an-event-to-a-parent-anchor-if-needed?noredirect=1#comment22001349_15530791">having issues</a> with event propagation when I wrap an icon with an anchor and try to attach a handlder to the anchor. Without access to "this" in the handler I am constantly dealing with the inner icon firing the event sometimes and the anchor firing other times.</p> <p>edit:</p> <p>As was suggested below, this-as is the way to do this. An example could be</p> <pre><code>(defn my-handler [e] (this-as this (let [data-attr (.data ($ this) "my-attr")] (log data-attr)))) </code></pre>
15,547,274
1
1
null
2013-03-20 17:58:03.46 UTC
1
2013-07-15 20:01:05.81 UTC
2017-05-23 12:16:25.81 UTC
null
-1
null
715,386
null
1
28
javascript|google-closure|clojurescript
5,709
<p>Use ClojureScript's <code>this-as</code> macro: <a href="https://github.com/clojure/clojurescript/commit/09ff093dc86b455e3090ce3612c5e01f3b5bada6" rel="noreferrer">https://github.com/clojure/clojurescript/commit/09ff093dc86b455e3090ce3612c5e01f3b5bada6</a>.</p>
15,772,859
Tell if UITableView has scrolled to top
<p>I tried this:</p> <pre><code>- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView </code></pre> <p>But it didn't fire when I scrolled the table view to the top.</p> <pre><code>- (void)scrollViewDidScroll:(UIScrollView *)scrollView </code></pre> <p>Does fire so the delegate isn't the problem.</p> <p>In viewDidLoad I also set <code>[myTbl setDoesScrollToTop:YES];</code></p>
15,772,943
2
1
null
2013-04-02 19:38:13.95 UTC
4
2020-01-22 10:51:38.51 UTC
2016-12-21 21:42:06.16 UTC
null
1,032,372
null
964,373
null
1
29
ios|objective-c|xcode|cocoa-touch
20,111
<p>The <code>scrollViewDidScrollToTop:</code> method fires when the user clicks on the status bar and the <code>scrollsToTop</code> property is set to <code>YES</code>. From the docs:</p> <blockquote> <p>The scroll view sends this message when it finishes scrolling to the top of the content. It might call it immediately if the top of the content is already shown. For the scroll-to-top gesture (a tap on the status bar) to be effective, the scrollsToTop property of the UIScrollView must be set to YES.</p> </blockquote> <p>It does not fire if the user manually scrolls to the top. If you want to handle this case you will have to implement the <code>scrollViewDidScroll:</code> method and check to see whether the scroll is at the top yourself.</p> <p>You can check this through the <a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScrollView_Class/Reference/UIScrollView.html#//apple_ref/occ/instp/UIScrollView/contentOffset" rel="noreferrer">contentOffset</a> property e.g.:</p> <pre><code>if (scrollView.contentOffset.y == 0) { // TOP } </code></pre>
10,839,253
Mockito - intercept any method invocation on a mock
<p>Is it possible to intercept all method invocations on a mock in a generic way?</p> <p><strong>Example</strong></p> <p>Given a vendor provided class such as:</p> <pre><code>public class VendorObject { public int someIntMethod() { // ... } public String someStringMethod() { // ... } } </code></pre> <p>I would like to create a mock that re-directs <em>all</em> method calls to another class where there are matching method signatures:</p> <pre><code>public class RedirectedToObject { public int someIntMethod() { // Accepts re-direct } } </code></pre> <p>The when().thenAnswer() construct in Mockito seems to fit the bill but I cannot find a way to match any method call with any args. The InvocationOnMock certainly gives me all these details anyway. Is there a generic way to do this? Something that would look like this, where the when(vo.*) is replaced with appropriate code:</p> <pre><code>VendorObject vo = mock(VendorObject.class); when(vo.anyMethod(anyArgs)).thenAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) { // 1. Check if method exists on RedirectToObject. // 2a. If it does, call the method with the args and return the result. // 2b. If it does not, throw an exception to fail the unit test. } } ); </code></pre> <p>Adding wrappers around the vendor classes to make mocking easy is not an option because:</p> <ol> <li>Too large an existing code base.</li> <li>Part of extremely performance critical applications.</li> </ol>
10,842,322
1
4
null
2012-05-31 18:34:17.223 UTC
4
2012-05-31 22:50:13.143 UTC
null
null
null
null
338,173
null
1
29
java|unit-testing|mockito
22,649
<p>I think what you want is: </p> <pre><code>VendorObject vo = mock(VendorObject.class, new Answer() { @Override public Object answer(InvocationOnMock invocation) { // 1. Check if method exists on RedirectToObject. // 2a. If it does, call the method with the args and return the // result. // 2b. If it does not, throw an exception to fail the unit test. } }); </code></pre> <p>Of course, if you want to use this approach frequently, no need for the Answer to be anonymous.</p> <p>From the <a href="http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#mock%28java.lang.Class,%20org.mockito.stubbing.Answer%29">documentation</a>: "It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems." Sounds like you.</p>
25,228,394
How do I write an arrow function in ES6 recursively?
<p>Arrow functions in ES6 do not have an <code>arguments</code> property and therefore <code>arguments.callee</code> will not work and would anyway not work in strict mode even if just an anonymous function was being used.</p> <p>Arrow functions cannot be named, so the named functional expression trick can not be used.</p> <p>So... How does one write a recursive arrow function? That is an arrow function that recursively calls itself based on certain conditions and so on of-course?</p>
25,233,790
13
5
null
2014-08-10 12:01:47.163 UTC
13
2021-07-10 09:13:54.65 UTC
2015-04-20 07:55:56.053 UTC
null
527,702
null
959,850
null
1
49
javascript|recursion|ecmascript-6|arrow-functions
27,451
<p>Writing a recursive function without naming it is a problem that is as old as computer science itself (even older, actually, since &lambda;-calculus predates computer science), since in &lambda;-calculus <em>all</em> functions are anonymous, and yet you still need recursion.</p> <p>The solution is to use a fixpoint combinator, usually the Y combinator. This looks something like this:</p> <pre><code>(y =&gt; y( givenFact =&gt; n =&gt; n &lt; 2 ? 1 : n * givenFact(n-1) )(5) )(le =&gt; (f =&gt; f(f) )(f =&gt; le(x =&gt; (f(f))(x)) ) ); </code></pre> <p>This will compute the factorial of <code>5</code> recursively.</p> <p>Note: the code is heavily based on this: <a href="http://kestas.kuliukas.com/YCombinatorExplained/">The Y Combinator explained with JavaScript</a>. All credit should go to the original author. I mostly just "harmonized" (is that what you call refactoring old code with new features from ES/Harmony?) it.</p>
25,209,808
Clear the console in Java
<p>I have a class extending the Thread class. In its run method there is a <code>System.out.println</code> statement. Before this print statement is executed I want to clear the console. How can I do that?</p> <p>I tried </p> <pre><code>Runtime.getRuntime().exec("cls"); // and "clear" too </code></pre> <p>and</p> <pre><code>System.out.flush(); </code></pre> <p>but neither worked.</p>
25,210,648
3
5
null
2014-08-08 18:16:20.21 UTC
null
2020-08-27 17:25:55.04 UTC
2014-08-08 18:37:11.127 UTC
null
1,449,636
null
3,546,294
null
1
5
java|eclipse|console
60,748
<p>You can try something around these lines with System OS dependency : </p> <pre><code>final String operatingSystem = System.getProperty("os.name"); if (operatingSystem .contains("Windows")) { Runtime.getRuntime().exec("cls"); } else { Runtime.getRuntime().exec("clear"); } </code></pre> <p>Or other way would actually be a bad way but actually to send backspaces to console till it clears out. Something like :</p> <pre><code>for(int clear = 0; clear &lt; 1000; clear++) { System.out.println("\b") ; } </code></pre>
31,780,094
Spring Boot default test throws an IllegalStateException
<p>I am starting to play with spring boot and I have problems with fresh new installation.</p> <p>I have created initial project using <a href="http://start.spring.io" rel="noreferrer">http://start.spring.io</a> .. here is my build.gradle:</p> <pre><code>buildscript { ext { springBootVersion = '1.2.5.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath("io.spring.gradle:dependency-management-plugin:0.5.2.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'spring-boot' apply plugin: 'io.spring.dependency-management' jar { baseName = 'springboot-demo1' version = '0.0.1-SNAPSHOT' } sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile("org.springframework.boot:spring-boot-starter-jdbc") runtime("mysql:mysql-connector-java") testCompile("org.springframework.boot:spring-boot-starter-test") } eclipse { classpath { containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER') containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8' } } task wrapper(type: Wrapper) { gradleVersion = '2.3' } </code></pre> <p>When I execute in the command line: </p> <pre><code>gradlew clean build </code></pre> <p>build fails. Here is the output:</p> <pre><code>D:\springboot-demo1&gt;gradlew clean build :clean :compileJava :processResources :classes :jar :findMainClass :startScripts :distTar :distZip :bootRepackage :assemble :compileTestJava :processTestResources UP-TO-DATE :testClasses :test info.gandraweb.faker.apns.JavaApnsFakerApplicationTests &gt; contextLoads FAILED java.lang.IllegalStateException Caused by: org.springframework.beans.factory.BeanCreationException Caused by: org.springframework.beans.factory.BeanCreationException Caused by: org.springframework.beans.factory.BeanCreationException Caused by: org.springframework.beans.BeanInstantiationException Caused by: org.springframework.beans.factory.BeanCreationException 1 test completed, 1 failed :test FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':test'. &gt; There were failing tests. See the report at: file:///D:/springboot-demo1/build/reports/tests/index.html * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 17.572 secs </code></pre> <p>Test failed. Here is Test class code which fails:</p> <pre><code>package info.gandraweb.faker.apns; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import static org.junit.Assert.*; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = JavaApnsFakerApplication.class) public class JavaApnsFakerApplicationTests { @Test public void contextLoads() { assertTrue(true); } } </code></pre> <p>This is fresh new installation of spring boot and fails immediately. What I have to do to make build passes and test execute without any errors?</p> <p>p.s.</p> <p>Here is stacktrace for error from build\reports\tests\index.html:</p> <pre><code>java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94) at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:259) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:261) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:219) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:86) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:49) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:64) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50) 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:483) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32) at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy2.processTestClass(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:106) 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:483) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360) at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64) 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) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) at org.springframework.boot.test.SpringApplicationContextLoader.loadContext(SpringApplicationContextLoader.java:103) at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68) at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86) ... 44 more Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ... 59 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) ... 61 more Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ... 73 more Caused by: org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.getDriverClassName(DataSourceProperties.java:137) at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource(DataSourceAutoConfiguration.java:117) 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:483) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ... 74 more </code></pre>
31,781,524
2
4
null
2015-08-03 05:38:21.21 UTC
3
2019-10-15 08:43:41.523 UTC
2015-08-03 14:57:40.727 UTC
null
613,628
null
267,073
null
1
33
java|spring|gradle|spring-boot
77,956
<p>Make sure you have connection properties in the application.properties</p> <p>For eg.</p> <pre><code>spring.datasource.url=jdbc:mysql://localhost/database spring.datasource.username=username spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver </code></pre>
33,070,395
Not able to parse a .csv file uploaded using Flask
<p>I am trying to upload a CSV file, work on it to produce results, and write back (download) a new CSV file containing the result. I am very new to Flask and I am not able to get a "proper" <code>csv.reader</code> object to iterate and work upon. Here is the code so far,</p> <pre><code>__author__ = 'shivendra' from flask import Flask, make_response, request import csv app = Flask(__name__) def transform(text_file_contents): return text_file_contents.replace("=", ",") @app.route('/') def form(): return """ &lt;html&gt; &lt;body&gt; &lt;h1&gt;Transform a file demo&lt;/h1&gt; &lt;form action="/transform" method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="data_file" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; """ @app.route('/transform', methods=["POST"]) def transform_view(): file = request.files['data_file'] if not file: return "No file" file_contents = file.stream.read().decode("utf-8") csv_input = csv.reader(file_contents) print(file_contents) print(type(file_contents)) print(csv_input) for row in csv_input: print(row) result = transform(file_contents) response = make_response(result) response.headers["Content-Disposition"] = "attachment; filename=result.csv" return response if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True) </code></pre> <p>The terminal output being</p> <pre><code>127.0.0.1 - - [12/Oct/2015 02:51:53] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [12/Oct/2015 02:51:59] "POST /transform HTTP/1.1" 200 - 4,5,6 &lt;class 'str'&gt; &lt;_csv.reader object at 0x105149438&gt; ['1'] ['', ''] ['2'] ['', ''] ['3'] [] ['4'] ['', ''] ['5'] ['', ''] ['6'] </code></pre> <p>Whereas the file I read is</p> <p><a href="https://i.stack.imgur.com/GNtIf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GNtIf.png" alt="enter image description here"></a></p> <p>What am I doing wrong to not get 2 lists representing 2 rows when I iterate the csv.reader object?</p>
33,071,581
2
7
null
2015-10-11 21:42:19.857 UTC
12
2021-02-07 12:55:42.58 UTC
2018-12-20 15:41:29.18 UTC
null
425,313
null
1,641,628
null
1
20
python|csv|flask
31,551
<p>OK, so there is one major problem with your script, <code>csv.reader</code> as noted <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="noreferrer">here</a> expects a file object or at least an object which supports the iterator protocol. You are passing a <code>str</code> which does implement the iterator protocol, but instead of iterating through the lines, it iterates through the characters. This is why you have the output you do.</p> <p>First, it gives a singe character <code>1</code> which the <code>csv.reader</code> sees as a line with one field. After that the <code>str</code> gives another single character <code>,</code> which the <code>csv.reader</code> sees as a line with two empty fields (since the comma is the field seperator). It goes on like that throughout the <code>str</code> until it's exhausted.</p> <p>The solution (or at least one solution) is to turn the <code>str</code> into a file-like object. I tried using the stream provided by <code>flask.request.files["name"]</code>, but that doesn't iterate through the lines. Next, I tried using a <code>cStringIO.StringIO</code> and that seemed to have a similar issue. I ended up at <a href="https://stackoverflow.com/questions/1875956/how-can-i-access-an-uploaded-file-in-universal-newline-mode">this</a> question which suggested an <code>io.StringIO</code> object in universal newlines mode which worked. I ended up with the following working code (perhaps it could be better):</p> <pre><code>__author__ = 'shivendra' from flask import Flask, make_response, request import io import csv app = Flask(__name__) def transform(text_file_contents): return text_file_contents.replace("=", ",") @app.route('/') def form(): return """ &lt;html&gt; &lt;body&gt; &lt;h1&gt;Transform a file demo&lt;/h1&gt; &lt;form action="/transform" method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="data_file" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; """ @app.route('/transform', methods=["POST"]) def transform_view(): f = request.files['data_file'] if not f: return "No file" stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None) csv_input = csv.reader(stream) #print("file contents: ", file_contents) #print(type(file_contents)) print(csv_input) for row in csv_input: print(row) stream.seek(0) result = transform(stream.read()) response = make_response(result) response.headers["Content-Disposition"] = "attachment; filename=result.csv" return response if __name__ == "__main__": app.run(host='0.0.0.0', port=5001, debug=True) </code></pre>
33,129,201
No qualifying bean of type [org.springframework.transaction.PlatformTransactionManager] is defined
<p>I am using 2 Weblogic data sources; In my XML configurations I have 2 persistence units, 2 entityManagerFactories, and 2 transactionManagers. The files are as follows:</p> <p><strong>persistence.xml</strong>:</p> <pre><code>&lt;persistence-unit name="modelPersistence" transaction-type="RESOURCE_LOCAL"&gt; &lt;provider&gt;org.eclipse.persistence.jpa.PersistenceProvider&lt;/provider&gt; &lt;/persistence-unit&gt; &lt;persistence-unit name="orderPersistence" transaction-type="RESOURCE_LOCAL"&gt; &lt;provider&gt;org.eclipse.persistence.jpa.PersistenceProvider&lt;/provider&gt; &lt;/persistence-unit&gt; </code></pre> <p><strong>config.xml</strong>:</p> <pre><code>&lt;!-- transactionManagers --&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt; &lt;/bean&gt; &lt;bean id="transactionManagerLegacy" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactoryLegacy" /&gt; &lt;/bean&gt; &lt;!-- entityManagerFactory --&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="dataSource" ref="dataSourceModel"/&gt; &lt;property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" /&gt; &lt;property name="persistenceUnitName" value="modelPersistence" /&gt; &lt;property name="jpaProperties"&gt; &lt;props&gt; &lt;prop key="eclipselink.logging.level"&gt;FINE&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="loadTimeWeaver"&gt; &lt;bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/&gt; &lt;/property&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"&gt; &lt;property name="databasePlatform" value="org.eclipse.persistence.platform.database.OraclePlatform" /&gt; &lt;property name="generateDdl" value="true"/&gt; &lt;property name="showSql" value="true"/&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- entityManagerFactoryLegacy --&gt; &lt;bean id="entityManagerFactoryLegacy" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="dataSource" ref="dataSourceOrder"/&gt; &lt;property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" /&gt; &lt;property name="persistenceUnitName" value="orderPersistence" /&gt; &lt;property name="jpaProperties"&gt; &lt;props&gt; &lt;prop key="eclipselink.logging.level"&gt;FINE&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="loadTimeWeaver"&gt; &lt;bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/&gt; &lt;/property&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"&gt; &lt;property name="databasePlatform" value="org.eclipse.persistence.platform.database.OraclePlatform" /&gt; &lt;property name="generateDdl" value="true"/&gt; &lt;property name="showSql" value="true"/&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- data source 1--&gt; &lt;bean id="dataSourceModel" class="org.springframework.jndi.JndiObjectFactoryBean" depends-on="model-datasource-jndi"&gt; &lt;property name="jndiName" ref="model-datasource-jndi" /&gt; &lt;property name="resourceRef" value="true" /&gt; &lt;/bean&gt; &lt;!-- data source 2--&gt; &lt;bean id="dataSourceOrder" class="org.springframework.jndi.JndiObjectFactoryBean" depends-on="order-datasource-jndi"&gt; &lt;property name="jndiName" ref="order-datasource-jndi" /&gt; &lt;property name="resourceRef" value="true" /&gt; &lt;/bean&gt; &lt;!-- configure persistenceUnitManager --&gt; &lt;bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"&gt; &lt;property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" /&gt; &lt;property name="dataSources"&gt; &lt;map&gt; &lt;entry key="jdbc/MODEL-DS" value-ref="dataSourceModel"/&gt; &lt;entry key="jdbc/ORDER-DS" value-ref="dataSourceOrder"/&gt; &lt;/map&gt; &lt;/property&gt; &lt;/bean&gt; &lt;jpa:repositories base-package="org.codingpedia.demo.repositories.ModelRepository" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/&gt; &lt;jpa:repositories base-package="org.codingpedia.demo.repositories.OrderRepository" entity-manager-factory-ref="entityManagerFactoryLegacy" transaction-manager-ref="transactionManagerLegacy"/&gt; </code></pre> <p><strong>ModelRepository</strong>:</p> <pre><code>@Repository ("ModelRepo") @PersistenceContext(unitName = "modelPersistence") public interface ModelRepository extends JpaRepository&lt;Model, String&gt; {} </code></pre> <p><strong>orderRepository</strong>:</p> <pre><code>@Repository ("OrderRepo") @PersistenceContext(unitName = "orderPersistence") public interface OrderRepository extends JpaRepository&lt;Model, String&gt; {} </code></pre> <p>Any suggestions on the correct annotation for handling multiple transaction managers? Am I missing something else? Other stack-overflow examples use DAOs which I have not found helpful as I am using repositories, model, and controller java files. I am also not using hibernate, which a lot of examples reference as well. Your insight is appreciated. </p> <p><strong>I am receiving the following error:</strong></p> <pre><code>org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.transaction.PlatformTransactionManager] is defined: expected single matching bean but found 2: transactionManagerLegacy,transactionManager at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:365) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331) at org.springframework.transaction.interceptor.TransactionAspectSupport.determineTransactionManager(TransactionAspectSupport.java:370) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:271) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy.$Proxy120.findAll(Unknown Source) at org.codingpedia.demo.controller.BaseController.index(BaseController.java:45) 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:497) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:844) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280) at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254) at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:346) at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:243) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3432) at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3402) at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120) at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57) at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2285) at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2201) at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179) at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1572) at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255) at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311) at weblogic.work.ExecuteThread.run(ExecuteThread.java:263) </code></pre>
33,129,944
3
7
null
2015-10-14 15:15:02.697 UTC
4
2015-12-15 16:34:43.303 UTC
2015-12-15 16:34:43.303 UTC
null
5,348,109
null
5,348,109
null
1
12
java|spring|jpa|eclipselink|spring-data-jpa
43,846
<p>You can use:</p> <pre><code>@Transactional("transactionManagerName") </code></pre> <p>See org.springframework.transaction.annotation.Transactional (@Transactional) annotation javadoc:</p> <pre><code>/** * A qualifier value for the specified transaction. * &lt;p&gt;May be used to determine the target transaction manager, * matching the qualifier value (or the bean name) of a specific * {@link org.springframework.transaction.PlatformTransactionManager} * bean definition. */ String value() default ""; </code></pre>
13,332,015
List of all movie title, actors, directors, writers on Imdb
<p>I am working on a web app which lets users tell their favourite movies, directors, movie- writers, and actors. For this I want to provide them a dropdown list or auto complete for each of them so that they can just pick their choices.</p> <p>For this: I need a list of all movie titles, actors, directors, writers present on Imdb.</p> <p>I checked Imdbpy and it does not seem to provide methods to get this data. </p> <p>Would using imdbpy2sql.py to create a database and using sql to query the db, provide the required data? Is there any other way to do this?</p> <p>Thanks!</p>
13,342,901
2
2
null
2012-11-11 14:26:54.17 UTC
8
2017-06-04 10:52:23.703 UTC
null
null
null
null
1,509,755
null
1
9
movie|imdb|imdbpy
29,860
<p>Using imdbpy2sql.py to create a database and using SQL to query the db, will provide you the required data.</p> <p>You can also try using <a href="http://www.jmdb.de/" rel="noreferrer">Java Movie Database</a> or <a href="https://code.google.com/p/imdbdumpimport/" rel="noreferrer">imdbdumpimport</a> to read in the text files to SQL.</p> <p>The last option to do this is parsing the <a href="http://www.imdb.com/interfaces" rel="noreferrer">plain text files</a> provided by IMDb yourself. </p>
13,767,748
Returning only simple paths in Neo4j Cypher query
<p>Given a query like the following:</p> <pre><code>START n = node(123) MATCH p = n-[r:LIKES*..3]-&gt;x RETURN p; </code></pre> <p>The result paths that I get with the query above contain cycles. </p> <p>How can I return only simple paths? </p> <p>Given this <a href="http://tinyurl.com/cymx37g" rel="noreferrer">example</a>:</p> <ul> <li>How can I avoid paths with repeated nodes like: [Neo, Morpheus, Trinity, Morpheus, Neo]</li> </ul>
13,948,958
3
3
null
2012-12-07 17:09:46.483 UTC
9
2015-11-03 01:44:42.467 UTC
2012-12-12 15:22:42.52 UTC
null
807,231
null
807,231
null
1
15
neo4j|traversal|cypher
10,844
<p>Specifying the uniqueness of paths is a planned feature of cypher.</p> <p>So right now we have to ascertain that no node is a duplicate in the path.</p> <p>There is an <code>ALL</code> predicate that must hold true for all elements of a collection (which a path is). And with <code>filter</code> you can extract the elements of an collection for that a certain condition holds true.</p> <pre><code>START neo=node(1) MATCH path= neo-[r:KNOWS*..4]-&gt;other WHERE ALL(n in nodes(path) where 1=length(filter(m in nodes(path) : m=n))) RETURN neo, LENGTH(path) AS length, EXTRACT(p in NODES(path) : p.name), other ORDER BY length </code></pre> <p>So what I did was:</p> <ul> <li>For all nodes of the path <code>n</code></li> <li>Filter the path for the nodes that are equal to <code>n</code></li> <li>determine the <code>length</code> of that collection</li> <li>assert with <code>ALL</code> that it has to be ONE for each <code>n</code></li> </ul> <p>see: <a href="http://console.neo4j.org/r/dpalbl" rel="noreferrer">http://console.neo4j.org/r/dpalbl</a></p>
13,489,139
How to write JSON string value in code?
<p>I want to store the following string in a String variable</p> <blockquote> <p>{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}</p> </blockquote> <p>This is the code I use ..</p> <pre><code>String str="{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}"; </code></pre> <p>.. but it's showing error ..</p>
13,489,199
9
1
null
2012-11-21 08:29:24.797 UTC
2
2022-05-19 03:24:21.127 UTC
2012-11-21 08:40:31.507 UTC
user166390
null
null
1,811,801
null
1
34
c#|json|string|syntax
59,923
<p>You have to do this <br/></p> <pre><code>String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}"; </code></pre> <p><br/>Please <a href="http://www.codeproject.com/Articles/371232/Escaping-in-Csharp-characters-strings-string-forma">see this for reference</a><br/>Also <a href="http://msdn.microsoft.com/en-us/library/h21280bw.aspx">from msdn :)</a><br/><br/></p> <pre><code>Short Notation UTF-16 character Description \' \u0027 allow to enter a ' in a character literal, e.g. '\'' \" \u0022 allow to enter a " in a string literal, e.g. "this is the double quote (\") character" \\ \u005c allow to enter a \ character in a character or string literal, e.g. '\\' or "this is the backslash (\\) character" \0 \u0000 allow to enter the character with code 0 \a \u0007 alarm (usually the HW beep) \b \u0008 back-space \f \u000c form-feed (next page) \n \u000a line-feed (next line) \r \u000d carriage-return (move to the beginning of the line) \t \u0009 (horizontal-) tab \v \u000b vertical-tab </code></pre>
13,389,203
pandas: slice a MultiIndex by range of secondary index
<p>I have a series with a MultiIndex like this:</p> <pre><code>import numpy as np import pandas as pd buckets = np.repeat(['a','b','c'], [3,5,1]) sequence = [0,1,5,0,1,2,4,50,0] s = pd.Series( np.random.randn(len(sequence)), index=pd.MultiIndex.from_tuples(zip(buckets, sequence)) ) # In [6]: s # Out[6]: # a 0 -1.106047 # 1 1.665214 # 5 0.279190 # b 0 0.326364 # 1 0.900439 # 2 -0.653940 # 4 0.082270 # 50 -0.255482 # c 0 -0.091730 </code></pre> <p>I'd like to get the s['b'] values where the second index ('<code>sequence</code>') is between 2 and 10.</p> <p>Slicing on the first index works fine:</p> <pre><code>s['a':'b'] # Out[109]: # bucket value # a 0 1.828176 # 1 0.160496 # 5 0.401985 # b 0 -1.514268 # 1 -0.973915 # 2 1.285553 # 4 -0.194625 # 5 -0.144112 </code></pre> <p>But not on the second, at least by what seems to be the two most obvious ways:</p> <p>1) This returns elements 1 through 4, with nothing to do with the index values</p> <pre><code>s['b'][1:10] # In [61]: s['b'][1:10] # Out[61]: # 1 0.900439 # 2 -0.653940 # 4 0.082270 # 50 -0.255482 </code></pre> <p>However, if I reverse the index and the first index is integer and the second index is a string, it works:</p> <pre><code>In [26]: s Out[26]: 0 a -0.126299 1 a 1.810928 5 a 0.571873 0 b -0.116108 1 b -0.712184 2 b -1.771264 4 b 0.148961 50 b 0.089683 0 c -0.582578 In [25]: s[0]['a':'b'] Out[25]: a -0.126299 b -0.116108 </code></pre>
13,389,808
5
2
null
2012-11-14 23:29:30.823 UTC
17
2019-07-24 12:56:51.883 UTC
null
null
null
null
529,841
null
1
37
python|pandas
47,760
<p>As <a href="https://stackoverflow.com/a/31490891/1240268">Robbie-Clarken answers</a>, since 0.14 you can pass a <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="noreferrer">slice in the tuple you pass to loc</a>:</p> <pre><code>In [11]: s.loc[('b', slice(2, 10))] Out[11]: b 2 -0.65394 4 0.08227 dtype: float64 </code></pre> <p>Indeed, you can pass a slice for each level:</p> <pre><code>In [12]: s.loc[(slice('a', 'b'), slice(2, 10))] Out[12]: a 5 0.27919 b 2 -0.65394 4 0.08227 dtype: float64 </code></pre> <p><em>Note: the slice is inclusive.</em></p> <hr> <h3>Old answer:</h3> <p>You can also do this using:</p> <pre><code>s.ix[1:10, "b"] </code></pre> <p>(It's good practice to do in a single ix/loc/iloc since this version allows assignment.)</p> <p>This answer was written prior to the <a href="https://github.com/pydata/pandas/pull/2922" rel="noreferrer">introduction of iloc</a> in early 2013, i.e. position/integer location - which may be preferred in this case. The reason it was created was to remove the ambiguity from integer-indexed pandas objects, and be more descriptive: "I'm slicing on position".</p> <pre><code>s["b"].iloc[1:10] </code></pre> <p>That said, I kinda disagree with the docs that ix is:</p> <blockquote> <p>most robust and consistent way</p> </blockquote> <p>it's not, the most consistent way is to describe what you're doing:</p> <ul> <li>use loc for labels</li> <li>use iloc for position</li> <li>use ix for both (if you really have to)</li> </ul> <p>Remember the <a href="https://www.python.org/dev/peps/pep-0020/" rel="noreferrer">zen of python</a>:</p> <blockquote> <p>explicit is better than implicit</p> </blockquote>
13,612,967
How to reverse a string in R
<p>I'm trying to teach myself R and in doing some sample problems I came across the need to reverse a string.</p> <p>Here's what I've tried so far but the paste operation doesn't seem to have any effect.</p> <p>There must be something I'm not understanding about lists? (I also don't understand why I need the [[1]] after strsplit.)</p> <pre class="lang-r prettyprint-override"><code>test &lt;- strsplit(&quot;greg&quot;, NULL)[[1]] test # [1] &quot;g&quot; &quot;r&quot; &quot;e&quot; &quot;g&quot; test_rev &lt;- rev(test) test_rev # [1] &quot;g&quot; &quot;e&quot; &quot;r&quot; &quot;g&quot; paste(test_rev) # [1] &quot;g&quot; &quot;e&quot; &quot;r&quot; &quot;g&quot; </code></pre>
13,613,131
14
8
null
2012-11-28 19:33:18.167 UTC
20
2022-08-27 10:13:35.917 UTC
2022-08-27 10:13:35.917 UTC
null
13,968,222
null
13,009
null
1
54
r|string
55,091
<p>As @mplourde points out, you want the <code>collapse</code> argument:</p> <pre><code>paste(test_rev, collapse='') </code></pre> <p>Most commands in R are vectorized, but how exactly the command handles vectors depends on the command. <code>paste</code> will operate over multiple vectors, combining the <code>i</code>th element of each:</p> <pre><code>&gt; paste(letters[1:5],letters[1:5]) [1] "a a" "b b" "c c" "d d" "e e" </code></pre> <p><code>collapse</code> tells it to operate within a vector instead.</p>
13,366,820
How do you make lettered lists using markdown?
<p><a href="http://daringfireball.net/projects/markdown/syntax#list">Markdown</a> allows ordered lists using numbers. How can I instead get an ordered list using <em>letters</em>? i.e.</p> <pre><code>A. the letter A B. the letter B C. etc </code></pre> <p>instead of </p> <pre><code>1. the number 1 2. the number 2 3. etc. </code></pre>
15,422,454
7
0
null
2012-11-13 18:49:37.763 UTC
19
2022-08-12 19:39:09.65 UTC
null
null
null
null
814,354
null
1
177
markdown
117,345
<p>It doesn't appear that standard Markdown has this capability. You can:</p> <ol> <li>Use CSS, by putting this somewhere in your markdown document (note, this will effect all ordered lists in the document)</li> </ol> <pre class="lang-html prettyprint-override"><code>&lt;style type=&quot;text/css&quot;&gt; ol { list-style-type: upper-alpha; } &lt;/style&gt; </code></pre> <ol start="2"> <li>Use an extended version of markdown. Pandoc markdown has a <a href="https://pandoc.org/MANUAL.html#extension-fancy_lists" rel="noreferrer"><code>fancy_lists</code> extension</a> that will allow you to mark lists with letters and roman numerals.</li> </ol> <p>Note: if using capital letters, two spaces are required before the text. See <a href="https://pandoc.org/MANUAL.html#fn1" rel="noreferrer">https://pandoc.org/MANUAL.html#fn1</a></p> <pre class="lang-markdown prettyprint-override"><code>A. the letter A A. the letter B A. etc </code></pre>
51,788,764
How to intercept a RequestRejectedException in Spring?
<p>I am seeing <em>a ton</em> of <code>RequestRejectedException</code> entries in my Tomcat log (sample pasted below). These started appearing in my log file after a minor version upgrade (Spring Security 4.2.4, IIRC) a few months ago, so this is clearly a new security feature in Spring that is enabled by default. A similar issue is <a href="https://stackoverflow.com/q/48453980/2074605">reported here</a>, but my question involves specifically how to intercept these exceptions in a controller. There is a Spring Security bug documented for this problem (<a href="https://github.com/spring-projects/spring-security/issues/5007" rel="noreferrer">Provide a way to handle RequestRejectedException</a>). However, they aren't targeting a fix for this problem until Spring 5.1.</p> <p>I understand <a href="https://stackoverflow.com/q/48580584/2074605">why these exceptions are being thrown</a>, and I do not want to <a href="https://stackoverflow.com/a/48636757/2074605">disable this security feature</a>.</p> <p>I want to gain some control over this feature so that:</p> <ol> <li>I know I'm not blocking legitimate users from my site.</li> <li>I can see what requests are triggering this (are they SQL Injection attacks?)</li> <li>I can adjust the server response. The Spring Security firewall dumps a complete stack trace to the web client (information disclosure), along with a <code>500 Internal Server Error</code> (which is wildly incorrect, this should be a <code>400 Bad Request</code>).</li> </ol> <p>I want to find a way to log the URL that was requested, but also suppress the stack trace specifically for these exceptions because they are polluting my log files without giving me any helpful information. Optimally, I'd like to intercept these exceptions and handle them in my application layer instead of reporting them in the Tomcat log at all.</p> <p>For example, this is one of thousands of these log entries that appear every day in my <code>catalina.out</code>:</p> <pre><code>Aug 10, 2018 2:01:36 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String ";" at org.springframework.security.web.firewall.StrictHttpFirewall.rejectedBlacklistedUrls(StrictHttpFirewall.java:265) at org.springframework.security.web.firewall.StrictHttpFirewall.getFirewalledRequest(StrictHttpFirewall.java:245) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:193) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:486) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) </code></pre> <p>I'm seeing over 3,200 of these in a two day period, and it has quickly become the single largest contributor to my <code>catalina.out</code> log file, to the point that it prevents me from seeing other, legitimate problems. Essentially, this new Spring Security feature is a form of built-in Denial-of-Service, and it has wasted hours of my time since April. I am not saying that it is not an important feature, simply that the default implementation is completely botched, and I want to find a way gain some control over it, both as a developer and as a systems administrator.</p> <p>I use a custom Error Controller for intercepting many other Exception types (including <code>IOException</code>) in Spring. However, <code>RequestRejectedException</code> seems to be falling through for some reason.</p> <p>This is the relevant part of my <code>ErrorController.java</code>, to give an idea of what I'm trying to accomplish:</p> <pre><code>@ControllerAdvice public final class ErrorController { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(ErrorController.class.getName()); /** * Generates an Error page by intercepting exceptions generated from HttpFirewall. * * @param ex A RequestRejectedException exception. * @return The tile definition name for the page. */ @ExceptionHandler(RequestRejectedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public String handleRequestRejectedException(final HttpServletRequest request, final RequestRejectedException ex) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Request Rejected", ex); } LOGGER.log(Level.WARNING, "Rejected request for [" + request.getRequestURL().toString() + "]. Reason: " + ex.getMessage()); return "errorPage"; } /** * Generates a Server Error page. * * @param ex An exception. * @return The tile definition name for the page. */ @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public String handleException(final Exception ex) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "Server Error", ex); } return "errorPage"; } } </code></pre> <p>This error controller works for many exceptions. For example, it successfully intercepted this <code>IllegalStateException</code>:</p> <pre><code>Aug 05, 2018 7:50:30 AM com.mycompany.spring.controller.ErrorController handleException SEVERE: Server Error java.lang.IllegalStateException: Cannot create a session after the response has been committed at org.apache.catalina.connector.Request.doGetSession(Request.java:2999) ... </code></pre> <p>However, this is not intercepting <code>RequestRejectedException</code> (as indicated by the lack of "Server Error" in the first log sample above).</p> <p>How can I intercept <code>RequestRejectedException</code> in an error controller?</p>
51,800,972
8
3
null
2018-08-10 14:33:11.64 UTC
8
2021-09-17 04:35:18.337 UTC
2018-08-13 16:51:46.987 UTC
null
2,074,605
null
2,074,605
null
1
46
java|spring|logging|spring-security|exception-handling
30,146
<p>It turns out that although <code>HttpFirewall</code> and <code>StrictHttpFirewall</code> contain several design errors (documented in the code below), it is just barely possible to escape Spring Security's <em>One True Firewall</em> and tunnel the <code>HttpFirewall</code> information via a request attribute to a <code>HandlerInterceptor</code> that can pass these flagged requests to a <em>real</em> (persistent) firewall without sacrificing the original business logic that flagged them in the first place. The method documented here should be fairly future-proof, as it conforms to a simple contract from the <code>HttpFirewall</code> interface, and the rest is simply the core Spring Framework and Java Servlet API.</p> <p>This is essentially a more complicated but more complete alternative to <a href="https://stackoverflow.com/a/51792347/2074605">my earlier answer</a>. In this answer, I implemented a new subclass of <code>StrictHttpFirewall</code> that intercepts and logs rejected requests at a specific logging level, but also adds an attribute to the HTTP request that flags it for downstream filters (or controllers) to handle. Also, this <code>AnnotatingHttpFirewall</code> provides an <code>inspect()</code> method that allows subclasses to add custom rules for blocking requests.</p> <p>This solution is split into two parts: (1) <em>Spring Security</em> and (2) <em>Spring Framework (Core)</em>, because that is the divide that caused this problem in the first place, and this shows how to bridge it. </p> <p>For reference, this is tested on Spring 4.3.17 and Spring Security 4.2.6. There may be significant changes when Spring 5.1 is released.</p> <hr> <p><strong>Part 1: Spring Security</strong></p> <p>This is the half of the solution that performs the logging and flagging within Spring Security.</p> <hr> <p><strong>AnnotatingHttpFirewall.java</strong></p> <pre><code>import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.web.firewall.FirewalledRequest; import org.springframework.security.web.firewall.RequestRejectedException; import org.springframework.security.web.firewall.StrictHttpFirewall; /** * Overrides the StrictHttpFirewall to log some useful information about blocked requests. */ public class AnnotatingHttpFirewall extends StrictHttpFirewall { /** * The name of the HTTP header representing a request that has been rejected by this firewall. */ public static final String HTTP_HEADER_REQUEST_REJECTED_FLAG = "X-HttpFirewall-RequestRejectedFlag"; /** * The name of the HTTP header representing the reason a request has been rejected by this firewall. */ public static final String HTTP_HEADER_REQUEST_REJECTED_REASON = "X-HttpFirewall-RequestRejectedReason"; /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(AnnotatingHttpFirewall.class.getName()); /** * Default constructor. */ public AnnotatingHttpFirewall() { super(); return; } /** * Provides the request object which will be passed through the filter chain. * * @param request The original HttpServletRequest. * @returns A FirewalledRequest (required by the HttpFirewall interface) which * inconveniently breaks the general contract of ServletFilter because * we can't upcast this to an HttpServletRequest. This prevents us * from re-wrapping this using an HttpServletRequestWrapper. */ @Override public FirewalledRequest getFirewalledRequest(final HttpServletRequest request) { try { this.inspect(request); // Perform any additional checks that the naive "StrictHttpFirewall" misses. return super.getFirewalledRequest(request); } catch (RequestRejectedException ex) { final String requestUrl = request.getRequestURL().toString(); // Override some of the default behavior because some requests are // legitimate. if (requestUrl.contains(";jsessionid=")) { // Do not block non-cookie serialized sessions. Google's crawler does this often. } else { // Log anything that is blocked so we can find these in the catalina.out log. // This will give us any information we need to make // adjustments to these special cases and see potentially // malicious activity. if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Intercepted RequestBlockedException: Remote Host: " + request.getRemoteHost() + " User Agent: " + request.getHeader("User-Agent") + " Request URL: " + request.getRequestURL().toString()); } // Mark this request as rejected. request.setAttribute(HTTP_HEADER_REQUEST_REJECTED, Boolean.TRUE); request.setAttribute(HTTP_HEADER_REQUEST_REJECTED_REASON, ex.getMessage()); } // Suppress the RequestBlockedException and pass the request through // with the additional attribute. return new FirewalledRequest(request) { @Override public void reset() { return; } }; } } /** * Provides the response which will be passed through the filter chain. * This method isn't extensible because the request may already be committed. * Furthermore, this is only invoked for requests that were not blocked, so we can't * control the status or response for blocked requests here. * * @param response The original HttpServletResponse. * @return the original response or a replacement/wrapper. */ @Override public HttpServletResponse getFirewalledResponse(final HttpServletResponse response) { // Note: The FirewalledResponse class is not accessible outside the package. return super.getFirewalledResponse(response); } /** * Perform any custom checks on the request. * This method may be overridden by a subclass in order to supplement or replace these tests. * * @param request The original HttpServletRequest. * @throws RequestRejectedException if the request should be rejected immediately. */ public void inspect(final HttpServletRequest request) throws RequestRejectedException { final String requestUri = request.getRequestURI(); // path without parameters // final String requestUrl = request.getRequestURL().toString(); // full path with parameters if (requestUri.endsWith("/wp-login.php")) { throw new RequestRejectedException("The request was rejected because it is a vulnerability scan."); } if (requestUri.endsWith(".php")) { throw new RequestRejectedException("The request was rejected because it is a likely vulnerability scan."); } return; // The request passed all custom tests. } } </code></pre> <hr> <p><strong>WebSecurityConfig.java</strong></p> <p>In <code>WebSecurityConfig</code>, set the HTTP firewall to the <code>AnnotatingHttpFirewall</code>.</p> <pre><code>@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { /** * Default constructor. */ public WebSecurityConfig() { super(); return; } @Override public final void configure(final WebSecurity web) throws Exception { super.configure(web); web.httpFirewall(new AnnotatingHttpFirewall()); // Set the custom firewall. return; } } </code></pre> <hr> <p><strong>Part 2: Spring Framework</strong></p> <p>The second part of this solution could conceivably be implemented as a <code>ServletFilter</code> or <code>HandlerInterceptor</code>. I'm going the path of a <code>HandlerInterceptor</code> because it seems to give the most flexibility and works directly within the Spring Framework.</p> <hr> <p><strong>RequestBlockedException.java</strong></p> <p>This custom exception can be handled by an Error Controller. This may be extended to add any request headers, parameters or properties available from the raw request (even the full request itself) that may be pertinent to application business logic (e.g., a persistent firewall).</p> <pre><code>/** * A custom exception for situations where a request is blocked or rejected. */ public class RequestBlockedException extends RuntimeException { private static final long serialVersionUID = 1L; /** * The requested URL. */ private String requestUrl; /** * The remote address of the client making the request. */ private String remoteAddress; /** * A message or reason for blocking the request. */ private String reason; /** * The user agent supplied by the client the request. */ private String userAgent; /** * Creates a new Request Blocked Exception. * * @param reqUrl The requested URL. * @param remoteAddr The remote address of the client making the request. * @param userAgent The user agent supplied by the client making the request. * @param message A message or reason for blocking the request. */ public RequestBlockedException(final String reqUrl, final String remoteAddr, final String userAgent, final String message) { this.requestUrl = reqUrl; this.remoteAddress = remoteAddr; this.userAgent = userAgent; this.reason = message; return; } /** * Gets the requested URL. * * @return A URL. */ public String getRequestUrl() { return this.requestUrl; } /** * Gets the remote address of the client making the request. * * @return A remote address. */ public String getRemoteAddress() { return this.remoteAddress; } /** * Gets the user agent supplied by the client making the request. * * @return A user agent string. */ public String getUserAgent() { return this.userAgent; } /** * Gets the reason for blocking the request. * * @return A message or reason for blocking the request. */ public String getReason() { return this.reason; } } </code></pre> <hr> <p><strong>FirewallInterceptor.java</strong></p> <p>This interceptor is invoked after the Spring Security filters have run (i.e., after <code>AnnotatingHttpFirewall</code> has flagged requests that should be rejected. This interceptor detects those flags (attributes) on the request and raises a custom exception that our Error Controller can handle.</p> <pre><code>import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** * Intercepts requests that were flagged as rejected by the firewall. */ public final class FirewallInterceptor implements HandlerInterceptor { /** * Default constructor. */ public FirewallInterceptor() { return; } @Override public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { if (Boolean.TRUE.equals(request.getAttribute(AnnotatingHttpFirewall.HTTP_HEADER_REQUEST_REJECTED))) { // Throw a custom exception that can be handled by a custom error controller. final String reason = (String) request.getAttribute(AnnotatingHttpFirewall.HTTP_HEADER_REQUEST_REJECTED_REASON); throw new RequestRejectedByFirewallException(request.getRequestURL().toString(), request.getRemoteAddr(), request.getHeader(HttpHeaders.USER_AGENT), reason); } return true; // Allow the request to proceed normally. } @Override public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception { return; } @Override public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception { return; } } </code></pre> <hr> <p><strong>WebConfig.java</strong></p> <p>In <code>WebConfig</code>, add the <code>FirewallInterceptor</code> to the registry.</p> <pre><code>@EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { /** * Among your other methods in this class, make sure you register * your Interceptor. */ @Override public void addInterceptors(final InterceptorRegistry registry) { // Register firewall interceptor for all URLs in webapp. registry.addInterceptor(new FirewallInterceptor()).addPathPatterns("/**"); return; } } </code></pre> <hr> <p><strong>ErrorController.java</strong></p> <p>This specifically handles the custom exception above, and produces a clean error page for the client while logging all of the relevant information and invoking any special business logic for a custom application firewall.</p> <pre><code>import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.web.servlet.NoHandlerFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import RequestBlockedException; @ControllerAdvice public final class ErrorController { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(ErrorController.class.getName()); /** * Generates an Error page by intercepting exceptions generated from AnnotatingHttpFirewall. * * @param request The original HTTP request. * @param ex A RequestBlockedException exception. * @return The tile definition name for the page. */ @ExceptionHandler(RequestBlockedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public String handleRequestBlockedException(final RequestBlockedException ex) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Rejected request from " + ex.getRemoteAddress() + " for [" + ex.getRequestUrl() + "]. Reason: " + ex.getReason()); } // Note: Perform any additional business logic or logging here. return "errorPage"; // Returns a nice error page with the specified status code. } /** * Generates a Page Not Found page. * * @param ex A NoHandlerFound exception. * @return The tile definition name for the page. */ @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public String handleException(final NoHandlerFoundException ex) { return "notFoundPage"; } } </code></pre> <hr> <p><strong>FirewallController.java</strong></p> <p>A controller with a default mapping that throws a <code>NoHandlerFoundException</code>. This circumvents the chicken-and-egg strategy in <a href="https://github.com/spring-projects/spring-framework/blob/master/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java" rel="noreferrer">DispatcherServlet.noHandlerFound</a>, allowing that method to <em>always</em> find a mapping so that <code>FirewallInterceptor.preHandle</code> is always invoked. This gives <code>RequestRejectedByFirewallException</code> priority over <code>NoHandlerFoundException</code>.</p> <p>Why this is necessary:</p> <p>As mentioned <a href="https://stackoverflow.com/a/31790661/2074605">here</a>, when a <code>NoHandlerFoundException</code> is thrown from <code>DispatcherServlet</code> (i.e., when a requested URL has no corresponding mapping), there is no way to handle the exceptions generated from the above firewall (<code>NoHandlerFoundException</code> is thrown prior to invoking <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html#preHandle-javax.servlet.http.HttpServletRequest-javax.servlet.http.HttpServletResponse-java.lang.Object-" rel="noreferrer">preHandle()</a>), so those requests will fall through to your 404 view (which is not the desired behavior in my case - you will see a lot of "No mapping found for HTTP request with URI..." messages). This could be fixed by moving the check for the special header into the <code>noHandlerFound</code> method. Unfortunately, there is no way to do this without writing a new Dispatcher Servlet from scratch, and then you may as well throw out the entire Spring Framework. It is impossible to extend <code>DispatcherServlet</code> due to the mix of protected, private and final methods, and the fact that its properties are inaccessible (no getters or setters). It is also impossible to wrap the class because there is no common interface that can be implemented. The default mapping in this class provides an elegant way to circumvent all of that logic.</p> <p><strong>Important caveat</strong>: The RequestMapping below will prevent resolution of static resources because it takes precedence over all registered ResourceHandlers. I am still looking for a workaround for this, but one possibility might be to try one of the methods for handling static resources suggested in <a href="https://stackoverflow.com/a/40563813/2074605">this answer</a>.</p> <pre><code>import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.NoHandlerFoundException; @Controller public final class FirewallController { /** * The name of the model attribute (or request parameter for advertisement click tracking) that contains the request URL. */ protected static final String REQUEST_URL = "requestUrl"; /** * The name of the model attribute that contains the request method. */ protected static final String REQUEST_METHOD = "requestMethod"; /** * The name of the model attribute that contains all HTTP headers. */ protected static final String REQUEST_HEADERS = "requestHeaders"; /** * Default constructor. */ public FirewallController() { return; } /** * Populates the request URL model attribute from the HTTP request. * * @param request The HTTP request. * @return The request URL. */ @ModelAttribute(REQUEST_URL) public final String getRequestURL(final HttpServletRequest request) { return request.getRequestURL().toString(); } /** * Populates the request method from the HTTP request. * * @param request The HTTP request. * @return The request method (GET, POST, HEAD, etc.). */ @ModelAttribute(REQUEST_METHOD) public final String getRequestMethod(final HttpServletRequest request) { return request.getMethod(); } /** * Gets all headers from the HTTP request. * * @param request The HTTP request. * @return The request headers. */ @ModelAttribute(REQUEST_HEADERS) public final HttpHeaders getRequestHeaders(final HttpServletRequest request) { return FirewallController.headers(request); } /** * A catch-all default mapping that throws a NoHandlerFoundException. * This will be intercepted by the ErrorController, which allows preHandle to work normally. * * @param requestMethod The request method. * @param requestUrl The request URL. * @param requestHeaders The request headers. * @throws NoHandlerFoundException every time this method is invoked. */ @RequestMapping(value = "/**") // NOTE: This prevents resolution of static resources. Still looking for a workaround for this. public void getNotFoundPage(@ModelAttribute(REQUEST_METHOD) final String requestMethod, @ModelAttribute(REQUEST_URL) final String requestUrl, @ModelAttribute(REQUEST_HEADERS) final HttpHeaders requestHeaders) throws NoHandlerFoundException { throw new NoHandlerFoundException(requestMethod, requestUrl, requestHeaders); } /** * Gets all headers from a HTTP request. * * @param request The HTTP request. * @return The request headers. */ public static HttpHeaders headers(final HttpServletRequest request) { final HttpHeaders headers = new HttpHeaders(); for (Enumeration&lt;?&gt; names = request.getHeaderNames(); names.hasMoreElements();) { final String headerName = (String) names.nextElement(); for (Enumeration&lt;?&gt; headerValues = request.getHeaders(headerName); headerValues.hasMoreElements();) { headers.add(headerName, (String) headerValues.nextElement()); } } return headers; } } </code></pre> <hr> <p><strong>Results</strong></p> <p>When both parts of this are working, you'll see the following two warnings logged (the first one is in Spring Security, the second one is the Spring Framework (Core) <code>ErrorController</code>). Now you have full control over logging, and an extensible application firewall that you can adjust however you need.</p> <pre><code>Sep 12, 2018 10:24:37 AM com.mycompany.spring.security.AnnotatingHttpFirewall getFirewalledRequest WARNING: Intercepted org.springframework.security.web.firewall.RequestRejectedException: Remote Host: 0:0:0:0:0:0:0:1 User Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0 Request URL: http://localhost:8080/webapp-www-mycompany-com/login.php Sep 12, 2018 10:24:37 AM com.mycompany.spring.controller.ErrorController handleException WARNING: Rejected request from 0:0:0:0:0:0:0:1 for [http://localhost:8080/webapp-www-mycompany-com/login.php]. Reason: The request was rejected because it is a likely vulnerability scan. </code></pre>
39,503,876
How to get the value from ion-select option
<p>I have an array of object called <strong>options</strong>.</p> <p>this is my html code </p> <pre><code> &lt;ion-item&gt; &lt;ion-label&gt;place&lt;/ion-label&gt; &lt;ion-select [(ngModel)]="place" (click)="optionsFn(item);"&gt; &lt;ion-option value="item" *ngFor="let item of options"&gt;{{item.name}} &amp;nbsp;&amp;nbsp;{{item.price}}&lt;/ion-option&gt; &lt;/ion-select&gt; &lt;/ion-item&gt; {{salespriceOp}} {{quantityOp}} </code></pre> <p>this is my .ts file code</p> <pre><code>product_option_value_idOp priceOp salespriceOp quantityOp skuOp nameOp options = [ { "product_option_value_id": "45", "name": "Bangalore Auto", "quantity": "12", "sku": "56876", "price": "100.00", "salesprice": "50" }, { "product_option_value_id": "51", "name": "Hyderabad Auto", "quantity": "23", "sku": "56543", "price": "200.00", "salesprice": "60" }, { "product_option_value_id": "52", "name": "Delhi Auto", "quantity": "14", "sku": "98767", "price": "300.00", "salesprice": "80" } ]; constructor(public navCtrl: NavController) { } optionsFn(item) {//here item is an object console.log(item); this.product_option_value_idOp = item.product_option_value_id; this.priceOp = item.price; this.salespriceOp = item.salesprice; this.quantityOp = item.quantity; this.skuOp = item.sku; this.nameOp = item.name; } </code></pre> <blockquote> <p>i am able to invoke the function but i am getting undefined in <code>console.log(item)</code></p> </blockquote>
39,507,608
6
5
null
2016-09-15 05:46:22.663 UTC
5
2021-05-01 11:35:10.333 UTC
2018-08-24 08:36:25.413 UTC
null
3,915,438
null
5,218,360
null
1
19
angular|typescript|ionic-framework|ionic2|ionic3
62,501
<p>There were several things that together caused that error. The first change there is that instead of using the <code>click</code> event like this:</p> <pre><code>(click)="optionsFn(item); </code></pre> <p>You should use the <code>ionChange</code> event that Ionic exposes like this:</p> <pre><code>(ionChange)="optionsFn();" </code></pre> <p>Also notice that since you use the <code>[(ngModel)]="place"</code> to bind the select element to one of your component's properties, you don't need to send the item as a parameter, because <code>this.place</code> will be the selected item when the <code>ionChange</code> event is triggered.</p> <p>That's why your <code>optionsFn</code> method would look like this:</p> <pre><code>public optionsFn(): void { //here item is an object console.log(this.place); let item = this.place; // Just did this in order to avoid changing the next lines of code :P this.product_option_value_idOp = item.product_option_value_id; this.priceOp = item.price; this.salespriceOp = item.salesprice; this.quantityOp = item.quantity; this.skuOp = item.sku; this.nameOp = item.name; } </code></pre>
24,107,288
Creating an SVG DOM element from a String
<p>How would I go about creating an SVG DOM element from a <code>String</code>?</p> <p>Example:</p> <pre><code>var svgStr = '&lt;svg width="500" height="400" xmlns="http://www.w3.org/2000/svg"&gt;&lt;!-- Created with Method Draw - http://github.com/duopixel/Method-Draw/ --&gt;&lt;g&gt;&lt;title&gt;background&lt;/title&gt;&lt;rect fill="#fff" id="canvas_background" height="402" width="502" y="-1" x="-1"/&gt;&lt;g display="none" overflow="visible" y="0" x="0" height="100%" width="100%" id="canvasGrid"&gt;&lt;rect fill="url(#gridpattern)" stroke-width="0" y="0" x="0" height="100%" width="100%"/&gt;&lt;/g&gt;&lt;/g&gt;&lt;g&gt;&lt;title&gt;Layer 1&lt;/title&gt;&lt;path id="svg_1" d="m118,242l64,-153l63,157c0,0 45,-71 49,-68c4,3 11,146 12,146c1,0 -173,-7 -173,-7c0,0 -61,-72 -61,-72c0,0 110,-156 46,-3z" fill-opacity="0.7" stroke-width="2" stroke="#995757" fill="#995757"/&gt;&lt;/g&gt;&lt;/svg&gt;'; </code></pre>
24,109,000
6
3
null
2014-06-08 14:48:04.72 UTC
9
2022-08-23 07:57:13.85 UTC
2020-12-23 05:40:38.89 UTC
null
1,814,486
null
1,814,486
null
1
34
javascript|svg
44,202
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMParser" rel="noreferrer">DOMParser</a> to parse an XML string.</p> <pre><code>var parser = new DOMParser(); var doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml"); </code></pre> <p>The root element for the parsed string will be doc.documentElement</p> <p>For this to work properly cross-browser you'll need to set the html namespace i.e. your string will need to look like this...</p> <pre><code>var svg2='&lt;svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" ... </code></pre>
9,228,542
Java - How to add a JOptionPane for Yes and No options
<p>So, I've read the Java API, but still can't seem to make heads or tails about how to do this. And believe me I have tried. I want an ActionListener to cause a message box with the text 'Do you really want to exit?', with options yes and no which exits the program or not depending on the selected button.</p> <p>Here's what I have for the ActionListener before I started to break it with the message box:</p> <pre><code>exitItem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent arg0) { window.dispose(); } } ); </code></pre> <p>How can I suitably change it to meet my requirements?</p>
9,228,613
4
2
null
2012-02-10 13:30:20.443 UTC
null
2017-08-25 09:20:20.693 UTC
2012-02-10 13:32:45.713 UTC
null
584,862
null
835,084
null
1
4
java|swing|actionlistener|joptionpane
46,001
<p>I think you want to do something like this inside your <code>ActionListener</code>:</p> <pre><code>int selectedOption = JOptionPane.showConfirmDialog(null, "Do you wanna close the window?", "Choose", JOptionPane.YES_NO_OPTION); if (selectedOption == JOptionPane.YES_OPTION) { window.dispose(); } </code></pre>
16,138,998
How exactly does a XOR Linked list work?
<p>The following <a href="http://www.geeksforgeeks.org/xor-linked-list-a-memory-efficient-doubly-linked-list-set-1/"> link </a> explains it.<br/> The implementation is said to work by storing the XOR of the previous and next address(say nxp), instead of storing both(previous and next address) separately.However, further along the implementation is said to work by <strong>xor-ing</strong> the previous address and nxp, in order to get the <em>next address</em>.</p> <p><br/> But isnt this practically using the <strong>same space</strong> as having previous and next pointers?</p>
16,139,017
5
1
null
2013-04-22 03:32:42.123 UTC
3
2018-07-17 14:12:13.093 UTC
null
null
null
null
919,858
null
1
30
algorithm
17,706
<p>In a doubly linked list, you store two pointers per node: prev and next. In an XOR linked list, you store one 'pointer' per node, which is the XOR of prev and next (or if one of them is absent, just the other (the same as XORing with 0)). The reason why you can still traverse an XOR linked list in both directions relies on the properties of XOR and the redundancy of information inherent in a double linked list.</p> <hr> <p>Imagine you have three nodes in your XOR linked list.</p> <p>A is the head, and has an unobfuscated pointer to B (B XOR 0, next only)</p> <p>B is the middle element, and has the XOR of pointers to A and to C.</p> <p>C is the tail, and an unobfuscated pointer to B (0 XOR B, prev only)</p> <p>When I am iterating over this list, I start at A. I note A's position in memory as I travel to B. When I wish to travel to C, I XOR B's pointer with A, granting me the pointer to C. I then note B's position in memory and travel to C.</p> <p>This works because XOR has the property of undoing itself if applied twice: C XOR A XOR A == C. Another way to think about it is, the doubly linked list stores no extra information a singly linked list does not (since it's just storing all the previous pointers as copies of next pointers somewhere else in memory), so by exploiting this redundancy we can have doubly linked list properties with only as many links as are needed. <strong>However,</strong> This only works if we start our XOR linked list traversal from the start or end — as if we just jump into a random node in the middle, we do not have the information necessary to start traversing.</p> <hr> <p>While an XOR linked list has the advantage of smaller memory usage, it has disadvantages — it will confuse the compiler, debugging and static analysis tools as your XOR of two pointers will not be correctly recognized by a pointer by anything except your code. It also slows down pointer access to have to do the XOR operation to recover the true pointer first. It also can't be used in managed code — XOR obfuscated pointers won't be recognized by the garbage collector.</p>
16,541,676
What are best practices for detecting pixel ratio/density?
<p>I am currently using JavaScript for mobile device detection on my website, this then allows me to serve different content for mobile or desktop users.</p> <p>Currently I use <code>window.devicePixelRatio</code> and <code>screen.width</code> to work out if the user if on a mobile device or not, like so:</p> <pre><code>var isMobileScreenWidth = ((screen.width / window.devicePixelRatio) &lt; 768) </code></pre> <p><code>768px</code> is the point at which we define mobile or desktop so 767 and below is mobile and 768 and above is desktop.</p> <p>This works perfectly, but I have recently come across an issue with Firefox, when Firefox is zoomed in and out it changes the <code>window.devicePixelRatio</code>, so:</p> <pre><code>zoom = 30%, window.devicePixelRatio = 0.3 zoom = 100%, window.devicePixelRatio = 1.0 zoom = 300%, window.devicePixelRatio = 3.0 </code></pre> <p>This now causes me a problem because any users which have their browser zoomed in on Firefox get the mobile version of the site.</p> <p>I was wondering if anyone knew of a different or better way of getting the pixel density which is separate from desktop browsers.</p> <p>I do use a small amount of User Agent detection as well but because it is a massive job to keep up with the constantly changing list of mobile user agents it is not possible for me to depend on both the screen resolution and user agent at the same time.</p> <p>If anyone has any ideas about this and can help that would be awesome.</p> <p>UPDATE:</p> <p>I have just come across this:</p> <pre><code>window.screen.availWidth / document.documentElement.clientWidth </code></pre> <p>This quick bit of math is suggested in this post:</p> <p><a href="https://stackoverflow.com/questions/16383503/window-devicepixelratio-does-not-work-in-ie-10-mobile">window.devicePixelRatio does not work in IE 10 Mobile?</a></p> <p>I have tested it and it work in Firefox, and solves my problem, but, unfortunately now causes a problem in Chrome, so:</p> <pre><code>Chrome zoom = 100%, window.devicePixelRatio = 1.0, window.screen.availWidth / document.documentElement.clientWidth = 3.0 </code></pre> <p>I cannot seem to find a solid solution which works for everything.</p>
17,459,342
2
2
null
2013-05-14 11:11:28.22 UTC
8
2019-02-20 23:06:33.913 UTC
2017-05-23 10:32:45.283 UTC
null
-1
null
2,017,669
null
1
33
javascript|mobile|device-detection|pixel-ratio
52,305
<p>You should leverage the manufacturer's hint via the <code>&lt;meta name="viewport" content="width=device-width"/&gt;</code> or <code>@-ms-viewport {width:device-width}</code> feature. It basically exposes the default zoom the device manufacturer considers optimal given the pixel density of the screen. After you do that, when you call <code>window.innerWidth</code> it will give you what your original equation was intended for but without relying on a measurement of pixel density. </p> <p>Avoid relying on <code>window.devicePixelRatio</code> for anything. Its meaning and the value it returns is currently in a state of flux and anything you make right now based around it will most likely break very soon.</p> <p>Note: Meta viewport only works on Android, iOS, and Windows Phone 8. <code>@-ms-viewport</code> only works (properly) on IE10 Metro and can interfere with proper Meta viewport behavior on Windows Phone 8.</p>
16,275,149
Does ifelse really calculate both of its vectors every time? Is it slow?
<p>Does <code>ifelse</code> really calculate both the <code>yes</code> and <code>no</code> vectors -- as in, the entirety of each vector? Or does it just calculate some values from each vector? </p> <p>Also, is <code>ifelse</code> really that slow? </p>
16,275,201
1
0
null
2013-04-29 09:22:22.44 UTC
23
2015-07-25 20:19:34.473 UTC
2015-02-03 23:57:47.943 UTC
null
202,229
null
1,492,421
null
1
64
r|performance|if-statement|vectorization
3,811
<h3>Yes. (With exception)</h3> <p><code>ifelse</code> calculates both its <code>yes</code> value and its <code>no</code> value. Except in the case where the <code>test</code> condition is either all <code>TRUE</code> or all <code>FALSE</code>. </p> <p>We can see this by generating random numbers and observing how many numbers are actually generated. (by reverting the <code>seed</code>). </p> <pre><code># TEST CONDITION, ALL TRUE set.seed(1) dump &lt;- ifelse(rep(TRUE, 200), rnorm(200), rnorm(200)) next.random.number.after.all.true &lt;- rnorm(1) # TEST CONDITION, ALL FALSE set.seed(1) dump &lt;- ifelse(rep(FALSE, 200), rnorm(200), rnorm(200)) next.random.number.after.all.false &lt;- rnorm(1) # TEST CONDITION, MIXED set.seed(1) dump &lt;- ifelse(c(FALSE, rep(TRUE, 199)), rnorm(200), rnorm(200)) next.random.number.after.some.TRUE.some.FALSE &lt;- rnorm(1) # RESET THE SEED, GENERATE SEVERAL RANDOM NUMBERS TO SEARCH FOR A MATCH set.seed(1) r.1000 &lt;- rnorm(1000) cat("Quantity of random numbers generated during the `ifelse` statement when:", "\n\tAll True ", which(r.1000 == next.random.number.after.all.true) - 1, "\n\tAll False ", which(r.1000 == next.random.number.after.all.false) - 1, "\n\tMixed T/F ", which(r.1000 == next.random.number.after.some.TRUE.some.FALSE) - 1 ) </code></pre> <p><strong>Gives the following output:</strong> </p> <pre><code>Quantity of random numbers generated during the `ifelse` statement when: All True 200 All False 200 Mixed T/F 400 &lt;~~ Notice TWICE AS MANY numbers were generated when `test` had both T &amp; F values present </code></pre> <hr> <h3>We can also see it in the source code itself:</h3> <pre><code>. . if (any(test[!nas])) ans[test &amp; !nas] &lt;- rep(yes, length.out = length(ans))[test &amp; # &lt;~~~~ This line and the one below !nas] if (any(!test[!nas])) ans[!test &amp; !nas] &lt;- rep(no, length.out = length(ans))[!test &amp; # &lt;~~~~ ... are the cluprits !nas] . . </code></pre> <p>Notice that <code>yes</code> and <code>no</code> are computed only if there is some non-<code>NA</code> value of <code>test</code> that is <code>TRUE</code> or <code>FALSE</code> (respectively).<br> At which point -- and this is the imporant part when it comes to efficiency -- <strong><em>the entirety of each vector</em></strong> is computed. </p> <hr> <h3>Ok, but is it slower?</h3> <p>Lets see if we can test it: </p> <pre><code>library(microbenchmark) # Create some sample data N &lt;- 1e4 set.seed(1) X &lt;- sample(c(seq(100), rep(NA, 100)), N, TRUE) Y &lt;- ifelse(is.na(X), rnorm(X), NA) # Y has reverse NA/not-NA setup than X </code></pre> <h3>These two statements generate the same results</h3> <pre><code>yesifelse &lt;- quote(sort(ifelse(is.na(X), Y+17, X-17 ) )) noiflese &lt;- quote(sort(c(Y[is.na(X)]+17, X[is.na(Y)]-17))) identical(eval(yesifelse), eval(noiflese)) # [1] TRUE </code></pre> <h3>but one is twice as fast as the other</h3> <pre><code>microbenchmark(eval(yesifelse), eval(noiflese), times=50L) N = 1,000 Unit: milliseconds expr min lq median uq max neval eval(yesifelse) 2.286621 2.348590 2.411776 2.537604 10.05973 50 eval(noiflese) 1.088669 1.093864 1.122075 1.149558 61.23110 50 N = 10,000 Unit: milliseconds expr min lq median uq max neval eval(yesifelse) 30.32039 36.19569 38.50461 40.84996 98.77294 50 eval(noiflese) 12.70274 13.58295 14.38579 20.03587 21.68665 50 </code></pre>
16,290,873
CSS3 calc(100%-88px) not working in Chrome
<p>I noticed that my usage of the CSS3 <code>calc()</code> function as the unit for <code>width</code> is not working in the latest version of Chrome.</p> <p>In the Chrome Developer tools, the rule with <code>calc()</code> has a <strike>strikethrough</strike> through it and an exclamation mark in a yellow triangle to the left of it. This is signaling that the property or value is not recognized.</p> <p>How do I get it to work in modern browsers? Because it is a value and not a property, where do the vendor prefixes go?</p> <h3>Update:</h3> <p>When I say it doesn't work, I mean that Chrome Dev Tools is saying that it is not recognizing my usage of it <code>width: calc(100%-88px);</code>. How do I know it is not recognizing it? Because of the strikethrough and the yellow triangle icon next to the style rule in chrome dev tools.</p>
16,291,105
4
1
null
2013-04-30 01:34:51.237 UTC
6
2022-09-10 00:28:58.057 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,277,987
null
1
76
google-chrome|css
67,364
<p>The problem in the question was caused by the lack of space around the subtraction operator.</p> <blockquote> <p>Note that the grammar requires spaces around binary ‘+’ and ‘-’ operators. The ‘*’ and ‘/’ operators do not require spaces.</p> </blockquote> <p><a href="https://www.w3.org/TR/css3-values/#calc-syntax" rel="nofollow noreferrer">https://www.w3.org/TR/css3-values/#calc-syntax</a></p> <p><sup>This <a href="https://css-tricks.com/a-complete-guide-to-calc-in-css/#aa-whitespace-matters" rel="nofollow noreferrer">article</a> mentions that the spacing is necessary for unambiguous parsing.</sup></p> <p><strong>Bad:</strong> <code>calc(100%-88px)</code><br /> <strong>Good:</strong> <code>calc(100% - 88px)</code></p> <hr /> <blockquote> <p>How do I know it is not recognizing it? Because of the strikethrough and the yellow triangle icon next to the style rule in chrome dev tools.</p> </blockquote> <p>A property that is <strike>struck</strike> through when viewed in Chrome's developer tools may be valid but overridden; however, a property struck through <em>and</em> with a warning triangle icon next to it is invalid.</p> <hr /> <p>2022 Update - <code>calc()</code> is <a href="https://caniuse.com/calc" rel="nofollow noreferrer">supported</a> by all modern browsers in a wide variety of scenarios, though proper spacing is still required.</p>
16,491,675
How to send custom message in Google C++ Testing Framework?
<p>I use <a href="http://code.google.com/p/googletest/">Google C++ Testing Framework</a> for unit testing of my code. I use <a href="https://github.com/xgsa/cdt-tests-runner/wiki/Tutorial">Eclipse CDT with C++ Unit testing module</a> for output analysis. </p> <p>Previously I used <a href="https://sourceforge.net/projects/cppunit/">CppUnit</a> it has macros family <a href="http://cppunit.sourceforge.net/doc/1.11.6/_test_assert_8h.html">CPPUNIT*_MESSAGE</a> that could be called like this: </p> <pre><code>CPPUNIT_ASSERT_EQUAL_MESSAGE("message",EXPECTED_VALUE,ACTUAL_VALUE) </code></pre> <p>And allows to send custom messages to test output.</p> <p><strong>Is there a way to include some custom text in google test output?</strong></p> <p>(Preferably the way that could include message to data that is read by existing programs for automated unit testing using google test.)</p>
16,491,892
6
0
null
2013-05-10 22:28:50.463 UTC
27
2021-06-16 18:55:09.203 UTC
null
null
null
null
614,735
null
1
110
c++|googletest
71,955
<p>The gtest macros return a stream for outputting diagnostic messages when a test fails.</p> <pre><code>EXPECT_TRUE(false) &lt;&lt; "diagnostic message"; </code></pre>
24,868,273
Run a C# .cs file from a PowerShell Script
<p>I have a <code>PowerShell V2</code> script that moves some files around and installs some services. However I would like to call and run a .cs file about halfway through the PowerShell Script. I have found plenty of articles on calling <code>PowerShell</code> from <code>C#</code> but none the opposite way around. I would just like the C# file to run once then continue running the PowerShell script. </p> <p>If anyone could point me in the direction of an article explaining how to accomplish this or if you know yourself and could help it would be greatly appreciated. </p>
24,868,351
5
5
null
2014-07-21 14:56:30.793 UTC
12
2022-07-15 04:39:34.643 UTC
2017-10-20 11:11:31.507 UTC
null
271,200
null
3,748,732
null
1
33
c#|powershell
36,566
<p>You're looking for the wrong thing. Put your C# into an assembly, and call its public classes, functions and methods from PowerShell, just like you would call the .NET Framework from Powershell.</p> <p>If you really want to compile and run C# source from PowerShell, see <a href="https://devblogs.microsoft.com/scripting/weekend-scripter-run-c-code-from-within-powershell/" rel="nofollow noreferrer">Weekend Scripter: Run C# Code from Within PowerShell</a>. </p>
37,196,734
React' findNodeHandle method stopped working
<p>After upgrade to <em>0.26.0-rc</em> version, this line:</p> <pre><code>React.findNodeHandle(this.refs.myRef) </code></pre> <p>Throws this error message:</p> <blockquote> <p>Unhandled JS Exception: _react2.default.findNodeHandle is not a function.</p> </blockquote> <p>I'm importing React with this:</p> <pre><code>import React from 'react'; </code></pre> <p>Docs <a href="https://facebook.github.io/react-native/docs/nativemethodsmixin.html#measurelayout" rel="noreferrer">still say</a>: <em>"As always, to obtain a native node handle for a component, you can use React.findNodeHandle(component)."</em></p>
37,783,101
3
5
null
2016-05-12 20:22:29.28 UTC
3
2017-08-04 16:50:41.217 UTC
2017-04-20 11:20:12.38 UTC
null
1,206,613
null
1,206,613
null
1
30
javascript|ecmascript-6|react-native|react-native-ios
21,280
<p>Now the function may be used without object:</p> <pre><code>import { ... findNodeHandle, ... } from 'react-native'; </code></pre> <p>And call it directly: </p> <pre><code>findNodeHandle(this.refs[refName]) </code></pre>
27,230,955
How to disable scrolling in the background when the mobile menu is open?
<p>I am building a mobile responsive website that has a nav menu. When I get to the bottom of the menu - If I continue scrolling when I reach the bottom of the menu - it scrolls the page in the background. How can I disable it? </p> <p>This is my jQuery code so far: </p> <pre><code>// When the document is loaded... $(document).ready(function() { $('#mob-menu-btn').click(function(){ $('.sports').slideToggle("slow"); }) $('#sub-menu').click(function(){ $('.sports2').slideToggle("slow"); }) }); </code></pre> <p>and this is my CSS: </p> <pre><code> .list{ width: 100%; overflow: hidden; overflow-y: auto; top: -10%; overflow: hidden; overflow-y: auto; } .sports li{ list-style-image:none; list-style-type: none; border-bottom: 2px solid #eeeeee; margin-bottom: 0px; margin-left: 0px; padding-top: 15px; padding-bottom: 15px; padding-left: 10px; width:100%; font-family: arial; text-decoration: none; overflow: hidden; } </code></pre>
27,263,789
9
7
null
2014-12-01 14:49:06.943 UTC
6
2021-07-31 16:51:02.557 UTC
2014-12-01 15:33:35.913 UTC
null
3,136,031
null
3,802,177
null
1
42
jquery|css
104,658
<p>When a menu is open, set <code>position: fixed</code> on the body, and remove on close.</p> <pre><code> .fixed-position { position: fixed; } if ($('#mob-menu').is(':visible')) { $('body').addClass(&quot;fixed-position&quot;); } else { $('body').removeClass(&quot;fixed-position&quot;); } </code></pre>
62,044,747
"message" field is empty in error response Spring Boot
<p>I have handled unauthorized exception like this</p> <pre><code>@ResponseStatus(value= HttpStatus.UNAUTHORIZED) public class UnauthorizedException extends RuntimeException { public UnauthorizedException(String message) { super(message); } } </code></pre> <p>but when I throw the error as follows</p> <pre><code>throw new UnauthorizedException("Invalid credentials"); </code></pre> <p>I get the error message empty in the response as follows</p> <pre><code>{ "timestamp": "2020-05-27T13:44:58.032+00:00", "status": 401, "error": "Unauthorized", "message": "", "path": "/auth/register" } </code></pre> <p>I tried using,</p> <pre><code>throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid credentials"); </code></pre> <p>but the result is still the same. When I added <em>spring-boot-devtools</em> dependency, I get the message as expected with the stack trace as well. How can I fix this?</p> <p>Spring version : 2.3.0 Java Version: 11.0 </p>
62,069,243
1
3
null
2020-05-27 13:50:16.797 UTC
4
2020-05-28 16:03:27.547 UTC
null
null
null
null
3,724,483
null
1
39
java|spring|spring-boot
7,762
<p>Ok got it, they have changed the default value for server.error.include-message to "never" (see the comment section here: <a href="https://spring.io/blog/2020/05/15/spring-boot-2-3-0-available-now" rel="noreferrer">Spring 2.3.0 Release Info</a></p> <p>All the default values are listed here: <a href="https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/" rel="noreferrer">Spring Boot Reference Documentation</a></p> <p>Just configure your application.yaml (or properties) like this.</p> <pre><code>server: error: include-message: always include-binding-errors: always </code></pre> <p>Mind that showing error messages may leak information about your server implementation.</p>
21,756,433
if or elif either true then do something
<p>this is just for academic interest. I encounter the following situation a lot.</p> <pre><code>either_true = False if x: ...do something1 either_true = True elif y: ...do something2 either_true = True if either_true: ..do something3 </code></pre> <p>is there any pythonic way of doing it, or in general better programming way of doing it. Basically do something3 executes only if or elif is true.</p>
21,764,553
10
8
null
2014-02-13 14:04:12.78 UTC
4
2014-02-21 06:57:15.607 UTC
null
null
null
null
1,572,215
null
1
46
python|python-2.7
3,082
<p>Your code is <em>almost</em> optimal, as far as code repetition and evaluation are concerned. The only thing I can think of to avoid repetition would be:</p> <pre><code># be optimistic! either_true = True if x: do_something1 elif y: do_something2 else: either_true = False if either_true: do_something3 </code></pre> <p>This removes one assignment, although the total number of lines doesn't change.</p> <p>The advantage is that this works with <code>n</code> conditions, without adding any other assignment, while your current solution requires an <code>either_true = True</code> for every condition.</p> <p>In my opinion they have about the same degree of readability, but the above code will be better with more conditions.</p> <p>Also there's no "pythonic" way other then a readable solution that avoids code repetition and is optimal in terms of efficiency, and I don't know of any kind of "better programming" to achieve the same result.</p>
17,334,014
Move files to directories based on extension
<p>I am new to Linux. I am trying to write a shell script which will <strong>move files to certain folders based on their extension</strong>, like for example in my downloads folder, I have all files of mixed file types. I have written the following script</p> <pre><code>mv *.mp3 ../Music mv *.ogg ../Music mv *.wav ../Music mv *.mp4 ../Videos mv *.flv ../Videos </code></pre> <p>How can I make it run automatically when a file is added to this folder? Now I have to manually run the script each time.</p> <p>One more question, is there any way of combining these 2 statements</p> <pre><code>mv *.mp3 ../../Music mv *.ogg ../../Music </code></pre> <p>into a single statement? I tried using <code>||</code> (C programming 'or' operator) and comma but they don't seem to work.</p>
17,334,054
6
2
null
2013-06-27 03:23:28.813 UTC
12
2020-04-14 09:46:13.353 UTC
2013-06-27 03:41:36.817 UTC
null
1,091,386
null
2,526,437
null
1
35
linux|shell
68,623
<p>There is no trigger for when a file is added to a directory. If the file is uploaded via a webpage, you might be able to make the webpage do it.</p> <p>You can put a script in crontab to do this, on unix machines (or task schedular in windows). Google crontab for a how-to.</p> <p>As for combining your commands, use the following:</p> <pre><code>mv *.mp3 *.ogg ../../Music </code></pre> <p>You can include as many different "globs" (filenames with wildcards) as you like. The last thing should be the target directory.</p>
17,578,820
Accessing outer class variable in inner class
<p>In inner classes, variables of outer class are accessible, but local variables of a method are not. I understood the part about local variables of a method not being accessible but I want to know why outer class variables are accessible? </p> <p>My understanding is that as an inner class binds with the outer class, so as long as the parent is available, the child can access its parent variables. Am I correct?</p>
17,578,924
2
4
null
2013-07-10 19:00:51.943 UTC
14
2016-02-10 11:57:45.393 UTC
2015-03-21 17:11:36.893 UTC
null
3,681,282
null
1,395,771
null
1
35
java|inner-classes
48,689
<p>Assuming your outer class is called <code>Outer</code>, from the scope of the inner class(non-static), <code>Outer.this.foo</code> to get at the field.</p> <p>For example,</p> <pre><code>Outer.this.foo=new ArrayList&lt;&gt;(); </code></pre> <p>where Outer is the name of the class and <code>foo</code> identifies the field.</p> <p>You can also grab it directly as <code>foo=new Baz()</code> but it'll pick the inner field if there's a naming conflict due to shadowing.</p> <p>if it's a static inner class, you need an explicit instance:</p> <pre><code>outerInstance.foo=new ArrayList&lt;&gt;(); </code></pre> <p>or if the field to access is static, access it as usual with:</p> <pre><code>Outer.staticFoo=new ArrayList&lt;&gt;(); </code></pre>
17,411,101
How to display percentage complete in Robocopy?
<p>Is there a way to show the percentage completed in Robocopy? I am running with /NDL and /NFL, but I would like to see the overall percentage... is this possible?</p>
17,411,204
2
2
null
2013-07-01 18:22:08.503 UTC
3
2019-05-11 22:49:21.747 UTC
null
null
null
null
1,143,724
null
1
42
command-line|robocopy
84,673
<p>I haven't found a way to do so. Instead I use PowerShell to do the copy and track progress.</p> <p>This might be of use: <a href="https://stackoverflow.com/questions/13883404/custom-robocopy-progress-bar-in-powershell">Custom RoboCopy Progress Bar in PowerShell</a></p>
17,181,849
Placeholder Mixin SCSS/CSS
<p>I'm trying to create a mixin for placeholders in sass. </p> <p>This is the mixin I've created.</p> <pre><code>@mixin placeholder ($css) { ::-webkit-input-placeholder {$css} :-moz-placeholder {$css} ::-moz-placeholder {$css} :-ms-input-placeholder {$css} } </code></pre> <p>This is how I'd like to include the mixin:</p> <pre><code>@include placeholder(font-style:italic; color: white; font-weight:100;); </code></pre> <p>Obviously this isn't going to work because of all the colons and semi-colons that's being passed through to the mixin, but... I'd really like to just input static css and pass it through exactly like the above function. </p> <p>Is this possible? </p>
17,181,946
6
0
null
2013-06-19 02:09:59.4 UTC
44
2019-04-24 02:07:33.803 UTC
null
null
null
null
1,683,943
null
1
133
css|sass
124,405
<p>You're looking for the <code>@content</code> directive:</p> <pre><code>@mixin placeholder { ::-webkit-input-placeholder {@content} :-moz-placeholder {@content} ::-moz-placeholder {@content} :-ms-input-placeholder {@content} } @include placeholder { font-style:italic; color: white; font-weight:100; } </code></pre> <p>SASS Reference has more information, which can be found here: <a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixin-content">http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixin-content</a></p> <hr> <p>As of Sass 3.4, this mixin can be written like so to work both nested and unnested:</p> <pre><code>@mixin optional-at-root($sel) { @at-root #{if(not &amp;, $sel, selector-append(&amp;, $sel))} { @content; } } @mixin placeholder { @include optional-at-root('::-webkit-input-placeholder') { @content; } @include optional-at-root(':-moz-placeholder') { @content; } @include optional-at-root('::-moz-placeholder') { @content; } @include optional-at-root(':-ms-input-placeholder') { @content; } } </code></pre> <p>Usage:</p> <pre><code>.foo { @include placeholder { color: green; } } @include placeholder { color: red; } </code></pre> <p>Output:</p> <pre><code>.foo::-webkit-input-placeholder { color: green; } .foo:-moz-placeholder { color: green; } .foo::-moz-placeholder { color: green; } .foo:-ms-input-placeholder { color: green; } ::-webkit-input-placeholder { color: red; } :-moz-placeholder { color: red; } ::-moz-placeholder { color: red; } :-ms-input-placeholder { color: red; } </code></pre>
17,329,495
how to use ng-option to set default value of select element
<p>I've seen the documentation of the Angular select directive here: <a href="http://docs.angularjs.org/api/ng.directive:select">http://docs.angularjs.org/api/ng.directive:select</a>. I can't figure how to set the default value. This is confusing: </p> <blockquote> <p>select as label for value in array</p> </blockquote> <p>Here is the object:</p> <pre><code>{ "type": "select", "name": "Service", "value": "Service 3", "values": [ "Service 1", "Service 2", "Service 3", "Service 4"] } </code></pre> <p>The html (working): </p> <pre><code>&lt;select&gt;&lt;option ng-repeat="value in prop.values"&gt;{{value}}&lt;/option&gt;&lt;/select&gt; </code></pre> <p>and then I'm trying to add an ng-option attribute inside the select element to set <code>prop.value</code> as the default option (not working).</p> <pre><code>ng-options="(prop.value) for v in prop.values" </code></pre> <p>What am i doing wrong?</p>
17,329,854
12
0
null
2013-06-26 20:08:02.83 UTC
34
2019-05-14 05:44:59.747 UTC
2016-09-19 13:10:31.707 UTC
null
2,112,538
null
2,112,538
null
1
151
angularjs
428,159
<p>So assuming that object is in your scope:</p> <pre><code>&lt;div ng-controller="MyCtrl"&gt; &lt;select ng-model="prop.value" ng-options="v for v in prop.values"&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>&nbsp;</p> <pre><code>function MyCtrl($scope) { $scope.prop = { "type": "select", "name": "Service", "value": "Service 3", "values": [ "Service 1", "Service 2", "Service 3", "Service 4"] }; } </code></pre> <p>Working Plunkr: <a href="http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g" rel="noreferrer">http://plnkr.co/edit/wTRXZYEPrZJRizEltQ2g</a></p>
30,424,248
Does UL have default margin or padding
<p>This might seem like a dumb question, but I've added an UL to a basic page and the list seems to be off-centered. There's nothing special about the list. No specific css added: just a list. When I load live it's slightly off center.<br> Is there a default margin or padding on the left side?</p> <pre><code>&lt;h3&gt;Title Heading&lt;/h3&gt; &lt;ul id="listItems"&gt; &lt;li&gt;itemOne&lt;/li&gt; &lt;li&gt;itemTwo&lt;/li&gt; &lt;li&gt;itemThree&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>The main body has all the css code for centering, aligning, float, etc. The 'Title Header' align perfectly. Just list is a little off.</p> <p>Thank you.</p> <p>Oh, don't know if this is important, but I added the 'id' cause... wanted to use 'first-of-type' to give 1st item em(bold).</p>
30,424,422
2
2
null
2015-05-24 13:48:56.623 UTC
2
2018-06-06 22:25:58.04 UTC
2018-06-06 22:25:58.04 UTC
null
1,032,372
null
3,607,870
null
1
17
html|css|alignment|html-lists
44,762
<p>The problem is that by default, browsers have custom css - in chrome for example:</p> <pre><code>ul, menu, dir { display: block; list-style-type: disc; -webkit-margin-before: 1em; -webkit-margin-after: 1em; -webkit-margin-start: 0px; -webkit-margin-end: 0px; -webkit-padding-start: 40px; } </code></pre> <p>You'll have to use a custom rule for your <code>ul</code>:</p> <pre><code>element.style { margin-left: 0px; /* set to 0 if your not using a list-style-type */ padding-left: 20px; } </code></pre>
18,392,300
Tool for testing RESTful Web services
<p>I am trying to evaluate the right tool to test RESTful Web services and eventually automate the same for our project. Wondering, what are the specifications I need to look for such test, when i compare various tools on internet.</p> <p>Definitely, one of the requirements would be an Open source tool.</p> <p>I have looked on few tools, such as SOAPUI,RestClient,TestMaker, RestAssured. Wanted to know the pros and cons of them. Also, any ideas or pointers on how to go about it would be of great help.</p>
18,394,784
3
1
null
2013-08-22 23:18:42.653 UTC
6
2016-04-08 14:42:27.537 UTC
null
null
null
null
2,640,248
null
1
18
web-services|rest|soapui|rest-client|rest-assured
40,123
<p>If you need complex parametrized soap and rest webservices testing and test automation, you definetly should try soapui. It is open source (<a href="https://github.com/SmartBear/soapui" rel="nofollow">https://github.com/SmartBear/soapui</a>), free in base edition tool with great documentation. In addition to webservices tests it provide scripting, load testing tool, ide support, web services mocking, running tests from GUI or console and much more. </p>
25,944,968
Check if a OneToOne relation exists in Django
<p>Now I'm using django 1.6</p> <p>I have two models relates with a <code>OneToOneField</code>.</p> <pre><code>class A(models.Model): pass class B(models.Model): ref_a = models.OneToOneField(related_name='ref_b', null=True) </code></pre> <hr> <p>First see my code that points out the problem:</p> <pre><code>a1 = A.objects.create() a2 = A.objects.create() b1 = B.objects.create() b2 = B.objects.create(ref_a=a2) # then I call: print(a1.ref_b) # DoesNotExist Exception raised print(a2.ref_b) # returns b2 print(b1.ref_a) # returns None print(b2.ref_a) # returns a2 </code></pre> <p>Now the problem is, if I want to check a <code>A</code> object, to judge whether it exists a <code>B</code> objects referencing it. How can I do?</p> <p>The valid way I tried is only to try and catch an exception, but is there any other prettier way?</p> <hr> <p>My effort:</p> <p>1 - The below code works, but is too ugly!</p> <pre><code>b = None try: b = a.ref_b except: pass </code></pre> <p>2 - I also tried to check the attributes in a, but not working:</p> <pre><code>b = a.ref_b if hasattr(a, 'ref_b') else None </code></pre> <hr> <p>Do you meet the same problem, friends? Please point me a way, thank you!</p>
27,042,585
3
3
null
2014-09-20 03:44:09.863 UTC
4
2018-07-04 09:34:14.267 UTC
null
null
null
null
2,544,762
null
1
31
python|django|model|one-to-one
22,297
<p>So you have a least two ways of checking that. First is to create try/catch block to get attribute, second is to use <code>hasattr</code>.</p> <pre><code>class A(models.Model): def get_B(self): try: return self.b except: return None class B(models.Model): ref_a = models.OneToOneField(related_name='ref_b', null=True) </code></pre> <p>Please try to avoid bare <code>except:</code> clauses. It can hide some <a href="https://stackoverflow.com/q/14797375/542196">problems</a>.</p> <p>The second way is:</p> <pre><code>class A(models.Model): def get_B(self): if(hasattr(self, 'b')): return self.b return None class B(models.Model): ref_a = models.OneToOneField(related_name='ref_b', null=True) </code></pre> <p>In both cases you can use it without any exceptions:</p> <pre><code>a1 = A.objects.create() a2 = A.objects.create() b1 = B.objects.create() b2 = B.objects.create(ref_a=a2) # then I call: print(a1.get_b) # No exception raised print(a2.get_b) # returns b2 print(b1.a) # returns None print(b2.a) # returns a2 </code></pre> <p>There is no other way, as throwing the exception is default behaviour from Django <a href="https://docs.djangoproject.com/en/1.7/topics/db/examples/one_to_one/" rel="noreferrer">One to One relationships</a>.</p> <p>And this is the example of handling it from official documentation.</p> <pre><code>&gt;&gt;&gt; from django.core.exceptions import ObjectDoesNotExist &gt;&gt;&gt; try: &gt;&gt;&gt; p2.restaurant &gt;&gt;&gt; except ObjectDoesNotExist: &gt;&gt;&gt; print("There is no restaurant here.") There is no restaurant here. </code></pre>
26,433,285
How to solve "The certificate is not valid and cannot be used to verify the identity of this website" error?
<p>The question is, <strong>How to solve "The certificate is not valid and cannot be used to verify the identity of this website" error?</strong>.</p> <p>Here are the details:</p> <p>I have a signed applet that has been working fine, until I updated Java to 8u25 (1.8.0_25-b18). Now, the application shows an alert message "Do you want to continue? The connection to this website is untrusted". There is a note in this message too, "<code>The certificate is not valid and cannot be used to verify the identity of this website</code>".</p> <p>The applet is loaded without problems. But when the user tries to use a specific function of that application, the warning message is displayed.</p> <p>I've checked the java console when this happens, and this warning message is displayed right after these lines:</p> <pre><code>security: Obtain certificate collection in SSL Root CA certificate store security: Invalid certificate from HTTPS server network: Cache entry not found [url: https://sub.domain.net:9876, version: null] </code></pre> <p>The application is downloaded from a different domain, say "<a href="https://app.domain.net/" rel="noreferrer">https://app.domain.net/</a>.....", so no jars are downloaded from "<a href="https://sub.domain.net:9876" rel="noreferrer">https://sub.domain.net:9876</a>", but the applet connects to "<a href="https://sub.domain.net:9876" rel="noreferrer">https://sub.domain.net:9876</a>" to send/receive data.</p> <p>The applet is signed correctly, and so far, it meets all the security requirements according to Java. This issue seems to happen when the application tries to connect internally with an HTTPS url like <code>https://sub.domain.net:9876</code>. That sites' SSL certificate is valid, issued by GoDaddy and has not expired.</p> <p>Again, this started to happen after updating my JRE to 8u25. I've tested adding the offending URL to Java security exception list, with no success.</p> <p>Here are a few screenshot of this problem:</p> <p>This is the warning message displayed: <img src="https://i.stack.imgur.com/fMdYC.png" alt="Warning message"> <img src="https://i.stack.imgur.com/8XdAz.png" alt="More information about the warning message"> <img src="https://i.stack.imgur.com/uyH4D.png" alt="Certificate basic information 1"> <img src="https://i.stack.imgur.com/UqHKn.png" alt="Certificate basic information 2"></p> <hr> <p><strong>Edit 10/18/2014:</strong></p> <p>Question posted in "Oracle Community" too, to increase answer options: <a href="https://community.oracle.com/message/12684985" rel="noreferrer">Question in Oracle Community</a>.</p> <hr> <p><strong>Edit 10/21/2014:</strong></p> <p>I noticed this: When I click the link "More Information" displayed in the "Security Warning" dialog, the reason displayed says:</p> <blockquote> <p>The application is being downloaded from a site other than the one specified by the security certificate.</p> <ul> <li><p>Downloading from "sub.domain.net"</p></li> <li><p>Expecting "*.DOMAIN.NET"</p></li> </ul> </blockquote> <p>This message says the application is BEING DOWNLOADED FROM "sub.domain.com", and that is false. The application (applet) is already downloaded, and it is only using that domain in an internal HTTPS request, to get/send business data, not to download additional Jars, JNLPs, etc.</p>
26,518,823
2
3
null
2014-10-17 20:53:22.673 UTC
4
2018-08-30 16:56:47.073 UTC
2014-10-21 06:30:29.643 UTC
null
524,725
null
524,725
null
1
7
java|security|ssl|applet|ssl-certificate
91,059
<p>I found how to solve this issue, and thanks to <a href="https://stackoverflow.com/users/3081018/steffen-ullrich">Steffen Ullrich</a> for a valid proposal. </p> <p>This is related to the <strong>certificate's Common Name (CN)</strong> value. In my case, that value was <code>*.DOMAIN.NET</code>, and to change it to <code>*.domain.net</code>, all we had to do was a procedure called "Domain Transfer". This means, to change the CN to <code>*.REKEY.DOMAIN.NET</code>, and then to change it again to <code>*.domain.net</code>. We could not change it to <code>*.domain.net</code> directly because the certificate provider says <code>*.DOMAIN.NET</code> and <code>*.domain.net</code> are the same. </p> <p>Now, this issue happened only with Java 7.71 and Java 8.25. Previous version of Java 7 and 8 don't have this issue (SSL certificate restrictions for CN in a different casing).</p> <p>Anyway, this solved the issue, and now we receive a gentle information message about the domain:</p> <p><img src="https://i.stack.imgur.com/yUoSO.png" alt="Notification Message after the certificate CN change"></p>
26,184,322
What's the point of Guava checkNotNull
<p>I'm pretty new to Guava (let's be honest, I'm not "pretty new", I'm a complete rookie on that subject) and so I decided to go through some documentation and got quite amazed while reading this:</p> <p><a href="https://google.github.io/guava/releases/23.0/api/docs/com/google/common/base/Preconditions.html#checkNotNull-T-" rel="noreferrer"><code>com.google.common.base.Preconditions.checkNotNull(...)</code></a></p> <p>I don't get the point of this method. This means that instead of doing : </p> <pre><code>myObject.getAnything(); </code></pre> <p><em>(which might cause a <code>NullPointerException</code> if myObject is null)</em></p> <p>I should use</p> <pre><code>checkNotNull(myObject).getAnything(); </code></pre> <p>which <strong>will</strong> throw a <code>NullPointerException</code> if <code>myObject</code> is null and return <code>myObject</code> if it is not null.</p> <p>I'm puzzled and this might be the stupidest question ever but ...</p> <p>What is the point of this? Those two lines do the exact same thing as for outcomes given any situations I can think of.</p> <p>I don't even think that the latter is more readable.</p> <p>So I must be missing something. What is it?</p>
26,184,472
3
3
null
2014-10-03 18:05:50.403 UTC
12
2017-12-23 12:11:11.26 UTC
2017-12-23 12:11:11.26 UTC
null
479,156
null
112,637
null
1
73
java|null|guava|preconditions
45,008
<p>The idea is to fail fast. For instance, consider this silly class:</p> <pre><code>public class Foo { private final String s; public Foo(String s) { this.s = s; } public int getStringLength() { return s.length(); } } </code></pre> <p>Let's say you don't want to allow null values for <code>s</code>. (or else <code>getStringLength</code> will throw a NPE). With the class as-is, by the time you catch that <code>null</code>, it's too late -- it's very hard to find out who put it there. The culprit could well be in a totally different class, and that <code>Foo</code> instance could have been constructed a long time ago. Now you have to comb over your code base to find out who could possibly have put a <code>null</code> value there.</p> <p>Instead, imagine this constructor:</p> <pre><code>public Foo(String s) { this.s = checkNotNull(s); } </code></pre> <p>Now, if someone puts a <code>null</code> in there, you'll find out <em>right away</em> -- and you'll have the stack trace pointing you exactly to the call that went wrong.</p> <hr> <p>Another time this can be useful is if you want to check the arguments before you take actions that can modify state. For instance, consider this class that computes the average of all string lengths it gets:</p> <pre><code>public class StringLengthAverager { private int stringsSeen; private int totalLengthSeen; public void accept(String s) { stringsSeen++; totalLengthSeen += s.length(); } public double getAverageLength() { return ((double)totalLengthSeen) / stringsSeen; } } </code></pre> <p>Calling <code>accept(null)</code> will cause an NPE to get thrown -- but not before <code>stringsSeen</code> has been incremented. This may not be what you want; as a user of the class, I may expect that if it doesn't accept nulls, then its state should be unchanged if you pass a null (in other words: the call should fail, but it shouldn't invalidate the object). Obviously, in this example you could also fix it by getting <code>s.length()</code> before incrementing <code>stringsSeen</code>, but you can see how for a longer and more involved method, it might be useful to first check that all of your arguments are valid, and only then modify state:</p> <pre><code> public void accept(String s) { checkNotNull(s); // that is, s != null is a precondition of the method stringsSeen++; totalLengthSeen += s.length(); } </code></pre>
5,138,077
HTML5 Video - File Loading Complete Event?
<p>I need to detect when a video file has completed loading. I'm thinking I should use progress->buffer, but in the back of my mind, I remember reading that this was unreliable. Is there a better way, or is this safe?</p> <p>Note, I will be keeping a localStorage cache of videos that have been completely downloaded by each user, so I'll know in advance if a video has already loaded, and could probably bypass progress->buffer if that's a sticking point.</p> <p>Thanks in advance.</p>
5,346,549
3
0
null
2011-02-28 04:09:05.167 UTC
13
2018-04-25 01:21:17.983 UTC
null
null
null
null
174,621
null
1
13
javascript|html|video|buffer|preload
20,740
<p>You can bind the "buffered" event, but (in Chrome at least) this works fine except that it doesn't call the last "buffered" event (i.e. it will detect 90%...94%...98%... but won't call on 100%). </p> <p><strong>Note: recent versions of jQuery should use .prop() instead of .attr()</strong></p> <p>To get around this I've used setInterval() to check the buffer every 500ms (where $html5Video is your <code>&lt;video&gt;</code> element:</p> <pre><code>var videoDuration = $html5Video.attr('duration'); var updateProgressBar = function(){ if ($html5Video.attr('readyState')) { var buffered = $html5Video.attr("buffered").end(0); var percent = 100 * buffered / videoDuration; //Your code here //If finished buffering buffering quit calling it if (buffered &gt;= videoDuration) { clearInterval(this.watchBuffer); } } }; var watchBuffer = setInterval(updateProgressBar, 500); </code></pre>
5,181,320
Under what circumstances are __rmul__ called?
<p>Say I have a list <code>l</code>. Under what circumstance is <code>l.__rmul__(self, other)</code> called?</p> <p>I basically understood the documentation, but I would also like to see an example to clarify its usages beyond any doubt.</p>
5,182,501
3
0
null
2011-03-03 13:28:19.703 UTC
18
2021-12-21 22:44:49.223 UTC
2017-01-10 22:28:26.943 UTC
null
3,924,118
null
254,704
null
1
67
python|operators
34,112
<p>When Python attempts to multiply two objects, it first tries to call the left object's <code>__mul__()</code> method. If the left object doesn't have a <code>__mul__()</code> method (or the method returns <code>NotImplemented</code>, indicating it doesn't work with the right operand in question), then Python wants to know if the right object can do the multiplication. If the right operand is the same type as the left, Python knows it can't, because if the left object can't do it, another object of the same type certainly can't either.</p> <p>If the two objects are different types, though, Python figures it's worth a shot. However, it needs some way to tell the right object that it <em>is</em> the right object in the operation, in case the operation is not commutative. (Multiplication is, of course, but not all operators are, and in any case <code>*</code> is not always used for multiplication!) So it calls <code>__rmul__()</code> instead of <code>__mul__()</code>.</p> <p>As an example, consider the following two statements:</p> <pre><code>print &quot;nom&quot; * 3 print 3 * &quot;nom&quot; </code></pre> <p>In the first case, Python calls the string's <code>__mul__()</code> method. The string knows how to multiply itself by an integer, so all is well. In the second case, the integer does not know how to multiply itself by a string, so its <code>__mul__()</code> returns <code>NotImplemented</code> and the string's <code>__rmul__()</code> is called. It knows what to do, and you get the same result as the first case.</p> <p>Now we can see that <code>__rmul__()</code> allows <em>all</em> of the string's special multiplication behavior to be contained in the <code>str</code> class, such that other types (such as integers) do not need to know anything about strings to be able to multiply by them. A hundred years from now (assuming Python is still in use) you will be able to define a new type that can be multiplied by an integer in either order, even though the <code>int</code> class has known nothing of it for more than a century.</p> <p>By the way, the string class's <code>__mul__()</code> has a bug in some versions of Python. If it doesn't know how to multiply itself by an object, it raises a <code>TypeError</code> instead of returning <code>NotImplemented</code>. That means you can't multiply a string by a user-defined type even if the user-defined type has an <code>__rmul__()</code> method, because the string never lets it have a chance. The user-defined type has to go first (e.g. <code>Foo() * 'bar'</code> instead of <code>'bar' * Foo()</code>) so its <code>__mul__()</code> is called. They seem to have fixed this in Python 2.7 (I tested it in Python 3.2 also), but Python 2.6.6 has the bug.</p>
25,897,951
Is there any standlone gui module for node application
<p>I want to build a code editor in nodejs. There is option like using an express server to show editor and to execute code in backend. But that would require a browser. So I am looking for node modules that can provide standalone gui for windows platform.</p>
25,898,945
6
3
null
2014-09-17 18:36:28.783 UTC
20
2019-10-05 07:56:27.3 UTC
null
null
null
null
2,504,754
null
1
53
node.js|user-interface
84,297
<p>There are a couple of different options, depending on how you want to proceed.</p> <p><strong>Option 1:</strong></p> <p>Use something like QT or GTK bindings to make a more traditional GUI application. These options generally are just Node bindings to the C/C++ API that GTK and QT expose. See <a href="https://github.com/arturadib/node-qt" rel="noreferrer">node-qt</a> and <a href="https://github.com/zcbenz/node-gui/" rel="noreferrer">yue</a>. Although these seem to not be actively developed.</p> <p><strong>Update:</strong> </p> <p>You can take a look at NodeGUI: <a href="https://github.com/nodegui/nodegui" rel="noreferrer">https://github.com/nodegui/nodegui</a></p> <p>NodeGUI is a javascript library for building cross-platform native desktop applications with JavaScript and CSS like styling. It uses Qt under the hood and works on Mac, Linux and Windows.</p> <p>It also has a react based renderer called React NodeGUI which is like React Native but for desktop: <a href="https://github.com/nodegui/react-nodegui" rel="noreferrer">https://github.com/nodegui/react-nodegui</a></p> <p><strong>Option 2:</strong></p> <p>Use a framework that takes HTML, CSS, and Javascript and bundles it into a standalone HTML5 app. There are a bunch of frame works out there that do this. Examples include <a href="https://github.com/rogerwang/node-webkit" rel="noreferrer">node-webkit</a> and <a href="http://appjs.com/" rel="noreferrer">AppJS</a> among many others.</p>
9,210,525
How do I convert hex to decimal in Python?
<p>I have some Perl code where the hex() function converts hex data to decimal. How can I do it on <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>?</p>
9,210,558
3
4
null
2012-02-09 12:06:01.083 UTC
29
2021-02-13 16:46:57.033 UTC
2014-10-12 03:58:06.137 UTC
null
63,550
null
699,467
null
1
167
python|hex|decimal
443,518
<p>If by "hex data" you mean a string of the form</p> <pre><code>s = "6a48f82d8e828ce82b82" </code></pre> <p>you can use</p> <pre><code>i = int(s, 16) </code></pre> <p>to convert it to an integer and</p> <pre><code>str(i) </code></pre> <p>to convert it to a decimal string.</p>
18,427,455
Multiple ggplots of different sizes
<p>It's relatively simple using <code>grid.arrange</code> in the <code>gridExtra</code> package to arrange multiple plots in a matrix, but how can you arrange plots (the ones I'm working on are from <code>ggplot2</code>) when some plots are intended to be larger than others? In base, I can use <code>layout()</code> such as in the example below:</p> <pre><code> nf &lt;- layout(matrix(c(1,1,1,2,3,1,1,1,4,5,6,7,8,9,9), byrow=TRUE, nrow=3)) layout.show(nf) </code></pre> <p>what is the equivalent for <code>ggplot</code> plots?</p> <p><img src="https://i.stack.imgur.com/FdRRs.png" alt="enter image description here"></p> <p>Some plots for inclusion</p> <pre><code>library(ggplot2) p1 &lt;- qplot(x=wt,y=mpg,geom="point",main="Scatterplot of wt vs. mpg", data=mtcars) p2 &lt;- qplot(x=wt,y=disp,geom="point",main="Scatterplot of wt vs disp", data=mtcars) p3 &lt;- qplot(wt,data=mtcars) p4 &lt;- qplot(wt,mpg,data=mtcars,geom="boxplot") p5 &lt;- qplot(wt,data=mtcars) p6 &lt;- qplot(mpg,data=mtcars) p7 &lt;- qplot(disp,data=mtcars) p8 &lt;- qplot(disp, y=..density.., geom="density", data=mtcars) p9 &lt;- qplot(mpg, y=..density.., geom="density", data=mtcars) </code></pre>
18,479,029
5
1
null
2013-08-25 09:18:24.927 UTC
17
2016-06-06 22:00:20.417 UTC
2013-08-26 23:53:10.72 UTC
null
1,664,978
null
1,664,978
null
1
22
r|layout|ggplot2|gridextra|gtable
12,978
<p>I appreciate all the other answers, but Didzis Elferts's comment on the OP connected to <a href="https://stackoverflow.com/a/9491019/1664978">the answer</a> that I found easiest to implement.</p> <pre><code>library(ggplot2) p1 &lt;- qplot(x=wt,y=mpg,geom="point",main="Scatterplot of wt vs. mpg", data=mtcars) p2 &lt;- qplot(x=wt,y=disp,geom="point",main="Scatterplot of wt vs disp", data=mtcars) p3 &lt;- qplot(wt,data=mtcars) p4 &lt;- qplot(wt,mpg,data=mtcars,geom="boxplot") p5 &lt;- qplot(wt,data=mtcars) p6 &lt;- qplot(mpg,data=mtcars) p7 &lt;- qplot(disp,data=mtcars) p8 &lt;- qplot(disp, y=..density.., geom="density", data=mtcars) p9 &lt;- qplot(mpg, y=..density.., geom="density", data=mtcars) vplayout &lt;- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y) grid.newpage() pushViewport(viewport(layout = grid.layout(3, 5))) # 3 rows, 5 columns print(p1, vp = vplayout(1:2, 1:3)) # the big plot covers rows 1:2 and cols 1:3 print(p2, vp = vplayout(1, 4)) print(p3, vp = vplayout(1, 5)) print(p4, vp = vplayout(2, 4)) print(p5, vp = vplayout(2, 5)) print(p6, vp = vplayout(3, 1)) print(p7, vp = vplayout(3, 2)) print(p8, vp = vplayout(3, 3)) print(p9, vp = vplayout(3, 4:5)) </code></pre>
15,456,033
Returning values from MyBatis <insert> mapped methods
<p>I have a Java project that uses MyBatis to access a PostgreSQL database. PostgreSQL allows to return fields of a newly created row after an <code>INSERT</code> statement, and I want to use it to return the auto-generated <code>BIGSERIAL</code> <code>id</code> of newly created records. So, I change the <code>insert</code> command in the XML to use feature of PostgreSQL, add an <code>resultType="long"</code> attribute to the <code>&lt;insert&gt;</code> tag, and in the Java interface of the mapper I set the insertion method to return <code>long</code> instead of <code>void</code>.</p> <p>When I try to run this, I get an <code>org.xml.sax.SAXParseException</code> saying that <code>Attribute "resultType" must be declared for element type "insert"</code>.</p> <p>Now, when I change the <code>&lt;insert&gt;</code> tag to <code>&lt;select&gt;</code> everything works fine, but it bothers me that I use <code>&lt;select&gt;</code> tag to perform an <code>INSERT</code> statement.</p> <p>Is there a way to make methods mapped to <code>&lt;insert&gt;</code> tags return results, or is MyBatis not designed for that, and I should just keep them as <code>&lt;select&gt;</code> tags?</p>
15,473,779
6
0
null
2013-03-16 23:43:04.8 UTC
9
2022-08-19 13:03:24.043 UTC
2013-03-18 15:23:15.78 UTC
null
759,126
null
794,380
null
1
21
postgresql|mybatis
59,259
<p>The return type of mapped insert method can be <code>void</code> or <code>int</code> (in which case it will return the number of the inserted row). You can do the following mechanism to return the generated id:</p> <pre><code>&lt;insert id="insert" parameterClass="MyParameter"&gt; &lt;selectKey order="AFTER" keyProperty="id" resultType="long"&gt; SELECT currval('my_seq') &lt;/selectKey&gt; INSERT INTO mytable(col1, col2) VALUES (#{val1}, #{val2}) &lt;/insert&gt; </code></pre> <p>This will set generated <code>id</code> column to <code>id</code> property of your parameter class. After that, object you passed as parameter will have generated <code>id</code> set in its property.</p>
15,436,721
Get index of enum from string?
<p>I have a string value, I also have an array of strings and an enum containing the range also. To get the index of the string in the array, from the value supplied I write this:</p> <pre><code>Arrays.asList(myClass.BAUD_RATES).indexOf(username) </code></pre> <p>How do I do this for an enum? Can I use ordinal? Or do i have to make my own method?</p> <p>The method might go like:</p> <pre><code>public enum Fruit { ... static public boolean isMember(String aName) { Fruit[] aFruits = Fruit.values(); for (Fruit aFruit : aFruits) if (aFruit.fruitname.equals(aName)) return aFruit; return false; } ... } </code></pre>
15,436,799
5
0
null
2013-03-15 15:52:47.943 UTC
1
2021-11-14 17:16:47.493 UTC
2018-09-13 19:37:23.243 UTC
null
1,393,766
null
1,803,007
null
1
34
java|android|enums
88,745
<p>Not sure if I understand you correctly but based on question title you may be looking for</p> <pre><code>YourEnum.valueOf("VALUE").ordinal(); </code></pre> <ol> <li><code>YourEnum.valueOf("VALUE")</code> returns enum <em>value</em> with name <code>"VALUE"</code></li> <li>each enum <em>value</em> knows its position (indexed from zero) which we can get by calling <code>ordinal()</code> method on it.</li> </ol>
15,388,206
Sending back a JSON response when failing Passport.js authentication
<p>I'm using <code>Node.js</code> as a backend API server for an iPhone client. I'm using <code>Passport.js</code> to authenticate with a <code>local strategy</code>. The relevant code is below:</p> <pre><code>// This is in user.js, my user model UserSchema.static('authenticate', function(username, password, callback) { this.findOne({ username: username }, function(err, user) { if (err){ console.log('findOne error occurred'); return callback(err); } if (!user){ return callback(null, false); } user.verifyPassword(password, function(err, passwordCorrect){ if (err){ console.log('verifyPassword error occurred'); return callback(err); } if (!passwordCorrect){ console.log('Wrong password'); return callback(err, false); } console.log('User Found, returning user'); return callback(null, user); }); }); }); </code></pre> <p>and</p> <pre><code>// This is in app.js app.get('/loginfail', function(req, res){ res.json(403, {message: 'Invalid username/password'}); }); app.post('/login', passport.authenticate('local', { failureRedirect: '/loginfail', failureFlash: false }), function(req, res) { res.redirect('/'); }); </code></pre> <p>Right now, I have managed to redirect a failed login to /loginfail, where I send back some JSON to the iPhone client. However, this doesn't have enough granularity. I want to be able to send back the appropriate errors to the iPhone client, such as: &quot;No user found&quot; or &quot;Password is wrong&quot;. With my existing code, I don't see how this can be accomplished.</p> <p>I tried to follow the examples for a custom callback on the passport.js site, but I just can't get it to work due to lack of node understanding. How could I modify my code so that I'd be able to send back a res.json with an appropriate error code/message?</p> <p>I am trying something like this now:</p> <pre><code>// In app.js app.post('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err) } if (!user) { console.log(info); // *** Display message without using flash option // re-render the login form with a message return res.redirect('/login'); } console.log('got user'); return res.json(200, {user_id: user._id}); })(req, res, next); }); // In user.js UserSchema.static('authenticate', function(username, password, callback) { this.findOne({ username: username }, function(err, user) { if (err){ console.log('findOne error occurred'); return callback(err); } if (!user){ return callback(null, false); } user.verifyPassword(password, function(err, passwordCorrect){ if (err){ return callback(err); } if (!passwordCorrect){ return callback(err, false, {message: 'bad password'}); } console.log('User Found, returning user'); return callback(null, user); }); }); }); </code></pre> <p>But back when I try to console.log(info), it just says undefined. I don't know how to get this custom callback working...Any help would be appreciated!</p>
15,397,432
6
2
null
2013-03-13 14:32:00.327 UTC
20
2021-03-31 21:38:14.54 UTC
2021-03-31 21:38:14.54 UTC
null
3,964,927
null
838,485
null
1
68
javascript|node.js|authentication|passport.js|passport-local
58,480
<p>I believe the callback function that your 'authenticate' static calls (called 'callback' in your code) accepts a 3rd parameter - "info" - which your code can provide. Then, instead of passing in the { failureRedirect: ...} object, pass in a function which takes 3 arguments - err, user, and info. The "info" you provided in your authenticate method will be passed to this callback.</p> <p>Passport calls this scenario "custom callback". See the docs here: <a href="http://passportjs.org/guide/authenticate/" rel="noreferrer">http://passportjs.org/guide/authenticate/</a></p>
15,304,562
How to put a delay on AngularJS instant search?
<p>I have a performance issue that I can't seem to address. I have an instant search but it's somewhat laggy, since it starts searching on each <code>keyup()</code>.</p> <p>JS:</p> <pre><code>var App = angular.module('App', []); App.controller('DisplayController', function($scope, $http) { $http.get('data.json').then(function(result){ $scope.entries = result.data; }); }); </code></pre> <p>HTML:</p> <pre><code>&lt;input id="searchText" type="search" placeholder="live search..." ng-model="searchText" /&gt; &lt;div class="entry" ng-repeat="entry in entries | filter:searchText"&gt; &lt;span&gt;{{entry.content}}&lt;/span&gt; &lt;/div&gt; </code></pre> <p>The JSON data isn't even that large, 300KB only, I think what I need to accomplish is to put a delay of ~1 sec on the search to wait for the user to finish typing, instead of performing the action on each keystroke. AngularJS does this internally, and after reading docs and other topics on here I couldn't find a specific answer.</p> <p>I would appreciate any pointers on how I can delay the instant search.</p>
15,304,977
13
5
null
2013-03-08 22:40:39.51 UTC
53
2019-07-29 03:09:39.497 UTC
2019-07-29 03:08:23.18 UTC
null
1,127,428
null
1,427,418
null
1
149
search|filter|angularjs|timeout|delay
141,989
<p>(See answer below for a Angular 1.3 solution.)</p> <p>The issue here is that the search will execute every time the model changes, which is every keyup action on an input.</p> <p>There would be cleaner ways to do this, but probably the easiest way would be to switch the binding so that you have a $scope property defined inside your Controller on which your filter operates. That way you can control how frequently that $scope variable is updated. Something like this:</p> <p>JS:</p> <pre><code>var App = angular.module('App', []); App.controller('DisplayController', function($scope, $http, $timeout) { $http.get('data.json').then(function(result){ $scope.entries = result.data; }); // This is what you will bind the filter to $scope.filterText = ''; // Instantiate these variables outside the watch var tempFilterText = '', filterTextTimeout; $scope.$watch('searchText', function (val) { if (filterTextTimeout) $timeout.cancel(filterTextTimeout); tempFilterText = val; filterTextTimeout = $timeout(function() { $scope.filterText = tempFilterText; }, 250); // delay 250 ms }) }); </code></pre> <p>HTML:</p> <pre><code>&lt;input id="searchText" type="search" placeholder="live search..." ng-model="searchText" /&gt; &lt;div class="entry" ng-repeat="entry in entries | filter:filterText"&gt; &lt;span&gt;{{entry.content}}&lt;/span&gt; &lt;/div&gt; </code></pre>
43,669,953
Why am I getting ReferenceError: Response is not defined?
<p>I am using node.js with express. I am trying to set up a basic server, but have no idea why I am getting a response error.</p> <pre><code>var http = require('http'); var myServer = http.createServer(function(req,res){ response.writeHead(200, {"Content-Type" : "text/plain"}); response.write('Hello World'); response.end(); }); myServer.listen(3000); </code></pre>
43,669,968
1
3
null
2017-04-28 00:18:14.75 UTC
1
2017-04-28 05:56:43.253 UTC
2017-04-28 05:56:43.253 UTC
null
720,391
null
4,887,007
null
1
7
javascript|node.js|express
48,961
<pre><code>function(req,res) </code></pre> <p>is supposed to be</p> <pre><code>function(req, response) { </code></pre> <p>You don't have a variable named <code>response</code> in the scope of the callback. That is the reason for the <code>reference error</code></p>
48,384,335
Is floating point arithmetic stable?
<p>I know that floating point numbers have precision and the digits after the precision is not reliable.</p> <p>But what if the equation used to calculate the number is the same? can I assume the outcome would be the same too?</p> <p>for example we have two float numbers <code>x</code> and <code>y</code>. Can we assume the result <code>x/y</code> from machine 1 is exactly the same as the result from machine 2? I.E. <code>==</code> comparison would return true</p>
48,384,367
6
6
null
2018-01-22 14:53:44.817 UTC
5
2018-01-22 20:03:06.403 UTC
null
null
null
null
2,872,388
null
1
39
c#|floating-point
3,925
<blockquote> <p>But what if the equation used to calculate the number is the same? can I assume the outcome would be the same too?</p> </blockquote> <p>No, not necessarily.</p> <p>In particular, in some situations the JIT is permitted to use a more accurate intermediate representation - e.g. 80 bits when your original data is 64 bits - whereas in other situations it won't. That can result in seeing different results when any of the following is true:</p> <ul> <li>You have slightly different code, e.g. using a local variable instead of a field, which can change whether the value is stored in a register or not. (That's one relatively obvious example; there are other much more subtle ones which can affect things, such as the existence of a <code>try</code> block in the method...)</li> <li>You are executing on a different processor (I used to observe differences between AMD and Intel; there can be differences between different CPUs from the same manufacturer too)</li> <li>You are executing with different optimization levels (e.g. under a debugger or not)</li> </ul> <p>From the C# 5 specification section 4.1.6:</p> <blockquote> <p>Floating-point operations may be performed with higher precision than the result type of the operation. For example, some hardware architectures support an "extended" or "long double" floating-point type with greater range and precision than the double type, and implicitly perform all floating-point operations using this higher precision type. Only at excessive cost in performance can such hardware architectures be made to perform floating-point operations with less precision, and rather than require an implementation to forfeit both performance and precision, C# allows a higher precision type to be used for all floating-point operations. Other than delivering more precise results, this rarely has any measurable effects. However, in expressions of the form <code>x * y / z</code>, where the multiplication produces a result that is outside the double range, but the subsequent division brings the temporary result back into the double range, the fact that the expression is evaluated in a higher range format may cause a finite result to be produced instead of an infinity.</p> </blockquote>
7,904,522
Knockout content editable custom binding
<p>Why in this example <a href="http://jsfiddle.net/JksKx/8/">http://jsfiddle.net/JksKx/8/</a> div lost cursor when i write text? How to fix such behavior?</p>
7,904,779
2
0
null
2011-10-26 14:55:36.923 UTC
8
2012-07-12 23:39:05.677 UTC
null
null
null
null
290,082
null
1
7
javascript|knockout.js|contenteditable
3,108
<p>The keyup event is firing and writing to your viewmodel, which then triggers the update function of the custom binding. This is writing the innerHTML back to the element, which is causing you to lose focus.</p> <p>An easy fix is to check in the update function if the element.innerHTML already is the same as the value that you want to set it to.</p> <p><a href="http://jsfiddle.net/rniemeyer/JksKx/9/">http://jsfiddle.net/rniemeyer/JksKx/9/</a></p> <pre><code>ko.bindingHandlers.htmlValue = { init: function(element, valueAccessor, allBindingsAccessor) { ko.utils.registerEventHandler(element, "keydown", function() { var modelValue = valueAccessor(); var elementValue = element.innerHTML; if (ko.isWriteableObservable(modelValue)) { modelValue(elementValue); } else { //handle non-observable one-way binding var allBindings = allBindingsAccessor(); if (allBindings['_ko_property_writers'] &amp;&amp; allBindings['_ko_property_writers'].htmlValue) allBindings['_ko_property_writers'].htmlValue(elementValue); } } ) }, update: function(element, valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()) || ""; if (element.innerHTML !== value) { element.innerHTML = value; } } }; </code></pre>
7,738,127
Find another part of PartialClass in Visual Studio IDE?
<p>Suppose I have a <code>partial class</code> in my application. </p> <p>Let's say I have one part of this class open in Visual Studio and I want to find the other parts. How can I do this? Is there a keyboard shortcut or any other method that I can use to quickly navigate to the other parts of my class?</p> <p>This would be useful because in a large application, there are so many individual *.cs files that manually searching for partial classes gets very inefficient. </p>
7,738,177
2
1
null
2011-10-12 09:44:13.363 UTC
2
2020-01-08 11:28:47.22 UTC
2015-11-12 20:12:14.693 UTC
null
1,828,486
null
468,968
null
1
49
c#|visual-studio
14,796
<p>If you open the context menu on the class name and click "Go To Definition (F12)", then the panel "Find Symbol Results" will show at the bottom (by default) of Visual Studio. Here you'll find all (partial) definitions of that class.</p> <p><img src="https://tweakers.net/ext/f/2566dVYmi88iyoKQWk5Pggdt/full.png" alt="partial class"></p>
8,871,337
How can I encrypt user settings (such as passwords) in my application?
<p>I want to provide the user the ability to save personal data encrypted. This might be trivial or might have been already asked, but I am not able to find an example of an easy to use way to encrypt/decrypt a password.</p> <p>I really don't need any super-magic-unbreakable password. I just need the password to be like difficult to break.</p> <p>I've seen some MSDN and SO questions but haven't found something to use.</p>
8,875,545
3
5
null
2012-01-15 16:36:24.833 UTC
16
2020-05-12 14:20:47.767 UTC
2020-05-12 14:20:47.767 UTC
null
850,848
null
245,495
null
1
24
c#|.net|winforms
20,116
<p><a href="https://stackoverflow.com/users/132599/david-clarke">David</a>, I thought <a href="https://stackoverflow.com/a/8874634/3312">your answer</a> was nifty, but I thought those would be niftier as extension methods. That would allow such syntax as:</p> <pre><code>string cypherText; string clearText; using (var secureString = "Some string to encrypt".ToSecureString()) { cypherText = secureString.EncryptString(); } using (var secureString = cypherText.DecryptString()) { clearText = secureString.ToInsecureString(); } </code></pre> <p>Here's the updated code:</p> <pre><code>using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Text; public static class SecureIt { private static readonly byte[] entropy = Encoding.Unicode.GetBytes("Salt Is Not A Password"); public static string EncryptString(this SecureString input) { if (input == null) { return null; } var encryptedData = ProtectedData.Protect( Encoding.Unicode.GetBytes(input.ToInsecureString()), entropy, DataProtectionScope.CurrentUser); return Convert.ToBase64String(encryptedData); } public static SecureString DecryptString(this string encryptedData) { if (encryptedData == null) { return null; } try { var decryptedData = ProtectedData.Unprotect( Convert.FromBase64String(encryptedData), entropy, DataProtectionScope.CurrentUser); return Encoding.Unicode.GetString(decryptedData).ToSecureString(); } catch { return new SecureString(); } } public static SecureString ToSecureString(this IEnumerable&lt;char&gt; input) { if (input == null) { return null; } var secure = new SecureString(); foreach (var c in input) { secure.AppendChar(c); } secure.MakeReadOnly(); return secure; } public static string ToInsecureString(this SecureString input) { if (input == null) { return null; } var ptr = Marshal.SecureStringToBSTR(input); try { return Marshal.PtrToStringBSTR(ptr); } finally { Marshal.ZeroFreeBSTR(ptr); } } } </code></pre>
5,580,443
how to fix width and height of primefaces dialogbox
<p>In my web application i want to fix height and width of primefaces dialogbox in the way in which the dialogbox appears exactly in the middle of my web page, and if one want to minimize the window then the dialogbox should also be minimised. i mean middle of my one of the frame not whole window. </p> <p>i.e. dynamic sized dialog box like % width and height</p> <p>thanks for any help...</p>
5,580,502
4
1
null
2011-04-07 11:39:35.913 UTC
null
2019-08-13 17:59:13.43 UTC
2019-08-13 17:59:13.43 UTC
null
4,478,047
null
692,383
null
1
13
jsf|primefaces|dialog
60,561
<p>You can use following code to make it of fixed dimension, </p> <pre><code>&lt;p:dialog header="Modal Dialog" widgetVar="dlg2" modal="true" width="300" height="200"&gt; &lt;h:outputText value="This is a Modal Dialog." /&gt; &lt;/p:dialog&gt; </code></pre> <p>and to make minimize functionality. you can play with javascript to get it done.</p> <p><strong>See Also</strong> </p> <ul> <li><a href="http://www.primefaces.org/showcase/ui/overlay/dialog/basic.xhtml" rel="noreferrer">Primefaces Show case</a></li> </ul>
5,270,368
How to include version string in the filename when building Android apk with ant?
<p>Normally we build android package in debug mode with the command</p> <pre><code>ant debug </code></pre> <p>and got the apk filename <strong>AppName-debug.apk</strong>.</p> <p>Is there any way to generate the apk file in the format of <strong><code>AppName-debug-&lt;version-number&gt;.apk</code></strong> directly without 'mv' command?</p> <p>Thanks.</p>
5,271,349
4
0
null
2011-03-11 07:58:38.24 UTC
11
2013-07-02 08:20:53.577 UTC
null
null
null
null
628,365
null
1
22
android|ant|version|apk
8,398
<p>I have done this in an automated way, by using the info from the Android manifest.</p> <p>My approach was to modify the local project ant <code>build.xml</code> file to import a custom copy of the master <code>build.xml</code> file, in the latest version of the SDK the master file that is imported into your local file is located at <code>&lt;SDK&gt;/tools/ant/build.xml</code> (was android_rules.xml in previous versions) Note the <code>import</code> line in the default <code>build.xml</code> file local to your project.</p> <p>The comments in the local <code>build.xml</code> created by the Android tools contain details on how to do customization, such that future updates to the tools will not break your changes.</p> <p>In the custom rules file add:</p> <pre><code>&lt;xmlproperty file="AndroidManifest.xml" prefix="mymanifest" collapseAttributes="true"/&gt; </code></pre> <p>This reads in the manifest as a set of ant properties, with a custom prefix to ensure no name collision.</p> <p>You can then add <strong>${mymanifest.manifest.android:versionName}</strong> to any of the spots that the apk name is defined, just search for <code>.apk</code> in the custom rules file.</p> <p>I've used this process to automate versioning files from a build server.</p> <p>With some additional tweaks it is also possible to have your release app signed automatically, buy setting the passwords in properties and using those in the signing task. The actual passwords where stored in a separate properties file that only lived on the build server. While a minor security risk, in some cases it is out weighed by the need for full end to end build automation.</p>
5,282,969
Learning efficient algorithms
<p>Up until now I've mostly concentrated on how to properly design code, make it as readable as possible and as maintainable as possible. So I alway chose to learn about the higher level details of programming, such as class interactions, API design, etc.</p> <p>Algorithms I never really found particularly interesting. As a result, even though I can come up with a good design for my programs, and even if I can come up with a solution to a given problem it rarely is the most efficient.</p> <p>Is there a particular way of thinking about problems that helps you come up with an as efficient solution as possible, or is it simple a matter of practice and/or memorizing?</p> <p>Also, what online resources can you recommend that teach you various efficient algorithms for different problems? </p>
5,282,992
5
4
null
2011-03-12 14:05:16.797 UTC
12
2011-06-09 16:10:14.6 UTC
null
null
null
null
627,005
null
1
18
algorithm|complexity-theory
2,827
<p><strong>Data dominates</strong>. If you design your program around the right abstract data structures (ADTs), you often get a clean design, the algorithms follow quite naturally and when performance is lacking, you should be able to "plug in" more efficient ones.</p> <p>A strong background in maths and logic helps here, as it allows you to visualize your program at a high level as the interaction between functions, sets, graphs, sequences, etc. You then decide whether the sets need to be ordered (balanced BST, O(lg n) operations) or not (hash tables, O(1) operations), what operations need to supported on sequences (vector-like or list-like), etc.</p> <p>If you want to learn some algorithms, get a good book such as Cormen et al. and try to implement the main data structures:</p> <ul> <li>binary search trees</li> <li>generic binary search trees (that work on more than just <code>int</code> or strings)</li> <li>hash tables</li> <li>priority queues/heaps</li> <li>dynamic arrays</li> </ul>
5,596,261
Intent Filter to Launch My Activity when custom URI is clicked
<p>I am trying to allow a URI to be registered to open up with my app. Like the <code>PatternRepository</code> on the Blackberry and the <code>CFBundleURLName</code>/<code>CFBundleURLSchemes</code> on the iPhone. How do I achieve the same results on the Android?</p> <p>The system will be sending emails with the following link: <code>myapp://myapp.mycompany.com/index/customerId/12345</code>. The idea is that the user should be able to click on the link to open up the customer activity in the application. </p> <p>I've tried numerous suggestions from other SO posts but I cannot get the OS to recognize the pattern and open my app. </p> <p>On The Gmail app it looks like this: myapp://<a href="http://myapp.mycompany.com/index/customerId/12345" rel="nofollow noreferrer">myapp.mycompany.com/index/customerId/12345</a>. It recognizes and underlines the <code>myapp.mycompany.com/index/customerId/12345</code> portion of the link and it opens it in a browser. The <code>myapp://</code> part is not <em>linkified</em>. </p> <p>The standard mail application treats the entire link as plain text.</p> <p>What am I missing here?</p> <p>PS: I've already looked at <a href="https://stackoverflow.com/questions/2448213/how-to-implement-my-very-own-uri-schema-on-android">How to implement my very own URI scheme on Android</a> and <a href="https://stackoverflow.com/questions/2430045/how-to-register-some-url-namespace-myapp-app-start-for-accessing-your-progra/2430468#2430468">How to register some URL namespace (myapp://app.start/) for accessing your program by calling a URL in browser in Android OS?</a></p> <p><strong>The Manifest:</strong> </p> <pre><code>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="2" android:versionName="0.0.8" package="com.mycompany.myapp.client.android"&gt; &lt;uses-sdk android:minSdkVersion="7" android:targetSdkVersion="7"/&gt; &lt;uses-permission android:name="android.permission.INTERNET"/&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/&gt; &lt;uses-permission android:name="android.permission.READ_PHONE_STATE"/&gt; &lt;application android:label="@string/app_name" android:name="myappApplication" android:icon="@drawable/ic_icon_myapp" android:debuggable="true"&gt; &lt;activity android:label="My App" android:name=".gui.activity.LoginActivity" label="@string/app_name"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".gui.activity.CustomerDetailActivity" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.VIEW" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.BROWSABLE" /&gt; &lt;data android:scheme="myapp"/&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".gui.activity.CustomerDetailActivity"/&gt; &lt;activity android:name=".gui.activity.CustomerImageViewerActivity" /&gt; &lt;activity android:name=".gui.activity.CustomerListActivity" android:configChanges="orientation|keyboardHidden"/&gt; &lt;activity android:name=".gui.activity.HomeActivity" android:configChanges="orientation|keyboardHidden"/&gt; &lt;activity android:name=".gui.activity.AboutActivity" android:configChanges="orientation|keyboardHidden"/&gt; &lt;activity android:name=".gui.activity.AccountActivity" android:configChanges="orientation|keyboardHidden" /&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre>
7,533,468
7
0
null
2011-04-08 14:05:07.24 UTC
20
2020-11-03 09:41:30.87 UTC
2017-05-23 12:33:18.21 UTC
null
-1
null
600,257
null
1
23
android|uri|android-manifest|android-intent
43,890
<p>The final solution was a hacky workaround to cover all bases. The email now also contains an attachment with an extension that is registered to open with the app.</p> <p><code>AndroidManifest.xml</code> :</p> <pre><code> &lt;activity android:name=&quot;.gui.activity.CustomerDetailActivity&quot; &gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt; &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt; &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt; &lt;data android:scheme=&quot;https&quot; android:host=&quot;myapp.mycompany.com&quot; /&gt; &lt;/intent-filter&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt; &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt; &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt; &lt;data android:scheme=&quot;myapp&quot; android:host=&quot;myapp.mycompany.com&quot; /&gt; &lt;/intent-filter&gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt; &lt;action android:name=&quot;android.intent.action.EDIT&quot; /&gt; &lt;action android:name=&quot;android.intent.action.PICK&quot; /&gt; &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt; &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt; &lt;data android:mimeType=&quot;application/myapp&quot; /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre>
5,141,559
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)
<p>I want to parse my XML document. So I have stored my XML document as below</p> <pre><code>class XMLdocs(db.Expando): id = db.IntegerProperty() name=db.StringProperty() content=db.BlobProperty() </code></pre> <p>Now my below is my code</p> <pre><code>parser = make_parser() curHandler = BasketBallHandler() parser.setContentHandler(curHandler) for q in XMLdocs.all(): parser.parse(StringIO.StringIO(q.content)) </code></pre> <p>I am getting below error</p> <pre><code>'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128) Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 517, in __call__ handler.post(*groups) File "/base/data/home/apps/parsepython/1.348669006354245654/mapreduce/base_handler.py", line 59, in post self.handle() File "/base/data/home/apps/parsepython/1.348669006354245654/mapreduce/handlers.py", line 168, in handle scan_aborted = not self.process_entity(entity, ctx) File "/base/data/home/apps/parsepython/1.348669006354245654/mapreduce/handlers.py", line 233, in process_entity handler(entity) File "/base/data/home/apps/parsepython/1.348669006354245654/parseXML.py", line 71, in process parser.parse(StringIO.StringIO(q.content)) File "/base/python_runtime/python_dist/lib/python2.5/xml/sax/expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "/base/python_runtime/python_dist/lib/python2.5/xml/sax/xmlreader.py", line 123, in parse self.feed(buffer) File "/base/python_runtime/python_dist/lib/python2.5/xml/sax/expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) File "/base/data/home/apps/parsepython/1.348669006354245654/parseXML.py", line 136, in characters print ch UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128) </code></pre>
5,141,671
7
1
null
2011-02-28 11:48:09.35 UTC
23
2019-09-30 10:16:47.403 UTC
2011-02-28 12:04:43.61 UTC
null
118,903
null
622,734
null
1
75
python|google-app-engine|xml-parsing
204,528
<p>It seems you are hitting a UTF-8 byte order mark (BOM). Try using this unicode string with BOM extracted out:</p> <pre><code>import codecs content = unicode(q.content.strip(codecs.BOM_UTF8), 'utf-8') parser.parse(StringIO.StringIO(content)) </code></pre> <p>I used <code>strip</code> instead of <code>lstrip</code> because in your case you had multiple occurences of BOM, possibly due to concatenated file contents.</p>
5,318,385
MVC 3: How to render a view without its layout page when loaded via ajax?
<p>I am learning about <a href="http://en.wikipedia.org/wiki/Progressive_enhancement" rel="noreferrer">Progressive Enhancement</a> and I have a question about AJAXifying views. In my MVC 3 project I have a layout page, a viewstart page, and two plain views.</p> <p>The viewstart page is in the root of the Views folder and thus applies to all views. It specifies that all views should use <code>_Layout.cshtml</code> for their layout page. The layout page contains two navigation links, one for each view. The links use <code>@Html.ActionLink()</code> to render themselves to the page.</p> <p>Now I have added jQuery and want to hijack these links and use Ajax to load their content on the page dynamically.</p> <pre><code>&lt;script type="text/javascript"&gt; $(function () { $('#theLink').click(function () { $.ajax({ url: $(this).attr('href'), type: "GET", success: function (response) { $('#mainContent').html(response); } }); return false; }); }); &lt;/script&gt; </code></pre> <p>There are two ways I can think of to do this, but I don't particularly like either one:</p> <p>1) I can take the entire View's contents and place them in a partial view, then have the main view call the partial view when it is rendered. That way, using <code>Request.IsAjaxRequest()</code> in the controller, I can return <code>View()</code> or return <code>PartialView()</code> based on whether or not the request is an Ajax request. I can't return the regular view to the Ajax request because then it would use the layout page and I'd get a second copy of the layout page injected. However, I don't like this because it forces me to create empty views with just a <code>@{Html.RenderPartial();}</code> in them for the standard GET requests.</p> <pre><code> public ActionResult Index() { if (Request.IsAjaxRequest()) return PartialView("partialView"); else return View(); } </code></pre> <p>Then in Index.cshtml do this:</p> <pre><code>@{Html.RenderPartial("partialView");} </code></pre> <p>2) I can remove the layout designation from _viewstart and specify it manually when the request is NOT Ajax:</p> <pre><code> public ActionResult Index() { if (Request.IsAjaxRequest()) return View(); // Return view with no master. else return View("Index", "_Layout"); // Return view with master. } </code></pre> <p>Does anyone have a better suggestion? Is there a way to return a view without its layout page? It would be much easier to explicitly say "don't include your layout" if it is an ajax request, than it would be to explicitly include the layout if it's not an ajax.</p>
5,318,423
7
0
null
2011-03-15 21:37:27.14 UTC
48
2021-02-05 12:27:03 UTC
2014-06-05 15:54:24.877 UTC
null
498,624
null
498,624
null
1
156
c#|asp.net-mvc|asp.net-mvc-3|master-pages|razor
162,619
<p>In <code>~/Views/ViewStart.cshtml</code>:</p> <pre><code>@{ Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml"; } </code></pre> <p>and in the controller:</p> <pre><code>public ActionResult Index() { return View(); } </code></pre>
16,644,639
How to create MVC 4 @Html.TextBox type="file"?
<p>I need to add the following field at my form</p> <pre><code>&lt;input type="file" class="input-file" /&gt; </code></pre> <p>I create model and describe this field (the last field)</p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CorePartners_Site2.Models { public class FeedbackForm { public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } public string Company { get; set; } public string AdditionalInformation { get; set; } public HttpPostedFileBase ProjectInformation { get; set; } } } </code></pre> <p>and create </p> <pre><code>@Html.TextBox(null, null, new { type="file", @class="input-file" }) </code></pre> <p>but it doesnt work, I get some exception. What's wrong?</p>
16,644,991
7
7
null
2013-05-20 07:30:52.82 UTC
2
2019-03-04 11:08:21.577 UTC
null
null
null
null
2,287,081
null
1
12
asp.net-mvc|asp.net-mvc-4
54,483
<p>Model </p> <pre><code>public class FeedbackForm { public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } public string Company { get; set; } public string AdditionalInformation { get; set; } public HttpPostedFileBase ProjectInformation { get; set; } } </code></pre> <p>View</p> <pre><code>@model FeedbackForm @Html.TextBox("Name") @Html.TextBox("Email") ... @Html.TextBox("ProjectInformation", null, new { type="file", @class="input-file" }) // submit button </code></pre> <p>My recommended view (strongly - typed)</p> <pre><code>@model FeedbackForm @Html.TextBoxFor(model=&gt;model.Name) @Html.TextBoxFor(model=&gt;model.Email) ... @Html.TextBoxFor(model=&gt;model.ProjectInformation, null, new { type="file", @class="input-file" }) // submit button </code></pre> <p>Controller </p> <pre><code>[HttpPost] public ActionResult FeedbackForm(FeedbackForm model) { // this is your uploaded file var file = model.ProjectInformation; ... return View(); } </code></pre> <p>MVC is using name convention, so if your textbox and model names match, then MVC will bind your inputs to your model.</p>
12,599,234
why does CSS background-size: cover not work in portrait mode on iOS?
<p>I'm trying to set up a manualy <code>splash-image</code> across devices. I'm doing so by checking for <code>orientation</code> (touch devices) or <code>screen width vs. screen height</code> (none touch) and set a url accordingly.</p> <p>Then I add this CSS rule via Javascript:</p> <pre><code> document.styleSheets[3].insertRule('.initHandler:before { background: url('+x+') no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; }', 0) </code></pre> <p>With <code>x</code> being the image to be loaded depending on orientation and screen size.</p> <p>My problem is this works fine in <code>landscape</code> mode, but on my iPad in <code>portrait</code> mode, the correct image is loaded (differ depending on portrait/landscape), BUT it is not expanded to fullscreen size.</p> <p><strong>Question</strong>:<br> Can I not use CSS <code>background-size</code> on iOS in portrait-mode?</p> <p>Thanks for help!</p> <p><strong>EDIT:</strong><br> Just tried on my Android Smartphone. Works fine there. Makes no sense, why it doesn't work on iPad.</p>
12,602,235
5
4
null
2012-09-26 10:02:01.367 UTC
8
2017-10-04 17:36:40.79 UTC
2012-09-26 10:10:28.283 UTC
null
536,768
null
536,768
null
1
13
ios|background|portrait|css
45,866
<p>While checking orientation please take note of these points from apple document - </p> <blockquote> <p><strong>Provide Launch Images :</strong></p> <p><em>iPhone-only applications</em> may only have one launch image. It should be in PNG format and measure 320 x 480 pixels. Name your launch image file Default.png.</p> <p><em>iPad-only applications:</em> Create a launch image for each supported orientation in the PNG format. Each launch image must be 1024 x 748 pixels (for landscape) or 768 x 1004 pixels (for portrait).</p> <p><em>Universal applications:</em> Include launch images for both iPhone and iPad.</p> <p><strong>Update Your Info.plist Settings</strong> Specify values for the UISupportedInterfaceOrientations and UIInterfaceOrientation</p> </blockquote> <p>and </p> <blockquote> <p><strong>Not all browsers recognize the cover keyword for background-size</strong>, and as a result, simply ignore it.</p> </blockquote> <p>So we can overcome that limitation by <em>setting the background-size to 100% width or height, depending on the orientation</em>. We can target the current orientation (as well as the iOS device, using device-width). With these two points I think you can use CSS <code>background-size:cover</code> on iOS in portrait-mode </p> <p>Here are some other resources I also came across while looking for a solution: <a href="http://kimili.com/journal/flexible-scalable-background-image" rel="nofollow noreferrer">Flexible scalable background images</a>, <a href="http://beingwicked.com/development/full-scalable-background-images/" rel="nofollow noreferrer">full scalable background images</a>, <a href="http://css-tricks.com/perfect-full-page-background-image/" rel="nofollow noreferrer">perfect scalable background images</a>, and <a href="http://wordpress.org/support/topic/background-image-problems-on-resize-iphoneipad" rel="nofollow noreferrer">this</a> discussion.</p>
12,482,455
querying on 10 million mongodb documents
<p>I am storing book meta-data like name,authors,price,publisher,etc in a mongodb document. I have about 10 million of these documents and they all are in one collection. <em>The average document size is 1.9 KB</em>. Now i have indexes on <code>name</code>,<code>authors</code> and <code>price</code>. In fact <em>i have 2 indexes on price one in ascending order and one descending order</em>. My mongodb version is 2.2.0 and i am using the php driver to query mongo. The driver's version is 1.12. But when i do a range query on price i get a <code>MongoCursorTimeoutException</code>. In my query i am trying to find books in a certain price range like "price less than 1000 and more than 500".</p> <p>Increasing the timeout doesn't seem to be a good idea(It is already 30 sec). Is there anything else that i can do to speed up the query process.</p> <p><strong>EDIT</strong> Actually my price index is compound. I have a status field which has an integer value so my price index looks like <code>{price:-1,status:1}</code> and <code>{price:1,status:1}</code> Also I am trying to retrieve 20 documents at a time with PHP.</p>
13,994,261
3
13
null
2012-09-18 18:00:00.18 UTC
8
2012-12-21 17:03:02.867 UTC
2012-09-21 19:21:37.193 UTC
null
535,962
null
535,962
null
1
13
php|mongodb
9,900
<p>As @JohnyHK said my RAM was too low. So increased it to 12 GB and it works now. Thanks everyone for their comments and answers</p>
12,249,089
How to use numpy with OpenBLAS instead of Atlas in Ubuntu?
<p>I have looked for an easy way to install/compile Numpy with OpenBLAS but didn't find an easy answer. All the documentation I have seen takes too much knowledge as granted for someone like me who is not used to compile software. There are two packages in Ubuntu related to OpenBLAS : <code>libopenblas-base</code> and <code>libopenblas-dev</code>. Once they are installed, what should I do to install Numpy again with them? Thanks!</p> <p>Note that when these OpenBLAS packages are installed, Numpy doesn't work anymore: it can't be imported: ImportError: /usr/lib/liblapack.so.3gf: undefined symbol: ATL_chemv. The problem occurs as well when installing Theano with their <a href="http://deeplearning.net/software/theano/install_ubuntu.html#install-ubuntu" rel="nofollow noreferrer">website instructions</a> for Ubuntu.</p> <p>This was noticed <a href="https://stackoverflow.com/questions/8917977/installing-lapack-for-numpy">here</a> already.</p>
12,251,204
3
3
null
2012-09-03 13:44:17.79 UTC
8
2015-09-06 10:22:12.187 UTC
2017-05-23 10:29:40.637 UTC
null
-1
null
627,087
null
1
15
python|ubuntu|numpy|installation|blas
13,113
<p>Run <code>sudo update-alternatives --all</code> and set <code>liblapack.so.3gf</code> to <code>/usr/lib/lapack/liblapack.so.3gf</code></p>
12,176,492
shell: delete the last line of a huge text log file
<p>I asked a <a href="https://stackoverflow.com/questions/12175344/php-pop-the-last-line-of-huge-text-log-file">question</a> regarding popping the last line of a text file in PHP, and now, is it possible to re-write the logic in shell script?</p> <p>I tried this to obtain the last line:</p> <pre><code>tail -n 1 my_log_file.log </code></pre> <p>but I am not sure how can I remove the last line and save the file.</p> <p>P.S. given that I use Ubuntu server.</p>
12,176,634
4
0
null
2012-08-29 11:04:40.733 UTC
9
2012-08-29 15:51:46.607 UTC
2017-05-23 12:17:39.08 UTC
null
-1
null
188,331
null
1
17
shell|tail
21,861
<p><em>(Solution is based on <a href="https://stackoverflow.com/questions/12176492/shell-delete-the-last-line-of-a-huge-text-log-file/12177339#12177339">sch's answer</a> so credit should go to him/her)</em></p> <p>This approach will allow you to efficiently retrieve the last line of the file and truncate the file to remove that line. This can better deal with large inputs as the file is not read sequentially.</p> <pre><code># retrieve last line from file LAST=$(tail -n 1 my_log_file.log) # truncate file let TRUNCATE_SIZE="${#LAST} + 1" truncate -s -"$TRUNCATE_SIZE" my_log_file.log # ... $LAST contains 'popped' last line </code></pre> <p>Note that this will not work as expected if the file is modified between the calls to <code>tail</code> and <code>truncate</code>.</p>
12,356,646
Xcopy Command excluding files and folders
<p>I want to copy files and folders in a directory to another folder excluding a list of files and folders.Is that possible.</p> <p>I was just trying to copy excluding file : </p> <pre><code> xcopy c:\t1 c:\t2 /EXCLUDE:exclusion.txt </code></pre> <p>But it keeps saying read cant read file : exclusion.txt</p> <p>Can anyone help me on this?</p> <p>Thanks</p>
21,447,865
3
1
null
2012-09-10 17:28:34.04 UTC
4
2019-12-18 17:31:46.867 UTC
2015-10-29 15:42:47.423 UTC
null
3,337,489
null
696,219
null
1
25
command-line|cmd|xcopy
120,568
<p>Just give full path to exclusion file: eg..</p> <p>-- <strong>no</strong> - - - - -<code>xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt</code></p> <p><strong>correct</strong> - - - <code>xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt</code></p> <p>In this example the file would be located <strong><em>" C:\list-of-excluded-files.txt "</em></strong> </p> <p>or...</p> <p><strong>correct</strong> - - - <code>xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt</code></p> <p>In this example the file would be located <strong><em>" C:\mybatch\list-of-excluded-files.txt "</em></strong></p> <p>Full path fixes syntax error.</p>
12,282,628
Why are initial random numbers similar when using similar seeds?
<p>I discovered something strange with the generation of random numbers using Java's Random class. Basically, if you create multiple Random objects using close seeds (for example between 1 and 1000) the first value generated by each generator will be almost the same, but the next values looks fine (i didn't search further).</p> <p>Here are the two first generated doubles with seeds from 0 to 9 :</p> <ul> <li>0 0.730967787376657 0.24053641567148587</li> <li>1 0.7308781907032909 0.41008081149220166</li> <li>2 0.7311469360199058 0.9014476240300544</li> <li>3 0.731057369148862 0.07099203475193139</li> <li>4 0.7306094602878371 0.9187140138555101</li> <li>5 0.730519863614471 0.08825840967622589</li> <li>6 0.7307886238322471 0.5796252073129174</li> <li>7 0.7306990420600421 0.7491696031336331</li> <li>8 0.7302511331990172 0.5968915822372118</li> <li>9 0.7301615514268123 0.7664359929590888</li> </ul> <p>And from 991 to 1000 :</p> <ul> <li>991 0.7142160704801332 0.9453385235522973</li> <li>992 0.7109015598097105 0.21848118381994108</li> <li>993 0.7108119780375055 0.38802559454181795</li> <li>994 0.7110807233541204 0.8793923921785096</li> <li>995 0.7109911564830766 0.048936787999225295</li> <li>996 0.7105432327208906 0.896658767102804</li> <li>997 0.7104536509486856 0.0662031629235198</li> <li>998 0.7107223962653005 0.5575699754613725</li> <li>999 0.7106328293942568 0.7271143712820883</li> <li>1000 0.7101849056320707 0.574836350385667</li> </ul> <p>And here is a figure showing the first value generated with seeds from 0 to 100,000.</p> <p>First random double generated based on the seed :</p> <p><img src="https://i.stack.imgur.com/2jDZh.jpg" alt="image"></p> <p>I searched for information about this, but I didn't see anything referring to this precise problem. I know that there is many issues with LCGs algorithms, but I didn't know about this one, and I was wondering if this was a known issue.</p> <p>And also, do you know if this problem only for the first value (or first few values), or if it is more general and using close seeds should be avoided?</p> <p>Thanks.</p>
12,284,419
4
8
null
2012-09-05 13:30:45.057 UTC
4
2012-09-05 15:04:55.377 UTC
2012-09-05 13:48:53.007 UTC
null
300,311
null
1,649,006
null
1
30
java|random
2,457
<p>You'd be best served by downloading and reading the <code>Random</code> source, as well as some papers on pseudo-random generators, but here are some of the relevant parts of the source. To begin with, there are three constant parameters that control the algorithm:</p> <pre><code>private final static long multiplier = 0x5DEECE66DL; private final static long addend = 0xBL; private final static long mask = (1L &lt;&lt; 48) - 1; </code></pre> <p>The multiplier works out to approximately 2^34 and change, the mask 2^48 - 1, and the addend is pretty close to 0 for this analysis.</p> <p>When you create a Random with a seed, the constructor calls <code>setSeed</code>:</p> <pre><code>synchronized public void setSeed(long seed) { seed = (seed ^ multiplier) &amp; mask; this.seed.set(seed); haveNextNextGaussian = false; } </code></pre> <p>You're providing a seed pretty close to zero, so initial seed value that gets set is dominated by <code>multiplier</code> when the two are OR'ed together. In all your test cases with seeds close to zero, the seed that is used internally is roughly 2^34; but it's easy to see that even if you provided very large seed numbers, similar user-provided seeds will yield similar internal seeds.</p> <p>The final piece is the <code>next(int)</code> method, which actually generates a random integer of the requested length based on the current seed, and then updates the seed:</p> <pre><code>protected int next(int bits) { long oldseed, nextseed; AtomicLong seed = this.seed; do { oldseed = seed.get(); nextseed = (oldseed * multiplier + addend) &amp; mask; } while (!seed.compareAndSet(oldseed, nextseed)); return (int)(nextseed &gt;&gt;&gt; (48 - bits)); } </code></pre> <p>This is called a 'linear congruential' pseudo-random generator, meaning that it generates each successive seed by multiplying the current seed by a constant multiplier and then adding a constant addend (and then masking to take the lower 48 bits, in this case). The quality of the generator is determined by the choice of multiplier and addend, but the ouput from all such generators can be easily predicted based on the current input and has a set period before it repeats itself (hence the recommendation not to use them in sensitive applications).</p> <p>The reason you're seeing similar initial output from <code>nextDouble</code> given similar seeds is that, because the computation of the next integer only involves a multiplication and addition, the magnitude of the next integer is not much affected by differences in the lower bits. Calculation of the next double involves computing a large integer based on the seed and dividing it by another (constant) large integer, and the magnitude of the result is mostly affected by the magnitude of the integer.</p> <p>Repeated calculations of the next seed will magnify the differences in the lower bits of the seed because of the repeated multiplication by the constant multiplier, and because the 48-bit mask throws out the highest bits each time, until eventually you see what looks like an even spread.</p>
12,069,669
How can you pass multiple primitive parameters to AsyncTask?
<p>There are related questions, such as <a href="https://stackoverflow.com/questions/5546049/how-can-i-pass-in-2-parameters-to-a-asynctask-class">How can I pass in 2 parameters to a AsyncTask class? </a>, but I ran into the difficulty of trying in vain to pass multiple primitives as parameters to an AsyncTask, so I want to share what I discovered. This subtlety is not captured in the existing questions and answers, so I want to help out anyone who runs into the same problem as I did and save them the pain.</p> <p>The question is this: I have multiple <em>primitive</em> parameters (e.g. two longs) that I want to pass to an AsyncTask to be executed in the background--how can it be done? (My answer...after struggling with this for awhile...can be found below.)</p>
12,069,670
6
0
null
2012-08-22 09:04:08.797 UTC
41
2019-12-21 16:46:23.417 UTC
2017-05-23 12:10:43.367 UTC
null
-1
null
896,660
null
1
84
android|android-asynctask|primitive|variadic-functions
99,694
<p>It is (strictly-speaking) NOT possible to pass multiple primitives to AsyncTask. For example, if you want to perform <code>myTask.execute(long1, long2)</code> and try to set up <code>private class myTask extends AsyncTask&lt;long, Void, Void&gt;</code> with the corresponding method:</p> <pre><code>@Override protected LocationItemizedOverlay doInBackground(long... params) {...} </code></pre> <p>your IDE will likely complain about needing to override a supertype method. Note that you are using the so-called <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html" rel="noreferrer">Varargs</a> method signature for <code>doInBackground</code>, where <code>(long... params)</code> is like saying "I accept a variable number of longs, stored as an array called params. I don't completely understand what causes a compiler/IDE complaint to be raised, but I think it has to do with how the generic class <code>Params</code> is defined.</p> <p>In any case, it is possible to achieve what you want with no problem, provided you correctly cast your primitives to their respective non-primitive wrappers (e.g. int => Integer, long => Long, etc.). Actually, you don't need to explicitly cast your primitives to non-primitives. Java seems to handle that for you. You just need to set up your ASyncTask as follows (for the example of longs):</p> <pre><code>private class MyTask extends AsyncTask&lt;Long, Void, Void&gt; { @Override protected void doInBackground(Long... params) { // Do stuff with params, for example: long myFirstParam = params[0] } ... } </code></pre> <p>You can then use this class as you originally intended, e.g.:</p> <pre><code>MyTask myTask = new MyTask(); myTask.execute(long1, long2); </code></pre> <p>Or for any number of primitives that you would like, PROVIDED THEY ARE OF THE SAME TYPE. If you need to pass multiple types of primitives, this can also be done, but you will need to modify the above to:</p> <pre><code>private class MyTask extends AsyncTask&lt;Object, Void, Void&gt; { @Override protected void doInBackground(Object... params) { // Do stuff with params, for example: long myLongParam = (Long) params[0]; int myIntParam = (Integer) params[1]; } ... } </code></pre> <p>This is more flexible, but it requires explicitly casting the parameters to their respective types. If this flexibility is not needed (i.e. a single data type), I recommend sticking to the first option, as it's slightly more readable.</p>
12,573,753
Creating Multifield Indexes in Mongoose / MongoDB
<p>I'm trying to find documentation, to no avail, on how to create multi-field indexes in Mongoosejs. In particular I have two fields that need to be indexed and unique. What is an example mongoose schema that indexes two fields together?</p>
12,574,045
4
0
null
2012-09-24 22:20:55.357 UTC
29
2020-03-19 00:48:26.093 UTC
2012-09-24 22:28:09.127 UTC
null
573,769
null
573,769
null
1
109
mongodb|mongoose
89,355
<p>You call the <code>index</code> method on your <code>Schema</code> object to do that as shown <a href="http://mongoosejs.com/docs/guide.html#indexes" rel="noreferrer">here</a>. For your case it would be something like:</p> <pre><code>mySchema.index({field1: 1, field2: 1}, {unique: true}); </code></pre>
3,679,465
Find number of active sessions created from a given client IP
<p>Is there a way to determine the number of active sessions created from a given client IP address?</p>
3,679,783
3
1
null
2010-09-09 18:29:55.297 UTC
10
2017-04-20 22:05:32.87 UTC
2010-09-09 19:13:48.077 UTC
null
157,882
null
389,489
null
1
11
java|session|servlets|ip-address
21,166
<p>The standard Servlet API doesn't offer facilities for that. Best what you can do is to maintain a <a href="http://download.oracle.com/javase/6/docs/api/java/util/Map.html" rel="noreferrer"><code>Map&lt;HttpSession, String&gt;</code></a> yourself (where the <code>String</code> is the IP address) with and check on every <a href="http://download.oracle.com/javaee/5/api/javax/servlet/ServletRequest.html" rel="noreferrer"><code>ServletRequest</code></a> if the <a href="http://download.oracle.com/javaee/5/api/javax/servlet/http/HttpSession.html#isNew%28%29" rel="noreferrer"><code>HttpSession#isNew()</code></a> and add it to the <code>Map</code> along with <a href="http://download.oracle.com/javaee/5/api/javax/servlet/ServletRequest.html#getRemoteAddr%28%29" rel="noreferrer"><code>ServletRequest#getRemoteAddr()</code></a>. Then you can get the amount of IP addresses with an active session using <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#frequency%28java.util.Collection,%20java.lang.Object%29" rel="noreferrer"><code>Collections#frequency()</code></a> on <a href="http://download.oracle.com/javase/6/docs/api/java/util/Map.html#values%28%29" rel="noreferrer"><code>Map#values()</code></a>. You only need to ensure that you remove the <code>HttpSession</code> from the <code>Map</code> during <a href="http://download.oracle.com/javaee/5/api/javax/servlet/http/HttpSessionListener.html#sessionDestroyed%28javax.servlet.http.HttpSessionEvent%29" rel="noreferrer"><code>HttpSessionListener#sessionDestroyed()</code></a>.</p> <p>This all can be done in a single <code>Listener</code> implementing the <a href="http://download.oracle.com/javaee/5/api/javax/servlet/ServletContextListener.html" rel="noreferrer"><code>ServletContextListener</code></a>, <a href="http://download.oracle.com/javaee/5/api/javax/servlet/http/HttpSessionListener.html" rel="noreferrer"><code>HttpSessionListener</code></a> and <a href="http://download.oracle.com/javaee/5/api/javax/servlet/ServletRequestListener.html" rel="noreferrer"><code>ServletRequestListener</code></a>.</p> <p>Here's a kickoff example:</p> <pre><code>public class SessionCounter implements ServletContextListener, HttpSessionListener, ServletRequestListener { private static final String ATTRIBUTE_NAME = "com.example.SessionCounter"; private Map&lt;HttpSession, String&gt; sessions = new ConcurrentHashMap&lt;HttpSession, String&gt;(); @Override public void contextInitialized(ServletContextEvent event) { event.getServletContext().setAttribute(ATTRIBUTE_NAME, this); } @Override public void requestInitialized(ServletRequestEvent event) { HttpServletRequest request = (HttpServletRequest) event.getServletRequest(); HttpSession session = request.getSession(); if (session.isNew()) { sessions.put(session, request.getRemoteAddr()); } } @Override public void sessionDestroyed(HttpSessionEvent event) { sessions.remove(event.getSession()); } @Override public void sessionCreated(HttpSessionEvent event) { // NOOP. Useless since we can't obtain IP here. } @Override public void requestDestroyed(ServletRequestEvent event) { // NOOP. No logic needed. } @Override public void contextDestroyed(ServletContextEvent event) { // NOOP. No logic needed. Maybe some future cleanup? } public static SessionCounter getInstance(ServletContext context) { return (SessionCounter) context.getAttribute(ATTRIBUTE_NAME); } public int getCount(String remoteAddr) { return Collections.frequency(sessions.values(), remoteAddr); } } </code></pre> <p>Define it in <code>web.xml</code> like follows:</p> <pre><code>&lt;listener&gt; &lt;listener-class&gt;com.example.SessionCounter&lt;/listener-class&gt; &lt;/listener&gt; </code></pre> <p>You can use it in any servlet like follows:</p> <pre><code>SessionCounter counter = SessionCounter.getInstance(getServletContext()); int count = counter.getCount("127.0.0.1"); </code></pre>
3,585,444
How can I change AssemblyProduct, AssemblyTitle using MSBuild?
<p>I have an MSBuild script which compiles my existing solution but I'd like to change some properties of one of the projects <em>within</em> the solution at compile-time, including but not limited to AssemblyProduct and AssemblyTitle.</p> <p>Here's a snippet of my build script:</p> <pre><code> &lt;Target Name="Compile" &gt; &lt;MSBuild Projects="..\MySolution.sln" Properties="Configuration=MyReleaseConfig;Platform=x86" /&gt; &lt;/Target&gt; </code></pre> <p>I've got one main executable and several DLLs that are compiled. I am aware of the <a href="http://msbuildextensionpack.codeplex.com/" rel="noreferrer">MSBuild Extension Pack</a> and I suspect it might help me to get to where I need to be, although I'm not sure how to proceed. </p> <p>Can I selectively change AssemblyInfo properties at build time?</p>
3,603,583
3
3
null
2010-08-27 14:58:52.813 UTC
14
2019-01-28 12:13:50.103 UTC
null
null
null
null
37,971
null
1
22
msbuild|assemblyinfo
28,321
<p>You're on the right track with the MSBuild Extension Pack.</p> <p>I find the easiest way to conditionally generate the assembly details at build time is to add an "AssemblyVersion" target <em>directly</em> to my .csproj file(s) that require an updated AssemblyInfo file. You can add the target directly to each csproj file that requires an updated AssemblyInfo file, or as I prefer to do it, create a custom targets file with the AssemblyVersion target and have each csproj file include your custom targets file.</p> <p>Either way you likely want to use the MSBuild Extension Pack or the <a href="https://github.com/loresoft/msbuildtasks/" rel="noreferrer">MSBuild Community Tasks</a> to use their respective AssemblyInfo task.</p> <p>Here's some code from our build scripts:</p> <pre><code>&lt;!-- Import the AssemblyInfo task --&gt; &lt;Import Project="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.Targets"/&gt; &lt;!-- Overriding the Microsoft.CSharp.targets target dependency chain --&gt; &lt;!-- Call our custom AssemblyVersion target before build, even from VS --&gt; &lt;PropertyGroup&gt; &lt;BuildDependsOn&gt; AssemblyVersion; $(BuildDependsOn) &lt;/BuildDependsOn&gt; &lt;/PropertyGroup&gt; &lt;ItemGroup&gt; &lt;AssemblyVersionFiles Include="$(MSBuildProjectDirectory)\Properties\AssemblyInfo.cs"/&gt; &lt;/ItemGroup&gt; &lt;Target Name="AssemblyVersion" Inputs="@(AssemblyVersionFiles)" Outputs="UpdatedAssemblyVersionFiles"&gt; &lt;Attrib Files="%(AssemblyVersionFiles.FullPath)" Normal="true"/&gt; &lt;AssemblyInfo CodeLanguage="CS" OutputFile="%(AssemblyVersionFiles.FullPath)" AssemblyCompany="$(CompanyName)" AssemblyCopyright="Copyright $(CompanyName), All rights reserved." AssemblyVersion="$(Version)" AssemblyFileVersion="$(Version)"&gt; &lt;Output TaskParameter="OutputFile" ItemName="UpdatedAssemblyVersionFiles"/&gt; &lt;/AssemblyInfo&gt; &lt;/Target&gt; </code></pre>
3,853,010
Get item count of a list<> using Linq
<p>I want to query a List&lt;> and find out how MANY items match the selection criteria. using LINQ and c# /.net 3.5. How would I modify the query to return an int count.</p> <pre><code>var specialBook = from n in StoreDisplayTypeList where n.DisplayType=="Special Book" select n; </code></pre>
3,853,024
3
0
null
2010-10-04 05:18:16.193 UTC
2
2017-12-31 06:55:08.753 UTC
2010-10-04 05:24:13.727 UTC
null
2,598
null
1,470,997
null
1
24
c#|linq|asp.net-3.5
78,337
<pre><code> var numSpecialBooks = StoreDisplayTypeList.Count(n =&gt; n.DisplayType == "Special Book"); </code></pre> <p>This uses an overload of <a href="http://msdn.microsoft.com/en-us/library/bb535181.aspx" rel="noreferrer"><code>Enumerable.Count</code></a> that takes a<code>Func&lt;TSource, bool&gt;</code>predicate to filter the sequence.</p>
3,632,952
Can Google Analytics show me visits by hour?
<p>I am interested in seeing visits on my site broken down by hour - is there any way to generate a report of this in Google Analytics? It appears that all metrics are only broken down by day. Maybe I can get this information through the GA API?</p>
24,781,297
3
5
null
2010-09-03 03:55:00.037 UTC
8
2015-07-16 22:53:55.403 UTC
2010-09-03 04:25:20.71 UTC
null
172,322
null
25,688
null
1
40
google-analytics|google-analytics-api
73,587
<p>Since Google Analytics was revised the currently accepted answer is no longer available. The current version of Google Analytics will let you view visitors per hour:</p> <ol> <li>Go to the Reporting Tab</li> <li>Select "Audience"</li> <li>Select "Overview"</li> <li>Select "Hourly"</li> </ol> <p><img src="https://i.stack.imgur.com/22SPG.png" alt="Visitors per hour per day"></p> <p>If you're trying to determine total traffic by hour of the day for a given date range then you can use this custom report:</p> <p><a href="https://www.google.com/analytics/web/permalink?type=custom_report&amp;uid=pToP7693ReSxfSIpbqHmWg">https://www.google.com/analytics/web/permalink?type=custom_report&amp;uid=pToP7693ReSxfSIpbqHmWg</a></p> <p><img src="https://i.stack.imgur.com/Azck9.png" alt="Vistors per hour"></p>
3,510,846
How to remove list of words from a list of strings
<p>Sorry if the question is bit confusing. This is similar to <a href="https://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings">this question</a></p> <p>I think this the above question is close to what I want, but in Clojure. </p> <p>There is <a href="https://stackoverflow.com/questions/3136689/find-and-replace-string-values-in-python-list">another</a> question </p> <p>I need something like this but instead of '[br]' in that question, there is a list of strings that need to be searched and removed.</p> <p>Hope I made myself clear. </p> <p>I think that this is due to the fact that strings in python are immutable.</p> <p>I have a list of noise words that need to be removed from a list of strings.</p> <p>If I use the list comprehension, I end up searching the same string again and again. So, only "of" gets removed and not "the". So my modified list looks like this</p> <pre><code>places = ['New York', 'the New York City', 'at Moscow' and many more] noise_words_list = ['of', 'the', 'in', 'for', 'at'] for place in places: stuff = [place.replace(w, "").strip() for w in noise_words_list if place.startswith(w)] </code></pre> <p>I would like to know as to what mistake I'm doing.</p>
3,510,894
4
1
null
2010-08-18 09:52:47.513 UTC
11
2012-10-07 23:15:17.717 UTC
2017-05-23 10:30:08.663 UTC
null
-1
null
24,382
null
1
10
python|regex|list-comprehension|stop-words
18,780
<p>Here is my stab at it. This uses regular expressions. </p> <pre><code>import re pattern = re.compile("(of|the|in|for|at)\W", re.I) phrases = ['of New York', 'of the New York'] map(lambda phrase: pattern.sub("", phrase), phrases) # ['New York', 'New York'] </code></pre> <p>Sans <code>lambda</code>:</p> <pre><code>[pattern.sub("", phrase) for phrase in phrases] </code></pre> <p><strong>Update</strong> </p> <p>Fix for the bug pointed out by <a href="https://stackoverflow.com/users/174728/gnibbler">gnibbler</a> (thanks!):</p> <pre><code>pattern = re.compile("\\b(of|the|in|for|at)\\W", re.I) phrases = ['of New York', 'of the New York', 'Spain has rain'] [pattern.sub("", phrase) for phrase in phrases] # ['New York', 'New York', 'Spain has rain'] </code></pre> <p>@prabhu: the above change avoids snipping off the trailing "<em>in</em>" from "Spain". To verify run both versions of the regular expressions against the phrase "Spain has rain".</p>
10,908,929
what is my HAProxy version?
<p>I installed HAProxy for load ballancing before. How can I check what is my haproxy version which installed before in mu ubuntu? </p>
11,725,470
5
0
null
2012-06-06 06:04:10.143 UTC
2
2020-12-11 11:13:04.117 UTC
null
null
null
null
1,192,227
null
1
24
version|haproxy
44,294
<p>haproxy --version</p> <p>If you want to see the package info on Ubuntu, you can use 'aptitude show haproxy' to get version and other details about what's installed.</p>
11,236,630
Can apple push notifications send more parameters than alert and sound?
<p>I have several pieces of metadata that I need to associate with a push notification.</p> <p>For example user no, message id.</p> <p>Can I send more parameters than what apple supports:</p> <pre><code> {aps = { alert = joetheman; sound = default; };} </code></pre> <p>Is this possible?</p>
11,236,671
4
0
null
2012-06-28 00:36:31.543 UTC
13
2019-07-02 20:02:41.57 UTC
null
null
null
null
84,885
null
1
26
ios|push-notification
43,276
<p>Yes. In the Push Notification Programming Guide section <a href="https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW1" rel="noreferrer">The Notification Payload</a> it states</p> <blockquote> <p>Providers can specify custom payload values outside the Apple-reserved aps namespace. Custom values must use the JSON structured and primitive types: dictionary (object), array, string, number, and Boolean. You should not include customer information as custom payload data. Instead, use it for such purposes as setting context (for the user interface) or internal metrics. For example, a custom payload value might be a conversation identifier for use by an instant-message client application or a timestamp identifying when the provider sent the notification. Any action associated with an alert message should not be destructive—for example, deleting data on the device.</p> </blockquote> <p>So your payload might look like</p> <pre><code>{ "aps": { "alert": "joetheman", "sound": "default" }, "message": "Some custom message for your app", "id": 1234 } </code></pre> <p>Further down on that same page are a number of examples that demonstrate this.</p>
10,935,763
github picture path
<h1>pictures can't show in github</h1> <p>I use markdown to write note, and when I want to add a picture, I do this:</p> <p><code>![Alt desc](/home/user_name/repo_name/pic/pic_name "desc")</code></p> <p>here comes a problem, when I <code>git push</code> the repo, the github coouldn't recognize the </p> <p>absolute path in my computer</p> <p>so my <strong>question</strong> is that what the picture path is in github and markdown file?</p>
10,936,427
2
0
null
2012-06-07 16:17:26.01 UTC
7
2012-06-08 05:33:18.417 UTC
null
null
null
null
1,415,715
null
1
30
github
21,263
<p>You're expected to use an absolute path to a http accessible image</p> <ul> <li><code>![Alt desc](http://www.example.com/image.png)</code></li> </ul> <p>If you're willing to link against your own repository, you should use the <strong><a href="https://stackoverflow.com/a/4605068/335418"><code>raw</code> url format</a></strong>.</p> <p>For instance, the following markdown </p> <ul> <li><code>![logo](https://github.com/libgit2/libgit2sharp/raw/master/square-logo.png)</code></li> </ul> <p>should display the following image</p> <p><img src="https://github.com/libgit2/libgit2sharp/raw/master/square-logo.png" alt="logo"></p> <p><strong>Note:</strong> An alternate raw format is also supported. The image above can also be accessed through the following url: <a href="https://raw.github.com/libgit2/libgit2sharp/master/square-logo.png" rel="noreferrer">https://raw.github.com/libgit2/libgit2sharp/master/square-logo.png</a></p> <h1>Update</h1> <p>Following your comment.</p> <p>The following markdown in <a href="https://github.com/liangxiao3/redhat_note/blob/master/basic_option.md" rel="noreferrer">basic_option.md</a> won't work.</p> <ul> <li><code>&gt; ![Alt vmware](https://github.com/liangxiao3/redhat_note/blob/master/pic/basic_vmware.jpg "vmware tool")</code></li> </ul> <p>Switching it to the markdown below should fix this Indeed, you didn't use the <strong>raw url format</strong> (see above)</p> <ul> <li><code>![Alt vmware](https://github.com/liangxiao3/redhat_note/raw/master/pic/basic_vmware.jpg)</code></li> </ul>
11,342,897
How to compare two UIImage objects
<p>I am developing one application.In that i am using the <code>imageviews</code>.SO before changeing the <code>UIImageview</code> image I need to take that image in <code>UIimage</code> obejct and compare with another <code>UIImage</code> object for finding both are sam or not. So please tell me how to do that one.</p>
11,342,977
19
2
null
2012-07-05 10:55:45.647 UTC
15
2020-08-10 17:30:50.13 UTC
2012-09-05 14:27:45.427 UTC
null
1,415,038
null
1,498,119
null
1
74
ios
59,239
<p>One way is to convert them to image data first, and then compare that.</p> <pre><code>- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2 { NSData *data1 = UIImagePNGRepresentation(image1); NSData *data2 = UIImagePNGRepresentation(image2); return [data1 isEqual:data2]; } </code></pre>
12,784,144
change img src on click
<p>I have searched the forum for one particular issue, yet all the solutions I found do not work for my problem.</p> <p>I have an image on the left hand side. On the right hand side, I have different words. So, When I click on a particular name, I want the picture to change to whatever picture I have in my image folder. Basically, I want the source of the image to change. Here is the code for my index:</p> <pre><code>&lt;div id="picture_here"&gt; &lt;img src="images/mtkili.png" id="picture"/&gt; &lt;/div&gt; &lt;div id="about"&gt; &lt;div id="mtl"&gt;Mtl&lt;/div&gt; &lt;/div&gt; &lt;div id="about_2"&gt; &lt;div id="contact"&gt;SF&lt;/div&gt; &lt;/div&gt; </code></pre> <p>and here are two jqueries formulas I tried:</p> <pre><code>$('#mtl').click(function(){ $('#picture').attr()({ 'src':'images/short.png' }) }) </code></pre> <p>and:</p> <pre><code>$('#mtl').click(function(){ $('#picture').attr('src', 'images/short.png'); }); </code></pre>
12,784,242
5
5
null
2012-10-08 14:49:59.657 UTC
5
2018-01-15 07:45:43.7 UTC
2014-07-14 17:57:47.907 UTC
null
321,731
null
1,729,155
null
1
15
jquery|image|src
79,353
<p>Your second attempt is correct. Here is the working jsFiddle: <a href="http://jsfiddle.net/MEHhs/">http://jsfiddle.net/MEHhs/</a></p> <p>So the code should be:</p> <p>html:</p> <pre><code>&lt;div id="picture_here"&gt; &lt;img src="http://www.sbtjapan.com/img/FaceBook_img.jpg" id="picture"/&gt; &lt;/div&gt; &lt;div id="about"&gt; &lt;div id="mtl"&gt;Mtl&lt;/div&gt; &lt;/div&gt; &lt;div id="about_2"&gt; &lt;div id="contact"&gt;SF&lt;/div&gt; &lt;/div&gt;​ </code></pre> <p>js:</p> <pre><code>$('#mtl').click(function(){ $('#picture').attr('src', 'http://profile.ak.fbcdn.net/hprofile-ak-ash3/41811_170099283015889_1174445894_q.jpg'); }); </code></pre> <p>I've added some existing images found on google.</p>
13,214,241
C++ Constructors vs Initialization Lists speed comparison
<p>Are there any differences in execution time between constructors and initialization lists?(or is it just a matter of coding preference). I have a set of objects that needs to be created frequently and would like to know if there is any performance gain by using initialization lists instead of constructors.</p> <p>If I were to create a million instances of class A and another million of class B which choice would be better(the objects represent packets generated within a network hence these numbers).</p> <pre><code> class A { private: int a, b; public: A(int a_var, int b_var):a(a_var), b(b_var) {}; }; class B { private: int a, b; public: B(int a_var, int b_var) { a = a_var; b = b_var; } }; </code></pre> <p>If any of the constructors is faster than the other for primitive types(as in the example) will it be faster if a and b were to be replaced by types?</p> <p>Type example:</p> <pre><code> class AType { private: string a, b; public: AType(string a_var, string b_var):a(a_var), b(b_var) {}; }; </code></pre>
13,214,310
5
4
null
2012-11-03 22:44:02.083 UTC
9
2013-09-02 13:57:32.34 UTC
2013-09-02 13:57:32.34 UTC
null
2,064,216
null
1,079,483
null
1
22
c++|constructor|initialization-list
21,560
<p>The difference is for types with no trivial default constructor, which is called for you by compiler in your class <code>B</code>. Your class <code>B</code> is equivalent to:</p> <pre><code> class B { private: SleepyInt a, b; public: // takes at least 20s B(int a_var, int b_var) : a(), b() // ^^^^^^^^^^ { a = a_var; b = b_var; } }; </code></pre> <p>If you do not place member variable or base class constructor in initialization list - ithe default constructor is called for them. <code>int</code> is basic type - its default constructor costs nothing - so no difference in your example, but for more complex types constructor+assignment might cost more than just constructing.</p> <p>Some funny example, just to illustrate the difference:</p> <pre><code>class SleepyInt { public: SleepyInt () { std::this_thread::sleep_for(std::chrono::milliseconds( 10000 )); } SleepyInt (int i) {} SleepyInt &amp; operator = (int i) { return *this; } }; class A { private: SleepyInt a, b; public: A(int a_var, int b_var):a(a_var), b(b_var) {}; }; class B { private: SleepyInt a, b; public: // takes at least 20s B(int a_var, int b_var) { a = a_var; b = b_var; } }; </code></pre>
17,037,937
XAMPP: Another web server daemon is already running?
<p>I have painfully analyzed all of yesterday if I had another apache/web-server instance running, with all of these commands</p> <pre><code>ps aux ps -e lsof netstat tunap </code></pre> <p>I DO NOT have another instance of Apache or ANY OTHER server running at port 8080.</p> <p>Yet, XAMPP gives me this:</p> <pre><code>XAMPP: Another web server daemon is already running </code></pre> <p>What should I do?</p> <p>I also edited httpd.conf to LISTEN to port 9876, and still the same.</p>
17,371,371
11
0
null
2013-06-11 06:40:30.16 UTC
4
2022-08-29 15:45:43.443 UTC
null
null
null
null
2,358,206
null
1
16
linux|apache|unix|ubuntu|xampp
41,077
<p>If:</p> <pre><code>lsof -Pi |grep 8080 returns no results netstat -na |grep 8080 returns no results ps -ef shows no web server processes </code></pre> <p>Then maybe there's a lockfile lying around that the startup is checking against? Those are typically found under /var/run but don't necessarily have to. At this point I would usually run strace to see what's going on:</p> <p>strace -e read=all -e write=all -f -o strace.out <strong>your_startup_command</strong></p> <p>Then open up strace.out, search for the "..is already running" string in the output, and starting looking at lines above it to see what is failing.</p>
17,126,037
How to delete only the content of file in python
<p>I have a temporary file with some content and a python script generating some output to this file. I want this to repeat N times, so I need to reuse that file (actually array of files). I'm deleting the whole content, so the temp file will be empty in the next cycle. For deleting content I use this code:</p> <pre><code>def deleteContent(pfile): pfile.seek(0) pfile.truncate() pfile.seek(0) # I believe this seek is redundant return pfile tempFile=deleteContent(tempFile) </code></pre> <p>My question is: Is there any other (better, shorter or safer) way to delete the whole content without actually deleting the temp file from disk?</p> <p>Something like <code>tempFile.truncateAll()</code>?</p>
17,126,137
5
5
null
2013-06-15 17:15:33.523 UTC
11
2022-02-16 14:45:13.48 UTC
null
null
null
null
2,428,361
null
1
38
python|file-io|seek
114,556
<blockquote> <p>How to delete only the content of file in python</p> </blockquote> <p>There are several ways of setting the logical size of a file to 0, depending how you access that file:</p> <p>To empty an open file:</p> <pre><code>def deleteContent(pfile): pfile.seek(0) pfile.truncate() </code></pre> <hr> <p>To empty an open file whose file descriptor is known:</p> <pre><code>def deleteContent(fd): os.ftruncate(fd, 0) os.lseek(fd, 0, os.SEEK_SET) </code></pre> <hr> <p>To empty a closed file (whose name is known)</p> <pre><code>def deleteContent(fName): with open(fName, &quot;w&quot;): pass </code></pre> <hr><hr> <blockquote> <p>I have a <strong>temporary file</strong> with some content [...] I need to <strong>reuse</strong> that file</p> </blockquote> <p>That being said, <em>in the general case</em> it is probably not efficient nor desirable to <em>reuse</em> a temporary file. Unless you have very specific needs, you should think about using <a href="https://docs.python.org/2/library/tempfile.html" rel="nofollow noreferrer"><code>tempfile.TemporaryFile</code></a> and a <em>context manager</em> to almost transparently create/use/delete your temporary files:</p> <pre><code>import tempfile with tempfile.TemporaryFile() as temp: # do whatever you want with `temp` # &lt;- `tempfile` guarantees the file being both closed *and* deleted # on the exit of the context manager </code></pre>
16,961,921
Plot data in descending order as appears in data frame
<p>I've been battling to order and plot a simple dataframe as a bar chart in ggplot2. </p> <p>I want to plot the data as it appears, so that the values ('count' variable) for the corresponding categories (e.g. 'humans', 'male') are plotted from high to low. </p> <p>I've followed other threads on this site asking similar questions, but can't get this to work!</p> <pre><code>## Dataset (mesh2) #Category Count #Humans 62 #Male 40 #Female 38 #Adult 37 #Middle Aged 30 #Liver/anatomy &amp; histology 29 #Organ Size 29 #Adolescent 28 #Child 21 #Liver/radiography* 20 #Liver Transplantation* 20 #Tomography, X-Ray Computed 20 #Body Weight 18 #Child, Preschool 18 #Living Donors* 18 #Infant 16 #Aged 14 #Body Surface Area 14 #Regression Analysis 11 #Hepatectomy 10 ## read in data (mesh2) as object (mesh2) mesh2 &lt;- read.csv("mesh2.csv", header = T) ## order data by count of mesh variable mesh2$cat2 &lt;- order(mesh2$Category, mesh2$Count, decreasing=TRUE) ## Barplot created in ggplot2 library(ggplot2) mesh2p &lt;- ggplot(mesh2, aes(x=cat2, y=Count)) + geom_bar (stat="identity") + scale_x_continuous(breaks=c(1:20), labels=c("Humans", "Male", "Female", "Adult", "MAged", "Liver anat &amp; hist", "Organ Size", "Adolescent", "Child", "Liver radiog", "Liver Transplnt", "Tomog X-Ray Computed", "Body Weight", "Child Preschool", "Living Donors", "Infant", "Aged", "BSA", "Regression Analysis", "Hepatectomy"))+ theme (axis.text.x=element_text(angle=45, hjust=1)) </code></pre>
16,968,999
1
3
null
2013-06-06 12:19:41.163 UTC
30
2019-01-31 15:58:01.487 UTC
2019-01-31 15:58:01.487 UTC
null
10,607,772
null
1,389,344
null
1
51
r|ggplot2
152,162
<p>You want <code>reorder()</code>. Here is an example with dummy data</p> <pre><code>set.seed(42) df &lt;- data.frame(Category = sample(LETTERS), Count = rpois(26, 6)) require("ggplot2") p1 &lt;- ggplot(df, aes(x = Category, y = Count)) + geom_bar(stat = "identity") p2 &lt;- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) + geom_bar(stat = "identity") require("gridExtra") grid.arrange(arrangeGrob(p1, p2)) </code></pre> <p>Giving:</p> <p><img src="https://i.stack.imgur.com/ShJSY.png" alt="enter image description here"></p> <p>Use <code>reorder(Category, Count)</code> to have <code>Category</code> ordered from low-high.</p>
16,660,039
Where is the layout preview in Android Studio?
<p>I installed Android Studio, but when I edit my layout files, I can't find a live preview! I just see an XML file. How can I see my layout in graphical view?</p> <p>This is how it looks like in my case:</p> <p><img src="https://i.stack.imgur.com/A6M7G.jpg" alt="enter image description here" /></p>
16,660,112
25
4
null
2013-05-20 23:52:17.553 UTC
34
2022-09-20 07:28:16.12 UTC
2021-09-15 12:31:08.293 UTC
null
40,342
null
1,037,845
null
1
182
android|android-studio
327,890
<p><strong>UPDATE 2 (2020-03-16)</strong></p> <p>The newer Android Studio version changed the location of this button. Now if you want to see the layout design preview you will need to press one of the buttons at the top right of your xml. The button that looks like an image icon will open the design dashboard, while the button next to it will open the split view where the design is placed next to the XML code:</p> <p><a href="https://i.stack.imgur.com/CJRiu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CJRiu.png" alt="enter image description here"></a> </p> <p><strong>ORIGINAL (2013-05-21)</strong></p> <p>You should have a <code>Design</code> button next to the <code>Text</code> button under the xml text editor:</p> <p><img src="https://i.stack.imgur.com/L3Fgq.jpg" alt="enter image description here"></p> <p>Or you can use the <code>Preview</code> button in the upper right corner to add a preview window next to the XML code:</p> <p><img src="https://i.stack.imgur.com/t4rkn.jpg" alt="enter image description here"></p> <p><strong>UPDATE:</strong></p> <p>If you dont have it, then do this: <code>View</code> -> <code>Tool Windows</code> -> <code>Preview</code></p> <p><img src="https://i.stack.imgur.com/y5VnU.jpg" alt="enter image description here"></p>
17,106,681
parseInt vs unary plus, when to use which?
<p>What are the differences between this line:</p> <pre><code>var a = parseInt("1", 10); // a === 1 </code></pre> <p>and this line</p> <pre><code>var a = +"1"; // a === 1 </code></pre> <p>This <a href="http://jsperf.com/parseint-vs-unary-operator" rel="noreferrer">jsperf test</a> shows that the unary operator is much faster in the current chrome version, assuming it is for node.js!?</p> <p>If I try to convert strings which are not numbers both return <code>NaN</code>:</p> <pre><code>var b = parseInt("test" 10); // b === NaN var b = +"test"; // b === NaN </code></pre> <p>So when should I prefer using <code>parseInt</code> over the unary plus (especially in node.js)???</p> <p><strong>edit</strong>: and what's the difference to the double tilde operator <code>~~</code>?</p>
17,106,701
6
2
null
2013-06-14 10:44:56.317 UTC
123
2022-04-04 10:48:21.99 UTC
2020-06-01 21:50:01.813 UTC
null
1,483,676
null
1,056,711
null
1
192
javascript|node.js
56,533
<p>Well, here are a few differences I know of:</p> <ul> <li><p>An empty string <code>&quot;&quot;</code> evaluates to a <code>0</code>, while <code>parseInt</code> evaluates it to <code>NaN</code>. IMO, a blank string should be a <code>NaN</code>.</p> <pre><code> +'' === 0; //true isNaN(parseInt('',10)); //true </code></pre> </li> <li><p>The unary <code>+</code> acts more like <code>parseFloat</code> since it also accepts decimals.</p> <p><code>parseInt</code> on the other hand stops parsing when it sees a non-numerical character, like the period that is intended to be a decimal point <code>.</code>.</p> <pre><code> +'2.3' === 2.3; //true parseInt('2.3',10) === 2; //true </code></pre> </li> <li><p><code>parseInt</code> and <code>parseFloat</code> parses and builds the string <em>left to right</em>. If they see an invalid character, it returns what has been parsed (if any) as a number, and <code>NaN</code> if none was parsed as a number.</p> <p>The unary <code>+</code> on the other hand will return <code>NaN</code> if the entire string is non-convertible to a number.</p> <pre><code> parseInt('2a',10) === 2; //true parseFloat('2a') === 2; //true isNaN(+'2a'); //true </code></pre> </li> <li><p>As seen in the comment of <a href="https://stackoverflow.com/users/246342">@Alex K.</a>, <code>parseInt</code> and <code>parseFloat</code> will parse by character. This means hex and exponent notations will fail since the <code>x</code> and <code>e</code> are treated as non-numerical components (at least on base10).</p> <p>The unary <code>+</code> will convert them properly though.</p> <pre><code> parseInt('2e3',10) === 2; //true. This is supposed to be 2000 +'2e3' === 2000; //true. This one's correct. parseInt(&quot;0xf&quot;, 10) === 0; //true. This is supposed to be 15 +'0xf' === 15; //true. This one's correct. </code></pre> </li> </ul>
4,499,732
internationalization in JSF with ResourceBundle entries which are loaded from database
<p>I'm working on a Java EE6 project using JPA/EJB/JSF and I'm having some trouble designing multiple language support for entities. There are three relevant entities:</p> <p>Language (has id)<br> Competence (has id)<br> CompetenceName (has Competence reference, Language reference and a String) </p> <p>Competence has a one-to-many reference to CompetenceName implemented with a Map, containing one object for every Language that there exists a name for a Competence. Note that competences are created <strong>dynamically</strong> and their names can thus not exist in a resource bundle.</p> <p>When listing the Competences on a web page, I want them to show with the language of the currently logged in user, this is stored in a Session Scoped Managed Bean.</p> <p>Is there any good way to accomplish this without breaking good MVC design? My first idea was to get the session scoped bean directly from a "getName" method in the Competence entity via FacesContext, and look in the map of CompetenceNames for it as following:</p> <pre><code>public class Competence { ... @MapKey(name="language") @OneToMany(mappedBy="competence", cascade=CascadeType.ALL, orphanRemoval=true) private Map&lt;Language, CompetenceName&gt; competenceNames; public String getName(String controller){ FacesContext context = FacesContext.getCurrentInstance(); ELResolver resolver = context.getApplication().getELResolver(); SessionController sc = (SessionController)resolver.getValue(context.getELContext(), null, "sessionController"); Language language = sc.getLoggedInUser().getLanguage(); if(competenceNames.get(language) != null) return competenceNames.get(language).getName(); else return "resource missing"; } </code></pre> <p>This solution feels extremly crude since the entity relies on the Controller layer, and have to fetch a session controller every time I want its name. A more MVC compliant solution would be to take a Language parameter, but this means that every single call from JSF will have to include the language fetched from the session scoped managed bean which does not feel like a good solution either.</p> <p>Does anyone have any thoughts or design patterns for this issue?</p>
4,500,633
2
0
null
2010-12-21 13:27:08.857 UTC
12
2013-09-10 19:08:49.413 UTC
2013-09-09 00:44:26.073 UTC
null
157,882
null
546,128
null
1
11
database|jsf|jpa|internationalization|resourcebundle
6,997
<p>Internationalization/localization should preferably be entirely done in the view side. The model shouldn't be aware of this.</p> <p>In JSF, the <code>&lt;resource-bundle&gt;</code> entry in <code>faces-config.xml</code> and the <code>&lt;f:loadBundle&gt;</code> in XHTML can also point to a fullworthy <code>ResourceBundle</code> class instead of basename of <code>.properties</code> files. In Java SE 6 there's a new <a href="http://download.oracle.com/javase/6/docs/api/java/util/ResourceBundle.Control.html" rel="noreferrer"><code>ResourceBundle.Control</code></a> API available which allows full control over loading and filling the bundle.</p> <p>Knowing those facts, it should be possible to load the bundle messages from the DB with a custom <code>ResourceBundle</code> and <code>Control</code>. Here's a kickoff example:</p> <pre class="lang-java prettyprint-override"><code>public class CompetenceBundle extends ResourceBundle { protected static final String BASE_NAME = "Competence.messages"; // Can be name of @NamedQuery protected static final Control DB_CONTROL = new DBControl(); private Map&lt;String, String&gt; messages; public CompetenceBundle() { setParent(ResourceBundle.getBundle(BASE_NAME, FacesContext.getCurrentInstance().getViewRoot().getLocale(), DB_CONTROL)); } protected CompetenceBundle(Map&lt;String, String&gt; messages) { this.messages = messages; } @Override protected Object handleGetObject(String key) { return messages != null ? messages.get(key) : parent.getObject(key); } @Override public Enumeration&lt;String&gt; getKeys() { return messages != null ? Collections.enumeration(messages.keySet()) : parent.getKeys(); } protected static class DBControl extends Control { @Override public ResourceBundle newBundle (String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { String language = locale.getLanguage(); Map&lt;String, String&gt; messages = getItSomehow(baseName, language); // Do your JPA thing. The baseName can be used as @NamedQuery name. return new CompetenceBundle(messages); } } } </code></pre> <p>This way you can declare it as follows in <code>faces-config.xml</code>:</p> <pre class="lang-xml prettyprint-override"><code>&lt;resource-bundle&gt; &lt;base-name&gt;com.example.i18n.CompetenceBundle&lt;/base-name&gt; &lt;var&gt;competenceBundle&lt;/var&gt; &lt;/resource-bundle&gt; </code></pre> <p>Or as follows in the Facelet:</p> <pre class="lang-html prettyprint-override"><code>&lt;f:loadBundle basename="com.example.i18n.CompetenceBundle" var="competenceBundle" /&gt; </code></pre> <p>Either way, you can use it the usual way:</p> <pre class="lang-html prettyprint-override"><code>&lt;h:outputText value="#{competenceBundle.name}" /&gt; </code></pre>
9,757,222
SQL query to exclude certain values from table
<p><img src="https://i.stack.imgur.com/IGeE2.png" alt="enter image description here"></p> <p>Hi everyone I am in the process of building a room allocating system that checks if a room is available on a given date. There are about 20 unique room ids and I've just included as snippet of several above. </p> <p>So for example if the user types in the date of 2012-01-01 I would want the <strong>room_id</strong> of 1 to be excluded from the results because as seen above it has been already booked for that date.</p> <p>In a sense any match found between the user's in-putted date should cause the entire list of corresponding room_id's to be excluded from the list.</p> <p>I used the below SQL query:</p> <pre><code>SELECT DISTINCT room_id FROM room_booking WHERE date_booked&lt;&gt;'$date' </code></pre> <p>Unfortunately it doesn't work because although it excludes the result for a single row, it includes the rest of the results for a given <em>room_id</em>? </p>
9,757,249
4
1
null
2012-03-18 09:19:43.967 UTC
4
2020-03-12 16:05:56.58 UTC
2012-03-18 11:07:59.753 UTC
null
436,493
null
436,493
null
1
5
sql
66,015
<p>Not tried this, but here goes</p> <pre><code>SELECT DISTINCT room_id FROM room_booking WHERE room_id NOT IN (SELECT DISTINCT room_id FROM room_booking WHERE date_booked = '$date' ) </code></pre>
9,967,558
Only allow two digits after decimal in textbox?
<p>I have a textbox where the user enters a number, but how can i make it so that if they type the '.' after it it only allows 2 decimal places?</p> <pre><code>private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) &amp;&amp; !char.IsDigit(e.KeyChar) &amp;&amp; e.KeyChar != '.') { e.Handled = true; } // only allow one decimal point if (e.KeyChar == '.' &amp;&amp; (sender as TextBox).Text.IndexOf('.') &gt; -1) { e.Handled = true; } } </code></pre>
9,967,694
7
2
null
2012-04-01 19:29:48.493 UTC
3
2022-07-14 08:16:58.127 UTC
2012-04-01 19:31:46.293 UTC
user166390
null
null
710,502
null
1
6
c#|winforms
42,370
<p>Just add: </p> <pre><code>if (Regex.IsMatch(textBox1.Text, @"\.\d\d")) { e.Handled = true; } </code></pre> <p>to the end of your function</p>
9,795,677
How to design global distributed transaction(none database)? Can JTA use for none db transaction?
<p>I think this is a fairly common question: how to put my business logic in a global transaction in distributed systems environment? Cite an example, I have a TaskA containing couples of sub tasks:</p> <p>TaskA {subtask1, subtask2, subtask3 ... }</p> <p>each of these subtasks may execute on local machine or a remote one, I hope TaskA executes in an atomic manner(success or fail) by means of transaction. Every subtask has a rollback function, once TaskA thinks the operation fails(because one of subtask fails), it calls each rollback function of subtasks. Otherwise TaskA commits the whole transaction.</p> <p>To do this, I follow "Audit trial" transaction pattern to have a record for each subtask, so TaskA can know operation results of subtasks then decide rollback or commit. This sounds like simple, however, the hard part is how to associate each subtask to the global transaction?</p> <p>When TaskA begins, it starts a global transaction about which subtask knows nothing. To make subtask aware of it, I have to pass the transaction context to every invocation of subtask. This is really dreadful! My subtask may either execute in a new thread or execute in remote by sending a message through AMQP broker, it's hard to consolidate the way of context propagation. </p> <p>I did some research like "Transaction Patterns - A Collection of Four Transaction Related Patterns", "Checked Transactions in an Asynchronous Message Passing Environment", none of these solve my problem. They either don't have practical example or don't solve the context propagation issue. </p> <p>I wonder how people solve this? as this sort of transaction must be common in enterprise software.</p> <p>Is X/Open XA only the solution for this? Can JTA help here(I have't look into JTA as most stuff for it relate to database transaction, and I am using Spring, I don't want to involve another Java EE application server in my software).</p> <p>Can some expert share some thoughts with me? thank you.</p> <h2>Conclusion</h2> <p><strong>Arjan and Martin gave out really good answers, thank you. Finally I didn't go with this way.</strong> After more research, I chose another pattern "<strong>CheckPoint</strong>" <a href="http://ncomprod.nokia.com/library/files/docs/Design_Patterns_for_Checkpoint-Based_Rollback_Recovery.pdf" rel="noreferrer" title="Check Point">1</a>.</p> <p>Looking into my requirement, I found my intention to "Audit Trial Transaction Pattern" is to know which level the operation has proceeded to, if it's failed, I can restart it at the failed spot after reloading some context. Actually this is not transaction, it didn't rollback other successful steps after failure. This is essence of CheckPoint pattern. However, studying distributed transaction stuff makes me learned lot of interesting things. Apart from what Arjan and Martin have mentioned. I also suggest people digging into this area take a look at CORBA which is a well-known protocol for distributed system.</p>
9,812,637
3
2
null
2012-03-20 22:00:56.4 UTC
11
2015-07-22 08:07:51.813 UTC
2013-12-03 16:18:11.49 UTC
null
-1
null
1,162,747
null
1
17
java|jta|distributed-transactions
9,486
<p>You're right, you need two-phase commit support thanks to a XA transaction manager provided by the JTA API.</p> <p>As far as I know Spring does not provide a transaction manager implementation itself. The <a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/transaction/jta/JtaTransactionManager.html">JtaTransactionManager</a> only delegates to existing implementation usually provided from JavaEE implementations.</p> <p>So you will have to plugin a JTA implementation into Spring to get effective job done. Here are some proposals:</p> <ul> <li><a href="http://jotm.ow2.org/xwiki/bin/view/Main/WebHome">JOTM</a></li> <li><a href="http://www.jboss.org/jbosstm">JBossTS</a> based on Arjuna.</li> <li><a href="http://www.atomikos.com/Main/TransactionsEssentials">Atokimos</a></li> </ul> <p>Then you will have to implement your resource manager to support two-phase commit. In the JavaEE worlds, it consists in a resource adapter packaged as a RAR archive. Depending on the type of resource, the following aspects are to read/implement:</p> <ul> <li><a href="http://docs.oracle.com/javaee/6/api/javax/transaction/xa/XAResource.html">XAResource</a> interface</li> <li><a href="http://java.sys-con.com/node/46283">JCA Java Connector Architecture</a> mainly if a remote connection is involved</li> <li><a href="http://www.developer.com/java/ent/article.php/10933_2224921_4/Transaction-Services-with-JTA-and-JTS.htm">JTS Transaction Service</a> if transaction propagation between nodes is required</li> </ul> <p>As examples, I recommend you to look at implementations for the classical "transactions with files" issue:</p> <ul> <li>the <a href="http://www.jboss.org/jbosstm/fileio">transactional file manager</a> from JBoss Transactions</li> <li><a href="http://xadisk.java.net/">XADisk project</a></li> </ul>
10,161,840
Eclipse: change name of existing package with classes inside
<p>In Eclipse, is it possible to change name of the package if it has name <code>(default package)</code> and has classes inside it?</p>
10,161,882
6
0
null
2012-04-15 12:02:15.807 UTC
10
2019-06-22 20:29:38.06 UTC
2015-10-14 22:15:16.83 UTC
null
4,561,047
null
480,632
null
1
46
java|eclipse
98,871
<p>In the version of Eclipse I'm using (Indigo service release 1), the "Rename" option doesn't come up for the default package (unlike other packages) - but if you select all the classes then right-click and select "Move" that will let you put them in a new package.</p> <p>(As far as I can tell, the Rename option is for renaming classes <em>without</em> changing their package, but Move certainly works for moving <em>between</em> packages.)</p> <p>Screenshots of the process:</p> <p><strong>Original situation</strong></p> <p><img src="https://i.stack.imgur.com/39H2l.png" alt="Before"></p> <p><strong>Select all classes and show the Refactor part of the context menu</strong></p> <p><img src="https://i.stack.imgur.com/3UWgI.png" alt="enter image description here"></p> <p><strong>Select "Move", click on Create Package and type in a name (mypackage in this case)</strong></p> <p><img src="https://i.stack.imgur.com/aklYG.png" alt="Move dialog"></p> <p><strong>The final result</strong></p> <p><img src="https://i.stack.imgur.com/o81wH.png" alt="After"></p> <p>Alternatively, if you want to move them to an existing package, you could just drag and drop the classes.</p> <p>For those suggesting Refactor -> Rename on the package, here's a screenshot showing that <em>not</em> working on my machine:</p> <p><img src="https://i.stack.imgur.com/5OkGE.png" alt="No Rename option"></p>
9,809,557
use a relative path in requirements.txt to install a tar.gz file with pip
<p>We're using a requirements.txt file to store all the external modules needed. Every module but one is gathered from internet. The other one is stored on a folder under the one holding the requirements.txt file.</p> <p>BTW, this module can be easily installed with pip install </p> <p>I've tried using this:</p> <pre><code>file:folder/module </code></pre> <p>or this:</p> <pre><code>file:./folder/module </code></pre> <p>or even this:</p> <pre><code>folder/module </code></pre> <p>but always throws me an error. Does anyone know which is the right way to do this?</p> <p>Thanks</p>
12,921,216
5
0
null
2012-03-21 17:14:22.793 UTC
8
2021-11-19 17:27:33.237 UTC
null
null
null
null
1,240,305
null
1
59
python|pip
63,777
<p>In the current version of pip (1.2.1) the way relative paths in a requirements file are interpreted is ambiguous and semi-broken. There is an open issue on the pip repository which explains the various problems and ambiguities in greater detail:</p> <p><a href="https://github.com/pypa/pip/issues/328">https://github.com/pypa/pip/issues/328</a></p> <p>Long story short the current implementation does not match the description in the pip documentation, so as of this writing there is no consistent and reliable way to use relative paths in <code>requirements.txt</code>.</p> <p>THAT SAID, placing the following in my <code>requirements.txt</code>:</p> <pre><code>./foo/bar/mymodule </code></pre> <p>works when there is a <code>setup.py</code> at the top level of the <code>mymodule</code> directory. Note the lack of the <code>file::</code> protocol designation and the inclusion of the leading <code>./</code>. This path is not relative to the <code>requirements.txt</code> file, but rather to the current working directory. Therefore it is necessary to navigate into the same directory as the <code>requirements.txt</code> and then run the command:</p> <pre><code>pip install -r requirements.txt </code></pre>
9,792,927
Javascript array search and remove string?
<p>I have:</p> <pre><code>var array = new Array(); array.push("A"); array.push("B"); array.push("C"); </code></pre> <p>I want to be able to do something like:</p> <p><code>array.remove("B");</code></p> <p>but there is no remove function. How do I accomplish this?</p>
44,433,050
11
3
null
2012-03-20 18:40:18.257 UTC
27
2022-04-28 09:24:35.327 UTC
2012-03-20 18:48:50.023 UTC
null
938,089
null
971,888
null
1
220
javascript|arrays
333,178
<p>I'm actually updating this thread with a more recent 1-line solution: </p> <pre><code>let arr = ['A', 'B', 'C']; arr = arr.filter(e =&gt; e !== 'B'); // will return ['A', 'C'] </code></pre> <p>The idea is basically to filter the array by selecting all elements different to the element you want to remove. </p> <p>Note: will remove all occurrences. </p> <p>EDIT:</p> <p>If you want to remove only the first occurence: </p> <pre><code>t = ['A', 'B', 'C', 'B']; t.splice(t.indexOf('B'), 1); // will return ['B'] and t is now equal to ['A', 'C', 'B'] </code></pre>
8,005,514
Is returning references of member variables bad practice?
<p>The following is said to be better than having First() and Second() as public members. I believe this is nearly as bad.</p> <pre><code>// Example 17-3(b): Proper encapsulation, initially with inline accessors. Later // in life, these might grow into nontrivial functions if needed; if not, then not. template&lt;class T, class U&gt; class Couple { public: Couple() : deleted_(false) { } void MarkDeleted() { deleted_ = true; } bool IsDeleted() { return deleted_; } private: T first_; U second_; bool deleted_; T&amp; First() { return first_; } U&amp; Second() { return second_; } }; </code></pre> <p>If you're giving a way to access a private variable outside of the class then what's the point? Shouldn't the functions be</p> <pre><code>T First(); void(or T) First(const T&amp;) </code></pre>
8,006,068
3
0
null
2011-11-04 06:13:58.257 UTC
16
2020-12-25 17:28:54.25 UTC
2020-12-25 17:28:54.25 UTC
null
1,047,213
user34537
null
null
1
56
c++|reference|member-variables
34,421
<p>There are several reasons why returning references (or pointers) to the internals of a class are bad. Starting with (what I consider to be) the most important:</p> <ol> <li><p><strong>Encapsulation</strong> is breached: you leak an implementation detail, which means that you can no longer alter your class internals as you wish. If you decided not to store <code>first_</code> for example, but to compute it on the fly, how would you return a reference to it ? You cannot, thus you're stuck.</p></li> <li><p><strong>Invariant</strong> are no longer sustainable (in case of non-const reference): anybody may access and modify the attribute referred to at will, thus you cannot "monitor" its changes. It means that you cannot maintain an invariant of which this attribute is part. Essentially, your class is turning into a blob.</p></li> <li><p><strong>Lifetime</strong> issues spring up: it's easy to keep a reference or pointer to the attribute after the original object they belong to ceased to exist. This is of course undefined behavior. Most compilers will attempt to warn about keeping references to objects on the stack, for example, but I know of no compiler that managed to produce such warnings for references returned by functions or methods: you're on your own.</p></li> </ol> <p>As such, it is usually better not to give away references or pointers to attributes. <em>Not even const ones!</em></p> <p>For small values, it is generally sufficient to pass them by copy (both <code>in</code> and <code>out</code>), especially now with move semantics (on the way in).</p> <p>For larger values, it really depends on the situation, sometimes a Proxy might alleviate your troubles.</p> <p>Finally, note that for some classes, having public members is not so bad. What would be the point of encapsulating the members of a <code>pair</code> ? When you find yourself writing a class that is no more than a collection of attributes (no invariant whatsoever), then instead of getting all OO on us and writing a getter/setter pair for each of them, consider making them public instead.</p>
8,245,935
Creating a composite Unique constraints on multiple columns
<p>This is my model:</p> <pre><code>class User {...} class Book { User author; int number; } </code></pre> <p>Every book number starts at 1 per author and increments upwards. So we'll have Books 1,2,3 by John Grisham, Book 1..5 by George Martin, etc...</p> <p>Is there a unique constraint I can place on <code>Book</code>, that would guarantee we don't have two books with the same number by the same author? Similar to <code>@Column(unique = true)</code>, but the constraint only applies on the composite of <code>Author X number</code>?</p>
8,246,357
3
1
null
2011-11-23 16:46:31.873 UTC
12
2019-05-17 16:55:37.567 UTC
2017-11-07 20:53:47.337 UTC
null
4,813,586
null
11,236
null
1
77
java|jpa|playframework|persistence
54,444
<p>Use <a href="http://docs.oracle.com/javaee/6/api/javax/persistence/UniqueConstraint.html" rel="noreferrer"><code>@UniqueConstraint</code></a>:</p> <pre><code>@Table( uniqueConstraints= @UniqueConstraint(columnNames={"author_id", "number"}) ) @Entity class Book extends Model { @ManyToOne @JoinColumn(name = "author_id") User author; int number; } </code></pre>
11,640,415
Generate matrix with iid normal random variables using R
<p>Is there a way to generate a data set with normally distributed random values in R without using a loop? Each entry would represent an independent random variable with a normal distribution.</p>
11,640,697
4
1
null
2012-07-24 22:33:56.373 UTC
7
2015-05-11 18:58:44.753 UTC
2012-07-25 00:59:31.047 UTC
null
1,154,578
Crawling Antz
1,549,915
null
1
21
r|random|normal-distribution
54,874
<p>To create an <code>N</code> by <code>M</code> matrix of iid normal random variables type this: </p> <pre><code>matrix( rnorm(N*M,mean=0,sd=1), N, M) </code></pre> <p>tweak the mean and standard deviation as desired. </p>
11,516,038
How to disable test suite in ScalaTest
<p>How to disable a test suite, i.e. all tests inside class extending <code>FunSpec</code>?</p> <p>The only solution I'd found is to replace <code>it</code> with <code>ignore</code> in front of each test, but it is boring to do so with the dozens of tests.</p>
11,533,713
6
1
null
2012-07-17 04:30:14.323 UTC
5
2021-10-15 02:56:34.657 UTC
null
null
null
null
664,448
null
1
29
scala|testing|scalatest
22,352
<p>The easy way to do this in 1.8 is to add a constructor that takes a dummy argument. ScalaTest (and sbt) won't discover the class if it doesn't have a public, no-arg constructor:</p> <pre><code>class MySuite(ignore: String) extends FunSuite { // ... } </code></pre> <p>In 2.0 you'll be able to just write @Ignore on the class:</p> <pre><code>@Ignore class MySuite extends FunSuite { // ... } </code></pre>
11,884,960
How to get index in Handlebars each helper?
<p>I'm using Handlebars for templating in my project. Is there a way to get the index of the current iteration of an "each" helper in Handlebars?</p> <pre><code>&lt;tbody&gt; {{#each item}} &lt;tr&gt; &lt;td&gt;&lt;!--HOW TO GET ARRAY INDEX HERE?--&gt;&lt;/td&gt; &lt;td&gt;{{this.key}}&lt;/td&gt; &lt;td&gt;{{this.value}}&lt;/td&gt; &lt;/tr&gt; {{/each}} &lt;/tbody&gt; </code></pre>
14,113,688
7
2
null
2012-08-09 13:49:55.823 UTC
68
2020-10-17 19:57:30.59 UTC
2013-04-18 16:21:44.39 UTC
null
169,000
null
369,034
null
1
298
javascript|handlebars.js
205,279
<p>In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper. </p> <hr> <p>snippet from : <a href="https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811" rel="noreferrer">https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811</a></p> <p>The index of the current array item has been available for some time now via @index:</p> <pre><code>{{#each array}} {{@index}}: {{this}} {{/each}} </code></pre> <p>For object iteration, use @key instead:</p> <pre><code>{{#each object}} {{@key}}: {{this}} {{/each}} </code></pre>
11,463,734
Split a List into smaller lists of N size
<p>I am attempting to split a list into a series of smaller lists.</p> <p><strong>My Problem:</strong> My function to split lists doesn't split them into lists of the correct size. It should split them into lists of size 30 but instead it splits them into lists of size 114?</p> <p>How can I make my function split a list into X number of Lists of size <strong>30 or less</strong>?</p> <pre><code>public static List&lt;List&lt;float[]&gt;&gt; splitList(List &lt;float[]&gt; locations, int nSize=30) { List&lt;List&lt;float[]&gt;&gt; list = new List&lt;List&lt;float[]&gt;&gt;(); for (int i=(int)(Math.Ceiling((decimal)(locations.Count/nSize))); i&gt;=0; i--) { List &lt;float[]&gt; subLocat = new List &lt;float[]&gt;(locations); if (subLocat.Count &gt;= ((i*nSize)+nSize)) subLocat.RemoveRange(i*nSize, nSize); else subLocat.RemoveRange(i*nSize, subLocat.Count-(i*nSize)); Debug.Log ("Index: "+i.ToString()+", Size: "+subLocat.Count.ToString()); list.Add (subLocat); } return list; } </code></pre> <p>If I use the function on a list of size 144 then the output is:</p> <blockquote> <p>Index: 4, Size: 120<br> Index: 3, Size: 114<br> Index: 2, Size: 114<br> Index: 1, Size: 114<br> Index: 0, Size: 114</p> </blockquote>
11,463,800
21
2
null
2012-07-13 03:27:09.1 UTC
74
2022-03-04 16:58:03.073 UTC
2014-08-18 08:45:47.437 UTC
null
1,315,444
null
972,202
null
1
310
c#|list|split
319,655
<pre><code>public static List&lt;List&lt;float[]&gt;&gt; SplitList(List&lt;float[]&gt; locations, int nSize=30) { var list = new List&lt;List&lt;float[]&gt;&gt;(); for (int i = 0; i &lt; locations.Count; i += nSize) { list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i))); } return list; } </code></pre> <p>Generic version:</p> <pre><code>public static IEnumerable&lt;List&lt;T&gt;&gt; SplitList&lt;T&gt;(List&lt;T&gt; locations, int nSize=30) { for (int i = 0; i &lt; locations.Count; i += nSize) { yield return locations.GetRange(i, Math.Min(nSize, locations.Count - i)); } } </code></pre>
11,655,116
How to update Xcode with a new Apple ID?
<p>I've recently changed apple ID and I've downloaded xCode on mac with another apple ID.</p> <p>Not the mac store informs me there is a new version for xCode but I need to insert password of the older Apple ID, and I can't just use the new one. It seems the app is associated with the old apple ID.</p> <p>I can't even download a new xCode using the new apple id, because it only gives me the option to update it with the old Apple ID.</p>
11,655,630
8
4
null
2012-07-25 17:16:30.75 UTC
21
2020-02-03 09:33:38.807 UTC
2015-05-26 13:50:09.1 UTC
null
1,118,488
null
257,022
null
1
72
xcode|apple-id
53,863
<p>Assuming you have the issue where you are getting the error </p> <blockquote> <p>To update this application, sign in to the account you used to purchase it.</p> </blockquote> <p>on the App Store app, go to Store --> Sign Out</p> <p>and then do the stuff suggested here</p> <p>check this fix from Beartech at <a href="https://discussions.apple.com/thread/2794280?start=15&amp;tstart=0" rel="noreferrer">https://discussions.apple.com/thread/2794280?start=15&amp;tstart=0</a></p> <blockquote> <p>The App Store used Spotlight in some way. My fix was to add the entire HD to the "Privacy" tab in the Spotlight System prefs pane, close the prefs and wait 30 seconds, re-open and remove your HD from the Privacy tab. Spolight begins reindexing. Re-opened the App Store and problem was fixed! Posting this here for others who might search later on. Also filed a bug report with Apple.</p> </blockquote> <p>hope this fixes the issue for you!</p> <p>edit: I think this is a different issue compared to what I had. Your only option is probbaly to delete xcode, and download with your new Apple ID</p>