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
493,210
Linux cross-compilation for ARM architecture
<p>I am interested in cross-compiling a Linux kernel for an ARM target on a x86 host. Are there some good practices you recommend? Which is the best cross-compile suite in your opinion? Have you settled up a custom cross-compile environment? If yes, what advices do you have? Is it a good idea?</p>
496,047
7
1
null
2009-01-29 20:16:28.537 UTC
23
2015-03-20 16:32:57.713 UTC
2013-10-22 08:13:40.56 UTC
null
321,731
Myrrdyn
21,550
null
1
20
linux|embedded|x86|arm
33,068
<p>There are two approaches I've used for ARM/Linux tools. The easiest is to download a pre-built tool chain directly.<br> <strong>Pro</strong>: It just works and you can get on with the interesting part of your project<br> <strong>Con</strong>: You are stuck with whichever version of gcc/binutils/libc they picked</p> <p>If the later matters to you, check out <a href="http://crosstool-ng.org/" rel="nofollow noreferrer">crosstool-ng</a>. This project is a configuration tool similar to the Linux kernel configuration application. Set which versions of gcc, binutils, libc (GNU or uCLibc), threading, and Linux kernel to build and crosstool-ng does the rest (i.e. downloads the tar balls, configures the tools, and builds them).<br> <strong>Pro</strong>: You get exactly what you selected during the configuration<br> <strong>Con</strong>: You get exactly what you selected during the configuration</p> <p>meaning you take on full responsibility for the choice of compiler/binutil/libc and their associated features/shortcomings/bugs. Also, as mentioned in the comments, there is some "pain" involved in selecting the versions of binutils, C library etc. as not all combinations necessarily work together or even build.</p> <p>One hybrid approach might be to start with the pre-built tools and replace them later with a custom solution via crosstool-ng if necessary.</p> <p><strong>Update</strong>: The answer originally used the <a href="http://www.codesourcery.com/gnu_toolchains/arm" rel="nofollow noreferrer">CodeSourcery tools</a> as an example of a pre-built tool chain. The CodeSourcery tools for ARM were free to <a href="http://www.mentor.com/embedded-software/sourcery-tools/sourcery-codebench/editions/lite-edition/" rel="nofollow noreferrer">download from Mentor Graphics</a>, but they are now called the Sourcery CodeBench and must be purchased from Mentor Graphics. Other options now include <a href="http://www.linaro.org/downloads/" rel="nofollow noreferrer">Linaro</a> as well as distribution specific tools from Android, Ubuntu, and others.</p>
501,653
Java: What's the difference between autoboxing and casting?
<p><a href="https://stackoverflow.com/questions/501412/why-does-autoboxing-make-some-calls-ambiguous-in-java">This question</a> is about "Why does autoboxing make some calls ambiguous in Java?"</p> <p>But reading through the answers, there are a number of references to casting and I'm not sure I completely understand the difference.</p> <p>Can someone provide a simple explanation?</p>
501,668
7
1
null
2009-02-01 21:53:39.12 UTC
14
2013-09-10 09:17:57.297 UTC
2017-05-23 12:33:54.993 UTC
Ray Booysen
-1
nzpcmad
9,922
null
1
26
java|casting|autoboxing
33,656
<p>Boxing is when you convert a primitive type to a reference type, un-boxing is the reverse. Casting is when you want one type to be treated as another type, between primitive types and reference types this means an implicit or explicit boxing operation. Whether it needs to be explicit is a language feature. </p>
804,926
Make outer div be automatically the same height as its floating content
<p>I want the outer <code>div</code>, which is black to wrap its <code>div</code>s floating within it. I dont want to use <code>style='height: 200px</code> in the <code>div</code> with the <code>outerdiv</code> id as I want it to be automatically the height of its content (eg, the floating <code>div</code>s).</p> <pre><code>&lt;div id='outerdiv' style='border: 1px solid black;background-color: black;'&gt; &lt;div style='width=300px;border: red 1px dashed;float: left;'&gt; &lt;p&gt;xxxxxxxxxxxxxxxxxxxxxxxxxxxxx&lt;/p&gt; &lt;/div&gt; &lt;div style='width=300px;border: red 1px dashed;float: right;'&gt; &lt;p&gt;zzzzzzzzzzzzzzzzzzzzzzzzzzzzz&lt;/p&gt; &lt;/div&gt; </code></pre> <p></p> <p>How to achieve this?</p>
804,936
7
0
null
2009-04-30 00:41:09.18 UTC
19
2013-10-22 01:12:19.757 UTC
2012-08-10 01:17:18.43 UTC
null
31,671
null
97,464
null
1
95
css|html|css-float
106,431
<p>You can set the <code>outerdiv</code>'s CSS to this</p> <pre><code>#outerdiv { overflow: hidden; /* make sure this doesn't cause unexpected behaviour */ } </code></pre> <p>You can also do this by adding an element at the end with <code>clear: both</code>. This can be added normally, with JS (not a good solution) or with <code>:after</code> CSS pseudo element (not widely supported in older IEs). </p> <p>The problem is that containers won't naturally expand to include floated children. Be warned with using the first example, if you have any children elements outside the parent element, they will be hidden. You can also use 'auto' as the property value, but this will invoke scrollbars if any element appears outside.</p> <p>You can also try floating the parent container, but depending on your design, this may be impossible/difficult.</p>
830,855
What Regex would capture everything from ' mark to the end of a line?
<p>I have a text file that denotes remarks with a single <code>'</code>. </p> <p>Some lines have two quotes but I need to get everything from the first instance of a <code>'</code> and the line feed.</p> <pre><code>I AL01 ' A-LINE '091398 GDK 33394178 402922 0831850 ' '091398 GDK 33394179 I AL02 ' A-LINE '091398 GDK 33394180 400722 0833118 ' '091398 GDK 33394181 I A10A ' A-LINE 102 ' 53198 DJ 33394182 395335 0832203 ' ' 53198 DJ 33394183 I A10B ' A-LINE 102 ' 53198 DJ 3339418 </code></pre>
830,887
7
0
null
2009-05-06 17:52:49.18 UTC
27
2019-10-24 18:58:02.653 UTC
2016-05-15 23:34:37.817 UTC
null
3,541,881
null
38,349
null
1
161
regex
269,606
<pre><code>'.* </code></pre> <p>I believe you need the option, Multiline.</p>
800,940
How to implement 'undo' operation in .net windows application?
<p>Assume that, a win form has certain input fields and user enters/re-enters some data.</p> <p>How to retain data previously entered by 'undo' operation?</p> <p>Just I want to know the best way to accomplish it.</p>
801,985
9
0
null
2009-04-29 05:00:10.75 UTC
12
2010-09-30 09:17:01.737 UTC
2010-01-05 17:17:41.353 UTC
null
184,528
null
53,262
null
1
12
.net|winforms|undo-redo
6,957
<p>There are a few options. The important thing is that you start designing it in early in the project. Trying to add it to an existing project can be <em>very</em> expensive if it wasn't designed with this capability in mind.</p> <p>There are a few fundamental patterns that you'll want to take advantage of:</p> <ol> <li><p><a href="http://en.wikipedia.org/wiki/Model-view-controller" rel="noreferrer">MVC</a> or <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="noreferrer">Observer</a> pattern. The first key isn't so much the religious or pattern-zealot implementation of your high-level architecture. What <em>is</em> important is that your software recognizes the difference between its current state and the displayed state, and decouples appropriately. There needs to be a common, clearly-defined coupling between your visual state and your application state. This provides you with the common architecture you need to create a command (see #2).</p> </li> <li><p>The <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="noreferrer">Command</a> pattern. You get a lot of quality with the command pattern (though it can come at the cost of some code that looks like it should be wizard-generated). The specific approach you take to the command pattern may vary (one class per command with implementation via overrides versus one class per many commands with implementation via event handlers, e.g.), but commands are the &quot;action&quot; class that @Ralph suggested structuring a stack around.</p> <p>This can be a bit tricky, but the general approach would be to listen for an event that would &quot;commit&quot; data from the visual state to the app state. The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx" rel="noreferrer"><code>Validated</code></a> event might be a good hook for a <code>Textbox</code>. The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.click.aspx" rel="noreferrer"><code>Click</code></a> event would make more sense for a <code>Button</code>. When that commit happens, you create the command associated with that control, you attempt to execute the command, and you add the command to your undo stack if the command completes successfully. Now you're tracking exactly what's happening and exactly the data it's happening with.</p> </li> <li><p>The <a href="http://en.wikipedia.org/wiki/Memento_pattern" rel="noreferrer">Memento</a> pattern. @JP Pulled out the last piece of the puzzle. You can use a memento on the saved command to store what the affected control's state was before the command executed. This, combined with an <code>UnExecute()</code> member on your command's interface, should be the last core piece of design you need to perform your task.</p> </li> </ol> <p>The nice thing about a structured approach like this is that you now have a natural extension point for additional behavior that needs to happen on a command-basis. Transactions are a natural fit, for example. In my current project, I'm using the WPF <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx" rel="noreferrer"><code>ICommand</code></a> interface (in my winforms project) to provide feedback about whether a given command <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.canexecute.aspx" rel="noreferrer"><code>CanExecute()</code></a> at any given time. This lets me enable and disable UI widgets appropriately in a purely command-driven way. :)</p> <p>The unfortunate thing is that there isn't a lot of support for this structure built-in to Winforms (as far as I know), so you'll need to build most of it from scratch. No single piece is particularly complicated, but you can find yourself generating a fair amount of mostly-boilerplate code for each command. It's also a pervasive design technique. For it to be effective, it has to be used consistently throughout the appropriate portions of the application. This makes retrofitting the functionality pretty expensive, especially if the original code is tightly coupled and incohesive.</p>
945,691
Automatically Print Image from Website
<p>A coworker and I were having a discussion about what is and isn't possible within the browser.</p> <p>Then a question came up that neither of us could answer with certainty. </p> <p>Can you create a webpage such that when you navigate to it, it engages the client-side printer and attempts to print a document. For instance, whenever you visit my personal website, you'll be treated to a print out of a picture of me, smiling. </p> <p>Now, this is a hideous idea. I'm aware. But the discussion intrigued me as to if it could be done, and how. My friend insisted that the best you could do was pop up the print dialog for the user, they would have to click print themselves. </p> <p>Would it be possible to bypass this step? Or just some fancy script to move the mouse over the print button and click on it? Or use an activeX control to interface with a Printer API directly?</p>
945,733
9
1
null
2009-06-03 16:25:16.713 UTC
9
2017-05-26 06:44:23.553 UTC
null
null
null
null
59,808
null
1
15
web-applications|printing
26,971
<p>You have to prompt the user to print the current page, there's no way to bypass this step (<em>possibly</em> in activeX for IE). That said, there's two different ways you could prompt the user to print images of you smiling when the page is loaded.</p> <p>Here's how to do it in JavaScript.</p> <pre><code>window.onload = function() { var img = window.open("me-smiling.png"); img.print(); } </code></pre> <p>And here's how to do it in css/javascript/html (assuming your picture has the <code>id</code> 'me-smiling'): CSS:</p> <pre><code>@media print { * { display:none; } img#me-smiling { display:block; } } </code></pre> <p>Javascript:</p> <pre><code> window.onload = function() { window.print() } </code></pre>
139,427
Which Coding convention to follow for PHP?
<p>Should I stick with Sun's Java code conventions for PHP code?</p>
139,453
9
0
null
2008-09-26 13:13:23.007 UTC
18
2016-09-18 14:39:37.273 UTC
2012-09-04 11:51:30.16 UTC
Prakash
896,872
Igor
4,235
null
1
29
php|coding-style
25,675
<p>For PHP, i'd suggest to follow <a href="http://framework.zend.com/manual/1.12/en/manual.html" rel="nofollow noreferrer">Zends suggestions</a></p> <p>As you might know, <a href="https://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why">Zend is the most widely used framework!</a></p>
1,105,765
Generating Fibonacci numbers in Haskell?
<p>In Haskell, how can I generate Fibonacci numbers based on the property that the nth Fibonacci number is equal to the (n-2)th Fibonacci number plus the (n-1)th Fibonacci number?</p> <p>I've seen this:</p> <pre><code>fibs :: [Integer] fibs = 1 : 1 : zipWith (+) fibs (tail fibs) </code></pre> <p>I don't really understand that, or how it produces an infinite list instead of one containing 3 elements.</p> <p>How would I write haskell code that works by calculating the actual definition and not by doing something really weird with list functions?</p>
1,105,840
12
4
null
2009-07-09 18:41:14.237 UTC
29
2022-01-28 08:40:29.597 UTC
2017-03-28 15:35:46.137 UTC
null
1,073,386
null
93,535
null
1
60
haskell|fibonacci
64,533
<p>Here's a different and simpler function that calculates the n'th Fibonacci number:</p> <pre><code>fib :: Integer -&gt; Integer fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) </code></pre> <p>The implementation you are referring to relays on some observations about how values in Fibonacci relate to each other (and how Haskell can define data structures in terms of themselfs in effect creating infinite data structures)</p> <p>The function in your question works like this:</p> <p>Assume you already had an infinite list of the Fibonacci numbers:</p> <pre><code> [ 1, 1, 2, 3, 5, 8, 13, .... ] </code></pre> <p>The <code>tail</code> of this list is</p> <pre><code> [ 1, 2, 3, 5, 8, 13, 21, .... ] </code></pre> <p><code>zipWith</code> combines two lists element by element using the given operator:</p> <pre><code> [ 1, 1, 2, 3, 5, 8, 13, .... ] + [ 1, 2, 3, 5, 8, 13, 21, .... ] = [ 2, 3, 5, 8, 13, 21, 34, .... ] </code></pre> <p>So the infinite list of Fibonacci numbers can be calculated by prepending the elements <code>1</code> and <code>1</code> to the result of zipping the infinite list of Fibonacci numbers with the tail of the infinite list of Fibonacci numbers using the <code>+</code> operator.</p> <p>Now, to get the n'th Fibonacci number, just get the n'th element of the infinite list of Fibonacci numbers:</p> <pre><code>fib n = fibs !! n </code></pre> <p>The beauty of Haskell is that it doesn't calculate any element of the list of Fibonacci numbers until its needed.</p> <p>Did I make your head explode? :)</p>
1,328,723
How to generate a simple popup using jQuery
<p>I am designing a web page. When we click the content of div named mail, how can I show a popup window containing a label email and text box?</p>
1,329,605
12
1
null
2009-08-25 14:37:40.333 UTC
118
2020-11-25 04:36:48.247 UTC
2017-08-03 23:23:16.353 UTC
null
30,697
null
148,814
null
1
223
javascript|jquery|css|ajax|popup
749,935
<p>First the CSS - tweak this however you like:</p> <pre><code>a.selected { background-color:#1F75CC; color:white; z-index:100; } .messagepop { background-color:#FFFFFF; border:1px solid #999999; cursor:default; display:none; margin-top: 15px; position:absolute; text-align:left; width:394px; z-index:50; padding: 25px 25px 20px; } label { display: block; margin-bottom: 3px; padding-left: 15px; text-indent: -15px; } .messagepop p, .messagepop.div { border-bottom: 1px solid #EFEFEF; margin: 8px 0; padding-bottom: 8px; } </code></pre> <p>And the JavaScript:</p> <pre><code>function deselect(e) { $('.pop').slideFadeToggle(function() { e.removeClass('selected'); }); } $(function() { $('#contact').on('click', function() { if($(this).hasClass('selected')) { deselect($(this)); } else { $(this).addClass('selected'); $('.pop').slideFadeToggle(); } return false; }); $('.close').on('click', function() { deselect($('#contact')); return false; }); }); $.fn.slideFadeToggle = function(easing, callback) { return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback); }; </code></pre> <p>And finally the html:</p> <pre><code>&lt;div class="messagepop pop"&gt; &lt;form method="post" id="new_message" action="/messages"&gt; &lt;p&gt;&lt;label for="email"&gt;Your email or name&lt;/label&gt;&lt;input type="text" size="30" name="email" id="email" /&gt;&lt;/p&gt; &lt;p&gt;&lt;label for="body"&gt;Message&lt;/label&gt;&lt;textarea rows="6" name="body" id="body" cols="35"&gt;&lt;/textarea&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Send Message" name="commit" id="message_submit"/&gt; or &lt;a class="close" href="/"&gt;Cancel&lt;/a&gt;&lt;/p&gt; &lt;/form&gt; &lt;/div&gt; &lt;a href="/contact" id="contact"&gt;Contact Us&lt;/a&gt; </code></pre> <p><a href="http://jsfiddle.net/SRw67/" rel="noreferrer">Here is a jsfiddle demo and implementation.</a></p> <p>Depending on the situation you may want to load the popup content via an ajax call. It's best to avoid this if possible as it may give the user a more significant delay before seeing the content. Here couple changes that you'll want to make if you take this approach.</p> <p>HTML becomes:</p> <pre><code>&lt;div&gt; &lt;div class="messagepop pop"&gt;&lt;/div&gt; &lt;a href="/contact" id="contact"&gt;Contact Us&lt;/a&gt; &lt;/div&gt; </code></pre> <p>And the general idea of the JavaScript becomes:</p> <pre><code>$("#contact").on('click', function() { if($(this).hasClass("selected")) { deselect(); } else { $(this).addClass("selected"); $.get(this.href, function(data) { $(".pop").html(data).slideFadeToggle(function() { $("input[type=text]:first").focus(); }); } } return false; }); </code></pre>
1,242,033
PHP header redirect not working
<p>I know this has been covered before but I cannot find an answer to this,</p> <p>I have always used this;</p> <pre><code>header("Location: http://www.website.com/"); exit(); </code></pre> <p>This has always worked in my current project and all of a sudden it is not working in any of my browsers</p> <p>I would like to figure out the problem and fix it instead of using</p> <pre><code>echo "&lt;script type='text/javascript'&gt;window.top.location='http://website.com/';&lt;/script&gt;"; </code></pre> <p>I also have error reporting enabled and it shows no errors</p> <pre><code>// SET ERROR REPORTING error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE); ini_set('display_errors', TRUE); </code></pre> <p><strong>Any ideas why it will not work?</strong></p>
1,242,045
13
2
null
2009-08-06 23:18:14.177 UTC
6
2018-11-29 14:17:55.703 UTC
null
null
null
null
143,030
null
1
13
php|redirect
62,427
<p>Try:</p> <pre><code>error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE); flush(); header("Location: http://www.website.com/"); die('should have redirected by now'); </code></pre> <p>See what you get. You shouldn't use ^ (xor) in your error_reporting() call because you're unintentionally asking for all errors EXCEPT notices and warnings.. which is what a 'headers already sent' error is.</p> <p>Edit:</p> <p>Also try putting flush() right above your header() call. </p>
740,287
How to check if one of the following items is in a list?
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
740,294
14
1
null
2009-04-11 15:13:07.73 UTC
76
2022-07-14 07:43:11.74 UTC
2015-06-23 20:31:01.47 UTC
null
2,642,204
null
37,056
null
1
280
python
513,174
<pre><code>&gt;&gt;&gt; L1 = [2,3,4] &gt;&gt;&gt; L2 = [1,2] &gt;&gt;&gt; [i for i in L1 if i in L2] [2] &gt;&gt;&gt; S1 = set(L1) &gt;&gt;&gt; S2 = set(L2) &gt;&gt;&gt; S1.intersection(S2) set([2]) </code></pre> <p>Both empty lists and empty sets are False, so you can use the value directly as a truth value.</p>
950,751
How to implement a list fold in Java
<p>I have a List and want to reduce it to a single value (functional programming term "fold", Ruby term <code>inject</code>), like </p> <pre><code>Arrays.asList("a", "b", "c") ... fold ... "a,b,c" </code></pre> <p>As I am infected with functional programming ideas (Scala), I am looking for an easier/shorter way to code it than</p> <pre><code>sb = new StringBuilder for ... { append ... } sb.toString </code></pre>
29,099,630
14
4
null
2009-06-04 13:56:22.297 UTC
9
2021-02-12 01:59:10.987 UTC
2010-09-07 18:12:27.183 UTC
null
104,143
null
104,143
null
1
25
java|collections|functional-programming|folding
34,792
<p>What you are looking for is a string <code>join()</code> method which Java has since 8.0. Try one of the methods below.</p> <ol> <li><p>Static method <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-" rel="noreferrer"><code>String#join(delimiter, elements)</code></a>:</p> <pre><code>Collection&lt;String&gt; source = Arrays.asList("a", "b", "c"); String result = String.join(",", source); </code></pre></li> <li><p><a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html" rel="noreferrer">Stream</a> interface supports a fold operation very similar to Scala’s <code>foldLeft</code> function. Take a look at the following concatenating <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html" rel="noreferrer">Collector</a>:</p> <pre><code>Collection&lt;String&gt; source = Arrays.asList("a", "b", "c"); String result = source.stream().collect(Collectors.joining(",")); </code></pre> <p>You may want to statically import <code>Collectors.joining</code> to make your code clearer.</p> <p>By the way this collector can be applied to collections of any particular objects:</p> <pre><code>Collection&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3); String result = numbers.stream() .map(Object::toString) .collect(Collectors.joining(",")); </code></pre></li> </ol>
4,973
Setting a div's height in HTML with CSS
<p>I am trying to lay out a table-like page with two columns. I want the rightmost column to dock to the right of the page, and this column should have a distinct background color. The content in the right side is almost always going to be smaller than that on the left. I would like the div on the right to always be tall enough to reach the separator for the row below it. How can I make my background color fill that space?</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-css lang-css prettyprint-override"><code>.rightfloat { color: red; background-color: #BBBBBB; float: right; width: 200px; } .left { font-size: 20pt; } .separator { clear: both; width: 100%; border-top: 1px solid black; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="separator"&gt; &lt;div class="rightfloat"&gt; Some really short content. &lt;/div&gt; &lt;div class="left"&gt; Some really really really really really really really really really really big content &lt;/div&gt; &lt;/div&gt; &lt;div class="separator"&gt; &lt;div class="rightfloat"&gt; Some more short content. &lt;/div&gt; &lt;div class="left"&gt; Some really really really really really really really really really really big content &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p>Edit: I agree that this example is very table-like and an actual table would be a fine choice. But my "real" page will eventually be less table-like, and I'd just like to first master this task!</p> <p>Also, for some reason, when I create/edit my posts in IE7, the code shows up correctly in the preview view, but when I actually post the message, the formatting gets removed. Editing my post in Firefox 2 seems to have worked, FWIW.</p> <hr> <p>Another edit: Yeah, I unaccepted GateKiller's answer. It does indeed work nicely on my simple page, but not in my actual heavier page. I'll investigate some of the links y'all have pointed me to.</p>
5,103
14
0
null
2008-08-07 17:02:23.413 UTC
7
2019-06-02 14:46:57.467 UTC
2016-11-30 09:31:39.41 UTC
Chris Farmer
2,571,493
null
404
null
1
39
html|css
175,590
<p>Ahem...</p> <blockquote> <p>The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page.</p> </blockquote> <p>Actually, 100% height will not work in most design situations - this may be short but it is not a good answer. Google "any column longest" layouts. The best way is to put the left and right cols inside a wrapper <code>div</code>, float the left and right cols and then float the wrapper - this makes it stretch to the height of the inner containers - then set background image on the outer wrapper. But watch for any horizontal margins on the floated elements in case you get the IE "double margin float bug".</p>
30,005
How do I fire an event when a iframe has finished loading in jQuery?
<p>I have to load a PDF within a page.</p> <p>Ideally I would like to have a loading animated gif which is replaced once the PDF has loaded.</p>
32,878
14
0
null
2008-08-27 12:52:29.927 UTC
29
2021-07-20 09:20:30.853 UTC
2011-12-12 04:07:51.09 UTC
Rob Cooper
31,671
Alex Andronov
3,168
null
1
97
javascript|jquery
185,782
<p>I'm pretty certain that it cannot be done.</p> <p>Pretty much anything else than PDF works, even Flash. (Tested on Safari, Firefox 3, IE 7)</p> <p>Too bad.</p>
24,849
Execute script after specific delay using JavaScript
<p>Is there any JavaScript method similar to the jQuery <code>delay()</code> or <code>wait()</code> (to delay the execution of a script for a specific amount of time)?</p>
24,852
15
0
null
2008-08-24 05:10:57.347 UTC
23
2022-04-28 12:25:47.53 UTC
2017-01-12 03:22:18.403 UTC
null
6,381,711
Niyaz
184
null
1
200
javascript|settimeout
475,282
<p>There is the following:</p> <pre><code>setTimeout(function, milliseconds); </code></pre> <p>function which can be passed the time after which the function will be executed.</p> <p>See: <a href="https://www.w3schools.com/jsref/met_win_settimeout.asp" rel="noreferrer">Window <code>setTimeout()</code> Method</a>.</p>
898,669
How can I detect if a file is binary (non-text) in Python?
<p>How can I tell if a file is binary (non-text) in Python?</p> <p>I am searching through a large set of files in Python, and keep getting matches in binary files. This makes the output look incredibly messy.</p> <p>I know I could use <code>grep -I</code>, but I am doing more with the data than what grep allows for.</p> <p>In the past, I would have just searched for characters greater than <code>0x7f</code>, but <code>utf8</code> and the like, make that impossible on modern systems. Ideally, the solution would be fast.</p>
898,723
21
7
null
2009-05-22 16:09:50.63 UTC
39
2022-08-25 10:50:16.063 UTC
2020-11-02 19:23:52.39 UTC
null
562,769
null
34,329
null
1
119
python|file|binary
90,679
<p>You can also use the <a href="https://docs.python.org/3/library/mimetypes.html" rel="nofollow noreferrer">mimetypes</a> module:</p> <pre class="lang-py prettyprint-override"><code>import mimetypes ... mime = mimetypes.guess_type(file) </code></pre> <p>It's fairly easy to compile a list of binary mime types. For example Apache distributes with a mime.types file that you could parse into a set of lists, binary and text and then check to see if the mime is in your text or binary list.</p>
318,630
Get the real width and height of an image with JavaScript? (in Safari/Chrome)
<p>I am creating a jQuery plugin.</p> <p>How do I get the real image width and height with Javascript in Safari?</p> <p>The following works with Firefox 3, IE7 and Opera 9:</p> <pre><code>var pic = $("img") // need to remove these in of case img-element has set width and height pic.removeAttr("width"); pic.removeAttr("height"); var pic_real_width = pic.width(); var pic_real_height = pic.height(); </code></pre> <p>But in Webkit browsers like Safari and Google Chrome values are 0.</p>
670,433
30
6
null
2008-11-25 19:44:38.617 UTC
127
2020-07-19 06:48:28.613 UTC
2020-01-24 20:58:53.237 UTC
null
2,499,852
Frank Bannister
27,623
null
1
280
javascript|jquery|safari|google-chrome|webkit
398,641
<p>Webkit browsers set the height and width property after the image is loaded. Instead of using timeouts, I'd recommend using an image's onload event. Here's a quick example:</p> <pre><code>var img = $("img")[0]; // Get my img elem var pic_real_width, pic_real_height; $("&lt;img/&gt;") // Make in memory copy of image to avoid css issues .attr("src", $(img).attr("src")) .load(function() { pic_real_width = this.width; // Note: $(this).width() will not pic_real_height = this.height; // work for in memory images. }); </code></pre> <p>To avoid any of the effects CSS might have on the image's dimensions, the code above makes an in memory copy of the image. This is a very clever solution suggested by <a href="https://stackoverflow.com/questions/318630#3192577">FDisk</a>.</p> <p>You can also use the <code>naturalHeight</code> and <code>naturalWidth</code> HTML5 attributes.</p>
6,382,669
Calendar control in asp.net c#
<p>I have a text box and a calendar in my ASP.NET web application.</p> <p>When I select any date in calendar, I would like the date/month/year of that date to be displayed in the text box.</p>
6,382,757
6
1
null
2011-06-17 07:29:53.703 UTC
1
2020-10-20 18:50:05.097 UTC
2020-10-20 18:50:05.097 UTC
null
2,756,409
null
788,902
null
1
3
c#|asp.net
70,815
<p>in .aspx file</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged"&gt; &lt;/asp:Calendar&gt; &lt;asp:TextBox ID="TextBox1" runat="server"&gt;&lt;/asp:TextBox&gt;&lt;/div&gt; &lt;/form&gt; </code></pre> <p>in .aspx.cs file</p> <pre><code>protected void Calendar1_SelectionChanged(object sender, EventArgs e) { TextBox1.Text = Calendar1.SelectedDate.ToString(); } </code></pre>
6,860,153
Exception when using FolderBrowserDialog
<p>I'm getting the following Exception when trying to use FolderBrowserDialog: <code>System.Threading.ThreadStateException: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.</code></p> <p>I have Googled this problem extensively and the solutions that everybody suggests seem to be to put <code>[STAThreadAttribute]</code> above the Main method, to delete all dll's from the Debug folder, or to use the <code>Invoke</code> method. I have tried all of these, and I still get the same exception.</p> <p>Here's the code:</p> <pre><code>public partial class Form1 : Form { public event EventHandler ChooseLocationHandler = null; public string DestFolder { set { textBox1.Text = value; } get { return textBox1.Text; } } public Form1() { InitializeComponent(); } private void ChooseLocationButton_Click(object sender, EventArgs e) { if (ChooseLocationHandler != null) ChooseLocationHandler(this, e); } } </code></pre> <p>And in my presenter is the following:</p> <pre><code>public partial class Presenter { Form1 myForm; public Presenter() { myForm = new Form1(); myForm.ChooseLocationHandler += ChooseLocationHandler; myForm.Show(); } public void ChooseLocationHandler(object obj, EventArgs e) { Form1 sender = (Form1)obj; FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.RootFolder = System.Environment.SpecialFolder.MyComputer; fbd.ShowNewFolderButton = true; if (fbd.ShowDialog() == DialogResult.Cancel) return; sender.DestFolder = fbd.SelectedPath; } } </code></pre> <p>I'm getting the Exception on fbd.ShowDialog().</p>
6,860,196
7
0
null
2011-07-28 13:57:42.07 UTC
8
2021-07-23 23:20:38.337 UTC
2011-07-28 14:06:54.677 UTC
null
864,027
null
864,027
null
1
31
c#|multithreading|exception|folderbrowserdialog
34,979
<p>A thread is either STA or MTA it can't be specified just for one method so the attribute must be present on the entry point.</p> <p>From <a href="http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx" rel="noreferrer"><code>STAThreadAttribute</code> in MSDN</a> :</p> <blockquote> <p>Apply this attribute to the entry point method (the Main() method in C# and Visual Basic). It has no effect on other methods.</p> </blockquote> <p>If this code is called from a secondary thread you have 3 choices :</p> <p><strong>IMPORTANT NOTE: Running (as you seem to do) System.Windows.Forms code inside an MTA thread is unwise, some functionalities like file open dialogs (not only folder) require a MTA thread to work.</strong></p> <h2>Changing your secondary thread apartment</h2> <p>If you create the thread yourself (and don't use the specificity of MTA) you could just change it's apartment before starting it :</p> <pre><code>var t = new Thread(...); t.SetApartmentState(ApartmentState.STA); </code></pre> <p>&nbsp;</p> <h2>Creating a thread just for it</h2> <p>If you don't control the thread creation you could do it in a temporary thread :</p> <pre><code>string selectedPath; var t = new Thread((ThreadStart)(() =&gt; { FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.RootFolder = System.Environment.SpecialFolder.MyComputer; fbd.ShowNewFolderButton = true; if (fbd.ShowDialog() == DialogResult.Cancel) return; selectedPath = fbd.SelectedPath; })); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); Console.WriteLine(selectedPath); </code></pre> <p>&nbsp;</p> <h2>Invoking in another(STA) thread</h2> <p>If your main thread also contain System.Windows.Forms code you could invoke in it's message loop to execute your code :</p> <pre><code>string selectedPath = null; Form f = // Some other form created on an STA thread; f.Invoke(((Action)(() =&gt; { FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.RootFolder = System.Environment.SpecialFolder.MyComputer; fbd.ShowNewFolderButton = true; if (fbd.ShowDialog() == DialogResult.Cancel) return; selectedPath = fbd.SelectedPath; })), null); Console.WriteLine(selectedPath); </code></pre>
6,548,157
How to write an ArrayList of Strings into a text file?
<p>I want to write an <code>ArrayList&lt;String&gt;</code> into a text file. </p> <p>The <code>ArrayList</code> is created with the code:</p> <pre><code>ArrayList arr = new ArrayList(); StringTokenizer st = new StringTokenizer( line, ":Mode set - Out of Service In Service"); while(st.hasMoreTokens()){ arr.add(st.nextToken()); } </code></pre>
6,548,204
7
5
null
2011-07-01 12:48:12.507 UTC
17
2019-06-25 19:27:55.6 UTC
2015-03-13 20:15:56.21 UTC
null
445,131
null
822,516
null
1
63
java
257,248
<pre><code>import java.io.FileWriter; ... FileWriter writer = new FileWriter("output.txt"); for(String str: arr) { writer.write(str + System.lineSeparator()); } writer.close(); </code></pre>
6,389,094
Adding same button to all view controllers in UINavigationController
<p>I have a <code>UINavigationController</code> (to use like a wizard page) which I create programmatically and I need to display a "Cancel" button to cancel the process in any <code>UIViewController</code>.</p> <p><b>Creating the <code>UINavigationController</code>:</b></p> <pre><code>FirstVC *firstVC = [[[FirstVC alloc] initWithNibName:@"FirstPage" bundle:nil] autorelease]; firstVC.delegate = self; navigationController = [[UINavigationController alloc] initWithRootViewController:firstVC]; [self.view addSubview:navigationController.view]; </code></pre> <p><b>Adding Cancel Button:</b></p> <pre><code>UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelRequestNewLeave:)]; navigationController.topViewController.navigationItem.rightBarButtonItem = cancelButton; [cancelButton release]; </code></pre> <p>But when I push a second page to <code>UINavigationController</code> the cancel button is not shown on the <code>UINavigationBar</code>. If I go back to first page, the cancel button is there. So, apparently the button is added only for the first view. I believe this is because I'm not subclassing <code>UINavigationController</code>, because I need to use it in a subview. But I don't know how to set the <code>rightBarButtonItem</code> in a <code>UINavigationController</code> which is created programmatically.</p> <pre><code>navigationController.topViewController.navigationItem.rightBarButtonItem = cancelButton; </code></pre> <p>Can someone shed a light on this?</p> <p>Thanks in advance.</p>
6,389,295
8
0
null
2011-06-17 16:53:08.153 UTC
11
2016-06-21 07:40:47.46 UTC
2015-03-12 12:54:45.197 UTC
null
4,536,708
null
724,480
null
1
30
iphone|ios|uinavigationcontroller
25,558
<p>The navigation item is per view controller. The navigation bar draws its contents from the navigation item of the view controller whose view it's currently framing, which corresponds to the view controller at the top of the navigation controller's stack.</p> <p>You basically need each view controller to stick a cancel button in its navigation item. You can do any of the following:</p> <ul> <li>Copy-paste the code into all relevant view controllers.</li> <li>Move the code into a utility function or class and call that.</li> <li>Create a common superclass for all relevant view controllers that handles setting up the cancel button for its subclasses.</li> </ul>
6,483,425
Prevent iPhone from zooming in on `select` in web-app
<p>I've got this code:</p> <pre><code>&lt;select&gt; &lt;option value="c"&gt;Klassen&lt;/option&gt; &lt;option value="t"&gt;Docenten&lt;/option&gt; &lt;option value="r"&gt;Lokalen&lt;/option&gt; &lt;option value="s"&gt;Leerlingen&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Running in a full-screen web-app on iPhone.</p> <p>When selecting something from this list, the iPhone zooms in on the <code>select</code>-element. And doesn't zoom back out after selecting something.</p> <p>How can I prevent this? Or zoom back out?</p>
13,468,469
12
0
null
2011-06-26 10:38:25.3 UTC
39
2021-05-27 11:03:54.84 UTC
2016-05-17 09:42:18.887 UTC
null
502,236
null
502,236
null
1
97
javascript|css|html|iphone-web-app
108,662
<p>It is probably because the browser is trying to zoom the area since the font size is less than the threshold, this generally happens in iphone.</p> <p>Giving a metatag attribute "user-scalable=no" will restrict the user from zooming elsewhere. Since the problem is with <strong>select</strong> element only, try using the following in your css, this hack is originally used for jquery mobile.</p> <p>HTML :</p> <pre><code>&lt;meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"&gt; </code></pre> <p>CSS:</p> <pre><code>select{ font-size: 50px; } </code></pre> <p>src: <a href="https://github.com/jquery/jquery-mobile/issues/2069" rel="noreferrer">unzoom after selecting in iphone</a></p>
6,879,427
Scala: write string to file in one statement
<p>For reading files in Scala, there is </p> <pre><code>Source.fromFile("file.txt").mkString </code></pre> <p>Is there an equivalent and concise way to write a string to file?</p> <p>Most languages support something like that. My favorite is Groovy:</p> <pre><code>def f = new File("file.txt") // Read def s = f.text // Write f.text = "file contents" </code></pre> <p>I'd like to use the code for programs ranging from a single line to a short page of code. Having to use your own library doesn't make sense here. I expect a modern language to let me write something to a file conveniently. </p> <p>There are posts similar to this, but they don't answer my exact question or are focused on older Scala versions.</p> <p>For example:</p> <ul> <li><a href="https://stackoverflow.com/questions/1284423/read-entire-file-in-scala">Read entire file in Scala?</a></li> <li><a href="https://stackoverflow.com/questions/4604237/how-to-write-to-a-file-in-scala">How to write to a file in Scala?</a></li> </ul>
30,577,743
17
7
null
2011-07-29 21:54:00.993 UTC
36
2022-06-05 19:26:47.793 UTC
2017-09-03 16:55:04.543 UTC
null
775,954
null
479,805
null
1
170
scala|scala-2.9
138,787
<p>A concise one line:</p> <pre><code>import java.io.PrintWriter new PrintWriter("filename") { write("file contents"); close } </code></pre>
41,511,973
Argument of '#selector' does not refer to an '@objc' method, property, or initializer
<p>I sublcassed in Swift 3 a <code>UIButton</code> subclass that is written in Objective-C.</p> <p>When I try to add a target, it fails with an error code:</p> <pre><code>class ActionButton: JTImageButton { func action() { } func configure()) { // ... self.addTarget(self, action: #selector(self.action()), for: .touchUpInside) // error: // Argument of '#selector' does not refer to an '@objc' method, property, or initializer } } </code></pre>
41,512,253
6
1
null
2017-01-06 18:26:42.257 UTC
5
2017-12-16 04:04:01.013 UTC
null
null
null
null
4,735,187
null
1
40
ios|objective-c|swift|cocoa-touch
66,793
<p>All you have to do is mark the func as <code>@objc</code> and there's no need for the <code>self</code> reference or the parenthesis</p> <pre><code>class ActionButton: JTImageButton { @objc func btnAction() { } func configure() { // ... self.addTarget(self, action: #selector(btnAction), for: .touchUpInside) // error: // Argument of '#selector' does not refer to an '@objc' method, property, or initializer } } </code></pre> <p>You can even make it <code>private</code> if you want</p>
15,571,267
Python: A4 size for a plot
<p>I have a code that saves a figure with:</p> <pre><code>savefig("foo.eps", orientation = 'portrait', format = 'eps') </code></pre> <p>If I don't specify anythingelse, the figure is correctly saved but when I print it, the figure fills only the half of a A4 sheet.If I modify the string as:</p> <pre><code>savefig("foo.eps", papertype = 'a4', orientation = 'portrait', format = 'eps') </code></pre> <p>Nothing chages! How can I set the size of the figure in a way that it fills the whole A4 sheet? Many thanks in advance.</p>
15,622,986
1
4
null
2013-03-22 13:13:55.32 UTC
8
2013-03-25 19:20:46.087 UTC
null
null
null
null
2,107,030
null
1
29
python|matplotlib
43,444
<p>Try to set the size of the figure (in inches) before you save it. You can do this when you initialize the figure by doing:</p> <pre><code>figure(figsize=(11.69,8.27)) # for landscape </code></pre> <p>or if the figure exists:</p> <pre><code>f = gcf() # f = figure(n) if you know the figure number f.set_size_inches(11.69,8.27) </code></pre> <p>or in advance for all plots, using</p> <pre><code>rc('figure', figsize=(11.69,8.27)) </code></pre>
15,717,754
How to autoplay a YouTube video in a UIWebView
<p>I have seen a lot of posts in here about this issue, but still couldn't find a perfect answer for this problem.</p> <p>So I have a tableview, and each cell has a play button inside it. When the user tap the play button, I add a <code>UIWebView</code> to this cell, and play a YouTube video. </p> <pre><code>static NSString *youTubeVideoHTML = @"&lt;html&gt;\ &lt;body style=\"margin:0;\"&gt;\ &lt;iframe class=\"youtube-player\" type=\"text/html\" width=\"%0.0f\" height=\"%0.0f\" src=\"http://www.youtube.com/embed/%@\" frameborder=\"0\"&gt;\ &lt;/iframe&gt;\ &lt;/body&gt;\ &lt;/html&gt;"; - (void)playVideoWithId:(NSString *)videoId { NSString *html = [NSString stringWithFormat:youTubeVideoHTML, self.frame.size.width, self.frame.size.height, videoId]; [self loadHTMLString:html baseURL:nil]; } </code></pre> <p><strong>The problem:</strong> </p> <p>This code doesn't actually play the video like I want, it just initiate the YouTube player and show it with the YouTube red play button. Only when user tap the red button, the video will start playing.<br> So user has to tap two buttons until the video starts - not the best user experience... </p> <p>Like I said I saw many posts about this issue, some not work at all, and some works but with some issues that bugs me. </p> <p>One of the working solutions I found was in <a href="https://stackoverflow.com/questions/9459711/detecting-uiwebview-finish-to-play-youtube-video-on-ipad">this post</a> by @ilias, he shows how to get this working with loading the HTML from a file (instead of a string like I do), problem with this approche is that for every video I play I need to:<br> load the htm file -> embed the video Id in it -> write the file to disc -> only now I can play the video. </p> <p>Strange thing is that this solution only work when you load the web view request from a file, if I try to load the request from a string equal to the file content, that doesn't work.</p>
15,721,703
5
5
null
2013-03-30 10:59:16.67 UTC
23
2016-02-10 19:19:34.54 UTC
2017-05-23 11:55:04.37 UTC
null
-1
null
954,267
null
1
34
ios|objective-c|youtube|uiwebview|youtube-api
41,334
<p>Apparently the problem was with the nil base url, when I changed it to resourceURL the autoplay worked.</p> <pre><code>[self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]]; </code></pre> <p>The full code for autoplay youtube videos (again this code mostly based on <a href="https://stackoverflow.com/questions/9459711/detecting-uiwebview-finish-to-play-youtube-video-on-ipad">this post</a> I just changed it to load from a string instead of a file): </p> <pre><code>static NSString *youTubeVideoHTML = @"&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;style&gt;body{margin:0px 0px 0px 0px;}&lt;/style&gt;&lt;/head&gt; &lt;body&gt; &lt;div id=\"player\"&gt;&lt;/div&gt; &lt;script&gt; var tag = document.createElement('script'); tag.src = \"http://www.youtube.com/player_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'%0.0f', height:'%0.0f', videoId:'%@', events: { 'onReady': onPlayerReady, } }); } function onPlayerReady(event) { event.target.playVideo(); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;"; - (void)playVideoWithId:(NSString *)videoId { NSString *html = [NSString stringWithFormat:youTubeVideoHTML, self.frame.size.width, self.frame.size.height, videoId]; [self loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]]; } </code></pre>
15,488,342
Binding inputs to an array of primitives using ngRepeat => uneditable inputs
<p>Here is a <a href="http://embed.plnkr.co/FrPul9VPj0UK90VDSqc4">demo</a> to my problem. </p> <pre><code>$scope.myNumbers = [10, 20, 30]; &lt;div ng-repeat="num in myNumbers"&gt;     &lt;input type="text" ng-model="num"&gt;     &lt;div&gt;current scope: {{num}}&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Can anyone explain to me why are the inputs uneditable/readonly? If it's by design, what's the rationale behind?</p> <p><strong>UPDATE 2/20/2014</strong></p> <p>It looks like this is no longer an issue for v1.2.0+ <a href="http://jsfiddle.net/grL95/">Demo</a>. But do keep in mind that although the user controls are now editable with the newer angularJS versions, it is the <code>num</code> property in the <strong><em>child scopes</em></strong>, not the parent scope, that get modified. In another words, modifying the values in the user controls does not affect the <code>myNumbers</code> array.</p>
15,490,942
5
4
null
2013-03-18 22:40:19.447 UTC
13
2014-02-20 19:23:55.16 UTC
2014-02-20 19:23:55.16 UTC
null
338,961
null
338,961
null
1
42
angularjs|angularjs-scope|angularjs-ng-repeat
59,601
<blockquote> <p>Can anyone explain to me why are the inputs uneditable/readonly? If it's by design, what's the rationale behind?</p> </blockquote> <p>It is by design, <a href="https://github.com/angular/angular.js/blob/master/CHANGELOG.md" rel="nofollow noreferrer">as of Angular 1.0.3</a>. Artem has a <a href="https://stackoverflow.com/a/13723990/215945">very good explanation</a> of how 1.0.3+ works when you "bind to each ng-repeat item directly" &ndash; i.e., </p> <pre><code>&lt;div ng-repeat="num in myNumbers"&gt; &lt;input type="text" ng-model="num"&gt; </code></pre> <p>When your page initially renders, here's a picture of your scopes (I removed one of the array elements, so the picture would have fewer boxes):</p> <p><a href="https://i.stack.imgur.com/kMfMZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kMfMZ.png" alt="enter image description here"></a> <sup><strong><em>(click to enlarge)</em></strong></sup></p> <p>Dashed lines show prototypical scope inheritance.<br> Gray lines show child &rarr; parent relationships (i.e., what <code>$parent</code> references).<br> Brown lines show $$nextSibling.<br> Gray boxes are primitive values. Blue boxes are arrays. Purple are objects.</p> <p>Note that the SO answer of mine that you referenced in a comment was written before 1.0.3 came out. Before 1.0.3, the <code>num</code> values in the ngRepeat child scopes would actually change when you typed into the text boxes. (These values would not be visible in the parent scope.) Since 1.0.3, ngRepeat now replaces the ngRepeat scope <code>num</code> values with the (unchanged) values from the parent/MainCtrl scope's <code>myNumbers</code> array during a digest cycle. This essentially makes the inputs uneditable.</p> <p>The fix is to use an array of objects in your MainCtrl:</p> <pre><code>$scope.myNumbers = [ {value: 10}, {value: 20} ]; </code></pre> <p>and then bind to the <code>value</code> property of the object in the ngRepeat:</p> <pre><code>&lt;div ng-repeat="num in myNumbers"&gt; &lt;input type="text" ng-model="num.value"&gt; &lt;div&gt;current scope: {{num.value}}&lt;/div&gt; </code></pre>
15,543,603
Installing Java 7 (Oracle) in Debian via apt-get
<p>Installing Oracle Java 7 in Debian via apt-get repository doesn't seems to work. </p> <pre><code>apt-get install oracle-java7-installer </code></pre> <p>Look like <code>apt-get</code> does not recognize <code>oracle-java7-installer</code>.</p>
15,543,636
1
5
null
2013-03-21 09:25:51.317 UTC
29
2015-10-19 07:49:43.35 UTC
2013-03-21 17:07:33.787 UTC
null
321,731
null
1,423,280
null
1
78
debian|java-7|apt-get
124,430
<p>Managed to get answer after do some google..</p> <pre><code>echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886 apt-get update # Java 7 apt-get install oracle-java7-installer # For Java 8 command is: apt-get install oracle-java8-installer </code></pre>
15,912,868
How can I delete multiple lines in vi?
<p>I have tried to follow the following:</p> <p><a href="https://stackoverflow.com/questions/3114936/how-to-delete-selected-text-in-vi-editor">How to delete selected text in VI editor</a></p> <p>but</p> <pre><code>5dd </code></pre> <p>gives</p> <blockquote> <p>E492: Not an editor command: 5dd</p> </blockquote> <p>I then tried:</p> <pre><code>5d </code></pre> <p>Which only deletes a single line. How can I delete multiple lines?</p>
15,919,791
11
1
null
2013-04-09 21:26:57.79 UTC
32
2020-01-03 14:45:30.51 UTC
2017-05-23 12:18:15.39 UTC
null
-1
null
144,152
null
1
144
vi
331,582
<p>Sounds like you're entering the commands in command mode (aka. "Ex mode"). In that context <code>:5d</code> would remove line number 5, nothing else. For <code>5dd</code> to work as intended -- that is, remove five consequent lines starting at the cursor -- enter it in normal mode and don't prefix the commands with <code>:</code>. </p>
10,813,528
Is it possible to center text in select box?
<p>I tried this: <a href="http://jsfiddle.net/ilyaD/KGcC3/" rel="noreferrer">http://jsfiddle.net/ilyaD/KGcC3/</a></p> <p>HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;select name="state" class="ddList"&gt; &lt;option value=""&gt;(please select a state)&lt;/option&gt; &lt;option class="lt" value="--"&gt;none&lt;/option&gt; &lt;option class="lt" value="AL"&gt;Alabama&lt;/option&gt; &lt;option class="lt" value="AK"&gt;Alaska&lt;/option&gt; &lt;option class="lt" value="AZ"&gt;Arizona&lt;/option&gt; &lt;option class="lt" value="AR"&gt;Arkansas&lt;/option&gt; &lt;option class="lt" value="CA"&gt;California&lt;/option&gt; &lt;option class="lt" value="CO"&gt;Colorado&lt;/option&gt; &lt;/select&gt; </code></pre> <p>CSS:</p> <pre class="lang-css prettyprint-override"><code>select { width: 400px; text-align: center; } select .lt { text-align: center; } </code></pre> <p>As you can see, it doesn't work. Is there a CSS-only way to center text in the select-box?</p>
10,813,603
23
4
null
2012-05-30 09:29:00.263 UTC
48
2022-06-10 12:33:57.837 UTC
2020-05-24 12:39:11.27 UTC
null
1,454,514
null
747,024
null
1
259
css
530,685
<p>I'm afraid this isn't possible with plain CSS, and won't be possible to make completely cross-browser compatible.</p> <p>However, using a jQuery plugin, you could style the dropdown:</p> <p><a href="https://www.filamentgroup.com/lab/jquery-ui-selectmenu-an-aria-accessible-plugin-for-styling-a-html-select.html" rel="noreferrer">https://www.filamentgroup.com/lab/jquery-ui-selectmenu-an-aria-accessible-plugin-for-styling-a-html-select.html</a></p> <p>This plugin hides the <code>select</code> element, and creates <code>span</code> elements etc on the fly to display a custom drop down list style. I'm quite confident you'd be able to change the styles on the spans etc to center align the items.</p>
10,646,358
hibernate exception Null value was assigned to a property of primitive type setter
<p>Having a frustrating problem with Hibernate 3.6.9. MS SQL Server 2008. Note the exception and the odd column index reference.</p> <p>The HQL Query itself:</p> <pre><code>Select r from DataStoreReference r join fetch r.container c where r.hash=:hash and r.state=0 </code></pre> <p>The stack trace:</p> <pre><code>2012-05-16 00:01:22,184 [BackgroundDeletionThread] ERROR org.hibernate.util.JDBCExceptionReporter - The value supplied cannot be converted to BIGINT. 2012-05-16 00:01:22,186 [BackgroundDeletionThread] ERROR org.hibernate.util.JDBCExceptionReporter - The value supplied cannot be converted to BIGINT. 2012-05-16 00:01:22,188 [BackgroundDeletionThread] ERROR org.hibernate.util.JDBCExceptionReporter - Invalid column index 14. 2012-05-16 00:01:22,190 [BackgroundDeletionThread] ERROR org.hibernate.util.JDBCExceptionReporter - The value supplied cannot be converted to BIGINT. 2012-05-16 00:01:22,193 [BackgroundDeletionThread] ERROR org.hibernate.util.JDBCExceptionReporter - The value supplied cannot be converted to BIGINT. 2012-05-16 00:01:22,194 [BackgroundDeletionThread] ERROR org.hibernate.util.JDBCExceptionReporter - Invalid column index 14. 2012-05-16 00:01:22,194 [BackgroundDeletionThread] ERROR com.flipper.utils.ServerErrorHandlerStrategy - reportError: Db :: com.flipper.datastore.workers.BackgroundDeletionThread.executeWork:87 :: EXCEPTION : com.flipper.datastore.exceptions.DBStoreException: Null value was assigned to a property of primitive type setter of com.flipper.datastore.model.DataStoreReference.usage com.flipper.datastore.exceptions.DBStoreException: Null value was assigned to a property of primitive type setter of com.flipper.datastore.model.DataStoreReference.usage at com.flipper.datastore.impl.hib.HibernateDBStore.getAllReferences(HibernateDBStore.java:301) at com.flipper.datastore.workers.BackgroundDeletionThread.processEntry(BackgroundDeletionThread.java:165) at com.flipper.datastore.workers.BackgroundDeletionThread.processSet(BackgroundDeletionThread.java:138) at com.flipper.datastore.workers.BackgroundDeletionThread.executeWork(BackgroundDeletionThread.java:84) at com.flipper.datastore.workers.BackgroundDeletionThread.run(BackgroundDeletionThread.java:60) Caused by: org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of com.flipper.datastore.model.DataStoreReference.usage at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:109) at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:583) at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:229) at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:3847) at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:152) at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:982) at org.hibernate.loader.Loader.doQuery(Loader.java:857) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274) at org.hibernate.loader.Loader.doList(Loader.java:2542) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276) at org.hibernate.loader.Loader.list(Loader.java:2271) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:459) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:365) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) at com.flipper.message.dao.DataStoreDao.getAllReferencesByHash(DataStoreDao.java:136) at com.flipper.datastore.impl.hib.HibernateDBStore.getAllReferences(HibernateDBStore.java:298) ... 4 more Caused by: java.lang.IllegalArgumentException at sun.reflect.GeneratedMethodAccessor556.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:66) ... 21 more </code></pre> <p>Now, I'd understand this from logic (and from googling) if the following were not true</p> <p>a) every instantiation of DataStoreReference is shortly followed by a setUsage of System.currentTimeMillis) b) the item is marked not-null in the mapping (see below) c) the exported table shows nulls only in the f_external column. The usage column has perfectly reasonable long numbers.</p> <p>The POJO:</p> <p>DataStoreReference</p> <pre><code>private long id; private String hash; private long date; private long sze; private long usage; private int state; private String external; private DataStoreContainer container; </code></pre> <p>followed by generic unmodified getter/setters.</p> <p>The mapping file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"&gt; &lt;hibernate-mapping package="com.flippr.datastore.model"&gt; &lt;class name="DataStoreReference" table="t_dsref"&gt; &lt;id name="id"&gt; &lt;column name="ds_reference_id"/&gt; &lt;generator class="native"/&gt; &lt;/id&gt; &lt;property name="hash" not-null="true" column="f_hash" lazy="false" index="idx_hash_dsr" type="string" length="128" /&gt; &lt;property name="state" not-null="true" column="f_state" lazy="false" index="idx_hash_dsr,idx_size_dsr,idx_usage_dsr" type="integer"/&gt; &lt;!-- hibernate hates the name size --&gt; &lt;property name="sze" not-null="true" column="f_size" lazy="false" index="idx_size_dsr" type="long"/&gt; &lt;property name="date" not-null="true" column="f_date" lazy="false" type="long"/&gt; &lt;property name="usage" not-null="true" column="f_usage" lazy="false" index="idx_usage_dsr" type="long"/&gt; &lt;property name="external" not-null="false" column="f_ext" lazy="false" type="string" length="160" /&gt; &lt;many-to-one name="container" class="com.flipper.datastore.model.DataStoreContainer" column="entity_id" foreign-key="fk_ds_container_id_dsr" not-found="ignore" not-null="true"/&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"&gt; &lt;hibernate-mapping package="com.flipper.datastore.model"&gt;   &lt;class name="DataStoreContainer" table="t_dscnt"&gt;     &lt;id name="id"&gt;       &lt;column name="ds_container_id"/&gt;       &lt;generator class="native"/&gt;     &lt;/id&gt;     &lt;property name="containerType" column="f_type" index="idx_containerType_dsc" lazy="false" type="integer"/&gt;     &lt;property name="fileCount" column="f_fc" lazy="false" type="long"/&gt;     &lt;property name="deletedCount" column="f_dc" lazy="false" type="long"/&gt;     &lt;property name="path" column="f_path" length="255" lazy="false"  type="string"/&gt;     &lt;set cascade="save-update,delete,delete-orphan,all-delete-orphan" inverse="true" name="documents"&gt;       &lt;key column="entity_id" /&gt;       &lt;one-to-many class="com.flipper.datastore.model.DataStoreReference"/&gt;     &lt;/set&gt;   &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre>
11,093,522
4
6
null
2012-05-18 03:32:07.223 UTC
8
2017-01-16 08:29:56.427 UTC
2014-02-27 09:21:25.46 UTC
null
2,845,946
null
282,968
null
1
13
java|sql|hibernate|persistence
63,363
<p>Turns out it is a bug with the enhanced Hibernate 3.6 MS SQL dialects. If you extend SQLServer2005 or SQLServer2008 dialects, you will have this issue. Using the older SQLServer dialect (which is pretty much what shipped with Hibernate 3.3x) you do not. Probably something to do with paging support introduced. Sigh</p>
25,230,024
Get DbContext from Entity in Entity Framework
<p>I'm deep somewhere in the Business layer in a debugging session in Visual Studio trying to figure out why an Entity is behaving strangely when trying to persist the changes.</p> <p>It would really be helpful to get a reference to the DbContext this Entity belongs to, at this point in the call stack.</p> <p>I.e. to see what the state is of this Entity is (Unchanged, Modified, etc).</p> <p>So I'm looking for a helper method like this:</p> <pre><code>var db_context = DbContextHelpers.GetDbContext(entity); // after that I could do something like this var state = db_context.Entry(entity); </code></pre> <p>I can use this stuff in the Immediate window during debugging.</p> <p>Anyone any suggestions?</p> <p><strong>Extra notes</strong></p> <p>The Entity must be aware of the <code>DbContext</code> somewhere, because it is using it for lazy loading navigation properties?</p>
43,667,414
3
8
null
2014-08-10 15:20:32.497 UTC
7
2017-05-11 23:28:25.913 UTC
2014-08-10 16:39:12.653 UTC
null
647,845
null
647,845
null
1
34
c#|entity-framework
34,061
<p>For EF6, I modified Dirk's answer slightly:</p> <pre><code> public static DbContext GetDbContextFromEntity(object entity) { var object_context = GetObjectContextFromEntity(entity); if (object_context == null || object_context.TransactionHandler == null) return null; return object_context.TransactionHandler.DbContext; } private static ObjectContext GetObjectContextFromEntity(object entity) { var field = entity.GetType().GetField("_entityWrapper"); if (field == null) return null; var wrapper = field.GetValue(entity); var property = wrapper.GetType().GetProperty("Context"); var context = (ObjectContext)property.GetValue(wrapper, null); return context; } </code></pre> <p>No new DbContext() and it's castable into your main Entities class.</p> <p>Note: To the above question of null return value, this will happen if the entity has not been saved/committed. New entities that can only be found in .Local do not seem to have the "_entityWrapper" field.</p>
31,681,732
lodash: Get duplicate values from an array
<p>Say I have an array like this: <code>[1, 1, 2, 2, 3]</code></p> <p>I want to get the duplicates which are in this case: <code>[1, 2]</code> </p> <p>Does <a href="https://lodash.com/" rel="noreferrer">lodash</a> support this? I want to do it in the shortest way possible.</p>
31,681,942
13
2
null
2015-07-28 16:09:49.627 UTC
6
2022-07-27 15:10:16.7 UTC
2017-01-24 16:49:11.933 UTC
null
3,235,127
null
3,235,127
null
1
40
javascript|arrays|lodash
65,994
<p>You can use this:</p> <pre><code>_.filter(arr, (val, i, iteratee) =&gt; _.includes(iteratee, val, i + 1)) </code></pre> <p>Note that if a number appears more than two times in your array you can always use <code>_.uniq</code>.</p>
35,621,249
Android recyclerview v.23.2.0 & design library v.23.2.0 are broken
<p>After update to v23.2.0 recyclerview items have strange behavior: very big with empty space. After update to design library 23.2.0 menu overflow icon became black (app has dark action bar).</p> <p><strong>UPDATE</strong> On my nexus 5 overflow icon &amp; recycler view row are fixed, but on Galaxy Tab 4 overflow icon is still black.</p> <p><strong>UPDATE 2</strong> If you have problems with empty spacing, fix layout parameters for your views (match_parent -> wrap_content), cause RecyclerView will now size itself based on the size of its contents. Read this blog <a href="http://android-developers.blogspot.am/2016/02/android-support-library-232.html">http://android-developers.blogspot.am/2016/02/android-support-library-232.html</a></p> <blockquote> <p>The RecyclerView widget provides an advanced and flexible base for creating lists and grids as well as supporting animations. This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.</p> <p>Due to this change, make sure to double check the layout parameters of your item views: previously ignored layout parameters (such as MATCH_PARENT in the scroll direction) will now be fully respected.</p> </blockquote> <p><strong>UPDATE 3</strong> Link to the issue that describes the problem with black icons in Action Bar <a href="https://code.google.com/p/android/issues/detail?id=201918">Issue 201918</a></p> <p><strong>UPDATE 4</strong> See my answer under post, icons problem is also solved</p>
35,627,261
2
13
null
2016-02-25 07:47:44.84 UTC
3
2020-02-23 17:01:20.077 UTC
2020-02-23 17:01:20.077 UTC
null
1,033,581
null
1,635,488
null
1
31
android|android-support-library|android-recyclerview|android-support-design
4,334
<p>The reason you are getting large open spaces is because of match_parent. It wasn't working correctly before, but now with the new release it is working differently. You just need to update to wrap_content instead of match_parent as that causes the layout to match the parent giving you the large spaces.</p> <blockquote> <p>The RecyclerView widget provides an advanced and flexible base for creating lists and grids as well as supporting animations. This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.</p> </blockquote> <p><a href="http://android-developers.blogspot.co.uk/2016/02/android-support-library-232.html">http://android-developers.blogspot.co.uk/2016/02/android-support-library-232.html</a></p>
33,064,377
Destructuring to get the last element of an array in es6
<p>In coffeescript this is straightforward:</p> <pre><code>coffee&gt; a = ['a', 'b', 'program'] [ 'a', 'b', 'program' ] coffee&gt; [_..., b] = a [ 'a', 'b', 'program' ] coffee&gt; b 'program' </code></pre> <p>Does es6 allow for something similar?</p> <pre><code>&gt; const [, b] = [1, 2, 3] 'use strict' &gt; b // it got the second element, not the last one! 2 &gt; const [...butLast, last] = [1, 2, 3] SyntaxError: repl: Unexpected token (1:17) &gt; 1 | const [...butLast, last] = [1, 2, 3] | ^ at Parser.pp.raise (C:\Users\user\AppData\Roaming\npm\node_modules\babel\node_modules\babel-core\node_modules\babylon\lib\parser\location.js:24:13) </code></pre> <p>Of course I can do it the es5 way -</p> <pre><code>const a = b[b.length - 1] </code></pre> <p>But maybe this is a bit prone to off by one errors. Can the splat only be the last thing in the destructuring?</p>
33,064,660
18
6
null
2015-10-11 11:20:50.367 UTC
18
2022-09-02 13:42:20.203 UTC
null
null
null
null
1,551,863
null
1
149
ecmascript-6|destructuring
137,213
<p>It is not possible in ES6/2015. The standard just doesn't provide for it.</p> <p>As you can see in <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-function-definitions" rel="noreferrer">the spec</a>, the <code>FormalParameterList</code> can either be:</p> <ul> <li>a <code>FunctionRestParameter</code></li> <li>a <code>FormalsList</code> (a list of parametes)</li> <li>a <code>FormalsList</code>, followed by a <code>FunctionRestParameter</code></li> </ul> <p>Having <code>FunctionRestParameter</code> followed by parameters is not provided.</p>
33,255,578
Old JaxB and JDK8 Metaspace OutOfMemory Issue
<p>We are working on a business application (1 million+ LOC) developed since 10+ years. While switching to JDK8 we get an issue with the metaspace of JDK8. This seems to be related to the JaxB-Version referenced in com.sun.xml.ws:webservices-rt:1.4 (Metro 1.4). Because of the intense linking in the application and legacy creation of classes/instances via JaxB it isn't simple to switch on the fly the old libraries.</p> <p>Currently we are researching this issue. We created a sample programm that reproduces this behavior:</p> <pre><code>import java.io.ByteArrayInputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class X { private static final String XML = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;x test=\"test\" /&gt;"; @XmlAttribute String test; public static void main( String[] args ) throws JAXBException, InterruptedException { System.out.println("start"); while ( true ) { JAXBContext jc = JAXBContext.newInstance( X.class ); Unmarshaller unmarshaller = jc.createUnmarshaller(); X object = (X) unmarshaller.unmarshal( new ByteArrayInputStream( XML.getBytes() ) ); System.out.println( object.test ); } } } </code></pre> <p>JDK7 keeps the PermGenSpace clean. (Simulated with 16M PermGen) <a href="http://i.stack.imgur.com/LDb1Y.png">Memory of run with JDK7</a></p> <p>Using JDK8 the application runs slowly to the OOM exception. The VisualVM catches the exception and keeps the process running on the maximum of available Metaspace. Even here it gets stucked after quite a while running on max. (Simulated with 16M Metaspace) <a href="http://i.stack.imgur.com/MTbC3.png">Memory of run with JDK8</a></p> <p>Has anyone some ideas how to get the garbage collectors legacy behavior, so we don't run into those out of memory issues? Or do you have any other ideas how to deal with this issue?</p> <p>Thanks.</p> <p>edit1: <strong>Run parameters JDK7:</strong></p> <p><code>-XX:+TraceClassLoading -XX:+TraceClassUnloading -XX:MaxPermSize=16M -XX:PermSize=1M -XX:+UseParallelOldGC -XX:+HeapDumpOnOutOfMemoryError</code></p> <p>=> No heap dumps are created</p> <p><strong>Run parameters JDK8:</strong></p> <p><code>-XX:+TraceClassLoading -XX:+TraceClassUnloading -XX:MaxMetaspaceSize=16M -XX:MetaspaceSize=1M -XX:+UseParallelOldGC -XX:+HeapDumpOnOutOfMemoryError</code></p> <p>=> heap dumps are generated while running.</p> <p>The Memory available of VisualVM does not show the real maximum metaspace value. If not limited the metaspace is constantly increasing untill memory is exceeded.</p> <p>edit 2:</p> <p>I have tried all available garbage collectors for JDK8. They all have the same issue. </p> <p>edit 3:</p> <p>Solving by exchanging the libs is difficult in our real application because of heavy coupling between JAXB &amp; several modules of our application. So a fix for the garbage collector behavior is needed for the short run. On the long run the propper fix is already planned.</p>
33,431,431
3
8
null
2015-10-21 09:28:07.577 UTC
13
2021-05-04 11:56:29.977 UTC
2015-10-22 11:13:01.43 UTC
null
4,964,080
null
4,964,080
null
1
29
java|jaxb|java-8|out-of-memory|java-metro-framework
17,371
<p>We solved our current issue untill able to fix all occurances in our application by using the following VM-parameter:</p> <pre><code>-Dcom.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize=true </code></pre> <p>I hope this will help others with similar issues...</p>
13,538,685
Dynamically generating Ge'ez unicodes
<p><img src="https://i.stack.imgur.com/yx7Xf.gif" alt="enter image description here"></p> <p>Hi. If you look at the image above, you will see a set of very weird-looking characters displayed along with some Latin characters. The weird ones are Eritrean characters. They are the characters we use in my country. So, to go strait to the point, I am hoping to create even the simplest possible bit of software or maybe even a batch file (if possible) to help me make these characters applicable on the web and make PCs understand and display them when being typed. Just like Arabic, Hindu, Chinese... characters are used. I think, since the question of 'creating a language' is often rare or because I may not know the correct term to use, when I searched the internet to find any tutorial or even a freelancer or anything, all I got was... nothing. So, I am hoping, if anyone can give me a step-by-step guide, or even just a clue about how to create this, would be very helpful. </p> <p>Thanks.</p>
13,546,972
7
18
null
2012-11-24 05:51:01.313 UTC
8
2019-05-27 14:41:32.517 UTC
2013-05-31 14:13:52.593 UTC
null
1,640,606
null
1,640,606
null
1
10
unicode|utf-8
8,653
<p>Your question asks &quot;how to create a language&quot;, so I will describe all the pieces that need to be in place for a new language (or more accurately, writing system). You ask specifically about the Eritrean alphabet, so I will provide specific examples of how that is supported on modern systems, and try to provide you pointers for the pieces you are missing. The answer is long, and provides lots of links, to support the two explanations.</p> <p>To work with a script like <a href="http://en.wikipedia.org/wiki/Ge%27ez_script" rel="nofollow noreferrer">Ge'ez</a> (also known as Ethiopic, the script used to write Amharic in Ethiopia and Tigrinya in Eritrea) you need a few things. The first is a way to encode the characters; a set of numbers representing each character, that the computer can use to represent the text. Luckily, <a href="http://en.wikipedia.org/wiki/Unicode" rel="nofollow noreferrer">Unicode</a> has become widespread, and Unicode is designed to be a universal character set that includes all of the world's languages. Unicode 3.0 introduced Ethiopic in the <a href="http://www.unicode.org/charts/PDF/U1200.pdf" rel="nofollow noreferrer">range U+1200-U+137F</a>, and later versions added supplements of more obscure characters in the ranges <a href="http://www.unicode.org/charts/PDF/U1380.pdf" rel="nofollow noreferrer">U+1380-U+1394</a>, <a href="http://www.unicode.org/charts/PDF/U2D80.pdf" rel="nofollow noreferrer">U+2D80-U+2DDF</a> and <a href="http://www.unicode.org/charts/PDF/UAB00.pdf" rel="nofollow noreferrer">U+AB00-U+AB2F</a>. If you wanted to support a language that Unicode didn't yet support, you would either need to use the <a href="http://en.wikipedia.org/wiki/Private_Use_%28Unicode%29" rel="nofollow noreferrer">private use area</a> and define your own mapping of characters to code points, or <a href="http://www.unicode.org/pending/proposals.html" rel="nofollow noreferrer">submit a proposal</a> to have your script added to Unicode; for example, see the proposal for <a href="ftp://ftp.ethiopic.org/pub/info/uni-proposal.txt" rel="nofollow noreferrer">Ethiopic</a>.</p> <p>Now, Unicode is just a <a href="http://www.unicode.org/glossary/#character_set" rel="nofollow noreferrer">character set</a>; an abstract mapping between characters and numbers. To actually transmit these characters as a sequence of bytes, you use a <a href="http://www.unicode.org/glossary/#character_encoding_form" rel="nofollow noreferrer">character encoding</a>. There are many encodings; some of them, like <a href="http://en.wikipedia.org/wiki/ASCII" rel="nofollow noreferrer">ASCII</a> and <a href="http://en.wikipedia.org/wiki/ISO/IEC_8859-1" rel="nofollow noreferrer">ISO-8859-1</a> only cover a subset of the full Unicode character set, while others, like <a href="http://en.wikipedia.org/wiki/UTF-8" rel="nofollow noreferrer">UTF-8</a> and <a href="http://en.wikipedia.org/wiki/UTF-16" rel="nofollow noreferrer">UTF-16</a>, cover the full range. For documents on the web, UTF-8 is the recommended character encoding; you should never use anything else if you can help it. In UTF-8, you can write Ge'ez directly in the document, for example: ኤርትራ. One thing to watch out for is that some programs (especially on Windows) will offer you &quot;Unicode&quot; as an encoding, when they mean UTF-16; you want to make sure to choose UTF-8, as it's more efficient and more compatible with a wider variety of software.</p> <p>If you are using encodings that don't cover the full range of Unicode, or you don't have a good way to type those characters, and you are writing HTML or XML, you can use <a href="http://en.wikipedia.org/wiki/Numeric_character_reference" rel="nofollow noreferrer">numeric character references</a> instead. To do this, you write the Unicode code point of the character you want to refer between <code>&amp;#</code> and <code>;</code>. You can write the number in decimal, or in hexadecimal prefixed with an <code>x</code>. For example, ሀ can be written <code>&amp;#x1200;</code> or <code>&amp;#4608;</code> (the semicolon at the end is important; it wasn't working for you in the comments because you were missing it).</p> <p>Now that you have a character set, and a way of encoding it, you need a way to display it. Some scripts are easier to display in others. For all scripts, you need a <a href="http://en.wikipedia.org/wiki/Computer_font" rel="nofollow noreferrer">font</a>; a file defining how each character looks. A font contains a collection of glyphs, or drawings of each character. Some scripts, like the <a href="http://en.wikipedia.org/wiki/Latin_alphabet" rel="nofollow noreferrer">Latin alphabet</a> (the alphabet used for English and most European languages) are relatively simple; each character is a separate glyph, and how they are drawn doesn't depend on what characters come before or after (though <a href="http://en.wikipedia.org/wiki/Diacritic" rel="nofollow noreferrer">diacritics</a> and <a href="http://en.wikipedia.org/wiki/Typographic_ligature" rel="nofollow noreferrer">ligatures</a> can make it a little more complicated). Others, like <a href="http://en.wikipedia.org/wiki/Arabic_alphabet" rel="nofollow noreferrer">Arabic</a> and <a href="http://en.wikipedia.org/wiki/Brahmic_scripts" rel="nofollow noreferrer">Indic scripts</a> are written in cursive, where letters join to each other so how they are drawn can depend on the characters near them. These languages require special rendering support like <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd374091%28v=vs.85%29.aspx" rel="nofollow noreferrer">Uniscribe</a> or <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd368038%28v=vs.85%29.aspx" rel="nofollow noreferrer">DirectWrite</a> on Windows, <a href="http://www.pango.org/" rel="nofollow noreferrer">Pango</a> on Linux, or advanced font technology like <a href="https://developer.apple.com/fonts/TTRefMan/RM06/Chap6AATIntro.html" rel="nofollow noreferrer">Apple Advanced Typography</a> or <a href="http://scripts.sil.org/cms/scripts/page.php?site_id=projects&amp;item_id=graphite_home" rel="nofollow noreferrer">Graphite</a>.</p> <p>Luckily, Ge'ez is a fairly simple writing system, that doesn't require any specialized rending support or advanced font systems. Each of the characters is a separate glyph, and it doesn't require any reordering. So a normal <a href="http://en.wikipedia.org/wiki/OpenType" rel="nofollow noreferrer">OpenType</a> font, displayed with the rendering systems already available on most computers, will do the job. But you still need the font in order to be able to display the characters. To create you own font, you can use <a href="http://fontforge.org/" rel="nofollow noreferrer">FontForge</a> (a free/open source tool), <a href="http://www.fontlab.com/font-editor/fontographer/" rel="nofollow noreferrer">Fontographer</a>, <a href="http://www.fontlab.com/font-editor/fontlab-studio/" rel="nofollow noreferrer">FontLab Studio</a>, or other similar software.</p> <p>For Ethiopic, you don't need to create your own. There are <a href="http://www.wazu.jp/gallery/Fonts_Ethiopic.html" rel="nofollow noreferrer">numerous fonts available</a> that include the Ethiopic characters, but one that I would recommend is <a href="http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&amp;item_id=AbyssinicaSIL" rel="nofollow noreferrer">Abyssinica SIL</a> from <a href="http://www.sil.org/" rel="nofollow noreferrer">SIL</a> (the Summer Institute of Linguistics), which does a lot of great work for minority languages and writing systems. Their fonts are available under a <a href="http://scripts.sil.org/OFL" rel="nofollow noreferrer">free license</a>, that allows you to use the font, redistribute the font, and modify the font, so their fonts are quite flexible and can be used in a wide variety of situations. Windows ships with <a href="http://www.microsoft.com/typography/fonts/font.aspx?FMID=1623" rel="nofollow noreferrer">Nyala</a>, which includes Ethiopic characters, since Windows Vista, and <a href="https://www.microsoft.com/typography/fonts/font.aspx?FMID=2114" rel="nofollow noreferrer">Ebrima</a>, which added support for Ethiopic characters in Windows 8; so people on Windows Vista or later should be able to view Ethiopic characters already. Mac OS X ships with <a href="http://support.apple.com/kb/HT5154" rel="nofollow noreferrer">Kefa as of 10.6</a>.</p> <p>Once you have the font, you will be able to view Ethiopic characters. But other people reading your documents might not have those fonts (if they are using an older version of Windows or Mac OS X, if they didn't install all of the fonts that came with Windows, or the like), in which case the characters will probably show up as boxes or question marks on their machine. You could give those people a redistributable font like Abyssinica SIL, or they could buy a font that includes Ethiopic characters, but that can be inconvenient. For working with word processor documents or plain text, that's probably the best you can do; they will need the font installed on their computer to be able to display the text. If you create a PDF on your computer, it should embed the fonts that it needs to display the text, so creating a PDF can be a convenient way to include uncommon fonts with your document.</p> <p>On a web page, you can use <a href="http://www.w3.org/TR/css3-fonts/#font-resources" rel="nofollow noreferrer">web fonts</a> to link to a font from your stylesheet, allowing the users web browser to load that font for that web page. Web fonts are supported <a href="http://caniuse.com/#feat=fontface" rel="nofollow noreferrer">all the way back to IE 6</a>, and in recent versions of most other web browsers, so they are actually quite widely supported. Different web browsers support different font file formats (<a href="http://en.wikipedia.org/wiki/Embedded_OpenType" rel="nofollow noreferrer">EOT</a>, <a href="http://en.wikipedia.org/wiki/TrueType" rel="nofollow noreferrer">TTF</a>, <a href="http://en.wikipedia.org/wiki/OpenType" rel="nofollow noreferrer">OpenType</a>, <a href="http://www.w3.org/TR/SVG/fonts.html" rel="nofollow noreferrer">SVG</a>, and <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format" rel="nofollow noreferrer">WOFF</a>), and slightly different syntaxes for the CSS (older versions of IE are based on an older draft), so it can be a bit tricky to make a page that is compatible with all browsers. Luckily, people have automated that process. Some web fonts are available online from <a href="http://www.google.com/webfonts" rel="nofollow noreferrer">Google Web Fonts</a> or <a href="http://www.fontsquirrel.com/fontface" rel="nofollow noreferrer">FontSquirrel</a>, but sadly, I couldn't find any Ethiopic fonts already hosted. However, you can <a href="http://www.fontsquirrel.com/fontface/generator" rel="nofollow noreferrer">upload a font to FontSquirrel</a>, and it will convert it into all of the major formats, and provide example CSS that will work on all modern browsers. Note that you should only do this with fonts that allow web embedding; not all fonts do. Since Abyssinica SIL is available under the Open Font License, you can use it, and I've run it through FontSquirrel for you; you can <a href="http://ephemera.continuation.org/stackoverflow/webfontkit-20121124-164442/abyssinicasil-r-demo.html" rel="nofollow noreferrer">see how it works</a> (check out the Glyphs &amp; Languages tab), or <a href="http://ephemera.continuation.org/stackoverflow/webfontkit-20121124-164442.zip" rel="nofollow noreferrer">download the kit</a>. To use it, just put the font files (<code>.ttf</code>, <code>.eot</code>, <code>.svg</code>, and <code>.woff</code>) on your server in the same directory as your CSS, and include the following in your CSS:</p> <pre><code>@font-face { font-family: 'abyssinica_silregular'; src: url('abyssinicasil-r.eot'); src: url('abyssinicasil-r.eot?#iefix') format('embedded-opentype'), url('abyssinicasil-r.woff') format('woff'), url('abyssinicasil-r.ttf') format('truetype'), url('abyssinicasil-r.svg#abyssinica_silregular') format('svg'); font-weight: normal; font-style: normal; } </code></pre> <p>Now that you know how to encode Ethiopic, view Ethiopic characters, and share documents containing Ethiopic characters, you are probably going to want to type them into documents. If you are using HTML, you could just type the numeric character reference described above. In other documents, you could just copy and paste the characters from a chart of all of them, like the Wikipedia page. But that would become pretty cumbersome. Depending on your system and settings, you can also use <a href="https://superuser.com/questions/13086/how-do-you-type-unicode-characters-using-hexadecimal-codes">Unicode Hex Input</a> to enter arbitrary Unicode characters, but that is also cumbersome.</p> <p>To fully support typing a script on your computer, you need a <a href="http://en.wikipedia.org/wiki/Keyboard_layout" rel="nofollow noreferrer">keyboard layout</a> or <a href="http://en.wikipedia.org/wiki/Input_method" rel="nofollow noreferrer">input method</a>. Some scripts can be typed with a simple keyboard layout, which says which keys correspond to which characters. If a script has more characters than there are keys on the keyboard, Shift and Alt (or Option on the Mac) can be used to map to more characters. <a href="http://en.wikipedia.org/wiki/Dead_key" rel="nofollow noreferrer">Dead keys</a> can also be used to expand the range of characters that you type; dead keys are sequences of two or more keystrokes that produce a single glyph; for example, on Mac OS X, to type &quot;á&quot;, you can type <kbd>Option-E</kbd> <kbd>A</kbd>. To create a keyboard layout on Windows, you can use the <a href="http://msdn.microsoft.com/en-us/goglobal/bb964665" rel="nofollow noreferrer">Microsoft Keyboard Layout Creator</a>. Mac OS X uses <a href="http://developer.apple.com/library/mac/#technotes/tn2056/_index.html" rel="nofollow noreferrer">an XML format</a> for keyboard layouts, so you can create one directly, or use <a href="http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&amp;id=ukelele" rel="nofollow noreferrer">Ukelele</a> from SIL to create one more easily. On systems using X11 (like Linux), you can <a href="http://hektor.umcs.lublin.pl/%7Emikosmul/computing/articles/custom-keyboard-layouts-xkb.html" rel="nofollow noreferrer">create your own XKB layouts</a>.</p> <p>If you need more characters than can be supported with modifiers and dead keys, like typing Chinese or Japanese, then you need a full-fledged input method. An input method allows you to run arbitrary code to map what someone types into the text it produces; for example, in a Japanese input method, you may type a phonetic representation of what you you are writing, and it will show you a drop down list of possible characters that match that representation, allowing you to choose the appropriate ones. Windows provides the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd318641%28v=vs.85%29.aspx" rel="nofollow noreferrer">Input Method Manager</a> for writing input methods, Mac OS X the <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/InputMethodKitFrameworkRef/_index.html" rel="nofollow noreferrer">Input Method Kit</a>, and X11 has a few ways to do it, such as <a href="http://www.scim-im.org/" rel="nofollow noreferrer">SCIM</a> and <a href="https://code.google.com/p/ibus/" rel="nofollow noreferrer">iBus</a>.</p> <p>The <a href="http://keyboards.ethiopic.org/specification/" rel="nofollow noreferrer">standard input method</a> for Ethiopic makes extensive use of dead keys. It looks like the most popular existing input method for Ethiopic is <a href="http://www.tavultesoft.com/ethiopic/" rel="nofollow noreferrer">Keyman</a>, which is a commercial input method that works on Mac and Windows, and in addition there's a free variant, <a href="http://kmfl.sourceforge.net/" rel="nofollow noreferrer">KMFL</a>, that works on Linux. SIL has <a href="http://scripts.sil.org/cms/scripts/page.php?item_id=AbyssinicaSIL_Download" rel="nofollow noreferrer">keyboard downloads</a> for this input method; they also have a keyboard layout for Mac OS X which uses dead keys to achieve the same thing. Mac OS X has more extensive dead key support, so it doesn't require an input method to support this form of input, while on Windows you need to use an input method like Keyman to be able to enter input this way. Google has a free input method for Windows, <a href="http://www.google.com/inputtools/windows/index.html" rel="nofollow noreferrer">Google Input Tools for Windows</a>, which supports Amharic, and allows you to <a href="http://www.google.com/inputtools/windows/canonical.html" rel="nofollow noreferrer">customize its input schemes</a>; you could try adapting their Amharic support for Tigrinya.</p> <p>If you just need to support input on a web site, you could do this in JavaScript, by writing an input method in JavaScript that transliterates from what someone types into Ethiopic. I do not know of any existing frameworks for doing this; however, I have found <a href="http://www.sayjack.com/type/korean/" rel="nofollow noreferrer">Korean</a> and <a href="http://jime.sourceforge.jp/javascriptime/" rel="nofollow noreferrer">Japanese</a> input methods implemented in JavaScript. You could take a look at how those are implemented. Upon looking further, I've found that Tavultesoft, who make Keyman, also have <a href="http://www.tavultesoft.com/keymanweb/" rel="nofollow noreferrer">KeymanWeb</a>, a JavaScript based input method that you can buy and embed in your site. MediaWiki also has an input method extension <a href="http://www.mediawiki.org/wiki/Extension:Narayam" rel="nofollow noreferrer">Narayam</a>, that includes a JavaScript based input method for MediaWiki based sites like Wikipedia, which includes an experimental Amharic input method. There is also a <a href="http://www.w3.org/TR/ime-api/" rel="nofollow noreferrer">draft W3C IME API</a>, which helps provide an interface between web apps and native IMEs, as well as JavaScript based IMEs. Given that it's still a draft, I don't know if it is yet supported anywhere.</p> <p>With all the above (a character set, encoding, fonts, rendering support, and an input method), you will be able to create, share, and view documents in your script. If that's all you need, great; the above will allow you to work with documents in a given script. But for full support for a language on your computer, not just its script or writing system, there are two more pieces that you need: a <a href="http://en.wikipedia.org/wiki/Locale" rel="nofollow noreferrer">locale</a>, and your software to be localized (translated and adapted) for your language.</p> <p>A locale specifies how programs should manipulate text in a given script, language, culture, and/or encoding. There are many common text processing operations that programs do: displaying numbers, displaying dates and times, sorting strings or names, and so on. How these should work can differ based on the language, script, and culture of the person using the program; for instance, in Swedish &quot;ü&quot; is sorted along with &quot;y&quot;, while in English and German it's sorted along with &quot;u&quot;. Differences may not be based on language: both Mexico and Spain use Spanish, but in Mexico numbers are displayed with <code>.</code> as the decimal separator (1½ is written &quot;1.5&quot;), while in Spain <code>,</code> is used as the decimal separator (1½ is written &quot;1,5&quot;). A locale specifies all of these rules. Because the locale can vary based on language, culture, and sometimes other factors, the language and country are usually used to specify the locale, and other information can be used as well.</p> <p>The most widely used standard for naming locales is <a href="https://www.rfc-editor.org/rfc/rfc4646" rel="nofollow noreferrer">RFC 4646 (BCP 47)</a>. Locales are usually specified as &quot;<i>ln</i>-<i>CC</i>&quot; with the language code <em>ln</em> and country code <em>CC</em>: US English is en-US, British English is en-UK, and French in France is fr-FR. If more information needs to be specified, it can be included. For instance, <a href="http://en.wikipedia.org/wiki/Serbian_language" rel="nofollow noreferrer">Serbian</a> can be written with either Latin or <a href="http://en.wikipedia.org/wiki/Cyrillic_script" rel="nofollow noreferrer">Cyrillic</a>, and so Serbian in Serbia can be either sr-Latn-CS or sr-Cyrl-CS. Tigrinya in Eritrea is written ti-ER.</p> <p>There are a variety of different formats for defining the rules that a particular locale has. Windows uses NLP files, a custom format that can be created with <a href="http://msdn.microsoft.com/en-us/magazine/cc163506.aspx" rel="nofollow noreferrer">Microsoft Locale Builder</a>. POSIX (Unix/Linux) locales can be created using <a href="http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap07.html" rel="nofollow noreferrer">localedef</a>. Many systems these days are moving towards the <a href="http://cldr.unicode.org/" rel="nofollow noreferrer">Unicode Common Locale Data Registry</a>, which specifies a standardized format for locale data as well as a comprehensive database of locales for many of the worlds languages. <a href="http://site.icu-project.org/" rel="nofollow noreferrer">ICU</a> is a library for C and Java (and used by many other environments) for manipulating Unicode text according to Unicode rules and locale data; they have a good <a href="http://demo.icu-project.org/icu-bin/locexp" rel="nofollow noreferrer">browser</a> for the data from the CLDR and their own locale data. For example, take a look at their entry for <a href="http://demo.icu-project.org/icu-bin/locexp?d_=en&amp;_=ti_ER" rel="nofollow noreferrer">ti-ER</a>.</p> <p>Finally, for full support of a language, you need to translate the software itself into that language. There are, of course, many pieces of software, and each one contains many strings that need to be translated. Some software is not designed to be translated; it has not been <a href="http://en.wikipedia.org/wiki/Internationalization_and_localization" rel="nofollow noreferrer">internationalized</a>. Some software can only be translated by whoever created it; the strings are built into the program and cannot be easily modified by a third party. But it is possible to localize some software, translating it to your language and culture. If the software has already been localized for several other languages and cultures, it is likely to be flexible enough to support a new language, and if it uses formats that are easily modifiable for localization information, it can be modified by third parties.</p> <p>For instance, applications on Mac OS X store their localization data in separate files within the application bundle. There is a tool called AppleGlot (you need to register for the <a href="https://developer.apple.com/" rel="nofollow noreferrer">Mac Developer Program</a> and go to the downloads area to find it) which can help you extract that data, provide a file with all of the strings which need to be translated, and allow you to combine that with the application again once you have. For open source software, such as much software available on Linux, you can work with the developers to provide translation. Some software uses <a href="http://www.gnu.org/software/gettext/manual/gettext.html" rel="nofollow noreferrer">gettext</a> for translation strings, which use the PO file format that you can edit using <a href="http://www.poedit.net/" rel="nofollow noreferrer">poedit</a>. Some uses Qt, for which you can use <a href="http://doc.qt.digia.com/qt/linguist-manual.html" rel="nofollow noreferrer">Qt Linguist</a>. Or for dealing with a wide variety of formats, you can use a commercial offering like <a href="http://www.maxprograms.com/products/swordfish.html" rel="nofollow noreferrer">Swordfish</a> or <a href="https://www.transifex.com/" rel="nofollow noreferrer">Transifex</a>.</p> <p>Of course, no one person can do all of the above; it takes many people working together to build support for a new language on modern computer systems. This is all intended to be a high-level tour of all of the components that go into language support for a given language, with references that will help you follow up on whichever aspects you would like to work on, as well as demonstrate what already works for Tigrinya and the Ge'ez script.</p>
13,370,719
Remove android default action bar
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2591036/how-to-hide-the-title-bar-for-an-activity-in-xml-with-existing-custom-theme">How to hide the title bar for an Activity in XML with existing custom theme</a> </p> </blockquote> <p>i remove the action bar by requestWindowFeature(Window.FEATURE_NO_TITLE); however, when the app starts, the action bar appears in a very short time before it executes the above statement. how can I make it totally disappear? thank</p>
13,370,836
2
2
null
2012-11-13 23:32:42.833 UTC
11
2014-10-14 17:14:13.637 UTC
2017-05-23 12:10:22.357 UTC
null
-1
null
1,602,167
null
1
25
android|android-actionbar
108,830
<p>I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:</p> <pre><code>&lt;android:theme="@android:style/Theme.NoTitleBar"&gt; </code></pre> <p>Just add it to your <code>application</code> tag to apply it app-wide.</p>
13,584,591
How to integrate Ajax with Symfony2
<p>I'm looking form simple tutorial/example about ajax in symfony2, for beginner?</p> <p>I have these examples:</p> <ul> <li><p>city.php: <a href="http://pastebin.com/Qm8LS5kh" rel="noreferrer">http://pastebin.com/Qm8LS5kh</a></p></li> <li><p>ajax_req.js: <a href="http://pastebin.com/UqJMad24" rel="noreferrer">http://pastebin.com/UqJMad24</a></p></li> <li><p>index.html: <a href="http://pastebin.com/H1err4Yh" rel="noreferrer">http://pastebin.com/H1err4Yh</a></p></li> </ul> <p>How can these be put into a Symfony2 app?</p>
13,585,748
1
4
null
2012-11-27 12:47:00.477 UTC
25
2012-11-27 13:58:50.347 UTC
2012-11-27 13:58:50.347 UTC
null
687,514
null
1,822,112
null
1
25
ajax|symfony
56,732
<p>It is easy. I will illustrate how to do an AJAX call in Symfony2 through 3 steps. For the following example, assume to use the jQuery library.</p> <ul> <li><p>Define the route for the action that has to handle your AJAX call. E.g.</p> <pre><code>AcmeHomeBundle_ajax_update_mydata: pattern: /update/data/from/ajax/call defaults: { _controller: AcmeHomeBundle:MyAjax:updateData } </code></pre></li> <li><p>Define the action in the <code>MyAjax</code> controller from <code>Home</code> bundle. E.g.</p> <pre><code>public function updateDataAction(){ $request = $this-&gt;container-&gt;get('request'); $data1 = $request-&gt;query-&gt;get('data1'); $data2 = $request-&gt;query-&gt;get('data2'); ... //handle data ... //prepare the response, e.g. $response = array("code" =&gt; 100, "success" =&gt; true); //you can return result as JSON return new Response(json_encode($response)); } </code></pre></li> <li><p>Prepare your <code>AJAX</code> call in your <code>Twig</code> template, e.g.:</p> <pre><code>function aButtonPressed(){ $.post('{{path('AcmeHomeBundle_ajax_update_mydata')}}', {data1: 'mydata1', data2:'mydata2'}, function(response){ if(response.code == 100 &amp;&amp; response.success){//dummy check //do something } }, "json"); } $(document).ready(function() { $('button').on('click', function(){aButtonPressed();}); }); </code></pre> <p>You can change the example by using other AJAX calls.</p></li> </ul>
13,694,605
How to use C source files in a C++ project?
<p>In a C++ project, including .h files of C source files will cause many errors because of different standards between C and C++.<br> How to use C source files in a C++ project (or in main.cpp)?</p>
13,694,703
4
10
null
2012-12-04 01:13:37.06 UTC
13
2019-02-15 14:25:21.677 UTC
2013-08-24 15:41:22.353 UTC
null
15,168
null
1,381,196
null
1
26
c++|c
42,477
<p>For the maximum reliability:</p> <ul> <li>Compile the C source with a C compiler.</li> <li>Compile the C++ source with a C++ compiler</li> <li>Preferably, write the main() function in C++.</li> <li>Link the program with a C++ compiler.</li> </ul> <p>Make sure that the C headers are either themselves aware of C++ or that the C++ code includes the C headers inside an <code>extern "C" { ... }</code> block.</p> <p>Either (C header file <code>cheader.h</code>):</p> <pre><code>#ifndef CHEADER_H_INCLUDED #define CHEADER_H_INCLUDED #ifdef __cplusplus extern "C" { #endif ...main contents of header... #ifdef __cplusplus } #endif #endif /* CHEADER_H_INCLUDED */ </code></pre> <p>or (C++ source code):</p> <pre><code>extern "C" { #include "cheader.h" } </code></pre> <p>Modern C style is very close to the common subset of the C and C++ languages. However, arbitrary C code is not C++ code for any of a very large number of reasons, and simply calling the C source files C++ source files (by changing the extension, or simply by compiling with the C++ compiler) is not guaranteed to be successful. In general, it is easier to compile C as C and C++ as C++ and then link the resulting object files with the C++ compiler (to ensure the correct support libraries are invoked).</p> <p>However, if the MSVC compiler is saying that programs using MFC have to be written solely in C++ (<em>MFC requires C++ compilation (use a .cpp suffix)</em> is the reported error), then you may have no choice but to ensure that your C code is compilable as C++ code. That means you'll have to cast the return values from <code>malloc()</code> et al; you have to worry about other places where you do not use a cast to convert a <code>void *</code> into some other pointer type; you have to worry about <code>sizeof('a') == 4</code> in C and <code>sizeof('a') == 1</code> in C++; you have to ensure that every function is declared before it is used; you have to ensure your C code does not use any C++ keywords (<code>typename</code>, <code>class</code> in particular; also <code>inline</code> sometimes — but the complete list is quite large).</p> <p>In some circles, you'd have to worry about the use of features in C99 that are not in C++2003 or C++2011, such as flexible array members, designated initializers, compound literals, variable-length arrays, and so on. However, if the C code is for MSVC, then that probably isn't going to be a problem; those features are not supported by the MSVC C compiler (it only supports C89, not C99).</p> <p>FWIW: I have a script to hunt down C++ keywords. It contains the following comment:</p> <pre><code># http://en.cppreference.com/w/cpp/keywords # plus JL annotations # and C (&lt;iso646.h&gt;) # and_eq C (&lt;iso646.h&gt;) # alignas (C++11 feature) # alignof (C++11 feature) # asm C (core) # auto(1) C (core) # bitand C (&lt;iso646.h&gt;) # bitor C (&lt;iso646.h&gt;) # bool C99 (&lt;stdbool.h&gt;) # break C (core) # case C (core) # catch # char C (core) # char16_t (C++11 feature) # char32_t (C++11 feature) # class # compl C (&lt;iso646.h&gt;) # const C (core) # constexpr (C++11 feature) # const_cast # continue C (core) # decltype (C++11 feature) # default(1) C (core) # delete(1) # double C (core) # dynamic_cast # else C (core) # enum C (core) # explicit # export # extern C (core) # false C99 (&lt;stdbool.h&gt;) # float C (core) # for C (core) # friend # goto C (core) # if C (core) # inline C (core) # int C (core) # long C (core) # mutable # namespace # new # noexcept (C++11 feature) # not C (&lt;iso646.h&gt;) # not_eq C (&lt;iso646.h&gt;) # nullptr (C++11 feature) # operator # or C (&lt;iso646.h&gt;) # or_eq C (&lt;iso646.h&gt;) # private # protected # public # register C (core) # reinterpret_cast # return C (core) # short C (core) # signed C (core) # sizeof C (core) # static C (core) # static_assert (C++11 feature) # static_cast # struct C (core) # switch C (core) # template # this # thread_local (C++11 feature) # throw # true C99 (&lt;stdbool.h&gt;) # try # typedef C (core) # typeid # typename # union C (core) # unsigned C (core) # using(1) # virtual # void C (core) # volatile C (core) # wchar_t C (core) # while C (core) # xor C (&lt;iso646.h&gt;) # xor_eq C (&lt;iso646.h&gt;) </code></pre> <p>The <code>(1)</code> suffixes is a footnote at CPP Reference:</p> <ul> <li><code>(1)</code> — meaning changed in C++11 </li> </ul>
13,503,734
PHP: Calling another class' method
<p>I'm still learning OOP so this might not even be possible (although I would be surprised if so), I need some help calling another classes method.</p> <p>For example in <code>ClassA I</code> have this method:</p> <pre><code>function getName() { return $this-&gt;name; } </code></pre> <p>now from <code>ClassB</code> (different file, but in the same directory), I want to call <code>ClassA</code>'s <code>getName()</code>, how do I do that? I tried to just do an <code>include()</code> but that does not work.</p> <p>Thanks!</p>
13,503,769
4
4
null
2012-11-21 23:29:00.43 UTC
22
2016-06-15 00:32:12.87 UTC
2016-06-14 20:13:03.25 UTC
null
145,279
null
604,843
null
1
40
php|oop
141,072
<pre><code>//file1.php &lt;?php class ClassA { private $name = 'John'; function getName() { return $this-&gt;name; } } ?&gt; //file2.php &lt;?php include ("file1.php"); class ClassB { function __construct() { } function callA() { $classA = new ClassA(); $name = $classA-&gt;getName(); echo $name; //Prints John } } $classb = new ClassB(); $classb-&gt;callA(); ?&gt; </code></pre>
13,733,299
Initialize MapFragment programmatically with Maps API v2
<p>I'm trying to add a MapFragment to my current Fragment. The use of nested fragments is restricted to FragmentTransactions, you can't use the xml tag in your layout. Also, I want it to be added to the main Fragment when the user presses a button. So, I'm creating the MapFragment programmatically with <code>getInstance()</code> when the user presses that button and adding it to the proper place. It is shown correctly, so far so good.</p> <p>The problem is that after attaching the MapFragment I need to get a reference to <code>GoogleMap</code> <strong>to place a Marker</strong>, but the <code>getMap()</code> method returns null (as the fragment's <code>onCreateView()</code> hasn't been called yet).</p> <p>I looked at the demo example code and I found the solution they use is initializing the MapFragment in <code>onCreate()</code> and getting the reference to GoogleMap in <code>onResume()</code>, after <code>onCreateView()</code> has been called.</p> <p>I need to get the reference to GoogleMap right after the MapFragment initialization, because I want the users to be able to show or hide the map with a button. I know a possible solution would be to create the Map at the start as said above and just set it's visibility gone, but I want the map to be off by default so it doesn't take the user's bandwidth if they don't explicitly asked for it.</p> <p>I tried with the <code>MapsInitializer</code>, but doesn't work either. I'm kind of stuck. Any ideas? Here is my testing code so far:</p> <pre><code>public class ParadaInfoFragment extends BaseDBFragment { // BaseDBFragment is just a SherlockFragment with custom utility methods. private static final String MAP_FRAGMENT_TAG = "map"; private GoogleMap mMap; private SupportMapFragment mMapFragment; private TextView mToggleMapa; private boolean isMapVisible = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_parada_info, container, false); mToggleMapa = (TextView) v.findViewById(R.id.parada_info_map_button); return v; } @Override public void onStart() { super.onStart(); mToggleMapa.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isMapVisible) { openMap(); } else { closeMap(); } isMapVisible = !isMapVisible; } }); } private void openMap() { // Creates initial configuration for the map GoogleMapOptions options = new GoogleMapOptions().camera(CameraPosition.fromLatLngZoom(new LatLng(37.4005502611301, -5.98233461380005), 16)) .compassEnabled(false).mapType(GoogleMap.MAP_TYPE_NORMAL).rotateGesturesEnabled(false).scrollGesturesEnabled(false).tiltGesturesEnabled(false) .zoomControlsEnabled(false).zoomGesturesEnabled(false); // Modified from the sample code: // It isn't possible to set a fragment's id programmatically so we set a // tag instead and search for it using that. mMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentByTag(MAP_FRAGMENT_TAG); // We only create a fragment if it doesn't already exist. if (mMapFragment == null) { // To programmatically add the map, we first create a // SupportMapFragment. mMapFragment = SupportMapFragment.newInstance(options); // Then we add it using a FragmentTransaction. FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.parada_info_map_container, mMapFragment, MAP_FRAGMENT_TAG); fragmentTransaction.commit(); } // We can't be guaranteed that the map is available because Google Play // services might not be available. setUpMapIfNeeded(); //XXX Here, getMap() returns null so the Marker can't be added // The map is shown with the previous options. } private void closeMap() { FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction(); fragmentTransaction.remove(mMapFragment); fragmentTransaction.commit(); } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the // map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = mMapFragment.getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { mMap.addMarker(new MarkerOptions().position(new LatLng(37.4005502611301, -5.98233461380005)).title("Marker")); } } } } </code></pre> <p>Thanks</p>
13,734,470
4
3
null
2012-12-05 22:03:55.833 UTC
32
2017-05-04 08:02:02.717 UTC
null
null
null
null
835,787
null
1
50
android|google-maps|android-fragments
62,464
<p>The good AnderWebs gave me an answer in <a href="https://plus.google.com/109061484468633397346/posts/51zFuTpbfiD" rel="noreferrer">Google+</a> but he is too laz.... emm busy to write it here again, so here is the short version: Extend the <code>MapFragment</code> class and override the <code>onCreateView()</code> method. After this method is done we can get a non-null reference to que <code>GoogleMap</code> object.</p> <p>This is my particular solution:</p> <pre><code>public class MiniMapFragment extends SupportMapFragment { private LatLng mPosFija; public MiniMapFragment() { super(); } public static MiniMapFragment newInstance(LatLng posicion){ MiniMapFragment frag = new MiniMapFragment(); frag.mPosFija = posicion; return frag; } @Override public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) { View v = super.onCreateView(arg0, arg1, arg2); initMap(); return v; } private void initMap(){ UiSettings settings = getMap().getUiSettings(); settings.setAllGesturesEnabled(false); settings.setMyLocationButtonEnabled(false); getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(mPosFija,16)); getMap().addMarker(new MarkerOptions().position(mPosFija).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))); } } </code></pre> <p>Now in the previous Fragment class I do</p> <pre><code>mMapFragment = MiniMapFragment.newInstance(new LatLng(37.4005502611301, -5.98233461380005)); </code></pre> <p>Maybe it's not perfect yet, because the screen blinks when showing the map. But not sure if the problem is because of this or something else.</p>
51,653,931
React configuration file for post deployment settings
<p>I've built a reactjs site and trying to get it to be deployable.</p> <p>right now all configuration is done via a config.js which is imported into all modules.</p> <p>But when I build the app, this gets compiled into the deployment js and isn't configurable.</p> <p>I want to have a separate file which a sys admin can configure various settings specific to their enviroment, such as the API end points (the app may not be running on the same server as the backend, and there will not be any access to DNS).</p> <p>Is there a way to do this in react? I do not wish to use 3rd party libraries for this either. </p>
51,655,661
8
3
null
2018-08-02 12:40:44.763 UTC
11
2022-09-06 06:30:09.757 UTC
null
null
null
null
4,296,683
null
1
17
reactjs|react-native
20,425
<p>I've managed to hack together a solution.</p> <p>in the public folder 'config.js'</p> <pre><code>var config = { x: 'y', }; </code></pre> <p>Next wrap the ReactDOM.render (App/index.js in a fucntion like so</p> <pre><code>window.RenderApp = (config) =&gt; { ReactDOM.render(&lt;App _config={config}/&gt;, document.getElementById('root')); } </code></pre> <p>In the index.html add these lines, the window.RenderApp HAS to be at the end, because it relies on bundle.js being imported which is auto added by react and has a random name in production.</p> <pre><code>&lt;/html&gt; ... &lt;head&gt; ... &lt;script type="text/javascript" src="%PUBLIC_URL%/config.js"&gt;&lt;/script&gt; ... &lt;/head&gt; ... &lt;body&gt; ... &lt;/body&gt; &lt;script&gt; window.RenderApp(config); &lt;/script&gt; &lt;/html&gt; </code></pre> <p>lastly to use the config variables in your App.js or what ever you called it</p> <pre><code>... constructor(props) { super(props) console.log(this.props._config) this.state = { .... config: this.props._config, } } ... </code></pre> <p>I found you have to set config to a state variables or else it will randomly throw undefined for the object, now just pass config down the hierarchy to use in your code.</p>
39,490,624
how to debug spring application with gradle
<p>I am working on spring app and need to step through a controller method to see how it works. I am working in eclipse and building my app with <code>gradle bootRun</code> command.</p> <p>How to run it in debug mode?</p> <p>i tried <code>gradle bootRun --debug</code> but it's just debug log, not debug mode</p> <p>i tried <code>gradle help --task bootRun</code> -- this gives me info about task there i saw <code>--debug-jvm</code> option but when i run <code>gradle bootRun --debug-jvm</code> application doesn't start</p>
40,661,369
6
4
null
2016-09-14 12:35:56.433 UTC
19
2022-03-08 23:37:07.487 UTC
2016-09-14 12:53:09.923 UTC
null
5,008,698
null
5,008,698
null
1
58
java|eclipse|spring|debugging|gradle
70,122
<p>After you run <code>gradle bootRun --debug-jvm</code> the application is suspended until you connect your debugger to the port it is listening on (port 5005).</p>
20,465,039
What does WEXITSTATUS(status) return?
<p>I am trying to understand how <code>WEXITSTATUS(status)</code> works. I have come across a piece of code where the return value of <code>WEXITSTATUS(status)</code> is being added to a variable. </p> <p>Here is the snippet:</p> <pre><code>waitpid(-1, &amp;status, 0); counter += WEXITSTATUS(status); </code></pre> <p>How can the return value of <code>WEXITSTATUS</code> be calculated?</p>
20,465,094
1
3
null
2013-12-09 07:07:46.367 UTC
6
2020-05-09 05:54:35.727 UTC
2015-12-15 09:23:12.927 UTC
null
694,576
null
1,487,396
null
1
38
c|unix|signals|posix|fork
122,898
<p><code>WEXITSTATUS(stat_val)</code> is a macro (so in fact it does not "<em>return</em>" something, but "evaluates" to something).</p> <p>For how it works you might like to look it up in the headers (which should be <code>#include</code>d via <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_wait.h.html" rel="noreferrer"><code>&lt;sys/wait.h&gt;</code></a>) that come with the C-compiler you use.</p> <p>The implementation of this macro might differ from one C-implementation to the other.</p> <p>Please note, that this macro only gives a sane value, if the macro <code>WIFEXITED(stat_val)</code> gave you a value unequal to <code>0</code>.</p> <p>Verbatim from <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html" rel="noreferrer"><code>waitpid()</code>'s POSIX specification</a>:</p> <blockquote> <p>WEXITSTATUS(<em>stat_val</em>)</p> <p>If the value of WIFEXITED(<em>stat_val</em>) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to <a href="https://pubs.opengroup.org/onlinepubs/9699919799/functions/_exit.html" rel="noreferrer"><em>_exit()</em></a> or <a href="https://pubs.opengroup.org/onlinepubs/9699919799/functions/exit.html" rel="noreferrer"><em>exit()</em></a>, or the value the child process returned from <em>main()</em>.</p> </blockquote> <hr> <p>The motivation behind adding up the return code(s?) of a particular program is only known to the code's author and the hopefully existing documentation.</p>
28,700,593
How to import set of icons into Android Studio project
<p>I downloaded collection of icons from <a href="https://developer.android.com/design/downloads/index.html" rel="noreferrer">Android Developers center</a> Each icon in this collection is ordered in forlders according to its resolution: drawable-hdpi, drawable-mdpi, drawable-xhdpi, drawable-xxhdpi.</p> <p>Is there a way to import all the 4 icon's files in one action to Android Studio or I need to copy it one by one? (when I used new->Image Asset , I had to fill a file path, I couldn't fill it with folder path)</p> <p><strong>Update 25/2/15:</strong><br> According to <a href="https://stackoverflow.com/questions/22370237/how-do-i-import-a-custom-made-icon-in-android-studio">this SO question</a>, seems like there is a way to generate the 4 size of icons by <a href="http://romannurik.github.io/AndroidAssetStudio/index.html" rel="noreferrer">Android Asset Studio</a>, and then import the zip file directly to your Android Studio project res folder - has anyone used it? </p>
28,704,026
8
5
null
2015-02-24 16:05:11.507 UTC
35
2020-11-23 07:42:29.783 UTC
2017-05-23 11:47:30.917 UTC
null
-1
null
242,389
null
1
69
android|android-studio|android-ui|android-icons
168,363
<hr> <p><strong>Edit :</strong> After Android Studios 1.5 android support <strong>Vector Asset Studio</strong>.</p> <hr> <p>Follow <a href="https://developer.android.com/studio/write/vector-asset-studio.html#running" rel="noreferrer">this</a>, which says:</p> <blockquote> <p>To start Vector Asset Studio:</p> <ol> <li>In Android Studio, open an Android app project. </li> <li>In the Project window, select the Android view.</li> <li>Right-click the res folder and select New > Vector Asset.</li> </ol> <p><a href="https://i.stack.imgur.com/WEsUo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WEsUo.png" alt="enter image description here"></a></p> </blockquote> <hr> <h2><strong>Old Answer</strong></h2> <p>Go to Settings > Plugin > Browse Repository > Search <a href="https://github.com/winterDroid/android-drawable-importer-intellij-plugin" rel="noreferrer">Android Drawable Import</a></p> <p>This plugin consists of 4 main features.</p> <ol> <li>AndroidIcons Drawable Import</li> <li>Material Icons Drawable Import</li> <li>Scaled Drawable</li> <li>Multisource-Drawable</li> </ol> <p><strong>How to Use Material Icons Drawable Import :</strong> (Android Studio 1.2)</p> <ul> <li>Go to File > Setting > Other Settings > Android Drawable Import</li> </ul> <p><img src="https://i.stack.imgur.com/VYfaN.png" alt="enter image description here"></p> <ul> <li>Download Material Icon and select your downloaded path.</li> </ul> <p><img src="https://i.stack.imgur.com/6fvUa.png" alt="enter image description here"></p> <ul> <li>Now right click on project , New > Material Icon Import</li> </ul> <p><img src="https://i.stack.imgur.com/twNEC.png" alt="enter image description here"></p> <ul> <li>Use your favorite drawable in your project.</li> </ul> <p><img src="https://i.stack.imgur.com/pYC8J.png" alt="enter image description here"> </p>
16,375,077
Using Icon Fonts as Markers in Google Maps V3
<p>I was wondering whether it is possible to use icon font icons (e.g. Font Awesome) as markers in Google Maps V3 to replace the default marker. To show/insert them in a HTML or PHP document the code for the marker would be:</p> <pre><code>&lt;i class="icon-map-marker"&gt;&lt;/i&gt; </code></pre>
27,468,230
8
5
null
2013-05-04 13:56:51.347 UTC
23
2021-06-11 00:44:23.42 UTC
null
null
null
null
2,290,300
null
1
52
google-maps-api-3|google-maps-markers|font-awesome|icon-fonts
57,754
<p>Here's my attempt at the same thing (using "markerwithlabel" utility library) before I realised Nathan did the same more elegantly above: <a href="http://jsfiddle.net/f3xchecf/">http://jsfiddle.net/f3xchecf/</a></p> <pre><code>function initialize() { var myLatLng = new google.maps.LatLng( 50, 50 ), myOptions = { zoom: 4, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP }, map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ), marker = new MarkerWithLabel({ position: myLatLng, draggable: true, raiseOnDrag: true, icon: ' ', map: map, labelContent: '&lt;i class="fa fa-send fa-3x" style="color:rgba(153,102,102,0.8);"&gt;&lt;/i&gt;', labelAnchor: new google.maps.Point(22, 50) }); marker.setMap( map ); } initialize(); </code></pre>
13,036,947
10 GIT lines erased 8Gb form my pc - How to get them back?
<p>I'm a beginner in GIT and didn't know how powerful this program is... I erased 8 Gb from several commands.<br> As I remember I typed the following lines:</p> <pre><code>$git config --global user.name "my name" $git config --global user.email "my email" $git add *.c $git commit -m $git status </code></pre> <p>then I saw a lot of files tracked and untracked, and I tried to remove them (from git). I didn't know I will remove them from my PC. So I did the following:</p> <pre><code>$git rm $git rm --cached *.c </code></pre> <p>this way I removed all the tracked files. So I continued:</p> <pre><code>$git clean -f $git clean -f -d $git clean -f -x $git clean -d -x -n </code></pre> <p>this way I removed some of the untracked files, the ones that weren't used by system (I'm using windows). And now this is what I have:</p> <pre><code>$git status On branch master Initial commit Untracked files: (use "git add &lt;file&gt;..." to include in what will be commited) .gitconfig AppData/ Desktop/ Favourites/ NTUSER.DAT NTUSER.DAT{some characters and numbers} ntuser.dat.LOG1 ntuser.dat.LOG $git checkout fatal: You are on a branch yet to be born </code></pre> <p>Maybe I used more commands but I don't remember! I just want to recover my old files, and I will stop using this lovely Git software.</p>
13,037,141
1
13
null
2012-10-23 18:34:48.603 UTC
13
2018-03-26 00:33:42.19 UTC
2018-03-26 00:33:42.19 UTC
null
1,429,387
null
1,769,195
null
1
4
git|recovery
5,030
<p>Oh boy. I see what you did, and it's not pretty. Let's read the documentation for "git clean":</p> <blockquote> <p>git-clean - Remove untracked files from the working tree</p> </blockquote> <p>This means that <code>git-clean</code> <strong>deletes</strong> files that it <strong>cannot restore.</strong> Git has some safety measures in place so that you don't accidentally run <code>git clean</code> -- it won't delete directories unless you specify <code>-d</code>, won't delete ignored files unless you pass <code>-x</code>, and won't do anything at all unless you specify <code>-f</code>.</p> <p>It looks like you turned your home directory into a Git repository, committed the <code>*.c</code> files, and then deleted everything else.</p> <p>It's basically like running <code>rm -rf *</code>, or <code>del /s *.*</code> in Windows. <strong>Don't do that.</strong></p> <h2>Solution</h2> <p>Restore from backup.</p> <p>If you don't have a backup, then this is a painful object lesson in <em>why</em> we have backups, and you will have to try to recover the deleted files -- and you must turn off your computer and not boot into Windows until this is complete.</p> <h2>Note on "untracked files"</h2> <p>An "untracked file" is a file that is not part of your Git repository. I can see how if you think that untracked files are part of your Git repo, you will try increasingly dangerous things until they are deleted. The untracked files were never part of your Git repo to begin with, so there was nothing you needed to do to remove them from your Git repo.</p> <h2>Note on <code>-f</code></h2> <p>The <code>-f</code> / <code>--force</code> option means "this command will delete data, and I know what I'm doing." Before you type <code>-f</code> at any command prompt you should reflect for a moment to think about what data this command will delete and make sure that you actually want to delete it.</p> <p>For example, <code>git rm</code> takes <code>-f</code> as a parameter. The <code>git rm</code> command will refuse to delete a file with uncommitted changes, because this will destroy the changes. Using <code>-f</code> overrides this behavior, allowing you to destroy data with <code>git rm</code>.</p>
21,440,745
Ruby: Creating a hash key and value from a variable in Ruby
<p>I have a variable <code>id</code> and I want to use it as a key in a hash so that the value assigned to the variable is used as key of the hash.</p> <p>For instance, if I have the variable <code>id = 1</code> the desired resulting hash would be <code>{ 1: 'foo' }</code>.</p> <p>I've tried creating the hash with,</p> <pre><code>{ id: 'foo' } </code></pre> <p>But that doesn't work, instead resulting in a hash with the symbol <code>:id</code> to <code>'foo'</code>.</p> <p>I could have sworn I've done this before but I am completely drawing a blank. </p>
21,441,197
1
5
null
2014-01-29 19:30:06.547 UTC
5
2021-06-20 10:03:42.687 UTC
2021-06-20 10:03:42.687 UTC
null
10,907,864
null
20,774
null
1
83
ruby|hash|syntax
72,395
<p>If you want to populate a new hash with certain values, you can pass them to <a href="http://www.ruby-doc.org/core-1.9.3/Hash.html#method-c-5B-5D" rel="noreferrer"><code>Hash::[]</code></a>:</p> <pre><code>Hash["a", 100, "b", 200] #=&gt; {"a"=&gt;100, "b"=&gt;200} Hash[ [ ["a", 100], ["b", 200] ] ] #=&gt; {"a"=&gt;100, "b"=&gt;200} Hash["a" =&gt; 100, "b" =&gt; 200] #=&gt; {"a"=&gt;100, "b"=&gt;200} </code></pre> <p>So in your case:</p> <pre><code>Hash[id, 'foo'] Hash[[[id, 'foo']]] Hash[id =&gt; 'foo'] </code></pre> <p>The last syntax <code>id =&gt; 'foo'</code> can also be used with <code>{}</code>:</p> <pre><code>{ id =&gt; 'foo' } </code></pre> <p>Otherwise, if the hash already exists, use <a href="http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-5B-5D-3D" rel="noreferrer"><code>Hash#=[]</code></a>:</p> <pre><code>h = {} h[id] = 'foo' </code></pre>
26,476,744
nvm ls-remote command results in "N/A"
<p>I'm trying to install Node with nvm, but when I type any version it's not available. When I type <code>nvm ls-remote</code> I just just get "N/A".</p> <p>I'm able to access the Internet, so I can't figure what could be going on.</p>
26,477,536
18
2
null
2014-10-20 23:49:06.917 UTC
27
2022-07-08 16:38:46.777 UTC
null
null
null
null
1,161,463
null
1
78
node.js|nvm
74,698
<p><strong>Update with comment from LJHarb, who maintains nvm.sh</strong></p> <p>LJHarb suggests that a typical problem causing this is that "the SSL certificate authorities installed in your system have gone out of date". Checking this and trying to fix this would be a better first step.</p> <p>In the case where you believe there <em>is</em> a problem on the nvm.sh side, LJHarb asks that users file a bug on <a href="https://github.com/creationix/nvm/issues">nvm.sh's issue tracker</a>.</p> <p>Feel free to see the original text in the comments section.</p> <p>Also, I'd like to point out that the below solutions are intended as workarounds only to be used temporarily if you're really in a bind. Permanently modifying the exported mirror or the nvm.sh script itself is not recommended.</p> <p><strong>Edit</strong>: Found easier fix</p> <p>You can export the non https version of the mirror it uses to grab the stuff:</p> <pre class="lang-sh prettyprint-override"><code>export NVM_NODEJS_ORG_MIRROR=http://nodejs.org/dist </code></pre> <p>Then nvm works</p> <p><strong>Pre edit</strong></p> <p>Had the same problem just now.</p> <p>Looks like by default it tries to use curl if it's available on your system.</p> <p>I assume you're on linux also, so try running <code>curl $NVM_NODEJS_ORG_MIRROR</code> and see if you get the same error I did:</p> <pre class="lang-none prettyprint-override"><code>curl: (77) error setting certificate verify locations: CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none </code></pre> <p>Maybe some cert is expired or otherwise misconfigured (or someone's doing something nasty), until it's fixed, if you don't mind going around the security issue, you can find the nvm.sh file (should be at <code>~/.nvm/nvm.sh</code> if you followed the install info), and you can add a <code>-k</code> on line 17 after the curl, so it looks like this:</p> <pre class="lang-none prettyprint-override"><code>-- nvm.sh -- nvm_download() { 16 if nvm_has "curl"; then 17 curl -k $* 18 elif nvm_has "wget"; then 19 # Emulate curl with wget ... } </code></pre> <p>Don't forget to restart your shell, then try <code>nvm ls-remote</code>. Assuming the fix worked, you should be able to use nvm now.</p>
19,721,473
Creating a text editor for iOS 7
<p><strong>Problem</strong></p> <p>I need to understand how TextKit works and how I can use it to build a text editor. I need to figure out how to draw ONLY the visible text the end-user interacts with or determine how I would go about lazily applying attributes to the visible text only without applying attributes to the entire changed range of text in the processEditing method.</p> <p><strong>Background</strong></p> <p>iOS 7 came out with TextKit. I have a tokenizer and code that fully implements TextKit (refer to Apple's TextKitDemo project -- a link is provided below)... and it works. However, it is REALLY slow. As text is parsed, by the NSTextStorage, it requires you to colorize the ENTIRE range of the edited text, in the processEditing method, on the same thread. Offloading the work to a thread doesn't help. It's simply too slow. I got to the point where I can re-attribute only the modified ranges, but if the range is too big the process will be slow. In some conditions the entire document could be invalidated after a change has been made.</p> <p>Here are some ideas I have. Please let me know if any of these will work or maybe nudge me in the right direction.</p> <p>1) Multiple NSTextContainers</p> <p>Reading the docs it appears that I can add multiple NSTextContainers within an NSLayoutManager. I'm assuming that by doing this I should be able to define not only the number of lines that can be drawn in the NSTextContainer, but I should also be able to know which NSTextContainer is visible to the end-user. I know that if I go this route I will need to invest a LOT of time just to see if it's feasible. Initial testing suggests that you only need one NSTextContainer. So I would have to subclass NSLayout or create a wrapper where the layout manager determines which text goes into which text container. Yuck. Also, I have NO idea how TextKit lets me know that it is time to draw a particular NSTextContainer... maybe this isn't how it works!</p> <p>2) Invalidating Ranges w/ NSLayoutManager </p> <p>Invalidating the layoutManager using the invalidateLayoutForCharacterRange:actualCharacterRange:. But what does this actually do and how will it offload the text attribution phase? When does it let me know that a particular text needs to be highlighted? Also, I see that the NSLayoutManager will lazily draw glyphs... how? when? How does this help me? How do I tap into this call so that I can attribute the backing string before it actually lays out the text? </p> <p>3) Over-riding the NSLayoutManager drawGlyphsForGlyphRange:atPoint: method.</p> <p>I really do not want to do this. That being said, in Mac OS X, NSAttributedStrings have this concept of temporary attributes where the style information is used only for presentation. This speeds up the process of highlighting GREATLY! The problem is, it doesn't exist in the iOS 7 TextKit framework (or it's there and I just don't know about it). I believe that by over-riding this method it will give me the same type of speeds you would get by using temporary attributes... as I could answer all of the layout, color and formatting questions in this method without ever touching the NSTextStorage attributed string. The only problem is, I don't know how this method works in relation to other methods provided in the NSLayoutManager class. Does it keep state of the width and height? Does it modify the size of the NSTextContainer when it's too small? Also, it only draws glyphs for characters that have been added in the text buffer. It doesn't re-draw the whole screen. only a tiny section of it... and that's perfectly fine. I have some ideas of how I could work with this... but I really have no desire to layout the glyphs. That is WAY too much work and I haven't found a good example that does this.</p> <p>I would greatly appreciate any help you have to offer.</p> <p>As a thank you, I'm listing all of the frameworks and references I have used over the last few years that have helped me get to where I am now in the hopes that they are helpful to you.</p> <p>Syntax highlighting frameworks:</p> <ul> <li><a href="http://colorer.sourceforge.net/">http://colorer.sourceforge.net/</a></li> <li><a href="https://github.com/MikeJ1971/Glint">https://github.com/MikeJ1971/Glint</a> (Does not support strings, comments, etc.)</li> <li><a href="https://projects.gnome.org/gtksourceview/features.html">https://projects.gnome.org/gtksourceview/features.html</a> (Provides a decent lib for token generation. Works with GTK but could potentially be re-written for a different layout manager)</li> <li><a href="http://parsekit.com/">http://parsekit.com/</a> (Good parser. However, you have to wrap the API to create a state machine when needing to repair ranges)</li> <li><a href="http://svn.gna.org/viewcvs/etoile/trunk/Etoile/Languages/LanguageKit/">http://svn.gna.org/viewcvs/etoile/trunk/Etoile/Languages/LanguageKit/</a></li> <li><a href="https://github.com/CodaFi/IDEKit">https://github.com/CodaFi/IDEKit</a> (AMAZING work. There is a ton of good ideas in this code. My problem is that I have absolutely no idea how it repairs ranges, or even if it does)</li> <li><a href="http://www.crimsoneditor.com/">http://www.crimsoneditor.com/</a> (An old Windows code editor. It has a very good tokenizer -- albeit a little difficult to read. It doesn't use regex expressions. That being said, I based my token logic off of this code and it is MUCH faster than any of the frameworks listed above)</li> </ul> <p>Resources:</p> <ul> <li><a href="http://cocoafactory.com/blog/2012/10/29/how-to-use-custom-nsattributedstring-attributes/">http://cocoafactory.com/blog/2012/10/29/how-to-use-custom-nsattributedstring-attributes/</a></li> <li><a href="https://github.com/objcio/issue-5-textkit">https://github.com/objcio/issue-5-textkit</a></li> <li><a href="http://alexgorbatchev.com/SyntaxHighlighter/">http://alexgorbatchev.com/SyntaxHighlighter/</a></li> <li><a href="http://docs.xamarin.com/samples/TextKitDemo/">http://docs.xamarin.com/samples/TextKitDemo/</a> (Apple's demo)</li> <li><a href="http://cocoadev.com/ImplementSyntaxHighlighting">http://cocoadev.com/ImplementSyntaxHighlighting</a> (Be sure to read all of the child articles. Great stuff)</li> </ul> <p>Most of these frameworks are the same. They either do not account for context switching (or you have to write the wrapper to provide context) for ranges or they do not repair context ranges as a user modifies the text (such as strings, multi-line comments, etc.). The last requirement is VERY important. Because if a tokenizer can't determine which ranges are affected by a change you will end up having to parse and attribute the entire string again. The only exception to this is the Crimson Editor. The issue with this tokenizer is that it doesn't save state at the time of tokenizing. At draw time, the algorithm uses the tokens to determine the state of drawing. It starts from the top of the document, up until it gets to the visible range of text. Needless to say, I have optimized this by cacheing the state of the document in certain parts of the document. </p> <p>The other issue is that the frameworks do not follow the same MVC pattern that Apple does -- which is to be expected. The frameworks that have a complete working editor all use hooks, provided by the API they are built on (ie GTK, Windows, etc.), that provides them with information of where and when to draw to what part of the screen. In my case, TextKit appears to require you to attribute the entire changed range in processEditing.</p> <p>Maybe my observations are wrong. (I hope they are!!) Maybe, ParseKit for instance, will work for what I need it to do and I simply don't understand how to use it. If so, please let me know! And thanks again!</p>
19,946,370
1
3
null
2013-11-01 05:46:24.75 UTC
17
2013-11-13 05:52:48.89 UTC
null
null
null
null
455,791
null
1
16
ios|objective-c|syntax-highlighting|parsekit|textkit
3,052
<p>I figured it out. I used none of the suggestions above. That being said, the performance I am getting now is simply incredible. Keep in mind that YMMV. The way you tokenize and cache meta-data about your string may be different than me. However, I was able to type in a 1400 line PHP file and it took only 0.015 seconds for any one change to complete. Simply incredible.</p> <p>Here is the approach I took:</p> <p>My UIViewController is a delegate to UITextViewDelegate and UIScrollViewDelegate.</p> <p>When UITextViewDelegate.textViewDidChange: is called I determine which range of text is currently visible to the end-user. I did this by using my existing sub-classed UITextView and adding this method to it:</p> <pre><code>- (NSRange)visibleRangeOfText { CGRect bounds = self.bounds; UITextPosition *start = [self characterRangeAtPoint:bounds.origin].start; UITextPosition *end = [self characterRangeAtPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))].end; return NSMakeRange([self offsetFromPosition:self.beginningOfDocument toPosition:start], [self offsetFromPosition:start toPosition:end]); } </code></pre> <p>After that, I pass the range to a subclassed NSTextStorage object, where it will then perform the magic to determine which lines need to be highlighted.</p> <p>The same goes for the UIScollViewDelegate method calls. Depending on which part of the view is being viewed I pass in the visible range to my subclassed NSTextStorage call and it determines if the lines have already been attributed, etc.</p> <p>I realize I'm leaving a lot up to the reader. I ended up using what I currently had and tweaked it a bit to work with the above implementation.</p> <p>I wanted to share some of my discoveries that I found interesting while implementing this:</p> <p>1) If you attempt to highlight any text ABOVE the current line, where the cursor is resting, you may see that the cursor "jumps" up within the view, and then settles back to the position where it was originally. I am almost positive this is caused by the NSTextStorage.processEditing method call. I was able to get it to where the system only highlights the line that was modified... so this issue is gone now.</p> <p>2) Originally I did this to prevent the cursor from jumping around:</p> <pre><code>NSRange selectedRange = [textView selectedTextRange]; [textView setScrollEnabled:NO]; NSRange visibleRange = [textView visibleRangeOfText]; [textStorage applyAttributesToRange:visibleRange]; [textView setScrollEnabled:YES]; </code></pre> <p>It worked... but the [textView setScrollEnabled:NO] call made a MASSIVE hit to performance. It took nearly 3/4 of a second for that command alone to finish on a 1400 line file. I'm not sure what causes it to be slow but I thought it was worth mentioning.</p>
19,331,404
str() vs repr() functions in python 2.7.5
<p>what is the difference between <code>str()</code> and <code>repr()</code> functions in python 2.7.5?</p> <p>Explanation on python.org:</p> <blockquote> <p>The <code>str()</code> function is meant to return representations of values which are fairly <strong>human-readable</strong>, while <code>repr()</code> is meant to generate representations which can be <strong>read by the interpreter</strong> (or will force a <code>SyntaxError</code> if there is no equivalent syntax)</p> </blockquote> <p>But it wasn't clear for me.</p> <p>some examples:</p> <pre><code>&gt;&gt;&gt; s = 'Hello, world.' &gt;&gt;&gt; str(s) 'Hello, world.' &gt;&gt;&gt; repr(s) "'Hello, world.'" # repr is giving an extra double quotes &gt;&gt;&gt; str(1.0/7.0) '0.142857142857' &gt;&gt;&gt; repr(1.0/7.0) '0.14285714285714285' # repr is giving value with more precision </code></pre> <p>so I want to know the following</p> <ol> <li>When should I use <code>str()</code> and when should I use <code>repr()</code>?</li> <li>In which cases I can use either of them?</li> <li>What can <code>str()</code> do which <code>repr()</code> can't?</li> <li>What can <code>repr()</code> do which <code>str()</code> can't?</li> </ol>
19,331,543
1
6
null
2013-10-12 06:48:59.94 UTC
12
2016-09-21 20:29:16.153 UTC
2013-10-12 07:02:57.563 UTC
null
100,297
null
2,818,583
null
1
34
python|string|python-2.7|repr
48,568
<blockquote> <p>When should i use str() and when should i use repr() ?</p> </blockquote> <p>Almost always use <code>str()</code> when creating output for end users. </p> <p><code>repr()</code> is mainly useful for debugging and exploring. For example, if you suspect a string has non printing characters in it, or a float has a small rounding error, <code>repr()</code> will show you; <code>str()</code> may not.</p> <p><code>repr()</code> can also be useful for generating literals to paste into your source code. It can also be used for persistence (with <code>ast.literal_eval</code> or <code>eval</code>), but this is rarely a good idea--if you want editable persisted values, something like JSON or YAML is much better, and if you don't plan to edit them, use pickle.</p> <blockquote> <p>2.In which cases i can use either of them ?</p> </blockquote> <p>Well, you <em>can</em> use them almost anywhere. You <em>shouldn't</em> generally use them except as described above.</p> <blockquote> <p>3.What can <code>str()</code> do which <code>repr()</code> can't ?</p> </blockquote> <p>Give you output fit for end-user consumption--not always (e.g., str(['spam', 'eggs']) isn't likely to be anything you want to put in a GUI), but more often than <code>repr()</code>.</p> <blockquote> <p>4.What can <code>repr()</code> do which <code>str()</code> can't</p> </blockquote> <p>Give you output that's useful for debugging--again, not always (the default for instances of user-created classes is rarely helpful), but whenever possible.</p> <p>And sometimes give you output that's a valid Python literal or other expression--but you rarely want to rely on that except for interactive exploration.</p>
17,396,796
How to deploy my spray API into production?
<p>I'm thinking about how should be the process to deploy my already locally tested rest api to the cloud, lets say an infrastructure as a service (not a platform as a service such as Heroku) like amazon.</p> <p>I have my local envorinment set up with sbt up and running but my question is How should I deploy this in a production environment?</p> <p>Is it sane to define a process in which the devops pulls the most recent changes from the git repo and then simply executes sbt run?</p> <p>I want to know how does the teams that uses scala+spray+sbt deploys their apis to a production environment.</p>
17,399,574
3
0
null
2013-07-01 02:44:18.487 UTC
16
2014-03-17 17:17:00.57 UTC
null
null
null
null
1,757,407
null
1
23
scala|akka|spray
7,618
<p>The heart of our services is scala + akka + spray + mongo. So we are using GitHub for version control. After merging checked PRs to the master branch, Jenkins automaticaly tests'n'builds project. If all tests were successful then Jenking runs a couple of scripts: </p> <ol> <li>Increment project version (currently written in shell, but will be changed to sbt)</li> <li>Run assembly task with <a href="https://github.com/sbt/sbt-assembly">sbt-assembly</a></li> <li>Run deploy script (written in Python with Fabric) wich deploys our jar to EC2</li> </ol> <p>Basicaly on the thrid step you have a couple of choices:</p> <p><strong>Make a runnable jar using IO/Spray boot file:</strong></p> <pre><code>object Boot extends App { implicit val system = ActorSystem("ServiceName") val log = system.log val service = system.actorOf(Props[Service], name="serviceActor") IO(Http) ! Http.Bind(service, interface = host, port = port) } </code></pre> <p><strong>Make a runnable jar as Akka's microkernel:</strong></p> <p>In this case you should extend Bootable trait and override <code>startup</code> and <code>shutdown</code> methods:</p> <pre><code>class Kernel extends Bootable { // many lines of code def startup() { scheduler.start() SomeActorSystem.startup() } def shutdown() { scheduler.shutdown() SomeActorSystem.shutdown() system.shutdown() } } </code></pre> <p><strong>Using a TypeSafe startscript:</strong></p> <p>Can't show an example, but it has a good intro on <a href="https://github.com/sbt/sbt-start-script">github</a> =)</p> <p>We are using all of this way in different cases. </p>
17,267,248
How/Where do I get geoJSON data for states, provinces, and administrative regions of non-US countries?
<p>I need geoJSON formatted paths for states, provinces, and regions within multiple countries. Most readily available geoJSON data is for US states and country level boundaries, not regions within the country. This geoJSON will be used to create a geographic visualization using D3.js.</p>
17,267,249
4
2
null
2013-06-24 02:28:17.17 UTC
36
2020-08-08 12:09:43.017 UTC
null
null
null
null
352,311
null
1
36
d3.js|shapefile|geojson
47,189
<p>There is a good writeup on how to generate geoJSON from shapefiles here<br/> <a href="http://vallandingham.me/shapefile_to_geojson.html" rel="noreferrer">http://vallandingham.me/shapefile_to_geojson.html</a></p> <p>The steps below should take you from start to finish:</p> <ol> <li><p>Install the Quantum GIS framework <a href="http://www.qgis.org/e/qgis" rel="noreferrer">http://www.qgis.org/e/qgis</a>.<br/> If you are on Mac OS X, you can use this version <a href="http://www.kyngchaos.com/software" rel="noreferrer">http://www.kyngchaos.com/software</a><br/> This will give you the ogr2ogr utility used for converting shapefiles to geoJSON</p></li> <li><p>Download the shapefiles for your country from here <a href="http://www.gadm.org/country" rel="noreferrer">http://www.gadm.org/country</a> and unzip</p></li> <li><p>For Canada, and possibly other countries, the shapefile with suffix 0 is for the country boundary and the suffix 1 is for the internal regions. Not sure if this naming is consistent across countries.</p></li> <li><p>Upload the region level shapefile to MapShaper <a href="http://mapshaper.com/test/MapShaper.swf" rel="noreferrer">http://mapshaper.com/test/MapShaper.swf</a><br/> You can skip this step if you don't care to optimize the size of your resulting geoJSON</p></li> <li><p>Set the 'simplification level' slider in MapShaper to the desired level and export the simplified shapefile as 'Shapefile - Polygons'</p></li> <li><p>Download .shp and .shx file to the local directory where you unzipped the original shapefiiles, replace the original files with the simplified ones.</p></li> <li><p>Navigate to the local directory and run the command below, replacing <em>&lt;shapefile&gt;</em> with the actual name of the shapefile you want to convert.</p> <p><em>ogr2ogr -f geoJSON regions.json &lt;shapefile&gt;.shp</em></p></li> </ol> <p>You should now have the regions for your country in geoJSON format. Check to make sure there are paths defined in regions.json and that property fields were maintained (ex. region name).</p>
17,188,279
String concatenation while incrementing
<p>This is my code:</p> <pre><code>$a = 5; $b = &amp;$a; echo ++$a.$b++; </code></pre> <p>Shouldn't it print 66?</p> <p>Why does it print 76?</p>
17,190,739
3
13
null
2013-06-19 09:56:24.677 UTC
14
2013-06-19 16:00:58.72 UTC
2013-06-19 16:00:58.72 UTC
null
1,253,312
null
2,500,553
null
1
38
php|post-increment|pre-increment
2,885
<p>Alright. This is actually pretty straight forward behavior, and it has to do with how references work in PHP. It is not a bug, but unexpected behavior.</p> <p>PHP internally uses copy-on-write. Which means that the internal variables are copied when you write to them (so <code>$a = $b;</code> doesn't copy memory until you actually change one of them). With references, it never actually copies. That's important for later.</p> <p>Let's look at those opcodes:</p> <pre><code>line # * op fetch ext return operands --------------------------------------------------------------------------------- 2 0 &gt; ASSIGN !0, 5 3 1 ASSIGN_REF !1, !0 4 2 PRE_INC $2 !0 3 POST_INC ~3 !1 4 CONCAT ~4 $2, ~3 5 ECHO ~4 6 &gt; RETURN 1 </code></pre> <p>The first two should be pretty easy to understand. </p> <ul> <li><strong>ASSIGN</strong> - Basically, we're assinging the value of <code>5</code> into the compiled variable named <code>!0</code>.</li> <li><strong>ASSIGN_REF</strong> - We're creating a reference from <code>!0</code> to <code>!1</code> (the direction doesn't matter)</li> </ul> <p>So far, that's straight forward. Now comes the interesting bit:</p> <ul> <li><strong>PRE_INC</strong> - This is the opcode that actually increments the variable. Of note is that it returns its result into a temporary variable named <code>$2</code>.</li> </ul> <p>So let's look at <a href="http://lxr.php.net/xref/PHP_TRUNK/Zend/zend_vm_execute.h#12481">the source code behind <code>PRE_INC</code></a> when called with a variable:</p> <pre><code>static int ZEND_FASTCALL ZEND_PRE_INC_SPEC_VAR_HANDLER(ZEND_OPCODE_HANDLER_ARGS) { USE_OPLINE zend_free_op free_op1; zval **var_ptr; SAVE_OPLINE(); var_ptr = _get_zval_ptr_ptr_var(opline-&gt;op1.var, execute_data, &amp;free_op1 TSRMLS_CC); if (IS_VAR == IS_VAR &amp;&amp; UNEXPECTED(var_ptr == NULL)) { zend_error_noreturn(E_ERROR, "Cannot increment/decrement overloaded objects nor string offsets"); } if (IS_VAR == IS_VAR &amp;&amp; UNEXPECTED(*var_ptr == &amp;EG(error_zval))) { if (RETURN_VALUE_USED(opline)) { PZVAL_LOCK(&amp;EG(uninitialized_zval)); AI_SET_PTR(&amp;EX_T(opline-&gt;result.var), &amp;EG(uninitialized_zval)); } if (free_op1.var) {zval_ptr_dtor(&amp;free_op1.var);}; CHECK_EXCEPTION(); ZEND_VM_NEXT_OPCODE(); } SEPARATE_ZVAL_IF_NOT_REF(var_ptr); if (UNEXPECTED(Z_TYPE_PP(var_ptr) == IS_OBJECT) &amp;&amp; Z_OBJ_HANDLER_PP(var_ptr, get) &amp;&amp; Z_OBJ_HANDLER_PP(var_ptr, set)) { /* proxy object */ zval *val = Z_OBJ_HANDLER_PP(var_ptr, get)(*var_ptr TSRMLS_CC); Z_ADDREF_P(val); fast_increment_function(val); Z_OBJ_HANDLER_PP(var_ptr, set)(var_ptr, val TSRMLS_CC); zval_ptr_dtor(&amp;val); } else { fast_increment_function(*var_ptr); } if (RETURN_VALUE_USED(opline)) { PZVAL_LOCK(*var_ptr); AI_SET_PTR(&amp;EX_T(opline-&gt;result.var), *var_ptr); } if (free_op1.var) {zval_ptr_dtor(&amp;free_op1.var);}; CHECK_EXCEPTION(); ZEND_VM_NEXT_OPCODE(); } </code></pre> <p>Now I don't expect you to understand what that's doing right away (this is deep engine voodoo), but let's walk through it. </p> <p>The first two if statements check to see if the variable is "safe" to increment (the first checks to see if it's an overloaded object, the second checks to see if the variable is the special error variable <code>$php_error</code>).</p> <p>Next is the really interesting bit for us. Since we're modifying the value, it needs to preform copy-on-write. So it calls:</p> <pre><code>SEPARATE_ZVAL_IF_NOT_REF(var_ptr); </code></pre> <p>Now, remember, we already set the variable to be a reference above. So the variable is not separated... Which means everything we do to it here will happen to <code>$b</code> as well...</p> <p>Next, the variable is incremented (<code>fast_increment_function()</code>). </p> <p>Finally, it sets the result <strong>as itself</strong>. This is copy-on-write again. It's not returning the <strong>value</strong> of the operation, but the actual <strong>variable</strong>. So what <code>PRE_INC</code> returns is <strong>still a reference to <code>$a</code> and <code>$b</code></strong>. </p> <ul> <li><strong>POST_INC</strong> - This behaves similarly to <code>PRE_INC</code>, except for one VERY important fact.</li> </ul> <p>Let's check out <a href="http://lxr.php.net/xref/PHP_TRUNK/Zend/zend_vm_execute.h#12575">the source code</a> again:</p> <pre><code>static int ZEND_FASTCALL ZEND_POST_INC_SPEC_VAR_HANDLER(ZEND_OPCODE_HANDLER_ARGS) { retval = &amp;EX_T(opline-&gt;result.var).tmp_var; ZVAL_COPY_VALUE(retval, *var_ptr); zendi_zval_copy_ctor(*retval); SEPARATE_ZVAL_IF_NOT_REF(var_ptr); fast_increment_function(*var_ptr); } </code></pre> <p>This time I cut away all of the non-interesting stuff. So let's look at what it's doing.</p> <p>First, it gets the return temporary variable (<code>~3</code> in our code above). </p> <p>Then it <strong>copies</strong> the value from its argument (<code>!1</code> or <code>$b</code>) into the result (and hence the reference is broken).</p> <p>Then it increments the argument.</p> <p>Now remember, the argument <code>!1</code> is the variable <code>$b</code>, which has a reference to <code>!0</code> (<code>$a</code>) <strong>and</strong> <code>$2</code>, which if you remember was the result from <code>PRE_INC</code>.</p> <p>So there you have it. It returns 76 because the reference is maintained in PRE_INC's result.</p> <p>We can prove this by forcing a copy, by assigning the pre-inc to a temporary variable first (through normal assignment, which will break the reference):</p> <pre><code>$a = 5; $b = &amp;$a; $c = ++$a; $d = $b++; echo $c.$d; </code></pre> <p>Which works as you expected. <a href="http://3v4l.org/6QiHr">Proof</a></p> <p>And we can reproduce the other behavior (your bug) by introducing a function to maintain the reference:</p> <pre><code>function &amp;pre_inc(&amp;$a) { return ++$a; } $a = 5; $b = &amp;$a; $c = &amp;pre_inc($a); $d = $b++; echo $c.$d; </code></pre> <p>Which works as you're seeing it (76): <a href="http://3v4l.org/AkdgC">Proof</a></p> <p>Note: the only reason for the separate function here is that PHP's parser doesn't like <code>$c = &amp;++$a;</code>. So we need to add a level of indirection through the function call to do it...</p> <p>The reason I don't consider this a bug is that it's how references are supposed to work. Pre-incrementing a referenced variable will return that variable. Even a non-referenced variable should return that variable. It may not be what you expect here, but it works quite well in almost every other case...</p> <h1>The Underlying Point</h1> <p>If you're using references, you're doing it wrong about 99% of the time. So don't use references unless you <strong>absolutely</strong> need them. PHP is a lot smarter than you may think at memory optimizations. And your use of references really hinders how it can work. So while you think you may be writing smart code, you're really going to be writing less efficient and less friendly code the vast majority of the time...</p> <p>And if you want to know more about References and how variables work in PHP, checkout <a href="http://www.youtube.com/watch?v=_YZIBWQr_yk">One Of My YouTube Videos</a> on the subject...</p>
73,654,810
Why does String creation using `newInstance()` method behave different when using `var` compared to using explicit type `String`?
<p>I am learning about reflection in Java. By accident, I discovered the following, for me unexpected behavior.</p> <p>Both tests as written below succeed.</p> <pre class="lang-java prettyprint-override"><code>class NewInstanceUsingReflection { @Test void testClassNewInstance() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { final var input = &quot;A string&quot;; final var theClass = input.getClass(); final var constructor = theClass.getConstructor(); final String newString = constructor.newInstance(); assertEquals(&quot;&quot;, newString); } @Test void testClassNewInstanceWithVarOnly() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { final var input = &quot;A string&quot;; final var theClass = input.getClass(); final var constructor = theClass.getConstructor(); final var newString = constructor.newInstance(); assertEquals(&quot;A string&quot;, newString); } } </code></pre> <p>The only difference apart from the assertion is that the <strong><code>newString</code></strong> variable type is explicit in the first test and declared as <code>var</code> in the second test.</p> <p>I'm using java 17 and the junit5 test framework.</p> <p>Why is the value of <code>newString</code> an empty string in the first test and the <code>input</code> string value in the second test?</p> <p>Does it have something todo with the string-pool?</p> <p>Or is something else going on?</p>
73,655,162
1
4
null
2022-09-08 20:39:50.86 UTC
6
2022-09-10 15:55:56.74 UTC
2022-09-10 15:55:56.74 UTC
null
19,952,766
null
19,952,766
null
1
69
java|reflection|string-pool
1,924
<p>Java17, same problem. The explanation is clearly: bug.</p> <p>decompiling it, the relevant section:</p> <pre><code> 20: anewarray #2 // class java/lang/Object 23: invokevirtual #35 // Method java/lang/reflect/Constructor.newInstance:([Ljava/lang/Object;)Ljava/lang/Object; 26: checkcast #41 // class java/lang/String 29: astore 4 31: ldc #23 // String A string 33: ldc #23 // String A string 35: invokevirtual #43 // Method java/lang/String.equals:(Ljava/lang/Object;)Z </code></pre> <p><code>astore 4</code> is where the result goes, which is nowhere: slot 4 is not used any further. Instead, the same string constant is loaded twice, trivially resulting in, effectively, <code>&quot;A string&quot;.equals(&quot;A string&quot;)</code>, which is of course <code>true</code>.</p> <p>Replacing <code>var</code> with String, recompiling, and rerunning <code>javap</code>:</p> <pre><code> 20: anewarray #2 // class java/lang/Object 23: invokevirtual #35 // Method java/lang/reflect/Constructor.newInstance:([Ljava/lang/Object;)Ljava/lang/Object; 26: checkcast #41 // class java/lang/String 29: astore 4 31: ldc #23 // String A string 33: aload 4 35: invokevirtual #43 // Method java/lang/String.equals:(Ljava/lang/Object;)Z </code></pre> <p>Identical in every way, except the second <code>ldc</code> is the correct <code>aload 4</code>.</p> <p>I'm having a hard time figuring out what's happening here. It feels more like the <code>var</code> is somehow causing that <code>ldc</code> to duplicate (in contrast to an analysis incorrectly thinking that the values are guaranteed to be identical; javac intentionally does very little such optimizations).</p> <p>I'm having a <em>really</em> hard time figuring out how this has been in <strong>2</strong> LTS releases. Impressive find.</p> <p>Next step is to verify on the <a href="https://jdk.java.net/18/" rel="noreferrer">latest JDK (18)</a>, and then to <a href="https://bugs.java.com/bugdatabase/" rel="noreferrer">file a bug</a>. I did a quick look if it has been reported already, but I'm not sure what search terms to use. I didn't find any report in my search, though.</p> <p>NB: The decompilation traces were produced using <code>javap -c -v NewInstanceUsingReflection</code>.</p> <p>EDIT: Just tried on ecj (<code>Eclipse Compiler for Java(TM) v20210223-0522, 3.25.0, Copyright IBM Corp 2000, 2020. All rights reserved.</code>) - bug doesn't happen there.</p>
30,368,739
How to draw a simple rounded rect in swift (rounded corners)
<p>I managed to draw a rect :-) But I don't know how to draw a rounded rect.</p> <p>Can someone help me out with the following code how to round the rect?</p> <pre><code>let canvas = UIGraphicsGetCurrentContext() rec = CGRectMake(0, 0, 40, 40); //var maskPath = UIBezierPath(roundedRect: rec, byRoundingCorners: .BottomLeft | .BottomRight, cornerRadii: CGSize(width: 3, height: 3)) CGContextAddRect(canvas, rec); CGContextFillPath(canvas); </code></pre>
30,369,145
6
3
null
2015-05-21 08:47:03.207 UTC
7
2021-07-24 16:44:59.343 UTC
2019-05-18 21:12:56.86 UTC
null
1,265,393
null
1,344,545
null
1
24
ios|swift|drawing
45,441
<p>//Put this code in ur drawRect</p> <p><strong>Objective - C</strong></p> <pre><code> - (void)drawRect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSaveGState(ctx); CGPathRef clippath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(x,y, width, height) cornerRadius:6].CGPath; CGContextAddPath(ctx, clippath); CGContextSetFillColorWithColor(ctx, self.color.CGColor); CGContextClosePath(ctx); CGContextFillPath(ctx); [self.color set]; [_path closePath]; // Implicitly does a line between p4 and p1 [_path fill]; // If you want it filled, or... [_path stroke]; // ...if you want to draw the outline. CGContextRestoreGState(ctx); } </code></pre> <p><strong>Swift 3</strong></p> <pre><code>func drawRect(rect : CGRect) { // Size of rounded rectangle let rectWidth = rect.width let rectHeight = rect.height // Find center of actual frame to set rectangle in middle let xf:CGFloat = (self.frame.width - rectWidth) / 2 let yf:CGFloat = (self.frame.height - rectHeight) / 2 let ctx: CGContext = UIGraphicsGetCurrentContext()! ctx.saveGState() let rect = CGRect(x: xf, y: yf, width: rectWidth, height: rectHeight) let clipPath: CGPath = UIBezierPath(roundedRect: rect, cornerRadius: rectCornerRadius).cgPath ctx.addPath(clipPath) ctx.setFillColor(rectBgColor.cgColor) ctx.closePath() ctx.fillPath() ctx.restoreGState() } </code></pre>
26,218,766
WPF MVVM: Binding a different ViewModel to each TabItem?
<p>I have a main window with a tab control containing 2 <code>tabItem</code>s:</p> <p><img src="https://i.stack.imgur.com/7cD4i.png" alt="Main Window"></p> <p>I currently have 1 <code>ViewModel</code> which services Tab1 &amp; Tab2. This <code>ViewModel</code> is becoming a little bloated with blurred SOC. I want to split the logic into 2 viewmodels: ViewModel 1 &amp; ViewModel2. My understanding is that you can set the Main Window <code>DataContext</code> to a Base ViewModel which holds a collection of ViewModels &amp; then you can assert each TabItem to a different ViewModel.</p> <p>The example's I've seen of these base ViewModels expose an ObservableCOllection like so:</p> <pre><code>private ObservableCollection&lt;ViewModel1&gt; _viewModelCollection Public Observable Collection&lt;ViewModel1&gt; ViewModelCollection { get { return _viewModelCollection; } set { _viewModelCollection = value; OnPropertyChanged("ViewModelCollection"); } } public BaseViewModel() { ViewModelCollection = new ObservableCollection&lt;ViewModel1&gt;(); ViewModelCollection.Add(new ViewModel1(Tab1); ViewModelCollection.Add(new ViewModel1(Tab2); } </code></pre> <p>But how do I assign a different ViewModel to each TabItem? I would want Tab1= ViewModel1 &amp; Tab2=ViewModel2?</p>
26,219,522
5
3
null
2014-10-06 14:45:40.303 UTC
10
2020-05-04 15:38:07.82 UTC
2015-07-09 17:10:33.333 UTC
null
64,161
null
1,860,030
null
1
21
c#|wpf|mvvm
21,228
<p>You can indeed add the view models for your tabs to a main view model. You can then bind to the child view models in the XAML for your tabs.</p> <p>Say that you have three viewmodels: <code>MainViewModel</code>, <code>Tab1ViewModel</code>, and <code>Tab2ViewModel</code>. On your <code>MainViewModel</code> you keep a collection of your tab viewmodels:</p> <pre><code>class MainViewModel { ObservableCollection&lt;object&gt; _children; public MainViewModel() { _children = new ObservableCollection&lt;object&gt;(); _children.Add(new Tab1ViewModel()); _children.Add(new Tab2ViewModel()); } public ObservableCollection&lt;object&gt; Children { get { return _children; } } } </code></pre> <p>After setting the <code>DataContext</code> of your main window to your <code>MainViewModel</code> you can bind the <code>DataContext</code> of your tabs by referencing the <code>Children</code> property:</p> <pre><code>&lt;TabControl&gt; &lt;TabItem DataContext="{Binding Children[0]}" x:Name="Tab1" Header="Tab1" &gt; &lt;!-- Tab content --&gt; &lt;/TabItem&gt; &lt;TabItem DataContext="{Binding Children[1]}" x:Name="Tab2" Header="Tab2" &gt; &lt;!-- Tab content --&gt; &lt;/TabItem&gt; &lt;/TabControl&gt; </code></pre>
5,297,122
Preventing cache on back-button in Safari 5
<p>As of recent safari 5 was released, and it turns out to cause some problems for my website. I have a dynamic website running classic ASP (though that shouldn't matter much) and the site has some creative use of the history stack. For instance, you can be on a page that lists products, then go to details about a product and change the product (admin-view). When you click save on the product the information is sent to the server via AJAX, and a <code>history.back()</code> is issued. This works great in all browsers (including safari &lt;= 4), however, in the newly released safari 5 it stopped working. It seems that when you click back in safari 5 it doesn't actually refresh the page, it only loads it from cache, which means that the changes made in the details view isn't shown. How can I go about to make this work in safari 5 as well? This is the current code I have to turn off caching (included at the top of every page):</p> <pre><code>Dim pStr pStr = "private, no-cache, no-store, must-revalidate" Response.AddHeader "pragma","no-cache" '? Response.AddHeader "cache-control", pStr '? Er ikke sikker på om disse 3 siste er nødvendige. Response.AddHeader "cache-control", "post-check=0, pre-check=0" '? Er ikke sikker på om disse 3 siste er nødvendige. Response.AddHeader "Expires", "Mon, 26 Jul 1997 05:00:00 GMT" '? Response.AddHeader "Last-Modified", Now() </code></pre>
15,497,411
3
0
null
2011-03-14 10:02:53.557 UTC
9
2013-11-12 16:51:00.783 UTC
null
null
null
null
213,323
null
1
23
safari|cache-control
19,175
<p>The empty <code>unload</code> handler will not work anymore. Instead you can check the <code>persisted</code> property of the <code>onpageshow</code> event. It is set to false on initial page load. When page is loaded from bfcache it is set to true. </p> <p>Kludgish solution is to force a reload when page is loaded from bfcache.</p> <pre><code>window.onpageshow = function(event) { if (event.persisted) { window.location.reload() } }; </code></pre> <p>If you are using jQuery then do:</p> <pre><code>$(window).bind("pageshow", function(event) { if (event.originalEvent.persisted) { window.location.reload() } }); </code></pre>
22,956,978
Instagram Unable to reach callback URL
<p>I'm having weird problem that instagram won't allow me to subscribe to more tags. I subscribed yesterday to 3 tags without any problem, I tried today with new tag and no effect. Does somebody else have same problems?</p> <p>I keep getting APISubscriptionError code 400 Unable to reach callback URL, but that URL is globaly accessible, even instagram is calling it every 5 min for tags i added yesterday.</p> <p>Any ideas?</p>
22,994,889
3
13
null
2014-04-09 08:33:47.483 UTC
9
2016-10-17 09:19:47.443 UTC
null
null
null
null
1,521,122
null
1
20
instagram
3,844
<p><strong>This problem has now been fixed.</strong> </p> <p>If it re-appears, here is workaround that I developed dealing with similar problems with the real-time API over the past couple years.</p> <p>Set your system up to use both the real-time API as well as the search API as a fallback. Ingest data coming through the real-time calls, but also periodically poll the search endpoint (either media/search or tag/search, depending on your application) for data you might have missed, ignoring IDs your system has already seen.</p> <p>Your system will be much more resilient to issues with the Instagram API and also allow restarting your system periodically without missing data (since you can catch back up to real-time).</p> <p>I keep track of "seen" Instagram IDs in a Redis set.</p>
15,126,824
Tips for creating "Context Free Grammar"
<p>I am new to CFG's,<br> Can someone give me tips in creating CFG that generates some language</p> <p>For example </p> <blockquote> <p><code> L = {a<sup>m</sup> b<sup>n</sup> | m >= n} </code></p> </blockquote> <p>What I got is:</p> <blockquote> <p><code>S<sub>o</sub> -> a | aS<sub>o</sub> | aS<sub>1</sub> | e </code><br> <code>S<sub>1</sub> -> b | bS<sub>1</sub> | e </code></p> </blockquote> <p>but I think this area is wrong, because there is a chance that the number of <strong><code>b</code></strong>'s can be greater than <strong><code>a</code></strong>'s.</p>
15,130,451
4
0
null
2013-02-28 03:20:21.237 UTC
22
2017-07-17 06:08:46.343 UTC
2013-10-21 08:17:04.387 UTC
null
1,673,391
user1988365
null
null
1
14
grammar|context-free-grammar|lexical-analysis|formal-languages
90,884
<h2>How to write CFG with example a<sup>m</sup>b<sup>n</sup></h2> <blockquote> <p>L = {a<sup>m</sup> b<sup>n</sup> | m >= n}. </p> </blockquote> <p><strong>Language description:</strong> a<sup>m</sup> b<sup>n</sup> consist of <strong><code>a</code></strong> followed by <strong><code>b</code></strong> where number of <strong><code>a</code></strong> are equal or more then number of <strong><code>b</code></strong>. </p> <p>some example strings: <code>{^, a, aa, aab, aabb, aaaab, ab......}</code></p> <p>So there is always one <strong><code>a</code></strong> for one <strong><code>b</code></strong> but extra <strong><code>a</code></strong> are possible. infect string can be consist of <strong><code>a</code></strong> only. Also notice <strong><code>^</code></strong> null is a member of language because in <strong><code>^</code></strong> <code>NumberOf(a) = NumberOf(b) = 0</code></p> <blockquote> <p>How to write a grammar that accepts the language formed by strings a<sup>m</sup> b<sup>n</sup>? </p> </blockquote> <p>In the grammar, there should be rules such that if you add a <strong><code>b</code></strong> symbol you also add a <strong><code>a</code></strong> symbol. </p> <p>and this can be done with something like: </p> <pre><code> S --&gt; aSb </code></pre> <p>But this is incomplete because we need a rule to generate extra <code>a</code>s: </p> <pre><code> A --&gt; aA | a </code></pre> <p>Combine two production rules into a single grammar <strong>CFG.</strong> </p> <pre><code> S --&gt; aSb | A A --&gt; aA | a </code></pre> <p>So you can generate any string that consist of <strong><code>a</code></strong> also <strong><code>a</code></strong> and <strong><code>b</code></strong> in (a<sup>m</sup> b<sup>n</sup>) pattern. </p> <p>But in above grammar there is <strong>no</strong> way to generate <strong><code>^</code></strong> string. </p> <p>So, change this grammar like this: </p> <pre><code> S --&gt; B | ^ B --&gt; aBb | A A --&gt; aA | a </code></pre> <p>this grammar can generate {a<sup>m</sup> b<sup>n</sup> | m >= n} language. </p> <p><strong>Note</strong>: to generate <code>^</code> null string, I added an extra first step in grammar by adding <code>S--&gt; B | ^</code>, So you can either add <code>^</code> or your string of symbol <strong><code>a</code></strong> and <strong><code>b</code></strong>. (<em>now <code>B</code> plays role of <code>S</code> from previous grammar to generate equal numbers of <strong><code>a</code></strong> and <strong><code>b</code></em></strong>) </p> <p><strong>Edit:</strong> Thanks to @Andy Hayden<br> You can also write equivalent grammar for same language {a<sup>m</sup> b<sup>n</sup> | m >= n}: </p> <pre><code> S --&gt; aSb | A A --&gt; aA | ^ </code></pre> <p>notice: here <code>A --&gt; aA | ^</code> can generate zero or any number of <strong><code>a</code></strong>. And that should be preferable to my grammar because it generates a smaller parse tree for the same string.<br> (<em>smaller in height preferable because of efficient parsing</em>) </p> <p>The following <strong>tips</strong> may be helpful to write Grammar for a formal language: </p> <blockquote> <ul> <li>You are to be clear about language that what it describes (meaning/pattern). </li> <li>You can remember solutions for some basic problems(the idea being that you can write new grammars). </li> <li>You can write rules for fundamental languages like <a href="https://stackoverflow.com/questions/13816439/left-linear-and-right-linear-grammars/13945932#13945932">I have written for RE in this example to write Right-Linear-Grammmar</a>. The rules will help you to write Grammar for New Languages. </li> <li>One different approach is to first draw <em>automata</em>, then convert automata to Grammar. We have predefined techniques to write grammar from automata from any class of formal language. </li> <li>Like a Good Programmer who learns by reading the code of others, similarly one can learn to write grammars for formal languages. </li> </ul> </blockquote> <p><sub>Also the grammar you have written is wrong.</sub></p>
15,365,871
Code for parsing a key/value in in file from shell script
<p>I have a file that I need to look up a value by key using a shell script. The file looks like:</p> <pre><code>HereIsAKey This is the value </code></pre> <p>How can I do something like:</p> <pre><code>MyVar=Get HereIsAKey </code></pre> <p>and then MyVar should equal "This is the value". The key has no whitespace and the value should be everything following whitespace after the key.</p>
15,366,113
6
0
null
2013-03-12 15:52:31.65 UTC
7
2014-09-30 10:58:32.787 UTC
null
null
null
null
602,543
null
1
17
linux|bash
51,302
<p>if <code>HereIsAKey</code> is unique in your file, try this with grep:</p> <pre><code>myVar=$(grep -Po "(?&lt;=^HereIsAKey ).*" file) </code></pre>
15,123,054
Adding tabindex dynamically
<p>I'd like to add <code>tabindex</code> to all form elements. The form is dynamic and I can't add it to the HTML. I would like to run it as a function.</p> <p>If there are several radio buttons with the same name, each must have it's own <code>tabindex</code> value. Most of the form elements on page start as <code>&lt;input&gt;</code>, except <code>&lt;select&gt;</code>. How do I account for that?</p> <p>I guess I will need to run a loop and add the attribute, right?</p> <pre class="lang-js prettyprint-override"><code>var n = 1; $('input, select').each(function() { $(this).attr('tabindex', n++); }); </code></pre>
15,123,392
5
1
null
2013-02-27 21:46:24.227 UTC
5
2022-08-08 14:42:14.313 UTC
2020-11-17 10:02:47.637 UTC
null
9,132,582
null
434,218
null
1
37
html|jquery|accessibility|tabindex
89,817
<p>Strange question, but yes that's the basic idea:</p> <pre><code>$(":input:not(:hidden)").each(function (i) { $(this).attr('tabindex', i + 1); }); </code></pre> <p>This uses <a href="http://api.jquery.com/input-selector/" rel="noreferrer">:input</a> to get everything including buttons and text areas. <code>:not(:hidden)</code> will just exclude the hidden inputs to avoid unnecessary tabs.</p>
15,256,600
passing 2 $index values within nested ng-repeat
<p>So I have an ng-repeat nested within another ng-repeat in order to build a nav menu. On each <code>&lt;li&gt;</code> on the inner ng-repeat loop I set an ng-click which calls the relevant controller for that menu item by passing in the $index to let the app know which one we need. However I need to also pass in the $index from the outer ng-repeat so the app knows which section we are in as well as which tutorial.</p> <pre><code>&lt;ul ng-repeat="section in sections"&gt; &lt;li class="section_title {{section.active}}" &gt; {{section.name}} &lt;/li&gt; &lt;ul&gt; &lt;li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu($index)" ng-repeat="tutorial in section.tutorials"&gt; {{tutorial.name}} &lt;/li&gt; &lt;/ul&gt; &lt;/ul&gt; </code></pre> <p>here's a Plunker <a href="http://plnkr.co/edit/bJUhI9oGEQIql9tahIJN?p=preview">http://plnkr.co/edit/bJUhI9oGEQIql9tahIJN?p=preview</a></p>
15,257,501
6
1
null
2013-03-06 19:46:51.7 UTC
53
2019-06-02 12:41:00.353 UTC
2016-06-10 07:03:13.633 UTC
null
219,547
null
555,116
null
1
332
angularjs|angularjs-ng-repeat
190,641
<p>Each ng-repeat creates a child scope with the passed data, and also adds an additional <code>$index</code> variable in that scope.</p> <p>So what you need to do is reach up to the parent scope, and use that <code>$index</code>.</p> <p>See <a href="http://plnkr.co/edit/FvVhirpoOF8TYnIVygE6?p=preview" rel="noreferrer">http://plnkr.co/edit/FvVhirpoOF8TYnIVygE6?p=preview</a></p> <pre><code>&lt;li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu($parent.$index)" ng-repeat="tutorial in section.tutorials"&gt; {{tutorial.name}} &lt;/li&gt; </code></pre>
14,989,274
Is it possible to determine the number of elements of a c++ enum class?
<p>Is it possible to determine the cardinality of a c++ <code>enum class</code>:</p> <pre><code>enum class Example { A, B, C, D, E }; </code></pre> <p>I tried to use <code>sizeof</code>, however, it returns the size of an enum element.</p> <pre><code>sizeof(Example); // Returns 4 (on my architecture) </code></pre> <p>Is there a standard way to get the cardinality (5 in my example) ?</p>
14,989,325
15
5
null
2013-02-20 20:27:11.34 UTC
18
2022-09-14 14:44:14.87 UTC
2013-12-02 02:12:34.25 UTC
null
493,122
null
1,695,593
null
1
110
c++|c++11|cardinality|enum-class
88,437
<p>Not directly, but you could use the following trick:</p> <pre><code>enum class Example { A, B, C, D, E, Count }; </code></pre> <p>Then the cardinality is available as <code>static_cast&lt;int&gt;(Example::Count)</code>.</p> <p>Of course, this only works nicely if you let values of the enum be automatically assigned, starting from 0. If that's not the case, you can manually assign the correct cardinality to Count, which is really no different from having to maintain a separate constant anyway:</p> <pre><code>enum class Example { A = 1, B = 2, C = 4, D = 8, E = 16, Count = 5 }; </code></pre> <p>The one disadvantage is that the compiler will allow you to use <code>Example::Count</code> as an argument for an enum value -- so be careful if you use this! (I personally find this not to be a problem in practice, though.)</p>
43,747,397
Simulate a button click in Jest
<p>Simulating a button click seems like a very easy/standard operation. Yet, I can't get it to work in Jest.js tests.</p> <p>This is what I tried (and also doing it using jQuery), but it didn't seem to trigger anything:</p> <pre><code>import { mount } from 'enzyme'; page = &lt;MyCoolPage /&gt;; pageMounted = mount(page); const button = pageMounted.find('#some_button'); expect(button.length).toBe(1); // It finds it alright button.simulate('click'); // Nothing happens </code></pre>
46,211,877
8
6
null
2017-05-02 21:17:51.67 UTC
29
2022-07-09 20:12:13.15 UTC
2020-09-24 17:45:29.247 UTC
null
63,550
null
7,007,593
null
1
129
javascript|reactjs|testing|jestjs|enzyme
312,390
<p><strong>#1 Using Jest</strong></p> <p>This is how I use the Jest mock callback function to test the click event:</p> <pre><code>import React from 'react'; import { shallow } from 'enzyme'; import Button from './Button'; describe('Test Button component', () =&gt; { it('Test click event', () =&gt; { const mockCallBack = jest.fn(); const button = shallow((&lt;Button onClick={mockCallBack}&gt;Ok!&lt;/Button&gt;)); button.find('button').simulate('click'); expect(mockCallBack.mock.calls.length).toEqual(1); }); }); </code></pre> <p>I am also using a module called <a href="https://github.com/airbnb/enzyme" rel="noreferrer">enzyme</a>. Enzyme is a testing utility that makes it easier to assert and select your React Components</p> <p><strong>#2 Using Sinon</strong></p> <p>Also, you can use another module called <a href="https://github.com/sinonjs/sinon" rel="noreferrer">Sinon</a> which is a standalone test spy, stubs and mocks for JavaScript. This is how it looks:</p> <pre><code>import React from 'react'; import { shallow } from 'enzyme'; import sinon from 'sinon'; import Button from './Button'; describe('Test Button component', () =&gt; { it('simulates click events', () =&gt; { const mockCallBack = sinon.spy(); const button = shallow((&lt;Button onClick={mockCallBack}&gt;Ok!&lt;/Button&gt;)); button.find('button').simulate('click'); expect(mockCallBack).toHaveProperty('callCount', 1); }); }); </code></pre> <p><strong>#3 Using Your own Spy</strong></p> <p>Finally, you can make your own naive spy (I don't recommend this approach unless you have a valid reason for that).</p> <pre><code>function MySpy() { this.calls = 0; } MySpy.prototype.fn = function () { return () =&gt; this.calls++; } it('Test Button component', () =&gt; { const mySpy = new MySpy(); const mockCallBack = mySpy.fn(); const button = shallow((&lt;Button onClick={mockCallBack}&gt;Ok!&lt;/Button&gt;)); button.find('button').simulate('click'); expect(mySpy.calls).toEqual(1); }); </code></pre>
38,377,276
Instance variables in methods outside the constructor (Python) -- why and how?
<p>My questions concern instance variables that are initialized <em>in methods outside the class constructor</em>. This is for Python. </p> <p>I'll first state what I understand: </p> <ol> <li>Classes may define a constructor, and it may also define other methods.</li> <li>Instance variables are generally defined/initialized within the constructor.</li> <li>But instance variables can also be defined/initialized <em>outside</em> the constructor, e.g. in the other methods of the same class. </li> <li><p>An example of (2) and (3) -- see <em>self.meow</em> and <em>self.roar</em> in the <strong>Cat</strong> class below:</p> <pre><code>class Cat(): def __init__(self): self.meow = "Meow!" def meow_bigger(self): self.roar = "Roar!" </code></pre></li> </ol> <p>My questions:</p> <ol> <li><p>Why is it best practice to initialize the instance variable within the constructor? </p></li> <li><p>What general/specific mess could arise if instance variables are regularly initialized in methods other than the constructor? (E.g. Having read Mark Lutz's Tkinter guide in his Programming Python, which I thought was excellent, I noticed that the instance variable used to hold the PhotoImage objects/references were initialized in the further methods, not in the constructor. It seemed to work without issue there, but could that practice cause issues in the long run?)</p></li> <li><p>In what scenarios would it be <em>better</em> to initialize instance variables in the other methods, rather than in the constructor?</p></li> </ol> <hr> <ol start="4"> <li><p>To my knowledge, instance variables exist not when the class object is created, but <em>after</em> the class object is instantiated. Proceeding upon my code above, I demonstrate this: </p> <pre><code>&gt;&gt; c = Cat() &gt;&gt; c.meow 'Meow!' &gt;&gt; c.roar Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Cat' object has no attribute 'roar' &gt;&gt;&gt; c.meow_bigger() &gt;&gt;&gt; c.roar 'Roar!' </code></pre> <p>As it were:</p> <ul> <li>I cannot access the instance variable (<em>c.roar</em>) at first. </li> <li>However, after I have called the instance method <em>c.meow_bigger()</em> once, I am suddenly able to access the instance variable <em>c.roar</em>. </li> <li>Why is the above behaviour so?</li> </ul></li> </ol> <p>Thank you for helping out with my understanding.</p>
38,378,757
7
3
null
2016-07-14 14:44:44.433 UTC
11
2020-03-30 13:21:46.277 UTC
2016-07-14 15:51:59.45 UTC
null
283,169
null
283,169
null
1
27
python|class|constructor|instance-variables
17,215
<blockquote> <p>Why is it best practice to initialize the instance variable within the constructor?</p> </blockquote> <h2>Clarity.</h2> <p>Because it makes it easy to see at a glance all of the attributes of the class. If you initialize the variables in multiple methods, it becomes difficult to understand the complete data structure without reading every line of code.</p> <p>Initializing within the <code>__init__</code> also makes documentation easier. With your example, you can't write "an instance of Cat has a <code>roar</code> attribute". Instead, you have to add a paragraph explaining that an instance of Cat might have a "roar" attribute, but only after calling the "meow_louder" method. </p> <p>Clarity is king. One of the smartest programmers I ever met once told me "show me your data structures, and I can tell you how your code works without seeing any of your code". While that's a tiny bit hyperbolic, there's definitely a ring of truth to it. One of the biggest hurdles to learning a code base is understanding the data that it manipulates. </p> <blockquote> <p>What general/specific mess could arise if instance variables are regularly initialized in methods other than the constructor?</p> </blockquote> <p>The most obvious one is that an object may not have an attribute available during all parts of the program, leading to having to add a lot of extra code to handle the case where the attribute is undefined.</p> <blockquote> <p>In what scenarios would it be better to initialize instance variables in the other methods, rather than in the constructor?</p> </blockquote> <p>I don't think there are any.</p> <p>Note: you don't necessarily have to initialize an attribute with it's final value. In your case it's acceptable to initialize <code>roar</code> to <code>None</code>. The mere fact that it has been initialized to <em>something</em> shows that it's a piece of data that the class maintains. It's fine if the value changes later. </p>
7,970,082
Mongoose: populate() / DBref or data duplication?
<p><strong>I have two collections:</strong></p> <ol> <li>Users</li> <li>Uploads</li> </ol> <p><br> Each upload has a <code>User</code> associated with it and I need to know their details when an <code>Upload</code> is viewed. Is it best practice to duplicate this data inside the the Uploads record, or use <a href="http://mongoosejs.com/docs/populate.html">populate()</a> to pull in these details from the Users collection referenced by <code>_id</code>?</p> <p><br> <strong>OPTION 1</strong></p> <pre><code>var UploadSchema = new Schema({ _id: { type: Schema.ObjectId }, _user: { type: Schema.ObjectId, ref: 'users'}, title: { type: String }, }); </code></pre> <p><br> <strong>OPTION 2</strong></p> <pre><code>var UploadSchema = new Schema({ _id: { type: Schema.ObjectId }, user: { name: { type: String }, email: { type: String }, avatar: { type: String }, //...etc }, title: { type: String }, }); </code></pre> <p><br> With 'Option 2' if any of the data in the <code>Users</code> collection changes I will have to update this across all associated <code>Upload</code> records. With 'Option 1' on the other hand I can just chill out and let <code>populate()</code> ensure the latest User data is always shown.</p> <p><strong>Is the overhead of using <code>populate()</code> significant? What is the best practice in this common scenario?</strong></p>
8,026,373
2
0
null
2011-11-01 17:07:53.6 UTC
9
2017-07-09 13:17:58.723 UTC
2017-09-22 18:01:22.247 UTC
null
-1
null
516,629
null
1
14
node.js|mongodb|mongoose|nosql
6,369
<p>If You need to query on your Users, keep users alone. If You need to query on your uploads, keep uploads alone.</p> <p>Another question you should ask yourself is: Every time i need this data, do I need the embedded objects (and vice-versa)? How many time this data will be updated? How many times this data will be read?</p> <p><strong>Think about a friendship request:</strong> Each time you need the request you need the user which made the request, then embed the request inside the user document.</p> <p>You will be able to create an index on the embedded object too, and your search will be mono query / fast / consistent.</p> <hr> <p><em>Just a link to my previous reply on a similar question:</em> <a href="https://stackoverflow.com/questions/3128200/mongo-db-relations-between-objects/7287321#7287321">Mongo DB relations between objects</a></p> <p>I think this post will be right for you <a href="http://www.mongodb.org/display/DOCS/Schema+Design" rel="nofollow noreferrer">http://www.mongodb.org/display/DOCS/Schema+Design</a></p> <p><strong>Use Cases</strong></p> <p><em>Customer / Order / Order Line-Item</em></p> <blockquote> <p>Orders should be a collection. customers a collection. line-items should be an array of line-items embedded in the order object.</p> </blockquote> <p><em>Blogging system.</em></p> <blockquote> <p>Posts should be a collection. post author might be a separate collection, or simply a field within posts if only an email address. comments should be embedded objects within a post for performance.</p> </blockquote> <p><strong>Schema Design Basics</strong></p> <p><em>Kyle Banker, 10gen</em></p> <blockquote> <p><a href="http://www.10gen.com/presentation/mongosf2011/schemabasics" rel="nofollow noreferrer">http://www.10gen.com/presentation/mongosf2011/schemabasics</a></p> </blockquote> <p><em>Indexing &amp; Query Optimization Alvin Richards, Senior Director of Enterprise Engineering</em></p> <blockquote> <p><a href="http://www.10gen.com/presentation/mongosf-2011/mongodb-indexing-query-optimization" rel="nofollow noreferrer">http://www.10gen.com/presentation/mongosf-2011/mongodb-indexing-query-optimization</a></p> </blockquote> <p>**These 2 videos are the bests on mongoddb ever seen imho*</p>
23,871,757
The std::transform-like function that returns transformed container
<p>I'm trying to implement a function similar to <code>std::transform</code> algorithm but instead of taking the output iterator by an argument I want to create and return a container with transformed input elements. </p> <p>Let's say that it's named <code>transform_container</code> and takes two arguments: container and functor. It should return the same container type but possibly parametrized by a different element type (the Functor can return element of different type).</p> <p>I'd like to use my function as in the example below:</p> <pre><code>std::vector&lt;int&gt; vi{ 1, 2, 3, 4, 5 }; auto vs = transform_container(vi, [] (int i) { return std::to_string(i); }); //vs will be std::vector&lt;std::string&gt; assert(vs == std::vector&lt;std::string&gt;({"1", "2", "3", "4", "5"})); std::set&lt;int&gt; si{ 5, 10, 15 }; auto sd = transform_container(si, [] (int i) { return i / 2.; }); //sd will be of type std::set&lt;double&gt; assert(sd == std::set&lt;double&gt;({5/2., 10/2., 15/2.})); </code></pre> <p>I was able two write two functions — one for <code>std::set</code> and one for <code>std::vector</code> — that seem to work properly. They are identical, except of the container typename. Their code is listed below.</p> <pre><code>template&lt;typename T, typename Functor&gt; auto transform_container(const std::vector&lt;T&gt; &amp;v, Functor &amp;&amp;f) -&gt; std::vector&lt;decltype(f(*v.begin()))&gt; { std::vector&lt;decltype(f(*v.begin()))&gt; ret; std::transform(std::begin(v), std::end(v), std::inserter(ret, ret.end()), f); return ret; } template&lt;typename T, typename Functor&gt; auto transform_container(const std::set&lt;T&gt; &amp;v, Functor &amp;&amp;f) -&gt; std::set&lt;decltype(f(*v.begin()))&gt; { std::set&lt;decltype(f(*v.begin()))&gt; ret; std::transform(std::begin(v), std::end(v), std::inserter(ret, ret.end()), f); return ret; } </code></pre> <p>However, when I attempted to merge them into a single general function that works with any container, I encountered numerous issues. The <code>set</code> and <code>vector</code> are class templates, so my function template must take a template template parameter. Moreover, set and vector templates have a different number of type parameters that needs to be properly adjusted. </p> <p>What is the best way to generalize the two function templates above into a function that works with any compatible container type?</p>
23,872,330
5
5
null
2014-05-26 13:53:05.147 UTC
15
2020-12-10 11:56:01.783 UTC
null
null
null
null
2,617,356
null
1
45
c++|templates|c++11|stl
11,353
<h3>Simplest cases: matching container types</h3> <p>For the simple case where the input type matches the output type (which I've since realized is not what you're asking about) go one level higher. Instead of specifying the type <code>T</code> that your container uses, and trying to specialize on a <code>vector&lt;T&gt;</code>, etc., just specify the type of the container itself:</p> <pre><code>template &lt;typename Container, typename Functor&gt; Container transform_container(const Container&amp; c, Functor &amp;&amp;f) { Container ret; std::transform(std::begin(c), std::end(c), std::inserter(ret, std::end(ret)), f); return ret; } </code></pre> <h3>More complexity: compatible value types</h3> <p>Since you want to try to change the item type stored by the container, you'll need to use a template template parameter, and modify the <code>T</code> to that which the returned container uses.</p> <pre><code>template &lt; template &lt;typename T, typename... Ts&gt; class Container, typename Functor, typename T, // &lt;-- This is the one we'll override in the return container typename U = std::result_of&lt;Functor(T)&gt;::type, typename... Ts &gt; Container&lt;U, Ts...&gt; transform_container(const Container&lt;T, Ts...&gt;&amp; c, Functor &amp;&amp;f) { Container&lt;U, Ts...&gt; ret; std::transform(std::begin(c), std::end(c), std::inserter(ret, std::end(ret)), f); return ret; } </code></pre> <h3>What of incompatible value types?</h3> <p>This only gets us partway there. It works fine with a transform from <code>signed</code> to <code>unsigned</code> but, when resolving with <code>T=int</code> and <code>U=std::string</code>, and handling sets, it tries to instantiate <code>std::set&lt;std::string, std::less&lt;int&gt;, ...&gt;</code> and thus doesn't compile.</p> <p>To fix this, we want to take an arbitrary set of parameters and replace instances of <code>T</code> with <code>U</code>, even if they are the parameters to other template parameters. Thus <code>std::set&lt;int, std::less&lt;int&gt;&gt;</code> should become <code>std::set&lt;std::string, std::less&lt;std::string&gt;&gt;</code>, and so forth. This involves some custom template meta programming, as suggested by other answers.</p> <h3>Template metaprogramming to the rescue</h3> <p>Let's create a template, name it <code>replace_type</code>, and have it convert <code>T</code> to <code>U</code>, and <code>K&lt;T&gt;</code> to <code>K&lt;U&gt;</code>. First let's handle the general case. If it's not a templated type, and it doesn't match <code>T</code>, its type shall remain <code>K</code>:</p> <pre><code>template &lt;typename K, typename ...&gt; struct replace_type { using type = K; }; </code></pre> <p>Then a specialization. If it's not a templated type, and it does match <code>T</code>, its type shall become <code>U</code>:</p> <pre><code>template &lt;typename T, typename U&gt; struct replace_type&lt;T, T, U&gt; { using type = U; }; </code></pre> <p>And finally a recursive step to handle parameters to templated types. For each type in a templated type's parameters, replace the types accordingly:</p> <pre><code>template &lt;template &lt;typename... Ks&gt; class K, typename T, typename U, typename... Ks&gt; struct replace_type&lt;K&lt;Ks...&gt;, T, U&gt; { using type = K&lt;typename replace_type&lt;Ks, T, U&gt;::type ...&gt;; }; </code></pre> <p>And finally update <code>transform_container</code> to use <code>replace_type</code>:</p> <pre><code>template &lt; template &lt;typename T, typename... Ts&gt; class Container, typename Functor, typename T, typename U = typename std::result_of&lt;Functor(T)&gt;::type, typename... Ts, typename Result = typename replace_type&lt;Container&lt;T, Ts...&gt;, T, U&gt;::type &gt; Result transform_container(const Container&lt;T, Ts...&gt;&amp; c, Functor &amp;&amp;f) { Result ret; std::transform(std::begin(c), std::end(c), std::inserter(ret, std::end(ret)), f); return ret; } </code></pre> <h3>Is this complete?</h3> <p>The problem with this approach is it is not necessarily safe. If you're converting from <code>Container&lt;MyCustomType&gt;</code> to <code>Container&lt;SomethingElse&gt;</code>, it's likely fine. But when converting from <code>Container&lt;builtin_type&gt;</code> to <code>Container&lt;SomethingElse&gt;</code> it's plausible that another template parameter shouldn't be converted from <code>builtin_type</code> to <code>SomethingElse</code>. Furthermore, alternate containers like <code>std::map</code> or <code>std::array</code> bring more problems to the party.</p> <p>Handling <code>std::map</code> and <code>std::unordered_map</code> isn't too bad. The primary problem is that <code>replace_type</code> needs to replace more types. Not only is there a <code>T</code> -&gt; <code>U</code> replacement, but also a <code>std::pair&lt;T, T2&gt;</code> -&gt; <code>std::pair&lt;U, U2&gt;</code> replacement. This increases the level of concern for unwanted type replacements as there's more than a single type in flight. That said, here's what I found to work; note that in testing I needed to specify the return type of the lambda function that transformed my map's pairs:</p> <pre><code>// map-like classes are harder. You have to replace both the key and the key-value pair types // Give a base case replacing a pair type to resolve ambiguities introduced below template &lt;typename T1, typename T2, typename U1, typename U2&gt; struct replace_type&lt;std::pair&lt;T1, T2&gt;, std::pair&lt;T1, T2&gt;, std::pair&lt;U1, U2&gt;&gt; { using type = std::pair&lt;U1, U2&gt;; }; // Now the extended case that replaces T1-&gt;U1 and pair&lt;T1,T2&gt; -&gt; pair&lt;T2,U2&gt; template &lt;template &lt;typename...&gt; class K, typename T1, typename T2, typename U1, typename U2, typename... Ks&gt; struct replace_type&lt;K&lt;T1, T2, Ks...&gt;, std::pair&lt;const T1, T2&gt;, std::pair&lt;const U1, U2&gt;&gt; { using type = K&lt;U1, U2, typename replace_type&lt; typename replace_type&lt;Ks, T1, U1&gt;::type, std::pair&lt;const T1, T2&gt;, std::pair&lt;const U1, U2&gt; &gt;::type ... &gt;; }; </code></pre> <h3>What about std::array?</h3> <p>Handling <code>std::array</code> adds to the pain, as its template parameters cannot be deduced in the template above. As Jarod42 notes, this is due to its parameters including values instead of just types. I've gotten partway by adding specializations and introducing a helper <code>contained_type</code> that extracts <code>T</code> for me (side note, per Constructor this is better written as the much simpler <code>typename Container::value_type</code> and works for all types I've discussed here). Even without the <code>std::array</code> specializations this allows me to simplify my <code>transform_container</code> template to the following (this may be a win even without support for <code>std::array</code>):</p> <pre><code>template &lt;typename T, size_t N, typename U&gt; struct replace_type&lt;std::array&lt;T, N&gt;, T, U&gt; { using type = std::array&lt;U, N&gt;; }; // contained_type&lt;C&gt;::type is T when C is vector&lt;T, ...&gt;, set&lt;T, ...&gt;, or std::array&lt;T, N&gt;. // This is better written as typename C::value_type, but may be necessary for bad containers template &lt;typename T, typename...&gt; struct contained_type { }; template &lt;template &lt;typename ... Cs&gt; class C, typename T, typename... Ts&gt; struct contained_type&lt;C&lt;T, Ts...&gt;&gt; { using type = T; }; template &lt;typename T, size_t N&gt; struct contained_type&lt;std::array&lt;T, N&gt;&gt; { using type = T; }; template &lt; typename Container, typename Functor, typename T = typename contained_type&lt;Container&gt;::type, typename U = typename std::result_of&lt;Functor(T)&gt;::type, typename Result = typename replace_type&lt;Container, T, U&gt;::type &gt; Result transform_container(const Container&amp; c, Functor &amp;&amp;f) { // as above } </code></pre> <p>However the current implementation of <code>transform_container</code> uses <code>std::inserter</code> which does not work with <code>std::array</code>. While it's possible to make more specializations, I'm going to leave this as a template soup exercise for an interested reader. I would personally choose to live without support for <code>std::array</code> in most cases.</p> <p><a href="http://coliru.stacked-crooked.com/a/b01898f8f2dd1753" rel="nofollow noreferrer">View the cumulative live example</a></p> <hr /> <p>Full disclosure: while this approach was influenced by Ali's quoting of Kerrek SB's answer, I didn't manage to get that to work in Visual Studio 2013, so I built the above alternative myself. Many thanks to parts of <a href="https://stackoverflow.com/a/11723847/89999">Kerrek SB's original answer</a> are still necessary, as well as to prodding and encouragement from Constructor and Jarod42.</p>
8,521,819
Performance of synchronize section in Java
<p>I had a small dispute over performance of <code>synchronized</code> block in Java. This is a theoretical question, which does not affect real life application. </p> <p>Consider single-thread application, which uses locks and synchronize sections. Does this code work slower than the same code without synchronize sections? If so, why? We do not discuss concurrency, since it’s only single thread application</p> <p><strong>Update</strong></p> <p>Found interesting <a href="http://www.ibm.com/developerworks/library/j-threads1/index.html" rel="noreferrer">benchmark</a> testing it. But it's from 2001. Things could have changed dramatically in the latest version of JDK</p>
14,386,464
6
3
null
2011-12-15 14:42:01.69 UTC
13
2019-02-15 14:44:51.507 UTC
2019-02-15 14:44:51.507 UTC
null
2,361,308
null
1,100,081
null
1
44
java|multithreading|performance|concurrency|synchronization
33,717
<p>There are 3 type of locking in HotSpot</p> <ol> <li><strong>Fat</strong>: JVM relies on OS mutexes to acquire lock.</li> <li><strong>Thin</strong>: JVM is using CAS algorithm. </li> <li><strong>Biased</strong>: CAS is rather expensive operation on some of the architecture. Biased locking - is special type of locking optimized for scenario when only one thread is working on object.</li> </ol> <p>By default JVM uses <strong>thin</strong> locking. Later if JVM determines that there is no contention thin locking is converted to <strong>biased</strong> locking. Operation that changes type of the lock is rather expensive, hence JVM does not apply this optimization immediately. There is special JVM option - <strong>XX:BiasedLockingStartupDelay=delay</strong> which tells JVM when this kind of optimization should be applied.</p> <p>Once biased, that thread can subsequently lock and unlock the object without resorting to expensive atomic instructions. </p> <p>Answer to the question: it depends. But if biased, the single threaded code with locking and without locking has average same performance.</p> <ul> <li><a href="https://blogs.oracle.com/dave/entry/biased_locking_in_hotspot" rel="noreferrer">Biased Locking in HotSpot </a> - Dave Dice's Weblog</li> <li><a href="https://wiki.openjdk.java.net/display/HotSpot/Synchronization" rel="noreferrer">Synchronization and Object Locking</a> - Thomas Kotzmann and Christian Wimmer</li> </ul>
4,959,524
When to check for EINTR and repeat the function call?
<p>I am programming a user application for a embedded Linux system, and I am using the common functions such as open, close, read, ioctl, etc. for the devices. Now, I read about EINTR, indicates that the function was interrupted by a signal, but I am not sure about the implications. In all the example programs I have, sometimes it is done, e.g. ioctl(), sometimes it is not done, e.g. read(). So, I am a little bit confused.</p> <p>When do I preferably check for EINTR and repeat the function call?</p>
4,960,077
4
2
null
2011-02-10 16:06:30.153 UTC
10
2020-01-17 22:33:34.017 UTC
2014-01-31 08:50:37.183 UTC
null
589,206
null
216,831
null
1
43
linux|eintr
34,971
<p>See sigaction : <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/sigaction.html" rel="noreferrer">http://pubs.opengroup.org/onlinepubs/009695399/functions/sigaction.html</a></p> <pre><code>SA_RESTART This flag affects the behavior of interruptible functions; that is, those specified to fail with errno set to EINTR. If set, and a function specified as interruptible is interrupted by this signal, the function shall restart and shall not fail with EINTR unless otherwise specified. If the flag is not set, interruptible functions interrupted by this signal shall fail with errno set to EINTR. </code></pre> <p>By default, you have the SA_RESTART behavior, so you don't have to worry about EINTR, if you don't play with signals.</p>
5,423,058
QFuture that can be cancelled and report progress
<p>The <code>QFuture</code> class has methods such as <code>cancel()</code>, <code>progressValue()</code>, etc. These can apparently be monitored via a <code>QFutureWatcher</code>. However, the documentation for <code>QtConcurrent::run()</code> reads:</p> <blockquote> <p>Note that the QFuture returned by QtConcurrent::run() does not support canceling, pausing, or progress reporting. The QFuture returned can only be used to query for the running/finished status and the return value of the function.</p> </blockquote> <p>I have looked in vain for what method actually <em>can</em> create a <code>QFuture</code> that can be cancelled and report progress for a single long-running operation. (It looks like maybe <code>QtConcurrent::map()</code> and similar functions can, but I just have a single, long-running method.)</p> <p>(For those familiar with .Net, something like the <code>BackgroundWorker</code> class.)</p> <p>What options are available?</p>
5,423,794
5
1
null
2011-03-24 17:25:08.417 UTC
17
2019-09-07 09:32:50.01 UTC
2015-05-08 08:59:44.713 UTC
null
4,414,557
null
183,339
null
1
18
multithreading|qt|qtconcurrent|qfuture
13,013
<p>For a long running single task, <a href="http://doc.trolltech.com/latest/qthread.html" rel="nofollow"><code>QThread</code></a> is probably your best bet. It doesn't have build-in progress reporting or canceling features so you will have to roll your own. But for simple progress update it's not that hard. To cancel the task, check for a flag that can be set from calling thread in your task's loop.</p> <p>One thing to note is if you override <code>QThread::run()</code> and put your task there, you can't emit signal from there since the QThread object is not created within the thread it runs in and you can't pull the QObject from the running thread. There is a good writeup on this <a href="http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/" rel="nofollow">issue</a>. </p>
5,043,339
Web.config isn't showing errors remotely even with customErrors="Off" (on ubuntu/mono)
<p>Here is my Web.config file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;customErrors mode="Off" /&gt; &lt;compilation debug="true" strict="false" explicit="true /&gt; &lt;pages&gt; &lt;namespaces&gt; &lt;clear /&gt; &lt;add namespace="System" /&gt; &lt;add namespace="System.Collections" /&gt; &lt;add namespace="System.Collections.Generic" /&gt; &lt;add namespace="System.Collections.Specialized" /&gt; &lt;add namespace="System.Configuration" /&gt; &lt;add namespace="System.Text" /&gt; &lt;add namespace="System.Text.RegularExpressions" /&gt; &lt;add namespace="System.Web" /&gt; &lt;add namespace="System.Web.Caching" /&gt; &lt;add namespace="System.Web.SessionState" /&gt; &lt;add namespace="System.Web.Security" /&gt; &lt;add namespace="System.Web.Profile" /&gt; &lt;add namespace="System.Web.UI" /&gt; &lt;add namespace="System.Web.UI.WebControls" /&gt; &lt;add namespace="System.Web.UI.WebControls.WebParts" /&gt; &lt;add namespace="System.Web.UI.HtmlControls" /&gt; &lt;/namespaces&gt; &lt;controls&gt; &lt;add src ="~/controls/maleBed.ascx" tagPrefix ="mycontrol" tagName ="male"/&gt; &lt;add src ="~/controls/femaleBed.ascx" tagPrefix ="mycontrol" tagName ="female"/&gt; &lt;/controls&gt; &lt;/pages&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p>Even with customErrors mode set to Off (and its definitely a capital "O") its still showing me the default errors page telling me to set this property before I can see that actual error remotely.</p> <p>I don't have a machine.config file, and I've also set this customErrors mode="Off" in the Web.Debug.config and the Web.Release.config.</p> <p>Any ideas anyone?</p> <p>Thank you very much.</p> <p><strong>Edit - what its showing:</strong></p> <pre><code>Server Error in '/' Application Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine. Details: To enable the details of this specific error message to be viewable on remote machines, please create a &lt;customErrors&gt; tag within a "web.config" configuration file located in the root directory of the current web application. This &lt;customErrors&gt; tag should then have its "mode" attribute set to "Off". &lt;!-- Web.Config Configuration File --&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;customErrors mode="Off"/&gt; &lt;/system.web&gt; &lt;/configuration&gt; Notes: The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's &lt;customErrors&gt; configuration tag to point to a custom error page URL. &lt;!-- Web.Config Configuration File --&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre>
7,144,723
6
2
null
2011-02-18 15:45:41.063 UTC
null
2016-05-19 12:41:58.02 UTC
2011-02-20 15:59:08.153 UTC
null
41,956
null
414,972
null
1
8
asp.net|mono|web-config|custom-errors
46,617
<p>Couldn't find an answer - we had to get Windows based hosting.</p>
5,149,830
jquery.ui.spinner change
<p>I'm trying to use the latest version of the jquery.ui.spinner.js . <a href="http://wiki.jqueryui.com/w/page/12138077/Spinner" rel="noreferrer">http://wiki.jqueryui.com/w/page/12138077/Spinner</a> </p> <p>The spinners are showing-up and updating the textboxes, but I'm having trouble figuring out how to capture the 'change' event. It triggers when you manually change the value in the textbox, but not when you use the spinner arrows.</p> <p>jquery:</p> <pre><code> $('input[name*="opening"]').spinner({ min: 0, max: 100}); $('#doorsize6w7h-f').spinner().change(function(){ alert($(this).spinner('value')); }); </code></pre> <p>html:</p> <pre><code>&lt;input type="text" value="0" class="front" id="doorsize6w7h-f" name="opening[0][0]" /&gt; </code></pre>
5,149,845
6
0
null
2011-03-01 02:12:48.59 UTC
3
2015-05-09 21:28:26.313 UTC
2012-01-29 13:16:57.53 UTC
null
508,666
null
625,639
null
1
24
jquery|events|user-interface|spinner|onchange
46,457
<p>Attach an event on the spinner controls that calls <code>change()</code> on your textbox.</p> <pre><code>$('.ui-spinner-button').click(function() { $(this).siblings('input').change(); }); </code></pre> <p><a href="http://jsfiddle.net/alexdickson/LYe2P/1/" rel="noreferrer">jsFiddle</a>.</p> <p>After setting up the spinner.</p>
5,378,071
Format C/C++ code on save
<p>The formatting options of Eclipse avoids me lots of conflicts with other users, and ensure that my code always looks "clean" (especially regarding my git commits). </p> <p>I know about the "Format on save" option in Java editor, but I could not find one in C/C++.</p> <p>Is this deliberate? </p> <p>May I expect to see such option one day? Or maybe I haven't looked enough?</p>
27,463,056
7
11
null
2011-03-21 13:14:59.98 UTC
5
2015-06-28 12:31:15.017 UTC
2013-01-30 16:54:58.193 UTC
null
1,420,197
null
408,484
null
1
28
c++|c|eclipse|code-formatting
5,734
<p>Format on save in CDT is now implemented in Eclipse Mars.</p>
41,600,326
How to revert the second to last commit but not the last commit?
<p>Say I have four commits <code>A--&gt;B--&gt;C--&gt;D</code> but C was terribly misguided. How can I undo C without losing the changes from D? I understand the basic functionality of <a href="https://git-scm.com/docs/git-revert" rel="noreferrer">git-revert</a> and <a href="https://stackoverflow.com/a/927386/5937428">undoing commits</a>, but I can't figure out how (if it is even possible) to undo a specific commit (not the latest) without having to redo the changes that came after it.</p>
41,600,781
2
5
null
2017-01-11 20:42:14.05 UTC
1
2018-07-28 20:27:24.357 UTC
2017-05-23 12:16:29.86 UTC
null
-1
null
5,937,428
null
1
31
git
15,727
<h2>Revert</h2> <p>The <code>git revert</code> command is designed to do exactly this.</p> <pre><code>git revert &lt;hash for C&gt; </code></pre> <p>This will create a new commit which reverses the change in C.</p> <h2>Rewrite History</h2> <p>You can also rewrite history. This is not generally recommended, and should only be used if you have a good reason to actually remove a commit from history (say, if it contains a password or something).</p> <pre><code>git rebase -i &lt;hash for B&gt; </code></pre> <p>In the editor, just delete the line with the hash for C. The usual caveats apply if you have already pushed.</p> <h2>Non-interactive</h2> <p>Technically, all of these options involve some kind of merge resolution which means they cannot truly be non-interactive. The only difference is the resulting history. With <code>git revert</code> you get a history that looks like this:</p> <pre><code>A -&gt; B -&gt; C -&gt; D -&gt; E ^ +--- reverts C </code></pre> <p>With <code>git rebase</code>, you end up with a history that looks like this:</p> <pre><code>A -&gt; B -----------&gt; E </code></pre> <p>You can of course just do <code>git rebase --onto B C</code>, instead of <code>git rebase -i</code>, but this is <em>still</em> an interactive process because you have to manually resolve any merge conflicts that can't be automatically resolved by the merge strategy.</p>
12,400,272
How do you filter a string to only contain letters?
<p>How do I make a function where it will filter out all the non-letters from the string? For example, <code>letters("jajk24me")</code> will return back <code>"jajkme"</code>. (It needs to be a for loop) and will <code>string.isalpha()</code> function help me with this?</p> <p>My attempt: </p> <pre><code>def letters(input): valids = [] for character in input: if character in letters: valids.append( character) return (valids) </code></pre>
12,400,392
6
2
null
2012-09-13 06:03:00.507 UTC
2
2021-02-16 14:12:25.67 UTC
2012-09-17 04:20:33.343 UTC
null
1,667,553
null
1,667,553
null
1
6
python
65,492
<p>If it needs to be in that for loop, and a regular expression won't do, then this small modification of your loop will work:</p> <pre><code>def letters(input): valids = [] for character in input: if character.isalpha(): valids.append(character) return ''.join(valids) </code></pre> <p>(The <code>''.join(valids)</code> at the end takes all of the characters that you have collected in a list, and joins them together into a string. Your original function returned that list of characters instead)</p> <p>You can also filter out characters from a string:</p> <pre><code>def letters(input): return ''.join(filter(str.isalpha, input)) </code></pre> <p>or with a list comprehension:</p> <pre><code>def letters(input): return ''.join([c for c in input if c.isalpha()]) </code></pre> <p>or you could use a regular expression, as others have suggested.</p>
12,075,445
Duplicate entry for key 'PRIMARY' in mysql
<p>I have a table called <code>tbl_jobs</code> that stores the meta data of some background jobs running in the application. The schema is like :</p> <pre><code>CREATE TABLE `tbl_jobs` ( `type` varchar(30) NOT NULL DEFAULT '', `last_run_on` datetime NOT NULL, `records_updated` text, PRIMARY KEY (`type`,`last_run_on`), UNIQUE KEY `index2` (`type`,`last_run_on`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ </code></pre> <p>Whenever a job runs it makes an entry in the table with the <code>type</code> which is a unique identifier for different jobs, <code>run time</code> and the <code>records updated</code> in that run.</p> <p>There are two different jobs that run at same time with types : <code>MAILER_UNLOCKED_REWARDS</code> and <code>MAILER_ALMOST_UNLOCKED</code>.</p> <p>When these jobs try to insert their entries with the same timestamp only one of them gets inserted and the other throws a <strong>Duplicate Entry for key</strong> error.</p> <p>For instance the two jobs ran the following :</p> <pre><code>INSERT INTO tbl_jobs (type, last_run_on, records_updated) VALUES ('MAILER_ALMOST_UNLOCKED', '2012-08-22 19:10:00', 'f8a35230fb214989ac75bf11c085aa28:b591426df4f340ecbce5a63c2a5a0174') </code></pre> <p>that ran successfully but when the second job ran the insert command</p> <pre><code>INSERT INTO tbl_jobs (type, last_run_on, records_updated) VALUES ('MAILER_UNLOCKED_REWARDS', '2012-08-22 19:10:00', '8a003e8934c07f040134c30959c40009:59bcc21b33a0466e8e5dc50443beb945') </code></pre> <p>It threw the error</p> <pre><code>Duplicate entry 'M-2012-08-22 19:10:00' for key 'PRIMARY' </code></pre> <p>The primary key is combination of <code>type</code> and <code>last_run_on</code> columns.</p> <p>If I delete the entry for the first job the insertion succeeds, i.e it is asking for <code>timestamp</code> alone to be unique.</p> <p>However the conflict for the same <code>timestamp</code> occurs only between these two jobs.There are other jobs that get inserted for the same <code>timestamp</code>.</p> <p>Any ideas on what could be the issue?</p>
12,075,629
3
4
null
2012-08-22 14:32:41.807 UTC
2
2016-03-15 18:05:31.857 UTC
2012-08-22 15:16:19.797 UTC
null
1,105,514
null
1,357,328
null
1
8
mysql|primary-key|duplicates
38,141
<p>Are you using the whole "type" field in your index? Or only the first character? Because the key MySQL is complaining about is</p> <pre><code>M-2012-08-22 19:10:00 </code></pre> <p>instead of MAILER_...</p> <p>Try running:</p> <pre><code> SHOW INDEXES FROM tbl_jobs; </code></pre> <p>It should give something like:</p> <pre><code>+----------+------------+----------+--------------+-------------+-----------+-------------+ ----------+--------+------+------------+---------+---------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | +----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | tbl_jobs | 0 | PRIMARY | 1 | type | A | 0 | NULL | NULL | | BTREE | | | | tbl_jobs | 0 | PRIMARY | 2 | last_run_on | A | 0 | NULL | NULL | | BTREE | | | </code></pre> <p>...</p> <p>and I suspect it will show instead "1" in the Sub_part column of the PRIMARY index:</p> <pre><code>+----------+------------+----------+--------------+-------------+-----------+-------------+ ----------+--------+------+------------+---------+---------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | +----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | tbl_jobs | 0 | PRIMARY | 1 | type | A | 0 | 1 | NULL | | BTREE | | | | tbl_jobs | 0 | PRIMARY | 2 | last_run_on | A | 0 | NULL | NULL | | BTREE | | | </code></pre> <p>...</p> <p>BTW, the primary key is always unique, so the second index <code>index2</code> you declare there is redundant.</p>
12,077,413
Order a matrix by multiple column in r
<p>I have a matrix</p> <pre><code>df&lt;-matrix(data=c(3,7,5,0,1,0,0,0,0,8,0,9), ncol=2) rownames(df)&lt;-c("a","b","c","d","e","f") [,1] [,2] a 3 0 b 7 0 c 5 0 d 0 8 e 1 0 f 0 9 </code></pre> <p>and I would like to order the matrix in descending order first by column 1 and then by column two resulting in the matrix</p> <pre><code>df.ordered&lt;-matrix(data=c(7,5,3,1,0,0,0,0,0,0,9,8),ncol=2) rownames(df.ordered)&lt;-c("b","c","a","e","f","d") [,1] [,2] b 7 0 c 5 0 a 3 0 e 1 0 f 0 9 d 0 8 </code></pre> <p>Any suggestions on how I could achieve this? Thanks.</p>
12,077,502
3
0
null
2012-08-22 16:23:00.16 UTC
8
2019-02-08 04:27:55.437 UTC
2019-02-08 04:27:55.437 UTC
null
14,768
null
1,392,044
null
1
23
r|sorting|matrix
61,049
<p>The <code>order</code> function should do it.</p> <pre><code>df[order(df[,1],df[,2],decreasing=TRUE),] </code></pre>
12,594,532
Clicking Event in UITableView
<p>I have a button and Table. Now I want to click in such way that Whenever I select any row in <code>tableview</code> and press the button, that particular button press event would happen. For that, firstly I have give tag to each row i.e</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *LabelCellIdentifier = @"cell"; UITableViewCell *cell; cell = [tableView dequeueReusableCellWithIdentifier:LabelCellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LabelCellIdentifier]; } if (indexPath.row &lt;= [_arrayMp3Link count]) { cell.textLabel.text = [_arrayMp3Link objectAtIndex:indexPath.row]; } // now tag each row NSInteger count = 1; for (NSInteger i = 0; i &lt; indexPath.section; i++) { count += [[tableView dataSource] tableView:tableView numberOfRowsInSection:i]; } count += indexPath.row; // dequeue, create and configure... cell.tag = count; return cell; } </code></pre> <p>and now in putting event in button when I select the row and press my button. But not getting the correct things.</p> <pre><code>(IBAction)doDownload:(id)sender { // to select first row if(cell.tag==1) { [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://www.google.com"]]; } </code></pre>
12,595,018
7
1
null
2012-09-26 04:24:34.727 UTC
null
2021-10-02 00:13:43.017 UTC
2016-02-04 08:04:31.96 UTC
null
2,267,838
null
1,699,102
null
1
23
iphone|objective-c|ios|uitableview|tableview
42,877
<p>Declare an <code>int</code> variable globally -</p> <pre><code>int rowNo; </code></pre> <p>Then assign value to it in <code>didSelectRowAtIndexPath:</code> method</p> <pre><code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { rowNo = indexPath.row; } </code></pre> <p>Now you have the indexNo. of selected row.</p> <pre><code>-(IBAction)doDownload:(id)sender { //Now compare this variable with 0 because first row index is 0. if(rowNo == 0) { [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://www.google.com"]]; } } </code></pre>
12,564,156
Three.js - Change Material on Runtime
<p>I have some .js files exported from Blender and load them with <code>THREE.JSONLoader();</code></p> <p>my callback:</p> <pre><code>var callback = function( geometry ) { createMesh(geometry); </code></pre> <p>my loading:</p> <pre><code>loader.load( "Models/sculp.js", callback ); </code></pre> <p>my create method:</p> <pre><code>function createMesh(geometry){ inArr[id] = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: 0xbbbbbb} ) ); inArr[id].scale.set( 100, 100, 100 ); scene.add( inArr[id] ); id++; } </code></pre> <p>Now I want to change my material on runtime by using my keyboard (changes color and opacity).</p> <p>How can I do that?</p>
12,566,263
1
0
null
2012-09-24 11:29:34.267 UTC
5
2012-09-24 15:26:52.323 UTC
2012-09-24 15:26:52.323 UTC
null
725,851
null
1,621,890
null
1
30
javascript|3d|webgl|three.js
53,803
<p>As you create a new material for each mesh I assume you only want to change the color of one mesh and not of all in the <code>inArr</code> array, and you probably need some sort of select for that. But changing the color of the material alone is quite easy:</p> <pre><code>var onKeyDown = function(event) { if (event.keyCode == 67) { // when 'c' is pressed object.material.color.setHex(0xff0000); // there is also setHSV and setRGB } }; document.addEventListener('keydown', onKeyDown, false); </code></pre> <p><code>object</code> is the mesh you want to change. Key codes can be found here: <a href="http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes" rel="noreferrer">http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes</a></p>
12,066,002
parsing JSONP $http.jsonp() response in angular.js
<p>I am using angular's <code>$http.jsonp()</code> request which is successfully returning json wrapped in a function:</p> <pre><code>var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback"; $http.jsonp(url). success(function(data, status, headers, config) { //what do I do here? }). error(function(data, status, headers, config) { $scope.error = true; }); </code></pre> <p>How to access/parse the returned function-wrapped-JSON?</p>
13,400,409
8
6
null
2012-08-22 03:36:51.98 UTC
52
2017-12-23 23:44:30.303 UTC
2017-09-23 22:35:03.953 UTC
null
3,885,376
null
1,216,755
null
1
114
javascript|angularjs|jsonp
213,785
<p><strong>UPDATE: since Angular 1.6</strong> </p> <blockquote> <p>You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go</p> </blockquote> <p>You must now define the callback like so:</p> <p><code>$http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})</code></p> <p>Change/access/declare param via <code>$http.defaults.jsonpCallbackParam</code>, defaults to <code>callback</code></p> <p>Note: You must also make sure your URL is added to the trusted/whitelist:</p> <p><code>$sceDelegateProvider.resourceUrlWhitelist</code> </p> <p>or explicitly trusted via: </p> <p><code>$sce.trustAsResourceUrl(url)</code></p> <p><strong><code>success/error</code> were <a href="https://code.angularjs.org/1.5.10/docs/api/ng/service/$http#deprecation-notice" rel="noreferrer">deprecated</a></strong>.</p> <blockquote> <p>The <code>$http</code> legacy promise methods <code>success</code> and <code>error</code> have been deprecated and will be removed in v1.6.0. Use the standard then method instead. If <code>$httpProvider.useLegacyPromiseExtensions</code> is set to <code>false</code> then these methods will throw <code>$http/legacy error</code>.</p> </blockquote> <p>USE:</p> <pre><code>var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts" var trustedUrl = $sce.trustAsResourceUrl(url); $http.jsonp(trustedUrl, {jsonpCallbackParam: 'callback'}) .then(function(data){ console.log(data.found); }); </code></pre> <p><strong>Previous Answer: Angular 1.5.x and before</strong></p> <p>All you should have to do is change <code>callback=jsonp_callback</code> to <code>callback=JSON_CALLBACK</code> like so:</p> <pre><code>var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK"; </code></pre> <p>And then your <code>.success</code> function should fire like you have it if the return was successful.</p> <p>Doing it this way keeps you from having to dirty up the global space. This is documented in the AngularJS documentation <a href="https://docs.angularjs.org/api/ng/service/$http#jsonp" rel="noreferrer">here</a>.</p> <p>Updated Matt Ball's fiddle to use this method: <a href="http://jsfiddle.net/subhaze/a4Rc2/114/" rel="noreferrer">http://jsfiddle.net/subhaze/a4Rc2/114/</a></p> <p><strong>Full example:</strong></p> <pre><code>var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK"; $http.jsonp(url) .success(function(data){ console.log(data.found); }); </code></pre>
4,017,344
Is HTTPS the only defense against Session Hijacking in an open network?
<p>So with <a href="http://codebutler.com/firesheep" rel="noreferrer">Firesheep</a>, everyone in a public Wi-Fi now has a one-click session hijack tool.</p> <p>The way it works - to my understanding - is that it simply captures all traffic and grabs the session cookie (so it doesn't steal passwords).</p> <p>From my understanding, this also means that a HTTPS secured login does not solve this alone, as further HTTP traffic would include the Session Cookie in clear text again.</p> <p>Tying the session to a specific IP address is useless thanks to NAT, and tying it to the user agent is easy to spoof.</p> <p>So is 100% HTTPS at all times the only way to prevent this type of session hijacking? Couldn't people simply sniff the entire HTTPS Traffic including the handshake, or is this stuff safe? (I'm thinking of replay attacks, but have no knowledge in that area.)</p> <p>Of course, not using public/open Wi-Fi Networks is the better choice, but I'm still interested what a website developer can do to protect his/her users.</p>
4,017,478
3
0
null
2010-10-25 17:46:06.293 UTC
29
2020-05-22 18:56:07.59 UTC
2010-10-29 19:08:55.567 UTC
null
63,550
null
91
null
1
38
security|session|encryption|https|cryptography
19,287
<p>Firesheep is <strong>nothing new</strong>. Session hijacking has been around for as long as web applications have been using Session IDs. Usually hackers just set their own cookie by typing this into the address bar: <code>javascript:document.cookie='SOME_COOKIE'</code>. This tool is for script kiddies that fear 1 line of JavaScript. </p> <p>Cookies can be hijacked if you don't use HTTPS for the entire life of the session and this is a part of <a href="http://www.owasp.org/index.php/Top_10_2010-A9-Insufficient_Transport_Layer_Protection" rel="nofollow noreferrer">OWASP A9 - Insufficient Transport Layer Protection</a>. But you can also hijack a session with XSS.</p> <p>1) Use <a href="http://www.owasp.org/index.php/HttpOnly" rel="nofollow noreferrer">httponly cookies</a>.</p> <p>2) Use "<a href="https://en.wikipedia.org/wiki/Secure_cookie" rel="nofollow noreferrer">secure cookies</a>" (Horrible name, but it's a flag that forces the browser to make the cookie HTTPS only.)</p> <p>3) Scan your web application for XSS.</p> <p>Also don't forget about <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="nofollow noreferrer">CSRF</a>! (Which Firesheep doesn't address.)</p>
38,505,904
Dynamically build select list from linq to entities query
<p>I'm looking for a way to dynamically create a select list from a iQueryable object.</p> <p>Concrete example, i want to do something like the following:</p> <pre><code>public void CreateSelectList(IQueryable(of EntityModel.Core.User entities), string[] columns) { foreach(var columnID in columns) { switch(columnID) { case "Type": SelectList.add(e =&gt; e.UserType); break; case "Name": SelectList.add(e =&gt; e.Name); break; etc.... } } var selectResult = (from u in entities select objSelectList); } </code></pre> <p>So all properties are known, i however don't know beforehand what properties are to be selected. That will be passed via the columns parameter.</p> <p>I know i'm going to run into issues with the type of the selectResult type, because when the select list is dynamic, the compiler doesn't know what the properties of the anonymous type needs to be.</p> <p>If the above is not possible: The scenario I need it for is the following:<br> I'm trying to create a class that can be implemented to display a paged/filtered list of data. This data can be anything (depends on the implementations).The linq used is linq to entities. So they are directly linked to sql data. Now i want to only select the columns of the entities that i am actually showing in the list. Therefore i want the select to be dynamic. My entity might have a hundred properties, but if only 3 of them are shown in the list, i don't want to generate a query that selects the data of all 100 columns and then only uses 3 of them. If there is a different approach that I haven't thought of, I'm open to ideas</p> <p>Edit:</p> <p>Some clarifications on the contraints:<br> - The query needs to work with linq to entities (see question subject)<br> - an entity might contain 100 columns, so selecting ALL columns and then only reading the ones i need is not an option.<br> - The end user decides what columns to show, so the columns to select are determined at run time<br> - i need to create a SINGLE select, having multiple select statements means having multiple queries on the database, which i don't want</p>
38,564,762
3
15
null
2016-07-21 13:39:58.03 UTC
11
2016-07-25 16:09:29.977 UTC
2016-07-22 13:15:49.797 UTC
null
1,141,404
null
1,141,404
null
1
9
c#|entity-framework|linq|linq-to-entities
8,467
<p>Dynamic select expression to a compile time known type can easily be build using <a href="https://msdn.microsoft.com/en-us/library/bb344570(v=vs.110).aspx" rel="noreferrer"><code>Expression.MemberInit</code></a> method with <code>MemberBinding</code>s created using the <a href="https://msdn.microsoft.com/en-us/library/bb298030(v=vs.110).aspx" rel="noreferrer"><code>Expression.Bind</code></a> method. </p> <p>Here is a custom extension method that does that:</p> <pre><code>public static class QueryableExtensions { public static IQueryable&lt;TResult&gt; Select&lt;TResult&gt;(this IQueryable source, string[] columns) { var sourceType = source.ElementType; var resultType = typeof(TResult); var parameter = Expression.Parameter(sourceType, "e"); var bindings = columns.Select(column =&gt; Expression.Bind( resultType.GetProperty(column), Expression.PropertyOrField(parameter, column))); var body = Expression.MemberInit(Expression.New(resultType), bindings); var selector = Expression.Lambda(body, parameter); return source.Provider.CreateQuery&lt;TResult&gt;( Expression.Call(typeof(Queryable), "Select", new Type[] { sourceType, resultType }, source.Expression, Expression.Quote(selector))); } } </code></pre> <p>The only problem is what is the <code>TResult</code> type. In <strong>EF Core</strong> you can pass the entity type (like <code>EntityModel.Core.User</code> in your example) and it will work. In <strong>EF 6</strong> and earlier, you need a separate non entity type because otherwise you'll get <code>NotSupportedException</code> - <em>The entity or complex type cannot be constructed in a LINQ to Entities query</em>.</p> <p><strong>UPDATE:</strong> If you want a to get rid of the string columns, I can suggest you replacing the extension method with the following class:</p> <pre><code>public class SelectList&lt;TSource&gt; { private List&lt;MemberInfo&gt; members = new List&lt;MemberInfo&gt;(); public SelectList&lt;TSource&gt; Add&lt;TValue&gt;(Expression&lt;Func&lt;TSource, TValue&gt;&gt; selector) { var member = ((MemberExpression)selector.Body).Member; members.Add(member); return this; } public IQueryable&lt;TResult&gt; Select&lt;TResult&gt;(IQueryable&lt;TSource&gt; source) { var sourceType = typeof(TSource); var resultType = typeof(TResult); var parameter = Expression.Parameter(sourceType, "e"); var bindings = members.Select(member =&gt; Expression.Bind( resultType.GetProperty(member.Name), Expression.MakeMemberAccess(parameter, member))); var body = Expression.MemberInit(Expression.New(resultType), bindings); var selector = Expression.Lambda&lt;Func&lt;TSource, TResult&gt;&gt;(body, parameter); return source.Select(selector); } } </code></pre> <p>with sample usage:</p> <pre><code>var selectList = new SelectList&lt;EntityModel.Core.User&gt;(); selectList.Add(e =&gt; e.UserType); selectList.Add(e =&gt; e.Name); var selectResult = selectList.Select&lt;UserDto&gt;(entities); </code></pre>
8,854,181
DefaultIfEmpty in LINQ
<p>Can somebody explain how <code>DefaultIfEmpty()</code> can be used in <em>LINQ</em>. I have ready some material but still need something solid to see what the use of it is.</p>
8,854,247
3
6
null
2012-01-13 16:51:06.703 UTC
1
2021-11-12 16:57:18.023 UTC
2014-09-07 18:52:13.303 UTC
null
1,628,280
null
996,431
null
1
36
.net|linq
27,392
<p>It basically returns a collection with a single element in case the source collection is empty.</p> <pre><code>var numbers = new int[] {1, 2, 3}; var aNumber = numbers.First(); </code></pre> <p>returns 1</p> <p>but </p> <pre><code>var numbers = new int[]; var aNumber = numbers.DefaultIfEmpty(12).Single(); </code></pre> <p>returns 12 as the collection is empty</p>
8,823,267
Linking against older symbol version in a .so file
<p>Using gcc and ld on x86_64 linux I need to link against a newer version of a library (glibc 2.14) but the executable needs to run on a system with an older version (2.5). Since the only incompatible symbol is memcpy (needing memcpy@GLIBC_2.2.5 but the library providing memcpy@GLIBC_2.14), I would like to tell the linker that instead of taking the default version for memcpy, it should take an old version I specify.</p> <p>I found a quite arkward way to do it: simply specify a copy of the old .so file at the linker command line. This works fine, but I don't like the idea of having multiple .so files (I could only make it work by specifying all old libraries I link to that also have references to memcpy) checked into the svn and needed by my build system.</p> <p>So I am searching for a way to tell the linker to take the old versioned symbol.</p> <p>Alternatives that don't work (well) for me are:</p> <ul> <li>Using asm .symver (as seen on <a href="http://web.archive.org/web/20160107032111/http://www.trevorpounds.com/blog/?p=103" rel="noreferrer">Web Archive of Trevor Pounds' Blog</a>) since this would require me to make sure the symver is before all the code that is using memcpy, which would be very hard (complex codebase with 3rd party code)</li> <li>Maintaining a build environment with the old libraries; simply because I want to develop on my desktop system and it would be a pita to sync stuff around in our network.</li> </ul> <p>When thinking about all the jobs a linker does, it doesn't seem like a hard thing to imlpement, after all it has some code to figure out the default version of a symbol too.</p> <p>Any other ideas that are on the same complexity level as a simple linker command line (like creating a simple linker script etc.) are welcome too, as long as they are not weird hacks like editing the resulting binary...</p> <p><strong>edit:</strong> To conserve this for the future readers, additionally to the below ideas I found the option <code>--wrap</code> to the linker, which might be useful sometimes too.</p>
8,823,419
11
6
null
2012-01-11 16:54:18.65 UTC
32
2020-04-20 16:36:38.977 UTC
2017-06-19 19:27:44.927 UTC
null
453,062
null
833,362
null
1
51
c|linux|gcc|linker|ld
43,236
<p>Just link memcpy statically - pull memcpy.o out of libc.a <code>ar x /path/to/libc.a memcpy.o</code> (whatever version - memcpy is pretty much a standalone function) and include it in your final link. Note that static linking may complicate licensing issues if your project is distributed to the public and not open-source.</p> <p>Alternatively, you could simply implement memcpy yourself, though the hand-tuned assembly version in glibc is likely to be more efficient</p> <p>Note that <a href="https://bugzilla.redhat.com/show_bug.cgi?id=691336">memcpy@GLIBC_2.2.5</a> is mapped to memmove (old versions of memcpy consistently copied in a predictable direction, which led to it sometimes being misused when memmove should have been used), and this is the only reason for the version bump - you could simply replace memcpy with memmove in your code for this specific case.</p> <p>Or you could go to static linking, or you could ensure that all systems on your network have the same or better version than your build machine.</p>
20,773,945
Storing compressed json data in local storage
<p>I want to store JSON data in local storage. Sometimes data stored could be more than 5MB(max threshold allowed by browsers for each domain). Is there anyway i can compress or zip the data and store it in local storage ? How much latency it will add if compression and decompression for every JS function on large data ?</p> <p>I am using this json data to display on webpage..... It is like a static data which is mostly same for entire session. we provide actions like search, filter etc on this json data...Whenever user enters a keyword, i search in this json data which is stored in local storage instead of making call to server</p>
20,774,589
1
5
null
2013-12-25 14:48:15.66 UTC
12
2020-01-31 04:08:04.663 UTC
2013-12-25 15:50:27.29 UTC
null
1,554,241
null
1,554,241
null
1
28
javascript|json|html|compression|local-storage
18,736
<p>As localStorage functionality seems to be limited to handle only string key/value pairs what you can do is to use <a href="http://pieroxy.net/blog/pages/lz-string/index.html" rel="noreferrer">lz-string library</a> to stringify the json object and compress it before storing it in localStorage </p> <p>Usage</p> <pre><code>// sample json object var jsonobj = {'sample': 'This is supposed to be ling string', 'score': 'another long string which is going to be compressed'} // compress string before storing in localStorage localStorage.setItem('mystring', LZString.compress(JSON.stringify(jsonobj))); // decompress localStorage item stored var string = LZString.decompress(localStorage.getItem('mystring')) // parse it to JSON object JSON.parse(string); </code></pre> <p>Check jsfiddle <a href="http://jsfiddle.net/raunakkathuria/7PQtC/1/" rel="noreferrer">http://jsfiddle.net/raunakkathuria/7PQtC/1/</a> as i have copied the complete script so look for running code at end of fiddle</p> <p>Use <code>compressToUTF16</code> and <code>decompressFromUTF16</code> if you are dealing with UTF characters but please note that the strings produced are therefore 6.66% bigger than those produced by <code>compress</code>. So use <code>utf</code> ones only when required.</p>
43,720,339
Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"
<p>I have a directory <code>apkmirror-scraper-compose</code> with the following structure:</p> <pre><code>. ├── docker-compose.yml ├── privoxy │   ├── config │   └── Dockerfile ├── scraper │   ├── Dockerfile │   ├── newnym.py │   └── requirements.txt └── tor └── Dockerfile </code></pre> <p>I'm trying to run the following <code>docker-compose.yml</code>:</p> <pre><code>version: '3' services: privoxy: build: ./privoxy ports: - "8118:8118" links: - tor tor: build: context: ./tor args: password: "" ports: - "9050:9050" - "9051:9051" scraper: build: ./scraper links: - tor - privoxy </code></pre> <p>where the <code>Dockerfile</code> for <code>tor</code> is</p> <pre><code>FROM alpine:latest EXPOSE 9050 9051 ARG password RUN apk --update add tor RUN echo "ControlPort 9051" &gt;&gt; /etc/tor/torrc RUN echo "HashedControlPassword $(tor --quiet --hash-password $password)" &gt;&gt; /etc/tor/torrc CMD ["tor"] </code></pre> <p>that for <code>privoxy</code> is</p> <pre><code>FROM alpine:latest EXPOSE 8118 RUN apk --update add privoxy COPY config /etc/privoxy/config CMD ["privoxy", "--no-daemon"] </code></pre> <p>where <code>config</code> consists of the two lines</p> <pre><code>listen-address 0.0.0.0:8118 forward-socks5 / tor:9050 . </code></pre> <p>and the <code>Dockerfile</code> for <code>scraper</code> is</p> <pre><code>FROM python:2.7-alpine ADD . /scraper WORKDIR /scraper RUN pip install -r requirements.txt CMD ["python", "newnym.py"] </code></pre> <p>where <code>requirements.txt</code> contains the single line <code>requests</code>. Finally, the program <code>newnym.py</code> is designed to simply test whether changing the IP address using Tor is working:</p> <pre><code>from time import sleep, time import requests as req import telnetlib def get_ip(): IPECHO_ENDPOINT = 'http://ipecho.net/plain' HTTP_PROXY = 'http://privoxy:8118' return req.get(IPECHO_ENDPOINT, proxies={'http': HTTP_PROXY}).text def request_ip_change(): tn = telnetlib.Telnet('tor', 9051) tn.read_until("Escape character is '^]'.", 2) tn.write('AUTHENTICATE ""\r\n') tn.read_until("250 OK", 2) tn.write("signal NEWNYM\r\n") tn.read_until("250 OK", 2) tn.write("quit\r\n") tn.close() if __name__ == '__main__': dts = [] try: while True: ip = get_ip() t0 = time() request_ip_change() while True: new_ip = get_ip() if new_ip == ip: sleep(1) else: break dt = time() - t0 dts.append(dt) print("{} -&gt; {} in ~{}s".format(ip, new_ip, int(dt))) except KeyboardInterrupt: print("Stopping...") print("Average: {}".format(sum(dts) / len(dts))) </code></pre> <p>The <code>docker-compose build</code> builds successfully, but if I try <code>docker-compose up</code>, I get the following error message:</p> <pre><code>Creating network "apkmirrorscrapercompose_default" with the default driver ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network </code></pre> <p>I tried searching for help on this error message, but couldn't find any. What is causing this error?</p>
43,721,103
25
17
null
2017-05-01 13:59:29.42 UTC
60
2022-09-20 17:18:08.973 UTC
null
null
null
null
995,862
null
1
298
python|docker|docker-compose
220,321
<p>Following <a href="https://stackoverflow.com/users/5040699/peter-hauge">Peter Hauge</a>'s <a href="https://stackoverflow.com/questions/43720339/docker-error-could-not-find-an-available-non-overlapping-ipv4-address-pool-am#comment74485284_43720339">comment</a>, upon running <code>docker network ls</code> I saw (among other lines) the following:</p> <pre><code>NETWORK ID NAME DRIVER SCOPE dc6a83d13f44 bridge bridge local ea98225c7754 docker_gwbridge bridge local 107dcd8aa889 host host local </code></pre> <p>The line with <code>NAME</code> and <code>DRIVER</code> as both <code>host</code> seems to be what he is referring to with "networks already created on your host". So, following <a href="https://gist.github.com/bastman/5b57ddb3c11942094f8d0a97d461b430" rel="noreferrer">https://gist.github.com/bastman/5b57ddb3c11942094f8d0a97d461b430</a>, I ran the command</p> <pre><code>docker network rm $(docker network ls | grep "bridge" | awk '/ / { print $1 }') </code></pre> <p>Now <code>docker-compose up</code> works (although <code>newnym.py</code> produces an error).</p>
22,040,246
Git pull is very slow... Why?
<p>Note I have studied the <a href="https://stackoverflow.com/questions/3055506/git-is-very-very-slow">git-is-very-very-slow</a> question, but in their case the reason was big binary files - while in my repository there is PHP/JS/HTML/CSS only code (no binaries) and the biggest file in the repository is around 800 KB.</p> <p>I've changed one file (a few lines), then <code>git add .</code> and <code>git commit -m &quot;msg&quot;</code>, then <code>git push origin master</code>.</p> <p>On some other machine, when I do <code>git pull origin master</code> it downloads a few MiB of data, and it takes more than 2 minutes to calculate the delta and apply changes. Something is terribly wrong here.</p> <p>I suspect some recent operations may cause this:</p> <p>recently, I've accidentally added many vendor assets (<code>bower_components</code> assets) when I realized it, I've used <code>git rm</code> to remove them from repository (and ofcourse, <code>git add</code>, <code>git commit</code> and <code>git push</code> to upstream).</p> <p>That was a few days ago and the problems I have right now started happeing around that time.</p> <p>I have two questions:</p> <ul> <li>Why this is happeing?</li> <li>How can I fix my repository?</li> </ul> <p>Note: I am the only one useing and pushing to this repo.</p>
24,085,738
7
6
null
2014-02-26 11:40:18.657 UTC
15
2021-08-28 15:52:18.47 UTC
2020-06-22 10:55:47.197 UTC
null
4,217,744
null
741,949
null
1
51
git|version-control|repository
59,603
<p>The problem was in <code>EmberJS</code> app directory. It contained <code>node_modules</code> and <code>bower_components</code> directories which kept third-party libraries used by <code>GruntJS</code> to build my JS and CSS assets.</p> <p>Each of these contained many files and directories.. considering that the dependency tree contained hundreds of libraries of size varying from small (few files) to big fat (many files).</p> <p>After removing these directories and ignoring them, the git repository works fast again.</p>
11,376,657
What is the difference between Delegate & Action in C#
<p>If I searched I will definitely get examples of showing what is a Delegate and Action. I have read the basic books giving examples of delegate. </p> <p>But what I want to know is their use in the real world. Please do not give Hello World example or the Animal class they are far too basic</p> <p>For e.g. :</p> <ol> <li>What are the difference between them</li> <li>When to use a delegate or action</li> <li>When not to use a delegate or action</li> <li>When they can be an over kill</li> </ol>
11,376,763
5
3
null
2012-07-07 16:17:26.78 UTC
8
2016-11-02 05:21:48.56 UTC
2012-07-16 11:22:23.71 UTC
null
21,199
null
1,310,467
null
1
35
c#
26,138
<p><code>Action</code> <em>is</em> a <code>Delegate</code>. It is defined like this:</p> <pre><code>public delegate void Action(); </code></pre> <p>You could create your own delegate types similarly to how you would create abstract methods; you write the signature but no implementation. You then create instances of these delegates by taking the reference of a method.</p> <pre><code>class Program { public static void FooMethod() { Console.WriteLine("Called foo"); } static void Main() { Action foo = FooMethod; // foo now references FooMethod() foo(); // outputs "Called foo" } } </code></pre>
11,262,617
Why choose tomcat over a java EE compliant application server?
<p>Java EE application servers provide all the features of tomcat, so why use tomcat (instead of glassfish for example as it is the official one)?</p> <p>Especially when Java EE features are needed like JPA, JAX-RS, JSF, and therefore more libraries have to be packaged with the application, while a EE-compliant application server would have provided it out of the box?</p>
11,276,137
7
8
null
2012-06-29 13:22:25.517 UTC
20
2014-07-31 13:53:50.527 UTC
2014-07-31 13:53:50.527 UTC
null
537,623
null
537,623
null
1
39
jakarta-ee|tomcat
38,896
<p>The question that was in our mind and the entire reason we created <a href="http://tomee.apache.org" rel="noreferrer">TomEE</a> was, why should people have to choose?</p> <h3>The whole &quot;Tomcat or JavaEE&quot; thing is tired and old.</h3> <p>After 10 years it still comes up and people argue against each other as to which is better and why.</p> <p>Here's the math in short form:</p> <ul> <li>In Java EE 6, we (JCP) created the Web Profile to formally acknowledge the need for smaller runtimes with a focused set of technologies.</li> </ul> <p>Great, we're half-way there, but people are still arguing &quot;Tomcat <em>or</em> JavaEE&quot;. The solution was clear, Tomcat needed to be Java EE certified. The Web Profile was created to allow for <em>exactly that</em>.</p> <ul> <li>In 2011 we (Apache) started doing the work to certify Apache Tomcat. Certification reached and announced at JavaOne 2011 as Apache TomEE. Final release announced in April.</li> </ul> <p>Awesome, now we are there.</p> <h3>The new Status Quo</h3> <ul> <li>There is a lighter version of JavaEE</li> <li>There is a JavaEE certified version of Tomcat</li> </ul> <p>All this happened in the last 2 years. Things have changed.</p> <p>If you want <strong>Tomcat and JavaEE</strong>, you can have it.</p>
11,333,624
Float right and position absolute doesn't work together
<p>I want a div to be always at the right of its parent div, so I use <code>float:right</code>. It works.</p> <p>But I also want it to not affect other content when inserted, so I use <code>position:absolute</code>.</p> <p>Now <code>float:right</code> doesn't work, my div is always at the left of its parent div. How can I move it to the right?</p>
11,333,667
5
0
null
2012-07-04 17:56:42.953 UTC
42
2021-12-21 21:24:11.203 UTC
2016-07-26 20:58:23.52 UTC
null
4,190,610
null
669,650
null
1
148
css|css-float|position
206,381
<p>Use</p> <p><code>position:absolute; right: 0;</code></p> <p>No need for <code>float:right</code> with absolute positioning</p> <p>Also, make sure the parent element is set to <code>position:relative;</code> </p>
12,996,823
Ember.js or Backbone.js for Restful backend
<p>I already know that ember.js is a more heavy weight approach in contrast to backbone.js. I read a lot of articles about both.</p> <p>I am asking myself, which framework works easier as frontend for a rails rest backend. For backbone.js I saw different approaches to call a rest backend. For ember it seems that I have to include some more libraries like 'data' or 'resources'. Why are there two libraries for this? </p> <p>So whats the better choice? There arent a lot of examples to connect the frontend with the backend too. Whats a good working example for a backend rest call to this:</p> <p>URI: ../restapi/topics GET auth credentials: admin/secrect format: json</p>
12,999,399
3
1
null
2012-10-21 09:57:12.107 UTC
80
2022-05-03 16:55:12.15 UTC
2022-05-03 16:55:12.15 UTC
null
792,066
null
1,189,762
null
1
98
ember.js|backbone.js
30,289
<p>Contrary to popular opinion Ember.js isn't a 'more heavy weight approach' to Backbone.js. They're different kinds of tools that target totally different end products. Ember's sweet spot is applications where the user will keep the application open for long periods of time, perhaps all day, and interactions with the application's views or underlying data trigger deep changes in the view hierarchy. Ember is larger than Backbone, but thanks to <code>Expires</code>, <code>Cache-Control</code> this only matters on the the first load. After two days of daily use that extra 30k will be overshadowed by data transfers, sooner if your content involves images.</p> <p>Backbone is ideal for applications with a small number of states where the view hierarchy remains relatively flat and where the user tends to access the app infrequently or for shorter periods of time. Backbone's code gets to remain short and sweet because it makes the assumption that the data backing the DOM will get thrown away and both items will be memory collected: <a href="https://github.com/documentcloud/backbone/issues/231#issuecomment-4452400">https://github.com/documentcloud/backbone/issues/231#issuecomment-4452400</a> Backbone's smaller size also makes it better suited to brief interactions.</p> <p>The apps people write in both frameworks reflect these uses: Ember.js apps include <a href="https://squareup.com/">Square's web dashboard</a>, <a href="http://www.zendesk.com/">Zendesk</a> (at least the agent/ticketing interface), and <a href="http://www.groupon.com/scheduler">Groupon's scheduler</a>: all applications a user might spend all day working in. </p> <p>Backbone apps focus more on brief or casual interactions, that are often just small sections of a larger static page: <a href="https://www.airbnb.com/">airbnb</a>, <a href="http://www.khanacademy.org/">Khan Academy</a>, <a href="https://foursquare.com/">Foursquare's map and lists</a>.</p> <p>You <em>can</em> use Backbone to make the kinds of applications that Ember targets (e.g. <a href="http://rdio.com">Rdio</a>) by a) increasing the amount of application code you're responsible for to avoid problems like memory leaks or zombie events (I don't personally recommend this approach) or b) by adding 3rd party libraries like <a href="http://marionettejs.com/">backbone.marionette</a> or <a href="https://github.com/onsi/coccyx">Coccyx</a> – there are many of these libraries that all try to provide similar overlapping functionality and you'll probably end up assembling your own custom framework that is bigger and requires more glue code than if you'd just used Ember.</p> <p>Ultimately the question of "which to use" has two answers.</p> <p>First, "Which should I use, generally, in my career": Both, just like you'll end up learning any tools specific to work you'll want to do in the future. You'd never ask "Backbone or D3?"; "Backbone or Ember" is an equally silly question.</p> <p>Second, "Which should I use, specifically, on my next project": Depends on the project. Both will communicate with a Rails server with equal ease. If your next project involves a mix of pages generated by the server with so-called "islands of richness" provided by JavaScript use Backbone. If your next project pushes all the interaction into the browser environment, use Ember.</p>
12,867,878
missing private key in the distribution certificate on keychain
<p>I have the following problem which I could not find a solution for anywhere. Basically, we have a company developer account (not enterprise) and so in order to submit our app, I requested from our team lead to send me the distribution certificate and create and send me a distribution provisioning profile. </p> <p>With the developer profile, everything works good, but when I installed the cert and the provisioning profile, I did not see the distribution profile on Xcode, and nor do I have a private key under the dist cert in the keychain.</p> <p>Does anyone know how to solve this? I read in diff places that I will need to revoke the certificate and create a new one, but I can't really do that since we have a bunch of apps in the company and I can't revoke it for everyone.</p>
12,867,936
21
2
null
2012-10-12 22:18:50.117 UTC
46
2022-09-13 18:33:17.043 UTC
2020-06-03 00:44:49.06 UTC
null
5,175,709
null
1,364,351
null
1
214
ios|iphone|xcode|keychain|codesign
284,280
<p><img src="https://i.stack.imgur.com/vXRjU.png" alt="enter image description here">Ahh this is a common issue, The solution is simple:</p> <p>Who ever created the developer credentials originally needs to go to the keychain on their computer and right click on the key(s) for private and public and export the key to a file. Then you just download that file on your computer and open it, and it will be added to your keychain.</p> <p>You need to have both the private key (.pem file) and the certificate for your provisioning profiles.</p>
30,492,236
"Access Is Denied" error when attempting to remote to Exchange server on localhost
<p>I am attempting to establish a PowerShell session to run several Exchange commands against an Exchange server on the localhost. I keep getting the following error:</p> <pre><code>New-PSSession : [&lt;HOSTNAME&gt;] Connecting to remote server &lt;HOSTNAME&gt; failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. At line:1 char:12 + $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 'h ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin gTransportException + FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed </code></pre> <p>My code is a copy paste from the Microsoft <a href="https://technet.microsoft.com/en-us/library/dd335083(v=exchg.150).aspx" rel="noreferrer">Technet Article</a>. It works against remote machine, but anytime I target the machine I am running from, I get the above error.</p> <p>What I've tried so far:</p> <ol> <li>Checked the <code>about_remote_troubleshooting</code> help topic. Nothing in there relating to Access Denied errors worked.</li> <li>Targeted remote machines using the same credentials as received the Access Denied error. (Connected without issue)</li> <li>Verified that my PowerShell session is running as Administrator. (It is)</li> <li>Verified that the Exchange Management Shell is able to launch successfully. (It is)</li> <li>Tried without credentials to see if that would work. (It didn't)</li> <li>Checked <code>net use</code> and <code>net session</code> to make sure I didn't have a weird multiple connections with the same credentials issue. (I didn't see anything to indicate that)</li> <li>Tried this both from the script that is causing issues and by typing the commands into a powershell console by hand. (got the same results both ways. Yay for consistency)</li> <li>Tried this on multiple systems. (Same result everywhere)</li> </ol> <p>Some quick notes:</p> <ul> <li>This is Exchange 2013 running on Windows Server 2012. It's a basic installation, just a test environment that has very little data and minimal configuration beyond installing and enabling remoting.</li> <li>The Credentials used were for the domain admin, which also has the necessary Exchange permissions to do whatever I need to do. I.e, so long as I target a machine that is not the one I am running from, I have no issues whatsoever, with nothing else changing about the way I am connecting. Additionally, this is a test domain where the domain admin's access hasn't been restricted or tweaked in any way, so it should have total and complete access to everything.</li> </ul> <p>The specific commands I am entering are:</p> <pre class="lang-psh prettyprint-override"><code>$cred = Get-Credential $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 'http://&lt;HOSTNAME&gt;/Powershell' -Credential $cred </code></pre> <p>Is connecting to the localhost like this something that I should be able to do? Or is it just not supported?</p> <p>I am at a complete loss at this point. Any help, even to point me in the right direction, would be greatly appreciated.</p> <p>EDIT: I should add, I've attempted connecting to this localhost from a different machine, using the same commands as above, and it worked without issue. So, I don't <em>think</em> it is a local configuration issue. </p>
30,576,415
2
5
null
2015-05-27 20:10:41.05 UTC
null
2018-04-05 20:16:38.673 UTC
2015-06-16 13:21:48.963 UTC
null
1,118,488
null
4,747,176
null
1
9
powershell|windows-server-2012|access-denied|powershell-remoting|exchange-server-2013
60,010
<p>So, I stumbled on the solution late last week. It seems to have something to do with the authentication being used. I had left the "-Authentication" parameter blank, intending to let the New-PSSession command sort out which method would be best. </p> <p>Apparently, this defaults to the "Negotiate" authentication method, which will select Kerberos against a remote machine, but will select NTLM otherwise (or at least, that was my observed/assumed behavior). See <a href="https://msdn.microsoft.com/en-us/library/system.management.automation.runspaces.authenticationmechanism(v=vs.85).aspx" rel="nofollow">this Microsoft description</a> of the authentication methods. </p> <p>Specifying a specific Authentication method (Both "Kerberos" and "Basic" worked, "Negotiate" didn't, I didn't tinker too much past this) clears the issue and allowed me to connect to the local exchange instance.</p> <p>So, rather than this:</p> <pre><code>$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 'http://&lt;HOSTNAME&gt;/Powershell' -Credential $cred </code></pre> <p>Do this:</p> <pre><code>$session = New-PSSession -Authentication Kerberos -ConfigurationName Microsoft.Exchange -ConnectionUri 'http://&lt;HOSTNAME&gt;/Powershell' -Credential $cred </code></pre> <p>Why did that work? I have no clue. I'll leave it to people who know more than me to explain it.</p>
37,341,614
Modules are installed using pip on OSX but not found when importing
<p>I successfully install different modules using pip and they are shown in the </p> <pre><code>pip list </code></pre> <p>such as:</p> <pre><code>beautifulsoup4 (4.4.1) requests (2.10.0) Scrapy (1.1.0) </code></pre> <h3>From Terminal</h3> <p>However, whenever I try to import it</p> <p><code>import beautifulsoup4</code> / <code>import bs4</code> or <code>import Scrapy</code> or <code>import requests</code></p> <p>the following error is shown:</p> <pre><code>$ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import requests Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named requests </code></pre> <p><em>Update:</em> if I launch python when I am at the correct site-packages directory</p> <pre><code>$ pwd /usr/local/lib/python2.7/site-packages $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) &gt;&gt;&gt; import requests &gt;&gt;&gt; import bs4 &gt;&gt;&gt; import scrapy </code></pre> <p>Then it works. This would solve the issue if writing directly on the Terminal. However, I have no clue about how to make it work inside a file.py, which will be the normal use.</p> <p>As far as I know, I only have Python2.7 installed.</p> <h3>From file.py</h3> <p>If I have a file.py saved in some local folder. This contains, for instance</p> <pre><code>import requests from bs4 import BeautifulSoup </code></pre> <p>when I try</p> <pre><code>python file.py </code></pre> <p>I get the same error.</p> <h1>Approach</h1> <p>Same happens with any other module from the list. I would think pip is installing them in a directory that Python is not reading, but as per what I read, it is the correct one.</p> <p>They are all installed here:</p> <pre><code>/usr/local/lib/python2.7/site-packages </code></pre> <p>Output requested by Padraic Cunningham:</p> <pre><code>$ which -a pip /usr/local/bin/pip $ which -a python /usr/bin/python /usr/local/bin/python </code></pre> <p>Output requested by leovp:</p> <pre><code>$ pip -V pip 8.1.2 from /usr/local/lib/python2.7/site-packages (python 2.7) </code></pre> <h3>Threads already checked</h3> <p>I have checked the following threads, but unfortunately they did not help me to solve the issue:</p> <ul> <li><a href="https://stackoverflow.com/questions/33899996/installing-pyside-using-pip-nmake-not-found">installing pyside using PIP - nmake not found</a></li> <li><a href="https://stackoverflow.com/questions/10569846/pip-installs-but-module-is-not-found">PIp installs but module is not found</a> ==> might have provided the right answer, but the links given do not work anymore</li> <li><a href="https://stackoverflow.com/questions/28802358/google-protobuf-installed-but-module-not-found">google.protobuf installed, but module not found</a></li> <li><a href="https://stackoverflow.com/questions/15052206/python-pip-install-module-is-not-found-how-to-link-python-to-pip-location">Python pip install module is not found. How to link python to pip location?</a></li> </ul> <p>Any ideas of what the problem is?</p>
37,342,150
6
11
null
2016-05-20 08:23:30.337 UTC
6
2021-02-27 11:52:25.283 UTC
2017-05-23 12:25:47.36 UTC
null
-1
null
5,802,289
null
1
28
python|macos|python-2.7|import|module
60,245
<p>Since your problem maybe caused due to various reason, I have listed down a few of them here :</p> <ul> <li>This is possibly because of what ever is stated here : <a href="https://stackoverflow.com/questions/10569846/pip-installs-but-module-is-not-found">Pip installs but module is not found</a>. Have updated the answer with newer link.</li> </ul> <p>The link you were looking for : <a href="https://pythonhosted.org/setuptools/setuptools.html#development-mode" rel="noreferrer">https://pythonhosted.org/setuptools/setuptools.html#development-mode</a></p> <ul> <li>It may also happen if you have <strong>two versions of python installed</strong>. If the <code>pip</code> that you are accessing is of one version &amp; the python interpreter used is another.</li> </ul> <p>So just see to that you are using the same version of python to install and use the package.</p> <p><strong>You may fix this using alias,</strong></p> <p>First, set up a shell alias:</p> <pre><code>alias python=/usr/local/bin/python3 </code></pre> <p>Then, type that at a prompt, or put it in your <code>~/.bashrc</code> so that whenever you open python from the terminal the correct version opens.</p> <ul> <li>If both of the above methods don't work for you then check this :</li> </ul> <p><a href="https://stackoverflow.com/questions/338768/python-importerror-no-module-named">ImportError No module named</a> or <a href="https://stackoverflow.com/questions/7587457/importerror-no-module-named-python">this</a></p>
16,840,851
Python regex split without empty string
<p>I have the following file names that exhibit this pattern:</p> <pre><code>000014_L_20111007T084734-20111008T023142.txt 000014_U_20111007T084734-20111008T023142.txt ... </code></pre> <p>I want to extract the middle two time stamp parts after the second underscore <code>'_'</code> and before <code>'.txt'</code>. So I used the following Python regex string split:</p> <pre><code>time_info = re.split('^[0-9]+_[LU]_|-|\.txt$', f) </code></pre> <p>But this gives me two extra empty strings in the returned list:</p> <pre><code>time_info=['', '20111007T084734', '20111008T023142', ''] </code></pre> <p>How do I get only the two time stamp information? i.e. I want:</p> <pre><code>time_info=['20111007T084734', '20111008T023142'] </code></pre>
16,841,075
5
0
null
2013-05-30 16:01:58.34 UTC
4
2020-05-05 14:46:08.757 UTC
null
null
null
null
1,649,466
null
1
35
python|regex
29,069
<p>Don't use <code>re.split()</code>, use the <code>groups()</code> method of regex <code>Match</code>/<code>SRE_Match</code> objects.</p> <pre><code>&gt;&gt;&gt; f = '000014_L_20111007T084734-20111008T023142.txt' &gt;&gt;&gt; time_info = re.search(r'[LU]_(\w+)-(\w+)\.', f).groups() &gt;&gt;&gt; time_info ('20111007T084734', '20111008T023142') </code></pre> <p>You can even name the capturing groups and retrieve them in a dict, though you use <code>groupdict()</code> rather than <code>groups()</code> for that. (The regex pattern for such a case would be something like <code>r'[LU]_(?P&lt;groupA&gt;\w+)-(?P&lt;groupB&gt;\w+)\.'</code>)</p>
17,032,174
Having trouble with user.is_authenticated in django template
<p>Sorry if you tried helping me when I asked this earlier. Had to delete that question because I wasn't being allowed to edit additional information for some reason.</p> <p>I'm working on implementing user authentication on my django website. Everything works. My views, models, urls, etc. are all set up. Users can register, log in, log out. The issue I'm having is with this bit of code:</p> <pre><code>{% if request.user.is_authenticated %} &lt;li&gt;&lt;a href="/logout"&gt;Log Out&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li&gt;&lt;a href="/login"&gt;Log In&lt;/a&gt;&lt;/li&gt; {% endif %} </code></pre> <p>Even when I'm logged in, it is still displaying "Log In" as an option rather than "Log Out". However, if I click on the link, it'll redirect me to /profile because that's what the view tells it to do if I'm logged in. So, clearly it knows I'm logged in, but the template isn't readint user.is_authenticated as true.</p> <p>The view relating to login requests is:</p> <pre><code>def LoginRequest(request): if request.user.is_authenticated(): return HttpResponseRedirect('/profile/') if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] profile = authenticate(username=username, password=password) if profile is not None: login(request, profile) return HttpResponseRedirect('/profile/') else: return render_to_response('template/login.html', {'form': form}, context_instance=RequestContext(request)) else: return render_to_response('template/login.html', {'form': form}, context_instance=RequestContext(request)) else: ''' user is not submitting the form, show them login form ''' form = LoginForm() context = {'form': form} return render_to_response('template/login.html', context, context_instance = RequestContext(request)) </code></pre>
17,032,272
2
0
null
2013-06-10 20:22:50.877 UTC
6
2020-02-27 22:23:37.793 UTC
2015-12-20 10:32:23.81 UTC
null
2,607,447
null
2,411,268
null
1
36
django|authentication
45,514
<p>If the auth context processor is enabled, then <code>user</code> is already in the template context, and you can do:</p> <pre><code>{% if user.is_authenticated %} </code></pre> <p>If you want to access <code>request</code> in the template, make sure you have enabled the <a href="https://docs.djangoproject.com/en/1.11/ref/templates/api/#django-template-context-processors-request" rel="noreferrer">request context processor</a>.</p> <p>In your question you are using <code>render_to_response</code>. Ever since Django 1.3, it has been better to use <code>render</code> instead of <code>render_to_response</code>. Using <code>render_to_response</code> with <code>RequestContext(request)</code> works in Django &lt;= 1.9, but from Django 1.10 onwards you must use the <code>render</code> shortcut if you want the context processors to work.</p> <pre><code>return render(request, 'template/login.html', context) </code></pre>
16,824,661
CORS request not working in Safari
<p>I am making a CORS xhr request. This works fine in chrome, however when I run in safari I get an 'Can not load ---- access not allowed by Access-control-allow-origin'. The code is exactly the same and I have set the CORS on the server. Below is my code.(has access control, but you are free to try without the accessToken)</p> <pre><code> var water; var req = new XMLHttpRequest; req.overrideMimeType("application/json"); req.open('GET', 'https://storage.googleapis.com/fflog/135172watersupplies_json', true); req.setRequestHeader('Authorization', 'Bearer ' + accessToken); origThis = this; var target = this; req.onload = function() { water = req; req.send(null); </code></pre> <p>After looking at the request headers I see that a OPTIONS request is made first and this is the request that is not allowed. The origin header is not included in the response in Safari, but is in chrome. What would cause this. Any help would be greatly appreciated.</p> <p>UPDATE: I have tried in Safari for Windows and it works, so I'm not sure what is going on here. The mac that I am using is a remote access (Macincloud.com), but I don't think that would have anything to do with it.</p>
17,014,671
13
0
null
2013-05-29 22:03:50.16 UTC
9
2021-07-29 22:24:34.947 UTC
2013-05-29 22:15:56.823 UTC
null
751,581
null
751,581
null
1
56
javascript|safari|xmlhttprequest|cors
94,127
<p>Thanks for all the responses, I got this finally myself. I added 'Origin' to my responseHeaders and works fine now.</p>
4,284,194
Terminating idle mysql connections
<p>I see a lot of connections are open and remain idle for a long time, say 5 minutes. </p> <p>Is there any solution to terminate / close it from server without restarting the mysql service?</p> <p>I am maintaining a legacy PHP system and can not close the connections those are established to execute the query.</p> <p>Should I reduce the timeout values in my.cnf file those defaults to 8 hours?</p> <pre><code># default 28800 seconds interactive_timeout=60 wait_timeout=60 </code></pre>
4,284,212
2
0
null
2010-11-26 09:52:27.597 UTC
17
2015-11-21 10:24:24.987 UTC
2010-11-26 23:08:31.907 UTC
null
327,563
null
139,150
null
1
47
mysql|timeout|kill|wait|python-idle
143,875
<h3>Manual cleanup:</h3> <p>You can KILL the processid.</p> <pre><code>mysql&gt; show full processlist; +---------+------------+-------------------+------+---------+-------+-------+-----------------------+ | Id | User | Host | db | Command | Time | State | Info | +---------+------------+-------------------+------+---------+-------+-------+-----------------------+ | 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL | +---------+------------+-------------------+------+---------+-------+-------+-----------------------+ mysql&gt; kill 1193777; </code></pre> <p>But:</p> <ul> <li>the php application might report errors (or the webserver, check the error logs)</li> <li><strong>don't fix what is not broken</strong> - if you're not short on connections, just leave them be.</li> </ul> <h3>Automatic cleaner service ;)</h3> <p>Or you configure your mysql-server by setting a shorter timeout on <a href="http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_wait_timeout" rel="noreferrer"><code>wait_timeout</code></a> and <a href="http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_interactive_timeout" rel="noreferrer"><code>interactive_timeout</code></a></p> <pre><code>mysql&gt; show variables like &quot;%timeout%&quot;; +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | connect_timeout | 5 | | delayed_insert_timeout | 300 | | innodb_lock_wait_timeout | 50 | | interactive_timeout | 28800 | | net_read_timeout | 30 | | net_write_timeout | 60 | | slave_net_timeout | 3600 | | table_lock_wait_timeout | 50 | | wait_timeout | 28800 | +--------------------------+-------+ 9 rows in set (0.00 sec) </code></pre> <p>Set with:</p> <pre><code>set global wait_timeout=3; set global interactive_timeout=3; </code></pre> <p>(and also set in your configuration file, for when your server restarts)</p> <p>But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...</p>