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
496,277
Git error: fatal: unable to connect a socket (Invalid argument)
<p>I've got msysGit (Git on Windows) working just fine on my home machine, but at work, where we are behind a Microsoft ISA proxy, I get the following error when I do a git clone:</p> <pre><code>H:\&gt;git clone git://github.com/akitaonrails/vimfiles.git Initialized empty Git repository in H:/vimfiles/.git/ github.com[0: 65.74.177.129]: errno=Invalid argument fatal: unable to connect a socket (Invalid argument) </code></pre> <p>I've tried setting the http_proxy environment variable to:</p> <pre><code>http://our-proxy-server:8088 </code></pre> <p>I've set the git http.proxy configuration directive:</p> <pre><code>git config --global http.proxy http://our-proxy-server:8088 </code></pre> <p>Neither of the above makes a difference.</p> <p>Doing a git clone with <code>http://</code> instead of <code>git://</code> yields this:</p> <pre><code>H:\&gt;git clone http://github.com/akitaonrails/vimfiles.git Initialized empty Git repository in H:/vimfiles/.git/ fatal: http://github.com/akitaonrails/vimfiles.git/info/refs download error - The requested URL returned error: 407 </code></pre> <p>407 is of course an authentication error.</p> <p>So my question is: has anyone managed to get git working from behind a proxy, specifically an ISA proxy? I don't know if it's going to be worth pursing this. Any help very much appreciated.</p> <p>Thanks!</p>
496,504
7
2
null
2009-01-30 16:54:32.11 UTC
23
2015-12-08 11:13:32.597 UTC
null
null
null
Charles Roper
1,944
null
1
50
windows|git|proxy|msysgit
101,698
<p>I had the exact same error; but the <a href="http://git-scm.com/docs/git-config" rel="noreferrer"><code>~/.gitconfig</code> global config file</a> was the key.</p> <p>If you have a proxy with authentication you need to put in it:</p> <pre><code>git config --global http.proxy http://login:password@our-proxy-server:8088 </code></pre> <p>And it just works (with '<code>git clone http:</code>')</p> <p>Example of a blog detailing the same setup: <a href="http://rip747.wordpress.com/2008/09/12/git-clone-over-http-who-knew/" rel="noreferrer">GIT clone over HTTP: who knew?</a></p> <hr> <p>If it still fails in 407, it could be related to a problem with <a href="http://kerneltrap.org/mailarchive/git/2007/1/3/234850/thread" rel="noreferrer">git-fetch losing authentication tokens on the second HTTP GET</a>. A <a href="http://daniel.haxx.se/blog/2008/12/08/scp-and-sftp-with-libcurl-on-windows/" rel="noreferrer">more recent version of libcurl</a> might be needed.</p> <hr> <p>Update January 2011: <a href="https://stackoverflow.com/users/567525/jbustamovej">jbustamovej</a> mentions in <a href="https://stackoverflow.com/questions/496277/git-error-fatal-unable-to-connect-a-socket-invalid-argument/4630559#4630559">his answer (upvoted)</a> his blog post "<a href="http://jmjpro.wordpress.com/2011/01/07/github-behind-corporate-proxy/" rel="noreferrer">GitHub Behind Corporate Proxy</a>", which adds this:</p> <blockquote> <p>It’s important to note that <strong>if your login has a backslash</strong>, as in <code>domain\login</code>, <strong>you must escape the backslash</strong>, as in:</p> </blockquote> <pre><code>git config --global http.proxy http://domain\\\login:password@our-proxy-server:8088 </code></pre>
1,238,355
Firing click event from code in gwt
<p>I have created a custom widget in gwt which extends the composite.I am using focus panel in that.For FocusPanel I added ClickHandler.Then I have added keyboard listner.Now on press of Enter key it should trigger click event.Can any one help me to trigger click event by using code in GWT?</p> <pre><code>focusPanel.addKeyPressHandler(new KeyPressHandler() { public void onKeyPress(KeyPressEvent event) { if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) { // TODO call onClick() method } } }); </code></pre> <p>Thanks</p>
1,238,512
8
0
null
2009-08-06 11:38:52.327 UTC
4
2015-02-16 01:12:17.843 UTC
null
null
null
null
40,945
null
1
23
gwt
61,166
<p>I haven't done this for a click event, but I've done change events like this.</p> <pre><code>NativeEvent event = Document.get().createChangeEvent(); DomEvent.fireNativeEvent(event, this); </code></pre> <p>The [<code>createClickEvent</code>](<a href="http://google-web-toolkit.googlecode.com/svn/javadoc/1.6/com/google/gwt/dom/client/Document.html#createClickEvent(int,%20int,%20int,%20int,%20int,%20boolean,%20boolean,%20boolean,%20boolean))" rel="noreferrer">http://google-web-toolkit.googlecode.com/svn/javadoc/1.6/com/google/gwt/dom/client/Document.html#createClickEvent(int,%20int,%20int,%20int,%20int,%20boolean,%20boolean,%20boolean,%20boolean))</a> method takes a lot more parameters though.</p> <pre><code>public final NativeEvent createClickEvent(int detail, int screenX, int screenY, int clientX, int clientY, boolean ctrlKey, boolean altKey, boolean shiftKey, boolean metaKey) </code></pre>
715,751
Attach to a processes output for viewing
<p>How would I 'attach' a console/terminal-view to an applications output so I can see what it may be saying?</p> <p>How would I detach from an applications output without killing the application?</p> <p>Normally if you fire up a talkative application using the command line you get to see all kinds of wonderful output. However, let’s say I have a particularly chatty programming running, like KINO, and I want to view its output at any given moment without restarting it through the command line. I cannot; at least I don't know how. </p>
715,763
8
2
null
2009-04-03 21:17:56.573 UTC
78
2022-04-28 15:59:39.493 UTC
2019-04-28 22:37:05.957 UTC
null
63,550
aggitan
46,857
null
1
139
linux|logging|command-line-interface
172,055
<p>There are a few options here. One is to redirect the output of the command to a file, and then use 'tail' to view new lines that are added to that file in real time.</p> <p>Another option is to launch your program inside of 'screen', which is a sort-of text-based Terminal application. Screen sessions can be attached and detached, but are nominally meant only to be used by the same user, so if you want to share them between users, it's a big pain in the ass.</p>
52,550
What does the comma operator , do?
<p>What does the <code>,</code> operator do in C?</p>
52,558
8
3
null
2008-09-09 18:34:09.777 UTC
80
2022-04-23 17:10:13.53 UTC
2017-05-22 07:00:53.437 UTC
null
584,518
Lane
2,064
null
1
199
c|operators|comma-operator
50,155
<p>The expression:</p> <pre><code>(expression1, expression2) </code></pre> <p>First <code>expression1</code> is evaluated, then <code>expression2</code> is evaluated, and the value of <code>expression2</code> is returned for the whole expression.</p>
1,225,594
Apache 13 permission denied in user's home directory
<p>My friend's website was working fine until he moved the document root from <code>/var/www/xxx</code> to <code>/home/user/xxx</code>.</p> <p>Apache gives 13 permission denied error messages when we try to access the site via a web browser.</p> <p>The site is configured as a virtual directory. All the Apache configurations were unchanged <em>(except for the directory change)</em>. </p> <p>We tried to <code>chmod 777 /home/user/xxx</code>, chown apache /home/user/xxx. But they didn't work.</p> <p>Is there some kind of security feature set on the user's home directories? The server OS is CentOS (Godaddy VPS).</p> <p>Any help is appreciated!</p> <p>Thanks!</p>
1,241,319
9
4
null
2009-08-04 03:18:48.157 UTC
9
2012-10-15 06:32:39.483 UTC
2012-10-15 06:32:39.483 UTC
null
939,986
null
150,094
null
1
41
apache|permissions
144,067
<p>Turns out... we had to also chmod 755 the parent directory, user, in addition to xxx. </p>
674,721
How do I subtract minutes from a date in JavaScript?
<p>How can I translate this pseudo code into working JS [don't worry about where the end date comes from except that it's a valid JavaScript date].</p> <pre><code>var myEndDateTime = somedate; //somedate is a valid JS date var durationInMinutes = 100; //this can be any number of minutes from 1-7200 (5 days) //this is the calculation I don't know how to do var myStartDate = somedate - durationInMinutes; alert(&quot;The event will start on &quot; + myStartDate.toDateString() + &quot; at &quot; + myStartDate.toTimeString()); </code></pre>
674,735
9
0
null
2009-03-23 18:47:28.493 UTC
14
2022-06-29 00:10:52.727 UTC
2021-04-18 10:20:32.903 UTC
Daniel L
472,495
brendan
225
null
1
178
javascript
206,941
<p>Once you know this:</p> <ul> <li>You can create a <code>Date</code> by calling the <a href="http://www.java2s.com/Tutorial/JavaScript/0240__Date/CreateDateobjectbycalltheconstructor.htm" rel="noreferrer">constructor</a> with milliseconds since Jan 1, 1970.</li> <li>The <code>valueOf()</code> a <code>Date</code> is the number of milliseconds since Jan 1, 1970</li> <li>There are <code>60,000</code> milliseconds in a minute :-]</li> </ul> <p>In the code below, a new <code>Date</code> is created by subtracting the appropriate number of milliseconds from <code>myEndDateTime</code>:</p> <pre><code>var MS_PER_MINUTE = 60000; var myStartDate = new Date(myEndDateTime - durationInMinutes * MS_PER_MINUTE); </code></pre>
852,439
How to sort elements of array list in C#
<p>I have an ArrayList that contains,</p> <pre><code>[0] = "1" [1] = "10" [2] = "2" [3] = "15" [4] = "17" [5] = "5" [6] = "6" [7] = "27" [8] = "8" [9] = "9" </code></pre> <p>Now i need to sort the array list such that it becomes,</p> <pre><code>[0] = "1" [1] = "2" [2] = "5" [3] = "6" [4] = "8" [5] = "9" [6] = "10" [7] = "15" [8] = "17" [9] = "27" </code></pre> <p>At last i will be getting the values from ArrayList and using them as <strong>'int'</strong> values. How can i do this? Or shall i convert them to int at first and then sort them.?</p>
852,490
10
1
null
2009-05-12 12:14:42.967 UTC
3
2021-04-11 10:26:41.82 UTC
null
null
null
null
73,137
null
1
11
c#
63,460
<p>If you can be sure the list contains only strings that can be transformed to integers, then with the <strong><a href="http://msdn.microsoft.com/en-us/library/bb534966.aspx" rel="noreferrer"><code>IEnumerable&lt;T&gt;.OrderBy</code></a></strong> extension method, try this:</p> <pre><code>var sortedList = list.OrderBy(item =&gt; int.Parse(item)); </code></pre> <p>If you're using an <code>ArrayList</code> instead of a <code>List&lt;string&gt;</code> (boo!), you'll need to <code>Cast</code> first:</p> <pre><code>var sortedList = list.Cast&lt;string&gt;().OrderBy(item =&gt; int.Parse(item)); </code></pre> <p>You can also define your own comparer as JaredPar noted, but IMO that's a lot of work for something that's already implemented. However, it's more efficient.</p>
109,188
How do I check if a directory is writeable in PHP?
<p>Does anyone know how I can check to see if a directory is writeable in PHP? </p> <p>The function <a href="http://php.net/manual/en/function.is-writable.php" rel="nofollow noreferrer"><code>is_writable</code></a> doesn't work for folders.</p> <blockquote> <p>Edit: It does work. See the accepted answer.</p> </blockquote>
109,195
10
0
null
2008-09-20 20:07:38.657 UTC
4
2019-12-13 20:38:28.41 UTC
2019-12-13 20:38:28.41 UTC
null
1,454,671
SeanDowney
5,261
null
1
62
php|permissions|directory
83,228
<p>Yes, it does work for folders....</p> <blockquote> <p>Returns TRUE if the filename exists and is writable. The filename argument may be a directory name allowing you to check if a directory is writable. </p> </blockquote>
1,011,863
How do I speed up the gwt compiler?
<p>We're starting to make heavier use of GWT in our projects, and the performance of the GWT compiler is becoming increasingly annoying. </p> <p>We're going to start altering our working practices to mitigate the problem, including a greater emphasis on the hosted-mode browser, which defers the need to run the GWT compiler until a later time, but that brings its own risks, particularly that of not catching issues with real browsers until much later than we'd like.</p> <p>Ideally, we'd like to make the GWT compiler itself quicker - a minute to compile a fairly small application is taking the piss. However, we are using the compile if a fairly naive fashion, so I'm hoping we can make some quick and easy gains.</p> <p>We're currently invoking com.google.gwt.dev.Compiler as a java application from ant Ant target, with 256m max heap and lots of stack space. The compiler is launched by Ant using fork=true and the latest Java 6 JRE, to try and take advantage of Java6's improved performance. We pass our main controller class to the compiler along with the application classpath, and off it goes.</p> <p>What else can we do to get some extra speed? Can we give it more information so it spends less time doing discovery of what to do?</p> <p>I know we can tell it to only compile for one browser, but we need to do multi-browser testing, so that's not really practical.</p> <p>All suggestions welcome at this point.</p>
1,011,877
10
0
null
2009-06-18 09:56:45.317 UTC
70
2021-04-07 09:13:31.673 UTC
2014-09-19 14:38:35.18 UTC
null
102,937
null
21,234
null
1
208
java|performance|gwt
104,444
<p>Let's start with the uncomfortable truth: GWT compiler performance is really lousy. You can use some hacks here and there, but you're not going to get significantly better performance.</p> <p>A nice performance hack you can do is to compile for only specific browsers, by inserting the following line in your <code>gwt.xml</code>:</p> <pre><code>&lt;define-property name="user.agent" values="ie6,gecko,gecko1_8"&gt;&lt;/define-property&gt; </code></pre> <p>or in gwt 2.x syntax, and for one browser only:</p> <pre><code>&lt;set-property name="user.agent" value="gecko1_8"/&gt; </code></pre> <p>This, for example, will compile your application for IE and FF only. If you know you are using only a specific browser for testing, you can use this little hack.</p> <p>Another option: if you are using several locales, and again using only one for testing, you can comment them all out so that GWT will use the default locale, this shaves off some additional overhead from compile time.</p> <p>Bottom line: you're not going to get order-of-magnitude increase in compiler performance, but taking several relaxations, you can shave off a few minutes here and there.</p>
334,009
How to read source code learn how to use large system?
<p>Let's say you want to start contributing to an open source project with thousands LOC. I am interesting in ways/suggestions on how you would start learning/hacking the new system. </p>
334,041
12
2
null
2008-12-02 14:02:42.863 UTC
11
2018-12-12 12:55:09.197 UTC
2014-08-18 12:20:47.5 UTC
null
2,246,344
Chrys
17,476
null
1
9
open-source
8,548
<p>Skim through the code, looking for places where you think you know what is occuring. Read through those sections to see if your initial thought holds up, and then try modifying it to see if you can change it to do something else.</p> <p>I'd suggest that this be guided slightly by the project roadmap so you can then move on to spotting where new features and bug fixes are so you can contribute in a meaningful manner.</p> <p>Also, read the documentation and any spin-up documents that may exist (functional specs, requirement specs, etc). This can further help you learn the code ropes quicker :)</p>
1,239,150
Looking for an easier way to write debugging print statements in Java
<p>EDIT: I would love to read reactions to Steve Reed's AOP approach. Comments to his answer are encouraged!</p> <p>I'm a novice, and at some point I realized it would be helpful to know the contents of a variable during program execution. So I started doing this:</p> <p>EDIT: fixed this. Used to be: var + ": " + var, which was totally wrong. Dumb typo.</p> <pre><code>System.err.println ( "var: " + var ); </code></pre> <p>Later I learned that this was common practice. At least, where a debugger was unavailable or unwanted.</p> <p>I use a basic text editor, and typing the print statement every time I need to debug a variable is pretty tiresome, so I thought, why not something like this:</p> <pre><code>void dbug ( Object obj ) { String variableName = obj.somehowGetVariableName(); String variableContents = obj.toString(); System.out.println ( variableName +": " + variableContents ); } </code></pre> <p>But apparently getting the variable name is easier said than done.</p> <p><a href="https://stackoverflow.com/questions/744226/java-reflection-how-to-get-the-name-of-a-variable">java-reflection-how-to-get-the-name-of-a-variable</a></p> <p>Am I stuck with:</p> <pre><code>System.err.println ( "var: " + var ); </code></pre> <p>Or is there a popular shorthand version of this?</p>
1,239,184
12
7
null
2009-08-06 14:12:57.543 UTC
1
2021-05-07 14:58:44.82 UTC
2017-05-23 11:53:26.26 UTC
null
-1
null
121,492
null
1
13
java|debugging
40,725
<p>I wouldn't try and write any fancy methods around printing out debugging info. Just stick with either <code>LOG.debug(...)</code> if you are using a logger or <code>System.err.println(...)</code> otherwise.</p> <p>You may wish to use <code>String.format("var=%s val=%s", "VarName", val)</code> instead of the String concatenation.</p> <p>Make sure that you override the <code>toString</code> method in each of your classes to provide meaningful debug info.</p> <p>At the end of the day it's often easier to fire up the debugger and take a look to see what's going on instead of having to trace through loads of logged debug lines.</p> <p>The only time when i'd use your kind of debug method would be if my application maintained all of the state inside a map which I could easily print out the key value pairs (e.g. the session map in a web application).</p>
381,037
True random generation in Java
<p>I was reading the Math.random() javadoc and saw that random is only psuedorandom. </p> <p>Is there a library (specifically java) that generates random numbers according to random variables like environmental temperature, CPU temperature/voltage, or anything like that?</p>
381,043
13
0
null
2008-12-19 14:03:47.34 UTC
16
2020-08-03 20:25:37.913 UTC
2008-12-19 14:30:21.547 UTC
tvanfosson
12,950
Gareth
47,690
null
1
25
java|random
53,295
<p>Check out <a href="http://random.org/" rel="noreferrer">http://random.org/</a></p> <p>RANDOM.ORG is a true random number service that generates randomness via atmospheric noise.</p> <p>The Java library for interfacing with it can be found here: <a href="http://sourceforge.net/projects/trng-random-org/" rel="noreferrer">http://sourceforge.net/projects/trng-random-org/</a></p>
414,222
Selecting most recent date between two columns
<p>If I have a table that (among other columns) has two DATETIME columns, how would I select the <strong>most recent</strong> date from those two columns.</p> <p>Example:</p> <pre><code>ID Date1 Date2 1 1/1/2008 2/1/2008 2 2/1/2008 1/1/2008 3 1/10/2008 1/10/2008 </code></pre> <p>If I wanted my results to look like </p> <pre><code>ID MostRecentDate 1 2/1/2008 2 2/1/2008 3 1/10/2008 </code></pre> <p>Is there a simple way of doing this that I am obviously overlooking? I know I can do subqueries and case statements or even write a function in sql server to handle it, but I had it in my head that there was a max-compare type function already built in that I am just forgetting about.</p>
414,232
13
0
null
2009-01-05 19:33:00.277 UTC
4
2019-12-25 09:17:32.483 UTC
2009-01-10 18:32:27.097 UTC
TheTXI
22,164
TheTXI
22,164
null
1
36
sql|database|sql-server-2005
80,901
<p>CASE is IMHO your best option:</p> <pre><code>SELECT ID, CASE WHEN Date1 &gt; Date2 THEN Date1 ELSE Date2 END AS MostRecentDate FROM Table </code></pre> <hr> <p>If one of the columns is nullable just need to enclose in <a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql" rel="noreferrer"><code>COALESCE</code></a>:</p> <pre><code>.. COALESCE(Date1, '1/1/1973') &gt; COALESCE(Date2, '1/1/1973') </code></pre>
1,025,674
The best way to remove duplicate values from NSMutableArray in Objective-C?
<p>The best way to remove duplicate values (<code>NSString</code>) from <code>NSMutableArray</code> in Objective-C?</p> <p>Is this the easiest and right way to do it?</p> <pre><code>uniquearray = [[NSSet setWithArray:yourarray] allObjects]; </code></pre>
1,025,745
14
4
null
2009-06-22 06:11:04.187 UTC
55
2018-05-23 13:52:52.55 UTC
2016-12-22 11:58:43.8 UTC
null
4,078,527
null
42,340
null
1
150
ios|objective-c|nsmutablearray
105,671
<p>Your <code>NSSet</code> approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an <code>NSSet</code> to begin with?</p> <p>I wrote the answer below in 2009; in 2011, Apple added <code>NSOrderedSet</code> to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:</p> <pre><code>NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray]; NSArray *arrayWithoutDuplicates = [orderedSet array]; </code></pre> <hr> <p>If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:</p> <pre><code>NSArray *copy = [mutableArray copy]; NSInteger index = [copy count] - 1; for (id object in [copy reverseObjectEnumerator]) { if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) { [mutableArray removeObjectAtIndex:index]; } index--; } [copy release]; </code></pre>
685,319
Git pull error: unable to create temporary sha1 filename
<p>I've got a small git repo setup with the only real purpose to be able to develop locally on several machines (work, home, laptop). Thus I have one branch and I commit/push once I leave a computer, pull once I sit down at the next. Has worked fine, up to now that is. Now when I pull on my 'live test' machine, I get the following:</p> <pre><code>remote: Counting objects: 38, done. remote: Compressiremote: ng objects: 100% (20/20), done. remote: Total 20 (delta 17), reused 0 (delta 0) error: unable to create temporary sha1 filename .git/objects/ed: File exists fatal: failed to write object fatal: unpack-objects failed </code></pre> <p>Searching around the net the only real answer I could find was the following: <a href="http://marc.info/?l=git&amp;m=122720741928774&amp;w=2" rel="noreferrer">http://marc.info/?l=git&amp;m=122720741928774&amp;w=2</a> which basically states that this is a bogus error that's on top of the pile and thus says nothing about what really is wrong.</p> <p>Where do I go from here to find out what is wrong?</p> <p>Edit: Removed the local copy and re-cloned</p>
692,062
19
0
null
2009-03-26 11:08:40.96 UTC
15
2019-12-06 18:11:11.57 UTC
2009-03-26 11:50:26.99 UTC
null
1,799,944
null
1,799,944
null
1
39
git
65,805
<p>For what it's worth, when I had this problem—but when committing—I tried <code>git-repack</code> and <code>git-gc</code>, but neither worked. I got a permission denied error, which led me to <code>chown</code> the entire repo recursively to the user I expected it to be, and I could then commit/push/pull with no problem.</p>
295,579
Fastest way to determine if an integer's square root is an integer
<p>I'm looking for the fastest way to determine if a <code>long</code> value is a perfect square (i.e. its square root is another integer): </p> <ol> <li>I've done it the easy way, by using the built-in <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#sqrt(double)" rel="noreferrer"><code>Math.sqrt()</code></a> function, but I'm wondering if there is a way to do it faster by restricting yourself to integer-only domain.</li> <li>Maintaining a lookup table is impractical (since there are about 2<sup>31.5</sup> integers whose square is less than 2<sup>63</sup>).</li> </ol> <p>Here is the very simple and straightforward way I'm doing it now:</p> <pre><code>public final static boolean isPerfectSquare(long n) { if (n &lt; 0) return false; long tst = (long)(Math.sqrt(n) + 0.5); return tst*tst == n; } </code></pre> <p><sub>Note: I'm using this function in many <a href="http://projecteuler.net/" rel="noreferrer">Project Euler</a> problems. So no one else will ever have to maintain this code. And this kind of micro-optimization could actually make a difference, since part of the challenge is to do every algorithm in less than a minute, and this function will need to be called millions of times in some problems.</sub></p> <hr> <p>I've tried the different solutions to the problem:</p> <ul> <li>After exhaustive testing, I found that adding <code>0.5</code> to the result of Math.sqrt() is not necessary, at least not on my machine.</li> <li>The <a href="https://en.wikipedia.org/wiki/Fast_inverse_square_root" rel="noreferrer">fast inverse square root</a> was faster, but it gave incorrect results for n >= 410881. However, as suggested by <a href="https://stackoverflow.com/users/38426/bobbyshaftoe">BobbyShaftoe</a>, we can use the FISR hack for n &lt; 410881.</li> <li>Newton's method was a good bit slower than <code>Math.sqrt()</code>. This is probably because <code>Math.sqrt()</code> uses something similar to Newton's Method, but implemented in the hardware so it's much faster than in Java. Also, Newton's Method still required use of doubles.</li> <li>A modified Newton's method, which used a few tricks so that only integer math was involved, required some hacks to avoid overflow (I want this function to work with all positive 64-bit signed integers), and it was still slower than <code>Math.sqrt()</code>.</li> <li>Binary chop was even slower. This makes sense because the binary chop will on average require 16 passes to find the square root of a 64-bit number.</li> <li>According to John's tests, using <code>or</code> statements is faster in C++ than using a <code>switch</code>, but in Java and C# there appears to be no difference between <code>or</code> and <code>switch</code>.</li> <li>I also tried making a lookup table (as a private static array of 64 boolean values). Then instead of either switch or <code>or</code> statement, I would just say <code>if(lookup[(int)(n&amp;0x3F)]) { test } else return false;</code>. To my surprise, this was (just slightly) slower. This is because <a href="https://stackoverflow.com/questions/299079/why-is-this-code-with-several-or-statements-slightly-faster-than-using-a-lookup-t#299205">array bounds are checked in Java</a>. </li> </ul>
424,936
36
32
2013-07-11 21:32:13.133 UTC
2008-11-17 13:43:21.907 UTC
717
2022-02-24 21:20:59.097 UTC
2019-10-29 17:00:34.03 UTC
Kip
4,825,845
Kip
18,511
null
1
1,578
java|math|optimization|perfect-square
316,059
<p>I figured out a method that works ~35% faster than your 6bits+Carmack+sqrt code, at least with my CPU (x86) and programming language (C/C++). Your results may vary, especially because I don't know how the Java factor will play out.</p> <p>My approach is threefold:</p> <ol> <li>First, filter out obvious answers. This includes negative numbers and looking at the last 4 bits. (I found looking at the last six didn't help.) I also answer yes for 0. (In reading the code below, note that my input is <code>int64 x</code>.) <pre><code>if( x &lt; 0 || (x&2) || ((x & 7) == 5) || ((x & 11) == 8) ) return false; if( x == 0 ) return true;</code></pre> </li> <li>Next, check if it's a square modulo 255 = 3 * 5 * 17. Because that's a product of three distinct primes, only about 1/8 of the residues mod 255 are squares. However, in my experience, calling the modulo operator (%) costs more than the benefit one gets, so I use bit tricks involving 255 = 2^8-1 to compute the residue. (For better or worse, I am not using the trick of reading individual bytes out of a word, only bitwise-and and shifts.) <pre><code>int64 y = x; y = (y & 4294967295LL) + (y &gt;&gt; 32); y = (y & 65535) + (y &gt;&gt; 16); y = (y & 255) + ((y &gt;&gt; 8) & 255) + (y &gt;&gt; 16); // At this point, y is between 0 and 511. More code can reduce it farther. </pre></code> To actually check if the residue is a square, I look up the answer in a precomputed table. <pre><code>if( bad255[y] ) return false; // However, I just use a table of size 512 </code></pre> </li> <li>Finally, try to compute the square root using a method similar to <a href="http://en.wikipedia.org/wiki/Hensel%27s_lemma" rel="noreferrer">Hensel's lemma</a>. (I don't think it's applicable directly, but it works with some modifications.) Before doing that, I divide out all powers of 2 with a binary search: <pre><code>if((x & 4294967295LL) == 0) x &gt;&gt;= 32; if((x & 65535) == 0) x &gt;&gt;= 16; if((x & 255) == 0) x &gt;&gt;= 8; if((x & 15) == 0) x &gt;&gt;= 4; if((x & 3) == 0) x &gt;&gt;= 2;</code></pre> At this point, for our number to be a square, it must be 1 mod 8. <pre><code>if((x & 7) != 1) return false;</code></pre> The basic structure of Hensel's lemma is the following. (Note: untested code; if it doesn't work, try t=2 or 8.) <pre><code>int64 t = 4, r = 1; t &lt;&lt;= 1; r += ((x - r * r) & t) &gt;&gt; 1; t &lt;&lt;= 1; r += ((x - r * r) & t) &gt;&gt; 1; t &lt;&lt;= 1; r += ((x - r * r) & t) &gt;&gt; 1; // Repeat until t is 2^33 or so. Use a loop if you want.</code></pre> The idea is that at each iteration, you add one bit onto r, the "current" square root of x; each square root is accurate modulo a larger and larger power of 2, namely t/2. At the end, r and t/2-r will be square roots of x modulo t/2. (Note that if r is a square root of x, then so is -r. This is true even modulo numbers, but beware, modulo some numbers, things can have even more than 2 square roots; notably, this includes powers of 2.) Because our actual square root is less than 2^32, at that point we can actually just check if r or t/2-r are real square roots. In my actual code, I use the following modified loop: <pre><code>int64 r, t, z; r = start[(x &gt;&gt; 3) & 1023]; do { z = x - r * r; if( z == 0 ) return true; if( z &lt; 0 ) return false; t = z & (-z); r += (z & t) &gt;&gt; 1; if( r &gt; (t &gt;&gt; 1) ) r = t - r; } while( t &lt;= (1LL &lt;&lt; 33) );</code></pre> The speedup here is obtained in three ways: precomputed start value (equivalent to ~10 iterations of the loop), earlier exit of the loop, and skipping some t values. For the last part, I look at <code>z = r - x * x</code>, and set t to be the largest power of 2 dividing z with a bit trick. This allows me to skip t values that wouldn't have affected the value of r anyway. The precomputed start value in my case picks out the "smallest positive" square root modulo 8192. </li> </ol> <p>Even if this code doesn't work faster for you, I hope you enjoy some of the ideas it contains. Complete, tested code follows, including the precomputed tables.</p> <pre><code>typedef signed long long int int64; int start[1024] = {1,3,1769,5,1937,1741,7,1451,479,157,9,91,945,659,1817,11, 1983,707,1321,1211,1071,13,1479,405,415,1501,1609,741,15,339,1703,203, 129,1411,873,1669,17,1715,1145,1835,351,1251,887,1573,975,19,1127,395, 1855,1981,425,453,1105,653,327,21,287,93,713,1691,1935,301,551,587, 257,1277,23,763,1903,1075,1799,1877,223,1437,1783,859,1201,621,25,779, 1727,573,471,1979,815,1293,825,363,159,1315,183,27,241,941,601,971, 385,131,919,901,273,435,647,1493,95,29,1417,805,719,1261,1177,1163, 1599,835,1367,315,1361,1933,1977,747,31,1373,1079,1637,1679,1581,1753,1355, 513,1539,1815,1531,1647,205,505,1109,33,1379,521,1627,1457,1901,1767,1547, 1471,1853,1833,1349,559,1523,967,1131,97,35,1975,795,497,1875,1191,1739, 641,1149,1385,133,529,845,1657,725,161,1309,375,37,463,1555,615,1931, 1343,445,937,1083,1617,883,185,1515,225,1443,1225,869,1423,1235,39,1973, 769,259,489,1797,1391,1485,1287,341,289,99,1271,1701,1713,915,537,1781, 1215,963,41,581,303,243,1337,1899,353,1245,329,1563,753,595,1113,1589, 897,1667,407,635,785,1971,135,43,417,1507,1929,731,207,275,1689,1397, 1087,1725,855,1851,1873,397,1607,1813,481,163,567,101,1167,45,1831,1205, 1025,1021,1303,1029,1135,1331,1017,427,545,1181,1033,933,1969,365,1255,1013, 959,317,1751,187,47,1037,455,1429,609,1571,1463,1765,1009,685,679,821, 1153,387,1897,1403,1041,691,1927,811,673,227,137,1499,49,1005,103,629, 831,1091,1449,1477,1967,1677,697,1045,737,1117,1737,667,911,1325,473,437, 1281,1795,1001,261,879,51,775,1195,801,1635,759,165,1871,1645,1049,245, 703,1597,553,955,209,1779,1849,661,865,291,841,997,1265,1965,1625,53, 1409,893,105,1925,1297,589,377,1579,929,1053,1655,1829,305,1811,1895,139, 575,189,343,709,1711,1139,1095,277,993,1699,55,1435,655,1491,1319,331, 1537,515,791,507,623,1229,1529,1963,1057,355,1545,603,1615,1171,743,523, 447,1219,1239,1723,465,499,57,107,1121,989,951,229,1521,851,167,715, 1665,1923,1687,1157,1553,1869,1415,1749,1185,1763,649,1061,561,531,409,907, 319,1469,1961,59,1455,141,1209,491,1249,419,1847,1893,399,211,985,1099, 1793,765,1513,1275,367,1587,263,1365,1313,925,247,1371,1359,109,1561,1291, 191,61,1065,1605,721,781,1735,875,1377,1827,1353,539,1777,429,1959,1483, 1921,643,617,389,1809,947,889,981,1441,483,1143,293,817,749,1383,1675, 63,1347,169,827,1199,1421,583,1259,1505,861,457,1125,143,1069,807,1867, 2047,2045,279,2043,111,307,2041,597,1569,1891,2039,1957,1103,1389,231,2037, 65,1341,727,837,977,2035,569,1643,1633,547,439,1307,2033,1709,345,1845, 1919,637,1175,379,2031,333,903,213,1697,797,1161,475,1073,2029,921,1653, 193,67,1623,1595,943,1395,1721,2027,1761,1955,1335,357,113,1747,1497,1461, 1791,771,2025,1285,145,973,249,171,1825,611,265,1189,847,1427,2023,1269, 321,1475,1577,69,1233,755,1223,1685,1889,733,1865,2021,1807,1107,1447,1077, 1663,1917,1129,1147,1775,1613,1401,555,1953,2019,631,1243,1329,787,871,885, 449,1213,681,1733,687,115,71,1301,2017,675,969,411,369,467,295,693, 1535,509,233,517,401,1843,1543,939,2015,669,1527,421,591,147,281,501, 577,195,215,699,1489,525,1081,917,1951,2013,73,1253,1551,173,857,309, 1407,899,663,1915,1519,1203,391,1323,1887,739,1673,2011,1585,493,1433,117, 705,1603,1111,965,431,1165,1863,533,1823,605,823,1179,625,813,2009,75, 1279,1789,1559,251,657,563,761,1707,1759,1949,777,347,335,1133,1511,267, 833,1085,2007,1467,1745,1805,711,149,1695,803,1719,485,1295,1453,935,459, 1151,381,1641,1413,1263,77,1913,2005,1631,541,119,1317,1841,1773,359,651, 961,323,1193,197,175,1651,441,235,1567,1885,1481,1947,881,2003,217,843, 1023,1027,745,1019,913,717,1031,1621,1503,867,1015,1115,79,1683,793,1035, 1089,1731,297,1861,2001,1011,1593,619,1439,477,585,283,1039,1363,1369,1227, 895,1661,151,645,1007,1357,121,1237,1375,1821,1911,549,1999,1043,1945,1419, 1217,957,599,571,81,371,1351,1003,1311,931,311,1381,1137,723,1575,1611, 767,253,1047,1787,1169,1997,1273,853,1247,413,1289,1883,177,403,999,1803, 1345,451,1495,1093,1839,269,199,1387,1183,1757,1207,1051,783,83,423,1995, 639,1155,1943,123,751,1459,1671,469,1119,995,393,219,1743,237,153,1909, 1473,1859,1705,1339,337,909,953,1771,1055,349,1993,613,1393,557,729,1717, 511,1533,1257,1541,1425,819,519,85,991,1693,503,1445,433,877,1305,1525, 1601,829,809,325,1583,1549,1991,1941,927,1059,1097,1819,527,1197,1881,1333, 383,125,361,891,495,179,633,299,863,285,1399,987,1487,1517,1639,1141, 1729,579,87,1989,593,1907,839,1557,799,1629,201,155,1649,1837,1063,949, 255,1283,535,773,1681,461,1785,683,735,1123,1801,677,689,1939,487,757, 1857,1987,983,443,1327,1267,313,1173,671,221,695,1509,271,1619,89,565, 127,1405,1431,1659,239,1101,1159,1067,607,1565,905,1755,1231,1299,665,373, 1985,701,1879,1221,849,627,1465,789,543,1187,1591,923,1905,979,1241,181}; bool bad255[512] = {0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1, 1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1, 0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,0,1, 1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1, 1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1, 1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1, 1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1, 0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1, 1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1, 0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,0,1, 1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1, 1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1, 1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1, 1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1, 1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1, 0,0}; inline bool square( int64 x ) { // Quickfail if( x &lt; 0 || (x&2) || ((x & 7) == 5) || ((x & 11) == 8) ) return false; if( x == 0 ) return true; // Check mod 255 = 3 * 5 * 17, for fun int64 y = x; y = (y & 4294967295LL) + (y &gt;&gt; 32); y = (y & 65535) + (y &gt;&gt; 16); y = (y & 255) + ((y &gt;&gt; 8) & 255) + (y &gt;&gt; 16); if( bad255[y] ) return false; // Divide out powers of 4 using binary search if((x & 4294967295LL) == 0) x &gt;&gt;= 32; if((x & 65535) == 0) x &gt;&gt;= 16; if((x & 255) == 0) x &gt;&gt;= 8; if((x & 15) == 0) x &gt;&gt;= 4; if((x & 3) == 0) x &gt;&gt;= 2; if((x & 7) != 1) return false; // Compute sqrt using something like Hensel's lemma int64 r, t, z; r = start[(x &gt;&gt; 3) & 1023]; do { z = x - r * r; if( z == 0 ) return true; if( z &lt; 0 ) return false; t = z & (-z); r += (z & t) &gt;&gt; 1; if( r &gt; (t &gt;&gt; 1) ) r = t - r; } while( t &lt;= (1LL &lt;&lt; 33) ); return false; }</code></pre>
34,513,558
Angular 2.0 and Modal Dialog
<p>I am trying to find some examples on how to do a Confirmation modal dialog in Angular 2.0. I have been using Bootstrap dialog for Angular 1.0 and unable to find any examples in the web for Angular 2.0. I also checked angular 2.0 docs with no luck.</p> <p>Is there a way to use the Bootstrap dialog with Angular 2.0?</p>
40,144,809
9
5
null
2015-12-29 14:57:04.543 UTC
56
2019-08-29 19:10:41.817 UTC
2019-08-29 19:10:41.817 UTC
null
4,505,446
null
636,525
null
1
131
modal-dialog|angular
225,122
<ul> <li>Angular 2 and up</li> <li>Bootstrap css (animation is preserved) </li> <li><strong>NO JQuery</strong></li> <li><strong>NO bootstrap.js</strong></li> <li>Supports <strong>custom modal content</strong> (just like accepted answer)</li> <li>Recently added support for <strong>multiple modals on top of each other</strong>.</li> </ul> <p>`</p> <pre><code>@Component({ selector: 'app-component', template: ` &lt;button type="button" (click)="modal.show()"&gt;test&lt;/button&gt; &lt;app-modal #modal&gt; &lt;div class="app-modal-header"&gt; header &lt;/div&gt; &lt;div class="app-modal-body"&gt; Whatever content you like, form fields, anything &lt;/div&gt; &lt;div class="app-modal-footer"&gt; &lt;button type="button" class="btn btn-default" (click)="modal.hide()"&gt;Close&lt;/button&gt; &lt;button type="button" class="btn btn-primary"&gt;Save changes&lt;/button&gt; &lt;/div&gt; &lt;/app-modal&gt; ` }) export class AppComponent { } @Component({ selector: 'app-modal', template: ` &lt;div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}" [ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;ng-content select=".app-modal-header"&gt;&lt;/ng-content&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;ng-content select=".app-modal-body"&gt;&lt;/ng-content&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;ng-content select=".app-modal-footer"&gt;&lt;/ng-content&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ` }) export class ModalComponent { public visible = false; public visibleAnimate = false; public show(): void { this.visible = true; setTimeout(() =&gt; this.visibleAnimate = true, 100); } public hide(): void { this.visibleAnimate = false; setTimeout(() =&gt; this.visible = false, 300); } public onContainerClicked(event: MouseEvent): void { if ((&lt;HTMLElement&gt;event.target).classList.contains('modal')) { this.hide(); } } } </code></pre> <p><strong>To show the backdrop</strong>, you'll need something like this CSS:</p> <pre><code>.modal { background: rgba(0,0,0,0.6); } </code></pre> <p><strong>The example now allows for multiple modals at the same time</strong>. (see the <code>onContainerClicked()</code> method).</p> <p><strong>For Bootstrap 4 css users</strong>, you need to make 1 minor change (because a css class name was updated from Bootstrap 3). This line: <code>[ngClass]="{'in': visibleAnimate}"</code> should be changed to: <code>[ngClass]="{'show': visibleAnimate}"</code></p> <p>To demonstrate, here is a <strong><a href="https://embed.plnkr.co/7kqyiW97CI696Ixn020g/" rel="noreferrer">plunkr</a></strong></p>
34,808,023
How to clear template cache?
<p>In Angular 2, how do you clear the template cache? There are tons of answers for Angular 1, but none for 2. </p> <p>The issue I am having is that when I change the contents of the html pages referenced by <code>templateUrl</code> on any components, the html pages don't change in the browser until I manually navigate to the <code>templateUrl</code> in the browser and hit reload. I know you can disable the browser cache to solve this during development, but my concern is that users can see an outdated html page if they have it cached in their browser when I go to update a website with Angular 2. </p> <p>Here is a link to the stack overflow questions for Angular 1 <a href="https://stackoverflow.com/questions/14718826/angularjs-disable-partial-caching-on-dev-machine">AngularJS disable partial caching on dev machine</a></p> <p>Below is a snippet and I am having issues with <code>app.html</code> updating when its content is changed. </p> <pre class="lang-ts prettyprint-override"><code>@Component({ selector: 'photogallery-app', templateUrl: './app/app.html', directives: [ROUTER_DIRECTIVES, CORE_DIRECTIVES] }) </code></pre>
36,585,119
9
10
null
2016-01-15 09:31:10.143 UTC
9
2018-08-13 07:02:08.253 UTC
2018-08-13 07:02:08.253 UTC
user6749601
null
null
4,466,312
null
1
32
angular
76,944
<p>First import the TemplateCompiler.</p> <pre><code>import { TemplateCompiler } from 'angular2/src/compiler/template_compiler'; </code></pre> <p>Next inject the TemplateCompiler in your constructor.</p> <pre><code>constructor(private _templateCompiler: TemplateCompiler) </code></pre> <p>Finally use that to clear the cache. Note this clears all templates.</p> <pre><code>this._templateCompiler.clearCache(); </code></pre> <p><strong>UPDATE: Angular 2 Beta 17</strong></p> <p>First import the RuntimeCompiler.</p> <pre><code>import { RuntimeCompiler} from 'angular2/src/compiler/runtime_compiler'; </code></pre> <p>Next inject the RuntimeCompiler in your constructor.</p> <pre><code>constructor(private _runtimeCompiler: RuntimeCompiler) </code></pre> <p>Finally use that to clear the cache. Note this clears all templates.</p> <pre><code>this._runtimeCompiler.clearCache(); </code></pre> <p><strong>UPDATE: Angular 2 RC 1</strong></p> <p>First import the RuntimeCompiler.</p> <pre><code>import { RuntimeCompiler} from '@angular/compiler/src/runtime_compiler'; </code></pre> <p>Next inject the RuntimeCompiler in your constructor.</p> <pre><code>constructor(private _runtimeCompiler: RuntimeCompiler) </code></pre> <p>Finally use that to clear the cache. Note this clears all templates.</p> <pre><code>this._runtimeCompiler.clearCache(); </code></pre> <p><strong>UPDATE: Angular 2 RC 4</strong></p> <p>First import the RuntimeCompiler. </p> <p><strong>Notice the path change from RC1. The path listed for RC1 will throw errors when calling .ClearCache() if used with RC4</strong></p> <pre><code>import { RuntimeCompiler} from '@angular/compiler'; </code></pre> <p>Next inject the RuntimeCompiler in your constructor</p> <pre><code>constructor(private _runtimeCompiler: RuntimeCompiler) </code></pre> <p>Finally use that to clear the cache. Note this clears all templates.</p> <pre><code>this._runtimeCompiler.clearCache(); </code></pre> <p><strong>UPDATE: Angular 2.0.0 (RTM)</strong></p> <p>It cannot be done. I have an app that serves one set templates for logged in users, and another set for those not logged in. After upgrading to 2.0.0, I can see no way to accomplish the same task. While I try to figure out the best way to re-architect the application, I have resorted to this instead:</p> <pre><code>location.reload(); </code></pre> <p>That works (but obviously reloads the entire page).</p>
6,983,732
IE10 User-Agent causes ASP.Net to not send back Set-Cookie (IE10 not setting cookies)
<p><strong>Summary</strong></p> <p>ASP.Net does not send back a <code>Set-Cookie</code> header when using IE 10. Meaning that for example you cannot login to an ASP.Net site using IE10 when using Forms Authentication for example.</p> <p><strong>Detail</strong></p> <p>We're currently testing one of our legacy web apps against IE 10 [Preview 2]. </p> <p>When attempting to login using Forms Authentication, we don't get a <code>Set-Cookie</code> header in the response if the user-agent is that of IE 10. We've tried this with a blank .Net 2 and .Net 4 site.</p> <p>Because we couldn't/wouldn't believe it, we even ran the follow HTTP request manually through <code>telnet</code> - after using all usual tools - and got the same response.</p> <pre><code>GET http://test.ourdomain.co.uk/ HTTP/1.1 Accept: */* Host: test.ourdomain.co.uk User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0) Content-Length: 0 </code></pre> <p>The above HTTP request returns no <code>Set-Cookie</code> in the response. Yet if we simply change the User-Agent to <code>Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/6.0)</code> it works!</p> <p>Can anyone else replicate this? I can't find any known issue with IE10 cookies other than an issue that effects non-standard URL patterns.</p> <p><strong>Hotfix</strong> </p> <p>After <a href="https://stackoverflow.com/users/21336/devio">devio</a> posted the original answer, with a workaround, <a href="https://stackoverflow.com/users/18636/nullptr">nullptr</a> has confirm that there is now a <a href="http://support.microsoft.com/kb/2600088" rel="nofollow noreferrer">hotfix for this</a>.</p> <p><a href="http://support.microsoft.com/kb/2600088" rel="nofollow noreferrer">http://support.microsoft.com/kb/2600088</a></p> <p>I've promoted the hotfix to the main question as it's just handier for future reference, but please do up-vote the users mentioned.</p>
6,984,397
6
6
null
2011-08-08 14:33:37.387 UTC
46
2014-01-23 01:33:14.63 UTC
2017-05-23 12:17:56.673 UTC
null
-1
null
431,880
null
1
91
asp.net|internet-explorer
48,237
<p>Found this entry on <a href="http://connect.microsoft.com/VisualStudio/feedback/details/662275/asp-net-user-agent-sniffing-and-ie10-internet-explorer-10" rel="noreferrer">MS Connect</a>, the behavior is a recognized bug.</p> <p>Suggested Workaround (from the entry):</p> <blockquote> <p>== Workaround ==</p> <p>In the meantime to make it work and to avoid similar issues in the future, I use a file ~\App_Browsers\BrowserFile.browser with the following:</p> </blockquote> <pre><code>&lt;browsers&gt; &lt;browser refID="Default"&gt; &lt;capabilities&gt;&lt;!-- To avoid wrong detections of e.g. IE10 --&gt; &lt;capability name="cookies" value="true" /&gt; &lt;capability name="ecmascriptversion" value="3.0" /&gt; &lt;/capabilities&gt; &lt;/browser&gt; &lt;/browsers&gt; </code></pre>
6,998,083
Python causing: IOError: [Errno 28] No space left on device: '../results/32766.html' on disk with lots of space
<p>I am running a Python script that is causing the above error. The unusual thing is this script is running on a different machine and is having no problems.</p> <p>The difference is that on the machine that is causing the problems I am writing to an external hard drive. To make things even weirder this script has run on the problem machine and already written over 30,000 files. </p> <p>Some relevant information (The code that is causing the error):</p> <pre><code>nPage = 0 while nPage != -1: for d in data: if len(d.contents) &gt; 1: if '&lt;script' in str(d.contents): l = str(d.contents[1]) start = l.find('http://') end = l.find('&gt;',start) out = get_records.openURL(l[start:end]) print COUNT with open('../results/'+str(COUNT)+'.html','w') as f: f.write(out) COUNT += 1 nPage = nextPage(mOut,False) </code></pre> <p>The directory I'm writing to:</p> <pre><code>10:32@lorax:~/econ/estc/bin$ ll ../ total 56 drwxr-xr-x 3 boincuser boincuser 4096 2011-07-31 14:29 ./ drwxr-xr-x 3 boincuser boincuser 4096 2011-07-31 14:20 ../ drwxr-xr-x 2 boincuser boincuser 4096 2011-08-09 10:38 bin/ lrwxrwxrwx 1 boincuser boincuser 47 2011-07-31 14:21 results -&gt; /media/cavalry/server_backup/econ/estc/results// -rw-r--r-- 1 boincuser boincuser 44759 2011-08-09 10:32 test.html </code></pre> <p>Proof there is enough space:</p> <pre><code>10:38@lorax:~/econ/estc/bin$ df -h Filesystem Size Used Avail Use% Mounted on /dev/sda1 9.0G 5.3G 3.3G 63% / none 495M 348K 495M 1% /dev none 500M 164K 500M 1% /dev/shm none 500M 340K 500M 1% /var/run none 500M 0 500M 0% /var/lock none 9.0G 5.3G 3.3G 63% /var/lib/ureadahead/debugfs /dev/sdc10 466G 223G 244G 48% /media/cavalry </code></pre> <p>Some things I have tried:</p> <ul> <li>Changing the path of the write to the direct location instead of going through the link</li> <li>Rebooting the machine</li> <li>Unmounting and re-mounting the drive</li> </ul>
7,626,428
9
7
null
2011-08-09 14:46:23.833 UTC
11
2022-03-05 05:34:06.457 UTC
2014-11-03 19:33:18.92 UTC
null
117,259
null
828,394
null
1
52
python|filesystems|hard-drive
215,017
<p>It turns out the best solution for me here was to just reformat the drive. Once reformatted all these problems were no longer problems.</p>
38,204,342
Python 'in' keyword in expression vs. in for loop
<p>I understand what the <code>in</code> operator does in this code:</p> <pre><code>some_list = [1, 2, 3, 4, 5] print(2 in some_list) </code></pre> <p>I also do understand that <code>i</code> will take on each value of the list in this code:</p> <pre><code>for i in [1, 2, 3, 4, 5]: print(i) </code></pre> <p>I am curious if the <code>in</code> operator used in the <code>for</code> loop is the same as the <code>in</code> operator used in the first code.</p>
38,204,487
3
2
null
2016-07-05 13:09:54.607 UTC
10
2019-05-16 23:30:36.613 UTC
2016-07-05 13:19:59.753 UTC
null
2,877,364
null
4,865,862
null
1
14
python|loops|python-3.x|semantics
22,737
<p>They are the same concept but not the same operators.</p> <p>In the <code>print(2 in some_list)</code> example, <code>in</code> is an operator that handles several different situations. The <a href="https://docs.python.org/3/reference/expressions.html#membership-test-details" rel="noreferrer">Python docs for the <code>in</code> operator</a> give the details, which I paraphrase as follows: <code>x in y</code> calls <code>y.__contains__(x)</code> if <code>y</code> has a <code>__contains__</code> member function. Otherwise, <code>x in y</code> tries iterating through <code>y.__iter__()</code> to find <code>x</code>, or calls <code>y.__getitem__(x)</code> if <code>__iter__</code> doesn't exist. The complexity is to provide consistent membership testing for older code as well as newer code &mdash; <code>__contains__</code> is what you want if you're implementing your own classes.</p> <p>In the <code>for</code> loop, <code>in</code> is just a marker that separates the loop-index variable from whatever you're looping over. The <a href="https://docs.python.org/3/reference/compound_stmts.html#grammar-token-for_stmt" rel="noreferrer">Python docs for the <code>for</code> loop</a> discuss the semantics, which I paraphrase as follows: whatever comes after <code>in</code> is evaluated at the beginning of a loop to provide an iterator. The loop body then runs for each element of the iterator (barring <code>break</code> or other control-flow changes). The <code>for</code> statement doesn't worry about <code>__contains__</code> or <code>__getitem__</code>.</p> <p><strong>Edit</strong> @Kelvin makes a good point: you can change the behaviour of <code>in</code> with respect to your own new-style classes (<code>class foo(object)</code>):</p> <ul> <li>To change <code>x in y</code>, <a href="https://docs.python.org/3/reference/datamodel.html#object.__contains__" rel="noreferrer">define <code>y.__contains__()</code></a>. </li> <li>To change <code>for x in y</code>, <a href="https://docs.python.org/3/tutorial/classes.html#iterators" rel="noreferrer">define <code>y.__iter__()</code></a>.</li> </ul>
15,568,792
OAuth and custom scheme result in a "ERR_UNKNOWN_URL_SCHEME" in Chrome
<p>I've been stuck on this for hours now as the thing was working before but suddenly stopped to behave as expected. I don't really know how and why as I've been re-checking every single line of code in the process without being able to see what's wrong so I'm asking you guys for help.</p> <p>Alright. So I've a <code>LoginScreen</code> activity with a button starting a new <code>Intent.ACTION_VIEW</code> on click. This start the OAUTH proccess in the browser with a <code>ApiManager.OAUTH_CALLBACK_URI</code> set to <code>stjapp://oauthresponse</code>.</p> <p>Here's my <code>AndroidManifest.xml</code> part for this activity :</p> <pre class="lang-xml prettyprint-override"><code>&lt;activity android:name=".LoginScreen" android:label="@string/application" android:launchMode="singleTask"&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;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="stjapp" android:host="oauthresponse" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>How I start the <code>Intent.ACTION_VIEW</code> in my activity :</p> <pre class="lang-cs prettyprint-override"><code>private View.OnClickListener loginHandler = new View.OnClickListener() { public void onClick(View v) { OAuthClientRequest request = null; try { request = OAuthClientRequest .authorizationLocation(ApiManager.OAUTH_AUTHORIZE) .setClientId(ApiManager.CLIENT_ID).setRedirectURI(ApiManager.OAUTH_CALLBACK_URI) .buildQueryMessage(); } catch (OAuthSystemException e) { e.printStackTrace(); } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getLocationUri() + "&amp;response_type=code")); startActivity(intent); } }; </code></pre> <p>And here's a screenshot of what happens in the browser :</p> <p><img src="https://dl.dropbox.com/u/97027952/Stackoverflow/report22032013/Screenshot_2013-03-22-18-55-36.png" alt="enter image description here"></p> <p>There, I'm supposed to get back to my <code>LoginScreen</code> activity and handle the <code>code</code> query parameters within <code>onNewIntent</code> method but ... yeah, the thing doesn't work as expected anymore.</p> <p>Any help appreciated.</p>
15,601,063
4
1
null
2013-03-22 11:06:46.373 UTC
7
2016-08-28 13:09:20.713 UTC
2013-03-22 11:17:53.97 UTC
user926721
null
user926721
null
null
1
12
android|android-intent|android-manifest
47,723
<p>It looks like this is a <a href="https://code.google.com/p/chromium/issues/detail?id=181186" rel="noreferrer">Chromium bug</a>. The workaround I'm using is a PHP landing page for the RedirectURI that opens the app via JavaScript (which is not affected by that bug):</p> <pre><code>&lt;script language="javascript"&gt; window.location = 'myscheme://myhost/?&lt;?=$_SERVER["QUERY_STRING"]?&gt;'; &lt;/script&gt; </code></pre>
15,496,950
using multiple io_service objects
<p>I have my application in which listen and process messages from both internet sockets and unix domain sockets. Now I need to add SSL to the internet sockets, I was using a single <code>io_service</code> object for all the sockets in the application. It seems now I need to add separate <code>io_service</code> objects for network sockets and unix domain sockets. I don't have any threads in my application and I use <code>async_send</code> and <code>async_recieve</code> and <code>async_accept</code> to process data and connections. Please point me to any examples using multiple <code>io_service</code> objects with async handlers. </p>
15,507,020
2
6
null
2013-03-19 10:28:49.283 UTC
18
2013-03-19 20:49:53.97 UTC
2013-03-19 20:49:53.97 UTC
null
283,302
null
743,185
null
1
12
boost-asio
17,635
<p>The question has a degree of uncertainty as if multiple <code>io_service</code> objects are required. I could not locate anything in the <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference.html">reference</a> documentation, or the overview for <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/overview/ssl.html">SSL</a> and <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/overview/posix/local.html">UNIX Domain Sockets</a> that mandated separate <code>io_service</code> objects. Regardless, here are a few options:</p> <hr> <h3>Single <code>io_service</code>:</h3> <p>Try to use a single <code>io_service</code>.</p> <p>If you do not have a direct handle to the <code>io_service</code> object, but you have a handle to a Boost.Asio I/O object, such as a socket, then a handle to the associated <code>io_service</code> object can be obtained by calling <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/basic_stream_socket/get_io_service.html"><code>socket.get_io_service()</code></a>.</p> <hr> <h3>Use a thread per <code>io_service</code>:</h3> <p>If multiple <code>io_service</code> objects are required, then dedicate a thread to each <code>io_service</code>. This approach is used in Boost.Asio's <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/example/http/server2/">HTTP Server 2</a> example.</p> <pre class="lang-cpp prettyprint-override"><code>boost::asio::io_service service1; boost::asio::io_service service2; boost::thread_group threads; threads.create_thread(boost::bind(&amp;boost::asio::io_service::run, &amp;service1)); service2.run(); threads.join_all(); </code></pre> <p>One consequence of this approach is that the it may require thread-safety guarantees to be made by the application. For example, if <code>service1</code> and <code>service2</code> both have completion handlers that invoke <code>message_processor.process()</code>, then <code>message_processor.process()</code> needs to either be thread-safe or called in a thread-safe manner.</p> <hr> <h3>Poll <code>io_service</code>:</h3> <p><a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/io_service.html"><code>io_service</code></a> provides non-blocking alternatives to <code>run()</code>. Where as <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/io_service/run/overload1.html"><code>io_service::run()</code></a> will block until all work has finished, <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/io_service/poll/overload1.html"><code>io_service::poll()</code></a> will run handlers that are ready to run and will not block. This allows for a single thread to execute the event loop on multiple <code>io_service</code> objects:</p> <pre class="lang-cpp prettyprint-override"><code>while (!service1.stopped() &amp;&amp; !service2.stopped()) { std::size_t ran = 0; ran += service1.poll(); ran += service2.poll(); // If no handlers ran, then sleep. if (0 == ran) { boost::this_thread::sleep_for(boost::chrono::seconds(1)); } } </code></pre> <p>To prevent a tight-busy loop when there are no ready-to-run handlers, it may be worth adding in a sleep. Be aware that this sleep may introduce latency in the overall handling of events.</p> <hr> <h3>Transfer handlers to a single <code>io_service</code>:</h3> <p>One interesting approach is to use a <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/io_service__strand.html"><code>strand</code></a> to transfer completion handlers to a single <code>io_service</code>. This allows for a thread per <code>io_service</code>, while preventing the need to have the application make thread-safety guarantees, as all completion handlers will post through a single service, whose event loop is only being processed by a single thread.</p> <pre class="lang-cpp prettyprint-override"><code>boost::asio::io_service service1; boost::asio::io_service service2; // strand2 will be used by service2 to post handlers to service1. boost::asio::strand strand2(service1); boost::asio::io_service::work work2(service2); socket.async_read_some(buffer, strand2.wrap(read_some_handler)); boost::thread_group threads; threads.create_thread(boost::bind(&amp;boost::asio::io_service::run, &amp;service1)); service2.run(); threads.join_all(); </code></pre> <p>This approach does have some consequences:</p> <ul> <li>It requires handlers that are intended to by ran by the main <code>io_service</code> to be wrapped via <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/io_service__strand/wrap.html"><code>strand::wrap()</code></a>.</li> <li>The asynchronous chain now runs through two <code>io_service</code>s, creating an additional level of complexity. It is important to account for the case where the secondary <code>io_service</code> no longer has work, causing its <code>run()</code> to return.</li> </ul> <p>It is common for an asynchronous chains to occur within the same <code>io_service</code>. Thus, the service never runs out of work, as a completion handler will post additional work onto the <code>io_service</code>.</p> <pre class="lang-none prettyprint-override"><code> | .------------------------------------------. V V | read_some_handler() | { | socket.async_read_some(..., read_some_handler) --' } </code></pre> <p>On the other hand, when a strand is used to transfer work to another <code>io_service</code>, the wrapped handler is invoked within <code>service2</code>, causing it to post the completion handler into <code>service1</code>. If the wrapped handler was the only work in <code>service2</code>, then <code>service2</code> no longer has work, causing <code>servce2.run()</code> to return.</p> <pre class="lang-none prettyprint-override"><code> service1 service2 ==================================================== .----------------- wrapped(read_some_handler) | . V . read_some_handler NO WORK | . | . '----------------&gt; wrapped(read_some_handler) </code></pre> <p>To account for this, the example code uses an <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/io_service__work.html"><code>io_service::work</code></a> for <code>service2</code> so that <code>run()</code> remains blocked until explicitly told to <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/reference/io_service/stop.html"><code>stop()</code></a>.</p>
15,744,689
Apply a coupon programmatically in Woocommerce
<p>In Woocommerce I'm trying to find a way to apply a 10% discount to an entire customer's order if the weight in the cart is over 100 lbs. I'm partway to achieving this. For the next step, I'm looking for a way to programmatically apply a coupon code via action/hook through functions.php.</p> <p>It appears that I can use the function woocommerce_ajax_apply_coupon to do this ( <a href="http://docs.woothemes.com/wc-apidocs/function-woocommerce_ajax_apply_coupon.html" rel="noreferrer">http://docs.woothemes.com/wc-apidocs/function-woocommerce_ajax_apply_coupon.html</a> ) but I am unsure of how to use it.</p> <p>So far I've modified cart.php to get the total weight of all the products in the cart, I've created a coupon that applies the discount (if entered manually) and I've added some code to functions.php to check the weight and display a message to the user.</p> <p>EDIT: Partial code removed, completed code included in the solution below.</p> <hr> <p>Thanks for the guidance Freney. Here's the working end result which successfully applies the discount coupon when the condition is met and also removes it when it's no longer met: </p> <pre><code>/* Mod: 10% Discount for weight greater than 100 lbs Works with code added to child theme: woocommerce/cart/cart.php lines 13 - 14: which gets $total_weight of cart: global $total_weight; $total_weight = $woocommerce-&gt;cart-&gt;cart_contents_weight; */ add_action('woocommerce_before_cart_table', 'discount_when_weight_greater_than_100'); function discount_when_weight_greater_than_100( ) { global $woocommerce; global $total_weight; if( $total_weight &gt; 100 ) { $coupon_code = '999'; if (!$woocommerce-&gt;cart-&gt;add_discount( sanitize_text_field( $coupon_code ))) { $woocommerce-&gt;show_messages(); } echo '&lt;div class="woocommerce_message"&gt;&lt;strong&gt;Your order is over 100 lbs so a 10% Discount has been Applied!&lt;/strong&gt; Your total order weight is &lt;strong&gt;' . $total_weight . '&lt;/strong&gt; lbs.&lt;/div&gt;'; } } /* Mod: Remove 10% Discount for weight less than or equal to 100 lbs */ add_action('woocommerce_before_cart_table', 'remove_coupon_if_weight_100_or_less'); function remove_coupon_if_weight_100_or_less( ) { global $woocommerce; global $total_weight; if( $total_weight &lt;= 100 ) { $coupon_code = '999'; $woocommerce-&gt;cart-&gt;get_applied_coupons(); if (!$woocommerce-&gt;cart-&gt;remove_coupons( sanitize_text_field( $coupon_code ))) { $woocommerce-&gt;show_messages(); } $woocommerce-&gt;cart-&gt;calculate_totals(); } } </code></pre>
15,755,208
3
0
null
2013-04-01 13:46:23.027 UTC
17
2020-02-17 05:26:46.86 UTC
2020-02-17 05:26:46.86 UTC
null
5,891,719
null
776,485
null
1
37
php|wordpress|woocommerce|discount|coupon
66,841
<p>First, create a discount coupon (via <a href="http://docs.woothemes.com/document/create-a-coupon-programatically/" rel="noreferrer">http://docs.woothemes.com/document/create-a-coupon-programatically/</a>):</p> <pre><code>$coupon_code = 'UNIQUECODE'; // Code - perhaps generate this from the user ID + the order ID $amount = '10'; // Amount $discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product $coupon = array( 'post_title' =&gt; $coupon_code, 'post_content' =&gt; '', 'post_status' =&gt; 'publish', 'post_author' =&gt; 1, 'post_type' =&gt; 'shop_coupon' ); $new_coupon_id = wp_insert_post( $coupon ); // Add meta update_post_meta( $new_coupon_id, 'discount_type', $discount_type ); update_post_meta( $new_coupon_id, 'coupon_amount', $amount ); update_post_meta( $new_coupon_id, 'individual_use', 'no' ); update_post_meta( $new_coupon_id, 'product_ids', '' ); update_post_meta( $new_coupon_id, 'exclude_product_ids', '' ); update_post_meta( $new_coupon_id, 'usage_limit', '1' ); update_post_meta( $new_coupon_id, 'expiry_date', '' ); update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' ); update_post_meta( $new_coupon_id, 'free_shipping', 'no' ); </code></pre> <p>Then apply that coupon to your order:</p> <pre><code>if (!$woocommerce-&gt;cart-&gt;add_discount( sanitize_text_field( $coupon_code ))) $woocommerce-&gt;show_messages(); </code></pre> <p>That last function returns a BOOL value: TRUE if the discount was successful, FALSE if it fails for any one of a variety of reasons.</p>
15,787,610
Call method only if it exists
<p>Is there some hidden Ruby/Rails-magic for simply calling a method only if it exists?</p> <p>Lets say I want to call</p> <pre><code>resource.phone_number </code></pre> <p>but I don't know beforehand if resource responds to <code>phone_number</code>. A way to do this is</p> <pre><code>resource.phone_number if resource.respond_to? :phone_number </code></pre> <p>That's not all that pretty if used in the wrong place. I'm curious if something exists that works more along the lines of how <code>try</code> is used (<code>resource.try(:phone_number)</code>).</p>
15,787,790
5
6
null
2013-04-03 12:39:33.147 UTC
9
2021-01-22 09:12:51.627 UTC
2013-04-03 13:26:35.953 UTC
null
524,293
null
524,293
null
1
73
ruby-on-rails|ruby
75,766
<p>If you are not satisfied with the standard ruby syntax for that, you are free to:</p> <pre><code>class Object def try_outside_rails(meth, *args, &amp;cb) self.send(meth.to_sym, *args, &amp;cb) if self.respond_to?(meth.to_sym) end end </code></pre> <p>Now: </p> <pre><code>resource.try_outside_rails(:phone_number) </code></pre> <p>will behave as you wanted.</p>
10,612,813
IntelliJ IDEA can't setup JDK
<p>I'm trying to setup JDK in IntelliJ IDEA and whatever I do, or whatever JDK version I select, nothing happens. The following situation remains: <img src="https://i.stack.imgur.com/Uri5G.png" alt="enter image description here"></p> <p>So I told IDEA what JDK it should use, but it still asks me to setup a JDK. Is this a bug or am I missing something? Can I apply any workaround to make everything work as usual? </p> <h2>ADDITION</h2> <p>The steps which I go through setting up the JDK: situation before setting up:<br> <img src="https://i.stack.imgur.com/iDeZZ.png" alt="enter image description here"> </p> <p>the first step:<br> <img src="https://i.stack.imgur.com/xi8gQ.png" alt="enter image description here"> </p> <p>the second step:<br> <img src="https://i.stack.imgur.com/Yz7r1.png" alt="enter image description here"> </p> <p>the third step:<br> <img src="https://i.stack.imgur.com/j88Dd.png" alt="enter image description here"> </p> <p>the situation after setting up JDK: <img src="https://i.stack.imgur.com/Cyqqm.png" alt="enter image description here"> </p> <p>SDKs:<br> <img src="https://i.stack.imgur.com/M2ef7.png" alt="enter image description here"> </p> <p>module settings:<br> <img src="https://i.stack.imgur.com/SQFwa.png" alt="enter image description here"></p>
10,620,799
7
12
null
2012-05-16 05:57:00.143 UTC
16
2017-09-11 21:20:24.613 UTC
2014-11-26 19:04:39.4 UTC
null
3,885,376
null
1,199,519
null
1
56
java|intellij-idea|settings
65,766
<p><code>File</code> | <code>Invalidate Caches</code> is the first thing you should try in case of such issues.</p>
35,606,147
How to call javascript function from <script> tag?
<pre><code>&lt;html&gt; &lt;script&gt; //some largeFunction() //load a script dynamically based on the previous code document.write("&lt;script src='//...'&gt;&lt;\/script&gt;"); &lt;/script&gt; &lt;/html&gt; </code></pre> <p>Question: is it possible to move the <code>largeFunction()</code> out of the static <code>html</code> page and put it into a <code>js</code> file? If yes, how could I then call that function statically before writing the <code>&lt;script&gt;</code> tag?</p>
35,606,262
4
6
null
2016-02-24 15:27:53.96 UTC
5
2016-02-24 16:25:32.6 UTC
null
null
null
null
1,194,415
null
1
25
javascript|html
132,009
<p>Short answer: Yes. </p> <p>As long as you load the first script containing the function first, you can call the function anywhere, as long as it's loaded first.</p> <pre><code>&lt;script src="file1.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="file2.js" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>In this example, make sure <code>file1.js</code> contains your <code>largeFunction()</code> function. You can then call <code>largeFunction();</code> inside <code>file2.js</code>.</p> <p>You can also do this:</p> <pre><code>&lt;script src="file1.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script&gt; largeFunction(); &lt;/script&gt; </code></pre> <p>Just make sure your FIRST script contains the function.</p>
35,588,699
Response to preflight request doesn't pass access control check
<p>I'm getting this error using ngResource to call a <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="nofollow noreferrer">REST</a> API on <a href="https://en.wikipedia.org/wiki/Amazon_Web_Services" rel="nofollow noreferrer">Amazon Web Services</a>:</p> <blockquote> <p>XMLHttpRequest cannot load <a href="http://server.apiurl.com:8000/s/login?login=facebook" rel="nofollow noreferrer">http://server.apiurl.com:8000/s/login?login=facebook</a>. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. <em>Error 405</em></p> </blockquote> <p>Service:</p> <pre><code>socialMarkt.factory('loginService', ['$resource', function ($resource) { var apiAddress = &quot;http://server.apiurl.com:8000/s/login/&quot;; return $resource(apiAddress, { login: &quot;facebook&quot;, access_token: &quot;@access_token&quot;, facebook_id: &quot;@facebook_id&quot; }, { getUser: { method: 'POST' } }); }]); </code></pre> <p>Controller:</p> <pre><code>[...] loginService.getUser(JSON.stringify(fbObj)), function (data) { console.log(data); }, function (result) { console.error('Error', result.status); } [...] </code></pre> <p>I'm using Chrome. What else can I do in order to fix this problem?</p> <p>I've even configured the server to accept headers from origin <code>localhost</code>.</p>
35,588,856
26
8
null
2016-02-23 21:37:06.937 UTC
112
2022-09-18 12:02:38.237 UTC
2022-09-18 11:34:29.393 UTC
user6269864
63,550
null
2,896,963
null
1
647
javascript|ajax|http|cors|http-status-code-405
2,005,027
<p>You are running into <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="nofollow noreferrer">CORS</a> issues.</p> <p>There are several ways to fix or workaround this.</p> <ol> <li>Turn off CORS. For example: <a href="https://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome">How to turn off CORS in Chrome</a></li> <li><a href="https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-app-launcher-info-dialog" rel="nofollow noreferrer">Use a plugin for your browser</a></li> <li>Use a proxy, such as <a href="https://en.wikipedia.org/wiki/Nginx" rel="nofollow noreferrer">nginx</a>. <a href="http://oskarhane.com/avoid-cors-with-nginx-proxy_pass/" rel="nofollow noreferrer">Example of how to set up</a></li> <li>Go through the necessary setup for your server. This is more a factor of the web server you have loaded on your <a href="https://en.wikipedia.org/wiki/Amazon_Elastic_Compute_Cloud" rel="nofollow noreferrer">EC2</a> instance (presuming this is what you mean by &quot;Amazon web service&quot;). For your specific server, you can refer to the <a href="https://enable-cors.org/server.html" rel="nofollow noreferrer">enable CORS website.</a></li> </ol> <p>More verbosely, you are trying to access <em>api.serverurl.com</em> from <a href="https://en.wikipedia.org/wiki/Localhost" rel="nofollow noreferrer">localhost</a>. This is the exact definition of a cross-domain request.</p> <p>By either turning it off just to get your work done (OK, but poor security for you if you visit other sites and just kicks the can down the road) or you can use a proxy which makes your browser think all requests come from the local host when really you have a local server that then calls the remote server.</p> <p>So <em>api.serverurl.com</em> might become <em>localhost:8000/api</em>, and your local nginx or other proxy will send to the correct destination.</p> <hr /> <p>Now by popular demand, <a href="https://www.w3.org/wiki/CORS_Enabled" rel="nofollow noreferrer" title="!00% more CORS info">100% more CORS information</a>—the same great taste!</p> <hr /> <p>Bypassing CORS is exactly what is shown for those simply learning the front end. <em><a href="https://codecraft.tv/courses/angular/http/http-with-promises/" rel="nofollow noreferrer">HTTP Example with Promises</a></em></p>
33,123,633
Redis or Ehcache?
<p>Which is better suited for the following environment:</p> <ol> <li>Persistence not a compulsion.</li> <li>Multiple servers (with Ehcache some cache sync must be required).</li> <li>Infrequent writes and frequent reads.</li> <li>Relatively small database (very less memory requirement).</li> </ol> <p>I will pour out what's in my head currently. I may be wrong about these.</p> <p>I know Redis requires a separate server (?) and Ehcache provides local cache so it must be faster but will replicate cache across servers (?). Updating all caches after some update on one is possible with Ehcache.</p> <p>My question is which will suit better for the environment I mentioned?<br> Whose performance will be better or what are scenarios when one may outperform another?</p> <p>Thanks in advance.</p>
33,150,333
2
6
null
2015-10-14 11:03:18.407 UTC
14
2021-12-20 15:51:11.517 UTC
2017-04-10 07:45:03.973 UTC
null
814,702
null
4,806,903
null
1
36
spring|caching|redis|spring-boot|ehcache
34,449
<p>You can think Redis as a <strong>shared data structure</strong>, while Ehcache is a <em>memory block</em> storing serialized data objects. This is the main difference.</p> <p>Redis as a <em>shared data structure</em> means you can put some <strong>predefined</strong> data structure (such as <em>String</em>, <em>List</em>, <em>Set</em> <a href="https://redis.io/topics/data-types" rel="noreferrer">etc</a>) in one language and retrieve it in another language. This is useful if your project is <strong>multilingual</strong>, for example: Java the backend side , and PHP the front side. You can use Redis for a shared cache. But it can only store predefined data structure, you cannot insert any Java objects you want.</p> <p>If your project is only Java, i.e. not <strong>multilingual</strong>, Ehcache is a convenient solution. </p>
13,762,713
a different object with the same identifier value was already associated with the session when trying to persist entity
<p>I have a slight problem that I don't know how to solve. Could you help me please? When I am trying to persist entity I get next exception:</p> <pre><code>12:47:39,398 ERROR [org.black.dmitriy.entityHome.ScheduleHome] (http--127.0.0.1-8080-1) javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session: [org.black.dmitriy.entity.Schedule#1] at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1333) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final] at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final] at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1295) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final] at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:859) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_04] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_04] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_04] at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_04] at org.jboss.seam.persistence.EntityManagerInvocationHandler.invoke(EntityManagerInvocationHandler.java:46) [jboss-seam.jar:2.3.0.Final] at $Proxy81.persist(Unknown Source) at org.jboss.seam.framework.EntityHome.persist(EntityHome.java:84) [jboss-seam.jar:2.3.0.Final] at org.black.dmitriy.entityHome.ConversationHome.tryPersist(ConversationHome.java:147) [ejb.jar:] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_04] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_04] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_04] at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_04] at org.jboss.seam.util.Reflections.invoke(Reflections.java:22) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.core.ConversationInterceptor.aroundInvoke(ConversationInterceptor.java:65) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.transaction.TransactionInterceptor$1.work(TransactionInterceptor.java:97) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.util.Work.workInTransaction(Work.java:61) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.transaction.TransactionInterceptor.aroundInvoke(TransactionInterceptor.java:91) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:186) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:104) [jboss-seam.jar:2.3.0.Final] at org.black.dmitriy.entityHome.ScheduleHome_$$_javassist_seam_8.tryPersist(ScheduleHome_$$_javassist_seam_8.java) [ejb.jar:] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_04] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) [rt.jar:1.7.0_04] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.7.0_04] at java.lang.reflect.Method.invoke(Method.java:601) [rt.jar:1.7.0_04] at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:335) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6] at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6] at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6] at org.jboss.el.parser.AstValue.invoke(AstValue.java:96) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6] at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276) [jboss-el-1.0_02.CR6.jar:1.0_02.CR6] at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105) [jsf-impl-2.1.7-jbossorg-2.jar:] at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final] at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) [jsf-impl-2.1.7-jbossorg-2.jar:] at javax.faces.component.UICommand.broadcast(UICommand.java:315) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final] at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final] at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final] at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) [jsf-impl-2.1.7-jbossorg-2.jar:] at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.7-jbossorg-2.jar:] at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) [jsf-impl-2.1.7-jbossorg-2.jar:] at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593) [jboss-jsf-api_2.1_spec-2.0.1.Final.jar:2.0.1.Final] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:] at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) [jboss-seam.jar:2.3.0.Final] at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158) [jboss-seam.jar:2.3.0.Final] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:397) [jbossweb-7.0.13.Final.jar:] at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final] at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:] at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_04] </code></pre> <p>I use seam 2.3, hibernate. I have one insert statement in my import.sql file:</p> <pre><code>INSERT INTO Schedules (id, name, dayCount, lessonCount, firstTermSize, secondTermSize, subgroupSize) VALUES(1, '2012/2013', 5, 8, 9, 9, 18) </code></pre> <p>which inserts one enity into table Schedules.</p> <p>Then I create new Schedule entity throw web page using EntityHome</p> <pre><code>@Name("scheduleHome") @Scope(ScopeType.CONVERSATION) public class ScheduleHome extends ConversationHome&lt;Schedule&gt; { private static final long serialVersionUID = 1L; public ScheduleHome() { } @Override protected boolean isUnique() { Schedule schedule = getInstance(); Schedule foundSchedule = ScheduleDAO.instance().getByName(schedule.getName()); if ((foundSchedule != null) &amp;&amp; (!foundSchedule.equals(schedule))) { showExistsErrorMessage(getInstance().getName()); return false; } return true; } @Override protected Schedule createInstance() { return new Schedule(); } @Override public String getEditOutcome() { return "scheduleEdit"; } @Override protected void prepareEntityForSaving() { } } </code></pre> <p>and the superclass</p> <pre><code>public abstract class ConversationHome&lt;T&gt; extends EntityHome&lt;T&gt; { private static final long serialVersionUID = 1L; private String parentView; public boolean isParentViewExists() { return parentView != null &amp;&amp; parentView.length() &gt; 0; } public void setParentView(String parentView) { this.parentView = parentView; } public String getParentView() { return parentView; } public abstract String getEditOutcome(); protected abstract void prepareEntityForSaving(); protected abstract boolean isUnique(); @Override @Create public void create() { create(false); } protected void create(boolean createNestedConversation) { Conversation conversation = Conversation.instance(); if (!createNestedConversation &amp;&amp; conversation.isLongRunning()) { getLog().debug("conversation already started, nested will not create(isLongRunning = #0, isNested = #1)", conversation.isLongRunning(), conversation.isNested()); } else { conversation.begin(false, conversation.isLongRunning()); conversation.changeFlushMode(FlushModeType.MANUAL); getLog().debug("create(isLongRunning = #0, isNested = #1, id = #2)", conversation.isLongRunning(), conversation.isNested(), conversation.getId()); } super.create(); } private boolean init(Long id) { FacesContext context = FacesContext.getCurrentInstance(); setParentView(Pages.getViewId(context)); if (id != null) { setId(id); try { getInstance(); getLog().debug("instance initialized #0", getInstance()); } catch (EntityNotFoundException e) { getLog().error(e); return false; } } return true; } public String startEdit(Long id) { getLog().debug("start editing #0", id); if (init(id)) { return getEditOutcome(); } else { return cancel(); } } public String cancel() { if (isManaged()) { getEntityManager().refresh(getInstance()); } return returnToParent(); } @End protected String returnToParent() { if (isParentViewExists()) { Conversation conversation = Conversation.instance(); getLog().debug("end conversation(id = #0, isLongRunning = #1, isNested = #2)", conversation.getId(), conversation.isLongRunning(), conversation.isNested()); conversation.end(true); return getParentView(); } else { clearInstance(); return null; } } public String tryPersist() { if (isUnique()) { try { prepareEntityForSaving(); String outcome = persist(); if (!"failed".equals(outcome)) { return returnToParent(); } } catch (Exception e) { getLog().error(getInstance(), e); showSaveErrorMessage(e); } } return "failed"; } } </code></pre> <p>and when i try to persist it i get this exception. and message on web page</p> <p>Save error with message: a different object with the same identifier value was already associated with the session: [org.black.dmitriy.entity.Schedule#1]</p> <p>It seams that hibernate set id property to 1, but I already have entity with <code>id = 1</code>, because I manually created it throw import.sql.</p> <p>Here is my Schedule entity :</p> <pre><code>import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; @Entity @Table(name = "Schedules") public class Schedule { @Id @GeneratedValue @Column(name = "id", nullable = false) private Long id; @NotNull @Column(name = "name", nullable = false, length = 40) private String name; @Column(name = "dayCount") private int dayCount = 5; @Column(name = "lessonCount") private int lessonCount = 8; @Column(name = "firstTermSize") private int firstTermSize = 9; @Column(name = "secondTermSize") private int secondTermSize = 9; @Column(name = "subgroupSize") private int subgroupSize = 18; @OneToMany(mappedBy = "schedule", cascade = CascadeType.ALL, targetEntity = Faculty.class) private List&lt;Faculty&gt; faculties = new ArrayList&lt;&gt;(); @OneToMany(mappedBy = "schedule", cascade = CascadeType.ALL, targetEntity = Building.class) private List&lt;Building&gt; buildings = new ArrayList&lt;&gt;(); public Schedule() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDayCount() { return dayCount; } public void setDayCount(int dayCount) { this.dayCount = dayCount; } public int getLessonCount() { return lessonCount; } public void setLessonCount(int lessonCount) { this.lessonCount = lessonCount; } public int getFirstTermSize() { return firstTermSize; } public void setFirstTermSize(int firstTermSize) { this.firstTermSize = firstTermSize; } public int getSecondTermSize() { return secondTermSize; } public void setSecondTermSize(int secondTermSize) { this.secondTermSize = secondTermSize; } public int getSubgroupSize() { return subgroupSize; } public void setSubgroupSize(int subgroupSize) { this.subgroupSize = subgroupSize; } public List&lt;Faculty&gt; getFaculties() { return faculties; } public void setFaculties(List&lt;Faculty&gt; faculties) { this.faculties = faculties; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Schedule)) { return false; } Schedule other = (Schedule) obj; if (id == null) { if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } return true; } @Override public String toString() { return this.name; } } </code></pre> <p>As you can see there is @GeneratedValue annotation on id property, so I think that hibernate should generate id himself and hibernate should know that there is entity in database with id = 1, and set id in new entity = 2. But Hibernate sets id in new entity to 1. Could you halp me please?</p>
13,806,897
2
0
null
2012-12-07 12:02:14.957 UTC
1
2013-09-05 05:04:16.403 UTC
2013-09-05 05:04:16.403 UTC
null
1,830,513
null
1,767,476
null
1
7
sql|hibernate|seam
45,778
<p>The problem was how hibernate generates your <code>id</code>'s, it starts from 1. When it assigns 1 to an object before saving it into database, it sees a row with same id already exists in the database and causes the exception. The simple and natural solution of this problem is simply to restrict hibernate, so that it can not assign <code>1</code> as an id to any object of the concerning class (in your case).</p> <p><b>Solution for mySql: </b></p> <p>If you are using mySql, you can create table manually and set the auto increment like:</p> <pre><code> CREATE TABLE IF NOT EXISTS `testTable` ( `id` number(11) NOT NULL AUTO_INCREMENT, ..., ..., ..., PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2; //assigning id by hibernate, will start from 2. </code></pre> <p>And in your domain class you can have id annotated like bellow:</p> <pre><code>@Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID") public long getId() { .... } </code></pre> <p><code>GenerationType.AUTO</code> by default uses auto increment in mySql. and after setting <code>AUTO_INCREMENT=2</code> hibernate will start assigning id's from <code>2</code> (hence <code>1</code> is skipped).</p> <p><b>Solution for Oracle: </b></p> <p>The same thing for oracle can be done if you restrict hibernate use a "sequence" and you set the initial point of the sequence as your wish. You can create a sequence to be start from <code>2</code> and increment by <code>1</code> like bellow:</p> <pre><code> create sequence idSequence start with 2 increment by 1 maxvalue 9999999999999; </code></pre> <p>And you can specify your sequence to be used to generate id's of your domain class's object like bellow:</p> <pre><code>@Id @SequenceGenerator(name = "idGeneratorSeq", sequenceName = "idSequence") @GeneratedValue(strategy = GenerationType.AUTO, generator = "idGeneratorSeq") @Column(name = "ID") public long getId() { .... } </code></pre> <p>And your problem is sovled.</p>
13,756,356
Different databases for different apps in Django
<p>I have multiple apps in my Django site: <em>mainsite</em>, <em>blog</em> and <em>tutorials</em>.</p> <p>Can I use different databases (e.g. PostgreSQL, MySQL) in different Django apps?</p>
13,756,801
1
1
null
2012-12-07 03:10:38.91 UTC
9
2019-05-09 11:35:52.477 UTC
2018-08-27 06:50:20.897 UTC
null
1,097,104
null
767,244
null
1
27
python|django
11,822
<p>Here is what you will have to do to get going.</p> <p>1) Update settings for databases that you want to use.</p> <p>settings.py</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/var/db/projectdb' } 'db_app1': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/var/db/app1db' } 'db_app2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/var/db/app2db' } </code></pre> <p>2) For each database, implement a database router that will route the queries appropriately. In your case implement in each app. Note this more or less taken from django docs.</p> <p>app1.dbRouter.py</p> <pre><code># DB router for app1 class App1DBRouter(object): """ A router to control app1 db operations """ def db_for_read(self, model, **hints): "Point all operations on app1 models to 'db_app1'" from django.conf import settings if not settings.DATABASES.has_key('db_app1'): return None if model._meta.app_label == 'app1': return 'db_app1' return None def db_for_write(self, model, **hints): "Point all operations on app1 models to 'db_app1'" from django.conf import settings if not settings.DATABASES.has_key('db_app1'): return None if model._meta.app_label == 'app1': return 'db_app1' return None def allow_relation(self, obj1, obj2, **hints): "Allow any relation if a model in app1 is involved" from django.conf import settings if not settings.DATABASES.has_key('db_app1'): return None if obj1._meta.app_label == 'app1' or obj2._meta.app_label == 'app1': return True return None def allow_syncdb(self, db, model): "Make sure the app1 app only appears on the 'app1' db" from django.conf import settings if not settings.DATABASES.has_key('db_app1'): return None if db == 'db_app1': return model._meta.app_label == 'app1' elif model._meta.app_label == 'app1': return False return None </code></pre> <p>3) Update <code>DATABASE_ROUTERS</code> in settings.py</p> <p>settings.py</p> <pre><code>DATABASE_ROUTERS = ['app1.dbRouter.App1DBRouter', 'app2.dbRouter.App2DBRouter'] </code></pre> <p><strong>Note for people who use Python 3</strong></p> <p>statements like</p> <pre><code> if not settings.DATABASES.has_key('db_app1'): </code></pre> <p>should become</p> <pre><code> if 'db_app1' not in settings.DATABASES: </code></pre>
13,481,276
Threading in python using queue
<p>I wanted to use threading in python to download lot of webpages and went through the following code which uses queues in one of the website.</p> <p>it puts a infinite while loop. Does each of thread run continuously with out ending till all of them are complete? Am I missing something.</p> <pre><code>#!/usr/bin/env python import Queue import threading import urllib2 import time hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com", "http://ibm.com", "http://apple.com"] queue = Queue.Queue() class ThreadUrl(threading.Thread): """Threaded Url Grab""" def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while True: #grabs host from queue host = self.queue.get() #grabs urls of hosts and prints first 1024 bytes of page url = urllib2.urlopen(host) print url.read(1024) #signals to queue job is done self.queue.task_done() start = time.time() def main(): #spawn a pool of threads, and pass them queue instance for i in range(5): t = ThreadUrl(queue) t.setDaemon(True) t.start() #populate queue with data for host in hosts: queue.put(host) #wait on the queue until everything has been processed queue.join() main() print "Elapsed Time: %s" % (time.time() - start) </code></pre>
13,481,512
3
3
null
2012-11-20 20:11:05.087 UTC
12
2013-04-26 02:38:24.65 UTC
2012-11-21 19:28:42.723 UTC
null
1,475,962
null
1,475,962
null
1
28
python|multithreading
54,067
<p>Setting the thread's to be <code>daemon</code> threads causes them to exit when the main is done. But, yes you are correct in that your threads will run continuously for as long as there is something in the <code>queue</code> else it will block.</p> <p>The documentation explains this detail <a href="http://docs.python.org/2/library/queue.html" rel="noreferrer">Queue docs</a></p> <p>The python Threading documentation explains the <code>daemon</code> part as well.</p> <p><em>The entire Python program exits when no alive non-daemon threads are left.</em></p> <p>So, when the queue is emptied and the <code>queue.join</code> resumes when the interpreter exits the threads will then die.</p> <p>EDIT: Correction on default behavior for <code>Queue</code></p>
13,633,789
Jquery .on with doubleclick event
<p>Why would this work :</p> <pre><code>$(document).on("dblclick", "#areaA tr:has(td)", function(e) { //code here }); </code></pre> <p>and this does not</p> <pre><code>$("#areaA tr:has(td)").on('dblclick', function(e) { //Code here }); </code></pre> <p>I'm following the example on the jquery documentation page exactly, but my double click does not fire. When I do it the first way, it works, but seems like it fires the event twice.</p> <p>This is in the context of a Kendo UI grid.</p> <p>Is there really a difference between these two pieces of code?</p>
13,633,810
3
1
null
2012-11-29 20:04:31.983 UTC
4
2017-07-31 14:06:48.96 UTC
2016-04-14 20:26:40.01 UTC
null
1,687,083
null
1,031,516
null
1
70
jquery
106,730
<p>The main difference is that the condition in the first one will be checked each time you click. So if the element with id <code>areaA</code> or the <code>tr</code> or <code>td</code> inside is added dynamically, only the first one can work.</p>
13,479,163
Round float to x decimals?
<p>Is there a way to round a python float to x decimals? For example:</p> <pre><code>&gt;&gt;&gt; x = roundfloat(66.66666666666, 4) 66.6667 &gt;&gt;&gt; x = roundfloat(1.29578293, 6) 1.295783 </code></pre> <p>I've found ways to trim/truncate them (66.666666666 --&gt; 66.6666), but not round (66.666666666 --&gt; 66.6667).</p>
13,479,195
5
0
null
2012-11-20 17:55:05.057 UTC
24
2021-08-01 11:07:43.97 UTC
2021-08-01 11:07:43.97 UTC
null
270,986
null
992,444
null
1
101
python|math|rounding
163,828
<p>Use the built-in function <code>round()</code>:</p> <pre><code>In [23]: round(66.66666666666,4) Out[23]: 66.6667 In [24]: round(1.29578293,6) Out[24]: 1.295783 </code></pre> <p>help on <code>round()</code>:</p> <blockquote> <p>round(number[, ndigits]) -> floating point number</p> <p>Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative.</p> </blockquote>
20,464,631
Detect permission of camera in iOS
<p>I am developing a very simple video app. I use the official control: UIImagePickerController.</p> <p>Here is the problem. When presenting the UIImagePickerController for the first time, the iOS will ask for the permission. The user can click yes or no. If the user clicks no, the control is not dismissed. Instead, if the user keeps clicking the start button, the timers go on while the screen is always black, and the user can't stop the timers or go back. The only thing the user can do is to kill the app. The next time the UIImagePickerController is presented, it is still a black screen and the user can't go back if clicking start. </p> <p>I was wondering if it's a bug. Is there any way we can detect the permission of the camera so that we can decide to show the UIImagePickerController or not?</p>
20,464,727
6
2
null
2013-12-09 06:40:11.25 UTC
33
2021-09-22 08:32:18.78 UTC
2018-05-17 10:40:56.747 UTC
null
1,033,581
null
418,751
null
1
158
ios|permissions|camera|uiimagepickercontroller|ios-permissions
94,386
<p>Check the <code>AVAuthorizationStatus</code> and handle the cases properly.</p> <pre><code>NSString *mediaType = AVMediaTypeVideo; AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType]; if(authStatus == AVAuthorizationStatusAuthorized) { // do your logic } else if(authStatus == AVAuthorizationStatusDenied){ // denied } else if(authStatus == AVAuthorizationStatusRestricted){ // restricted, normally won't happen } else if(authStatus == AVAuthorizationStatusNotDetermined){ // not determined?! [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) { if(granted){ NSLog(@"Granted access to %@", mediaType); } else { NSLog(@"Not granted access to %@", mediaType); } }]; } else { // impossible, unknown authorization status } </code></pre>
3,307,576
What is the function got get all the media files wordpress?
<p>Can anyone suggest me what is the function to get all the images stored for wordpress? I just need to list all the images seen under menu Media of the wordpress admin.</p> <p>Thanks in advance</p>
3,307,762
2
0
null
2010-07-22 09:50:25.7 UTC
10
2014-09-15 13:59:48.177 UTC
null
null
null
null
75,472
null
1
15
wordpress|function|image
19,614
<p>Uploaded images are stored as posts with the type "attachment"; use get_posts() with the right parameters. In <a href="http://codex.wordpress.org/Template_Tags/get_posts" rel="noreferrer">the Codex entry for get_posts()</a>, this example:</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; -1, 'post_status' =&gt; null, 'post_parent' =&gt; null, // any parent ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $post) { setup_postdata($post); the_title(); the_attachment_link($post-&gt;ID, false); the_excerpt(); } } ?&gt; </code></pre> <p>...loops through all the attachments and displays them.</p> <p>If you just want to get images, as TheDeadMedic commented, you can filter with <code>'post_mime_type' =&gt; 'image'</code> in the arguments.</p>
3,693,820
Bottom borders on WPF Grid
<p>I'd like to set a bottom border on each row in the grid, but can only find how to put all 4 borders around each cell.. </p> <pre><code>&lt;Grid Height="174" HorizontalAlignment="Left" Margin="23,289,0,0" Name="grid2" VerticalAlignment="Top" Width="730"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="45" /&gt; &lt;RowDefinition Height="25" /&gt; &lt;RowDefinition Height="25" /&gt; &lt;RowDefinition Height="25" /&gt; &lt;RowDefinition Height="25" /&gt; &lt;RowDefinition Height="25" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="255" /&gt; &lt;ColumnDefinition Width="95" /&gt; &lt;ColumnDefinition Width="95" /&gt; &lt;ColumnDefinition Width="95" /&gt; &lt;ColumnDefinition Width="95" /&gt; &lt;ColumnDefinition Width="95" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;/Grid&gt; </code></pre> <p>For another grid I'm using that needs all four borders, I'm using </p> <pre><code>&lt;Border Grid.Column="0" Grid.Row="0" BorderBrush="#61738B" BorderThickness="1" /&gt; </code></pre> <p>P.S. The contents of the grid are some labels, textboxes, etc.. if that matters at all.</p>
3,693,827
2
0
null
2010-09-12 05:05:02.257 UTC
2
2020-01-29 03:25:38.583 UTC
2020-01-29 03:25:38.583 UTC
null
285,795
null
333,255
null
1
46
c#|wpf|border|wpf-grid
54,752
<p>On a <code>Border</code> control You can do <code>BorderThickness="0 0 0 1"</code> to only have a bottom border shown. </p> <p>Top and bottom border thickness of 5, left and right border thickness of 0</p> <p><code>BorderThickness="0 5"</code></p> <p>Top and bottom border thickness of 0, left and right border thickness of 5</p> <p><code>BorderThickness="5 0"</code></p> <p>Border Thickness - Left: 1, Top: 2, Right:3, Bottom: 4</p> <p><code>BorderThickness="1 2 3 4"</code></p> <p>Hope this helps!</p>
16,200,965
Regular Expression - Validate Gmail addresses
<p>I am trying to create an expression to validate Gmail addresses. That's what I've done so far.</p> <pre><code>^([\w]*[\w\.]*(?!\.)@gmail.com) </code></pre> <p>I am trying to create an expression to validate Gmail addresses. That's what I've done so far.</p> <p>But it isn't working as I want.</p> <p>Gmail address:</p> <ol> <li>First and last character has to be [a-z0-9]</li> <li>The username contents only [a-z0-9.]</li> <li>There cannot be consecutive periods (i.e: <code>[email protected]</code> [This is wrong])</li> <li>There length of the username has to be between 6 and 30 letters.</li> </ol> <p>Being honest I don't have much experience with the Regular Expressions.</p> <p>By the way, is there a documentation for Regular Expression?</p>
16,201,085
10
4
null
2013-04-24 19:54:00.767 UTC
8
2022-03-10 18:55:15.177 UTC
2018-09-02 18:35:33.24 UTC
user2137179
6,634,591
user2137179
null
null
1
18
regex
65,429
<p>You did not tell which regex implementation you use.</p> <pre><code>^[a-z0-9](\.?[a-z0-9]){5,}@g(oogle)?mail\.com$ </code></pre> <ul> <li><code>[a-z0-9]</code> first character</li> <li><code>(\.?[a-z0-9]){5,}</code> at least five following alphanumeric characters, maybe preceded by a dot (see @Daniel's comment, copied from @Christopher's answer)</li> <li><code>g(oogle)?mail</code> gmail or googlemail (see @alroc's answer)</li> </ul> <p>Probably you will want to use case-insensitive pattern matching, too. (<code>/.../i</code> in JavaScript.)</p>
16,207,427
compile error: cannot find symbol: In, StdIn and StdOut
<p>The code is from <a href="http://algs4.cs.princeton.edu/11model/BinarySearch.java.html">http://algs4.cs.princeton.edu/11model/BinarySearch.java.html</a> for Algorithms textbook.</p> <pre class="lang-java prettyprint-override"><code>import java.util.Arrays; public class BinarySearch { // precondition: array a[] is sorted public static int rank(int key, int[] a) { int lo = 0; int hi = a.length - 1; while (lo &lt;= hi) { // Key is in a[lo..hi] or not present. int mid = lo + (hi - lo) / 2; if (key &lt; a[mid]) hi = mid - 1; else if (key &gt; a[mid]) lo = mid + 1; else return mid; } return -1; } public static void main(String[] args) { int[] whitelist = In.readInts(args[0]); Arrays.sort(whitelist); // read key; print if not in whitelist while (!StdIn.isEmpty()) { int key = StdIn.readInt(); if (rank(key, whitelist) == -1) StdOut.println(key); } } } </code></pre> <p>I get this error</p> <pre><code>$ javac BinarySearch.java BinarySearch.java:44: cannot find symbol symbol : variable In location: class BinarySearch int[] whitelist = In.readInts(args[0]); ^ BinarySearch.java:49: cannot find symbol symbol : variable StdIn location: class BinarySearch while (!StdIn.isEmpty()) { ^ BinarySearch.java:50: cannot find symbol symbol : variable StdIn location: class BinarySearch int key = StdIn.readInt(); ^ BinarySearch.java:52: cannot find symbol symbol : variable StdOut location: class BinarySearch StdOut.println(key); ^ 4 errors </code></pre>
16,207,478
7
1
null
2013-04-25 06:00:17.233 UTC
3
2021-07-13 09:07:54.347 UTC
null
null
null
null
536,890
null
1
19
java
44,742
<p>Classes <code>StdIn</code>, <code>StdOut</code> and <code>In</code> aren't part of the standard Java libraries. They're support classes provided to go along with the Princeton course.</p> <p>From the <a href="http://algs4.cs.princeton.edu/11model/" rel="nofollow noreferrer">1.1 Programming Model</a> page linked in the source code:</p> <blockquote> <p>Standard input and standard output. <a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdIn.html" rel="nofollow noreferrer"><code>StdIn.java</code></a> and <a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdOut.html" rel="nofollow noreferrer"><code>StdOut.java</code></a> are libraries for reading in numbers and text from standard input and printing out numbers and text to standard output. Our versions have a simpler interface than the corresponding Java ones (and provide a few tecnical improvements).</p> <p>...</p> <p><a href="http://algs4.cs.princeton.edu/11model/In.java.html" rel="nofollow noreferrer"><code>In.java</code></a> and <a href="http://algs4.cs.princeton.edu/11model/Out.java.html" rel="nofollow noreferrer"><code>Out.java</code></a> are object-oriented versions that support multiple input and output streams, including reading from a file or URL and writing to a file.</p> </blockquote> <p>So if you want to use the binary search code as-is, you'll need to download those files.</p>
16,326,529
Python - get process names,CPU,Mem Usage and Peak Mem Usage in windows
<p>I am wanting to get a list of all the process names, CPU, Mem Usage and Peak Mem Usage. I was hoping I could use ctypes. but I am happy to hear any other options. Thanks for your time.</p>
16,331,254
3
2
null
2013-05-01 21:06:31.573 UTC
8
2020-09-01 07:48:21.953 UTC
null
null
null
null
2,334,276
null
1
24
python|windows|memory|process|cpu
62,028
<p>You can use <a href="https://github.com/giampaolo/psutil" rel="nofollow noreferrer"><code>psutil</code></a>.</p> <p>For example, to obtain the list of process names:</p> <pre><code>process_names = [proc.name() for proc in psutil.process_iter()] </code></pre> <p>For info about the CPU use <a href="https://psutil.readthedocs.io/en/latest/#psutil.cpu_percent" rel="nofollow noreferrer"><code>psutil.cpu_percent</code></a> or <a href="https://psutil.readthedocs.io/en/latest/#psutil.cpu_times" rel="nofollow noreferrer"><code>psutil.cpu_times</code></a>. For info about memory usage use <a href="https://psutil.readthedocs.io/en/latest/#psutil.virtual_memory" rel="nofollow noreferrer"><code>psutil.virtual_memory</code></a>.</p> <p>Note that psutil works with Linux, OS X, Windows, Solaris and FreeBSD and with python 2.4 through 3.3.</p>
16,108,399
Deny access to specific file types in specific directory
<p>For some application, users are able to upload their own files. Since this can be very large files, they are allowed to upload them via their own FTP client.</p> <p>Of course I wouldn't like them to upload some PHP files with which they can access all other files on the server. One of the ways I want to prevent this behavior is by denying access to specific file types (like php, rb, py, etc.) only in these folders.</p> <p>I have found ways to deny access to folders, to files, to files in folders, but nothing about file types in folders.</p> <p>I tried combining what I've found, like:</p> <pre><code>&lt;Files ~ "\.inc$"&gt; Order allow,deny Deny from all &lt;/Files&gt; </code></pre> <p>changing to</p> <pre><code>&lt;Files uploads/ "\.inc$"&gt; Order allow,deny Deny from all &lt;/Files&gt; </code></pre> <p>or alternative ways</p> <pre><code>RewriteRule ^(\.php) - [F,L,NC] </code></pre> <p>to</p> <pre><code>RewriteRule ^(uploads/\.php) - [F,L,NC] </code></pre> <p>However, I can't find out what syntax I should use.</p> <p>So, for example, I could have the following (basic example):</p> <pre><code>/index.php /uploads/ hack.php hack.rb hack.py pony.jpg </code></pre> <p>I want hack.php/rb/py to be unavailable, but everything else to be available. What syntax should I use?</p>
20,489,058
3
0
null
2013-04-19 15:41:40.497 UTC
5
2020-12-31 18:59:08.637 UTC
2013-12-10 08:03:34.66 UTC
null
1,862,009
null
2,299,798
null
1
26
file|.htaccess|directory|file-type
43,921
<p>The FilesMatch directive works purely on filenames. It doesn't look at the path portion at all.</p> <p>If you want to specify directives in the root .htaccess file to control a subdirectory, you can use <a href="http://httpd.apache.org/docs/current/mod/mod_rewrite.html" rel="noreferrer">mod_rewrite</a>.</p> <p>Try this:</p> <pre><code>RewriteRule ^uploads/.*\.(php|rb|py)$ - [F,L,NC] </code></pre> <p>The above will block any filename ending in .php or .rb or .py in the /uploads directory or its subdirectories. For example, it will block:</p> <ul> <li>/uploads/something.php</li> <li>/uploads/something/more.php </li> </ul> <p>Note that there is no leading slash in the rewrite rule. The path that you need to use in the directive will be different depending on where it's placed. The above directive, if placed in the document root's .htaccess file, will work for files in a directory called <em>uploads</em> that is directly beneath document root.</p> <p>While the above answers your question, it would be <strong>safer to allow</strong> only specific files rather than trying to block files. Often a server will execute files with extensions other than the ones you've listed.</p> <p>You could do something like this:</p> <pre><code>RewriteCond %{REQUEST_URI} ^/uploads [NC] RewriteCond %{REQUEST_URI} !\.(jpe?g|png|gif)$ [NC] RewriteRule .* - [F,L] </code></pre> <p>With the above, if the request URI begins with /uploads but does not end with one of the specified extensions, then it is forbidden. You can change the extensions to whatever suits your needs. But that way, you can permit extensions as needed rather than finding out too late that you missed blocking one.</p> <p>This rule (from your question)</p> <pre><code>RewriteRule ^(uploads/\.php) - [F,L,NC] </code></pre> <p>will block</p> <ul> <li>/uploads/.php</li> <li>/uploads/.phpmore</li> </ul> <p>but it does not allow for anything between the directory name and the file extension.</p> <p>If you are going to use rewirte rules, you might want to learn more about regexp. I often refer to <a href="http://www.regular-expressions.info/" rel="noreferrer">www.regular-expressions.info</a> when I need to look up something.</p>
16,233,910
Can transient keywords mark a method?
<p>In a java class java.util.Locale, I find that the keyword transient marked a method.</p> <pre><code> public final class Locale implements Cloneable, Serializable { private static class LocaleNameGetter implements sun.util.LocaleServiceProviderPool.LocalizedObjectGetter { public transient String getObject(LocaleNameProvider localenameprovider, Locale locale, String s, Object aobj[]) { if(!$assertionsDisabled &amp;&amp; aobj.length != 2) throw new AssertionError(); int i = ((Integer)aobj[0]).intValue(); String s1 = (String)aobj[1]; switch(i) { case 0: // '\0' return localenameprovider.getDisplayLanguage(s1, locale); case 1: // '\001' return localenameprovider.getDisplayCountry(s1, locale); case 2: // '\002' return localenameprovider.getDisplayVariant(s1, locale); } if(!$assertionsDisabled) throw new AssertionError(); else return null; } </code></pre> <p>Can someone tell me why can this be?</p>
16,234,127
6
6
null
2013-04-26 10:09:34.507 UTC
9
2021-10-12 07:19:27.07 UTC
null
null
null
null
2,255,879
null
1
26
java|transient
13,549
<p>No it can't, it's only valid for fields. You seem to get your source from .class by decompiling. This is the decompiler bug, if you take a look at <code>java.lang.reflect.Modifier</code> src you will see that <code>transient</code> and <code>varargs</code> have the same value</p> <pre><code>public static final int TRANSIENT = 0x00000080; ... static final int VARARGS = 0x00000080; </code></pre> <p>for a field <code>0x00000080</code> means <code>transient</code>, for a method (your case) it means <code>varargs</code>. This is how <code>getObject</code> looks like in java.util.Locale src</p> <pre><code>public String getObject(LocaleNameProvider localeNameProvider, Locale locale, String key, Object... params) { &lt;-- varargs </code></pre> <p>In .class (bytecode) varargs is represented by Object[] as the last parameter + modifier bit 7 = 1 (0x80). I guess the decompiler is old and simply does not know about <code>varargs</code> which is since Java 1.5 so it printed it as <code>transient</code>.</p>
16,114,000
Nesting Media Queries
<p>By default I want to give my body element a green border. On a device that supports retina display I want to check for size first. On an ipad I want to give my body a red border and on an iphone I want to give it a blue border. But nesting media queries like so doesn't work: </p> <pre><code>body { border: 1px solid green; } @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { @media (max-width: 768px) and (min-width: 320px) { body { border: 1px solid red; } } @media (max-width: 320px) { body { border: 1px solid blue; } } } </code></pre>
16,114,118
2
1
null
2013-04-19 21:48:09.507 UTC
3
2022-09-21 04:46:59.783 UTC
2013-04-24 00:36:52.96 UTC
user967451
null
user967451
null
null
1
30
css|responsive-design|media-queries|retina-display
21,517
<p>No. You need to use the <code>and</code> operator and write that as two queries. You can, however, do this in SCSS, which will compile to CSS, but it will combine them by unfolding them and using the <code>and</code> operator.</p> <p>This is a common problem, and once I first wrote LESS or SCSS, I didn't ever want to go back to writing this long-hand.</p> <p>Long-handed CSS:</p> <pre><code>@media (-webkit-min-device-pixel-ratio: 2) and (max-width: 768px) and (min-width: 320px), (min-resolution: 192dpi) and (max-width: 768px) and (min-width: 320px) { body { border: 1px solid red; } } @media (-webkit-min-device-pixel-ratio: 2) and (max-width: 320px), (min-resolution: 192dpi) and (max-width: 320px) { body { border: 1px solid blue; } } </code></pre> <p>Nesting queries may work, but support varies across browsers.</p>
16,266,809
Convert from latitude, longitude to x, y
<p>I want to convert GPS location (latitude, longitude) into x,y coordinates. I found many links about this topic and applied it, but it doesn't give me the correct answer!</p> <p>I am following these steps to test the answer: (1) firstly, i take two positions and calculate the distance between them using maps. (2) then convert the two positions into x,y coordinates. (3) then again calculate distance between the two points in the x,y coordinates and see if it give me the same result in point(1) or not.</p> <p>one of the solution i found the following, but it doesn't give me correct answer!</p> <pre><code>latitude = Math.PI * latitude / 180; longitude = Math.PI * longitude / 180; // adjust position by radians latitude -= 1.570795765134; // subtract 90 degrees (in radians) // and switch z and y xPos = (app.radius) * Math.sin(latitude) * Math.cos(longitude); zPos = (app.radius) * Math.sin(latitude) * Math.sin(longitude); yPos = (app.radius) * Math.cos(latitude); </code></pre> <p>also i tried this <a href="https://stackoverflow.com/a/1185413/2035790">link</a> but still not work with me well!</p> <p>any help how to convert from(latitude, longitude) to (x,y) ?</p> <p>Thanks,</p>
16,271,669
5
1
null
2013-04-28 19:23:48.867 UTC
13
2022-04-24 09:01:07.237 UTC
2020-05-28 14:28:21.227 UTC
null
767,664
null
2,035,790
null
1
44
gps|mapping|geometry
133,856
<h1>No exact solution exists</h1> <p>There is no isometric map from the sphere to the plane. When you convert lat/lon coordinates from the sphere to x/y coordinates in the plane, you cannot hope that all lengths will be preserved by this operation. You have to accept some kind of deformation. Many different map projections do exist, which can achieve different compromises between preservations of lengths, angles and areas. For smallish parts of earth's surface, <a href="http://en.wikipedia.org/wiki/Transverse_Mercator_projection">transverse Mercator</a> is quite common. You might have heard about <a href="http://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system">UTM</a>. But there are <a href="http://en.wikipedia.org/wiki/List_of_map_projections">many more</a>.</p> <p>The formulas you quote compute x/y/z, i.e. a point in 3D space. But even there you'd not get correct distances automatically. The shortest distance between two points on the surface of the sphere would go through that sphere, whereas distances on the earth are mostly geodesic lengths following the surface. So they will be longer.</p> <h1>Approximation for small areas</h1> <p>If the part of the surface of the earth which you want to draw is relatively small, then you can use a very simple approximation. You can simply use the horizontal axis <em>x</em> to denote longitude λ, the vertical axis <em>y</em> to denote latitude φ. The ratio between these should not be 1:1, though. Instead you should use cos(φ<sub>0</sub>) as the aspect ratio, where φ<sub>0</sub> denotes a latitude close to the center of your map. Furthermore, to convert from angles (measured in radians) to lengths, you multiply by the radius of the earth (which in this model is assumed to be a sphere).</p> <ul> <li><em>x</em> = <em>r</em> λ cos(φ<sub>0</sub>)</li> <li><em>y</em> = <em>r</em> φ</li> </ul> <p>This is simple <a href="http://en.wikipedia.org/wiki/Equirectangular_projection">equirectangular projection</a>. In most cases, you'll be able to compute cos(φ<sub>0</sub>) only once, which makes subsequent computations of large numbers of points really cheap.</p>
16,413,373
git get short hash from regular hash
<p>I have a regular long SHA-1 hash string. I would like to get the shortest unambiguous SHA-1 hash string version of it. That is, the one I would get by using <code>git log -1 --pretty=format:%h</code>, assuming the long hash refers to the last commit.</p>
16,414,158
2
1
null
2013-05-07 07:19:08.237 UTC
9
2018-07-15 09:18:48.987 UTC
2013-05-07 07:20:21.157 UTC
null
31,671
null
1,773,706
null
1
63
git|github
53,156
<p>The shortest SHA1 you can get has a length of 4. Rev parse will give you a SHA1 of 7 digits by default with the <a href="https://git-scm.com/docs/git-rev-parse#git-rev-parse---shortlength" rel="noreferrer">short</a> option :</p> <pre><code>git rev-parse --short 921103db8259eb9de72f42db8b939895f5651489 921103d </code></pre> <p>You have to specify 4 to the short option to have the shortest unambiguous SHA1 :</p> <pre><code>git rev-parse --short=4 921103db8259eb9de72f42db8b939895f5651489 92110 </code></pre> <p>You can also set it in the <a href="https://git-scm.com/docs/git-config#git-config-coreabbrev" rel="noreferrer"><code>core.abbrev</code></a> configuration variable.</p>
55,194,118
How do I parse a string to number while destructuring?
<p>I am trying to experiment around destructuring assignment. Now I have a case which I trying to cop up with destructuring itself.</p> <p>For example, I have an input like this:</p> <pre><code>let input = {latitude: "17.0009", longitude: "82.2108"} </code></pre> <p>Where <code>latitude</code> and <code>longitude</code> key values are strings, but I want to parse them into a number while destructuring.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let input = {latitude: "17.0009", longitude: "82.2108"} let {latitude,longitude} = input console.log(typeof latitude,typeof longitude)</code></pre> </div> </div> </p> <p>I can see in <a href="https://babeljs.io/repl/#?babili=false&amp;browsers=&amp;build=&amp;builtIns=false&amp;spec=false&amp;loose=false&amp;code_lz=DYUwLgBAhgTjEF4IG9hTASzAVwCYgC4IAiARgHYA6ABloE5iAaCYAewDsBzLPQkgDgBMlQaWr9iAXwBQ00JFToe-Rmy7KQkxNDiygA&amp;debug=false&amp;forceAllTransforms=false&amp;shippedProposals=false&amp;circleciRepo=&amp;evaluate=true&amp;fileSize=false&amp;timeTravel=false&amp;sourceType=module&amp;lineWrap=true&amp;presets=es2015%2Creact%2Cstage-2&amp;prettier=false&amp;targets=&amp;version=7.3.4" rel="noreferrer"><strong>babel repl</strong></a> that this takes a reference of an object and then access each key. So the above code is the same as:</p> <pre><code>"use strict"; var arr = { latitude: "17.0009", longitude: "82.2108" }; var latitude = arr.latitude, longitude = arr.longitude; </code></pre> <p>I want do something like using the destructuring syntax itself.</p> <pre><code>"use strict"; var arr = { latitude: "17.0009", longitude: "82.2108" }; var latitude = Number(arr.latitude), longitude = Number(arr.longitude); </code></pre> <p>I am open to see some hacks too.</p> <p><strong>Update</strong></p> <p>I am able to come with up one hack with the <code>,</code> operator:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = {latitude: "17.0009", longitude: "82.2108"} let {lat,lng} = ({latitude,longitude} = arr, ({lat:+latitude,lng:+longitude})) console.log(typeof lat, typeof lng)</code></pre> </div> </div> </p> <p><strong><em>On side note:-</em></strong> you must read <a href="https://stackoverflow.com/a/55197490/9624435"> Moritz Roessler's answer</a> this is hacky but contains good knowledge and information</p>
55,194,704
8
7
null
2019-03-16 06:35:57.437 UTC
8
2020-06-09 00:24:42.97 UTC
2019-03-18 17:11:11.933 UTC
null
9,624,435
null
9,624,435
null
1
35
javascript|ecmascript-6|destructuring
10,438
<p>Destructuring is just a nice way to unpack properties from objects and arrays and assign them to variables. As the trasnpiled code in the question suggests, any kind of operation is not possible.</p> <p>One <em>hack</em> would be to create 2 more variables (which don't exist in <code>input</code>) and set the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Default_values" rel="noreferrer">default value</a> to the number equivalent of the previously destrucutred properties:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let input = { latitude: "17.0009", longitude: "82.2108" } let { latitude, longitude, lat = +latitude, long = +longitude } = input console.log(typeof latitude, typeof longitude, typeof lat, typeof long)</code></pre> </div> </div> </p> <p>The code <em>approximately</em> trasnpliles to this (<a href="https://babeljs.io/repl#?babili=false&amp;browsers=&amp;build=&amp;builtIns=false&amp;spec=false&amp;loose=false&amp;code_lz=AQ4GwUwF2BLA7ADgVxgXmAb3AQyrKZAEwgC5gAiARgHYA6ABiYE4KAacAe3gHMDiylABwAmOiKoMhFYAF8AUKHDQsufIRIcw3Phoha8wDAGowefpq68jwUzosQ5NhCihA&amp;debug=false&amp;forceAllTransforms=false&amp;shippedProposals=false&amp;circleciRepo=&amp;evaluate=false&amp;fileSize=false&amp;timeTravel=false&amp;sourceType=module&amp;lineWrap=false&amp;presets=env&amp;prettier=false&amp;targets=&amp;version=7.3.4" rel="noreferrer">Babel</a>):</p> <pre><code>var latitude = input.latitude, longitude = input.longitude, lat = input.lat === undefined ? +latitude : input.lat, long = input.long === undefined ? +longitude : input.long; </code></pre> <p>It's just exploiting the order in which the variables are created and assigned property values. Again, this works only if there are no <code>lat</code> or <code>long</code> properties in <code>input</code>. Otherwise, it will fail the ternary condition and <code>lat</code> will be set to <code>input.lat</code>.</p> <hr> <p>Something like this would be much easier to read though:</p> <pre><code>let { latitude, longitude } = input; let lat = +latitude, long = +longitude; </code></pre> <p>OR</p> <pre><code>let [ lat, long ] = [ +latitude, +longitude ] </code></pre>
41,894,411
How to force CURL to ask for http/1.1? Or maybe there's another issue, not sure
<p>I've got a piece of code (let's name it Code A) working in a framework and I want to make it work in another framework. The working piece of code makes a successful POST request using CURL like this (request with CURLOPT_VERBOSE on):</p> <pre><code>* Connected to android.clients.google.com (216.58.209.238) port 443 (#0) * ALPN, offering http/1.1 * Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH * successfully set certificate verify locations: * CAfile: /Applications/MAMP/Library/OpenSSL/cert.pem CApath: none * SSL connection using TLSv1.2 / ECDHE-ECDSA-AES128-GCM-SHA256 * ALPN, server accepted to use http/1.1 * Server certificate: * subject: C=US; ST=California; L=Mountain View; O=Google Inc; CN=*.google.com * start date: Jan 18 19:17:59 2017 GMT * expire date: Apr 12 18:51:00 2017 GMT * subjectAltName: host "android.clients.google.com" matched cert's "android.clients.google.com" * issuer: C=US; O=Google Inc; CN=Google Internet Authority G2 * SSL certificate verify ok. &gt; POST /auth HTTP/1.1 Host: android.clients.google.com Accept: */* Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Content-Length: 97 </code></pre> <p>The http framework here (yii2/httpclient, to be specific) has too many dependencies to bring it to the other project so I'm trying to recreate it on low level like this (let's name it Code B):</p> <pre><code>&lt;?php $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, 'post-data-here'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, 'https://android.clients.google.com/auth'); curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded; charset=UTF-8"]); // just because I'm desperate curl_setopt($ch, CURLOPT_VERBOSE, true); $content = curl_exec($ch); </code></pre> <p>I'm expecting that to have the same result, but this is what I get:</p> <pre><code>* Connected to android.clients.google.com (216.58.209.238) port 443 (#0) * TLS 1.2 connection using TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 * Server certificate: *.google.com * Server certificate: Google Internet Authority G2 * Server certificate: GeoTrust Global CA &gt; POST /auth HTTP/1.1 Host: android.clients.google.com Accept: */* Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Content-Length: 97 * upload completely sent off: 97 out of 97 bytes &lt; HTTP/1.1 200 OK &lt; Content-Type: text/plain; charset=utf-8 &lt; Cache-Control: no-cache, no-store, max-age=0, must-revalidate &lt; Pragma: no-cache &lt; Expires: Mon, 01 Jan 1990 00:00:00 GMT &lt; Date: Fri, 27 Jan 2017 12:07:12 GMT &lt; X-Content-Type-Options: nosniff &lt; X-Frame-Options: SAMEORIGIN &lt; X-XSS-Protection: 1; mode=block &lt; Server: GSE &lt; Alt-Svc: clear &lt; Accept-Ranges: none &lt; Vary: Accept-Encoding &lt; Transfer-Encoding: chunked &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;HTTP Version Not Supported&lt;/TITLE&gt; &lt;/HEAD&gt; &lt;BODY BGCOLOR="#FFFFFF" TEXT="#000000"&gt; &lt;H1&gt;HTTP Version Not Supported&lt;/H1&gt; &lt;H2&gt;Error 505&lt;/H2&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>And instead of a valid response I get "Error 505: HTTP Version Not Supported". The only difference I see is that the working code tries to "ALPN, offering http/1.1" while the latter code doesn't do that. And the certificate part after that, but it's never ever mentioned in code A so I'm not sure what does it do to provide it.</p> <p>Both versions of code run on the same server, same version of PHP (5.6) and CURL (7.51.0). The difference in verbose log starts BEFORE any data being sent, so I guess it's not about any data or headers being set incorrectly.</p> <p>What I tried so far (with little or no effect):</p> <ol> <li>curl_setopt($ch, CURLOPT_SSL_ENABLE_ALPN, whatever) - does not work because CURLOPT_SSL_ENABLE_ALPN is not defined at all (although it must be in this version of CURL, not sure what's wrong)</li> <li>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, whatever)</li> <li>curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, whatever)</li> <li>curl_setopt($ch, CURLOPT_SSLVERSION, whatever)</li> <li>some other desperate silly stuff I'm even ashamed to show here</li> </ol> <p>I've tried to learn the working code as deep as I could but it seems that it doesn't do anything over the simple HTTP POST. I tracked every curl_setopt it makes and it seems there are only these curl_setopt I used in my code, nothing extra. Still, it works and my code doesn't.</p> <p>I've tried making the same using the command line:</p> <pre><code>$ curl https://android.clients.google.com/auth -v --http1.1 -X POST --no-alpn --no-npn --data "copypasted-post-data-from-code-B-and-yes-its-urlencoded" </code></pre> <p>Got the correct result:</p> <pre><code>* Trying 216.58.209.238... * TCP_NODELAY set * Connected to android.clients.google.com (216.58.209.238) port 443 (#0) * Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH * successfully set certificate verify locations: * CAfile: /Applications/MAMP/Library/OpenSSL/cert.pem CApath: none ... &gt; POST /auth HTTP/1.1 &gt; Host: android.clients.google.com &gt; User-Agent: curl/7.51.0 &gt; Accept: */* &gt; Content-Length: 97 &gt; Content-Type: application/x-www-form-urlencoded &gt; * upload completely sent off: 97 out of 97 bytes &lt; HTTP/1.1 200 OK &lt; Content-Type: text/plain; charset=utf-8 &lt; Cache-Control: no-cache, no-store, max-age=0, must-revalidate &lt; Pragma: no-cache &lt; Expires: Mon, 01 Jan 1990 00:00:00 GMT &lt; Date: Fri, 27 Jan 2017 13:22:27 GMT &lt; X-Content-Type-Options: nosniff &lt; X-Frame-Options: SAMEORIGIN &lt; X-XSS-Protection: 1; mode=block &lt; Server: GSE &lt; Alt-Svc: clear &lt; Accept-Ranges: none &lt; Vary: Accept-Encoding &lt; Transfer-Encoding: chunked &lt; SID=BAD_COOKIE LSID=BAD_COOKIE Auth=here-s-the-data-i-need </code></pre>
41,895,644
2
6
null
2017-01-27 12:51:47.64 UTC
2
2017-01-27 13:56:37.743 UTC
2017-01-27 13:30:26.607 UTC
null
222,173
null
222,173
null
1
36
php|ssl|curl
88,005
<p>Okay, I figured it out.</p> <p>Actually, BEFORE that piece of code in Code B there was another request executed using yet another library (Httpful, to be exact) and it seems that request messed things up somehow. I did not know that something can affect a request performed with a clean curl_init().</p> <p>Anyway, when I replaced all those Httpful calls prior to the request in question with low level ones, everything worked fine.</p>
58,065,603
Netlify renders 404 on page refresh (using React and react-router)
<p>I have deployed my site with Netlify, and I’m having trouble with the routing. </p> <p>Here is my website: <a href="https://redux-co.netlify.com/" rel="noreferrer">https://redux-co.netlify.com/</a></p> <p>And my GitHub repo: <a href="https://github.com/jenna-m/redux-co" rel="noreferrer">https://github.com/jenna-m/redux-co</a></p> <p>Specifically, if a user navigates to any page besides the home page and refreshes the page, the default Netlify 404 renders. From the 404 page, if I navigate back to the home page and refresh, the home page is rendered.</p> <p>Also, my custom 404 page isn’t working as it does when I’m on <code>localhost:3000</code>, but I would like to get this refresh issue figured out first before dealing with my custom 404 component.</p> <p>I’m using React and react-router, and I understand that since I’m using react-router, my website won’t deploy right out of the box.</p> <hr> <p>This is my <code>_redirects</code> file, which is in the <code>/public</code> folder with my <code>index.html</code> file:</p> <pre><code>/* /index.html 200 </code></pre> <p>This is my <code>“build”</code> located in <code>package.json</code>:</p> <pre><code>…   "scripts": {     "start": "react-scripts start",     "build": "react-scripts build &amp;&amp; cp build/index.html build/404.html",     "test": "react-scripts test",     "eject": "react-scripts eject"   } … </code></pre> <hr> <p>I have read about other people experiencing this and what they’ve done to overcome the problem. This is what I’ve referenced so far…</p> <p><a href="https://www.freecodecamp.org/news/how-to-deploy-a-react-application-to-netlify-363b8a98a985/" rel="noreferrer">https://www.freecodecamp.org/news/how-to-deploy-a-react-application-to-netlify-363b8a98a985/</a></p> <p><a href="https://hugogiraudel.com/2017/05/13/using-create-react-app-on-netlify/" rel="noreferrer">https://hugogiraudel.com/2017/05/13/using-create-react-app-on-netlify/</a></p> <p>This person was using Vue and not React, but I gave these solutions an attempt anyway:</p> <p><a href="https://github.com/vuejs/vuepress/issues/457#issuecomment-390206649" rel="noreferrer">https://github.com/vuejs/vuepress/issues/457#issuecomment-390206649</a></p> <p><a href="https://github.com/vuejs/vuepress/issues/457#issuecomment-463745656" rel="noreferrer">https://github.com/vuejs/vuepress/issues/457#issuecomment-463745656</a></p>
59,000,164
16
1
null
2019-09-23 15:23:47.193 UTC
20
2022-09-05 04:10:49.143 UTC
null
null
null
null
11,995,771
null
1
57
reactjs|react-router|http-status-code-404|netlify
35,955
<p><strong>This was simple and it worked for me</strong>. I found this link <a href="https://create-react-app.dev/docs/deployment#netlify" rel="noreferrer">https://create-react-app.dev/docs/deployment#netlify</a></p> <p>So as suggested by that link, I added a <code>_redirects</code> file inside the <code>/public</code> folder like <code>/public/_redirects</code>. I then pasted <code>/* /index.html 200</code> into the <code>_redirects</code> file. I did all that in my VS Code, after which I pushed to github and then ofcourse my netlify re-deploys automatically everytime I push to github. My problem was solved and <strong>refresh nolonger brings the 404 error.</strong></p> <p>In my package.json, the build section looks like this;</p> <pre><code>"scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" } </code></pre> <p><strong>Note:</strong> Some articles say that you need to add <code>_redirects</code> in the <code>build</code> folder, but then build folder is not among what gets pushed to github in my case, so that's why adding <code>_redirects</code> to <code>public</code> folder worked better for me, as the public folder can be pushed along with my code.</p>
22,419,958
What is the difference between Big Data and Data Mining?
<p>As Wikpedia states </p> <blockquote> <p>The overall goal of the data mining process is to extract information from a data set and transform it into an understandable structure for further use</p> </blockquote> <p>How is this related with Big Data? Is it correct if I say that Hadoop is doing data mining in a parallel manner? </p>
22,421,731
6
2
null
2014-03-15 05:25:46.203 UTC
14
2018-07-15 19:27:54.2 UTC
2016-12-27 14:55:56.423 UTC
null
4,373,584
null
2,285,855
null
1
24
hadoop|machine-learning|bigdata|data-mining|data-science
29,803
<h2>Big data is everything</h2> <p>Big data is a <em>marketing</em> term, not a technical term. Everything is big data these days. My USB stick is a "personal cloud" now, and my harddrive is big data. Seriously. This is a totally unspecific term that is largely defined by what the marketing departments of various very optimistic companies can sell - and the C*Os of major companies buy, in order to make magic happen. Update: and by now, the same applies to <strong>data science</strong>. It's just marketing.</p> <h2>Data mining is the old big data</h2> <p>Actually, data mining was just as overused... it could mean anything such as </p> <ul> <li>collecting data (think NSA)</li> <li>storing data</li> <li>machine learning / AI (which predates the term data mining)</li> <li><strong>non-ML data mining</strong> (as in "knowledge discovery", where the term data mining was actually coined; but where the focus is on new knowledge, not on learning of existing knowledge)</li> <li>business rules and analytics</li> <li>visualization</li> <li>anything involving data you want to sell for truckloads of money</li> </ul> <p>It's just that marketing needed a new term. "Business intelligence", "business analytics", ... they <strong>still keep on selling the same stuff</strong>, it's just rebranded as "big data" now.</p> <h2>Most "big" data mining isn't big</h2> <p>Since most methods - at least those that give interesting results - just don't scale, most data "mined" isn't actually big. It's clearly much bigger than 10 years ago, but not big as in Exabytes. A survey by KDnuggets had something like 1-10 GB being the average "largest data set analyzed". That is not big data by any data management means; it's only large by what can be analyzed using <em>complex</em> methods. (I'm not talking about trivial algorithms such a k-means).</p> <h2>Most "big data" isn't data mining</h2> <p>Now "Big data" is real. Google has Big data, and CERN also has big data. Most others probably don't. Data starts being big, when you need 1000 computers just to <em>store</em> it.</p> <p>Big data technologies such as Hadoop are also real. They aren't always used sensibly (don't bother to run hadoop clusters less than 100 nodes - as this point you probably can get much better performance from well-chosen non-clustered machines), but of course people write such software.</p> <p>But most of what is being done isn't data mining. It's <a href="https://en.wikipedia.org/wiki/Extract,_transform,_load" rel="nofollow noreferrer">Extract, Transform, Load (ETL)</a>, so it is replacing data warehousing. Instead of using a database with structure, indexes and accelerated queries, the data is just dumped into hadoop, and when you have figured out what to do, you re-read all your data and extract the information you really need, tranform it, and load it into your excel spreadsheet. Because after selection, extraction and transformation, usually it's not "big" anymore.</p> <h2>Data quality suffers with size</h2> <p>Many of the marketing promises of big data will not hold. Twitter produces much less insights for most companies than advertised (unless you are a teenie rockstar, that is); and the Twitter user base is <em>heavily biased</em>. Correcting for such a bias is hard, and needs highly experienced statisticians.</p> <p>Bias from data is one problem - if you just collect some random data from the internet or an appliction, it will usually be not representative; in particular not of potential users. Instead, you will be overfittig to the existing heavy-users if you don't manage to cancel out these effects.</p> <p>The other big problem is just noise. You have spam bots, but also other tools (think Twitter "trending topics" that cause reinforcement of "trends") that make the data much noiser than other sources. Cleaning this data is <em>hard</em>, and not a matter of technology but of statistical domain expertise. For example <strong>Google Flu Trends</strong> was repeatedly found to be rather inaccurate. It worked in some of the earlier years (maybe because of overfitting?) but is not anymore of good quality.</p> <p>Unfortunately, a lot of big data users pay too little attention to this; which is probably one of the many reasons why most big data projects seem to fail (the others being incompetent management, inflated and unrealistic expectations, and lack of company culture and skilled people).</p> <h2>Hadoop != data mining</h2> <p>Now for the second part of your question. Hadoop doesn't do data mining. Hadoop manages data storage (via HDFS, a very primitive kind of distributed database) and it schedules computation tasks, allowing you to run the computation on the same machines that store the data. It does <em>not</em> do any complex analysis.</p> <p>There are some tools that try to bring data mining to Hadoop. In particular, <strong>Apache Mahout can be called the official Apache attempt to do data mining on Hadoop</strong>. Except that it is mostly a machine learning tool (machine learning != data mining; data mining sometimes uses methods from machine learning). Some parts of Mahout (such as clustering) are far from advanced. The problem is that <strong>Hadoop is good for linear problems, but most data mining isn't linear</strong>. And non-linear algorithms don't just scale up to large data; you need to carefully develop linear-time approximations and live with losses in accuracy - losses that must be smaller than what you would lose by simply working on smaller data.</p> <p>A good example of this trade-off problem is k-means. K-means actually is a (mostly) linear problem; so it can be somewhat run on Hadoop. A single iteration is linear, and if you had a good implementation, it would scale well to big data. However, the number of iterations until convergence also grows with data set size, and thus it isn't really linear. However, as this is a statistical method to find "means", the results actually do not improve much with data set size. So while you can run k-means on big data, it does not make a whole lot of sense - you could just take a sample of your data, run a highly-efficient single-node version of k-means, and the results will be just as good. Because the extra data just gives you some extra digits of precision of a value that you do not need to be that precise.</p> <p>Since this applies to quite a lot of problems, actual data mining on Hadoop doesn't seem to kick off. Everybody tries to do it, and a lot of companies sell this stuff. But it doesn't really work much better than the non-big version. But as long as customers want to buy this, companies will sell this functionality. And as long as it gets you a grant, researchers will write papers on this. Whether it works or not. That's life.</p> <p>There are a few cases where these things work. Google search is an example, and Cern. But also image recognition (but not using Hadoop, clusters of GPUs seem to be the way to go there) has recently benefited from an increase in data size. But in any of these cases, you have rather clean data. Google indexes everything; Cern discards any non-interesting data, and only analyzes interesting measurements - there are no spammers feeding their spam into Cern... and in image analysis, you train on preselected relevant images, not on say webcams or random images from the internet (and if so, you treat them as random images, not as representative data).</p>
21,639,305
D3js take data from an array instead of a file
<p>I have found this excellent d3js chart <a href="http://bl.ocks.org/Caged/6476579" rel="noreferrer">here</a>. However in my case I want this chart to take value from an array instead of a tsv file. I want to make it to take values from a table []. How I can do that? because it uses a function for that, and I do not know where I should put my array.</p> <pre><code>Using d3-tip to add tooltips to a d3 bar chart. &lt;!DOCTYPE html&gt; &lt;meta charset="utf-8"&gt; &lt;style&gt; body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .bar { fill: orange; } .bar:hover { fill: orangered ; } .x.axis path { display: none; } .d3-tip { line-height: 1; font-weight: bold; padding: 12px; background: rgba(0, 0, 0, 0.8); color: #fff; border-radius: 2px; } /* Creates a small triangle extender for the tooltip */ .d3-tip:after { box-sizing: border-box; display: inline; font-size: 10px; width: 100%; line-height: 1; color: rgba(0, 0, 0, 0.8); content: "\25BC"; position: absolute; text-align: center; } /* Style northward tooltips differently */ .d3-tip.n:after { margin: -1px 0 0 0; top: 100%; left: 0; } &lt;/style&gt; &lt;body&gt; &lt;script src="http://d3js.org/d3.v3.min.js"&gt;&lt;/script&gt; &lt;script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"&gt;&lt;/script&gt; &lt;script&gt; var margin = {top: 40, right: 20, bottom: 30, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var formatPercent = d3.format(".0%"); var x = d3.scale.ordinal() .rangeRoundBands([0, width], .1); var y = d3.scale.linear() .range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left") .tickFormat(formatPercent); var tip = d3.tip() .attr('class', 'd3-tip') .offset([-10, 0]) .html(function(d) { return "&lt;strong&gt;Frequency:&lt;/strong&gt; &lt;span style='color:red'&gt;" + d.frequency + "&lt;/span&gt;"; }) var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); svg.call(tip); d3.tsv("data.tsv", type, function(error, data) { x.domain(data.map(function(d) { return d.letter; })); y.domain([0, d3.max(data, function(d) { return d.frequency; })]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Frequency"); svg.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.letter); }) .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.frequency); }) .attr("height", function(d) { return height - y(d.frequency); }) .on('mouseover', tip.show) .on('mouseout', tip.hide) }); function type(d) { d.frequency = +d.frequency; return d; } &lt;/script&gt; </code></pre> <p>Thanks a lot</p>
21,668,952
2
3
null
2014-02-07 22:57:25.367 UTC
16
2019-02-19 16:14:21.417 UTC
2014-02-07 23:28:14.697 UTC
null
2,824,542
null
2,824,542
null
1
49
javascript|html|svg|d3.js
46,332
<p>The <a href="https://github.com/mbostock/d3/wiki/Gallery" rel="noreferrer">D3 gallery</a> has a lot of good examples, but a lot of the examples loads their data from a <a href="http://en.wikipedia.org/wiki/Tab-separated_values" rel="noreferrer">tab-separated values file</a>. This is a nice way to separate data and visualization in short examples, but it can be a bit confusing if you are new to D3 and JavaScript, since it requires some basic knowledge about both d3.tsv() and callback functions to understand what is going on.</p> <p><em>Disclaimer: The following sections will give some very simplified explanations.</em></p> <h2>What is d3.tsv() doing?</h2> <p>d3.tsv() is basically responsible for loading the data from data.tsv, parse it into a variable called data, and send this variable to a <a href="http://en.wikipedia.org/wiki/Callback_(computer_programming)#JavaScript" rel="noreferrer">callback function</a>.</p> <pre><code>d3.tsv("data.tsv", type, function(error, data) { &lt;- This is the callback function! // This code is executed when the data.tsv file is loaded. }); </code></pre> <p>As soon as the data is loaded, it is sent as the data argument to the function. Then the code inside the callback function is executed. Since we don't need the callback function for anything else than as an argument to the d3.tsv() function, we make it directly as an <a href="http://en.wikipedia.org/wiki/Anonymous_function" rel="noreferrer">anonymous function</a>, instead of giving it a name like usual.</p> <p>This kind of use of callback and anonymous functions is very typical of JavaScript, and is well worth reading up on. <a href="http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/" rel="noreferrer">Understand JavaScript Callback Functions and Use Them</a> and <a href="http://cwbuecheler.com/web/tutorials/2013/javascript-callbacks/" rel="noreferrer">Understanding JavaScript Callbacks</a> should get you started.</p> <p>Let's see how we can use this information to rewrite our code.</p> <h2>How can I rewrite the example to use data from a local variable?</h2> <p>First we have to make variable containing our data. Let's call it "data", the same as in our callback function, and give it the values from the example.</p> <pre><code>var data = [ {letter: "A", frequency: .08167}, {letter: "B", frequency: .01492}, {letter: "C", frequency: .02780}, {letter: "D", frequency: .04253}, {letter: "E", frequency: .12702}, {letter: "F", frequency: .02288}, {letter: "G", frequency: .02022}, {letter: "H", frequency: .06094}, {letter: "I", frequency: .06973}, {letter: "J", frequency: .00153}, {letter: "K", frequency: .00747}, {letter: "L", frequency: .04025}, {letter: "M", frequency: .02517}, {letter: "N", frequency: .06749}, {letter: "O", frequency: .07507}, {letter: "P", frequency: .01929}, {letter: "Q", frequency: .00098}, {letter: "R", frequency: .05987}, {letter: "S", frequency: .06333}, {letter: "T", frequency: .09056}, {letter: "U", frequency: .02758}, {letter: "V", frequency: .01037}, {letter: "W", frequency: .02465}, {letter: "X", frequency: .00150}, {letter: "Y", frequency: .01971}, {letter: "Z", frequency: .00074} ]; </code></pre> <p>Put this variable somewhere before the call to d3.tsv, as the code in the callback function is dependent on this variable. </p> <p>I have choose to represent the data as a list of objects with a letter and frequency property. This is an easy way to do it, since it closely resembles the way d3.tsv() would parse the .tsv file. This means that we don't have to change the code in the callback function, since it already expects a variable with data in this format. You can change this if you like, but remember to change how the callback code uses the "data" variable.</p> <p>Now we can remove the code related to the d3.tsv call, just leaving the code contained in the callback function. So this code:</p> <pre><code>d3.tsv("data.tsv", type, function(error, data) { x.domain(data.map(function(d) { return d.letter; })); // code omitted. .on('mouseout', tip.hide) }); </code></pre> <p>Becomes this code:</p> <pre><code>x.domain(data.map(function(d) { return d.letter; })); // code omitted. .on('mouseout', tip.hide) </code></pre> <p>Now the example should be working fine. You can play around with this strategy for rewriting other examples in the D3 gallery as well.</p> <p>Finally, I have included the code for the new index.html file. A working example can be found at <a href="http://jsfiddle.net/59vLw/" rel="noreferrer">JSFiddle</a>.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;meta charset="utf-8"&gt; &lt;style&gt; body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .bar { fill: orange; } .bar:hover { fill: orangered ; } .x.axis path { display: none; } .d3-tip { line-height: 1; font-weight: bold; padding: 12px; background: rgba(0, 0, 0, 0.8); color: #fff; border-radius: 2px; } /* Creates a small triangle extender for the tooltip */ .d3-tip:after { box-sizing: border-box; display: inline; font-size: 10px; width: 100%; line-height: 1; color: rgba(0, 0, 0, 0.8); content: "\25BC"; position: absolute; text-align: center; } /* Style northward tooltips differently */ .d3-tip.n:after { margin: -1px 0 0 0; top: 100%; left: 0; } &lt;/style&gt; &lt;body&gt; &lt;script src="http://d3js.org/d3.v3.min.js"&gt;&lt;/script&gt; &lt;script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"&gt;&lt;/script&gt; &lt;script&gt; var margin = {top: 40, right: 20, bottom: 30, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var formatPercent = d3.format(".0%"); var x = d3.scale.ordinal() .rangeRoundBands([0, width], .1); var y = d3.scale.linear() .range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left") .tickFormat(formatPercent); var tip = d3.tip() .attr('class', 'd3-tip') .offset([-10, 0]) .html(function(d) { return "&lt;strong&gt;Frequency:&lt;/strong&gt; &lt;span style='color:red'&gt;" + d.frequency + "&lt;/span&gt;"; }) var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); svg.call(tip); // The new data variable. var data = [ {letter: "A", frequency: .08167}, {letter: "B", frequency: .01492}, {letter: "C", frequency: .02780}, {letter: "D", frequency: .04253}, {letter: "E", frequency: .12702}, {letter: "F", frequency: .02288}, {letter: "G", frequency: .02022}, {letter: "H", frequency: .06094}, {letter: "I", frequency: .06973}, {letter: "J", frequency: .00153}, {letter: "K", frequency: .00747}, {letter: "L", frequency: .04025}, {letter: "M", frequency: .02517}, {letter: "N", frequency: .06749}, {letter: "O", frequency: .07507}, {letter: "P", frequency: .01929}, {letter: "Q", frequency: .00098}, {letter: "R", frequency: .05987}, {letter: "S", frequency: .06333}, {letter: "T", frequency: .09056}, {letter: "U", frequency: .02758}, {letter: "V", frequency: .01037}, {letter: "W", frequency: .02465}, {letter: "X", frequency: .00150}, {letter: "Y", frequency: .01971}, {letter: "Z", frequency: .00074} ]; // The following code was contained in the callback function. x.domain(data.map(function(d) { return d.letter; })); y.domain([0, d3.max(data, function(d) { return d.frequency; })]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Frequency"); svg.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.letter); }) .attr("width", x.rangeBand()) .attr("y", function(d) { return y(d.frequency); }) .attr("height", function(d) { return height - y(d.frequency); }) .on('mouseover', tip.show) .on('mouseout', tip.hide) function type(d) { d.frequency = +d.frequency; return d; } &lt;/script&gt; </code></pre>
21,455,045
AngularJS $http, CORS and http authentication
<p>Because using CORS and http authentication with AngularJS can be tricky I edited the question to share one learned lesson. First I want to thank igorzg. His answer helped me a lot. The scenario is the following: You want to send POST request to a different domain with AngularJS $http service. There are several tricky things to be aware of when getting AngularJS and the server setup. </p> <p>First: In your application config you must allow cross domain call</p> <pre><code>/** * Cors usage example. * @author Georgi Naumov * [email protected] for contacts and * suggestions. **/ app.config(function($httpProvider) { //Enable cross domain calls $httpProvider.defaults.useXDomain = true; }); </code></pre> <p>Second: You must specify withCredentials: true and username and password into request. </p> <pre><code> /** * Cors usage example. * @author Georgi Naumov * [email protected] for contacts and * suggestions. **/ $http({ url: 'url of remote service', method: "POST", data: JSON.stringify(requestData), withCredentials: true, headers: { 'Authorization': 'Basic bashe64usename:password' } }); </code></pre> <p>Тhird: Server setup. You must provide:</p> <pre><code>/** * Cors usage example. * @author Georgi Naumov * [email protected] for contacts and * suggestions. **/ header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Origin: http://url.com:8080"); header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); </code></pre> <p>For every request. When you receive OPTION you must pass:</p> <pre><code>/** * Cors usage example. * @author Georgi Naumov * [email protected] for contacts and * suggestions. **/ if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { header( "HTTP/1.1 200 OK" ); exit(); } </code></pre> <p>HTTP authentication and everything else comes after that.</p> <p>Here is complete example of usage of server side with php. </p> <pre><code>&lt;?php /** * Cors usage example. * @author Georgi Naumov * [email protected] for contacts and * suggestions. **/ header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Origin: http://url:8080"); header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization"); if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { header( "HTTP/1.1 200 OK" ); exit(); } $realm = 'Restricted area'; $password = 'somepassword'; $users = array('someusername' =&gt; $password); if (isset($_SERVER['PHP_AUTH_USER']) == false || isset($_SERVER['PHP_AUTH_PW']) == false) { header('WWW-Authenticate: Basic realm="My Realm"'); die('Not authorised'); } if (isset($users[$_SERVER['PHP_AUTH_USER']]) &amp;&amp; $users[$_SERVER['PHP_AUTH_USER']] == $password) { header( "HTTP/1.1 200 OK" ); echo 'You are logged in!' ; exit(); } ?&gt; </code></pre> <p>There is an article on my blog about this issue which can be seen <a href="http://georgi-naumov.blogspot.com/2014/02/angularjs-http-cors-and-http.html">here</a>.</p>
21,455,819
2
5
null
2014-01-30 11:21:44.99 UTC
49
2017-09-07 13:30:46.327 UTC
2015-09-11 03:51:36.493 UTC
null
2,503,750
null
907,047
null
1
87
angularjs|cors
142,153
<p>No you don't have to put credentials, You have to put headers on client side eg:</p> <pre><code> $http({ url: 'url of service', method: "POST", data: {test : name }, withCredentials: true, headers: { 'Content-Type': 'application/json; charset=utf-8' } }); </code></pre> <p>And and on server side you have to put headers to this is example for nodejs:</p> <pre><code>/** * On all requests add headers */ app.all('*', function(req, res,next) { /** * Response settings * @type {Object} */ var responseSettings = { "AccessControlAllowOrigin": req.headers.origin, "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name", "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS", "AccessControlAllowCredentials": true }; /** * Headers */ res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials); res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin); res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with"); res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods); if ('OPTIONS' == req.method) { res.send(200); } else { next(); } }); </code></pre>
21,490,860
Relative imports with unittest in Python
<p>I am trying to use Python unittest and relative imports, and I can't seem to figure it out. I know there are a lot of related questions, but none of them have helped so far. Sorry if this is repetitive, but I would really appreciate any help. I was trying to use the syntax from PEP 328 <a href="http://www.python.org/dev/peps/pep-0328/" rel="noreferrer">http://www.python.org/dev/peps/pep-0328/</a> but I must have something wrong. </p> <p>My directory structure is:</p> <pre><code>project/ __init__.py main_program.py lib/ __init__.py lib_a lib_b tests/ __init__.py test_a test_b </code></pre> <p>I run my tests using:</p> <pre><code>python -m unittest test_module1 test_module2 </code></pre> <p>test_a needs to import both lib/lib_a and main_program. This is the code from test_a I am trying to use for the import:</p> <pre><code>from ..lib import lib_a as lib from ...project import main_program </code></pre> <p>both raise this error:</p> <pre><code>ValueError: Attempted relative import in non-package </code></pre> <p>All of my <strong>init</strong>.py files are currently empty. </p> <p>Any specific advice would be greatly appreciated!!</p> <p>Edit:</p> <p>This may be the answer: <a href="https://stackoverflow.com/questions/1342975/python-packages">Python Packages?</a> I'm still verifying if this will work. </p> <p>Edit II:</p> <p>To clarify, at this point I have attempted to run my test file in 3 different ways:</p> <pre><code>project/tests $ python -m unittest test_a project/tests $ python -m test_a project/tests $ ./test_a </code></pre> <p>All three fail with the same error as above. When I use the same three syntaxes but in the project directory, I get this error:</p> <pre><code>ValueError: Attempted relative import beyond toplevel package </code></pre> <p>Thanks again. </p>
22,149,759
3
8
null
2014-01-31 21:59:25.24 UTC
4
2020-04-06 05:51:23.223 UTC
2017-05-23 12:17:58.683 UTC
null
-1
null
1,945,087
null
1
42
python|python-import|python-unittest
22,250
<p>In my experience it is easiest if your project root is not a package, like so:</p> <pre><code>project/ test.py run.py package/ __init__.py main_program.py lib/ __init__.py lib_a lib_b tests/ __init__.py test_a test_b </code></pre> <p>However, as of python 3.2 , the unittest module provides the <code>-t</code> option, which lets you set the top level directory, so you could do (from <code>package/</code>):</p> <pre><code>python -m unittest discover -t .. </code></pre> <p>More details at the <a href="http://docs.python.org/3/library/unittest.html#test-discovery" rel="noreferrer">unittest docs</a>.</p>
17,157,272
Is there a way to set a default parameter equal to another parameter value?
<p>For example, I have a basic method that will return a list of permutations.</p> <pre><code>import itertools def perms(elements, set_length=elements): data=[] for x in range(elements): data.append(x+1) return list(itertools.permutations(data, set_length)) </code></pre> <p>Now I understand, that in its current state this code won't run because the second <code>elements</code> isn't defined, but is there and elegant way to accomplish what I'm trying to do here? If that's still not clear, I want to make the default <code>setLength</code> value equal to the first argument passed in. Thanks.</p>
17,157,303
4
1
null
2013-06-17 21:36:00.863 UTC
5
2019-04-16 13:37:26.29 UTC
2019-04-16 13:37:26.29 UTC
null
42,973
null
2,007,537
null
1
47
python|python-3.x
16,582
<p>No, function keyword parameter defaults are determined when the function is <em>defined</em>, not when the function is executed.</p> <p>Set the default to <code>None</code> and detect that:</p> <pre><code>def perms(elements, setLength=None): if setLength is None: setLength = elements </code></pre> <p>If you need to be able to specify <code>None</code> as a argument, use a different sentinel value:</p> <pre><code>_sentinel = object() def perms(elements, setLength=_sentinel): if setLength is _sentinel: setLength = elements </code></pre> <p>Now callers can set <code>setLength</code> to <code>None</code> and it won't be seen as the default.</p>
18,504,967
pandas dataframe create new columns and fill with calculated values from same df
<p>Here is a simplified example of my df:</p> <pre><code>ds = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D']) ds A B C D 1 1.099679 0.042043 0.083903 0.410128 2 0.268205 0.718933 1.459374 0.758887 3 0.680566 0.538655 0.038236 1.169403 </code></pre> <p>I would like to sum the data in the columns row wise:</p> <pre><code>ds['sum']=ds.sum(axis=1) ds A B C D sum 1 0.095389 0.556978 1.646888 1.959295 4.258550 2 1.076190 2.668270 0.825116 1.477040 6.046616 3 0.245034 1.066285 0.967124 0.791606 3.070049 </code></pre> <p>Now, here comes my question! I would like to create 4 new columns and calculate the percentage value from the total (sum) in every row. So first value in the first new column should be (0.095389/4.258550), first value in the second new column (0.556978/4.258550)...and so on... Help please </p>
18,505,101
2
0
null
2013-08-29 07:40:53.39 UTC
15
2013-08-29 08:03:58.96 UTC
null
null
null
null
2,219,369
null
1
43
python|pandas|calculated-columns
122,844
<p>You can do this easily manually for each column like this:</p> <pre><code>df['A_perc'] = df['A']/df['sum'] </code></pre> <hr> <p>If you want to do this in one step for all columns, you can use the <code>div</code> method (<a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior">http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior</a>):</p> <pre><code>ds.div(ds['sum'], axis=0) </code></pre> <p>And if you want this in one step added to the same dataframe:</p> <pre><code>&gt;&gt;&gt; ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc') A B C D sum A_perc B_perc \ 1 0.151722 0.935917 1.033526 0.941962 3.063127 0.049532 0.305543 2 0.033761 1.087302 1.110695 1.401260 3.633017 0.009293 0.299283 3 0.761368 0.484268 0.026837 1.276130 2.548603 0.298739 0.190013 C_perc D_perc sum_perc 1 0.337409 0.307517 1 2 0.305722 0.385701 1 3 0.010530 0.500718 1 </code></pre>
18,664,579
Recommended way to save uploaded files in a servlet application
<p>I read <a href="https://stackoverflow.com/a/2663855/281545">here</a> that one should not save the file in the server anyway as it is not portable, transactional and requires external parameters. However, given that I need a tmp solution for tomcat (7) and that I have (relative) control over the server machine I want to know :</p> <ul> <li><p>What is the best place to save the file ? Should I save it in <code>/WEB-INF/uploads</code> (advised against <a href="https://stackoverflow.com/a/13617442/281545">here</a>) or someplace under <code>$CATALINA_BASE</code> (see <a href="https://stackoverflow.com/a/1047581/281545">here</a>) or ... ? The JavaEE 6 tutorial <a href="http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html#gmhbq" rel="noreferrer">gets the path from the user</a> (:wtf:). NB : The file should not be downloadable by any means.</p></li> <li><p>Should I set up a config parameter as detailed <a href="https://stackoverflow.com/a/2663250/281545">here</a> ? I'd appreciate some code (I'd rather give it a relative path - so it is at least Tomcat portable) - <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/Part.html#write%28java.lang.String%29" rel="noreferrer"><code>Part.write()</code></a> looks promising - but apparently needs a absolute path</p></li> <li><p>I'd be interested in an exposition of the disadvantages of this approach vs a database/JCR repository one</p></li> </ul> <p>Unfortunately the <a href="http://balusc.blogspot.gr/2009/02/fileservlet-supporting-resume-and.html" rel="noreferrer">FileServlet</a> by @BalusC concentrates on downloading files, while his <a href="https://stackoverflow.com/a/2424824/281545">answer</a> on uploading files skips the part on where to save the file.</p> <p>A solution easily convertible to use a DB or a JCR implementation (like <a href="http://jackrabbit.apache.org/frequently-asked-questions.html" rel="noreferrer">jackrabbit</a>) would be preferable.</p>
18,664,715
2
1
null
2013-09-06 18:49:20.23 UTC
112
2021-04-13 11:34:36.777 UTC
2017-05-23 12:02:50.28 UTC
null
-1
null
281,545
null
1
125
tomcat|servlets|file-upload|servlet-3.0
149,989
<p>Store it anywhere in an accessible location <strong>except</strong> of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to <a href="https://stackoverflow.com/questions/8885201/uploaded-image-only-available-after-refreshing-the-page">Uploaded image only available after refreshing the page</a>:</p> <blockquote> <ol> <li><p>Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called &quot;publishing&quot;). This is the main cause of the problem you're seeing.</p> </li> <li><p>In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.</p> </li> <li><p>Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.</p> </li> </ol> </blockquote> <p>It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you <a href="https://stackoverflow.com/questions/12160639/what-does-servletcontext-getrealpath-mean-and-when-should-i-use-it">do <strong>not</strong> ever use <code>getRealPath()</code> method</a>. Using that method is in <em>any</em> case alarming.</p> <p>The path to the storage location can in turn be definied in many ways. You have to do it all by <em>yourself</em>. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that <code>@MultipartConfig(location)</code> does <strong>not</strong> specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.</p> <p>So, the path to the final storage location can be definied in either of the following ways:</p> <ul> <li><p>Hardcoded:</p> <pre><code> File uploads = new File(&quot;/path/to/uploads&quot;); </code></pre> </li> <li><p>Environment variable via <code>SET UPLOAD_LOCATION=/path/to/uploads</code>:</p> <pre><code> File uploads = new File(System.getenv(&quot;UPLOAD_LOCATION&quot;)); </code></pre> </li> <li><p>VM argument during server startup via <code>-Dupload.location=&quot;/path/to/uploads&quot;</code>:</p> <pre><code> File uploads = new File(System.getProperty(&quot;upload.location&quot;)); </code></pre> </li> <li><p><code>*.properties</code> file entry as <code>upload.location=/path/to/uploads</code>:</p> <pre><code> File uploads = new File(properties.getProperty(&quot;upload.location&quot;)); </code></pre> </li> <li><p><code>web.xml</code> <code>&lt;context-param&gt;</code> with name <code>upload.location</code> and value <code>/path/to/uploads</code>:</p> <pre><code> File uploads = new File(getServletContext().getInitParameter(&quot;upload.location&quot;)); </code></pre> </li> <li><p>If any, use the server-provided location, e.g. in <a href="https://stackoverflow.com/questions/9468045/reading-writing-a-text-file-in-a-servlet-where-should-this-file-be-stored-in-jb/">JBoss AS/WildFly</a>:</p> <pre><code> File uploads = new File(System.getProperty(&quot;jboss.server.data.dir&quot;), &quot;uploads&quot;); </code></pre> </li> </ul> <p>Either way, you can easily reference and save the file as follows:</p> <pre><code>File file = new File(uploads, &quot;somefilename.ext&quot;); try (InputStream input = part.getInputStream()) { Files.copy(input, file.toPath()); } </code></pre> <p>Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:</p> <pre><code>File file = File.createTempFile(&quot;somefilename-&quot;, &quot;.ext&quot;, uploads); try (InputStream input = part.getInputStream()) { Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING); } </code></pre> <p>How to obtain <code>part</code> in JSP/Servlet is answered in <a href="https://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet">How to upload files to server using JSP/Servlet?</a> and how to obtain <code>part</code> in JSF is answered in <a href="https://stackoverflow.com/questions/27677397/how-to-upload-file-using-jsf-2-2-hinputfile-where-is-the-saved-file/">How to upload file using JSF 2.2 &lt;h:inputFile&gt;? Where is the saved File?</a></p> <p>Note: do <strong>not</strong> use <a href="http://docs.oracle.com/javaee/7/api/javax/servlet/http/Part.html#write(java.lang.String)" rel="nofollow noreferrer"><code>Part#write()</code></a> as it interprets the path relative to the temporary storage location defined in <code>@MultipartConfig(location)</code>. Also make absolutely sure that you aren't corrupting binary files such as PDF files or image files by converting bytes to characters during reading/writing by incorrectly using a <code>Reader</code>/<code>Writer</code> instead of <code>InputStream</code>/<code>OutputStream</code>.</p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/14211843/how-to-save-uploaded-file/14214223#14214223">How to save uploaded file in JSF</a> (JSF-targeted, but the principle is pretty much the same)</li> <li><a href="https://stackoverflow.com/questions/1812244/simplest-way-to-serve-static-data-from-outside-the-application-server-in-a-java">Simplest way to serve static data from outside the application server in a Java web application</a> (in case you want to serve it back)</li> <li><a href="https://stackoverflow.com/questions/31255366/how-to-save-generated-file-in-servlet-based-web-application">How to save generated file temporarily in servlet based web application</a></li> </ul>
10,130,395
__inline functions vs normal functions in C
<p>I am studying macros and found many sources and questions regarding difference between macros and inline functions. But there is nothing which concretely specifies and differentiates pros&amp;cons of inline vs normal functions. </p> <p>But what about if I want to select between normal function and inline function?</p> <p>I know that use of inline function increase the code size. But as while studying size is not the primary issue , efficiency is the goal. Making a function an inline function suggests that calls to the function be as fast as possible.(Due to stack and stuff overhead) </p> <p>Is always using inline function is better or not? If not then <strong>WHY</strong>? What are the benefits of using normal functions over inline?</p> <p>While reading other questions I read that inline is only a hint to compiler. Compiler may ignore it. When does compiler ignore it and <strong>WHY</strong>?</p>
10,130,669
5
6
null
2012-04-12 19:26:43.42 UTC
8
2012-04-12 22:21:52.62 UTC
2012-04-12 19:32:08.177 UTC
null
742,173
null
742,173
null
1
4
c|inline|c99
13,096
<p>Inlining a function can have several advantages:</p> <ol> <li><p>It can make the program size <em>smaller</em>. This is typically the case when a function is only used once. Also, see 2. and 3.</p></li> <li><p>The compiler can eliminate unused bits of the function, if the compiler knows that a variable is constant, or non-NULL, or something like that. This can save size, but also makes the code more efficient at run time.</p></li> <li><p>The compiler can eliminate bits of the calling function, or even other inlined functions because it can see what the function does with/to the data. (Say the code checks the return value and calls an error function if it's NULL, it might be able to rule that out.</p></li> <li><p>It can reduce the call overhead, but in current processors with predictive branching that's not as much of a win as you might think.</p></li> <li><p>It can hoist constant bit out of loops, do common subexpression elimination, and many other optimizations to make looping code more efficient, and such like.</p></li> </ol> <p>And then there's the disadvantages:</p> <ol> <li><p>It can make the code larger, obviously.</p></li> <li><p>It can increase register pressure within the calling function which might confuse the compiler and prevent it optimizing as well.</p></li> <li><p>Having one hot function that can live in the CPU cache can be quicker than duplicating it to many places that are not always cached.</p></li> <li><p>It can hamper debugging.</p></li> </ol> <p>The reason that the inline function is just a hint is mostly because the C standard does not require that the compiler optimize anything at all. If it wasn't a hint then optimization wouldn't be optional. Also, just because the function <em>isn't</em> marked inline doesn't stop the compiler inlining it if it calculates that doing so would be advantageous.</p>
5,085,392
What is the value of an undefined constant used in #if?
<p>My preprocessor appears to assume that undefined constants are 0 for the purpose of evaluating <code>#if</code> conditions.</p> <p>Can this be relied upon, or do undefined constants give undefined behaviour?</p>
5,085,425
3
0
null
2011-02-22 23:42:20.557 UTC
8
2020-03-01 17:38:21.793 UTC
2016-06-20 09:34:20.893 UTC
null
4,370,109
null
500,690
null
1
77
c++|c-preprocessor
10,869
<p>Yes, it can be relied upon. The C99 standard specifies at §6.10.1 ¶3:</p> <blockquote> <p>After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers are replaced with the pp-number <code>0</code></p> </blockquote> <p><em><strong>Edit</em></strong></p> <p>Sorry, I thought it was a C question; still, no big deal, the equivalent section in the C++ standard (§16.1 ¶4) states:</p> <blockquote> <p>After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers and keywords, except for <code>true</code> and <code>false</code>, are replaced with the pp-number <code>0</code></p> </blockquote> <p>The only difference is the different handling of <code>true</code> and <code>false</code>, which in C do not need special handling, while in C++ they have a special meaning even in the preprocessing phase.</p>
5,032,844
Ruby: what does :: prefix do?
<p>I was reading through the source of <a href="https://github.com/wycats/artifice" rel="noreferrer">Artifice</a> and saw:</p> <pre><code>module Artifice NET_HTTP = ::Net::HTTP # ... end </code></pre> <p>line: <a href="https://github.com/wycats/artifice/blob/master/lib/artifice.rb#L6" rel="noreferrer">https://github.com/wycats/artifice/blob/master/lib/artifice.rb#L6</a></p> <p>Why not just do <code>Net::HTTP</code> instead of <code>::Net::HTTP</code>, i.e., what does it mean when you use <code>::</code> as a prefix?</p>
5,033,013
3
3
null
2011-02-17 18:12:45.883 UTC
27
2020-04-02 00:29:49.64 UTC
null
null
null
null
242,933
null
1
95
ruby|namespaces
16,800
<p>The <code>::</code> is the scope resolution operator. What it does is determines what scope a module can be found under. For example:</p> <pre><code>module Music module Record # perhaps a copy of Abbey Road by The Beatles? end module EightTrack # like Gloria Gaynor, they will survive! end end module Record # for adding an item to the database end </code></pre> <p>To access <code>Music::Record</code> from outside of <code>Music</code> you would use <code>Music::Record</code>.</p> <p>To reference <code>Music::Record</code> from <code>Music::EightTrack</code> you could simply use <code>Record</code> because it's defined in the same scope (that of <code>Music</code>).</p> <p>However, to access the <code>Record</code> module responsible for interfacing with your database from <code>Music::EightTrack</code> you can't just use <code>Record</code> because Ruby thinks you want <code>Music::Record</code>. That's when you would use the scope resolution operator as a prefix, specifying the global/main scope: <code>::Record</code>.</p>
9,166,157
insert into values with where clause
<p>I am trying to programmatically enter values into my table. </p> <p>I cannot use a straight Select @variables. I have to use the keyword Values.</p> <p>How can I create a where clause when using Values in the insert into. </p> <p>I am trying to avoid duplicates</p> <pre><code> DECLARE @MyID INT DECLARE @Phone varchar(10) DECLARE @MyDATE DateTime DECLARE @Agent as varchar(50) DECLARE @Charge as varchar(50) DECLARE @Vendor as varchar(50) SET @MyID = 215199999 SET @Phone = '9999999999' SET @MyDATE = '2010-12-04 11:56:12.000' SET @Agent = 'fbrown' SET @Charge = 'NO' SET @Vendor = 'NO' INSERT INTO [MyDB].[dbo].[Accounts] (MyID,Phone,MyDate,Agent,Charge,Vendor) VALUES ( @MyID ,@Phone ,@MyDATE ,@Agent ,@Charge ,@Vendor ) WHERE MyID NOT IN (@MyID) </code></pre>
9,166,197
5
3
null
2012-02-06 19:40:43.923 UTC
1
2021-03-04 23:06:55.923 UTC
null
null
null
null
819,318
null
1
7
sql|sql-server-2008|sql-server-2005|tsql
72,328
<pre><code>IF NOT EXISTS(SELECT 1 FROM [MyDB].[dbo].[Accounts] WHERE MyID = @MyID) INSERT INTO [MyDB].[dbo].[Accounts] (MyID, Phone, MyDate, Agent, Charge, Vendor) VALUES (@MyID, @Phone, @MyDATE, @Agent, @Charge, @Vendor) </code></pre>
9,390,126
Pythonic way to check if something exists?
<p>This is pretty basic but I was coding and started wondering if there was a pythonic way to check if something does not exist. Here's how I do it if its true:</p> <pre><code>var = 1 if var: print 'it exists' </code></pre> <p>but when I check if something does not exist, I often do something like this:</p> <pre><code>var = 2 if var: print 'it exists' else: print 'nope it does not' </code></pre> <p>Seems like a waste if all I care about is knIs there a way to check if something does not exist without the else?</p>
9,390,225
6
3
null
2012-02-22 06:29:29.97 UTC
34
2020-03-19 21:09:44.617 UTC
2018-08-01 05:22:43.097 UTC
null
6,862,601
null
640,558
null
1
88
python|if-statement
364,127
<p>LBYL style, "look before you leap":</p> <pre><code>var_exists = 'var' in locals() or 'var' in globals() </code></pre> <p>EAFP style, "easier to ask forgiveness than permission":</p> <pre><code>try: var except NameError: var_exists = False else: var_exists = True </code></pre> <p>Prefer the second style (EAFP) when coding in Python, because it is generally more reliable. </p>
9,363,689
What do those yellow horizontal arrows in eclipse, at the left of the line numbers do?
<p>I'm talking about the lines that are in the same visual space as my break points. What do those do, and why are popping up and covering my break points?</p> <p>I am in the Java perspective, i'm looking at the code (code editor view), the debugger is not running, my application is not running. My eclipse is Helios. and I've got RTC tools installed on it.</p> <p>Thx, you guys are awesome.</p> <p>EDIT: arrows are not triangles. I wasn't talking about the warnings :P</p> <p>EDIT #2: a snapshot added:<img src="https://i.stack.imgur.com/xcqLH.jpg" alt="enter image description here"></p>
9,363,795
5
5
null
2012-02-20 15:31:43.143 UTC
6
2014-11-25 12:49:34.27 UTC
2014-11-25 12:49:34.27 UTC
null
2,323,904
null
1,037,251
null
1
83
java|eclipse
26,457
<p>The yellow arrows show up next to search results for me. If you go to the search tab and delete the results they should go away.</p>
20,057,084
How to move main content with Drawer Layout left side
<p>Just checked how to make menu with DrawerLayout <a href="http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/" rel="noreferrer">here</a>. But left side menu is moving on the front of main content. How can I set it to menu and main content move side by side(menu is pushing content to the right)?</p>
20,311,247
6
2
null
2013-11-18 20:21:45.763 UTC
57
2018-02-20 11:46:29.64 UTC
null
null
null
null
717,177
null
1
64
android|android-ui
39,310
<p>If you <strong>dont want to use third-party libraries</strong>, you can implement it yourself just overriding the onDrawerSlide from the ActionBarDrawerToggle. There you can translate your framelayout view based on the opening % of your drawer.</p> <p>Example with code:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent"/&gt; &lt;ListView android:id="@+id/left_drawer" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:choiceMode="singleChoice" android:divider="@android:color/transparent" android:dividerHeight="0dp"/&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <p>And here, override onDrawerSlide:</p> <pre><code>public class ConfigurerActivity extends ActionBarActivity { private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private FrameLayout frame; private float lastTranslate = 0.0f; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); frame = (FrameLayout) findViewById(R.id.content_frame); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.acc_drawer_open, R.string.acc_drawer_close) { @SuppressLint("NewApi") public void onDrawerSlide(View drawerView, float slideOffset) { super.onDrawerSlide(drawerView, slideOffset); float moveFactor = (mDrawerList.getWidth() * slideOffset); if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB) { frame.setTranslationX(moveFactor); } else { TranslateAnimation anim = new TranslateAnimation(lastTranslate, moveFactor, 0.0f, 0.0f); anim.setDuration(0); anim.setFillAfter(true); frame.startAnimation(anim); lastTranslate = moveFactor; } } }; mDrawerLayout.setDrawerListener(mDrawerToggle); // ... more of your code } } </code></pre> <p>Since setTranslationX is not available in pre-honeycomb android versions, i managed it using TranslateAnimation for lower version devices.</p> <p>Hope it helps!</p>
14,923,570
Create pdf from html in golang
<p>How to create PDF files from an HTML input in Google Go? If it is not possible yet, are there any initations that aims to solve this problem?</p> <p>I'm looking for a solution like TCPDF in php.</p>
24,324,299
8
1
null
2013-02-17 16:58:05.347 UTC
11
2022-09-23 20:39:03.393 UTC
2013-02-18 19:09:32.613 UTC
null
440,723
null
440,723
null
1
37
pdf|pdf-generation|go
53,545
<p>what about <strong>gopdf</strong> (<a href="https://github.com/signintech/gopdf" rel="nofollow noreferrer">https://github.com/signintech/gopdf</a>).</p> <p>It seems like you are looking for.</p>
43,901,810
Spring Boot logging with Lombok
<p>I would like to use <a href="https://projectlombok.org/features/Log.html" rel="noreferrer">Project Lombok's log annotation</a> in my Spring Boot projects but I don't want to lose the functionality of being able to change the logging from the <code>application.properties</code>. </p> <p>The Spring logging docs aren't overly clear on what the default logging implementation should be used, and there are 7 Lombok choices!</p> <p>Any ideas?</p>
43,902,039
1
4
null
2017-05-10 20:05:46.423 UTC
10
2021-03-23 20:54:47.74 UTC
null
null
null
null
1,258,079
null
1
32
java|spring-boot|lombok
78,838
<p>I would use <code>@Slf4j</code>. Tested the following and it works as expected.</p> <pre><code>@SpringBootApplication @Slf4j public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); log.info(&quot;testing logging with lombok&quot;); } } </code></pre> <p>Then you can change the logging level as described <a href="https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-custom-log-levels" rel="noreferrer">here</a>.</p> <pre><code>logging.level.com.example.DemoApplication=WARN </code></pre> <p>Note: <em>Below clarifies that SLF4J is correctly handled but point is made in last 5 words!</em></p> <p><a href="https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-logging" rel="noreferrer">From the docs</a>:</p> <blockquote> <p>Default configurations are provided for Java Util Logging, Log4J2 and Logback.&quot; ... &quot;By default, If you use the ‘Starters’, Logback will be used for logging. Appropriate Logback routing is also included to ensure that dependent libraries that use Java Util Logging, Commons Logging, Log4J or <strong>SLF4J</strong> will all <strong>work correctly.</strong></p> </blockquote>
7,727,738
C# - How do I iterate all the rows in Excel._Worksheet?
<p>I am looking to programmatically pull data from an Excel worksheet and insert it into a database table. </p> <p>How do I determine the number of columns and rows in a worksheet or otherwise iterate the rows? </p> <p>I have</p> <pre><code>Excel._Worksheet worksheet = (Excel._Worksheet)workbook.ActiveSheet; </code></pre> <p>I tried <code>worksheet.Range.Rows.Count</code></p> <p>which tosses up</p> <blockquote> <p>Indexed property 'Microsoft.Office.Interop.Excel._Worksheet.Range' has non-optional arguments which must be provided</p> </blockquote> <p>What needs to be done?</p>
12,681,669
2
1
null
2011-10-11 14:33:43.767 UTC
7
2020-01-15 11:46:23.207 UTC
2011-10-11 14:40:01.407 UTC
null
30,018
null
87,796
null
1
24
c#|excel|excel-2007|excel-interop
68,085
<pre><code>public void IterateRows(Excel.worksheet worksheet) { //Get the used Range Excel.Range usedRange = worksheet.UsedRange; //Iterate the rows in the used range foreach(Excel.Range row in usedRange.Rows) { //Do something with the row. //Ex. Iterate through the row's data and put in a string array String[] rowData = new String[row.Columns.Count]; for(int i = 0; i &lt; row.Columns.Count; i++) rowData[i] =Convert.ToString(row.Cells[1, i + 1].Value2); } } </code></pre> <p>This compiles and runs just great for me! I'm using it to extract rows with missing fields to an error log.</p>
7,871,871
is link / href with just parameters (starting with question mark) valid?
<p>Is this link valid?</p> <pre><code>&lt;a href="?lang=en"&gt;eng&lt;/a&gt; </code></pre> <p>I know the browsers treat it as expected and I know the <a href="https://stackoverflow.com/questions/5637969/is-an-empty-href-valid">empty link would be ok</a> too - but is it ok to specify just the parameters?</p> <p>I am curious because question mark ("?") is only a convention by most HTTP servers (AFAIK), though I admit it is a prevailing one.</p> <p>So, to recap:</p> <ol> <li><p>will all browsers interpret this correctly?</p></li> <li><p>is this in RFC?</p></li> <li><p>can I expect some trouble using this?</p></li> </ol> <p><strong>UPDATE:</strong> the intended action on click is to redirect to the same page, but with different GET parameters ("lang=en" in above example).</p>
7,872,230
2
3
null
2011-10-24 06:13:09.26 UTC
6
2016-07-20 10:22:51.603 UTC
2017-05-23 12:09:11.97 UTC
null
-1
null
593,487
null
1
65
html|url|parameters|get
33,009
<p>Yes, it is.<br /> You can find it in <a href="https://www.rfc-editor.org/rfc/rfc1808#section-5" rel="nofollow noreferrer">RFC 1808 - Relative Uniform Resource Locators</a>:</p> <blockquote> <p>Within an object with a well-defined base URL of<br /> Base: <code>&lt;URL:http://a/b/c/d;p?q#f&gt;</code><br /> the relative URLs would be resolved as follows:</p> <h3>5.1. Normal Examples</h3> <p><code>?y</code> = <code>&lt;URL:http://a/b/c/d;p?y&gt;</code></p> </blockquote> <p><a href="https://www.rfc-editor.org/rfc/rfc3986" rel="nofollow noreferrer">RFC 3986 - Uniform Resource Identifier (URI): Generic Syntax</a> restates the same, and adds more details, including the grammar:</p> <pre><code>relative-ref = relative-part [ &quot;?&quot; query ] [ &quot;#&quot; fragment ] relative-part = &quot;//&quot; authority path-abempty / path-absolute / path-noscheme / path-empty #; zero characters </code></pre> <p>Now, that is not to say all browsers implement it according to the standard, but it looks like this should be safe.</p>
23,765,065
Visual Studio 2013 License Product Key
<p>I installed Visual Studio 2013 Professional as a Trial version while waiting for my company to complete the license purchase. </p> <p>They completed the purchase of 4 licenses (64 bit), but were not given <code>Product Keys</code>. Instead, there is a particular <code>.iso</code> file with the license or product key embedded in some way.</p> <p>I want to avoid having to uninstall Visual Studio 2013 only to reinstall Visual Studio 2013 and re-setup all my settings. Is this possible? Is there a way to extract the license/product key from the <code>.iso</code> or from other coworkers desktops that did a clean install?</p> <p>Here is what I have tried (with 2 coworker installations):</p> <ol> <li><p>Looking for the license info in: </p> <p><code>HKLM\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\12.0\Licenses\*</code></p> <p>but it is unique on both computers.</p></li> <li><p>Looking for the Product Key in:</p> <p><code>HKLM\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\12.0\Registration\2000.0x0000\PIDKEY</code></p> <p>One install had one, which my install said was invalid when attempting to use it. The other install had a blank <code>PIDKEY</code>.</p></li> <li><p>Looking inside <code>SW_DVD5_Visual_Studio_Pro_2013_English_MLF_X19-20996.ISO</code> but I see no mention of a License or Product Key.</p></li> <li><p>Checking their <code>Help &gt; Register Product</code> in Visual Studio, which simply says</p> <blockquote> <p>License: Product key applied</p> </blockquote></li> <li><p>Tried doing an install/repair from the ISO but it says:</p> <blockquote> <p>The product version that you are trying to set up is earlier than the version already installed on this computer.</p> </blockquote> <p>Likely because of the <a href="http://www.microsoft.com/en-us/download/details.aspx?id=42666" rel="noreferrer">Visual Studio 2013 Update 1 and 2</a></p></li> </ol> <p>Again, I would really like to avoid the multi-hour process of reinstalling VS 2013. Is there any way?</p>
23,916,077
1
4
null
2014-05-20 16:16:19.95 UTC
18
2016-05-10 06:34:45.163 UTC
2014-05-21 21:15:38.273 UTC
null
1,445,356
null
1,445,356
null
1
41
visual-studio|visual-studio-2013|licensing
297,606
<p>I solved this, without having to completely reinstall Visual Studio 2013.</p> <p>For those who may come across this in the future, the following steps worked for me:</p> <ol> <li>Run the ISO (or <code>vs_professional.exe</code>).</li> <li><p>If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. <strong>If you don't get this error, skip to step 3</strong> <img src="https://i.stack.imgur.com/aqOtS.png" alt="&quot;The product version that you are trying to set up is earlier than the version already installed on this computer.&quot;"></p> <ul> <li><p>Click the link for 'examine the log file' and look near the bottom of the log, for this line: <img src="https://i.stack.imgur.com/X5Jgv.png" alt="Detected related bundle ... operation: Downgrade"></p></li> <li><p>open <code>regedit.exe</code> and do an <code>Edit &gt; Find...</code> for that GUID. In my case it was <code>{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}</code>. This was found in:</p> <blockquote> <p>HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}</p> </blockquote></li> <li><p>Edit the <code>BundleVersion</code> value and change it to a lower version. I changed mine from <code>12.0.21005.13</code> to <code>12.0.21000.13</code>: <img src="https://i.stack.imgur.com/WJqOJ.png" alt="BundleVersion for Visual Studio"> <img src="https://i.stack.imgur.com/Pxnsq.png" alt="lower the version for BundleVersion"></p></li> <li><p>Exit the registry</p></li> </ul></li> <li><p>Run the ISO (or <code>vs_professional.exe</code>) again. <strong>If it has a repair button like the image below, you can skip to step 4</strong>. </p> <p><img src="https://i.stack.imgur.com/Soh3Fm.png" alt="Visual Studio Repair button"></p> <ul> <li>Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). <em>This took about 20 minutes.</em></li> </ul></li> <li><p>Run the ISO (or <code>vs_professional.exe</code>) again. This time repair should be visible.</p></li> <li><p>Click <code>Repair</code> and let it update your installation and apply its embedded license key. <em>This took about 20 minutes.</em></p></li> </ol> <hr> <p>Now when you run Visual Studio 2013, it should indicate that a license key was applied, under <code>Help &gt; Register Product</code>:</p> <p><img src="https://i.stack.imgur.com/hKjO9.png" alt="License: Product key applied"></p> <p>Hope this helps somebody in the future!</p> <p><a href="http://johndelizo.wordpress.com/2013/12/23/visual-studio-2013-setup-blocked-the-product-version-that-you-are-trying-to-set-up-is-earlier-than-the-version-already-installed-on-this-computer-fixed/" rel="noreferrer">Reference blog 'story'</a></p>
23,660,929
How to check whether a jpeg image is color or gray scale using only Python stdlib
<p>I have to write a test case in python to check whether a jpg image is in color or grayscale. Can anyone please let me know if there is any way to do it with out installing extra libraries like opencv?</p>
23,661,373
9
5
null
2014-05-14 17:06:37.647 UTC
11
2021-01-18 13:51:23.597 UTC
2014-05-14 17:38:41.28 UTC
null
202,229
null
3,137,388
null
1
37
python|image-processing|python-2.6
72,155
<p>You can check every pixel to see if it is grayscale (R == G == B)</p> <pre><code>import Image def is_grey_scale(img_path): img = Image.open(img_path).convert('RGB') w, h = img.size for i in range(w): for j in range(h): r, g, b = img.getpixel((i,j)) if r != g != b: return False return True </code></pre>
5,303,819
How to run tests in parallel in Django?
<p>In my Django projects I use sqlite database to run tests. Since it uses only memory, it's much faster than MySQL, but it's still not fast enough. During tests, only one of 4 processors is used, and not much memory is consumed. So, I'd like to have 4 sqlite databases in memory to run 4 tests in parallel.</p> <p>Has anyone tried this?</p>
34,182,885
4
2
null
2011-03-14 20:03:16.587 UTC
4
2020-06-08 19:12:32.35 UTC
null
null
null
null
327,812
null
1
31
django|testing|parallel-processing
15,471
<p>Since Django 1.9 it's possible to run the tests in parallel by Django with its built-in unit-test features.</p> <p>Django Docs: <a href="https://docs.djangoproject.com/en/3.0/ref/django-admin/#cmdoption-test-parallel" rel="noreferrer">https://docs.djangoproject.com/en/3.0/ref/django-admin/#cmdoption-test-parallel</a></p>
5,274,362
reading a dynamic property list into a spring managed bean
<p>I've been searching but cannot find these steps. I hope I'm missing something obvious.</p> <p>I have a properties file with the following contents:</p> <pre><code>machines=A,B </code></pre> <p>I have another file like that but having a different number of members in the machines element like this:</p> <pre><code>machines=B,C,D </code></pre> <p>My question is how do I load this variable-length machines variable into a bean in my spring config in a generic way?</p> <p>something like this:</p> <pre><code>&lt;property name="machines" value="${machines}"/&gt; </code></pre> <p>where machines is an array or list in my java code. I can define it however I want if I can figure out how to do this.</p> <p>Basically I'd rather have spring do the parsing and stick each value into a list element instead of me having to write something that reads in the full machines string and do the parsing myself (with the comma delimiter) to put each value into an array or list. Is there an easy way to do this that I'm missing? </p>
5,274,503
5
2
null
2011-03-11 14:47:20.253 UTC
10
2018-11-16 08:50:50.117 UTC
2011-03-11 14:50:33.13 UTC
null
21,234
null
655,524
null
1
27
spring|dynamic|javabeans
24,232
<p>You may want to take a look at Spring's StringUtils class. It has a number of useful methods to convert a comma separated list to a Set or a String array. You can use any of these utility methods, using Spring's factory-method framework, to inject a parsed value into your bean. Here is an example: </p> <pre><code>&lt;property name="machines"&gt; &lt;bean class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet"&gt; &lt;constructor-arg type="java.lang.String" value="${machines}"/&gt; &lt;/bean&gt; &lt;/property&gt; </code></pre> <p>In this example, the value for 'machines' is loaded from the properties file. </p> <p>If an existing utility method does not meet your needs, it is pretty straightforward to create your own. This technique allows you to execute any static utility method.</p>
4,890,480
C program to convert Fahrenheit to Celsius always prints zero
<p>I need some help with a program for converting Fahrenheit to Celsius in C. My code looks like this</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { int fahrenheit; double celsius; printf("Enter the temperature in degrees fahrenheit:\n\n\n\n"); scanf("%d", &amp;fahrenheit); celsius = (5 / 9) * (fahrenheit - 32); printf("The converted temperature is %lf\n", celsius); return 0; } </code></pre> <p>Every time I execute it it the result is 0.000000. I know I'm missing something but can't figure out what. </p>
4,890,488
6
2
null
2011-02-03 19:02:51.493 UTC
2
2019-02-10 16:54:16.707 UTC
2019-02-10 16:54:16.707 UTC
null
15,168
null
602,087
null
1
6
c
87,824
<p>5/9 will result in integer division, which will = 0</p> <p>Try <code>5.0/9.0</code> instead.</p>
5,587,585
java.lang.NoClassDefFoundError
<p>I'm learning Java am having trouble running an example program.</p> <p>I have two files:</p> <p>GoodDog.java:</p> <pre><code> class GoodDog { private int size; public int getSize() { return size; } public void setSize(int s) { size = s; } void bark() { if (size &gt; 60) { System.out.println("Wooof! WoooF!"); } else if (size &gt; 14) { System.out.println("Ruff! Ruff!"); } else { System.out.println("Yip! Yip!"); } } } </code></pre> <p>GoodDogTestDrive.java:</p> <pre><code> class GoodDogTestDrive { public static void main (String[] args) { GoodDog one = new GoodDog(); one.setSize(70); GoodDog two = new GoodDog(); two.setSize(8); System.out.println("Dog one: " + one.getSize () ); System.out.println("Dog two: " + two.getSize () ); one.bark(); two.bark(); } } </code></pre> <p>They are typed out exactly the way they are in the book and compile without issue. When I try to run GoodDogTestDrive I get this:</p> <pre><code>nephi-shields-mac-mini:/Developer/MyProjects/GoodDog nephishields$ java GoodDogTestDrive.class java.lang.NoClassDefFoundError: GoodDogTestDrive/class Exception in thread "main" nephi-shields-mac-mini:/Developer/MyProjects/GoodDog nephishields$ </code></pre> <p>What am I doing wrong?</p>
5,587,608
7
2
null
2011-04-07 21:00:24.167 UTC
1
2013-12-26 07:24:47.687 UTC
2012-06-02 10:26:05.293 UTC
null
1,136,195
user588389
null
null
1
8
java|noclassdeffounderror
48,708
<p>Don't include the <code>.class</code> in the command:</p> <pre><code>java GoodDogTestDrive </code></pre>
4,959,770
How to pass a javascript variable into a erb code in a js view?
<p>I have this Javascript view in my Rails 3 project:</p> <p>app/views/expenses/new_daily.js.erb</p> <pre><code>var i = parseInt($('#daily').attr('data-num')) + 1; //$('#daily').append('agrego fila ' + i + ' &lt;br /&gt;'); $('#daily').append('&lt;%= escape_javascript(render(partial: 'new_expense', locals: { i: i })) %&gt;'); $('#daily').attr('data-num', i); </code></pre> <p>I want to pass my 'i' javascript variable to a ruby partial through locals, How I can accomplish this?</p>
5,946,254
8
0
null
2011-02-10 16:23:53.577 UTC
7
2018-09-14 18:51:14.12 UTC
null
null
null
null
611,678
null
1
29
javascript|ruby-on-rails|view|erb
83,419
<p>As far as i know there is no way to do it directly and the reason is fairly simple too, html is executed at the server side and javascript is a client side language which means its executed in your local browser, thats why if you even try to pass a variable between the two you'll have to make a request to the server, However this problem is tackled by calling an AJAX request, this AJAX request does the same thing as sending a new request to the server however it does that without refreshing or reloading the page to it gives the users the illusion that no request was made.</p> <p><strong>a guy asks a similar question <a href="http://www.quora.com/Ruby-on-Rails/Can-I-pass-a-JavaScript-variable-to-a-Rails-method" rel="nofollow noreferrer">Here</a></strong></p> <p><strong>and you can learn more about AJAX <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started" rel="nofollow noreferrer">Here on MDN</a>:</strong></p>
5,231,371
Springs XmlBeanFactory is deprecated
<p>I try to learn Spring. I am following this site <a href="http://www.roseindia.net/spring/spring3/spring-3-hello-world.shtml">http://www.roseindia.net/spring/spring3/spring-3-hello-world.shtml</a></p> <p>I tried one example in that. I am using some what like below, but here it shows:</p> <blockquote> <p>The type XmlBeanFactory is deprecated</p> </blockquote> <p>What do I have to use as an alternative to this?</p> <pre><code>public class SpringHelloWorldTest { public static void main(String[] args) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("SpringHelloWorld.xml")); Spring3HelloWorld myBean = (Spring3HelloWorld)beanFactory.getBean("Spring3HelloWorldBean"); myBean.sayHello(); } } </code></pre>
9,210,939
12
1
null
2011-03-08 10:44:44.553 UTC
11
2020-04-26 13:02:38.57 UTC
2016-01-16 23:19:45.427 UTC
null
3,885,376
null
587,012
null
1
57
java|spring|deprecated|xmlbeans
62,686
<blockquote> <p>ApplicationContext is a sub-interface of BeanFactory.You can use this way</p> </blockquote> <pre><code>public class SpringHelloWorldTest { public static void main(String[] args) { ApplicationContext context= new ClassPathXmlApplicationContext("SpringHelloWorld.xml"); Spring3HelloWorld myBean= (Spring3HelloWorld) context.getBean("Spring3HelloWorldBean"); myBean.sayHello(); } } </code></pre>
5,340,724
Get changes from master into branch in Git
<p>In my repository I have a branch called <code>aq</code> which I'm working on.</p> <p>I then committed new work and bugs in <code>master</code>. </p> <p>What is the best way to get those commits into the <code>aq</code> branch? Create another new branch out of <code>master</code> and merge it with <code>aq</code>?</p>
5,340,773
13
4
null
2011-03-17 14:51:32.313 UTC
275
2020-05-15 06:10:52.57 UTC
2016-07-06 12:13:34.707 UTC
null
1,958,461
null
34,548
null
1
894
git|version-control|git-merge
1,004,196
<p>Check out the <code>aq</code> branch, and rebase from <code>master</code>.</p> <pre><code>git checkout aq git rebase master </code></pre>
4,992,794
How to add bulleted list to android application?
<p>How do add a bulleted list to my textview?</p>
5,891,755
17
1
null
2011-02-14 13:38:23.113 UTC
27
2021-11-01 21:22:43.86 UTC
2021-11-01 21:22:43.86 UTC
null
1,264,804
null
590,849
null
1
102
android|textview
106,394
<p>Tough to do as ul/li/ol are not supported. Fortunately you can use this as syntactic sugar:</p> <pre><code>&amp;#8226; foo&lt;br/&gt; &amp;#8226; bar&lt;br/&gt; &amp;#8226; baz&lt;br/&gt; </code></pre> <p><code>&amp;#8226;</code> is the html entity for a list bullet more choices are here <a href="http://www.elizabethcastro.com/html/extras/entities.html">http://www.elizabethcastro.com/html/extras/entities.html</a></p> <p>more about which tags are supported provided by Mark Murphy (@CommonsWare) <a href="http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html">http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html</a> Load that up with Html.fromHtml</p> <pre><code>((TextView)findViewById(R.id.my_text_view)).setText(Html.fromHtml(myHtmlString)); </code></pre>
4,859,292
How to get a random value from dictionary?
<p>How can I get a random pair from a <code>dict</code>? I'm making a game where you need to guess a capital of a country and I need questions to appear randomly.</p> <p>The <code>dict</code> looks like <code>{'VENEZUELA':'CARACAS'}</code></p> <p>How can I do this?</p>
4,859,322
20
0
null
2011-02-01 05:37:05.667 UTC
48
2022-08-03 05:30:14.87 UTC
2021-02-09 16:36:41.957 UTC
null
355,230
null
569,183
null
1
207
python|random|dictionary|key
363,332
<p>One way would be:</p> <pre><code>import random d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'} random.choice(list(d.values())) </code></pre> <p><strong>EDIT</strong>: The question was changed a couple years after the original post, and now asks for a pair, rather than a single item. The final line should now be:</p> <pre><code>country, capital = random.choice(list(d.items())) </code></pre>
16,962,683
VBA Stop calculation of cells
<p>Very new to VBA in Excel, got asked to do some validation on cell change and got a bit stuck.</p> <p>So, user needs to enter a monetary value into a cell, let's say D16, so I thought I'd hook into the _Change event on the Worksheet which works quite well.</p> <p>However, I need the rest of the worksheet to not complete the calculation when an entry has been submitted into D16, basically, when 500000 is entered, other cells gets updated with values from another worksheet.</p> <p>My code</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) If Target = Range("D16") Then Dim numeric numeric = IsNumeric(Target) If numeric = False Then MsgBox "error" Exit Sub /// this is where I need to "stop" the calculations from firing End If End If End Sub </code></pre>
16,962,844
2
1
null
2013-06-06 12:54:54.767 UTC
2
2013-06-06 13:03:19.637 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
428,682
null
1
8
excel|vba
55,327
<p>I hope below code helps. You need to paste this in sheet code section.</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) On Error Resume Next Application.EnableEvents = False Application.Calculation = xlCalculationManual Dim rng As Range Set rng = Range("D16") If Not Intersect(Target, rng) Is Nothing And IsNumeric(Target) Then If Target.Value &gt;= 500000 Then MsgBox "Value is greater than 500000" End If End If Application.EnableEvents = True Application.Calculation = xlCalculationAutomatic End Sub </code></pre>
12,210,451
How to prevent memcpy buffer overflow?
<p>There are some binary buffers with fixed sizes in a program that are used to store data, and memcpy is used to copy the buffer from one to another one. Since the source buffer may be larger than the destination buffer, how can I detect if there is buffer overflow?</p>
12,210,481
4
7
null
2012-08-31 07:06:43.603 UTC
5
2021-06-09 13:23:51.34 UTC
2021-06-09 13:23:51.34 UTC
null
15,168
null
921,119
null
1
12
c|memcpy|buffer-overflow|fortify-source
42,328
<p>You have to know how much data is in the source buffer and how much space is available in the target buffer.</p> <p>Do not call <code>memcpy()</code> if there is not enough space in the target buffer for all the data you want to copy from the source buffer. (You have to decide whether it is OK to truncate the data if the source is bigger than the target.)</p> <p>If you don't know, rewrite the code so that you do know how much space there is; otherwise, it is not safe.</p> <p>Note that if there is a chance of the source and target buffers overlapping, you should use <code>memmove()</code> rather then <code>memcpy()</code>.</p> <p>In C++, look askance at using <code>memcpy()</code> in the first place; that is a C-style operation rather than C++.</p>
12,467,731
How to set boolean values in an INI configuration file?
<p>I've seen a variety of ways used to set boolean values in INI files:</p> <ul> <li><code>variable = true</code></li> <li><code>variable = 1</code></li> <li><code>variable = on</code></li> <li><code>variable = yes</code></li> </ul> <p>Which is the most canonical, common, and/or preferred way?</p>
48,239,798
2
0
null
2012-09-17 22:03:13.39 UTC
0
2018-02-06 21:01:06.703 UTC
2012-09-17 22:11:03.917 UTC
null
31,100
null
31,100
null
1
32
app-config|ini
20,957
<p>There's no spec for INI files, but for whatever it's worth, I'll list the behaviour of a few implementations from languages I know.</p> <p>Python's built-in <code>configparser</code> module offers a <a href="https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.getboolean" rel="noreferrer"><code>getboolean</code></a> that behaves as follows:</p> <blockquote> <p>the accepted values ... are <code>'1'</code>, <code>'yes'</code>, <code>'true'</code>, and <code>'on'</code>, which cause this method to return <code>True</code>, and <code>'0'</code>, <code>'no'</code>, <code>'false'</code>, and <code>'off'</code>, which cause it to return <code>False</code>.</p> </blockquote> <p>In PHP's <a href="http://php.net/manual/en/function.parse-ini-file.php" rel="noreferrer"><code>parse_init_file</code></a>, on the other hand:</p> <blockquote> <p>String values <em>"true"</em>, <em>"on"</em> and <em>"yes"</em> are converted to <strong>TRUE</strong>. <em>"false"</em>, <em>"off"</em>, <em>"no"</em> and <em>"none"</em> are considered <strong>FALSE</strong>.</p> </blockquote> <p>Meanwhile, .NET has no built-in support for INI parsing, but its most popular INI-parsing library, <a href="https://github.com/rickyah/ini-parser" rel="noreferrer">ini-parser</a>, offers no support whatsoever for automatic parsing of values and returns them all as strings. Its <a href="https://github.com/rickyah/ini-parser#getting-started" rel="noreferrer"><em>Getting Started</em></a> examples show parsing booleans with .NET's <a href="https://docs.microsoft.com/en-us/dotnet/api/system.boolean.parse" rel="noreferrer"><code>Boolean.Parse</code></a>, which will accept the strings <code>"true"</code> and <code>"false"</code> (with any capitalisation) and throw an exception if given anything else.</p> <p>In summary: there is absolutely no consistency on this question between different implementations of INI parsers.</p> <p>I would recommend:</p> <ul> <li>If you are only going to parse your INI using a single parser, check how that parser behaves and craft your INI to suit its particular implementation.</li> <li>If you need to support a wide range of parsers (for example, for language interoperability), then either abandon INI as a format entirely, or else entirely avoid using any of the magic boolean values that some parsers understand and instead stick to <code>1</code> and <code>0</code>.</li> </ul>
12,435,252
How to create custom additional fields in UserProfile in MVC4
<p>I faced with new ASP MVC 4 feature, it shipped with new membership db schema and new initialization. In mvc 3 and old versions developer able to create custom user profile fields using specifications in web.config, but now i faced with method in filters namespace in default mvc 4 project:</p> <pre><code>WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); </code></pre> <p>and user profile table:</p> <pre><code>[Table("UserProfile")] public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } } </code></pre> <p>But the method InitializeDatabaseConnection generate only UserName and UserId i need to generate other additional fields.</p> <p>I have good experience in EF codeFirst approach, and in that case i try to edit UserProfile Class:</p> <pre><code>[Table("UserProfile")] public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } [Column] [Required] public string UserName { get; set; } [Column] [Required] public string FirstName { get; set; } [Column] [Required] public string LastName { get; set; } } </code></pre> <p>But when i regenerate database, i havent see any changes, Custom Db fields not generated. Help me please, how can i create custom user fields?</p>
12,461,447
5
1
null
2012-09-15 06:55:54.93 UTC
46
2014-07-24 18:41:02.9 UTC
2013-02-06 18:42:35.81 UTC
null
2,026,719
null
1,346,297
null
1
40
c#|asp.net-mvc|entity-framework|asp.net-mvc-4|simplemembership
49,000
<p>Elaborating from the answer above </p> <p>The <code>WebSecurity.InitializeDatabaseConnection</code> Method help states that</p> <blockquote> <p>If you want to use a database table that contains user profile information (user names, email addresses, and so on), you specify a connection string and table name that the membership system uses to connect to that information. If you do not want to use an existing user profile table, you can specify that the InitializeDatabaseConnection() method should automatically create the user profile table. (A database for the user profile table must already exist.)</p> </blockquote> <p>So if we want more fields into the <code>UserProfile</code> table we just need to make sure we are creating a profile table and run the <code>InitializeDatabaseConnection</code> method after the table is already in place.</p> <p>In the standard MVC4.0 project template from VS2012 I've commented out the Account controller</p> <pre><code>[Authorize] //[InitializeSimpleMembership] public class AccountController : Controller { </code></pre> <p>and moved <code>InitializeDatabaseConnection</code> into the EF Code First Database Initializer</p> <pre><code>public class MyDatabaseInit: DropCreateDatabaseAlways&lt;MyDatabaseContext&gt; { protected override void Seed(MyDatabaseContext context) { SeedMembership(); } private void SeedMembership() { WebSecurity.InitializeDatabaseConnection("MyDatabaseContext", "UserProfile", "UserId", "UserName", autoCreateTables: true); } } </code></pre> <p>ensuring that the <code>InitializeDatabaseConnection</code> runs once the table is already in place.</p> <p>Added the <code>UserProfile</code> class to my EF Code First model</p> <pre><code>public class MyDatabaseContext : DbContext { public DbSet&lt;UserProfile&gt; UserProfiles { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;(); } } </code></pre> <p>Added the extra field in the <code>UserProfile</code> table</p> <pre><code>[Table("UserProfile")] public class UserProfile { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } public string MobilePhone { get; set; } } </code></pre> <p>All you need now is to set the database initialization strategy when the application starts and also call a query on the database the make sure it gets created at that point, before any authorization/authentication code is called.</p> <pre><code>protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); Database.SetInitializer&lt;MyDatabaseContext&gt;(new MyDatabaseInit()); new MyDatabaseContext().UserProfile.Find(1); } </code></pre>
12,070,744
Add back button to action bar
<p>I have been trying to add a back button to the action bar.</p> <p>I want my view to look like this: <img src="https://i.stack.imgur.com/72m0D.jpg" alt="enter image description here"></p> <p>I want to add the back button in the left of the action bar.</p> <p>I added this code</p> <pre><code>ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); </code></pre> <p>but it doesn't work.</p> <p>How can I fix this?</p>
13,741,187
11
4
null
2012-08-22 10:03:28.72 UTC
18
2018-11-29 06:24:08.653 UTC
2018-02-11 12:31:42.02 UTC
null
1,000,551
null
833,219
null
1
64
android|android-layout|android-actionbar
143,835
<p>After setting <code>actionBar.setHomeButtonEnabled(true);</code></p> <p>Add the following code:</p> <pre><code>@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // app icon in action bar clicked; goto parent activity. this.finish(); return true; default: return super.onOptionsItemSelected(item); } } </code></pre>
12,627,586
Is node.js rmdir recursive ? Will it work on non empty directories?
<p>The documentation for <a href="http://nodejs.org/api/fs.html#fs_fs_rmdir_path_callback">fs.rmdir</a> is very short and doesn't explain the behavior of rmdir when the directory is not empty.</p> <p><strong>Q</strong>: What happens if I try to use this API to delete a non empty directory ?</p>
12,631,454
23
4
null
2012-09-27 18:10:11.42 UTC
11
2021-09-24 07:44:11.03 UTC
2012-09-28 01:37:11.943 UTC
null
1,060,205
null
1,060,205
null
1
84
node.js
83,090
<p>Short answer: <em>node.js</em> <code>fs.rmdir()</code> calls the POSIX <code>rmdir()</code>; this will remove an empty directory, or <em>return an error</em>. In the given case, the call will invoke the callback function and pass the error as an exception.</p> <p>The problem here is that the node.js documentation refers to <a href="https://stackoverflow.com/questions/453993/is-there-a-listing-of-the-posix-api-functions">POSIX</a>:</p> <p>The <a href="http://nodejs.org/api" rel="nofollow noreferrer">Node.js API Docs</a> <strong><a href="http://nodejs.org/api/fs.html#fs_file_system" rel="nofollow noreferrer">File System</a></strong> API started out as</p> <blockquote> <p><em>simple wrappers around standard POSIX functions.</em></p> </blockquote> <p>This almost changes the question into a duplicate of: <a href="https://stackoverflow.com/questions/453993/is-there-a-listing-of-the-posix-api-functions">Is there a listing of the POSIX API / functions?</a></p> <p>The description for <code>fs.rmdir</code> is terse, but sufficient.</p> <blockquote> <p>Asynchronous rmdir(2).</p> </blockquote> <p>The <code>rmdir(2)</code> here is an implicit reference to the documentation for the <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/rmdir.html" rel="nofollow noreferrer"><code>rmdir() system call</code></a>. The number (2) here is an old unix man page convention to indicate Section 2 of the Manual pages, containing the kernel interfaces.</p>
24,253,976
Android Package manager has died with TransactionTooLargeException
<p>My app reads the list of all installed APK files, and then loop through the list to read the APK info, however it throws a TransactionTooLargeException exception.</p> <p>From what I have read here <a href="http://developer.android.com/reference/android/os/TransactionTooLargeException.html">http://developer.android.com/reference/android/os/TransactionTooLargeException.html</a>, google recommends to break large transactions into smaller transactions. However it seems this happens in the middle when looping through the APK list. If I catch the exception and continue it, the rest all works fine. Is there a way to reduce the memory usage while calling the getPackageInfo? Does that call hold some thing even after it already returned.</p> <p>Here is the trace when it happened:</p> <pre><code>at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:89) at com.myapp.appreader.getAppDetails(Appreader.java:207) at com.myapp.appreader.collectData(Appreader.java:99) at com.myapp.appreader.AppDataCollectionTask.run(AppDataCollectionTask.java:26) at com.myapp.appreader.service.AppDataTaskExecutor$AppDataAsyncTask.executeTask(AppDataTaskExecutor.java:439) at com.myapp.appreader.service.AppDataTaskExecutor$AppDataAsyncTask.doInBackground(AppDataTaskExecutor.java:327) at com.myapp.appreader.service.AppDataTaskExecutor$AppDataAsyncTask.doInBackground(AppDataTaskExecutor.java:1) at android.os.AsyncTask$2.call(AsyncTask.java:287) at java.util.concurrent.FutureTask.run(FutureTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) at java.lang.Thread.run(Thread.java:856)\nCaused by: android.os.TransactionTooLargeExceptionat android.os.BinderProxy.transact(Native Method) at android.content.pm.IPackageManager$Stub$Proxy.getPackageInfo(IPackageManager.java:1538) at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:84) </code></pre>
24,265,790
2
7
null
2014-06-17 00:10:01.6 UTC
10
2015-05-05 20:37:03.587 UTC
2014-07-13 07:42:36.81 UTC
null
321,731
null
485,918
null
1
11
android|exception|transactions|android-package-managers
23,342
<p>There is a 1MB limit on a Binder transaction, which means most IPC invocations have to be modest in size.</p> <p>If you hit a <code>TransactionTooLargeException</code> or similar Binder failures when retrieving data from <code>PackageManager</code> (e.g., <code>getPackageInfo()</code>), try splitting your request over multiple calls, with fewer flags (e.g., <code>GET_META_DATA</code>) per call. Hopefully this will reduce the size of any individual transaction to be under the 1MB limit.</p> <p>Also, if you are using calls on <code>PackageManager</code> that return multiple results (e.g., <code>getInstalledPackages()</code>, try asking for <em>no</em> flags on that call, then retrieving the values for each package individually, to avoid getting a lot of data on a lot of entries at once.</p> <p>And, of course, only use flags that you need, particularly if your call might contain some. <code>GET_META_DATA</code> is a classic example of that: many apps use it (e.g., for Play Services), but if you do not need to know the metadata information, don't request it.</p>
24,245,276
Why does Rust not have a return value in the main function, and how to return a value anyway?
<p>In Rust the main function is defined like this:</p> <pre><code>fn main() { } </code></pre> <p>This function does not allow for a return value though. Why would a language not allow for a return value and is there a way to return something anyway? Would I be able to safely use the C <code>exit(int)</code> function, or will this cause leaks and whatnot? </p>
50,459,909
5
7
null
2014-06-16 13:47:09.787 UTC
8
2020-01-26 16:30:55.947 UTC
2015-10-16 12:09:44.543 UTC
null
155,423
null
2,558,778
null
1
49
return|program-entry-point|rust
27,886
<p>As of <a href="https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1260-2018-05-10" rel="noreferrer">Rust 1.26</a>, <code>main</code> can return a <code>Result</code>:</p> <pre><code>use std::fs::File; fn main() -&gt; Result&lt;(), std::io::Error&gt; { let f = File::open("bar.txt")?; Ok(()) } </code></pre> <p>The returned error code in this case is 1 in case of an error. With <code>File::open("bar.txt").expect("file not found");</code> instead, an error value of 101 is returned (at least on my machine).</p> <p>Also, if you want to return a more generic error, use:</p> <pre><code>use std::error::Error; ... fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; { ... } </code></pre>
3,395,000
Why I'm getting "cannot modify header information headers already sent by registration_model" error in codeigniter?
<p>I have a problem with model in my codeigniter app. I'm getting this error of sending headers information. Basically, codeigniter is complaining about my registration model sending header information before anything else. How is it possible? I thought that models are only for holding db queries methods and nothing more. Can someone please explain me that?</p> <p>This is how the beginning of a controller looks like:</p> <pre><code>function User() { parent::Controller(); $this-&gt;view_data['base_url'] = base_url(); $this-&gt;load-&gt;model('User_registration_model'); // don't forget capital, it's important $this-&gt;load-&gt;model('user_map_model'); // don't forget capital, it's important $this-&gt;load-&gt;model('Tribe_model'); // don't forget capital, it's important $this-&gt;load-&gt;library('email'); // Loading email library $this-&gt;load-&gt;library('session'); // sets up the session $this-&gt;load-&gt;library ('form_validation'); // Loading form validation library $this-&gt;load-&gt;helper(array('form', 'url')); } </code></pre>
3,395,099
3
4
null
2010-08-03 08:57:03.103 UTC
7
2013-01-15 13:15:58.383 UTC
null
null
null
null
359,656
null
1
12
php|codeigniter
50,137
<p>Note that headers should be sent <strong><em>before</em></strong> anything else. Make sure that there is no code/html or even space/indentation before the header function and there is nothing before the first opening php tag <code>&lt;?php</code> as well as ending tag <code>?&gt;</code> in your view.</p>
26,154,726
AngularJS - Closing Modal Window
<p>My includes are:<br></p> <pre><code>bootstrap.css [ getbootstrap.com/2.3.2 ] angular/ui-bootstrap-tpls-0.10.0.min.js from: [ angular-ui.github.io/bootstrap ] </code></pre> <p>I am using AngularJS and Twitter Bootstrap.<br></p> <p><em>From AngularJS I open the modal window as follows:</em></p> <pre><code>var modalInstance = $modal.open({ templateUrl: 'resources/html/mymodal.html', controller: 'mymodalController', scope: $scope }); </code></pre> <p><em>My Modal Template is:</em></p> <pre><code>&lt;div class="modal"&gt; &lt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;&amp;times;&lt;/button&gt; &lt;/div&gt; ..... &lt;/div&gt; </code></pre> <p><br> <strong>Question:</strong><br> The close [x] button is not working <br> When I click on it, the modal does not go away. But when I press Esc - the modal vanishes.<br> So looks like ... data-dismiss="modal" is not working. Any ideas?</p>
26,154,897
3
5
null
2014-10-02 05:02:35.15 UTC
2
2016-05-08 09:16:22.507 UTC
2015-06-10 07:24:08.46 UTC
null
4,948,889
null
974,169
null
1
7
angularjs|twitter-bootstrap|angular-ui-bootstrap
55,827
<p>the <code>data-dismiss</code> attribute is used by the bootstrap javascript (as I see you got the html source code from, <a href="http://getbootstrap.com/javascript/#modals" rel="noreferrer">http://getbootstrap.com/javascript/#modals</a> )</p> <p>UI Bootstrap won't be binding to that close button because it isn't looking for that attribute, you need to add an ng-click and dismiss the modal like in the examples</p> <p><a href="http://angular-ui.github.io/bootstrap/#/modal" rel="noreferrer">http://angular-ui.github.io/bootstrap/#/modal</a></p> <p><strong>in controller:</strong></p> <pre><code>$scope.cancel = function () { $modalInstance.dismiss('cancel'); }; </code></pre> <p>Modal template...</p> <pre><code>&lt;button class="btn btn-warning" ng-click="cancel()"&gt;Cancel&lt;/button&gt; </code></pre>
11,116,760
Save Json in Javascript variable
<p>I'm studying javascript these days and I have question. I have variable that contain an url. I would like to save the content of the url pointed by my variable in another variable...</p> <p>The first variable is something like:</p> <pre><code>var Link = "http://mysite.com/json/public/search?q=variabile&amp;k=&amp;e=1"; </code></pre> <p>If I open the link I see something like:</p> <pre><code>{ "count": 1, "e": 1, "k": null, "privateresult": 0, "q": "gabriel", "start": 0, "cards": [ { "__guid__": "cdf8ee96538c3811a6a118c72365a9ec", "company": false, "__title__": "Gabriel Butoeru", "__class__": "entity", "services": false, "__own__": false, "vanity_urls": [ "gabriel-butoeru" ] } ] } </code></pre> <p>How can I save the json content in another javascript variable?</p>
11,116,930
5
6
null
2012-06-20 09:39:42.463 UTC
6
2016-01-26 20:11:48.307 UTC
null
null
null
null
1,453,638
null
1
6
javascript|html|json|variables
45,194
<p>You would need a simple AJAX request to get the contents into a variable.</p> <pre><code>var xhReq = new XMLHttpRequest(); xhReq.open("GET", yourUrl, false); xhReq.send(null); var jsonObject = JSON.parse(xhReq.responseText); </code></pre> <p>Please note that AJAX is bound by <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">same-origin-policy</a>, in case that URL is different this will fail.</p>
11,115,637
What is Magento's index_event table
<p>I'm playing with improving performance during saving category and I found that once category is updated via Magenti API or backend then the following update query is called</p> <pre><code>SQL: UPDATE `index_event` SET `event_id` = ?, `type` = ?, `entity` = ?, `entity_pk` = ?, `created_at` = ?, `old_data` = ?, `new_data` = ? WHERE (event_id='13066') BIND: Array ( [0] =&gt; 13066 [1] =&gt; save [2] =&gt; catalog_category [3] =&gt; 2867 [4] =&gt; 2011-09-22 13:50:54 [5] =&gt; a:4:{s:30:"Mage_Catalog_Model_Indexer_Url";N;s:40:"Mage_Catalog_Model_Category_Indexer_Flat";N;s:43:"Mage_Catalog_Model_Category_Indexer_Product";N;s:41:"Mage_CatalogSearch_Model_Indexer_Fulltext";N;} [6] =&gt; a:11:{s:35:"cataloginventory_stock_match_result";b:0;s:34:"catalog_product_price_match_result";b:0;s:24:"catalog_url_match_result";b:1;s:30:"Mage_Catalog_Model_Indexer_Url";N;s:33:"catalog_product_flat_match_result";b:0;s:34:"catalog_category_flat_match_result";b:1;s:40:"Mage_Catalog_Model_Category_Indexer_Flat";N;s:37:"catalog_category_product_match_result";b:1;s:43:"Mage_Catalog_Model_Category_Indexer_Product";N;s:35:"catalogsearch_fulltext_match_result";b:1;s:41:"Mage_CatalogSearch_Model_Indexer_Fulltext";N;} </code></pre> <p>Can anyone tell me what does it mean and will happen? It looks like some indexing actions are pushed to a queue but when does it execute?</p>
11,123,773
1
0
null
2012-06-20 08:31:20.5 UTC
9
2016-06-07 11:10:46.417 UTC
2016-06-07 11:10:46.417 UTC
null
19,405
null
1,005,244
null
1
11
performance|magento|indexing
7,032
<p>Your assumption <em>"It looks like some indexing actions are pushed to a queue"</em> is correct.</p> <p>To answer your question <em>"but when does it execute?"</em>:</p> <p>Some Magento models, like</p> <pre><code>Mage_Core_Model_Store Mage_Catalog_Model_Product Mage_Catalog_Model_Category Mage_CatalogInventory_Model_Stock_Item Mage_Tag_Model_Tag Mage_Tag_Model_Tag_Relation </code></pre> <p>for example, queue index events. Mainly before deleting and/or after committing.</p> <p>They do this by either calling the <code>logEvent()</code> or the <code>processEntityAction()</code> method of the <code>Mage_Index_Model_Indexer</code> class.</p> <ul> <li><p>If they call <code>logEvent()</code> directly, an index event will only be queued. Reindexing will not even be tried.</p></li> <li><p>If they call <code>processEntityAction()</code>, also an index event will be queued, but Magento will try to process this index event right after queueing.</p></li> </ul> <p>There's also a third method <code>Mage_Index_Model_Indexer::indexEvents()</code> being called by some modules. The difference to the former two is, that <code>indexEvents()</code> does <em>not</em> queue any index event, but will only try to immediately reindex. </p> <p>Note that any reindexing thru <code>processEntityAction()</code> and <code>indexEvents()</code> will only happen, if the process mode of the corresponding index type is <code>Mage_Index_Model_Process::MODE_REAL_TIME</code>.</p> <p>You can check this via <code>System -&gt; Index Management</code>. If the <code>Mode</code> column reads <em>Update on save</em>, than that index is set to <code>MODE_REAL_TIME</code>.</p> <p>If it reads <em>Manual Update</em> instead, it's set to <code>Mage_Index_Model_Process::MODE_MANUAL</code>, which means automatic reindexing will never happen at all.</p> <p>In the latter case you need to manually trigger the reindexing processes to get your data reindexed. That can be achieved using several methods, e.g. by using <code>System -&gt; Index Management -&gt; Index -&gt; Reindex data -&gt; Submit</code>, or using the Magento <code>shell/indexer.php</code> on the command line, or by scripting your own indexer process collection handling started by a cron job.</p>
11,450,089
Changing Large MySQL InnoDB Tables
<p>Adding a new column or adding a new index can take hours and days for large innodb tables in MySQL with more than 10 million rows. What is the best way to increase the performance on large innodb tables in these two cases? More memory, tweaking the configuration (for example increasing the <a href="http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_sort_buffer_size">sort_buffer_size</a> or <a href="http://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html#sysvar_innodb_buffer_pool_size">innodb_buffer_pool_size</a>), or some kind of trick? Instead of altering a table directly, one could create a new one, change it, and copy the old data the new, like this which is useful for <a href="http://www.rndblog.com/don%E2%80%99t-alter-table-do-copy-and-rename/">ISAM tables</a> and <a href="http://onehub.com/blog/posts/adding-columns-to-large-mysql-tables-quickly/">multiple changes</a>: </p> <pre><code>CREATE TABLE tablename_tmp LIKE tablename; ALTER TABLE tablename_tmp ADD fieldname fieldtype; INSERT INTO tablename_tmp SELECT * FROM tablename; ALTER TABLE tablename RENAME tablename_old; ALTER TABLE tablename_tmp RENAME tablename; </code></pre> <p>Is it recommendable for innodb tables, too, or is it just what the ALTER TABLE command does anway?</p>
11,450,445
2
2
null
2012-07-12 10:40:38.55 UTC
24
2016-10-08 13:36:30.357 UTC
2012-07-12 12:08:50.683 UTC
null
771,581
null
771,581
null
1
43
mysql|performance|optimization
27,574
<p><strong>Edit 2016:</strong> we've recently (August 2016) released <code>gh-ost</code>, modifying my answer to reflect it.</p> <p>Today there are several tools which allow you to do online alter table for MySQL. These are:</p> <ul> <li><strong>edit 2016:</strong> <a href="https://github.com/github/gh-ost" rel="noreferrer">gh-ost</a>: GitHub's triggerless schema migration tool (disclaimer: I am author of this tool)</li> <li><a href="http://openarkkit.googlecode.com/svn/trunk/openarkkit/doc/html/oak-online-alter-table.html" rel="noreferrer">oak-online-alter-table</a>, as part of the <em>openark-kit</em> (disclaimer: I am author of this tool)</li> <li><a href="http://www.percona.com/doc/percona-toolkit/2.1/pt-online-schema-change.html" rel="noreferrer">pt-online-schema-change</a>, as part of the <em>Percona Toolkit</em></li> <li>Facebook's <a href="http://www.facebook.com/notes/mysql-at-facebook/online-schema-change-for-mysql/430801045932" rel="noreferrer">online schema change for MySQL</a></li> </ul> <h3>Let's consider the "normal" `ALTER TABLE`:</h3> <p>A large table will take long time to <code>ALTER</code>. <code>innodb_buffer_pool_size</code> is important, and so are other variables, but on very large table they are all negligible. It just takes time.</p> <p>What MySQL does to <code>ALTER</code> a table is to create a new table with new format, copy all rows, then switch over. During this time the table is completely locked.</p> <h3>Consider your own suggestion:</h3> <p>It will most probably perform worst of all options. Why is that? Because you're using an InnoDB table, the <code>INSERT INTO tablename_tmp SELECT * FROM tablename</code> makes for a transaction. a <strong>huge</strong> transaction. It will create even more load than the normal <code>ALTER TABLE</code>.</p> <p>Moreover, you will have to shut down your application at that time so that it does not write (<code>INSERT</code>, <code>DELETE</code>, <code>UPDATE</code>) to your table. If it does - your whole transaction is pointless.</p> <h3>What the online tools provide</h3> <p>The tools do not all work alike. However, the basics are shared: </p> <ul> <li>They create a "shadow" table with altered schema</li> <li>They create and use triggers to propagate changes from original table to ghost table</li> <li>They <em>slowly</em> copy all the rows from your table to shadow table. They do so in chunks: say, 1,000 rows at a time. </li> <li>They do all the above while you are still able to access and manipulate the original table.</li> <li>When satisfied, they swap the two, using a <code>RENAME</code>.</li> </ul> <p>The <em>openark-kit</em> tool has been in use for 3.5 years now. The Percona tool is a few months old, but possibly more tested then the former. Facebook's tool is said to work well for Facebook, but does not provide with a general solution to the average user. I haven't used it myself.</p> <p><strong>Edit 2016:</strong> <code>gh-ost</code> is a triggerless solution, which significantly reduces master write-load on the master, decoupling the migration write load from the normal load. It is auditable, controllable, testable. We've developed it internally at GitHub and released it as open source; we're doing all our production migrations via <code>gh-ost</code> today. See more <a href="http://githubengineering.com/gh-ost-github-s-online-migration-tool-for-mysql/" rel="noreferrer">here</a>.</p> <p>Each tool has its own limitations, look closely at documentation.</p> <h3>The conservative way</h3> <p>The conservative way is to use an Active-Passive Master-Master replication, do the <code>ALTER</code> on the standby (passive) server, then switch roles and do the <code>ALTER</code> again on what used to be the active server, now turned passive. This is also a good option, but requires an additional server, and deeper knowledge of replication.</p>
11,121,613
Casting object to array - any magic method being called?
<p>I have an object of class Foo:</p> <pre><code>class Foo extends Bar { protected $a; protected $b; } $obj = new Foo(); </code></pre> <p>What I want (and have) to do is cast this object to an array, like this:</p> <pre><code>$arr = (array)$obj; </code></pre> <p>Is there any magic (or not magic :)) method that is being called at this moment? Or is there any other way to intercept it? I know I can write a simple method, eg. <code>asArray()</code> in Foo, but I'm looking for some more "native" PHP ways.</p>
11,121,630
6
0
null
2012-06-20 14:16:52.497 UTC
4
2016-12-28 16:41:31.74 UTC
null
null
null
null
1,469,483
null
1
44
php|arrays|object|casting
35,658
<p>You can have the class implement the <a href="http://us2.php.net/manual/en/class.arrayaccess.php" rel="noreferrer"><code>ArrayAccess</code></a> interface. This will allow you to treat the object like an array without casting and you get total control over how the members are used.</p>
11,428,427
"No module named simple" error in Django
<pre><code>ImportError at / No module named simple Django Version: 1.5.dev20120710212642 </code></pre> <p>I installed latest django version. I am using </p> <pre><code>from django.views.generic.simple import redirect_to </code></pre> <p>in my urls.py. What is wrong? Is it deprecated?</p>
11,429,714
4
0
null
2012-07-11 08:20:43.263 UTC
23
2015-02-12 10:50:52.973 UTC
null
null
null
null
594,781
null
1
65
django
35,653
<p>Use <a href="https://docs.djangoproject.com/en/1.4/topics/class-based-views/#class-based-generic-views" rel="noreferrer">class-based views</a> instead of <code>redirect_to</code> as these function-based generic views have been deprecated.</p> <p>Here is simple example of class-based views usage</p> <pre><code>from django.conf.urls import patterns, url, include from django.views.generic import TemplateView urlpatterns = patterns('', (r'^about/', TemplateView.as_view(template_name="about.html")), ) </code></pre> <p><strong>Update</strong></p> <p>If someone wants to redirect to a URL, Use <a href="https://docs.djangoproject.com/en/1.4/ref/class-based-views/#django.views.generic.base.RedirectView" rel="noreferrer">RedirectView</a>.</p> <pre><code>from django.views.generic import RedirectView urlpatterns = patterns('', (r'^one/$', RedirectView.as_view(url='/another/')), ) </code></pre>
11,205,020
How can I detect which layout is selected by Android in my application?
<p>Assume I have an activity with three different layouts in different resource folders. For example:</p> <blockquote> <p><code>layout-land/my_act.xml</code><br> <code>layout-xlarge/my_act.xml</code><br> <code>layout-xlarge-land/my_act.xml</code><br></p> </blockquote> <p>In different devices and different positions one of them is selected by Android.<br>How can I find out which one is selected <em>programmatically</em>?</p> <p>Does Android have any API that returns these layouts to the program?</p> <hr> <p><strong>Edit</strong>: <a href="https://stackoverflow.com/a/11205220/779408">Graham Borland's solution</a> has a problem in some situations that I mentioned in the comments.</p>
11,670,441
8
5
null
2012-06-26 10:08:06.787 UTC
36
2013-11-24 13:52:43.76 UTC
2017-05-23 10:31:17.15 UTC
null
-1
null
779,408
null
1
71
android|android-layout|resources
27,653
<p>You could create a <code>values-&lt;config&gt;</code> directory for each of your supported configurations. Inside of each of those directories, create a <code>strings.xml</code> with a single <code>selected_configuration</code> string which describes the current configuration. At runtime, fetch the string using the standard <code>getString</code> method, which will do the configuration resolution for you and return the correct string for the configuration. This is untested.</p>
11,361,985
Output data from all columns in a dataframe in pandas
<p>I have a csv file with the name <code>params.csv</code>. I opened up <code>ipython qtconsole</code> and created a pandas <code>dataframe</code> using:</p> <pre><code>import pandas paramdata = pandas.read_csv('params.csv', names=paramnames) </code></pre> <p>where, <code>paramnames</code> is a python list of string objects. Example of <code>paramnames</code> (the length of actual list is 22):</p> <pre><code>paramnames = ["id", "fc", "mc", "markup", "asplevel", "aspreview", "reviewpd"] </code></pre> <p>At the ipython prompt if I type <code>paramdata</code> and press enter then I do not get the dataframe with columns and values as shown in examples on <a href="http://pandas.sourceforge.net/indexing.html#additional-column-access" rel="noreferrer">Pandas website</a>. Instead, I get information about the dataframe. I get:</p> <pre><code>In[35]: paramdata Out[35]: &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 59 entries, 0 to 58 Data columns: id 59 non-null values fc 59 non-null values mc 59 non-null values markup 59 non-null values asplevel 59 non-null values aspreview 59 non-null values reviewpd 59 non-null values </code></pre> <p>If I type <code>paramdata['mc']</code> then I do get the values as expected for the <code>mc</code> column. I have two questions:</p> <p>(1) In the examples on the pandas website (see, for example, the output of <code>df</code> here: <a href="http://pandas.sourceforge.net/indexing.html#additional-column-access" rel="noreferrer">http://pandas.sourceforge.net/indexing.html#additional-column-access</a>) typing the name of the dataframe gives the actual data. Why am I getting information about the dataframe as shown above instead of the actual data? Do I need to set some output options somewhere?</p> <p>(2) How do I output all columns in the dataframe to the screen without having to type their names, i.e., without having to type something like <code>paramdata[['id','fc','mc']]</code>. </p> <p>I am using pandas version 0.8. </p> <p>Thank you.</p>
11,362,056
7
0
null
2012-07-06 12:12:49.907 UTC
38
2019-01-30 06:44:42.4 UTC
2019-01-21 20:36:10.433 UTC
null
4,909,087
null
316,357
null
1
129
python|pandas
281,797
<p>There is too much data to be displayed on the screen, therefore a summary is displayed instead.</p> <p>If you want to output the data anyway (it won't probably fit on a screen and does not look very well):</p> <pre><code>print paramdata.values </code></pre> <p>converts the dataframe to its numpy-array matrix representation.</p> <pre><code>paramdata.columns </code></pre> <p>stores the respective column names and</p> <pre><code>paramdata.index </code></pre> <p>stores the respective index (row names).</p>
12,793,577
How to control number of minor grid lines in ggplot2?
<p>By default, it seems that ggplot2 uses a minor grid that is just half of the major grid. Is there any way to to break this up?</p> <p>For example, I have a plot where the x-axis is years, and the major breaks are (1850, 1900, 1950, 2000). This means the minor grid points are at (1875, 1925, 1975), which is a little unintuitive for years. How can I make the minor grid appear at every decade?</p>
12,793,752
1
4
null
2012-10-09 05:50:22.317 UTC
8
2012-10-09 06:13:22.06 UTC
null
null
null
null
210,945
null
1
52
r|ggplot2
67,577
<p>You do it by explicitly specifying <code>minor_breaks()</code> in the <code>scale_x_continuous</code>. Note that since I did not specify <code>panel.grid.major</code> in my trivial example below, the two plots below don't have those (but you should add those in if you need them). To solve your issue, you should specify the years either as a sequence or just a vector of years as the argument for <code>minor_breaks()</code>.</p> <p>e.g. </p> <pre><code> ggplot(movies, aes(x=rating)) + geom_histogram() + theme(panel.grid.minor = element_line(colour="blue", size=0.5)) + scale_x_continuous(minor_breaks = seq(1, 10, 1)) </code></pre> <p><img src="https://i.stack.imgur.com/APC6V.png" alt="enter image description here"></p> <pre><code> ggplot(movies, aes(x=rating)) + geom_histogram() + theme(panel.grid.minor = element_line(colour="blue", size=0.5)) + scale_x_continuous(minor_breaks = seq(1, 10, 0.5)) </code></pre> <p><img src="https://i.stack.imgur.com/k0Nvp.png" alt="enter image description here"></p>
30,542,095
Mailer Error: SMTP connect() failed in php mailer( https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting)
<p>Here is code for sending email from localhost after i referred a lot from online.</p> <p>html form:</p> <pre><code>&lt;form method=&quot;post&quot; action=&quot;email.php&quot;&gt; Email: &lt;input name=&quot;email&quot; id=&quot;email&quot; type=&quot;text&quot; /&gt;&lt;br /&gt; Message:&lt;br /&gt; &lt;textarea name=&quot;message&quot; id=&quot;message&quot; rows=&quot;15&quot; cols=&quot;40&quot;&gt;&lt;/textarea&gt;&lt;br /&gt; &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt; &lt;/form&gt; </code></pre> <p>email.php:</p> <pre><code>&lt;?php // $email and $message are the data that is being // posted to this page from our html contact form $email = $_REQUEST['email'] ; $message = $_REQUEST['message'] ; require_once('class.phpmailer.php'); require 'PHPMailerAutoload.php'; require 'class.smtp.php'; $mail = new PHPMailer(); $body='hellooooo'; $mail-&gt;IsSMTP(); $mail-&gt;Host = &quot;ssl://smtp.gmail.com&quot;; // specify main and backup server $mail-&gt;SMTPAuth = true; // turn on SMTP authentication $mail-&gt;Username = &quot;[email protected]&quot;; // SMTP username $mail-&gt;Password = &quot;zzz&quot;; // SMTP password $mailer-&gt;SMTPSecure = 'ssl'; $mailer-&gt;Port = 465;//587; $mail-&gt;AddAddress(&quot;xxx&quot;, &quot;xx&quot;); $mail-&gt;SetFrom('[email protected]','xxxx'); $mail-&gt;WordWrap = 50; $mail-&gt;IsHTML(true); $mail-&gt;Subject = &quot;You have received feedback from your website!&quot;; $mail-&gt;MsgHTML($body); if(!$mail-&gt;Send()) { echo &quot;Message could not be sent. &lt;p&gt;&quot;; echo &quot;Mailer Error: &quot; . $mail-&gt;ErrorInfo; exit; } echo &quot;Message has been sent&quot;; ?&gt; </code></pre> <p>so when i run my code it shows error like this,</p> <blockquote> <p>Message could not be sent.</p> <p>Mailer Error: SMTP connect() failed. <a href="https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting" rel="nofollow noreferrer">https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting</a></p> </blockquote> <p>And i removed semicolon in this line <code>;extension=php_openssl.dll</code> from the following files, and restart the xampp.</p> <pre><code>c/xampp/apache/bin/php.ini and c/xampp/php/php.ini </code></pre> <p>still stays same error..</p> <p><strong>Note:</strong> I m new to php, but i want to know particular this one and fix the problem. and I referred similar questions in stack, but it didn't help me,</p> <p>Can anybody help me to fix this?</p> <p>Thanks,</p>
30,542,230
1
13
null
2015-05-30 04:00:34.737 UTC
1
2015-05-30 04:26:34.917 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
4,773,326
null
1
4
php|email|phpmailer
65,848
<p>It looks like your credentials for connecting to your authentication has failed. I often send mail from my local and I found it that it's a LOT easier to use another SMTP than gmail, like <a href="https://mandrillapp.com/login/?referrer=%2F" rel="nofollow">mandrillapp</a>, free until 12,000 mails. There are a lot of things that I don't understand in your code so I will share mine.</p> <pre><code>&lt;?php require 'PHPMailer-master/PHPMailerAutoload.php'; $mail = new PHPMailer; //$mail-&gt;SMTPDebug = 3; // Enable verbose debug output $mail-&gt;isSMTP(); // Set mailer to use SMTP $mail-&gt;Host = 'smtp.mandrillapp.com'; // Specify main and backup SMTP servers $mail-&gt;SMTPAuth = true; // Enable SMTP authentication $mail-&gt;Username = '[email protected]'; // SMTP username $mail-&gt;Password = 'mandrilapp_will_give_you_a_password'; // SMTP password $mail-&gt;Port = 587; // TCP port to connect to $mail-&gt;From = '[email protected]'; $mail-&gt;FromName = 'Test phpmailer'; $mail-&gt;addAddress('[email protected]'); // Name is optional $mail-&gt;isHTML(true); // Set email format to HTML $mail-&gt;Subject = 'Here is the subject'; $mail-&gt;Body = 'This is the HTML message body &lt;b&gt;in bold!&lt;/b&gt;'; $mail-&gt;AltBody = 'This is the body in plain text for non-HTML mail clients'; if(!$mail-&gt;send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail-&gt;ErrorInfo; } else { echo 'Message has been sent'; } </code></pre> <p>Be sure to have PHPMailer-master folder (you can download it from <a href="https://github.com/PHPMailer/PHPMailer" rel="nofollow">here</a>) at the same level as your php file. This is how I link phpmailer. Hope it helps, if you have any questions, ask me!</p>
30,614,396
What does i = (i, ++i, 1) + 1; do?
<p>After reading <a href="https://stackoverflow.com/a/4176333/2411320">this answer</a> about undefined behavior and sequence points, I wrote a small program:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { int i = 5; i = (i, ++i, 1) + 1; printf(&quot;%d\n&quot;, i); return 0; } </code></pre> <p>The output is <code>2</code>. Oh God, I didn't see the decrement coming! What is happening here?</p> <p>Also, while compiling the above code, I got a warning saying:</p> <blockquote> <p>px.c:5:8: warning: left-hand operand of comma expression has no effect<br></p> <pre><code> [-Wunused-value] i = (i, ++i, 1) + 1; ^ </code></pre> </blockquote> <p>Why? But probably it will be automatically answered by the answer of my first question.</p>
30,614,442
7
28
null
2015-06-03 08:12:28.857 UTC
26
2017-03-17 18:15:35.583 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,411,320
null
1
174
c|operators|expression|compiler-warnings|comma-operator
17,659
<p>In the expression <code>(i, ++i, 1)</code>, the comma used is the <a href="http://en.wikipedia.org/wiki/Comma_operator">comma operator</a> </p> <blockquote> <p>the comma operator (represented by the token <code>,</code>) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). </p> </blockquote> <p>Because it discards its first operand, it is generally <strong>only useful where the first operand has desirable side effects</strong>. If the side effect to the first operand does not takes place, then the compiler may generate warning about the expression with no effect. </p> <p>So, in the above expression, the leftmost <code>i</code> will be evaluated and its value will be discarded. Then <code>++i</code> will be evaluated and will increment <code>i</code> by 1 and again the value of the expression <code>++i</code> will be discarded, <em>but the side effect to <code>i</code> is permanent</em>. Then <code>1</code> will be evaluated and the value of the expression will be <code>1</code>. </p> <p>It is equivalent to </p> <pre><code>i; // Evaluate i and discard its value. This has no effect. ++i; // Evaluate i and increment it by 1 and discard the value of expression ++i i = 1 + 1; </code></pre> <p>Note that <strong>the above expression is perfectly valid and does not invoke undefined behavior</strong> because there is a <a href="http://en.wikipedia.org/wiki/Sequence_point">sequence point</a> between the evaluation of the left and right operands of the comma operator.</p>
17,081,753
How do i request mic record permission from user
<p>I am using the new iOS7 developer SDK and now the app request from the user his permission to record from mic when the App try to record in the first time. <img src="https://i.stack.imgur.com/bPsjB.png" alt="enter image description here"></p> <p>My App will record after a countdown,so the user can't see this request. I use this code to check the <code>requestRecordPermission</code>:</p> <pre><code>[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) { if (granted) { // Microphone enabled code } else { // Microphone disabled code } }]; </code></pre> <p>But how can i trigger the request by myself before i start to record ?</p>
17,081,770
6
1
null
2013-06-13 07:42:53.18 UTC
9
2020-01-26 17:00:47.903 UTC
2013-09-29 09:15:17.777 UTC
user2110287
null
user2110287
null
null
1
23
objective-c|ios7|xcode5
39,142
<p>In the new iOS7 it's very simple try this:</p> <pre><code>if([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission)]) { [[AVAudioSession sharedInstance] requestRecordPermission]; } </code></pre>
16,795,548
Rotate and translate
<p>I'm having some problems rotating and positioning a line of text. Now it's just position that works. The rotation also works, but only if I disable the positioning.</p> <p>CSS:</p> <pre><code>#rotatedtext { transform-origin: left; transform: rotate(90deg); transform: translate(50%, 50%); } </code></pre> <p>The html is just plain text.</p>
16,801,578
4
0
null
2013-05-28 15:12:32.233 UTC
17
2021-07-17 08:58:33.877 UTC
2021-07-17 08:58:33.877 UTC
null
4,284,627
null
2,428,972
null
1
120
css|webkit|transform|css-transforms
181,781
<p>The reason is because you are using the transform property twice. Due to CSS rules with the cascade, the last declaration wins if they have the same specificity. As both transform declarations are in the same rule set, this is the case.</p> <p>What it is doing is this:</p> <ol> <li>rotate the text 90 degrees. Ok.</li> <li>translate 50% by 50%. Ok, this is same property as step one, so do this step and ignore step 1.</li> </ol> <p>See <a href="http://jsfiddle.net/Lx76Y/" rel="noreferrer">http://jsfiddle.net/Lx76Y/</a> and open it in the debugger to see the first declaration overwritten</p> <p>As the translate is overwriting the rotate, you have to combine them in the same declaration instead: <a href="http://jsfiddle.net/Lx76Y/1/" rel="noreferrer">http://jsfiddle.net/Lx76Y/1/</a></p> <p>To do this you use a space separated list of transforms:</p> <pre><code>#rotatedtext { transform-origin: left; transform: translate(50%, 50%) rotate(90deg) ; } </code></pre> <p>Remember that they are specified in a chain, so the translate is applied first, then the rotate after that.</p>
20,883,404
Javascript: Returning the last word in a string
<p>right to it:</p> <p>I have a <code>words</code> string which has two words in it, and i need to return the last word. They are seperated by a " ". How do i do this?</p> <pre><code>function test(words) { var n = words.indexOf(" "); var res = words.substring(n+1,-1); return res; } </code></pre> <p>I've been told to use <code>indexOf</code> and <code>substring</code> but it's not required. Anyone have an easy way to do this? (with or without <code>indexOf</code> and <code>substring</code>)</p>
20,883,492
11
7
null
2014-01-02 12:50:25.757 UTC
13
2022-02-20 08:07:59.547 UTC
2014-08-03 05:41:49.26 UTC
null
1,903,116
null
3,153,403
null
1
58
javascript|string|substring
93,661
<p>Try this:</p> <p>you can use words with n word length.</p> <p>example:</p> <pre><code> words = "Hello World"; words = "One Hello World"; words = "Two Hello World"; words = "Three Hello World"; </code></pre> <p>All will return same value: "World"</p> <pre><code>function test(words) { var n = words.split(" "); return n[n.length - 1]; } </code></pre>