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
3,752,019
How to get the index of a value in a vector using for_each?
<p>I have the following code (compiler: MSVC++ 10):</p> <pre><code>std::vector&lt;float&gt; data; data.push_back(1.0f); data.push_back(1.0f); data.push_back(2.0f); // lambda expression std::for_each(data.begin(), data.end(), [](int value) { // Can I get here index of the value too? }); </code></pre> <p>What I want in the above code snippet is to get the index of the value in the data vector inside the lambda expression. It seems for_each only accepts a single parameter function. Is there any alternative to this using for_each and lambda?</p>
3,752,089
10
0
null
2010-09-20 13:41:20.893 UTC
7
2018-08-24 08:24:18.977 UTC
2014-12-20 00:40:03.423 UTC
null
2,642,204
null
189,636
null
1
34
c++|c++11|lambda
33,209
<p>I don't think you can capture the index, but you can use an outer variable to do the indexing, capturing it into the lambda:</p> <pre><code>int j = 0; std::for_each(data.begin(), data.end(), [&amp;j](float const&amp; value) { j++; }); std::cout &lt;&lt; j &lt;&lt; std::endl; </code></pre> <p>This prints 3, as expected, and <code>j</code> holds the value of the index.</p> <p>If you want the actual iterator, you maybe can do it similarly:</p> <pre><code>std::vector&lt;float&gt;::const_iterator it = data.begin(); std::for_each(data.begin(), data.end(), [&amp;it](float const&amp; value) { // here "it" has the iterator ++it; }); </code></pre>
3,450,022
Check and return duplicates array php
<p>I would like to check if my array has any duplicates and return the duplicated values in an array. I want this to be as efficient as possible.</p> <p>Example:</p> <pre><code>$array = array( 1, 2, 2, 4, 5 ); function return_dup($array); // should return 2 $array2 = array( 1, 2, 1, 2, 5 ); function return_dup($array2); // should return an array with 1,2 </code></pre> <p>Also the initial array is always 5 positions long</p>
3,450,223
10
0
null
2010-08-10 14:28:10.787 UTC
6
2020-10-11 00:50:45.467 UTC
2020-10-11 00:00:42.153 UTC
null
947,370
null
450,504
null
1
50
php|arrays|duplicates
79,109
<p>this will be ~100 times faster than array_diff</p> <pre><code>$dups = array(); foreach(array_count_values($arr) as $val =&gt; $c) if($c &gt; 1) $dups[] = $val; </code></pre>
3,616,221
Search code inside a Github project
<p>Is there a way to grep for something inside a Github project's code?</p> <p>I could pull the source and grep it locally, but I was wondering if it's possible through the web interface or a 3rd-party alternative.</p> <p>Ideas?</p>
3,616,259
11
3
null
2010-09-01 08:29:54.46 UTC
80
2022-08-18 21:53:57.143 UTC
null
null
null
null
392,350
null
1
371
git|search|github
206,365
<p>Update Dec. 2021: search has <a href="https://stackoverflow.com/a/70279542/6309">been improved again</a>, with Search for an exact string, with support for substring matches and special characters, or regexps.</p> <p><a href="https://i.stack.imgur.com/A4l07.png" rel="noreferrer"><img src="https://i.stack.imgur.com/A4l07.png" alt="regex" /></a></p> <p>But only on <a href="https://cs.github.com/about" rel="noreferrer"><strong>cs.github.com</strong></a>, and still in beta (waitlist applies)</p> <hr /> <p>Update January 2013: a <strong><a href="https://github.com/blog/1381-a-whole-new-code-search" rel="noreferrer">brand new search has arrived!</a></strong>, based on <strong><a href="http://www.elasticsearch.org/community/" rel="noreferrer">elasticsearch.org</a></strong>:</p> <p>A search for stat within the ruby repo will be expressed as <strong><a href="https://github.com/search?q=stat%20repo:ruby/ruby&amp;type=Code&amp;ref=advsearch&amp;l=" rel="noreferrer"><code>stat repo:ruby/ruby</code></a></strong>, and will now just work<sup><sup>TM</sup></sup>.<br /> (the repo name is not case sensitive: <a href="https://github.com/search?q=repo:wordpress/wordpress%20test&amp;type=Code&amp;ref=searchresults" rel="noreferrer"><code>test repo:wordpress/wordpress</code></a> returns the same as <a href="https://github.com/search?q=repo:Wordpress/Wordpress%20test&amp;type=Code&amp;ref=searchresults" rel="noreferrer"><code>test repo:Wordpress/Wordpress</code></a>)</p> <p><img src="https://i.stack.imgur.com/oKLeR.png" alt="enter image description here" /></p> <p>Will give:</p> <p><img src="https://i.stack.imgur.com/MjPTm.png" alt="enter image description here" /></p> <p>And you have many other examples of search, based <a href="https://stackoverflow.com/a/5740886/6309">on followers</a>, or <a href="https://stackoverflow.com/a/12241932/6309">on forks</a>, or...</p> <hr /> <p><strong>Update July 2012</strong> (old days of Lucene search and poor code indexing, combined with broken GUI, kept here for archive):</p> <p>The search (based on <a href="http://wiki.apache.org/solr/SolrQuerySyntax" rel="noreferrer">SolrQuerySyntax</a>) is now more permissive and the dreaded &quot;<code>Invalid search query. Try quoting it.</code>&quot; is gone when using the <em>default</em> search selector &quot;Everything&quot;:)</p> <p>(I suppose we can all than <strong><a href="https://twitter.com/pea53" rel="noreferrer">Tim Pease</a></strong>, which had in one of his objectives <a href="https://github.com/blog/1116-tim-pease-is-a-githubber" rel="noreferrer">&quot;hacking on improved search experiences for all GitHub properties</a>&quot;, and <a href="https://twitter.com/vonc_/status/197565733830541313" rel="noreferrer">I did mention this Stack Overflow question</a> at the time ;) )</p> <p>Here is an illustration of a grep within the ruby code: it will looks for repos and users, but <em>also</em> for what I wanted to search in the first place: the code!</p> <p><img src="https://i.stack.imgur.com/HhkVy.png" alt="GitHub more permissive search results" /></p> <hr /> <p>Initial answer and illustration of the former issue (Sept. 2012 =&gt; March 2012)</p> <p>You can use the <a href="http://github.com/search" rel="noreferrer">advanced search GitHub form</a>:</p> <ul> <li>Choose <code>Code</code>, <code>Repositories</code> or <code>Users</code> from the drop-down and</li> <li>use the <strong>corresponding prefixes listed for that search type</strong>.</li> </ul> <p>For instance, Use the <strong><code>repo:username/repo-name</code></strong> directive to limit the search to a <strong>code</strong> repository.<br /> The initial &quot;<code>Advanced Search</code>&quot; page includes the section:</p> <blockquote> <p><em><strong>Code</strong></em> Search:</p> <p>The Code search will look through all of the code publicly hosted on GitHub. You can also filter by :</p> <ul> <li>the language <strong><code>language:</code></strong></li> <li>the repository name (including the username) <strong><code>repo:</code></strong></li> <li>the file path <strong><code>path:</code></strong></li> </ul> </blockquote> <p>So if you select the &quot;<code>Code</code>&quot; search selector, then your query grepping for a text within a repo will work:</p> <p><img src="https://i.stack.imgur.com/a58WF.png" alt="Good Search selector" /></p> <hr /> <p>What is <em>incredibly</em> <strong>unhelpful</strong> from GitHub is that:</p> <ul> <li>if you forget to put the right search selector (here &quot;<code>Code</code>&quot;), you will get an error message:<br /> &quot;<strong><code>Invalid search query. Try quoting it.</code></strong>&quot;</li> </ul> <p><img src="https://i.stack.imgur.com/fJtQ8.png" alt="Wrong selector for the code filer" /></p> <ul> <li><p>the error message doesn't help you at all.<br /> No amount of &quot;<code>quoting it</code>&quot; will get you out of this error.</p> </li> <li><p>once you get that error message, you don't get the sections reminding you of the right association between the search <em>selectors</em> (&quot;<code>Repositories</code>&quot;, &quot;<code>Users</code>&quot; or &quot;<code>Language</code>&quot;) and the (right) search <em>filters</em> (here &quot;<code>repo:</code>&quot;).<br /> Any further attempt you do won't display those associations (selectors-filters) back. Only the error message you see above...<br /> The only way to get back those arrays is by clicking the &quot;<code>Advance Search</code>&quot; icon:</p> </li> </ul> <p><img src="https://i.stack.imgur.com/fpEFn.png" alt="Advance Search Icon on GitHub" /></p> <ul> <li><p>the &quot;<code>Everything</code>&quot; search selector, which is the default, is actually the <em>wrong</em> one for <em>all</em> of the search filters! Except &quot;<code>language:</code>&quot;...<br /> (You could imagine/assume that &quot;<code>Everything</code>&quot; would help you to pick whatever search selector actually works with the search filter &quot;<code>repo:</code>&quot;, but nope. That would be too easy)</p> </li> <li><p>you cannot specify the search selector you want through the &quot;<code>Advance Search</code>&quot; field alone!<br /> (but you can for &quot;<code>language:</code>&quot;, even though &quot;<code>Search Language</code>&quot; is another combo box just below the &quot;<code>Search for</code>&quot; 'type' one...)</p> </li> </ul> <p><img src="https://i.stack.imgur.com/6AWA6.png" alt="Wrong search selector" /></p> <hr /> <p>So, the user's experience usually is as follows:</p> <ul> <li>you click &quot;<code>Advanced Search</code>&quot;, glance over those sections of filters, and notice one you want to use: &quot;<code>repo:</code>&quot;</li> <li>you make a first advanced search &quot;<code>repo:jruby/jruby stat</code>&quot;, but with the default Search selector &quot;<code>Everything</code>&quot;<br /> =&gt; <code>FAIL</code>! (and the arrays displaying the association &quot;Selectors-Filters&quot; is <strong>gone</strong>)</li> <li>you notice that &quot;Search for&quot; selector thingy, select the <em>first</em> choice &quot;<code>Repositories</code>&quot; (&quot;Dah! I want to search within repositories...&quot;)<br /> =&gt; <code>FAIL</code>!</li> <li>dejected, you select the next choice of selectors (here, &quot;<code>Users</code>&quot;), without even looking at said selector, just to give it one more try...<br /> =&gt; <code>FAIL</code>!</li> <li>&quot;Screw this, GitHub search is <strong>broken</strong>! I'm outta here!&quot;<br /> ...<br /> <sup>(GitHub advanced search is actually not broken. Only their GUI is...)</sup></li> </ul> <hr /> <p>So, to recap, if you want to &quot;grep for something inside a Github project's code&quot;, as the OP <a href="https://stackoverflow.com/users/392350/ben-humphreys">Ben Humphreys</a>, don't forget to select the &quot;<code>Code</code>&quot; search selector...</p>
3,931,156
Finding the hundred largest numbers in a file of a billion
<p>I went to an interview today and was asked this question:</p> <blockquote> <p>Suppose you have one billion integers which are unsorted in a disk file. How would you determine the largest hundred numbers?</p> </blockquote> <p>I'm not even sure where I would start on this question. What is the most efficient process to follow to give the correct result? Do I need to go through the disk file a hundred times grabbing the highest number not yet in my list, or is there a better way?</p>
3,931,214
14
5
null
2010-10-14 07:56:40.513 UTC
36
2016-12-09 22:14:59.283 UTC
2016-03-10 03:56:46.047 UTC
null
603,977
null
379,071
null
1
36
algorithm|sorting
13,421
<p>Here's my initial algorithm:</p> <pre><code>create array of size 100 [0..99]. read first 100 numbers and put into array. sort array in ascending order. while more numbers in file: get next number N. if N &gt; array[0]: if N &gt; array[99]: shift array[1..99] to array[0..98]. set array[99] to N. else find, using binary search, first index i where N &lt;= array[i]. shift array[1..i-1] to array[0..i-2]. set array[i-1] to N. endif endif endwhile </code></pre> <p>This has the (very slight) advantage is that there's no O(n^2) shuffling for the first 100 elements, just an O(n log n) sort and that you very quickly identify and throw away those that are too small. It also uses a binary search (7 comparisons max) to find the correct insertion point rather than 50 (on average) for a simplistic linear search (not that I'm suggesting anyone else proffered such a solution, just that it may impress the interviewer).</p> <p>You may even get bonus points for suggesting the use of optimised <code>shift</code> operations like <code>memcpy</code> in C provided you can be sure the overlap isn't a problem.</p> <hr> <p>One other possibility you may want to consider is to maintain three lists (of up to 100 integers each):</p> <pre><code>read first hundred numbers into array 1 and sort them descending. while more numbers: read up to next hundred numbers into array 2 and sort them descending. merge-sort lists 1 and 2 into list 3 (only first (largest) 100 numbers). if more numbers: read up to next hundred numbers into array 2 and sort them descending. merge-sort lists 3 and 2 into list 1 (only first (largest) 100 numbers). else copy list 3 to list 1. endif endwhile </code></pre> <p>I'm not sure, but that may end up being more efficient than the continual shuffling.</p> <p>The merge-sort is a simple selection along the lines of (for merge-sorting lists 1 and 2 into 3):</p> <pre><code>list3.clear() while list3.size() &lt; 100: while list1.peek() &gt;= list2.peek(): list3.add(list1.pop()) endwhile while list2.peek() &gt;= list1.peek(): list3.add(list2.pop()) endwhile endwhile </code></pre> <p>Simply put, pulling the top 100 values out of the combined list by virtue of the fact they're already sorted in descending order. I haven't checked in detail whether that would be more efficient, I'm just offering it as a possibility.</p> <p>I suspect the interviewers would be impressed with the potential for "out of the box" thinking and the fact that you'd stated that it should be evaluated for performance.</p> <p>As with most interviews, technical skill is <em>one</em> of the the things they're looking at.</p>
7,770,030
Preset the "save as type" field while using Application.FileDialog(msoFileDialogSaveAs) with MSAccess
<p>I searched all over for a way to do this.</p> <p>I want to open a Save As dialog box so the user can choose the location to save a file. But, <strong>I want the "Save as type" field to be preset with "comma seperated value File (*.csv)"</strong></p> <p>The problem is the "Filter" methode does not seem to work with "msoFileDialogSaveAs". Is it possible to preset the file type using "Application.FileDialog(msoFileDialogSaveAs)"?</p> <p>At the moment, if I save the file with the .csv extension and then open it in excel, I get the "<em>The file you are trying to open xxx.csv is in a different format than specified by the file extension ...</em>" message. The file works correctly though.</p> <pre><code> With Application.FileDialog(msoFileDialogSaveAs) .Title = "xxx" .AllowMultiSelect = False .InitialFileName = "xxx.csv" '.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" result = .Show If (result &lt;&gt; 0) Then ' create file FileName = Trim(.SelectedItems.Item(1)) fnum = FreeFile Open FileName For Output As fnum ' Write the csv data from form record set For Each fld In rs.Fields str = str &amp; fld.Name &amp; ", " Next ' Write header line str = Left(str, Len(str) - 2) ' remove last semi colon and space Print #fnum, str str = "" ' Write each row of data rs.MoveFirst Do While Not rs.EOF For i = 0 To 40 str = str &amp; rs(i) &amp; ", " ' write each field seperated by a semi colon Next i str = Left(str, Len(str) - 2) ' remove last semi colon and space Print #fnum, str str = "" rs.MoveNext Loop ' close file Close #fnum End If End With </code></pre> <p>Than You!</p>
7,770,786
5
5
null
2011-10-14 15:36:53.137 UTC
3
2020-06-05 15:15:42.207 UTC
2011-10-14 16:14:25.973 UTC
null
648,798
null
648,798
null
1
15
vba|ms-access-2007
49,071
<p>As stated he <code>FileDialog</code> help states <code>msoFileDialogSaveAs</code> is not supported.</p> <p>You can force a CSV extension on <code>FileName</code> when the dialog unloads;</p> <pre><code>FileName = getCSVName(FileName) ... Function getCSVName(fileName As String) As String Dim pos As Long pos = InStrRev(fileName, ".") If (pos &gt; 0) Then fileName = Left$(fileName, pos - 1) End If getCSVName = fileName &amp; ".CSV" End Function </code></pre> <p>If excel isn't liking your CSV, check if there are any values you need to quote to escape newlines/" (http://stackoverflow.com/questions/566052/can-you-encode-cr-lf-in-into-csv-files)</p> <p>And instead of this pattern;</p> <pre><code>For i = 0 To 40 str = str &amp; rs(i) &amp; ", " ' write each field seperated by a semi colon Next i str = Left(str, Len(str) - 2) ' remove last semi colon and space </code></pre> <p>you can;</p> <pre><code>dim delimiter as string ... For i = 0 To 40 str = str &amp; delimiter &amp; rs(i) ' write each field seperated by a semi colon delimiter = "," Next </code></pre>
7,871,767
Changing image view background dynamically
<p>I have a a set of 10 imageviews in my layout. I have given them sequential id's also as</p> <pre><code>android:id="@+id/pb1" android:id="@+id/pb2" </code></pre> <p>Now I want to change background dynamically. </p> <pre><code> int totalPoi = listOfPOI.size(); int currentPoi = (j/totalPoi)*10; for (i=1;i&lt;=currentPoi;i++) { imageview.setBackgroundResource(R.drawable.progressgreen); } </code></pre> <p>Now inside the for loop I want to set the image view background dynamically. i,e if the currentpoi value is 3, background of 3 image views should be changed. What ever the times the for loop iterates that many image view's background should be changed. Hope the question is clear now.</p> <p>Note : I have only 1 image progressgreen that need to be set to 10 image views</p>
7,876,872
6
1
null
2011-10-24 05:57:50.62 UTC
2
2016-08-02 17:46:13.67 UTC
2011-10-24 07:30:07.08 UTC
null
243,709
null
824,546
null
1
4
android|imageview
44,084
<p>Finally I did this in the following way, </p> <p>I placed all the id's in the array as</p> <pre><code>int[] imageViews = {R.id.pb1, R.id.pb2,R.id.pb3,R.id.pb4,R.id.pb5,R.id.pb6,R.id.pb7,R.id.pb8,R.id.pb9,R.id.pb10}; </code></pre> <p>Now: </p> <pre><code>int pindex = 0; for (pindex; pindex &lt;currentPoi; pindex++) { ImageView img = (ImageView) findViewById(imageViews[pindex]) ; img.setImageResource(R.drawable.progressgreen); } </code></pre> <p>Now, I am able to change the images dynamically. </p> <p>@goto10. Thanks for your help. I will debug your point to see what went wrong in my side</p>
7,957,944
Search for Capital Letter in String
<p>I am trying to search a string for the last index of a capital letter. I don't mind using regular expressions, but I'm not too familiar with them.</p> <pre><code>int searchPattern = searchString.lastIndexOf(" "); String resultingString = searchString.substring(searchPattern + 1); </code></pre> <p>As you can see, with my current code I'm looking for the last space that is included in a string. I need to change this to search for last capital letter.</p>
7,958,064
6
1
null
2011-10-31 18:23:53.583 UTC
0
2019-04-13 00:56:45.17 UTC
null
null
null
null
1,015,683
null
1
4
java
46,623
<p>You can write a method as follows:</p> <pre><code>public int lastIndexOfUCL(String str) { for(int i=str.length()-1; i&gt;=0; i--) { if(Character.isUpperCase(str.charAt(i))) { return i; } } return -1; } </code></pre>
8,060,170
Printing hexadecimal characters in C
<p>I'm trying to read in a line of characters, then print out the hexadecimal equivalent of the characters.</p> <p>For example, if I have a string that is <code>"0xc0 0xc0 abc123"</code>, where the first 2 characters are <code>c0</code> in hex and the remaining characters are <code>abc123</code> in ASCII, then I should get </p> <pre><code>c0 c0 61 62 63 31 32 33 </code></pre> <p>However, <code>printf</code> using <code>%x</code> gives me</p> <pre><code>ffffffc0 ffffffc0 61 62 63 31 32 33 </code></pre> <p>How do I get the output I want without the <code>"ffffff"</code>? And why is it that only c0 (and 80) has the <code>ffffff</code>, but not the other characters?</p>
8,060,195
7
1
null
2011-11-09 03:59:16.96 UTC
41
2018-11-06 19:49:23.273 UTC
2011-11-09 05:08:49.82 UTC
null
571,189
null
270,043
null
1
120
c|hex|printf
436,220
<p>You are seeing the <code>ffffff</code> because <code>char</code> is signed on your system. In C, vararg functions such as <code>printf</code> will promote all integers smaller than <code>int</code> to <code>int</code>. Since <code>char</code> is an integer (8-bit signed integer in your case), your chars are being promoted to <code>int</code> via sign-extension.</p> <p>Since <code>c0</code> and <code>80</code> have a leading 1-bit (and are negative as an 8-bit integer), they are being sign-extended while the others in your sample don't.</p> <pre><code>char int c0 -&gt; ffffffc0 80 -&gt; ffffff80 61 -&gt; 00000061 </code></pre> <p>Here's a solution:</p> <pre><code>char ch = 0xC0; printf("%x", ch &amp; 0xff); </code></pre> <p>This will mask out the upper bits and keep only the lower 8 bits that you want.</p>
8,240,637
Convert numbers to letters beyond the 26 character alphabet
<p>I'm creating some client side functions for a mappable spreadsheet export feature.</p> <p>I'm using jQuery to manage the sort order of the columns, but each column is ordered like an Excel spreadsheet i.e. a b c d e......x y z aa ab ac ad etc etc</p> <p>How can I generate a number as a letter? Should I define a fixed array of values? Or is there a dynamic way to generate this?</p>
8,241,071
8
0
null
2011-11-23 10:29:09.947 UTC
7
2022-07-18 16:41:24.16 UTC
2015-12-14 08:06:05.313 UTC
null
493,762
null
493,762
null
1
28
javascript|jquery
23,625
<p>I think you're looking for something like this</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> function colName(n) { var ordA = 'a'.charCodeAt(0); var ordZ = 'z'.charCodeAt(0); var len = ordZ - ordA + 1; var s = ""; while(n &gt;= 0) { s = String.fromCharCode(n % len + ordA) + s; n = Math.floor(n / len) - 1; } return s; } // Example: for(n = 0; n &lt; 125; n++) document.write(n + ":" + colName(n) + "&lt;br&gt;");</code></pre> </div> </div> </p>
4,138,754
Getting an attribute value in xml element
<p>I have an xml string like this and I want to get attribute value of "name" in a loop for each element. How do I do that? I am using javax.xml.parsers library. </p> <pre class="lang-js prettyprint-override"><code>&lt;xml&gt; &lt;Item type="ItemHeader" name="Plan Features" id="id_1"/&gt; &lt;Item type="Deductible" name="Deductible" id="a"&gt;Calendar Year &lt;Item type="Text" name="Individual" id="b"&gt;200&lt;/Item&gt; &lt;Item type="Text" name="Family" id="c"&gt;350&lt;/Item&gt; &lt;/Item&gt; &lt;Item lock="|delete|" type="Empty" name="Out-of-Pocket Annual Maximum" id="id_2"&gt; &lt;Item type="Text" name="Individual" id="d"&gt;400&lt;/Item&gt; &lt;Item type="Currency" name="Individual Out-of-Network" id="id_5"&gt;$320.00&lt;/Item&gt; &lt;Item type="Text" name="Family" id="e"&gt;670&lt;/Item&gt; &lt;/Item&gt; &lt;Item type="Text" name="Life Time Maximum" id="u"&gt;8000&lt;/Item&gt; &lt;Item type="Text" name="Coinsurance" id="f"&gt;60&lt;/Item&gt; &lt;Item type="Text" name="Office Visits" id="g"&gt;10&lt;/Item&gt; &lt;Item type="Text" name="Routine Physicals" id="h"&gt;12&lt;/Item&gt; &lt;Item type="Text" name="Preventive Care" id="m"/&gt; &lt;Item type="Text" name="Physician Services" id="i"/&gt; &lt;Item type="Text" name="Emergency Room Services / Urgent Care" id="j"/&gt; &lt;Item type="Text" name="Hospital Admission Services" id="k"/&gt; &lt;Item type="Text" name="Chiropractic" id="n"/&gt; &lt;Item type="Text" name="Prescription Drugs" id="l"/&gt; &lt;Item type="Text" name="Specialty Drugs" id="o"/&gt; &lt;Item type="Currency" name="Custom Field 2" id="id_4"&gt;$250.00&lt;/Item&gt; &lt;Item type="Boolean" name="Pre Tax Reduction Available" id="t"&gt;false&lt;/Item&gt; &lt;Item type="Boolean" name="Conversion Privilege" id="p"&gt;false&lt;/Item&gt; &lt;Item type="ItemHeader" name="Plan Setup" id="id_3"/&gt; &lt;Item type="Termination" name="Benefit Termination Date" id="q"&gt;Immediate&lt;/Item&gt; &lt;Item type="Determination" name="Premium Redetermination Date" id="r"&gt;Not Applicable&lt;/Item&gt; &lt;Item type="Participation" name="Participation Requirement" id="s"/&gt; &lt;/xml&gt; </code></pre> <p>This is what I am trying till now</p> <pre><code>DocumentBuilderFactory dbc = DocumentBuilderFactory.newInstance(); DocumentBuilder dbuilder; try { dbuilder = dbc.newDocumentBuilder(); Document doc = dbuilder.parse(new InputSource(new StringReader(plan.getProvisions()))); NodeList nl = doc.getElementsByTagName("Item"); for(int i = 0 ; i &lt; nl.getLength(); i++){ if(i == row){ Element e = (Element)nl.item(i); description = e.getAttribute("name"); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } </code></pre>
4,138,822
3
0
null
2010-11-09 21:20:18.227 UTC
6
2017-10-30 21:49:39.867 UTC
2017-10-30 21:49:39.867 UTC
null
1,021,725
null
203,018
null
1
24
java|xml
147,392
<p>I think I got it. I have to use <code>org.w3c.dom.Element</code> explicitly. I had a different Element field too.</p>
4,210,138
View() vs. PartialView()
<p>The <code>View()</code> method can load Partial Views. </p> <p>Is the difference between <code>View()</code> and <code>PartialView()</code> is that <code>View()</code> can load views and partial views and <code>PartialView()</code> can only load partial views?</p>
4,210,291
3
2
null
2010-11-17 23:08:36.88 UTC
6
2017-02-09 12:57:16.287 UTC
2010-11-17 23:26:19.81 UTC
null
23,199
null
89,605
null
1
38
asp.net-mvc
29,208
<p>It's up to a view engine to decide if they want to treat partial views different from regular views.</p> <p>For example, in the WebFormViewEngine there is no difference.</p> <p>In the new ASP.NET MVC 3 RazorViewEngine there are some differences. Only regular views will have the "_viewstart.cshtml" pages run because they are meant for things such as setting up layout pages.</p>
4,535,846
PHP: Adding prefix strings to array values
<p>What is the best way to add a specific value or values to an array? Kinda hard to explain, but this should help:</p> <pre><code>&lt;?php $myarray = array("test", "test2", "test3"); $myarray = array_addstuff($myarray, " "); var_dump($myarray); ?&gt; </code></pre> <p>Which outputs:</p> <pre><code>array(3) { [0]=&gt; string(5) " test" [1]=&gt; string(6) " test2" [2]=&gt; string(6) " test3" } </code></pre> <p>You could do so like this:</p> <pre><code>function array_addstuff($a, $i) { foreach ($a as &amp;$e) $e = $i . $e; return $a; } </code></pre> <p>But I'm wondering if there's a faster way, or if this function is built-in.</p>
4,535,862
4
1
null
2010-12-26 23:25:43.757 UTC
2
2017-08-04 22:21:08.7 UTC
2017-04-28 17:56:43.11 UTC
null
5,423,014
null
345,645
null
1
23
php|arrays
42,682
<p>In the case that you're using a PHP version >= 5.3:</p> <pre><code>$array = array('a', 'b', 'c'); array_walk($array, function(&amp;$value, $key) { $value .= 'd'; } ); </code></pre>
4,547,453
Can you write virtual functions / methods in Java?
<p>Is it possible to write <em>virtual</em> methods in Java, as one would do in C++?</p> <p>Or, is there a proper Java approach which you can implement that produces similar behavior? Could I please have some examples?</p>
4,547,462
6
0
null
2010-12-28 16:17:57.587 UTC
46
2019-10-28 06:48:28.48 UTC
2015-04-11 19:10:57.55 UTC
null
445,131
null
486,483
null
1
189
java|virtual|virtual-functions
244,240
<h2>From <a href="http://en.wikipedia.org/wiki/Virtual_function" rel="noreferrer">wikipedia</a></h2> <blockquote> <p>In <strong>Java</strong>, all non-static methods are by default "<strong>virtual functions.</strong>" Only methods marked with the <strong>keyword final</strong>, which cannot be overridden, along with <strong>private methods</strong>, which are not inherited, are <strong>non-virtual</strong>.</p> </blockquote>
4,770,297
Convert UTC datetime string to local datetime
<p>I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.</p> <p>In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:</p> <pre><code>datetime.utcfromtimestamp(timestamp) </code></pre> <p>That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)</p> <p>The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so: </p> <pre><code>"2011-01-21 02:37:21" </code></pre> <p>How do I convert this string to a DateTime in the users correct time zone?</p> <p>Also, what is the recommended storage for a users timezone information? (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second. </p>
4,771,733
16
2
null
2011-01-22 20:14:50.58 UTC
134
2022-02-09 18:44:36.91 UTC
2019-03-09 10:57:35.05 UTC
null
355,230
null
443,722
null
1
288
python|datetime|utc|localtime
510,848
<p>If you don't want to provide your own <code>tzinfo</code> objects, check out the <a href="http://niemeyer.net/python-dateutil">python-dateutil</a> library. It provides <code>tzinfo</code> implementations on top of a <a href="http://en.wikipedia.org/wiki/Tz_database">zoneinfo (Olson) database</a> such that you can refer to time zone rules by a somewhat canonical name.</p> <pre><code>from datetime import datetime from dateutil import tz # METHOD 1: Hardcode zones: from_zone = tz.gettz('UTC') to_zone = tz.gettz('America/New_York') # METHOD 2: Auto-detect zones: from_zone = tz.tzutc() to_zone = tz.tzlocal() # utc = datetime.utcnow() utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S') # Tell the datetime object that it's in UTC time zone since # datetime objects are 'naive' by default utc = utc.replace(tzinfo=from_zone) # Convert time zone central = utc.astimezone(to_zone) </code></pre> <p><strong>Edit</strong> Expanded example to show <code>strptime</code> usage</p> <p><strong>Edit 2</strong> Fixed API usage to show better entry point method</p> <p><strong>Edit 3</strong> Included auto-detect methods for timezones (Yarin)</p>
14,372,880
simple examples of filter function, recursive option specifically
<p>I am seeking some simple (i.e. - no maths notation, long-form reproducible code) examples for the <code>filter</code> function in R I think I have my head around the convolution method, but am stuck at generalising the recursive option. I have read and battled with various documentation, but the help is just a bit opaque to me.</p> <p>Here are the examples I have figured out so far:</p> <pre><code># Set some values for filter components f1 &lt;- 1; f2 &lt;- 1; f3 &lt;- 1; </code></pre> <p>And on we go:</p> <pre><code># basic convolution filter filter(1:5,f1,method="convolution") [1] 1 2 3 4 5 #equivalent to: x[1] * f1 x[2] * f1 x[3] * f1 x[4] * f1 x[5] * f1 # convolution with 2 coefficients in filter filter(1:5,c(f1,f2),method="convolution") [1] 3 5 7 9 NA #equivalent to: x[1] * f2 + x[2] * f1 x[2] * f2 + x[3] * f1 x[3] * f2 + x[4] * f1 x[4] * f2 + x[5] * f1 x[5] * f2 + x[6] * f1 # convolution with 3 coefficients in filter filter(1:5,c(f1,f2,f3),method="convolution") [1] NA 6 9 12 NA #equivalent to: NA * f3 + x[1] * f2 + x[2] * f1 #x[0] = doesn't exist/NA x[1] * f3 + x[2] * f2 + x[3] * f1 x[2] * f3 + x[3] * f2 + x[4] * f1 x[3] * f3 + x[4] * f2 + x[5] * f1 x[4] * f3 + x[5] * f2 + x[6] * f1 </code></pre> <p>Now's when I am hurting my poor little brain stem. I managed to figure out the most basic example using info at this post: <a href="https://stackoverflow.com/a/11552765/496803">https://stackoverflow.com/a/11552765/496803</a></p> <pre><code>filter(1:5, f1, method="recursive") [1] 1 3 6 10 15 #equivalent to: x[1] x[2] + f1*x[1] x[3] + f1*x[2] + f1^2*x[1] x[4] + f1*x[3] + f1^2*x[2] + f1^3*x[1] x[5] + f1*x[4] + f1^2*x[3] + f1^3*x[2] + f1^4*x[1] </code></pre> <p>Can someone provide similar code to what I have above for the convolution examples for the recursive version with <code>filter = c(f1,f2)</code> and <code>filter = c(f1,f2,f3)</code>?</p> <p>Answers should match the results from the function:</p> <pre><code>filter(1:5, c(f1,f2), method="recursive") [1] 1 3 7 14 26 filter(1:5, c(f1,f2,f3), method="recursive") [1] 1 3 7 15 30 </code></pre> <h1>EDIT</h1> <p>To finalise using @agstudy's neat answer:</p> <pre><code>&gt; filter(1:5, f1, method="recursive") Time Series: Start = 1 End = 5 Frequency = 1 [1] 1 3 6 10 15 &gt; y1 &lt;- x[1] &gt; y2 &lt;- x[2] + f1*y1 &gt; y3 &lt;- x[3] + f1*y2 &gt; y4 &lt;- x[4] + f1*y3 &gt; y5 &lt;- x[5] + f1*y4 &gt; c(y1,y2,y3,y4,y5) [1] 1 3 6 10 15 </code></pre> <p>and...</p> <pre><code>&gt; filter(1:5, c(f1,f2), method="recursive") Time Series: Start = 1 End = 5 Frequency = 1 [1] 1 3 7 14 26 &gt; y1 &lt;- x[1] &gt; y2 &lt;- x[2] + f1*y1 &gt; y3 &lt;- x[3] + f1*y2 + f2*y1 &gt; y4 &lt;- x[4] + f1*y3 + f2*y2 &gt; y5 &lt;- x[5] + f1*y4 + f2*y3 &gt; c(y1,y2,y3,y4,y5) [1] 1 3 7 14 26 </code></pre> <p>and...</p> <pre><code>&gt; filter(1:5, c(f1,f2,f3), method="recursive") Time Series: Start = 1 End = 5 Frequency = 1 [1] 1 3 7 15 30 &gt; y1 &lt;- x[1] &gt; y2 &lt;- x[2] + f1*y1 &gt; y3 &lt;- x[3] + f1*y2 + f2*y1 &gt; y4 &lt;- x[4] + f1*y3 + f2*y2 + f3*y1 &gt; y5 &lt;- x[5] + f1*y4 + f2*y3 + f3*y2 &gt; c(y1,y2,y3,y4,y5) [1] 1 3 7 15 30 </code></pre>
14,373,503
4
2
null
2013-01-17 05:45:40.363 UTC
13
2015-12-24 10:25:51.623 UTC
2017-05-23 11:54:10.437 UTC
null
-1
null
496,803
null
1
27
r|filter|time-series
24,258
<p>In the recursive case, I think no need to expand the expression in terms of xi. The key with "recursive" is to express the right hand expression in terms of previous y's.</p> <p>I prefer thinking in terms of filter size. </p> <p>filter size =1</p> <pre><code>y1 &lt;- x1 y2 &lt;- x2 + f1*y1 y3 &lt;- x3 + f1*y2 y4 &lt;- x4 + f1*y3 y5 &lt;- x5 + f1*y4 </code></pre> <p>filter size = 2</p> <pre><code>y1 &lt;- x1 y2 &lt;- x2 + f1*y1 y3 &lt;- x3 + f1*y2 + f2*y1 # apply the filter for the past value and add current input y4 &lt;- x4 + f1*y3 + f2*y2 y5 &lt;- x5 + f1*y4 + f2*y3 </code></pre>
14,685,149
Creating an installer for Java desktop application
<p>I know this question has been asked many a times and all the time there is an answer which says about using an executable jar or making an .exe using launch4j or similar app.</p> <p>I may sound like a novice, which I actually am. </p> <p>I have been trying a few things with a Java project. I have successfully made an executable jar and also an .exe file from it. All thanks to your previous answers in SO :)</p> <p>But, I want to create a installer for Windows. Like, pressing Next for 2 - 3 times(which shows all the terms and conditions etc), then a user specify a location(like C:\Program Files\New Folder\My App), then my .exe, lib folder, img folder, other important folders get pasted in the destination folder along with the .exe file and then a shortcut is created on a desktop.</p> <p>Any pointers to how can I achieve this ?</p>
14,686,023
8
3
null
2013-02-04 10:52:29.923 UTC
22
2022-03-16 10:09:11.057 UTC
2017-01-05 04:34:03.287 UTC
null
1,759,128
null
1,759,128
null
1
29
java|deployment|installation|desktop-application
48,498
<p>I have been using <a href="http://www.jrsoftware.org/isinfo.php">InnoSetup</a> for a long time. It has always worked very well. It can do everything you need (unpack files, put shortcuts on desktop, start menu etc) and generates installers that we are used to.</p>
35,003,153
Incorrect syntax near 'THROW'
<pre><code>IF @SQL IS NOT NULL BEGIN BEGIN TRY EXEC sp_executesql @SQL PRINT 'SUCCESS: ' + @SQL END TRY BEGIN CATCH SET @ErrorMessage = N'Error dropping constraint' + @CRLF + 'Table ' + @TableName + @CRLF + 'Script: ' + @SQL + @CRLF + 'Error message: ' + ERROR_MESSAGE() + @CRLF THROW 50100, @ErrorMessage, 1; END CATCH END </code></pre> <p>When the <code>CATCH</code> executes, I get the following error:</p> <blockquote> <p>Msg 102, Level 15, State 1, Line 257<br> Incorrect syntax near 'THROW'.</p> </blockquote> <p>Replacing <code>THROW</code> with <code>PRINT @ErrorMessage</code> works.</p> <p>Replacing <code>@ErrorMessage</code> variable with a literal string works.</p> <p>According to the docs, however, THROW is supposed to be able to take a variable. Not sure what to make of this. </p>
35,003,196
3
0
null
2016-01-25 21:54:56.89 UTC
3
2020-08-18 11:13:16.013 UTC
2016-01-25 23:48:27.373 UTC
null
2,123,899
null
2,123,899
null
1
46
sql-server|tsql|sql-server-2014
17,116
<p>From <a href="https://msdn.microsoft.com/en-us/library/ee677615.aspx">MSDN</a>:</p> <blockquote> <p>The statement before the THROW statement must be followed by the semicolon (;) statement terminator.</p> </blockquote>
49,948,350
phpMyAdmin on MySQL 8.0
<p><strong>UPDATE</strong><br> Newer versions of phpMyAdmin solved this issue. I've successfully tested with phpMyAdmin 5.0.1</p> <hr> <p>I have installed the MySQL 8.0 server and phpMyAdmin, but when I try to access it from the browser the following errors occur:</p> <pre><code>#2054 - The server requested authentication method unknown to the client mysqli_real_connect(): The server requested authentication method unknown to the client [caching_sha2_password] mysqli_real_connect(): (HY000/2054): The server requested authentication method unknown to the client </code></pre> <p>I imagine it must have something to do with the strong passwords implemented and the relative freshness of the MySQL release.</p> <p>But I know nothing of the most advanced driver and connection configuration.</p> <p>Has someone faced the same problem and solved it? :D</p>
50,437,307
18
2
null
2018-04-20 19:15:20.577 UTC
34
2021-09-14 10:18:17.94 UTC
2020-02-19 12:43:37.413 UTC
null
8,569,585
null
8,569,585
null
1
83
mysql|phpmyadmin|database-connection|mysql-8.0
186,948
<p>Log in to MySQL console with <strong>root</strong> user:</p> <pre><code>root@9532f0da1a2a:/# mysql -u root -pPASSWORD </code></pre> <p>and change the Authentication Plugin with the password there:</p> <pre><code>mysql&gt; ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD'; Query OK, 0 rows affected (0.08 sec) </code></pre> <p><em>You can read more info about the Preferred Authentication Plugin on the MySQL 8.0 Reference Manual</em></p> <p><a href="https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html#upgrade-caching-sha2-password" rel="nofollow noreferrer">https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html#upgrade-caching-sha2-password</a></p> <p>It is working perfectly in a <strong>docker</strong>ized environment:</p> <pre><code>docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -p 3306:3306 -d mysql:latest docker exec -it mysql bash mysql -u root -pPASSWORD ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD'; exit exit docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest </code></pre> <p>So you can now log in to phpMyAdmin on http://localhost:8080 with root / PASSWORD</p> <hr /> <p><strong>mysql/mysql-server</strong></p> <p>If you are using <a href="https://hub.docker.com/r/mysql/mysql-server/" rel="nofollow noreferrer" title="mysql/mysql-server">mysql/mysql-server</a> docker image</p> <p><em>But remember, it is just a 'quick and dirty' solution in the development environment. It is not wise to change the <a href="https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html#upgrade-caching-sha2-password" rel="nofollow noreferrer">MySQL Preferred Authentication Plugin</a>.</em></p> <pre><code>docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -e MYSQL_ROOT_HOST=% -p 3306:3306 -d mysql/mysql-server:latest docker exec -it mysql mysql -u root -pPASSWORD -e &quot;ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';&quot; docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest </code></pre> <p><strong>Updated solution at 10/04/2018</strong></p> <p>Change the MySQL default authentication plugin by uncommenting the <code>default_authentication_plugin=mysql_native_password</code> setting in <code>/etc/my.cnf</code></p> <p><em>use at your own risk</em></p> <pre><code>docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -e MYSQL_ROOT_HOST=% -p 3306:3306 -d mysql/mysql-server:latest docker exec -it mysql sed -i -e 's/# default-authentication-plugin=mysql_native_password/default-authentication-plugin=mysql_native_password/g' /etc/my.cnf docker stop mysql; docker start mysql docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest </code></pre> <p><strong>Updated workaround at 01/30/2019</strong></p> <pre><code>docker run --name mysql -e MYSQL_ROOT_PASSWORD=PASSWORD -e MYSQL_ROOT_HOST=% -p 3306:3306 -d mysql/mysql-server:latest docker exec -it mysql sed -i -e 's/# default-authentication-plugin=mysql_native_password/default-authentication-plugin=mysql_native_password/g' /etc/my.cnf docker exec -it mysql mysql -u root -pPASSWORD -e &quot;ALTER USER root IDENTIFIED WITH mysql_native_password BY 'PASSWORD';&quot; docker stop mysql; docker start mysql docker run --name phpmyadmin -d --link mysql:db -p 8080:80 phpmyadmin/phpmyadmin:latest </code></pre> <p><a href="https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_default_authentication_plugin" rel="nofollow noreferrer">default_authentication_plugin</a></p> <p><strong>Updated solution at 09/13/2021</strong></p> <p>ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';</p> <ul> <li>exactly with quotes *</li> </ul>
50,220,854
Could not use Observable.of in RxJs 6 and Angular 6
<pre><code> import { Observable, of } from "rxjs"; // And if I try to return like this return Observable.of(this.purposes); </code></pre> <p>I am getting an error stating, Property 'of' does not exist on type 'typeof Observable'</p>
50,245,593
3
2
null
2018-05-07 19:05:01.89 UTC
9
2019-05-13 17:05:54.707 UTC
2018-08-27 09:43:20.7 UTC
null
5,490,782
null
7,962,294
null
1
64
angular|rxjs6|angular-observable
45,821
<p>Looks like cartant's comment is correct, the <a href="https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md" rel="noreferrer">RxJS upgrade guide</a> doesn't cover that method specifically but does say <em>"Classes that operate on observables have been replaced by functions"</em></p> <p>Which seems to mean all or most of those class methods like .of, .throw etc. have been replaced by a function</p> <p>So instead of</p> <pre><code>import { Observable, of } from "rxjs"; Observable.of(this.purposes); </code></pre> <p>do</p> <pre><code>import { of } from "rxjs"; of(this.purposes); </code></pre>
59,391,984
Test Explorer (VS) shows '<Unknown project>'
<p>Everthing below is made in VS2019, using .NET Framework 4.7 and NUnit + NUnit3TestAdapter</p> <p>I created an assembly called Exitus.Tests, and added a few unit tests. However, do to some issues with Nuget, that I could not solve, I made another project called Exitus.UnitTests and removed the once file I had in the old project (including changing the namespace). </p> <p>Now the new test project showed op correctly in the explorer, but a "ghost" of the old project remained:</p> <p><a href="https://i.stack.imgur.com/ntW1F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ntW1F.png" alt="Visual Studio test explorer"></a></p> <p>If I try to run the test, the output window shows the following error:</p> <blockquote> <p>System.InvalidOperationException: The following TestContainer was not found 'C:\Users\xxx\Source\Repositories\Expire\Exitus.Tests\bin\Debug\Exitus.Tests.dll' at Microsoft.VisualStudio.TestWindow.Client.TestContainer.TestContainerProvider.d__46.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.VisualStudio.TestWindow.Controller.TestContainerConfigurationQueryByTestsBase.d__6.MoveNext() (...)</p> </blockquote> <p>The stack trace is a lot longer, but the curious thing is the second line, stating that it could not find the test container at <code>\Exitus.Tests\bin\Debug\Exitus.Tests.dll</code>. This is the name of the old test project, which I removed and deleted. I have searched my entire project for the term <code>Exitus.Tests</code> and it returns no results. </p> <p>Is there anyway to forcefully remove this 'ghost' project? </p>
59,393,012
5
1
null
2019-12-18 12:24:14.817 UTC
16
2020-06-02 07:42:00.803 UTC
null
null
null
null
2,445,415
null
1
182
c#|visual-studio|nunit
17,965
<ol> <li>Close <kbd>Visual Studio</kbd>.</li> <li>Delete the <code>*.testlog</code> files in: <em>solutionfolder</em>\.vs\<em>solution name</em>\v16\TestStore\<em>number</em>.</li> </ol>
63,576,252
Android emulators are not working on macOS Big Sur 11.3+
<p>I have upgraded the mac OS to Big Sur and none of the emulators are working. It seems that all Android emulators Fails on Mac OS Big Sur Beta. I deleted the old emulators and created new ones with different HW/SW, unsuccessfully. Introduced the following issues in the android emulator.</p> <ol> <li>ffffffffb69b4dbb: unhandled exit 1d</li> <li>Emulator Engine Failed</li> <li>adb Device Offline</li> </ol> <p><a href="https://issuetracker.google.com/issues/165038831" rel="nofollow noreferrer">https://issuetracker.google.com/issues/165038831</a></p> <p>Does anyone have a solution?</p> <p><strong>EDIT 27.04.2021</strong></p> <pre><code>~/Library/Android/sdk/emulator/emulator -gpu host -read-only -feature HVF -avd Pixel_4_API_29 emulator: Android emulator version 30.5.5.0 (build_id 7285888) (CL:N/A) handleCpuAcceleration: feature check for hvf cannot add library /Users/dunatv/Library/Android/sdk/emulator/qemu/darwin-x86_64/lib64/vulkan/libvulkan.dylib: failed added library /Users/dunatv/Library/Android/sdk/emulator/lib64/vulkan/libvulkan.dylib cannot add library /Users/dunatv/Library/Android/sdk/emulator/qemu/darwin-x86_64/lib64/vulkan/libMoltenVK.dylib: failed HVF error: HV_ERROR qemu-system-x86_64: failed to initialize HVF: Invalid argument HAX is working and emulator runs in fast virt mode. qemu-system-x86_64: Back to HAX accelerator added library /Users/dunatv/Library/Android/sdk/emulator/lib64/vulkan/libMoltenVK.dylib emulator: INFO: GrpcServices.cpp:301: Started GRPC server at 127.0.0.1:8554, security: Local </code></pre> <p><strong>UPDATE: 11 Aug 2021</strong></p> <p>Currently the Emulators and Arctic Fox are working. Tested on Big Sur 11.5.1</p>
64,072,957
14
17
null
2020-08-25 09:50:02.983 UTC
8
2021-08-11 06:16:36.103 UTC
2021-08-11 06:16:36.103 UTC
null
843,001
null
843,001
null
1
53
android-emulator|macos-big-sur
36,443
<p><strong>Update, 10-1-2020</strong></p> <p>The Android Emulator team has pushed 30.1.5 which fixes this issue in stable. The dev build, 30.2.0 does not contain this fix. It should be available &quot;soon&quot; according to the Googler's working on this.</p> <p>Another note, if you experience poor performance in your emulator you may wish to try using the host's GPU for rendering. This can be accomplished by running the following command in your terminal where -avd is the name of your emulator device with spaces turned to underscores.</p> <pre><code>~/Library/Android/sdk/emulator/emulator -gpu host -feature HVF -avd pixel_3a_api_29 </code></pre> <p><strong>Old information</strong>, kept for educational value:</p> <p><a href="https://android-review.googlesource.com/c/platform/external/qemu/+/1432904" rel="noreferrer">This</a> is the reference to the commit fixing this issue for Big Sur. This looks like it should be released in the emulator 30.1.5 (see log <a href="https://android.googlesource.com/platform/external/qemu/+log/refs/heads/emu-30-release" rel="noreferrer">https://android.googlesource.com/platform/external/qemu/+log/refs/heads/emu-30-release</a>) which should be in the next canary build.</p> <p>If you can't wait, you should be able to build off that branch. Lightly tested guide heavily pulling from the readme of the repo:</p> <pre><code># Get the google repo tool - you can skip if you already have it curl http://commondatastorage.googleapis.com/git-repo-downloads/repo &gt; /usr/local/bin/repo &amp;&amp; chmod +x /usr/local/bin/repo # Get the code, will take some time. Probably best to go get a coffee here or run on a server if you have poor internet mkdir -p $HOME/emu-master-dev &amp;&amp; cd $HOME/emu-master-dev repo init -u https://android.googlesource.com/platform/manifest -b emu-master-dev repo sync -j8 # Get XCode 10.1 - required https://download.developer.apple.com/Developer_Tools/Xcode_10.1/Xcode_10.1.xip sudo xcodebuild -license accept &amp;&amp; sudo xcode-select --install # Get MacOS 10.13 SDK which is required export XCODE_PATH=$(xcode-select -print-path 2&gt;/dev/null) git clone https://github.com/phracker/MacOSX-SDKs cp -r MacOSX-SDKs/MacOSX10.13.sdk/ &quot;$XCODE_PATH/Platforms/MacOSX.platform/Developer/SDKs&quot; # Build the emulator, which will be another coffee break... cd external/qemu &amp;&amp; android/rebuild.sh # run it :) ./objs/emulator -list-avds </code></pre>
34,830,964
How to limit the maximum number of running Celery tasks by name
<p>How do you limit the number of instances of a specific Celery task that can be ran simultaneously?</p> <p>I have a task that processes large files. I'm running into a problem where a user may launch several tasks, causing the server to run out of CPU and memory as it tries to process too many files at once. I want to ensure that only N instances of this one type of task are ran at any given time, and that other tasks will sit queued in the scheduler until the others complete.</p> <p>I see there's a <a href="http://docs.celeryproject.org/en/latest/userguide/tasks.html" rel="noreferrer">rate_limit</a> option in the task decorator, but I don't think this does what I want. If I'm understanding the docs correctly, this will just limit how quickly the tasks are launched, but it won't restrict the overall number of tasks running, so this will make my server will crash more slowly...but it will still crash nonetheless.</p>
52,166,342
3
0
null
2016-01-16 19:07:52.08 UTC
9
2018-09-04 12:26:48.297 UTC
null
null
null
null
247,542
null
1
17
python|celery|celery-task
8,669
<p>You have to setup extra queue and set desired concurrency level for it. From <a href="http://docs.celeryproject.org/en/latest/userguide/routing.html#id2" rel="noreferrer">Routing Tasks</a>:</p> <pre><code># Old config style CELERY_ROUTES = { 'app.tasks.limited_task': {'queue': 'limited_queue'} } </code></pre> <p>or </p> <pre><code>from kombu import Exchange, Queue celery.conf.task_queues = ( Queue('default', default_exchange, routing_key='default'), Queue('limited_queue', default_exchange, routing_key='limited_queue') ) </code></pre> <p>And start extra worker, serving only limited_queue:</p> <pre><code>$ celery -A celery_app worker -Q limited_queue --loglevel=info -c 1 -n limited_queue </code></pre> <p>Then you can check everything running smoothly using <a href="https://flower.readthedocs.io/en/latest/" rel="noreferrer">Flower</a> or inspect command:</p> <pre><code>$ celery -A celery_app worker inspect --help </code></pre>
47,843,039
How to properly convert domain entities to DTOs while considering scalability & testability
<p>I have read several articles and Stackoverflow posts for converting domain objects to DTOs and tried them out in my code. When it comes to testing and scalability I am always facing some issues. I know the following three possible solutions for converting domain objects to DTOs. Most of the time I am using Spring.</p> <p><strong>Solution 1: Private method in the service layer for converting</strong></p> <p>The first possible solution is to create a small "helper" method in the service layer code which is convertig the retrieved database object to my DTO object. </p> <pre><code>@Service public MyEntityService { public SomeDto getEntityById(Long id){ SomeEntity dbResult = someDao.findById(id); SomeDto dtoResult = convert(dbResult); // ... more logic happens return dtoResult; } public SomeDto convert(SomeEntity entity){ //... Object creation and using getter/setter for converting } } </code></pre> <p>Pros:</p> <ul> <li>easy to implement</li> <li>no additional class for convertion needed -> project doesn't blow up with entities</li> </ul> <p>Cons: </p> <ul> <li>problems when testing, as <code>new SomeEntity()</code> is used in the privated method and if the object is deeply nested I have to provide a adequate result of my <code>when(someDao.findById(id)).thenReturn(alsoDeeplyNestedObject)</code> to avoid NullPointers if convertion is also dissolving the nested structure</li> </ul> <p><strong>Solution 2: Additional constructor in the DTO for converting domain entity to DTO</strong></p> <p>My second solution would be to add an additional constructor to my DTO entity to convert the object in the constructor.</p> <pre><code>public class SomeDto { // ... some attributes public SomeDto(SomeEntity entity) { this.attribute = entity.getAttribute(); // ... nesting convertion &amp; convertion of lists and arrays } } </code></pre> <p>Pros:</p> <ul> <li>no additional class for converting needed</li> <li>convertion hided in the DTO entity -> service code is smaller</li> </ul> <p>Cons:</p> <ul> <li>usage of <code>new SomeDto()</code> in the service code and therefor I have to provide the correct nested object structure as a result of my <code>someDao</code> mocking. </li> </ul> <p><strong>Solution 3: Using Spring's Converter or any other externalized Bean for this converting</strong></p> <p>If recently saw that Spring is offering a class for converting reasons: <code>Converter&lt;S, T&gt;</code> but this solution stands for every externalized class which is doing the convertion. With this solution I am injecting the converter to my service code and I call it when i want to convert the domain entity to my DTO.</p> <p>Pros:</p> <ul> <li>easy to test as I can mock the result during my test case</li> <li>separation of tasks -> a dedicated class is doing the job</li> </ul> <p>Cons:</p> <ul> <li>doesn't "scale" that much as my domain model grows. With a lot of entities I have to create two converters for every new entity (-> converting DTO entitiy and entitiy to DTO)</li> </ul> <p>Do you have more solutions for my problem and how do you handle it? Do you create a new Converter for every new domain object and can "live" with the amount of classes in the project?</p> <p>Thanks in advance!</p>
47,853,826
5
1
null
2017-12-16 06:05:14.163 UTC
22
2021-05-21 15:41:57.007 UTC
null
null
null
null
9,085,273
null
1
37
java|spring|spring-boot|design-patterns|junit
32,917
<blockquote> <p>Solution 1: Private method in the service layer for converting</p> </blockquote> <p>I guess <strong>Solution 1</strong> will not not work well, because your DTOs are domain-oriented and not service oriented. Thus it will be likely that they are used in different services. So a mapping method does not belong to one service and therefore should not be implemented in one service. How would you re-use the mapping method in another service?</p> <p>The 1. solution would work well if you use dedicated DTOs per service method. But more about this at the end.</p> <blockquote> <p>Solution 2: Additional constructor in the DTO for converting domain entity to DTO</p> </blockquote> <p>In general a good option, because you can see the DTO as an adapter to the entity. In other words: the DTO is another representation of an entity. Such designs often wrap the source object and provide methods that give you another view on the wrapped object.</p> <p>But a DTO is a data <strong>transfer</strong> object so it might be serialized sooner or later and send over a network, e.g. using <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#remoting" rel="nofollow noreferrer">spring's remoting capabilities</a>. In this case the client that receives this DTO must deserialize it and thus needs the entity classes in it's classpath, even if it only uses the DTO's interface.</p> <blockquote> <p>Solution 3: Using Spring's Converter or any other externalized Bean for this converting</p> </blockquote> <p>Solution 3 is the solution that I also would prefer. But I would create a <code>Mapper&lt;S,T&gt;</code> interface that is responsible for mapping from source to target and vice versa. E.g.</p> <pre><code>public interface Mapper&lt;S,T&gt; { public T map(S source); public S map(T target); } </code></pre> <p>The implementation can be done using a mapping framework like <a href="http://modelmapper.org/getting-started/" rel="nofollow noreferrer">modelmapper</a>.</p> <hr /> <p>You also said that a converter for each entity</p> <blockquote> <p>doesn't &quot;scale&quot; that much as my domain model grows. With a lot of entities I have to create two converters for every new entity (-&gt; converting DTO entitiy and entitiy to DTO)</p> </blockquote> <p>I doupt that you only have to create 2 converter or one mapper for one DTO, because your DTO is domain-oriented.</p> <p>As soon as you start to use it in another service you will recognize that the other service usually should or can not return all values that the first service does. You will start to implement another mapper or converter for each other service.</p> <p>This answer would get to long if I start with pros and cons of dedicated or shared DTOs, so I can only ask you to read my blog <a href="https://www.link-intersystems.com/blog/2012/01/12/pros-and-cons-of-service-layer-designs/" rel="nofollow noreferrer">pros and cons of service layer designs</a>.</p> <p><strong>EDIT</strong></p> <blockquote> <p>About the third solution: where do you prefer to put the call for the mapper?</p> </blockquote> <p>In the layer above the use cases. DTOs are data transfer objects, because they pack data in data structures that are best for the transfer protocol. Thus I call that layer the transport layer. This layer is responsible for mapping use case's request and result objects from and to the transport representation, e.g. json data structures.</p> <p><strong>EDIT</strong></p> <blockquote> <p>I see you're ok with passing an entity as a DTO constructor parameter. Would you also be ok with the opposite? I mean, passing a DTO as an Entity constructor parameter?</p> </blockquote> <p>A good question. The opposite would not be ok for me, because I would then introduce a dependency in the entity to the transport layer. This would mean that a change in the transport layer can impact the entities and I don't want changes in more detailed layers to impact more abstract layers.</p> <p>If you need to pass data from the transport layer to the entity layer you should apply the dependency inversion principle.</p> <p>Introduce an interface that will return the data through a set of getters, let the DTO implement it and use this interface in the entities constructor. Keep in mind that this interface belongs to the entity's layer and thus should not have any dependencies to the transport layer.</p> <pre><code> interface +-----+ implements || +------------+ uses +--------+ | DTO | ---------------||-&gt; | EntityData | &lt;---- | Entity | +-----+ || +------------+ +--------+ </code></pre>
26,094,084
ng-class condition changes, but not updating classes
<p>I have a very strange issue. I have to set an <code>active</code> class on the appropriate <code>&lt;li&gt;</code> when the <code>$scope.selectedCat == cat.id</code>. The list is generated with ng-repeat. If selectedCat is false, the 'Browse All Categories' list item (outside of ng-repeat) is set to active. <code>setCat()</code> sets the value of the <code>$scope.selectedCat</code> variable:</p> <pre><code>&lt;div id="cat-list" ng-controller="CatController"&gt; &lt;li ng-class="{'active': {{selectedCat == false}}}"&gt; &lt;a&gt; &lt;div class="name" ng-click="setCat(false)" &gt;Browse All Categories&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class="has-subcat" ng-repeat="cat in cats | filter:catsearch" ng-class="{'active': {{selectedCat == cat.id}}}"&gt; &lt;a&gt; &lt;div cat class="name" ng-click="setCat({{cat.id}})" ng-bind-html="cat.name | highlight:catsearch"&gt;&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;/div&gt; </code></pre> <p>When the page loads, everything works fine (snapshot from FireBug):</p> <pre><code>&lt;li ng-class="{'active': true}" class="ng-scope active"&gt; &lt;!-- ngRepeat: cat in cats | filter:catsearch --&gt; &lt;li class="has-subcat ng-isolate-scope" ng-repeat="cat in cats | filter:catsearch" ng-class="{'active': false}"&gt; </code></pre> <p>However when I set $scope.selectedClass to a <code>cat.id</code> value, the condition within ng-class gets evaluated correctly, but ng-class won't update the classes accordingly:</p> <pre><code>&lt;li ng-class="{'active': false}" class="ng-scope active"&gt; &lt;!--Right here!--&gt; &lt;!-- ngRepeat: cat in cats | filter:catsearch --&gt; &lt;li class="has-subcat ng-isolate-scope" ng-repeat="cat in cats | filter:catsearch" ng-class="{'active': true}"&gt; </code></pre> <p>Please note that in the first line active class stays set, while ng-class evaluates to false. In the last line active is not set, while ng-class evaluates to true.</p> <p>Any ideas why it doesn't work? What's the correct Angular way of doing this?</p>
26,094,123
5
0
null
2014-09-29 06:56:27.133 UTC
null
2019-07-20 13:19:04.74 UTC
null
null
null
null
3,009,639
null
1
31
javascript|angularjs|ng-class
43,517
<p>Replace:</p> <pre class="lang-none prettyprint-override"><code>ng-class="{'active': {{selectedCat == cat.id}}}" </code></pre> <p>With:</p> <pre class="lang-none prettyprint-override"><code>ng-class="{'active': selectedCat == cat.id}" </code></pre> <p>You never need to nest those curly braces like that, in Angular.</p> <p>Have a look at the <a href="https://docs.angularjs.org/api/ng/directive/ngClass"><code>ng-class</code> documentation</a> for some more examples.</p>
7,536,142
How to Model Real-World Relationships in a Graph Database (like Neo4j)?
<p>I have a general question about modeling in a graph database that I just can't seem to wrap my head around.</p> <p>How do you model this type of relationship: "Newton invented Calculus"?</p> <p>In a <a href="http://docs.neo4j.org/chunked/snapshot/graphdb-neo4j-relationships.html" rel="noreferrer">simple graph</a>, you could model it like this:</p> <pre><code>Newton (node) -&gt; invented (relationship) -&gt; Calculus (node) </code></pre> <p>...so you'd have a bunch of "invented" graph relationships as you added more people and inventions.</p> <p>The problem is, you start needing to add a bunch of properties to the relationship:</p> <ul> <li>invention_date</li> <li>influential_concepts</li> <li>influential_people</li> <li>books_inventor_wrote</li> </ul> <p>...and you'll want to start creating relationships between those properties and other nodes, such as:</p> <ul> <li>influential_people: relationship to person nodes</li> <li>books_inventor_wrote: relationship to book nodes</li> </ul> <p>So now it seems like the "real-world relationships" ("invented") should actually be a node in the graph, and the graph should look like this:</p> <pre><code>Newton (node) -&gt; (relationship) -&gt; Invention of Calculus (node) -&gt; (relationship) -&gt; Calculus (node) </code></pre> <p>And to complicate things more, other people are also participated in the invention of Calculus, so the graph now becomes something like:</p> <pre><code>Newton (node) -&gt; (relationship) -&gt; Newton's Calculus Invention (node) -&gt; (relationship) -&gt; Invention of Calculus (node) -&gt; (relationship) -&gt; Calculus (node) Leibniz (node) -&gt; (relationship) -&gt; Leibniz's Calculus Invention (node) -&gt; (relationship) -&gt; Invention of Calculus (node) -&gt; (relationship) -&gt; Calculus (node) </code></pre> <p>So I ask the question because it seems like <em>you don't want to set properties on the actual graph database "relationship" objects</em>, because you may want to at some point treat them as nodes in the graph.</p> <p>Is this correct?</p> <p>I have been studying the <a href="http://www.freebase.com/docs/mql/ch02.html" rel="noreferrer">Freebase Metaweb Architecture</a>, and they seem to be treating everything as a node. For example, Freebase has the idea of a <a href="http://wiki.freebase.com/wiki/CVT/Mediator_CVT_proposal" rel="noreferrer">Mediator/CVT</a>, where you can create a "Performance" node that links an "Actor" node to a "Film" node, like here: <a href="http://www.freebase.com/edit/topic/en/the_last_samurai" rel="noreferrer">http://www.freebase.com/edit/topic/en/the_last_samurai</a>. Not quite sure if this is the same issue though.</p> <p>What are some guiding principles you use to figure out if the "real-world relationship" should actually be a graph node rather than a graph relationship?</p> <p>If there are any good books on this topic I would love to know. Thanks!</p>
7,538,711
1
0
null
2011-09-24 00:30:27.633 UTC
9
2014-12-07 17:10:40.597 UTC
2014-12-07 17:10:40.597 UTC
null
169,992
null
169,992
null
1
20
nosql|neo4j|graph-databases
3,866
<p>Some of these things, such as <code>invention_date</code>, can be stored as properties on the edges as in most graph databases edges can have properties in the same way that vertexes can have properties. For example you could do something like this (code follows <a href="https://github.com/tinkerpop/blueprints" rel="noreferrer">TinkerPop's Blueprints</a>):</p> <pre><code>Graph graph = new Neo4jGraph("/tmp/my_graph"); Vertex newton = graph.addVertex(null); newton.setProperty("given_name", "Isaac"); newton.setProperty("surname", "Newton"); newton.setProperty("birth_year", 1643); // use Gregorian dates... newton.setProperty("type", "PERSON"); Vertex calculus = graph.addVertex(null); calculus.setProperty("type", "KNOWLEDGE"); Edge newton_calculus = graph.addEdge(null, newton, calculus, "DISCOVERED"); newton_calculus.setProperty("year", 1666); </code></pre> <p>Now, lets expand it a little bit and add in Liebniz:</p> <pre><code>Vertex liebniz = graph.addVertex(null); liebniz.setProperty("given_name", "Gottfried"); liebniz.setProperty("surnam", "Liebniz"); liebniz.setProperty("birth_year", "1646"); liebniz.setProperty("type", "PERSON"); Edge liebniz_calculus = graph.addEdge(null, liebniz, calculus, "DISCOVERED"); liebniz_calculus.setProperty("year", 1674); </code></pre> <p>Adding in the books:</p> <pre><code>Vertex principia = graph.addVertex(null); principia.setProperty("title", "Philosophiæ Naturalis Principia Mathematica"); principia.setProperty("year_first_published", 1687); Edge newton_principia = graph.addEdge(null, newton, principia, "AUTHOR"); Edge principia_calculus = graph.addEdge(null, principia, calculus, "SUBJECT"); </code></pre> <p>To find out all of the books that Newton wrote on things he discovered we can construct a graph traversal. We start with Newton, follow the out links from him to things he discovered, then traverse links in reverse to get books on that subject and again go reverse on a link to get the author. If the author is Newton then go back to the book and return the result. This query is written in <a href="https://github.com/tinkerpop/gremlin" rel="noreferrer">Gremlin</a>, a Groovy based domain specific language for graph traversals:</p> <pre><code>newton.out("DISCOVERED").in("SUBJECT").as("book").in("AUTHOR").filter{it == newton}.back("book").title.unique() </code></pre> <p>Thus, I hope I've shown a little how a clever traversal can be used to avoid issues with creating intermediate nodes to represent edges. In a small database it won't matter much, but in a large database you're going to suffer large performance hits doing that.</p> <p>Yes, it is sad that you can't associate edges with other edges in a graph, but that's a limitation of the data structures of these databases. Sometimes it makes sense to make everything a node, for example, in Mediator/CVT a performance has a bit more concreteness too it. Individuals may wish address only Tom Cruise's performance in "The Last Samurai" in a review. However, for most graph databases I've found that application of some graph traversals can get me what I want out of the database.</p>
40,746,319
Error: <rect> attribute width: Expected length, "NaN". and <text> attribute dx: Expected length, "NaN"
<p>I want to implement a bar chart in D3, but my values on the dx axis are of type Date, data type which the D3 library should accept, but it seems to give me an error like this: attribute width: Expected length, "NaN". This is my code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;a bar graph&lt;/title&gt; &lt;/head&gt; &lt;style&gt; .axis path, .axis line{ fill: none; stroke: black; shape-rendering: crispEdges; } .axis text { font-family: sans-serif; font-size: 11px; } .MyRect { fill: steelblue; } .MyText { fill: white; text-anchor: middle; } &lt;/style&gt; &lt;body&gt; &lt;script src="http://d3js.org/d3.v4.min.js" charset="utf-8"&gt;&lt;/script&gt; &lt;script&gt; var width=400; var height=400; var svg=d3.select("body") .append("svg") .attr("width",width) .attr("height",height); var padding = {left:30, right:30, top:20, bottom:20}; var dataset=[10,20,30,40,33,24,12,5]; var xScale = d3.scaleBand() .domain(d3.range(dataset.length)) .range([0, width-padding.left-padding.right]); var yScale = d3.scaleLinear() .domain([0,d3.max(dataset)]) .range([height-padding.top-padding.bottom,0]); var xAxis = d3.axisBottom() .scale(xScale) var yAxis = d3.axisLeft() .scale(yScale) var rectPadding=4; var rects = svg.selectAll(".Myrect") .data(dataset) .enter() .append("rect") .attr("class","Myrect") .attr("transform","translate(" + padding.left + "," + padding.top + ")") .attr("x",function(d,i){ return xScale(i) + rectPadding/2; }) .attr("y",function(d){ return yScale(d); }) .attr("width",xScale.range()- rectPadding) .attr("height",function(d){ return height - padding.top - padding.bottom - yScale(d); }); var texts = svg.selectAll(".MyText") .data(dataset) .enter() .append("text") .attr("class","MyText") .attr("transform","translate(" + padding.left + "," + padding.top + ")") .attr("x", function(d,i){ return xScale(i) + rectPadding/2; }) .attr("y",function(d){ return yScale(d); }) .attr("dx",function(){ return (xScale.range() - rectPadding)/2; }) .attr("dy",function(d){ return 20; }) .text(function(d){ return d; }); svg.append("g") .attr("class","axis") .attr("transform","translate(" + padding.left + "," + (height - padding.bottom) + ")") .call(xAxis); svg.append("g") .attr("class","axis") .attr("transform","translate(" + padding.left + "," + padding.top + ")") .call(yAxis); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And the another error: attribute dx: Expected length, "NaN". I think it arises from band scales, but after using the introduction of the official, it still can't work. The introduction of the official:</p> <pre><code>var x = d3.scaleBand() .domain(["a", "b", "c"]) .range([0, width]); </code></pre> <p>So when I want to call the code, I think it should be used like this in my pasted code:</p> <pre><code>var texts = svg.selectAll(".MyText") .data(dataset) .enter() .append("text") .attr("class","MyText") .attr("transform","translate(" + padding.left + "," + padding.top + ")") .attr("x", function(d,i){ return xScale(i) + rectPadding/2; }) .attr("y",function(d){ return yScale(d); }) .attr("dx",function(){ return (xScale.range() - rectPadding)/2; }) .attr("dy",function(d){ return 20; }) .text(function(d){ return d; }); </code></pre> <p>But it seems to give me two errors. I'm a beginner. Thank you very much!</p>
40,746,745
2
0
null
2016-11-22 15:56:17.783 UTC
2
2021-11-09 12:05:04.94 UTC
null
null
null
null
7,188,536
null
1
16
javascript|d3.js
41,542
<p>Right now, for the width of the rectangles and the <code>dx</code> of the texts, you're using:</p> <pre><code>xScale.range() - rectPadding </code></pre> <p>But <code>xScale.range()</code> returns an array, and <code>array - number</code> will give you a <code>NaN</code>. And you're not getting anywhere with a <code>NaN</code>...</p> <p>Instead of <code>xScale.range()</code>, which will return an array, you should use:</p> <pre><code>xScale.bandwidth(); </code></pre> <p>Which not only returns a proper number, but it's also what you're looking for.</p> <p>Here is your code with that change: </p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;style&gt; .axis path, .axis line { fill: none; stroke: black; shape-rendering: crispEdges; } .axis text { font-family: sans-serif; font-size: 11px; } .MyRect { fill: steelblue; } .MyText { fill: white; text-anchor: middle; } &lt;/style&gt; &lt;body&gt; &lt;script src="https://d3js.org/d3.v4.min.js" charset="utf-8"&gt;&lt;/script&gt; &lt;script&gt; var width = 400; var height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var padding = { left: 30, right: 30, top: 20, bottom: 20 }; var dataset = [10, 20, 30, 40, 33, 24, 12, 5]; var xScale = d3.scaleBand() .domain(d3.range(dataset.length)) .range([0, width - padding.left - padding.right]); var yScale = d3.scaleLinear() .domain([0, d3.max(dataset)]) .range([height - padding.top - padding.bottom, 0]); var xAxis = d3.axisBottom() .scale(xScale) var yAxis = d3.axisLeft() .scale(yScale) var rectPadding = 4; var rects = svg.selectAll(".Myrect") .data(dataset) .enter() .append("rect") .attr("class", "Myrect") .attr("transform", "translate(" + padding.left + "," + padding.top + ")") .attr("x", function(d, i) { return xScale(i) + rectPadding / 2; }) .attr("y", function(d) { return yScale(d); }) .attr("width", xScale.bandwidth() - rectPadding) .attr("height", function(d) { return height - padding.top - padding.bottom - yScale(d); }); var texts = svg.selectAll(".MyText") .data(dataset) .enter() .append("text") .attr("class", "MyText") .attr("transform", "translate(" + padding.left + "," + padding.top + ")") .attr("x", function(d, i) { return xScale(i) + rectPadding / 2; }) .attr("y", function(d) { return yScale(d); }) .attr("dx", function() { return (xScale.bandwidth() - rectPadding) / 2; }) .attr("dy", function(d) { return 20; }) .text(function(d) { return d; }); svg.append("g") .attr("class", "axis") .attr("transform", "translate(" + padding.left + "," + (height - padding.bottom) + ")") .call(xAxis); svg.append("g") .attr("class", "axis") .attr("transform", "translate(" + padding.left + "," + padding.top + ")") .call(yAxis); &lt;/script&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <hr> <p><strong>PS:</strong> You don't need <code>rectPadding</code>. Just set the padding in the band scale:</p> <pre><code>var xScale = d3.scaleBand() .domain(d3.range(dataset.length)) .range([0, width-padding.left-padding.right]) .padding(0.2);//some value here </code></pre>
38,619,691
Referring to resources named with variables in Terraform
<p>I'm trying to create a module in Terraform that can be instantiated multiple times with different variable inputs. Within the module, how do I reference resources when their names depend on an input variable? I'm trying to do it via the bracket syntax (<code>"${aws_ecs_task_definition[var.name].arn}"</code>) but I just guessed at that.</p> <p>(Caveat: I might be going about this in completely the wrong way)</p> <p>Here's my module's (simplified) <code>main.tf</code> file:</p> <pre><code>variable "name" {} resource "aws_ecs_service" "${var.name}" { name = "${var.name}_service" cluster = "" task_definition = "${aws_ecs_task_definition[var.name].arn}" desired_count = 1 } resource "aws_ecs_task_definition" "${var.name}" { family = "ecs-family-${var.name}" container_definitions = "${template_file[var.name].rendered}" } resource "template_file" "${var.name}_task" { template = "${file("task-definition.json")}" vars { name = "${var.name}" } } </code></pre> <p>I'm getting the following error:</p> <pre><code>Error loading Terraform: Error downloading modules: module foo: Error loading .terraform/modules/af13a92c4edda294822b341862422ba5/main.tf: Error reading config for aws_ecs_service[${var.name}]: parse error: syntax error </code></pre>
38,622,882
2
0
null
2016-07-27 17:33:41.163 UTC
5
2019-01-29 22:53:01.243 UTC
null
null
null
null
53,597
null
1
28
terraform
42,745
<p>I was fundamentally misunderstanding how modules worked.</p> <p>Terraform does not support interpolation in resource names (see the <a href="https://github.com/hashicorp/terraform/issues/571" rel="noreferrer">relevant</a> <a href="https://github.com/hashicorp/terraform/issues/1976" rel="noreferrer">issues</a>), but that doesn't matter in my case, because the resources of each instance of a module are in the instance's namespace. I was worried about resource names colliding, but the module system already handles that.</p>
38,892,021
How to clear complete cache in Varnish?
<p>I'm looking for a way to clear the cache for all domains and all URLs in Varnish.</p> <p>Currently, I would need to issue individual commands for each URLs, for example:</p> <pre><code>curl -X PURGE http://example.com/url1 curl -X PURGE http://example.com/url1 curl -X PURGE http://subdomain.example.com/ curl -X PURGE http://subdomain.example.com/url1 // etc. </code></pre> <p>While I'm looking for a way to do something like</p> <pre><code>curl -X PURGE http://example.com/* </code></pre> <p>And that would clear all URLs under example.com, but also all URLs in sub-domains of example.com, basically all the URLs managed by Varnish.</p> <p>Any idea how to achieve this?</p> <p>This is my current VCL file:</p> <pre><code>vcl 4.0; backend default { .host = "127.0.0.1"; .port = "8080"; } sub vcl_recv { # Command to clear the cache # curl -X PURGE http://example.com if (req.method == "PURGE") { return (purge); } } </code></pre>
39,794,441
4
1
null
2016-08-11 09:10:28.877 UTC
4
2018-05-17 12:41:17.74 UTC
null
null
null
null
561,309
null
1
14
caching|varnish|varnish-vcl|varnish-4|clear-cache
72,199
<p>With Varnish 4.0 I ended up implementing it with the <code>ban</code> command:</p> <pre><code>sub vcl_recv { # ... # Command to clear complete cache for all URLs and all sub-domains # curl -X XCGFULLBAN http://example.com if (req.method == "XCGFULLBAN") { ban("req.http.host ~ .*"); return (synth(200, "Full cache cleared")); } # ... } </code></pre>
53,416,685
Docker-compose tagging and pushing
<p>I have a few docker containers that I try to sync with <code>docker-compose</code> (currently are being run by bash scripts). I'm looking for a way to tag and push them to our ec2 based dockerhub (private server).</p> <p>Using simply <code>docker</code> we did something like this (for each container):</p> <pre><code>$ docker build -f someDockerfile -t some $ docker tag some &lt;docker_hub_server&gt;/some $ docker push &lt;docker_hub_server&gt;/some </code></pre> <p>I'm trying to replicate this in <code>docker-compose</code>. I tried a few things but this one seems close to working (but didn't work of course):</p> <blockquote> <p>docker-compose.yml:</p> </blockquote> <pre><code>version: '3' services: some: container_name:some image: some:&lt;docker_hub_server&gt;/some </code></pre> <p>But when i run:</p> <pre><code>$ docker-compose push </code></pre> <p>I get: </p> <pre><code>Pushing some (base:&lt;docker_hub_server&gt;/base:latest)... ERROR: invalid reference format </code></pre> <p>Any ideas on how I can tag and push my containers?</p> <p>p.s.: I know that this is not the way <code>docker-compose</code> is meant to be used, but I also know it's possible and it fits my needs.</p>
53,418,591
2
0
null
2018-11-21 16:36:48.56 UTC
8
2022-01-17 21:12:33.693 UTC
2018-11-23 06:20:46.463 UTC
null
9,164,010
null
7,217,896
null
1
22
docker|docker-compose
38,779
<p>I have tested this approach with Docker Hub, so you should be able to achieve what you want with the following configuration and shell session:</p> <blockquote> <p>docker-compose.yml</p> </blockquote> <pre><code>version: '3' services: build-1: build: context: ./build-1 image: user/project-1 build-2: build: context: ./build-2 image: user/project-2 </code></pre> <p>(Here, you should replace <code>user/project-1</code> with <code>registry.name/user/project-1</code> if you are not using Docker Hub but another Docker registry, e.g., <code>quay.io/user/project-1</code>.)</p> <p>The various fields involved here (<code>build:</code>, <code>context:</code>, etc.) are described in <a href="https://docs.docker.com/compose/compose-file/" rel="noreferrer">this page of the docker-compose documentation</a>.</p> <p>The <code>docker-compose.yml</code> file above assume you have the following tree (including a <a href="https://git-scm.com/docs/gitignore" rel="noreferrer">.gitignore</a> and some <a href="https://docs.docker.com/engine/reference/builder/#dockerignore-file" rel="noreferrer">.dockerignore</a> files, to comply with best practices):</p> <pre><code>. ├── build-1 │   ├── Dockerfile │   └── .dockerignore ├── build-2 │   ├── Dockerfile │   └── .dockerignore ├── docker-compose.yml └── .gitignore </code></pre> <p>Then do in a terminal:</p> <pre><code>$ docker login # → append the domain name of your Docker registry # if you are not using Docker Hub; for example: # docker login quay.io $ docker-compose build --pull $ docker-compose push # and optionally: $ docker logout </code></pre> <p>Finally, below are some remarks to clarify a few details related to your question:</p> <ul> <li><p>In your example session</p> <pre><code>$ docker build -f someDockerfile -t some . # with "." as context build path $ docker tag some …/some $ docker push …/some </code></pre> <p><code>some</code> is a temporary image name (not a container) so it seems unnecessary: you could just as well have run the following, with the same outcome.</p> <pre><code>$ docker build -f someDockerfile -t …/some . $ docker push …/some </code></pre></li> <li><p>Your <code>docker-compose.yml</code> example contained the line:</p> <pre><code>image: some:&lt;docker_hub_server&gt;/some </code></pre> <p>Actually, the image tags can contain <code>:</code> to specify a version, but not in this way (it should be a suffix). For example, you could tag an image <code>user/some:1.0</code> or <code>user/some:latest</code>, and by convention this latter example <code>user/some:latest</code> admits <code>user/some</code> as a shorter, equivalent name.</p></li> <li><p>Note that the full syntax for image tags is</p> <pre><code>registry.name:port/user/project:version </code></pre> <p>where <code>registry.name</code> should be the domain name or hostname of the desired Docker registry (if omitted, it will default to Docker Hub).</p> <p>This is mentioned in <a href="https://docs.docker.com/engine/reference/commandline/tag/#tag-an-image-referenced-by-name-and-tag" rel="noreferrer">that page of the official documentation</a>.</p> <p>So for example, if you use the Quay Docker registry, the image tag could be <code>quay.io/user/some:latest</code> or more succinctly <code>quay.io/user/some</code>.</p></li> </ul>
50,021,282
Python Argparse - How can I add text to the default help message?
<p>I'm using python's argparse to handle parsing of arguments. I get a default help message structured like so:</p> <pre><code>usage: ProgramName [-h] ... Description positional arguments: ... optional arguments: -h, --help show this help message and exit ... </code></pre> <p>What I want is to add an entire new section to this message, for example:</p> <pre><code>usage: ProgramName [-h] ... Description positional arguments: ... optional arguments: -h, --help show this help message and exit ... additional information: This will show additional information relevant to the user. .... </code></pre> <p>Is there a way to achieve this behavior? A solution that is supported by both python 2.7 and 3.x is preferred.</p> <p>Edit: I would also rather have a solution that will add the new section / sections at the bottom of the help message.</p>
50,021,771
2
0
null
2018-04-25 11:35:49.083 UTC
6
2021-12-03 15:33:36.173 UTC
2021-12-03 15:33:36.173 UTC
null
8,075,540
null
3,531,416
null
1
36
python|argparse
17,893
<p>You can quite do it using <a href="https://docs.python.org/3/library/argparse.html#epilog" rel="noreferrer">epilog</a>. Here is an example below:</p> <pre><code>import argparse import textwrap parser = argparse.ArgumentParser( prog='ProgramName', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''\ additional information: I have indented it exactly the way I want it ''')) parser.add_argument('--foo', nargs='?', help='foo help') parser.add_argument('bar', nargs='+', help='bar help') parser.print_help() </code></pre> <p>Result : </p> <pre><code>usage: ProgramName [-h] [--foo [FOO]] bar [bar ...] positional arguments: bar bar help optional arguments: -h, --help show this help message and exit --foo [FOO] foo help additional information: I have indented it exactly the way I want it </code></pre>
36,683,951
Generate random number with jinja2
<p>I need to generate a random number between 1 and 50. Aparently the random filter needs a <a href="http://jinja.pocoo.org/docs/dev/templates/#random" rel="noreferrer">sequence</a>. How can I create a list with numbers from 1 to 50 in Jinja? </p> <pre><code>{{ [1,n,50]|random() }} </code></pre>
36,683,970
2
0
null
2016-04-18 01:04:01.69 UTC
2
2022-09-14 21:08:05.637 UTC
null
null
null
null
2,990,084
null
1
28
python-2.7|flask|jinja2
27,450
<p>Jinja2 also includes the <a href="https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-globals.range" rel="nofollow noreferrer"><code>range</code></a> function which returns a sequence of numbers from <code>start</code> to <code>end - 1</code>, so you can use it with <a href="https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.random" rel="nofollow noreferrer"><code>random</code></a>:</p> <pre><code>Your lucky number is: {{ range(1, 51) | random }} </code></pre>
28,236,840
Detect when slick slider initialises
<p>I'm trying to fire some code when <a href="http://kenwheeler.github.io/slick/" rel="noreferrer">slick</a> initializes. Apparently in the newest version 1.4 "callback methods have been deprecated and replaced with events."</p> <p>This doesn't work for me though:</p> <pre><code>$('.spv-slider').on('init', function(event, slick){ console.log("initialised") }); </code></pre> <p>what's wrong with it?</p>
29,143,460
1
0
null
2015-01-30 13:19:05.29 UTC
3
2016-06-02 06:00:25.923 UTC
2016-06-02 06:00:25.923 UTC
null
2,333,214
null
1,937,021
null
1
20
jquery|slick.js
83,509
<p>I'm not sure at which point you tried to initialize slickslider, but you have to do it <strong>after</strong> binding the <code>init</code> event.</p> <p>So write your piece of code as you did and after that initialize the slider:</p> <pre><code>$('.spv-slider').on('init', function(event, slick){ console.log("initialized") }); </code></pre> <p>And then:</p> <pre><code>$('.spv-slider').slick(); </code></pre>
20,978,946
Facebook React.js: how do you render stateful components on the server?
<p>I think I'm conceptually missing something with server-side rendering using React.js</p> <p>Assume I want to create a page to display items from a server-side DB, with an input field to filter them. </p> <p>I want a page:</p> <ul> <li>that responds to a URL like <code>/items?name=foobar</code></li> <li>with a React input field to filter the items by name</li> <li>with a React component to display the list of filtered items</li> </ul> <p>Assume I have a public REST API to query the items on the client side.</p> <p>Conceptually, what I want to do at first request (<code>GET /items?name=foobar</code>) is : </p> <ul> <li>I want my input field to show what the user passed as a Parameter, so I need to pass the query parameter ('foobar') to the react component, as a 'prop' (like <code>initialName</code>)</li> </ul> <p>So I tried this: </p> <pre><code> // A stateful component, maintaining the value of a query field var ItemForm = React.createClass({ getInitialState : function () { return { name : this.props.initialName }; }, handleInputValueChanged : function() { var enteredName = this.refs.query.getDOMNode().value.trim(); this.props.onNameChanged(enteredName); }, render : function () { return React.DOM.form({ children : [ React.DOM.label({ children : "System name" }), React.DOM.input({ ref : "query", value : this.state.name, onChange : this.handleInputValueChanged }) ] }); } }); </code></pre> <ul> <li>I also have to do my database query <em>on the server</em> to get a list of items, and pass this list of items as a 'prop' of the ItemList (like 'initialItems')</li> </ul> <p>As I understand it, I need a simple component to display the list, receiving it as a 'prop': </p> <pre><code> // A stateless component, displaying a list of item var ItemList = return React.createClass({ propTypes : { items : React.PropTypes.array }, render : function () { return React.DOM.ul({ children : _.map(this.props.items, function (item) { return React.DOM.li({ children : [ React.DOM.span({ children : ["Name : ", item.name].join(" ") })] }); }) }); } }); </code></pre> <ul> <li>Now, I need a component do display the whole Page ; this component will have to maintain the state of the whole page, that is, look at the name entered in the field, and make API queries to update the list items. However I don't understand how this component can have an 'initialState' that would work both on the server-side and for later rendering on the client side. </li> </ul> <p>I tried this: </p> <pre><code> // A stateful react component, maintaining the list of items var ItemPage = React.createClass({ getInitialState : function () { // ????? // This is where I'm sure the problem lies. // How can this be known both on server and client side ? return { items : this.props.initialItems || [] }; }, queryItems : function (enteredName) { var self = this; // The field was emptied, we must clear everything if (!enteredName) { this.setState({ items : [] }); } else { // The field was changed, we want to do a query // then change the state to trigger a UI update. // The query code is irrelevant, I think. doQuery(enteredName).then(function (items) { self.setState({ items : items }); }); } }, render : function () { // I don't want to display the same view // if there is no results. // This uses a 'state' property of the page var results = null; if (_.isEmpty(this.state.items)) { results = React.DOM.div({ ref : "results", children : "No results" }); } else { results = ItemListView({ // Here items is a 'prop', the ItemList is technically // stateless items : this.state.items }); } return React.DOM.div({ children : [ ItemForm({ initialName : this.props.initialName, onNameChanged : this.queryItems }), results ] }); } }); </code></pre> <p>That's where I'm stuck. I can render things on the server side using something like:</p> <pre><code>var name = // The name from the query parameters var items = doQueryOnServerSide(name); React.renderComponentAsString(ItemPage({ initialName : name, initialItems : items }); </code></pre> <p>But when I try to do write the client side javascript, what should I do ? I know where I want my dom to be rendered, but what initial props should I pass to the react component? </p> <pre><code>React.renderComponent(ItemPage({ initialName : ??? // Read the name parameter from URL ? initialItems : ??? // I don't know yet, and I don't want to make an API call until the user entered something in the input box }); </code></pre> <p>Most attempts I have tried ends up with the DOM being 'erased' on the client-side, with this message:</p> <blockquote> <p>React attempted to use reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server.</p> </blockquote> <p>Note that only the markup of my ItemList component is erased, so I suppose it's an implementation problem of my component, but I don't really know where to start.</p> <p>Am I on the right track? Or do I miss something entirely? </p>
20,982,615
1
0
null
2014-01-07 18:21:06.753 UTC
18
2019-06-25 15:08:22.2 UTC
2019-06-25 15:08:22.2 UTC
null
1,033,581
null
77,804
null
1
29
reactjs|isomorphic-javascript
12,622
<p>When using server rendering, you should always pass down the same props that you used to render the component on the server. In this case, you need to pass down the same initialItems prop in order for <code>React.renderComponent</code> to pick up the server-rendered markup (by simply JSONifying the props and putting it in the call to <code>renderComponent</code>).</p> <p>Your general structure of reading from initialItems when specified makes sense to me. Doing so allows you to either make a component with preloaded data or one that has none. What you need to set the initial state to depends on what you want to show in cases where you're rendering a brand-new component from scratch. (If you're always picking up server-rendered markup then you can simply always pass the <code>initialName</code> and <code>initialItems</code> props.)</p> <p>Hope that makes sense.</p>
21,331,664
How to show tab close button in GVIM?
<p>Please let me know how to show the close button on each tab page in GVIM.</p> <p>Also, is it possible to set a warning if I am closing GVIM with multiple tab pages open?</p>
21,332,263
3
0
null
2014-01-24 11:35:59.38 UTC
19
2017-03-30 19:16:45.07 UTC
2017-03-30 19:16:45.07 UTC
null
327,074
null
3,146,151
null
1
12
button|vim|tabs|warnings|tabpage
13,679
<h3>Showing the close button</h3> <p>The <code>'tabline'</code> option can include a <code>%X</code> marker for the close tab button, but that only works for the console version of the tab line. <code>:help 'guitablabel'</code> explicitly states:</p> <blockquote> <p>Note that syntax highlighting is not used for the option. The %T and %X items are also ignored.</p> </blockquote> <p>So, to literally get what you want, you'd have to switch to the (uglier) text-based tab line with</p> <pre><code>:set guioptions-=e </code></pre> <p>But note that using the mouse (even though you may be customized to that by other applications like web browser tabs) is discouraged in Vim. If you right mouse button-click on a GUI tab label, you can alternatively also choose <code>|Close tab|</code> from the popup menu.</p> <h3>Preventing tab close</h3> <p><sup>(Note that asking multiple questions is frowned upon here; please ask them separately.)</sup></p> <p>I don't think this is possible; there is a <code>VimLeavePre</code> event that you could hook into, but it cannot prevent the closing of Vim; the action (e.g. <code>:qall!</code>) cannot be undone. If you are used to closing Vim always via a mapping or command, you could overwrite that and include a check in there (using <code>tabpagenr('$') &gt; 1</code>).</p> <p>If you're concerned with losing your window / tab layout, rather have a look at <em>Vim sessions</em> (which can be persisted automatically in the background). This will allow to re-launch Vim with the previously opened windows.</p>
47,698,037
How can I set a height to a Dialog in Material-UI?
<p>I'm going with the Material-UI example for a <code>Dialog</code> with a custom width:</p> <pre><code>const customContentStyle = { width: '100%', maxWidth: 'none', }; // some omitted code &lt;Dialog title=&quot;Dialog With Custom Width&quot; actions={actions} modal={true} contentStyle={customContentStyle} open={this.state.open} &gt; This dialog spans the entire width of the screen. &lt;/Dialog&gt; </code></pre> <p>I know that I'm able to set a custom width because I've overridden the <code>maxWidth</code>, however I want to be able to do the same with the height so that I can resize the height of the dialog. I've tried setting the <code>maxHeight</code> to <code>none</code> and setting <code>height</code>, but I've had no luck with it.</p>
47,763,027
5
0
null
2017-12-07 15:08:40.507 UTC
8
2022-05-17 21:16:11.87 UTC
2021-09-18 04:46:09.643 UTC
null
9,449,426
null
5,570,050
null
1
47
reactjs|material-ui
61,317
<p>You need to <a href="https://material-ui-next.com/customization/overrides/#overriding-with-classes" rel="nofollow noreferrer">override some of the default behavior</a> of the <a href="https://material-ui-next.com/api/dialog/" rel="nofollow noreferrer">Dialog</a>. Its <code>paper</code> class implements a flexbox with a columnar flex-direction and defines a max-height of <code>90vh</code>. This allows the Dialog to grow to its content and present scrollbars once it reaches 90% of the viewport's visible height.</p> <p>If you need to set the Dialog height to some percentage of the viewport, override the <code>paper</code> class, defining <code>min-height</code> and <code>max-height</code> in a manner similar to the example below:</p> <pre class="lang-js prettyprint-override"><code>import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Dialog from 'material-ui/Dialog'; const styles = { dialogPaper: { minHeight: '80vh', maxHeight: '80vh', }, }; const YourDialog = ({ classes }) =&gt; ( &lt;Dialog classes={{ paper: classes.dialogPaper }}&gt; &lt;div&gt;dialogishness&lt;/div&gt; &lt;/Dialog&gt; ); export default withStyles(styles)(YourDialog); </code></pre> <p>This will ensure that the Dialog's height is 80% of the viewport.</p>
47,076,373
How to design a Cloud Firestore database schema
<p>Migrating from realtime database to cloud firestore needs a total redesign of the database. For this I created an example with some main design decisions. See picture and the database design in the spreadsheet below. My two questions are:</p> <p>1 - when I have a one to many relation is it also an option to store information as an array within the document? See line 8 in database design.</p> <p>2 - Should I include only a reference, or duplicate all information in the one to many relation. See line 38 in the database model.</p> <p><a href="https://i.stack.imgur.com/ITbw4.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ITbw4.jpg" alt="enter image description here"></a></p> <p><a href="https://docs.google.com/spreadsheets/d/13KtzSwR67-6TQ3V9X73HGsI2EQDG9FA8WMN9CCHKq48/edit?usp=sharing" rel="noreferrer">https://docs.google.com/spreadsheets/d/13KtzSwR67-6TQ3V9X73HGsI2EQDG9FA8WMN9CCHKq48/edit?usp=sharing</a></p>
47,077,449
2
0
null
2017-11-02 13:20:01.573 UTC
12
2019-03-14 01:48:10.16 UTC
2017-11-02 13:34:38.487 UTC
null
6,558,256
null
6,558,256
null
1
20
firebase|google-cloud-firestore
16,931
<p>For Question 1 there's a solution in the firestore docs: <a href="https://cloud.google.com/firestore/docs/solutions/arrays" rel="noreferrer">https://cloud.google.com/firestore/docs/solutions/arrays</a></p> <p>instead of using an array you use a map of values and set them to 'true' which allows you to query for them, like so:</p> <pre><code>teachers: { "teacherid1": true, "teacherid2": true, "teacherid3": true } </code></pre> <p>And for Question 2, you just need to save the teacher-ids because if you have those you can easily query for the corresponding data.</p>
24,616,108
Web API and OData- Pass Multiple Parameters
<p>Is it possible to get OData to do the following? I would like to be able to query a REST call by passing on parameters that may not be the primary key. Can I call a REST method like --&gt; <code>GetReports(22, 2014)</code> or <code>Reports(22, 2014)</code>?</p> <pre class="lang-cs prettyprint-override"><code>[HttpGet] [ODataRoute(&quot;Reports(Id={Id}, Year={Year})&quot;)] public IHttpActionResult GetReports([FromODataUri]int Id, [FromODataUri]int Year) { return Ok(_reportsRepository.GetReports(Id, Year)); } </code></pre> <p><strong>Here is my latest change.</strong></p> <pre class="lang-cs prettyprint-override"><code>//Unbound Action OData v3 var action = builder.Action(&quot;ListReports&quot;); action.Parameter&lt;int&gt;(&quot;key&quot;); action.Parameter&lt;int&gt;(&quot;year&quot;); action.ReturnsCollectionFromEntitySet&lt;Report&gt;(&quot;Reports&quot;); </code></pre> <p><strong>my method for controller ReportsController</strong></p> <pre class="lang-cs prettyprint-override"><code>[HttpPost] [EnableQuery] public IHttpActionResult ListReports([FromODataUri] int key, ODataActionParameters parameters) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } int year = (int)parameters[&quot;year&quot;]; return Ok(_reportsRepository.GetReports(key, year).Single()); } </code></pre> <p><strong>I tried calling the url like:</strong></p> <pre><code>http://localhost:6064/odata/Reports(key=5,year=2014)/ListReports </code></pre> <p>No HTTP resource was found that matches the request URI '<code>http://localhost:6064/odata/Reports(key%3D5%2Cyear%3D2014)/ListReports'</code>.`</p>
24,648,416
2
0
null
2014-07-07 17:12:06.423 UTC
5
2022-09-05 12:47:24.853 UTC
2022-09-05 12:47:24.853 UTC
null
14,353,529
null
715,447
null
1
19
c#|odata|asp.net-web-api2
43,063
<p>You can define a function import named GetReports that has two parameters.</p> <p><em>(Note: the name of the function import can't be the same with entity set name)</em></p> <p>Configure your EDM model as:</p> <pre><code>var builder = new ODataConventionModelBuilder(); builder.EntitySet&lt;Report&gt;("Reports"); var function = builder.Function("GetReports"); function.Parameter&lt;int&gt;("Id"); function.Parameter&lt;int&gt;("Year"); function.ReturnsCollectionFromEntitySet&lt;Report&gt;("Reports"); var model = builder.GetEdmModel(); </code></pre> <p>And then write your method as:</p> <pre><code>[HttpGet] [ODataRoute("GetReports(Id={Id},Year={Year})")] public IHttpActionResult WhateverName([FromODataUri]int Id, [FromODataUri]int Year) { return Ok(_reportsRepository.GetReports(Id, Year)); } </code></pre> <p>Then the request</p> <pre><code>Get ~/GetReports(Id=22,Year=2014) </code></pre> <p>will work.</p>
53,335,567
Use pandas.shift() within a group
<p>I have a dataframe with panel data, let's say it's time series for 100 different objects:</p> <pre><code>object period value 1 1 24 1 2 67 ... 1 1000 56 2 1 59 2 2 46 ... 2 1000 64 3 1 54 ... 100 1 451 100 2 153 ... 100 1000 21 </code></pre> <p>I want to add a new column <code>prev_value</code> that will store previous <code>value</code> for each object:</p> <pre><code>object period value prev_value 1 1 24 nan 1 2 67 24 ... 1 99 445 1243 1 1000 56 445 2 1 59 nan 2 2 46 59 ... 2 1000 64 784 3 1 54 nan ... 100 1 451 nan 100 2 153 451 ... 100 1000 21 1121 </code></pre> <p>Can I use .shift() and .groupby() somehow to do that?</p>
53,335,744
2
0
null
2018-11-16 10:08:14.303 UTC
10
2021-02-24 10:09:24.147 UTC
null
null
null
null
9,629,391
null
1
56
python|pandas|pandas-groupby
54,033
<p>Pandas' grouped objects have a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.shift.html" rel="noreferrer"><code>groupby.DataFrameGroupBy.shift</code></a> method, which will shift a specified column in each group <em>n</em> <code>periods</code>, just like the regular dataframe's <code>shift</code> method:</p> <pre><code>df['prev_value'] = df.groupby('object')['value'].shift() </code></pre> <p>For the following example dataframe:</p> <pre><code>print(df) object period value 0 1 1 24 1 1 2 67 2 1 4 89 3 2 4 5 4 2 23 23 </code></pre> <p>The result would be:</p> <pre><code> object period value prev_value 0 1 1 24 NaN 1 1 2 67 24.0 2 1 4 89 67.0 3 2 4 5 NaN 4 2 23 23 5.0 </code></pre>
35,652,665
java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7
<p>I'm not able to run a simple <code>spark</code> job in <code>Scala IDE</code> (Maven spark project) installed on <code>Windows 7</code></p> <p>Spark core dependency has been added.</p> <pre><code>val conf = new SparkConf().setAppName("DemoDF").setMaster("local") val sc = new SparkContext(conf) val logData = sc.textFile("File.txt") logData.count() </code></pre> <p>Error: </p> <pre><code>16/02/26 18:29:33 INFO SparkContext: Created broadcast 0 from textFile at FrameDemo.scala:13 16/02/26 18:29:34 ERROR Shell: Failed to locate the winutils binary in the hadoop binary path java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. at org.apache.hadoop.util.Shell.getQualifiedBinPath(Shell.java:278) at org.apache.hadoop.util.Shell.getWinUtilsPath(Shell.java:300) at org.apache.hadoop.util.Shell.&lt;clinit&gt;(Shell.java:293) at org.apache.hadoop.util.StringUtils.&lt;clinit&gt;(StringUtils.java:76) at org.apache.hadoop.mapred.FileInputFormat.setInputPaths(FileInputFormat.java:362) at &lt;br&gt;org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015) at org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015) at &lt;br&gt;org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176) at &lt;br&gt;org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176)&lt;br&gt; at scala.Option.map(Option.scala:145)&lt;br&gt; at org.apache.spark.rdd.HadoopRDD.getJobConf(HadoopRDD.scala:176)&lt;br&gt; at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:195)&lt;br&gt; at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)&lt;br&gt; at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)&lt;br&gt; at scala.Option.getOrElse(Option.scala:120)&lt;br&gt; at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)&lt;br&gt; at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)&lt;br&gt; at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239)&lt;br&gt; at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237)&lt;br&gt; at scala.Option.getOrElse(Option.scala:120)&lt;br&gt; at org.apache.spark.rdd.RDD.partitions(RDD.scala:237)&lt;br&gt; at org.apache.spark.SparkContext.runJob(SparkContext.scala:1929)&lt;br&gt; at org.apache.spark.rdd.RDD.count(RDD.scala:1143)&lt;br&gt; at com.org.SparkDF.FrameDemo$.main(FrameDemo.scala:14)&lt;br&gt; at com.org.SparkDF.FrameDemo.main(FrameDemo.scala)&lt;br&gt; </code></pre>
35,652,866
13
0
null
2016-02-26 13:12:01.55 UTC
31
2022-02-09 05:47:14.857 UTC
2017-01-30 20:56:19.43 UTC
null
147,511
null
3,985,845
null
1
111
eclipse|scala|apache-spark
153,629
<p><a href="http://teknosrc.com/spark-error-java-io-ioexception-could-not-locate-executable-null-bin-winutils-exe-hadoop-binaries/" rel="nofollow noreferrer">Here</a> is a good explanation of your problem with the solution.</p> <ol> <li><p>Download the version of winutils.exe from <a href="http://public-repo-1.hortonworks.com/hdp-win-alpha/winutils.exe" rel="nofollow noreferrer">https://github.com/steveloughran/winutils</a>.</p> </li> <li><p>Set up your <code>HADOOP_HOME</code> environment variable on the OS level or programmatically:</p> <p><code>System.setProperty(&quot;hadoop.home.dir&quot;, &quot;full path to the folder with winutils&quot;);</code></p> </li> <li><p>Enjoy</p> </li> </ol>
23,454,975
How to convert hours and minutes to minutes with moment.js?
<p>I need to convert hours and minutes in minutes values. With pure JavaScript Date object I do the following:</p> <pre><code>var d = new Date(); var minutes = d.getHours() * 60 + d.getMinutes(); </code></pre> <p>I've just switched to <a href="http://momentjs.com/">moment.js</a> and looking for better solution likes the following:</p> <pre><code>var minutes = moment(new Date()).toMinutes() </code></pre> <p>Is there is something like this?</p>
23,455,023
6
0
null
2014-05-04 10:10:13.327 UTC
4
2021-11-06 14:16:06.693 UTC
null
null
null
null
1,006,884
null
1
22
javascript|date|momentjs
74,851
<p>I think your best bet is to create a <code>Duration</code> and then get the minutes using <code>asMinutes</code>. This is probably clearer when describing an interval of time.</p> <pre><code>moment.duration().asMinutes() </code></pre> <p><a href="http://momentjs.com/docs/#/durations/minutes/" rel="noreferrer">Here is the reference</a> in the docs.</p>
43,186,315
Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists
<p>I was following the tutorial on <strong>o7planning</strong> and got stuck at step 6:</p> <p><a href="http://o7planning.org/en/10169/java-servlet-tutorial" rel="noreferrer">http://o7planning.org/en/10169/java-servlet-tutorial</a></p> <p>It's just a simple project that show <em>HelloWorld</em> but for some reason I keep getting <code>404</code> error. Detail:</p> <p><a href="https://i.stack.imgur.com/ASMwv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ASMwv.png" alt="enter image description here" /></a> However the Tomcat welcome page showing properly.</p> <p><a href="https://i.stack.imgur.com/ybGTj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ybGTj.png" alt="Tomcat welcome page" /></a></p> <p>Here solutions that I've tried so far (and they are NOT working):</p> <blockquote> <p>Right-click project -&gt; properties -&gt; Project Facets -&gt; Runtimes -&gt; checked &quot;Apache Tomcat v9.0&quot; -&gt; Apply -&gt; finish.</p> <p>Server tab -&gt; Right-click &quot;Tomcat v9.0...&quot; -&gt; properties -&gt; switch location -&gt; Choose &quot;Use tomcat installation&quot; on &quot;Server locations&quot; panel.</p> </blockquote>
43,186,803
2
0
null
2017-04-03 13:45:07.753 UTC
20
2019-11-13 21:16:10.17 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
7,090,655
null
1
78
java|tomcat|http-status-code-404
944,668
<p>Problem solved, I've not added the <strong>index.html</strong>. Which is point out in the <strong>web.xml</strong></p> <p><a href="https://i.stack.imgur.com/8OoEx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8OoEx.png" alt="enter image description here"></a></p> <p><strong>Note:</strong> a project may have more than one <strong>web.xml</strong> file.</p> <p>if there are another <strong>web.xml</strong> in </p> <blockquote> <p>src/main/webapp/WEB-INF</p> </blockquote> <p>Then you might need to add another index (this time <strong>index.jsp</strong>) to </p> <blockquote> <p>src/main/webapp/WEB-INF/pages/</p> </blockquote>
51,998,995
Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function 'createDataList':.)
<p>I tried to fetch data from the internet with moviedb API, I followed the tutorial at <a href="https://flutter.io/cookbook/networking/fetch-data/" rel="noreferrer">https://flutter.io/cookbook/networking/fetch-data/</a></p> <p>but I'm getting the below error. </p> <blockquote> <p>Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function 'createDataList':.)</p> </blockquote> <p>This my code </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-html lang-html prettyprint-override"><code>Future&lt;List&lt;DataModel&gt;&gt; fetchData() async{ final response = await http.get("https://api.themoviedb.org/3/movie/now_playing?api_key=d81172160acd9daaf6e477f2b306e423&amp;language=en-US"); if(response.statusCode == 200){ return compute(createDataList,response.body.toString()); } } List&lt;DataModel&gt; createDataList(String responFroJson) { final parse = json.decode(responFroJson).cast&lt;Map&lt;String, dynamic&gt;&gt;(); return parse.map&lt;DataModel&gt; ((json) =&gt; DataModel.fromtJson(json)).toList(); }</code></pre> </div> </div> </p> <p>Screenshot of the error message <a href="https://i.stack.imgur.com/0tKHB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0tKHB.png" alt="enter image description here"></a></p>
51,999,033
2
0
null
2018-08-24 06:55:04.737 UTC
6
2021-12-31 21:45:13.5 UTC
2018-08-24 08:44:58.287 UTC
null
3,187,077
null
10,268,205
null
1
48
flutter
21,596
<p><code>compute</code> can only take a top-level function, but not instance or static methods.</p> <p>Top-level functions are functions declared not inside a class and not inside another function</p> <pre><code>List&lt;DataModel&gt; createDataList(String responFroJson) { ... } class SomeClass { ... } </code></pre> <p>should fix it.</p> <p><a href="https://docs.flutter.io/flutter/foundation/compute.html" rel="noreferrer">https://docs.flutter.io/flutter/foundation/compute.html</a></p> <blockquote> <p>R is the type of the value returned. The callback argument must be a top-level function, not a closure or an instance or static method of a class.</p> </blockquote>
694,344
Regular expression that matches between quotes, containing escaped quotes
<p><em>This was originally a question I wanted to ask, but while researching the details for the question I found the solution and thought it may be of interest to others.</em></p> <p>In Apache, the full request is in double quotes and any quotes inside are always escaped with a backslash:</p> <pre><code>1.2.3.4 - - [15/Apr/2005:20:35:37 +0200] "GET /\" foo=bat\" HTTP/1.0" 400 299 "-" "-" "-" </code></pre> <p>I'm trying to construct a regex which matches all distinct fields. My current solution always stops on the first quote after the <code>GET</code>/<code>POST</code> (actually I only need all the values including the size transferred):</p> <pre><code>^(\d+\.\d+\.\d+\.\d+)\s+[^\s]+\s+[^\s]+\s+\[(\d+)/([A-Za-z]+)/(\d+):(\d+):(\d+):(\d+)\s+\+\d+\]\s+"[^"]+"\s+(\d+)\s+(\d+|-) </code></pre> <p>I guess I'll also provide my solution from my PHP source with comments and better formatting:</p> <pre><code>$sPattern = ';^' . # ip address: 1 '(\d+\.\d+\.\d+\.\d+)' . # ident and user id '\s+[^\s]+\s+[^\s]+\s+' . # 2 day/3 month/4 year:5 hh:6 mm:7 ss +timezone '\[(\d+)/([A-Za-z]+)/(\d+):(\d+):(\d+):(\d+)\s+\+\d+\]' . # whitespace '\s+' . # request uri '"[^"]+"' . # whitespace '\s+' . # 8 status code '(\d+)' . # whitespace '\s+' . # 9 bytes sent '(\d+|-)' . # end of regex ';'; </code></pre> <p>Using this with a simple case where the URL doesn't contain other quotes works fine:</p> <pre><code>1.2.3.4 - - [15/Apr/2005:20:35:37 +0200] "GET /\ foo=bat\ HTTP/1.0" 400 299 "-" "-" "-" </code></pre> <p>Now I'm trying to get support for none, one or more occurrences of <code>\"</code> into it, but can't find a solution. Using regexpal.com I've came up with this so far:</p> <pre><code>^(\d+\.\d+\.\d+\.\d+)\s+[^\s]+\s+[^\s]+\s+\[(\d+)/([A-Za-z]+)/(\d+):(\d+):(\d+):(\d+)\s+\+\d+\]\s+"(.|\\(?="))*" </code></pre> <p>Here's only the changed part:</p> <pre><code> # request uri '"(.|\\(?="))*"' . </code></pre> <p>However, it's too greedy. It eats everything until the last <code>"</code>, when it should only eat until the first <code>"</code> not preceded by a <code>\</code>. I also tried introducing the requirement that there's no <code>\</code> before the <code>"</code> I want, but it still eats to the end of the string (Note: I had to add extraneous <code>\</code> characters to make this work in PHP):</p> <pre><code> # request uri '"(.|\\(?="))*[^\\\\]"' . </code></pre> <p>But then it hit me: <strong>*<code>?</code></strong>: If used immediately after any of the quantifiers <em>, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times)</em></p> <pre><code> # request uri '"(.|\\(?="))*?[^\\\\]"' . </code></pre> <p>The full regex:</p> <pre><code>^(\d+\.\d+\.\d+\.\d+)\s+[^\s]+\s+[^\s]+\s+\[(\d+)/([A-Za-z]+)/(\d+):(\d+):(\d+):(\d+)\s+\+\d+\]\s+"(.|\\(?="))*?[^\\]"\s+(\d+)\s+(\d+|-) </code></pre> <p><strong>Update 5th May 2009:</strong></p> <p>I discovered a small flaw in the regexp due parsing millions of lines: it breaks on lines which contain the backslash character right before the double quote. In other words:</p> <pre><code>...\\" </code></pre> <p>will break the regex. Apache will not log <code>...\"</code> but will always escape the backslash to <code>\\</code>, so it's safe to assume that when there're two backslash characters before the double quote.</p> <p>Anyone has an idea how to fix this with the the regex?</p> <p>Helpful resources: <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Global_Objects:RegExp#Special_characters_in_regular_expressions" rel="noreferrer">the JavaScript Regexp documentation at developer.mozilla.org</a> and <a href="http://regexpal.com/" rel="noreferrer">regexpal.com</a></p>
694,356
1
0
2009-03-29 08:59:41.65 UTC
2009-03-29 08:59:41.667 UTC
9
2009-05-12 07:03:28 UTC
2009-05-12 07:03:28 UTC
mfn
47,573
mfn
47,573
null
1
10
regex|pcre
25,302
<p>Try this:</p> <pre><code>"(?:[^\\"]+|\\.)*" </code></pre> <p>This regular expression matches a double quote character followed by a sequence of either any character other than <code>\</code> and <code>"</code> or an escaped sequence <code>\</code><em><code>α</code></em> (where <em><code>α</code></em> can be any character) followed by the final double quote character. The <code>(?:</code><em><code>expr</code></em><code>)</code> syntax is just a non-capturing group.</p>
2,363,777
iPhone: How to Pass Data Between Several Viewcontrollers in a Tabbar App
<p>I have following problem:</p> <p>I have built a tabbar application with 4 tabs. I want to pass a object/variable from the first tab controller to the third one and initialize this controller with the corresponding object. </p> <p>I've already done some research. The best way, corresponding to a clean model approach, would be to call some initWithObject: method on the called viewcontroller. How can I achieve this? How can I call the <code>init</code> method of the receivercontroller within the callercontroller? Can you give me some code example?</p> <p>Edit: To pass data between several views/classes etc simply create some Kind of data class which holds the data beeing shared between several classes. For more information follow the link: <a href="http://www.drobnik.com/touch/2009/05/the-death-of-global-variables/" rel="noreferrer">Singleton</a></p>
2,364,524
3
0
null
2010-03-02 14:30:08.733 UTC
12
2015-06-18 15:41:44.177 UTC
2013-07-19 15:29:56.387 UTC
null
426,671
null
284,444
null
1
20
iphone|objective-c|uiviewcontroller|uitabbarcontroller
26,043
<p>You need a data model object that stores the data for application. </p> <p>A data model is a customized, standalone object accessible from anywhere in the application. The data model object knows nothing about any views or view controllers. It just stores data and the logical relationships between that data. </p> <p>When different parts of the app need to write or read data, they write and read to the data model. In your case, view1 would save its data to the data model when it unloads and then view2 would read that data from the data model when it loads (or vice versa.) </p> <p>In a properly designed app, no two view controllers should have access to the internal data of another controller. (The only reason a view controllers needs to know of the existence of another controller is if it has to trigger the loading of that other controller.) </p> <p>The quick and dirty way to create a data model is to add attributes to the app delegate and then call the app delegate from the view controllers using:</p> <pre><code>YourAppDelegateClass *appDelegate = [[UIApplication sharedApplication] delegate]; myLocalProperty = appDelegate.someDataModelProperty; </code></pre> <p>This will work for small project but as your data grows complex, you should create a dedicated class for your data model. </p> <p>Edit:</p> <p>To clarify for your specific case, you would add the call to the data model when the receiver viewController becomes active. </p> <p>Placing the data in an init method or a <code>viewDidLoad</code> won't work because in a <code>UITabBar</code> the users can switch back and forth without unloading the view or reinitializing the view controller. </p> <p>The best place to retrieve changing data is in the <code>viewWillAppear</code> controller method. That way the data will be updated every time the user switches to that tab.</p>
2,746,309
Best Fit Scheduling Algorithm
<p>I'm writing a scheduling program with a difficult programming problem. There are several events, each with multiple meeting times. I need to find an arrangement of meeting times such that each schedule contains any given event exactly once, using one of each event's multiple meeting times.</p> <p>Obviously I could use brute force, but that's rarely the best solution. I'm guessing this is a relatively basic computer science problem, which I'll learn about once I am able to start taking computer science classes. In the meantime, I'd prefer any links where I could read up on this, or even just a name I could Google.</p>
2,749,869
4
7
null
2010-04-30 17:06:01.617 UTC
14
2018-02-10 15:47:13.257 UTC
2010-06-06 16:36:59.253 UTC
null
279,691
null
23,335
null
1
28
algorithm|scheduling|genetic-algorithm|genetic-programming
23,697
<p>I think you should use genetic algorithm because:</p> <ul> <li>It is best suited for large problem instances.</li> <li>It yields reduced time complexity on the price of inaccurate answer(Not the ultimate best)</li> <li>You can specify constraints &amp; preferences easily by adjusting fitness punishments for not met ones.</li> <li>You can specify time limit for program execution.</li> <li><p>The quality of solution depends on how much time you intend to spend solving the program..</p> <p><a href="http://en.wikipedia.org/wiki/Genetic_algorithm" rel="noreferrer">Genetic Algorithms Definition</a></p> <p><a href="http://www.ai-junkie.com/ga/intro/gat1.html" rel="noreferrer">Genetic Algorithms Tutorial</a></p> <p><a href="http://www.codeproject.com/KB/recipes/GaClassSchedule.aspx" rel="noreferrer">Class scheduling project with GA</a></p></li> </ul>
2,650,374
c++ Initializing a struct with an array as a member
<p>Edited again because it originally wasn't clear that I'm trying to initialize the arrays at compile time, not at run time...</p> <hr> <p>I've got the following reduced testcase:</p> <pre><code>typedef struct TestStruct { int length; int values[]; }; TestStruct t = {3, {0, 1, 2}}; TestStruct t2 = {4, {0, 1, 2, 3}}; int main() { return(0); } </code></pre> <p>This works with Visual C++, but doesn't compile with g++ under linux. Can anyone help me make this specific kind of initializer portable?</p> <p>Additional details: the actual structure I'm working with has several other int values, and the array can range in length from a single entry to over 1800 entries.</p> <p>EDIT: I think (but am not sure) that this is not a VLA issue. To clarify, I'm trying to get the compiler to do the work for me at compile-time. The length of the array at run-time is constant. Apologies if I'm wrong; I'm primarily a c#/Perl/Ruby programmer who is stuck maintaining this legacy app...</p> <p>Any help much appreciated. Thanks!</p>
2,650,432
4
2
null
2010-04-16 03:21:30.48 UTC
9
2014-04-12 06:46:10.217 UTC
2010-04-16 04:25:33.227 UTC
null
83,715
null
83,715
null
1
34
c++|struct|initialization|portability
89,558
<p>c++ doesn't have the same flexible array member as last element as c99. You should use a <code>std::vector</code> if you don't know how many elements or you should specify how many if you do.</p> <p><strong>EDIT:</strong> You have said in your edit that the array is a runtime constant, so specify the size and it should work fine. g++ has no problem with the following code:</p> <pre><code>struct TestStruct { // note typedef is not needed */ int length; int values[3]; // specified the size }; TestStruct t = {3, {0, 1, 2}}; int main() { // main implicitly returns 0 if none specified } </code></pre> <p><strong>EDIT:</strong> to address your comment, you could use templates like this:</p> <pre><code>template &lt;int N&gt; struct TestStruct { int length; int values[N]; }; TestStruct&lt;3&gt; t3 = {3, {0, 1, 2}}; TestStruct&lt;2&gt; t2 = {2, {0, 1}}; int main() {} </code></pre> <p>The only problem is that there is no easy way to put both t2 and t3 in a container (like a list/vector/stack/queue/etc because they have different sizes. If you want that, you should use <code>std::vector</code>. Also, if you are doing that, then it isn't necessary to store the size (it is associated with the type). So you could do this instead:</p> <pre><code>template &lt;int N&gt; struct TestStruct { static const int length = N; int values[N]; }; TestStruct&lt;3&gt; t3 = {{0, 1, 2}}; TestStruct&lt;2&gt; t2 = {{0, 1}}; int main() {} </code></pre> <p>But once again, you cannot put t2 and t3 in a "collection" together easily.</p> <p><strong>EDIT:</strong> All in all, it sounds like you (unless you store more data than just some numbers and the size) don't need a struct at all, and can't just use a plain old vector.</p> <pre><code>typedef std::vector&lt;int&gt; TestStruct; int t2_init[] = { 0, 1, 2 }; TestStruct t3(t3_init, t3_init + 3); int t2_init[] = { 0, 1 }; TestStruct t2(t2_init, t2_init + 2); int main() {} </code></pre> <p>Which would allow you to have both t2 and t3 in a collection together. Unfortunately <code>std::vector</code> doesn't (yet) have array style initializer syntax, so i've used a shortcut. But it's simple enough to write a function to populate the vectors in a nice fashion.</p> <p><strong>EDIT:</strong> OK, so you don't need a collection, but you need to pass it to a function, you can use templates for that to preserve type safety!</p> <pre><code>template &lt;int N&gt; struct TestStruct { static const int length = N; int values[N]; }; TestStruct&lt;3&gt; t3 = {{0, 1, 2}}; TestStruct&lt;2&gt; t2 = {{0, 1}}; template &lt;int N&gt; void func(const TestStruct&lt;N&gt; &amp;ts) { /* you could make it non-const if you need it to modify the ts */ for(int i = 0; i &lt; N; ++i) { /* we could also use ts.length instead of N here */ std::cout &lt;&lt; ts.values[i] &lt;&lt; std::endl; } } // this will work too... template &lt;class T&gt; void func2(const T &amp;ts) { for(int i = 0; i &lt; ts.length; ++i) { std::cout &lt;&lt; ts.values[i] &lt;&lt; std::endl; } } int main() { func(t2); func(t3); func2(t2); } </code></pre>
2,565,755
LaTeX book class: Twosided document with wrong margins
<p>I am trying to write my thesis in latex... Cannot get the layout straight though :? I'm using the following document class:</p> <pre><code>\documentclass[11pt,a4paper,twoside,openright]{book} </code></pre> <p>My problem is: on the <em>odd</em> numbered pages there is a big margin right, and a small margin left - it should be the other way round... (for binding &amp; stuff) I am a little puzzled by this -- am I just to stupid to see the obvious? The odd page numbers appear on the 'right' page of a bound document, so there needs to be a larger gutter margin on the left for binding -- and vice versa. Right?</p> <p>Why does LaTeX not behave like this?</p> <p>Here is the full code to produce a small Tex file that shows my problem:</p> <pre><code>\documentclass[11pt,a4paper,twoside,openright]{book} \begin{document} \chapter{blah} Lorem ipsum ius et accumsan tractatos, aliquip deterruisset cu usu. Ea soleat eirmod nostrud eum, est ceteros similique ad, at mea tempor petentium. At decore neglegentur quo, ea ius doming dictas facilis, duo ut porro nostrum suavitate. \end{document} </code></pre> <p>Edit: I know about a lot of ways to manually specify the page margins, like</p> <pre><code>\setlength{\oddsidemargin}{53pt} </code></pre> <p>or ...</p> <pre><code>\usepackage[lmargin=1cm,rmargin=2.5cm,tmargin=2.5cm,bmargin=2.5cm]{geometry} </code></pre> <p>I just wanted to use the default settings and don't understand why they do not behave as expected.</p>
2,565,797
4
0
null
2010-04-02 08:35:37.593 UTC
21
2013-05-12 14:40:48.55 UTC
2013-05-12 14:40:48.55 UTC
null
39,974
null
210,368
null
1
46
latex|document|margins
51,599
<p>The extra space is for the margin notes. In general, to see what's going on with your layout, you can put <code>\usepackage{layout}</code> in your preamble, and then stick <code>\layout</code> in your document to get a diagram and listing of geometry settings.</p> <p>In your case, as I say, what's going in is the extra space for margin notes. If you don't want it, use <code>\setlength{\marginparwidth}{0pt}</code>.</p>
29,283,040
How to add custom certificate authority (CA) to nodejs
<p>I'm using a CLI tool to build hybrid mobile apps which has a cool upload feature so I can test the app on a device without going through the app store (it's ionic-cli). However, in my company like so many other companies TLS requests are re-signed with the company's own custom CA certificate which I have on my machine in the keychain (OS X). However, nodejs does not use the keychain to get its list of CA's to trust. I don't control the ionic-cli app so I can't simply pass in a { ca: } property to the https module. I could also see this being a problem for any node app which I do not control. Is it possible to tell nodejs to trust a CA?</p> <p>I wasn't sure if this belonged in Information Security or any of the other exchanges...</p>
47,160,447
6
0
null
2015-03-26 15:51:05.35 UTC
22
2022-03-16 17:58:56.873 UTC
null
null
null
null
1,454,406
null
1
101
node.js|npm
149,134
<p>Node.js 7.3.0 (and the LTS versions 6.10.0 and 4.8.0) added <a href="https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file" rel="noreferrer"><code>NODE_EXTRA_CA_CERTS</code></a> environment variable for you to pass the CA certificate file. It will be safer than disabling certificate verification using <code>NODE_TLS_REJECT_UNAUTHORIZED</code>.</p> <pre><code>$ export NODE_EXTRA_CA_CERTS=[your CA certificate file path] </code></pre>
31,776,546
Why does Runtime.exec(String) work for some but not all commands?
<p>When I try to run <code>Runtime.exec(String)</code>, certain commands work, while other commands are executed but fail or do different things than in my terminal. Here is a self-contained test case that demonstrates the effect:</p> <pre><code>public class ExecTest { static void exec(String cmd) throws Exception { Process p = Runtime.getRuntime().exec(cmd); int i; while( (i=p.getInputStream().read()) != -1) { System.out.write(i); } while( (i=p.getErrorStream().read()) != -1) { System.err.write(i); } } public static void main(String[] args) throws Exception { System.out.print("Runtime.exec: "); String cmd = new java.util.Scanner(System.in).nextLine(); exec(cmd); } } </code></pre> <p>The example works great if I replace the command with <code>echo hello world</code>, but for other commands -- especially those involving filenames with spaces like here -- I get errors even though the command is clearly being executed:</p> <pre><code>myshell$ javac ExecTest.java &amp;&amp; java ExecTest Runtime.exec: ls -l 'My File.txt' ls: cannot access 'My: No such file or directory ls: cannot access File.txt': No such file or directory </code></pre> <p>meanwhile, copy-pasting to my shell:</p> <pre><code>myshell$ ls -l 'My File.txt' -rw-r--r-- 1 me me 4 Aug 2 11:44 My File.txt </code></pre> <p>Why is there a difference? When does it work and when does it fail? How do I make it work for all commands?</p>
31,776,547
1
0
null
2015-08-02 21:00:56.83 UTC
17
2016-01-19 23:51:54.43 UTC
null
null
null
null
1,899,640
null
1
42
java|runtime.exec
30,411
<h3>Why do some commands fail?</h3> <p>This happens because the command passed to <code>Runtime.exec(String)</code> is not executed in a shell. The shell performs a lot of common support services for programs, and when the shell is not around to do them, the command will fail.</p> <h3>When do commands fail?</h3> <p>A command will fail whenever it depends on a shell features. The shell does a lot of common, useful things we don't normally think about:</p> <ol> <li><p><strong>The shell splits correctly on quotes and spaces</strong></p> <p>This makes sure the filename in <code>"My File.txt"</code> remains a single argument. </p> <p><code>Runtime.exec(String)</code> naively splits on spaces and would pass this as two separate filenames. This obviously fails.</p></li> <li><p><strong>The shell expands globs/wildcards</strong></p> <p>When you run <code>ls *.doc</code>, the shell rewrites it into <code>ls letter.doc notes.doc</code>. </p> <p><code>Runtime.exec(String)</code> doesn't, it just passes them as arguments. </p> <p><code>ls</code> has no idea what <code>*</code> is, so the command fails.</p></li> <li><p><strong>The shell manages pipes and redirections.</strong></p> <p>When you run <code>ls mydir &gt; output.txt</code>, the shell opens "output.txt" for command output and removes it from the command line, giving <code>ls mydir</code>. </p> <p><code>Runtime.exec(String)</code> doesn't. It just passes them as arguments. </p> <p><code>ls</code> has no idea what <code>&gt;</code> means, so the command fails.</p></li> <li><p><strong>The shell expands variables and commands</strong></p> <p>When you run <code>ls "$HOME"</code> or <code>ls "$(pwd)"</code>, the shell rewrites it into <code>ls /home/myuser</code>. </p> <p><code>Runtime.exec(String)</code> doesn't, it just passes them as arguments.</p> <p><code>ls</code> has no idea what <code>$</code> means, so the command fails.</p></li> </ol> <h3>What can you do instead?</h3> <p>There are two ways to execute arbitrarily complex commands:</p> <p><strong>Simple and sloppy:</strong> delegate to a shell. </p> <p>You can just use <code>Runtime.exec(String[])</code> (note the array parameter) and pass your command directly to a shell that can do all the heavy lifting:</p> <pre><code>// Simple, sloppy fix. May have security and robustness implications String myFile = "some filename.txt"; String myCommand = "cp -R '" + myFile + "' $HOME 2&gt; errorlog"; Runtime.getRuntime().exec(new String[] { "bash", "-c", myCommand }); </code></pre> <p><strong>Secure and robust:</strong> take on the responsibilities of the shell.</p> <p>This is not a fix that can be mechanically applied, but requires an understanding the Unix execution model, what shells do, and how you can do the same. However, you can get a solid, secure and robust solution by taking the shell out of the picture. This is facilitated by <code>ProcessBuilder</code>.</p> <p>The command from the previous example that requires someone to handle 1. quotes, 2. variables, and 3. redirections, can be written as:</p> <pre><code>String myFile = "some filename.txt"; ProcessBuilder builder = new ProcessBuilder( "cp", "-R", myFile, // We handle word splitting System.getenv("HOME")); // We handle variables builder.redirectError( // We set up redirections ProcessBuilder.Redirect.to(new File("errorlog"))); builder.start(); </code></pre>
46,540,664
'No application found. Either work inside a view function or push an application context.'
<p>I'm trying to separate my Flask-SQLAlchemy models into separate files. When I try to run <code>db.create_all()</code> I get <code>No application found. Either work inside a view function or push an application context.</code></p> <p><code>shared/db.py</code>:</p> <pre><code>from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() </code></pre> <p><code>app.py</code>:</p> <pre><code>from flask import Flask from flask_sqlalchemy import SQLAlchemy from shared.db import db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'My connection string' db.init_app(app) </code></pre> <p><code>user.py</code>:</p> <pre><code>from shared.db import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) email_address = db.Column(db.String(300), unique=True, nullable=False) password = db.Column(db.Text, nullable=False) </code></pre>
46,541,219
1
0
null
2017-10-03 08:51:10.507 UTC
17
2019-06-18 15:48:28.527 UTC
2017-10-03 13:02:39.673 UTC
null
400,617
null
5,905,951
null
1
89
python|flask|flask-sqlalchemy
71,830
<p>Use <code>with app.app_context()</code> to push an application context when creating the tables.</p> <pre><code>app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'My connection string' db.init_app(app) with app.app_context(): db.create_all() </code></pre>
1,007,018
XSLT expression to check if variable belongs to set of elements
<p>I have code like this:</p> <pre><code> &lt;xsl:if test="$k='7' or $k = '8' or $k = '9'"&gt; </code></pre> <p>Is there any way to put this expression in a form, like, for instance SQL</p> <pre><code> k IN (7, 8, 9) </code></pre> <p>Ty :)</p>
1,007,037
2
0
null
2009-06-17 13:28:03.22 UTC
4
2018-09-14 12:55:28.78 UTC
null
null
null
null
82,660
null
1
23
xslt
44,534
<p>XSLT / XPath 1.0:</p> <pre><code>&lt;!-- a space-separated list of valid values --&gt; &lt;xsl:variable name="list" select="'7 8 9'" /&gt; &lt;xsl:if test=" contains( concat(' ', $list, ' '), concat(' ', $k, ' ') ) "&gt; &lt;xsl:value-of select="concat('Item ', $k, ' is in the list.')" /&gt; &lt;/xsl:if&gt; </code></pre> <p>You can use other separators if needed. </p> <p>In XSLT / XPath 2.0 you could do something like:</p> <pre><code>&lt;xsl:variable name="list" select="fn:tokenize('7 8 9', '\s+')" /&gt; &lt;xsl:if test="fn:index-of($list, $k)"&gt; &lt;xsl:value-of select="concat('Item ', $k, ' is in the list.')" /&gt; &lt;/xsl:if&gt; </code></pre> <p>If you can use document structure to define your list, you could do:</p> <pre><code>&lt;!-- a node-set defining the list of currently valid items --&gt; &lt;xsl:variable name="list" select="/some/items[1]/item" /&gt; &lt;xsl:template match="/"&gt; &lt;xsl:variable name="k" select="'7'" /&gt; &lt;!-- test if item $k is in the list of valid items --&gt; &lt;xsl:if test="count($list[@id = $k])"&gt; &lt;xsl:value-of select="concat('Item ', $k, ' is in the list.')" /&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; </code></pre>
1,111,645
Comparing Timer with DispatcherTimer
<p>what is a difference <code>between System.Windows.Forms.Timer()</code> and <code>System.Windows.Threading.DispatcherTimer()</code> ? In which cases, we should use them? any best practices ?</p>
1,111,699
2
0
null
2009-07-10 19:55:24.003 UTC
22
2019-11-04 18:24:23.933 UTC
2009-07-11 00:22:31.93 UTC
null
23,199
null
119,504
null
1
102
c#|timer
64,374
<p><code>Windows.Forms.Timer</code> uses the windows forms message loop to process timer events. It should be used when writing timing events that are being used in Windows Forms applications, and you want the timer to fire on the main UI thread.</p> <p><code>DispatcherTimer</code> is the WPF timing mechanism. It should be used when you want to handle timing in a similar manner (although this isn't limited to a single thread - each thread has its own dispatcher) and you're using WPF. It fires the event on the same thread as the Dispatcher.</p> <p>In general, <strong><em><code>WPF == DispatcherTimer</code> and <code>Windows Forms == Forms.Timer</code>.</em></strong></p> <p>That being said, there is also <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.timer" rel="noreferrer"><code>System.Threading.Timer</code></a>, which is a timer <code>class</code> that fires on a separate thread. This is good for purely numerical timing, where you're not trying to update the UI, etc.</p>
2,396,422
C# merge two objects together at runtime
<p>I have a situation where I am loading a very unnormalized record set from Excel. I pull in each row and create the objects from it one at a time. each row could contain a company and / or a client.</p> <p>My issue is that multiple rows could have the same objects, so I may have already created it. I do a comparison to see if it is already in the list. If so I need to merge the two objects to ensure I have not gained any new information from the second row.</p> <p>so:</p> <pre><code>company - client - address - phone ---------------------------------------- mycompany - - myaddress - mycompnay - myclient - - myphone </code></pre> <p>so the first row would create a company object with an address of "myaddress". The second row would create another company object (which by my rules is the same company as the name is the same), this also having a client reference and a phone number.</p> <p>So I would know they are the same but need to ensure all the data is merged into one object.</p> <p>At the moment I am creating a utility class that takes both objects, (one being the primary and the other to be merged, so one has priority if there is a clash), it goes through each variable and assigns the values if there are any. This is a bit boiler plate heavy and I was hoping there might be some utility I could utilize to do the manual work for me.</p> <p>The example has been simplified as there are a fair few other variables, some basic types and others that are more complex items.</p>
2,396,483
5
2
null
2010-03-07 13:38:41.503 UTC
12
2012-11-26 15:01:23.99 UTC
2010-03-07 13:51:46.587 UTC
null
76,337
null
6,486
null
1
21
c#
18,232
<p>Reflection would work. Something like:</p> <pre><code>public static void MergeWith&lt;T&gt;(this T primary, T secondary) { foreach (var pi in typeof(T).GetProperties()) { var priValue = pi.GetGetMethod().Invoke(primary, null); var secValue = pi.GetGetMethod().Invoke(secondary, null); if (priValue == null || (pi.PropertyType.IsValueType &amp;&amp; priValue.Equals(Activator.CreateInstance(pi.PropertyType)))) { pi.GetSetMethod().Invoke(primary, new object[]{secValue}); } } } </code></pre>
2,455,158
Find window previously opened by window.open
<p>We've got the following situation, running from a single domain:</p> <p>Page A uses <code>window.open()</code> to open a named window (a popup player). <code>window.open()</code> gives page A a reference to the window.</p> <p>User now reloads page A. The reference to the named window is lost. Using <code>window.open()</code> to "find" the window has the unfortunate side effect of reloading it (undesirable). Is there any other way to get a reference to this window?</p>
2,455,480
5
2
null
2010-03-16 14:31:23.79 UTC
9
2019-11-06 12:42:29.453 UTC
null
null
null
null
14,357
null
1
24
javascript|window.open
28,597
<p>Try this:</p> <pre><code>var playerUrl = 'http://my.player...'; var popupPlayer= window.open('', 'popupPlayer', 'width=150,height=100') ; if(popupPlayer.location.href == 'about:blank' ){ popupPlayer.location = playerUrl ; } popupPlayer.focus(); </code></pre> <p>It will open a blank window with a unique name. Since the url is blank, the content of the window will not be reloaded. </p>
2,354,784
__attribute__((format(printf, 1, 2))) for MSVC?
<p>With GCC, I can specify <code>__attribute__((format(printf, 1, 2)))</code> , telling the compiler that this function takes vararg parameters that are printf format specifiers. </p> <p>This is very helpful in the cases where I wrap e.g. the vsprintf function family. I can have <code>extern void log_error(const char *format, ...) __attribute__((format(printf, 1, 2)));</code></p> <p>And whenever I call this function, gcc will check that the types and number of arguments conform to the given format specifiers as it would for printf, and issue a warning if not.</p> <p>Does the Microsoft C/C++ compiler have anything similar ?</p>
2,354,807
5
0
null
2010-03-01 09:21:26.583 UTC
3
2022-09-19 16:05:56.917 UTC
null
null
null
null
126,769
null
1
30
c++|c|visual-c++
12,432
<p>While GCC checks format specifiers when -Wformat is enabled, VC++ has no such checking, even for standard functions so there is no equivalent to this <code>__attribute__</code> because there is no equivalent to -Wformat.</p> <p>I think Microsoft's emphasis on C++ (evidenced by maintaining ISO compliance for C++ while only supporting C89) may be in part the reason why VC++ does not have format specifier checking; in C++ using <code>&lt;iostream&gt;</code> format specifiers are unnecessary.</p>
2,855,015
how to make requiredfieldvalidator error message display after click submit button
<p>now, the error message will display if I move out of current textbox. I don't want to display it until I click submit button.</p>
2,855,057
6
0
null
2010-05-18 06:43:53.363 UTC
2
2020-09-11 20:19:54.377 UTC
null
null
null
null
241,297
null
1
6
asp.net|requiredfieldvalidator
62,658
<p>This isn't possible when ClientScript is enabled for your validators. And the ClientScript is by default enabled for your validators. You need to disable this by settings EnableClientScript to False in your source.</p> <p>Now in the event handler of your submit button call Page.Validate() and Page.IsValid to see if every validators did pass the test.</p> <p>Example:</p> <pre><code>&lt;asp:RequiredFieldValidator ID="rfvFirstName" runat="server" ControlToValidate="txtFirstName" EnableClientScript="false" Display="Dynamic" SetFocusOnError="true" /&gt; Page.Validate(); if (!Page.IsValid) { //show a message or throw an exception } </code></pre>
2,473,597
BitSet to and from integer/long
<p>If I have an integer that I'd like to perform bit manipulation on, how can I load it into a <code>java.util.BitSet</code>? How can I convert it back to an int or long? I'm not so concerned about the size of the <code>BitSet</code> -- it will always be 32 or 64 bits long. I'd just like to use the <code>set()</code>, <code>clear()</code>, <code>nextSetBit()</code>, and <code>nextClearBit()</code> methods rather than bitwise operators, but I can't find an easy way to initialize a bit set with a numeric type.</p>
2,473,719
6
1
null
2010-03-18 21:56:01.99 UTC
7
2021-11-27 15:13:20.113 UTC
2017-01-02 07:22:52.097 UTC
null
1,075,341
null
190,201
null
1
59
java|bit-manipulation|bitset
69,388
<p>The following code creates a bit set from a long value and vice versa:</p> <pre><code>public class Bits { public static BitSet convert(long value) { BitSet bits = new BitSet(); int index = 0; while (value != 0L) { if (value % 2L != 0) { bits.set(index); } ++index; value = value &gt;&gt;&gt; 1; } return bits; } public static long convert(BitSet bits) { long value = 0L; for (int i = 0; i &lt; bits.length(); ++i) { value += bits.get(i) ? (1L &lt;&lt; i) : 0L; } return value; } } </code></pre> <p>EDITED: Now both directions, @leftbrain: of cause, you are right</p>
2,633,112
Get JSF managed bean by name in any Servlet related class
<p>I'm trying to write a custom servlet (for AJAX/JSON) in which I would like to reference my <code>@ManagedBeans</code> by name. I'm hoping to map:</p> <p><code>http://host/app/myBean/myProperty</code></p> <p>to: </p> <pre><code>@ManagedBean(name="myBean") public class MyBean { public String getMyProperty(); } </code></pre> <p>Is it possible to load a bean by name from a regular servlet? Is there a JSF servlet or helper I could use for it?</p> <p>I seem to be spoilt by Spring in which all this is too obvious.</p>
2,633,733
6
2
null
2010-04-13 20:53:32.92 UTC
86
2020-05-04 11:44:00.087 UTC
2015-02-01 15:26:17.12 UTC
null
157,882
null
277,683
null
1
105
jsf|jakarta-ee|servlets|jsf-2|managed-bean
155,648
<p>In a servlet based artifact, such as <code>@WebServlet</code>, <code>@WebFilter</code> and <code>@WebListener</code>, you can grab a &quot;plain vanilla&quot; JSF <code>@ManagedBean @RequestScoped</code> by:</p> <pre><code>Bean bean = (Bean) request.getAttribute(&quot;beanName&quot;); </code></pre> <p>and <code>@ManagedBean @SessionScoped</code> by:</p> <pre><code>Bean bean = (Bean) request.getSession().getAttribute(&quot;beanName&quot;); </code></pre> <p>and <code>@ManagedBean @ApplicationScoped</code> by:</p> <pre><code>Bean bean = (Bean) getServletContext().getAttribute(&quot;beanName&quot;); </code></pre> <p>Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return <code>null</code>. You'd then need to manually create the bean and use <code>setAttribute(&quot;beanName&quot;, bean)</code>.</p> <hr /> <p>If you're able to use CDI <a href="https://jakarta.ee/specifications/platform/8/apidocs/javax/inject/Named.html" rel="noreferrer"><code>@Named</code></a> instead of the since JSF 2.3 deprecated <code>@ManagedBean</code>, then it's even more easy, particularly because you don't anymore need to manually create the beans:</p> <pre><code>@Inject private Bean bean; </code></pre> <p>Note that this won't work when you're using <code>@Named @ViewScoped</code> because the bean can only be identified by JSF view state and that's only available when the <code>FacesServlet</code> has been invoked. So in a filter which runs before that, accessing an <code>@Inject</code>ed <code>@ViewScoped</code> will always throw <code>ContextNotActiveException</code>.</p> <hr /> <p>Only when you're inside <code>@ManagedBean</code>, then you can use <a href="https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/bean/ManagedProperty.html" rel="noreferrer"><code>@ManagedProperty</code></a>:</p> <pre><code>@ManagedProperty(&quot;#{bean}&quot;) private Bean bean; </code></pre> <p>Note that this doesn't work inside a <code>@Named</code> or <code>@WebServlet</code> or any other artifact. It really works inside <code>@ManagedBean</code> only.</p> <hr /> <p>If you're not inside a <code>@ManagedBean</code>, but the <code>FacesContext</code> is readily available (i.e. <code>FacesContext#getCurrentInstance()</code> doesn't return <code>null</code>), you can also use <a href="https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/application/Application.html#evaluateExpressionGet-javax.faces.context.FacesContext-java.lang.String-java.lang.Class-" rel="noreferrer"><code>Application#evaluateExpressionGet()</code></a>:</p> <pre><code>FacesContext context = FacesContext.getCurrentInstance(); Bean bean = context.getApplication().evaluateExpressionGet(context, &quot;#{beanName}&quot;, Bean.class); </code></pre> <p>which can be convenienced as follows:</p> <pre><code>@SuppressWarnings(&quot;unchecked&quot;) public static &lt;T&gt; T findBean(String beanName) { FacesContext context = FacesContext.getCurrentInstance(); return (T) context.getApplication().evaluateExpressionGet(context, &quot;#{&quot; + beanName + &quot;}&quot;, Object.class); } </code></pre> <p>and can be used as follows:</p> <pre><code>Bean bean = findBean(&quot;bean&quot;); </code></pre> <hr /> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/4347374/backing-beans-managedbean-or-cdi-beans-named">Backing beans (@ManagedBean) or CDI Beans (@Named)?</a></li> </ul>
2,385,553
How can I generate an HTML report for Junit results?
<p>Is there a way to (easily) generate a HTML report that contains the tests results ? I am currently using JUnit in addition to Selenium for testing web apps UI.</p> <p>PS: Given the project structure I am not supposed to use Ant :(</p>
2,401,679
8
2
null
2010-03-05 09:04:53.377 UTC
24
2022-03-29 11:16:57.873 UTC
2010-11-30 23:50:17.867 UTC
null
183,172
null
211,701
null
1
59
html|junit|selenium|report
157,394
<p>If you <em>could</em> use Ant then you would just use the JUnitReport task as detailed here: <a href="http://ant.apache.org/manual/Tasks/junitreport.html" rel="noreferrer">http://ant.apache.org/manual/Tasks/junitreport.html</a>, but you mentioned in your question that you're not supposed to use Ant. I believe that task merely transforms the XML report into HTML so it would be feasible to use any XSLT processor to generate a similar report.</p> <p>Alternatively, you could switch to using TestNG ( <a href="http://testng.org/doc/index.html" rel="noreferrer">http://testng.org/doc/index.html</a> ) which is very similar to JUnit but has a default HTML report as well as several other cool features.</p>
2,935,183
Bash: infinite sleep (infinite blocking)
<p>I use <code>startx</code> to start X which will evaluate my <code>.xinitrc</code>. In my <code>.xinitrc</code> I start my window manager using <code>/usr/bin/mywm</code>. Now, if I kill my WM (in order to f.e. test some other WM), X will terminate too because the <code>.xinitrc</code> script reached EOF. So I added this at the end of my <code>.xinitrc</code>:</p> <pre><code>while true; do sleep 10000; done </code></pre> <p>This way X won't terminate if I kill my WM. Now my question: how can I do an <strong>infinite sleep</strong> instead of looping sleep? Is there a command which will kinda like freeze the script?</p>
22,100,106
11
1
null
2010-05-29 13:12:14.017 UTC
35
2022-08-09 11:53:44.893 UTC
2021-01-13 13:15:40.563 UTC
null
5,825,294
null
239,117
null
1
208
linux|bash|sleep|infinite
147,651
<p><code>sleep infinity</code> does exactly what it suggests and works without cat abuse.</p>
2,872,959
How to tell if an array is a permutation in O(n)?
<p>Input: A <em>read-only</em> array of N elements containing integer values from 1 to N (some integer values can appear more than once!). And a memory zone of a <strong>fixed</strong> size (10, 100, 1000 etc - <strong>not</strong> depending on N).</p> <p>How to tell <strong>in O(n)</strong> if the array represents a permutation?</p> <p>--What I achieved so far (an answer proved that this was <strong>not</strong> good):--</p> <p><strike></p> <ol> <li>I use the limited memory area to store the sum and the product of the array.</li> <li>I compare the sum with <strong>N*(N+1)/2</strong> and the product with <strong>N!</strong></li> </ol> <p>I know that if condition (2) is true I <strong>might</strong> have a permutation. I'm wondering if there's a way to prove that condition (2) is sufficient to tell if I have a permutation. So far I haven't figured this out ...</p> <p></strike></p>
2,874,631
16
6
null
2010-05-20 10:44:42.38 UTC
31
2016-10-26 16:24:57.99 UTC
2011-07-22 22:26:21.697 UTC
null
387,076
null
13,136
null
1
40
arrays|algorithm|permutation
17,191
<p>I'm very slightly skeptical that there is a solution. Your problem seems to be very close to one posed several years ago in the mathematical literature, with <a href="http://geomete.com/abdali/papers/duplmath.pdf" rel="nofollow noreferrer">a summary given here ("The Duplicate Detection Problem", S. Kamal Abdali, 2003)</a> that uses cycle-detection -- the idea being the following:</p> <p>If there is a duplicate, there exists a number <code>j</code> between 1 and N such that the following would lead to an infinite loop:</p> <pre><code>x := j; do { x := a[x]; } while (x != j); </code></pre> <p>because a permutation consists of one or more subsets S of distinct elements s<sub>0</sub>, s<sub>1</sub>, ... s<sub>k-1</sub> where s<sub>j</sub> = a[s<sub>j-1</sub>] for all j between 1 and k-1, and s<sub>0</sub> = a[s<sub>k-1</sub>], so all elements are involved in cycles -- one of the duplicates would not be part of such a subset.</p> <p>e.g. if the array = [2, 1, 4, 6, <strong>8</strong>, 7, 9, 3, 8]</p> <p>then the element in bold at position 5 is a duplicate because all the other elements form cycles: { 2 -> 1, 4 -> 6 -> 7 -> 9 -> 8 -> 3}. Whereas the arrays [2, 1, 4, 6, 5, 7, 9, 3, 8] and [2, 1, 4, 6, 3, 7, 9, 5, 8] are valid permutations (with cycles { 2 -> 1, 4 -> 6 -> 7 -> 9 -> 8 -> 3, 5 } and { 2 -> 1, 4 -> 6 -> 7 -> 9 -> 8 -> 5 -> 3 } respectively).</p> <p>Abdali goes into a way of finding duplicates. Basically the following algorithm (using <a href="http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare" rel="nofollow noreferrer">Floyd's cycle-finding algorithm</a>) works if you happen across one of the duplicates in question:</p> <pre><code>function is_duplicate(a, N, j) { /* assume we've already scanned the array to make sure all elements are integers between 1 and N */ x1 := j; x2 := j; do { x1 := a[x1]; x2 := a[x2]; x2 := a[x2]; } while (x1 != x2); /* stops when it finds a cycle; x2 has gone around it twice, x1 has gone around it once. If j is part of that cycle, both will be equal to j. */ return (x1 != j); } </code></pre> <p>The difficulty is I'm not sure your problem as stated matches the one in his paper, and I'm also not sure if the method he describes runs in O(N) or uses a fixed amount of space. A potential counterexample is the following array:</p> <p>[3, 4, 5, 6, 7, 8, 9, 10, ... N-10, N-9, N-8, N-7, N-2, N-5, N-5, N-3, N-5, N-1, N, 1, 2]</p> <p>which is basically the identity permutation shifted by 2, with the elements [N-6, N-4, and N-2] replaced by [N-2, N-5, N-5]. This has the correct sum (not the correct product, but I reject taking the product as a possible detection method since the space requirements for computing N! with arbitrary precision arithmetic are O(N) which violates the spirit of the "fixed memory space" requirement), and if you try to find cycles, you will get cycles { 3 -> 5 -> 7 -> 9 -> ... N-7 -> N-5 -> N-1 } and { 4 -> 6 -> 8 -> ... N-10 -> N-8 -> N-2 -> N -> 2}. The problem is that there could be up to N cycles, (identity permutation has N cycles) each taking up to O(N) to find a duplicate, and you have to keep track somehow of which cycles have been traced and which have not. I'm skeptical that it is possible to do this in a fixed amount of space. But maybe it is.</p> <p>This is a heavy enough problem that it's worth asking on <a href="https://mathoverflow.net/">mathoverflow.net</a> (despite the fact that most of the time mathoverflow.net is cited on stackoverflow it's for problems which are too easy)</p> <hr> <p><strong>edit:</strong> I did <a href="https://mathoverflow.net/questions/25374/duplicate-detection-problem/25419#25419">ask on mathoverflow</a>, there's some interesting discussion there.</p>
2,394,935
Can I underline text in an Android layout?
<p>How can I define <em>underlined</em> text in an Android layout <code>xml</code> file?</p>
2,394,939
27
1
null
2010-03-07 02:26:35.263 UTC
123
2022-04-21 15:38:10.05 UTC
2018-10-11 04:16:40.403 UTC
null
1,033,581
null
114,066
null
1
787
android|android-layout|fonts
650,416
<p>It can be achieved if you are using a <a href="http://developer.android.com/guide/topics/resources/available-resources.html#stringresources" rel="noreferrer"><strong>string resource</strong></a> xml file, which supports HTML tags like <code>&lt;b&gt;&lt;/b&gt;</code>, <code>&lt;i&gt;&lt;/i&gt;</code> and <code>&lt;u&gt;&lt;/u&gt;</code>.</p> <pre><code>&lt;resources&gt; &lt;string name=&quot;your_string_here&quot;&gt;&lt;![CDATA[This is an &lt;u&gt;underline&lt;/u&gt;.]]&gt;&lt;/string&gt; &lt;/resources&gt; </code></pre> <p>If you want to underline something from code use:</p> <pre><code>TextView textView = (TextView) view.findViewById(R.id.textview); SpannableString content = new SpannableString(&quot;Content&quot;); content.setSpan(new UnderlineSpan(), 0, content.length(), 0); textView.setText(content); </code></pre>
23,916,521
PHP push new key and value in existing object array
<p>In my study how objects and arrays work with PHP I have a new problem. Searching in existing questions didn't give myself the right "push".</p> <p>I have this for example:</p> <pre><code>$html_doc = (object) array ( "css" =&gt; array(), "js" =&gt; array() ); array_push($html_doc , "title" =&gt; "testtitle"); </code></pre> <p>Why is this not working? Do i need to specify first the key title? Or is there another "1 line" solution?</p>
23,916,580
2
0
null
2014-05-28 15:59:14.79 UTC
6
2014-05-28 16:07:48.517 UTC
null
null
null
null
2,808,712
null
1
19
php|arrays|object|push
85,467
<p>array_push() doesn't allow you to specify keys, only values: use </p> <pre><code>$html_doc["title"] = "testtitle"; </code></pre> <p>.... except you're not working with an array anyway, because you're casting that array to an object, so use</p> <pre><code>$html_doc-&gt;title = "testtitle"; </code></pre>
45,713,593
What is the right way to send a client certificate with every request made by the resttemplate in spring?
<p>i want to consume a REST service with my spring application. To access that service i have a client certificate (self signed and in .jks format) for authorization. What is the proper way to authenticate against the rest service?</p> <p>This is my request:</p> <pre><code>public List&lt;Info&gt; getInfo() throws RestClientException, URISyntaxException { HttpEntity&lt;?&gt; httpEntity = new HttpEntity&lt;&gt;(null, new HttpHeaders()); ResponseEntity&lt;Info[]&gt; resp = restOperations.exchange( new URI(BASE_URL + "/Info"), HttpMethod.GET, httpEntity, Info[].class); return Arrays.asList(resp.getBody()); } </code></pre>
45,717,851
2
0
null
2017-08-16 12:29:40.153 UTC
10
2018-08-01 06:10:35.273 UTC
null
null
null
null
4,925,613
null
1
24
java|spring|x509certificate|resttemplate|client-certificates
54,933
<p>Here is example how to do this using <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html" rel="noreferrer">RestTemplate</a> and <a href="https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/" rel="noreferrer">Apache HttpClient</a></p> <p>You should define your own <code>RestTemplate</code> with configured SSL context:</p> <pre><code>@Bean public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception { char[] password = "password".toCharArray(); SSLContext sslContext = SSLContextBuilder.create() .loadKeyMaterial(keyStore("classpath:cert.jks", password), password) .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); HttpClient client = HttpClients.custom().setSSLContext(sslContext).build(); return builder .requestFactory(new HttpComponentsClientHttpRequestFactory(client)) .build(); } private KeyStore keyStore(String file, char[] password) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); File key = ResourceUtils.getFile(file); try (InputStream in = new FileInputStream(key)) { keyStore.load(in, password); } return keyStore; } </code></pre> <p>Now all remote calls performed by this template will be signed with <code>cert.jks</code>. <strong>Note</strong>: You would need to put <code>cert.jks</code> into your classpath</p> <pre><code>@Autowired private RestTemplate restTemplate; public List&lt;Info&gt; getInfo() throws RestClientException, URISyntaxException { HttpEntity&lt;?&gt; httpEntity = new HttpEntity&lt;&gt;(null, new HttpHeaders()); ResponseEntity&lt;Info[]&gt; resp = restTemplate.exchange( new URI(BASE_URL + "/Info"), HttpMethod.GET, httpEntity, Info[].class); return Arrays.asList(resp.getBody()); } </code></pre>
10,616,131
Repository pattern - Why exactly do we need Interfaces?
<p>I have read from internet I got this points which says Interfaces is used for this</p> <ul> <li>Use TDD methods </li> <li>Replace persistance engine</li> </ul> <p>But I'm not able to understand how interface will be usefull to this point <code>Replace persistance engine</code>. lets consider I'm creating a basic(without generics) repository for <code>EmployeeRepository</code></p> <pre><code>public class EmployeeRepository { public employee[] GetAll() { //here I'll return from dbContext or ObjectContex class } } </code></pre> <p>So how interfaces come into picture?</p> <p>and if suppose i created an interface why upcasting is used ? for e.g</p> <pre><code> IEmployee emp = new EmployeeRepository() ; vs EmployeeRepository emp = new EmployeeRepository(); </code></pre> <p>Please explain me precisely and also other usefullness of Interface in regard to Repository Pattern.</p>
10,616,188
2
0
null
2012-05-16 09:54:44.897 UTC
21
2012-09-07 11:29:11.83 UTC
2012-05-17 05:25:31.557 UTC
null
1,388,948
null
1,388,948
null
1
52
c#|asp.net-mvc-3|repository-pattern
20,736
<blockquote> <p>So how interfaces come into picture ?</p> </blockquote> <p>Like this:</p> <pre><code>public interface IEmployeeRepository { Employee[] GetAll(); } </code></pre> <p>and then you could have as many implementations as you like:</p> <pre><code>public class EmployeeRepositoryEF: IEmployeeRepository { public Employee[] GetAll() { //here you will return employees after querying your EF DbContext } } public class EmployeeRepositoryXML: IEmployeeRepository { public Employee[] GetAll() { //here you will return employees after querying an XML file } } public class EmployeeRepositoryWCF: IEmployeeRepository { public Employee[] GetAll() { //here you will return employees after querying some remote WCF service } } and so on ... you could have as many implementation as you like </code></pre> <p>As you can see it's not really important how we implement the repository. What's important is that all repositories and implementations respect the defined contract (interface) and all posses a <code>GetAll</code> method returning a list of employees.</p> <p>And then you will have a controller which uses this interface.</p> <pre><code>public class EmployeesController: Controller { private readonly IEmployeeRepository _repository; public EmployeesController(IEmployeeRepository repository) { _repository = repository; } public ActionResult Index() { var employees = _repository.GetAll(); return View(employees); } } </code></pre> <p>See how the controller no longer depends on a specific implementation of the repository? All it needs to know is that this implementation respects the contract. Now all that you need to do is to configure your favorite dependency injection framework to use the implementation you wish. </p> <p>Here's an example of how this is done with Ninject:</p> <ol> <li>Install the <a href="https://nuget.org/packages/Ninject.MVC3">Ninject.MVC3</a> NuGet</li> <li><p>In the generated <code>~/App_Start/NinjectWebCommon.cs</code> code you simply decide to use the EF implementation with a single line of code:</p> <pre><code>private static void RegisterServices(IKernel kernel) { kernel.Bind&lt;IEmployeeRepository&gt;().To&lt;EmployeeRepositoryEF&gt;(); } </code></pre></li> </ol> <p>This way you no longer need to do any manual instantiations of those repository classes and worry about upcasting or whatever. It is the dependency injection framework that manages them for you and will take care of injecting the defined implementation into the controller constructor.</p> <p>And by simply modifying this configuration you could switch your data access technology without touching a single line of code in your controller. That's way unit testing in isolation also comes into play. Since your controller code is now weakly coupled to the repository (thanks to the interface we introduced) all you need to do in the unit test is to provide some mock implementation on the repository which allows you to define its behavior. This gives you the possibility to unit test the Index controller action without any dependency on a database or whatever. Complete isolation. </p> <p>I also invite you to checkout the <a href="http://www.asp.net/mvc/overview/dependency-injection">following articles</a> about TDD and DI in ASP.NET MVC.</p>
18,659,992
How to select using WITH RECURSIVE clause
<p>I have googled and read throug some articles like <a href="http://www.postgresql.org/docs/9.1/static/queries-with.html" rel="noreferrer">this postgreSQL manual page</a> or <a href="http://gennick.com/with.html" rel="noreferrer">this blog page</a> and tried making queries myself with a moderate success (part of them hangs, while others works good and fast), but so far I can not <em>completely</em> understand how this <em>magic</em> works.</p> <p>Can anybody give very clear explanation demonstrating such query semantics and execution process, better based on typical samples like factorial calculation or full tree expansion from <code>(id,parent_id,name)</code> table?</p> <p>And what are the basic guidlines and typical mistakes that one should know to make good <code>with recursive</code> queries?</p>
18,660,789
1
0
null
2013-09-06 14:18:28.53 UTC
17
2013-09-06 15:07:22.597 UTC
2013-09-06 14:56:38.16 UTC
null
2,754,703
null
2,754,703
null
1
26
sql|postgresql|recursive-query
32,352
<p>First of all, let us try to simplify and clarify algorithm description given on the <a href="http://www.postgresql.org/docs/9.1/static/queries-with.html">manual page</a>. To simplify it consider only <code>union all</code> in <code>with recursive</code> clause for now (and <code>union</code> later):</p> <pre><code>WITH RECURSIVE pseudo-entity-name(column-names) AS ( Initial-SELECT UNION ALL Recursive-SELECT using pseudo-entity-name ) Outer-SELECT using pseudo-entity-name </code></pre> <p>To clarify it let us describe query execution process in pseudo code:</p> <pre><code>working-recordset = result of Initial-SELECT append working-recordset to empty outer-recordset while( working-recordset is not empty ) begin new working-recordset = result of Recursive-SELECT taking previous working-recordset as pseudo-entity-name append working-recordset to outer-recordset end overall-result = result of Outer-SELECT taking outer-recordset as pseudo-entity-name </code></pre> <p>Or even shorter - Database engine executes initial select, taking its result rows as working set. Then it repeatedly executes recursive select on the working set, each time replacing contents of the working set with query result obtained. This process ends when empty set is returned by recursive select. And all result rows given firstly by initial select and then by recursive select are gathered and feeded to outer select, which result becomes overall query result.</p> <p>This query is calculating <strong>factorial</strong> of 3:</p> <pre><code>WITH RECURSIVE factorial(F,n) AS ( SELECT 1 F, 3 n UNION ALL SELECT F*n F, n-1 n from factorial where n&gt;1 ) SELECT F from factorial where n=1 </code></pre> <p>Initial select <code>SELECT 1 F, 3 n</code> gives us initial values: 3 for argument and 1 for function value. <br>Recursive select <code>SELECT F*n F, n-1 n from factorial where n&gt;1</code> states that every time we need to multiply last funcion value by last argument value and decrement argument value. <br>Database engine executes it like this:</p> <p>First of all it executes initail select, which gives the initial state of working recordset:</p> <pre><code>F | n --+-- 1 | 3 </code></pre> <p>Then it transforms working recordset with recursive query and obtain its second state:</p> <pre><code>F | n --+-- 3 | 2 </code></pre> <p>Then third state:</p> <pre><code>F | n --+-- 6 | 1 </code></pre> <p>In the third state there is no row which follows <code>n&gt;1</code> condition in recursive select, so forth working set is loop exits.</p> <p>Outer recordset now holds all the rows, returned by initial and recursive select:</p> <pre><code>F | n --+-- 1 | 3 3 | 2 6 | 1 </code></pre> <p>Outer select filters out all intermediate results from outer recordset, showing only final factorial value which becomes overall query result:</p> <pre><code>F -- 6 </code></pre> <p>And now let us consider table <code>forest(id,parent_id,name)</code>:</p> <pre><code>id | parent_id | name ---+-----------+----------------- 1 | | item 1 2 | 1 | subitem 1.1 3 | 1 | subitem 1.2 4 | 1 | subitem 1.3 5 | 3 | subsubitem 1.2.1 6 | | item 2 7 | 6 | subitem 2.1 8 | | item 3 </code></pre> <p>'<strong>Expanding full tree</strong>' here means sorting tree items in human-readable depth-first order while calculating their levels and (maybe) paths. Both tasks (of correct sorting and calculating level or path) are not solvable in one (or even any constant number of) SELECT without using WITH RECURSIVE clause (or Oracle CONNECT BY clause, which is not supported by PostgreSQL). But this recursive query does the job (well, almost does, see the note below):</p> <pre><code>WITH RECURSIVE fulltree(id,parent_id,level,name,path) AS ( SELECT id, parent_id, 1 as level, name, name||'' as path from forest where parent_id is null UNION ALL SELECT t.id, t.parent_id, ft.level+1 as level, t.name, ft.path||' / '||t.name as path from forest t, fulltree ft where t.parent_id = ft.id ) SELECT * from fulltree order by path </code></pre> <p>Database engine executes it like this:</p> <p>Firstly, it executes initail select, which gives all highest level items (roots) from <code>forest</code> table:</p> <pre><code>id | parent_id | level | name | path ---+-----------+-------+------------------+---------------------------------------- 1 | | 1 | item 1 | item 1 8 | | 1 | item 3 | item 3 6 | | 1 | item 2 | item 2 </code></pre> <p>Then, it executes recursive select, which gives all 2nd level items from <code>forest</code> table:</p> <pre><code>id | parent_id | level | name | path ---+-----------+-------+------------------+---------------------------------------- 2 | 1 | 2 | subitem 1.1 | item 1 / subitem 1.1 3 | 1 | 2 | subitem 1.2 | item 1 / subitem 1.2 4 | 1 | 2 | subitem 1.3 | item 1 / subitem 1.3 7 | 6 | 2 | subitem 2.1 | item 2 / subitem 2.1 </code></pre> <p>Then, it executes recursive select again, retrieving 3d level items:</p> <pre><code>id | parent_id | level | name | path ---+-----------+-------+------------------+---------------------------------------- 5 | 3 | 3 | subsubitem 1.2.1 | item 1 / subitem 1.2 / subsubitem 1.2.1 </code></pre> <p>And now it executes recursive select again, trying to retrieve 4th level items, but there are none of them, so the loop exits.</p> <p>The outer SELECT sets the correct human-readable row order, sorting on path column:</p> <pre><code>id | parent_id | level | name | path ---+-----------+-------+------------------+---------------------------------------- 1 | | 1 | item 1 | item 1 2 | 1 | 2 | subitem 1.1 | item 1 / subitem 1.1 3 | 1 | 2 | subitem 1.2 | item 1 / subitem 1.2 5 | 3 | 3 | subsubitem 1.2.1 | item 1 / subitem 1.2 / subsubitem 1.2.1 4 | 1 | 2 | subitem 1.3 | item 1 / subitem 1.3 6 | | 1 | item 2 | item 2 7 | 6 | 2 | subitem 2.1 | item 2 / subitem 2.1 8 | | 1 | item 3 | item 3 </code></pre> <p><strong>NOTE</strong>: Resulting row order will remain correct only while there are no punctuation characters collation-preceeding <code>/</code> in the item names. If we rename <code>Item 2</code> in <code>Item 1 *</code>, it will break row order, standing between <code>Item 1</code> and its descendants. <br>More stable solution is using tab character (<code>E'\t'</code>) as path separator in query (which can be substituted by more readable path separator later: in outer select, before displaing to human or etc). Tab separated paths will retain correct order until there are tabs or control characters in the item names - which easily can be checked and ruled out without loss of usability.</p> <p>It is very simple to modify last query to expand any arbitrary subtree - you need only to substitute condition <code>parent_id is null</code> with <code>perent_id=1</code> (for example). Note that this query variant will return all levels and paths <em>relative to</em> <code>Item 1</code>.</p> <p>And now about <strong>typical mistakes</strong>. The most notable typical mistake specific to recursive queries is defining ill stop conditions in recursive select, which results in infinite looping. </p> <p>For example, if we omit <code>where n&gt;1</code> condition in factorial sample above, execution of recursive select will never give an empty set (because we have no condition to filter out single row) and looping will continue infinitely.</p> <p>That is the most probable reason why some of your queries hang (the other non-specific but still possible reason is very ineffective select, which executes in finite but very long time).</p> <p>There are not much RECURSIVE-specific querying <strong>guidlines</strong> to mention, as far as I know. But I would like to suggest (rather obvious) step by step recursive query building procedure.</p> <ul> <li><p>Separately build and debug your initial select.</p></li> <li><p>Wrap it with scaffolding WITH RECURSIVE construct <br>and begin building and debugging your recursive select.</p></li> </ul> <p>The recommended scuffolding construct is like this:</p> <pre><code>WITH RECURSIVE rec( &lt;Your column names&gt; ) AS ( &lt;Your ready and working initial SELECT&gt; UNION ALL &lt;Recursive SELECT that you are debugging now&gt; ) SELECT * from rec limit 1000 </code></pre> <p>This simplest outer select will output the whole outer recordset, which, as we know, contains all output rows from initial select and every execution of recusrive select in a loop in their original output order - just like in samples above! The <code>limit 1000</code> part will prevent hanging, replacing it with oversized output in which you will be able to see the missed stop point.</p> <ul> <li>After debugging initial and recursive select build and debug your outer select.</li> </ul> <p>And now the last thing to mention - the difference in using <strong><code>union</code></strong> instead of <code>union all</code> in <code>with recursive</code> clause. It introduces row uniqueness constraint which results in two extra lines in our execution pseudocode:</p> <pre><code>working-recordset = result of Initial-SELECT discard duplicate rows from working-recordset /*union-specific*/ append working-recordset to empty outer-recordset while( working-recordset is not empty ) begin new working-recordset = result of Recursive-SELECT taking previous working-recordset as pseudo-entity-name discard duplicate rows and rows that have duplicates in outer-recordset from working-recordset /*union-specific*/ append working-recordset to outer-recordset end overall-result = result of Outer-SELECT taking outer-recordset as pseudo-entity-name </code></pre>
35,605,408
Dagger 2 injection in non Activity Java class
<p>I am trying to use Dagger2 for DI, it works perfectly fine for Activity/Fragment related classes where there is a onCreate lifecycle event. Now I have a plain Java class which I want to be injected. Any ideas as to how to go about it would be appreciated. The code I have looks like this :</p> <p>BasicMoviesUsecaseComponent.java - </p> <pre><code>@PerActivity @Component(dependencies = AppComponent.class, modules = BasicMoviesUsecasesModule.class) public interface BasicMoviesUsecasesComponent { void inject(PaymentsManager paymentsManager); } </code></pre> <p>DatabaseModule.java - </p> <pre><code> @Module public class DatabaseModule { @Provides @Singleton Realm provideRealmInstance(Context context) { return Realm.getInstance(context); } @Provides @Singleton DatabaseProvider provideDatabaseInstance(Realm realm) { return new DatabaseProvider(realm); } @Provides @Singleton SharedPreferences provideSharedPrefs(Context context) { return context.getSharedPreferences(context.getPackageName()+"_prefs", Context.MODE_PRIVATE); } @Provides @Singleton SharedPreferencesManager provideSharedPreferencesManager(SharedPreferences sharedPreferences) { return new SharedPreferencesManager(sharedPreferences); } @Provides @Singleton PaymentsManager providePaymentsManager(SharedPreferencesManager sharedPreferencesManager) { return new PaymentsManager(sharedPreferencesManager); } } </code></pre> <p>AppComponent.java - </p> <pre><code> @Singleton @Component(modules = { ApplicationModule.class, DomainModule.class, DatabaseModule.class }) public interface AppComponent { Bus bus(); Realm realm(); DatabaseProvider dbProvider(); SharedPreferencesManager sharedPreferencesManager(); } </code></pre> <p>Here is the class I need to inject the SharedPreferencesManager into and I am unable to do so :</p> <p>MyManager.java - </p> <pre><code> private class MyManager { private SharedPreferencesManager manager; @Inject MyManager(SharedPreferencesManager manager){ this.manager = manager; } private void initializeDependencyInjector() { BMSApplication app = BMSApplication.getInstance(); DaggerBasicMoviesUsecasesComponent.builder() .appComponent(app.getAppComponent()) .basicMoviesUsecasesModule(new BasicMoviesUsecasesModule()) .build().inject(PaymentsManager.this); } } </code></pre> <p>How do I call initializeDependencyInjector() ? </p>
35,615,857
2
0
null
2016-02-24 14:51:57.917 UTC
14
2020-05-11 07:50:55.23 UTC
null
null
null
null
1,542,720
null
1
28
java|android|dependency-injection|dagger-2
16,512
<p>You should generally use constructor injection whenever possible. The call to <code>component.inject(myObject)</code> is mostly to be used for objects which you can not instantiate yourself (like activities or fragments).</p> <p>Constructor injection is basically what you already did:</p> <pre><code>private class MyManager { private SharedPreferencesManager manager; @Inject MyManager(SharedPreferencesManager manager){ this.manager = manager; } } </code></pre> <p>Dagger will create the object for you and pass in your <code>SharedPreferencesManager</code>. There is no need to call init or something similar.</p> <p>The real question is how to <em>obtain</em> an object of <code>MyManager</code>. To do so, again, dagger will handle it for you.</p> <p>By annotating the constructor with <code>@Inject</code> you tell dagger how it can create an object of that type. To use it, just inject it or declare it as a dependency.</p> <pre><code>private class MyActivity extends Activity { @Inject MyManager manager; public void onCreate(Bundle savedState){ component.inject(this); } } </code></pre> <p>Or just add a getter to a component (as long as <code>SharedPreferenceManager</code> can be provided, <code>MyManager</code> can also be instantiated):</p> <pre><code>@Component(dependencies = SharedPreferenceManagerProvidingComponent.class) public interface MyComponent { MyManager getMyManager(); } </code></pre>
35,592,750
How does for<> syntax differ from a regular lifetime bound?
<p>Consider the following code:</p> <pre><code>trait Trait&lt;T&gt; {} fn foo&lt;'a&gt;(_b: Box&lt;dyn Trait&lt;&amp;'a usize&gt;&gt;) {} fn bar(_b: Box&lt;dyn for&lt;'a&gt; Trait&lt;&amp;'a usize&gt;&gt;) {} </code></pre> <p>Both functions <code>foo</code> and <code>bar</code> seem to accept a <code>Box&lt;Trait&lt;&amp;'a usize&gt;&gt;</code>, although <code>foo</code> does it more concisely than <code>bar</code>. What is the difference between them?</p> <p>Additionally, in what situations would I need <code>for&lt;&gt;</code> syntax like that above? I know the Rust standard library uses it internally (often related to closures), but why might my code need it?</p>
35,595,491
1
0
null
2016-02-24 03:35:20.25 UTC
57
2019-09-26 15:26:43.43 UTC
2019-09-26 15:26:43.43 UTC
null
1,830,736
null
1,830,736
null
1
101
rust
9,349
<p><code>for&lt;&gt;</code> syntax is called <em>higher-ranked trait bound</em> (HRTB), and it was indeed introduced mostly because of closures.</p> <p>In short, the difference between <code>foo</code> and <code>bar</code> is that in <code>foo()</code> the lifetime for the internal <code>usize</code> reference is provided <em>by the caller</em> of the function, while in <code>bar()</code> the same lifetime is provided <em>by the function itself</em>. And this distinction is very important for the implementation of <code>foo</code>/<code>bar</code>.</p> <p>However, in this particular case, when <code>Trait</code> has no methods which use the type parameter, this distinction is pointless, so let's imagine that <code>Trait</code> looks like this:</p> <pre><code>trait Trait&lt;T&gt; { fn do_something(&amp;self, value: T); } </code></pre> <p>Remember, lifetime parameters are very similar to generic type parameters. When you use a generic function, you always specify all of its type parameters, providing concrete types, and the compiler monomorphizes the function. Same thing goes with lifetime parameters: when you call a function which have a lifetime parameter, <em>you</em> specify the lifetime, albeit implicitly:</p> <pre><code>// imaginary explicit syntax // also assume that there is TraitImpl::new::&lt;T&gt;() -&gt; TraitImpl&lt;T&gt;, // and TraitImpl&lt;T&gt;: Trait&lt;T&gt; 'a: { foo::&lt;'a&gt;(Box::new(TraitImpl::new::&lt;&amp;'a usize&gt;())); } </code></pre> <p>And now there is a restriction on what <code>foo()</code> can do with this value, that is, with which arguments it may call <code>do_something()</code>. For example, this won't compile:</p> <pre><code>fn foo&lt;'a&gt;(b: Box&lt;Trait&lt;&amp;'a usize&gt;&gt;) { let x: usize = 10; b.do_something(&amp;x); } </code></pre> <p>This won't compile because local variables have lifetimes which are strictly smaller than lifetimes specified by the lifetime parameters (I think it is clear why it is so), therefore you can't call <code>b.do_something(&amp;x)</code> because it requires its argument to have lifetime <code>'a</code>, which is strictly greater than that of <code>x</code>.</p> <p>However, you can do this with <code>bar</code>:</p> <pre><code>fn bar(b: Box&lt;for&lt;'a&gt; Trait&lt;&amp;'a usize&gt;&gt;) { let x: usize = 10; b.do_something(&amp;x); } </code></pre> <p>This works because now <code>bar</code> can select the needed lifetime instead of the caller of <code>bar</code>.</p> <p>This does matter when you use closures which accept references. For example, suppose you want to write a <code>filter()</code> method on <code>Option&lt;T&gt;</code>:</p> <pre><code>impl&lt;T&gt; Option&lt;T&gt; { fn filter&lt;F&gt;(self, f: F) -&gt; Option&lt;T&gt; where F: FnOnce(&amp;T) -&gt; bool { match self { Some(value) =&gt; if f(&amp;value) { Some(value) } else { None } None =&gt; None } } } </code></pre> <p>The closure here must accept a reference to <code>T</code> because otherwise it would be impossible to return the value contained in the option (this is the same reasoning as with <code>filter()</code> on iterators).</p> <p>But what lifetime should <code>&amp;T</code> in <code>FnOnce(&amp;T) -&gt; bool</code> have? Remember, we don't specify lifetimes in function signatures only because there is lifetime elision in place; actually the compiler inserts a lifetime parameter for each reference inside a function signature. There <em>should</em> be <em>some</em> lifetime associated with <code>&amp;T</code> in <code>FnOnce(&amp;T) -&gt; bool</code>. So, the most "obvious" way to expand the signature above would be this:</p> <pre><code>fn filter&lt;'a, F&gt;(self, f: F) -&gt; Option&lt;T&gt; where F: FnOnce(&amp;'a T) -&gt; bool </code></pre> <p>However, this is not going to work. As in the example with <code>Trait</code> above, lifetime <code>'a</code> is <em>strictly longer</em> than the lifetime of any local variable in this function, including <code>value</code> inside the match statement. Therefore, it is not possible to apply <code>f</code> to <code>&amp;value</code> because of lifetime mismatch. The above function written with such signature won't compile.</p> <p>On the other hand, if we expand the signature of <code>filter()</code> like this (and this is actually how lifetime elision for closures works in Rust now):</p> <pre><code>fn filter&lt;F&gt;(self, f: F) -&gt; Option&lt;T&gt; where F: for&lt;'a&gt; FnOnce(&amp;'a T) -&gt; bool </code></pre> <p>then calling <code>f</code> with <code>&amp;value</code> as an argument is perfectly valid: <em>we</em> can choose the lifetime now, so using the lifetime of a local variable is absolutely fine. And that's why HRTBs are important: you won't be able to express a lot of useful patterns without them.</p> <p>You can also read another explanation of HRTBs in <a href="https://doc.rust-lang.org/nightly/nomicon/hrtb.html">Nomicon</a>.</p>
19,175,089
Eclipse project-wide error: Warning: The environment variable HOME is not set. The following directory will be used to store the Git
<p>Started Eclipse and got this error. How do I fix it?</p> <pre><code>Warning: The environment variable HOME is not set. The following directory will be used to store the Git user global configuration and to define the default location to store repositories: 'C:\Documents and Settings\Wizard'. If this is not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and EGit might behave differently since they see different configuration options. This warning can be switched off on the Team &gt; Git &gt; Confirmations and Warnings preference page. </code></pre> <p>If any additional information is needed, let me know and I will provide it.</p>
19,175,190
6
0
null
2013-10-04 06:53:32.647 UTC
9
2019-04-07 12:08:23.947 UTC
2014-07-13 13:03:18.58 UTC
null
1,287,093
null
2,576,903
null
1
31
eclipse|git|egit
111,758
<p>You need to set the JAVA_HOME variable in your system. Depends on your Operating system you can check for "How to set Environment variable?" and from that point you need to set environment variable</p> <p>Variable Name : JAVA_HOME Value : Path of Java upto bin folder</p> <ol> <li>In Windows 7, type "environment" at the start menu </li> <li>Select "Edit environment variables for your account"</li> <li>Click the "New" button.</li> <li>Enter "HOME" in the name field</li> <li>Enter "%USERPROFILE%" or some other path in the value field.</li> <li>Click OK, and OK again. You have just added the Home directory on Windows.</li> </ol>
19,002,378
Applying a function to two lists?
<p>To find the row-wise correlation of two matrices X and Y, the output should have a correlation value for row 1 of X and row 1 of Y, ..., hence in total ten values (because there are ten rows):</p> <pre><code>X &lt;- matrix(rnorm(2000), nrow=10) Y &lt;- matrix(rnorm(2000), nrow=10) sapply(1:10, function(row) cor(X[row,], Y[row,])) </code></pre> <p>Now, how should I <strong>apply this function to two lists (containing around 50 dataframes each)?</strong></p> <p>Consider list A has dataframes $1, $2, $3... and so on and list B has similar number of dataframes $1, $2, $3. So the function should be applied to <code>listA$1,listB$1</code> and <code>listA$2,listB$2</code> ... and so on for other dataframes in the list. In the end I will have ten values in case of comparison 1 (<code>listA$1</code> and <code>listB$1</code>) and for others as well.</p> <p>Could this be done using "lapply"?</p>
19,002,916
1
0
null
2013-09-25 10:25:28.913 UTC
4
2018-09-21 19:50:38.287 UTC
2018-09-21 19:50:38.287 UTC
null
6,888,231
null
2,810,362
null
1
29
r|parameter-passing|apply|mapply
24,255
<p>You seem to be looking for <code>mapply</code>. Here's an example:</p> <pre><code>listA &lt;- list(matrix(rnorm(2000), nrow=10), matrix(rnorm(2000), nrow=10)) listB &lt;- list(matrix(rnorm(2000), nrow=10), matrix(rnorm(2000), nrow=10)) mapply(function(X,Y) { sapply(1:10, function(row) cor(X[row,], Y[row,])) }, X=listA, Y=listB) </code></pre>
30,035,932
How do I use this JavaScript variable in HTML?
<p>I'm trying to make a simple page that asks you for your name, and then uses name.length (JavaScript) to figure out how long your name is.</p> <p>This is my code so far:</p> <pre><code>&lt;script&gt; var name = prompt("What's your name?"); var lengthOfName = name.length &lt;/script&gt; &lt;body&gt; &lt;/body&gt; </code></pre> <p>I'm not quite sure what to put within the body tags so that I can use those variables that I stated before. I realize that this is probably a really beginner level question, but I can't seem to find the answer.</p>
30,036,015
8
2
null
2015-05-04 17:12:46.03 UTC
18
2022-09-22 11:21:57.443 UTC
2015-05-05 05:03:34.783 UTC
null
2,034,696
null
4,863,221
null
1
44
javascript|html|variables
347,399
<p>You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.</p> <p>If you want to display a variable on the screen, this is done with JavaScript.</p> <p>First, you need somewhere for it to write to:</p> <pre><code>&lt;body&gt; &lt;p id="output"&gt;&lt;/p&gt; &lt;/body&gt; </code></pre> <p>Then you need to update your JavaScript code to write to that <code>&lt;p&gt;</code> tag. Make sure you do so <em>after</em> the page is ready.</p> <pre><code>&lt;script&gt; window.onload = function(){ var name = prompt("What's your name?"); var lengthOfName = name.length document.getElementById('output').innerHTML = lengthOfName; }; &lt;/script&gt; </code></pre> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>window.onload = function() { var name = prompt("What's your name?"); var lengthOfName = name.length document.getElementById('output').innerHTML = lengthOfName; };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p id="output"&gt;&lt;/p&gt;</code></pre> </div> </div> </p>
25,557,874
Elastic beanstalk deployment taking longer than timeout period, how do I increase timeout period
<p>Elastic beanstalk deployment of a new environment for an application using the AWS website warns</p> <pre><code>Create environment operation is complete, but with command timeouts. Try increasing the timeout period </code></pre> <p>and although it eventually shows environment as green trying to connect to the url just gives</p> <pre><code>Service Temporarily Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. </code></pre> <p>An earlier version of the application works fine, but in the ebextensions it has to copy a large file from s3 and then unzip it, this takes quite a while. The earlier version of the application only has to copy a 3GB file but the new version has to copy a 6GB file and as I can see no other errors Im guessing this has caused the timeout and prevented tomcat starting.</p> <p>But how do I increase the timeout, I cannot see where I am meant to do it ?</p>
25,558,805
4
0
null
2014-08-28 20:56:53.427 UTC
10
2018-02-01 21:55:15.64 UTC
null
null
null
null
1,480,018
null
1
27
amazon-web-services|amazon-elastic-beanstalk
23,934
<p>You can do this using option settings. Option settings can be specified using ebextensions.</p> <p>Create a file in your app source in a directory called <code>.ebextensions</code>. Lets say the file is <code>.ebextensions/01-increase-timeout.config</code>.</p> <p>The contents of the file should be:</p> <pre><code>option_settings: - namespace: aws:elasticbeanstalk:command option_name: Timeout value: 1000 </code></pre> <p>Note this file is in YAML format. After this you can update your environment with this version of source code.</p> <p>From documentation for this option setting:</p> <blockquote> <p>Timeout: Number of seconds to wait for an instance to complete executing commands.</p> <p>For example, if source code deployment tasks are still running when you reach the configured timeout period, AWS Elastic Beanstalk displays the following error: "Some instances have not responded to commands. Responses were not received from ." You can increase the amount of time that the AWS Elastic Beanstalk service waits for your source code to successfully deploy to the instance.</p> </blockquote> <p>You can read more about ebextensions <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers.html" rel="noreferrer">here</a>. Documentation on option settings is available <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html" rel="noreferrer">here</a>.</p>
8,849,684
WordPress, jQuery UI CSS Files?
<p>I'm trying to create a WordPress plugin, and I would like to have jQuery UI Tabs in one of my settings pages.</p> <p>I already have the scripting code set:</p> <pre><code>wp_enqueue_script('jquery'); // Enque jQuery wp_enqueue_script('jquery-ui-core'); // Enque jQuery UI Core wp_enqueue_script('jquery-ui-tabs'); // Enque jQuery UI Tabs </code></pre> <p>...and I have created the HTML and JavaScript too. Until here all are fine.</p> <p>The question is:</p> <p>The WordPress platform comes with some scripts already pre-installed like the one I have enqueue above. My script runs fine with the tabs, but it is not styled! So what I'm trying to ask, does the WordPress platform come with jQuery UI Theme pre-installed? ...and if so, how do I enqueue the style into my plugin?</p>
11,789,443
6
0
null
2012-01-13 11:13:19.547 UTC
4
2017-11-11 05:34:54.32 UTC
2012-08-18 20:24:19.697 UTC
null
1,376,780
null
366,664
null
1
32
jquery|jquery-ui|wordpress|jquery-ui-css-framework
45,607
<p>Sounds more like you have an issue with finding an available styling within WordPress for the jquery-ui theme.</p> <p>To answer your question. <strong>No, WordPress has no useful styles available within the platform itself.</strong> The only available css is in \wp-includes\jquery-ui-dialog.css, and that alone isn't very useful.</p> <p>I also had the same issue, and I found <strong>two options</strong>. Either store it in a CSS folder and load it from there, or load it via <strong>URL</strong> (Google APIs). For JQuery UI I decided to rely on Google's CDA and added a way to utilize the 'Theme Roller'. Storing that amount of css code seems un-nessecary to begin with, and its too bad WordPress doesn't provide any styling support like they do with the jquery-ui scripts.</p> <p>However, WP does offer scripts, which will keep the CSS up to date with <code>$wp_scripts-&gt;registered['jquery-ui-core']-&gt;ver</code>. You can either access it with <code>wp_scripts();</code> OR <code>global $wp_scripts;</code>.</p> <p>Static-theme</p> <pre><code>$wp_scripts = wp_scripts(); wp_enqueue_style('plugin_name-admin-ui-css', 'http://ajax.googleapis.com/ajax/libs/jqueryui/' . $wp_scripts-&gt;registered['jquery-ui-core']-&gt;ver . '/themes/smoothness/jquery-ui.css', false, PLUGIN_VERSION, false); </code></pre> <p>OR Dynamic-theme</p> <pre><code>$wp_scripts = wp_scripts(); wp_enqueue_style('plugin_name-admin-ui-css', 'http://ajax.googleapis.com/ajax/libs/jqueryui/' . $wp_scripts-&gt;registered['jquery-ui-core']-&gt;ver . '/themes/' . $pluginOptions['jquery_ui_theme'] . '/jquery-ui.css', false, PLUGIN_VERSION, false); </code></pre> <p>And an example of locally storing it</p> <pre><code>wp_enqueue_style('plugin_name-admin-ui-css', plugins_url() . '/plugin-folder-name/includes/css/jquery-ui-theme-name.css', false, PLUGIN_VERSION, false); </code></pre>
8,571,754
Android Split Action Bar with Action Items on the top and bottom?
<p>Is there a way to specify some action items to the top part of the Split Action Bar while the others go to the bottom? Or is it all or nothing, whereby all the action items go to the bottom part of the split only?</p> <p><img src="https://i.stack.imgur.com/STzk0.png" alt="enter image description here"></p>
8,609,144
5
0
null
2011-12-20 06:50:27.067 UTC
27
2015-02-03 07:09:25.047 UTC
2012-05-01 20:52:53.313 UTC
null
723,980
null
723,980
null
1
57
android|android-actionbar|android-menu
42,491
<p>This is currently not possible.</p> <p>See the response directly from Android developers Reto Meier and Roman Nurik during the Android Developer Office Hours: <a href="http://youtu.be/pBmRCBP56-Q?t=55m50s" rel="noreferrer">http://youtu.be/pBmRCBP56-Q?t=55m50s</a></p>
30,681,905
Adding items to Endless Scroll RecyclerView with ProgressBar at bottom
<p>I followed Vilen's excellent answer on SO: <a href="https://stackoverflow.com/questions/27044449/put-an-indeterminate-progressbar-as-footer-in-a-recyclerview-grid/28090719#comment49412644_28090719">Put an indeterminate progressbar as footer in a RecyclerView grid</a> on how to implement an endless scroll recyclerview with ProgressBar.</p> <p>I implemented it myself and it works but I would like to extend the example. I want to add extra items at the top of the recyclerview, similar to how Facebook does it when you add a new status update. </p> <p>I was not able to add extra items onto the list successfully - here is my code that I added onto Vilen's code in his MainActivity:</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.add) { myDataset.add(0, "Newly added"); mRecyclerView.smoothScrollToPosition(0); mAdapter.notifyItemInserted(0); } return super.onOptionsItemSelected(item); } </code></pre> <p>When I clicked the "Add" button:</p> <p><img src="https://i.stack.imgur.com/dhW8I.gif" alt="Adding a new item"></p> <p>When I scroll down, I get two spinners instead of one:</p> <p><img src="https://i.stack.imgur.com/ZsAlc.gif" alt="Scroll down"></p> <p>When the spinners finish and the next 5 items are loaded, the spinner is still there:</p> <p><img src="https://i.stack.imgur.com/BwhM5.gif" alt="after spinner"></p> <p>What am I doing wrong?</p>
30,691,092
2
0
null
2015-06-06 10:48:17.157 UTC
33
2015-12-29 01:26:51.763 UTC
2017-05-23 12:17:50.79 UTC
null
-1
null
3,178,944
null
1
32
android|android-recyclerview|infinite-scroll
46,289
<p>The problem is that when you add new item internal <code>EndlessRecyclerOnScrollListener</code> doesn't know about it and counters breaking. As a matter of fact answer with <code>EndlessRecyclerOnScrollListener</code> has some limitations and possible problems, e.g. if you load 1 item at a time it will not work. So here is an enhanced version.</p> <ol> <li>Get rid of <code>EndlessRecyclerOnScrollListener</code> we don't need it anymore</li> <li><p>Change your adapter to this which contains scroll listener</p> <pre><code>public class MyAdapter&lt;T&gt; extends RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt; { private final int VIEW_ITEM = 1; private final int VIEW_PROG = 0; private List&lt;T&gt; mDataset; // The minimum amount of items to have below your current scroll position before loading more. private int visibleThreshold = 2; private int lastVisibleItem, totalItemCount; private boolean loading; private OnLoadMoreListener onLoadMoreListener; public MyAdapter(List&lt;T&gt; myDataSet, RecyclerView recyclerView) { mDataset = myDataSet; if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) { final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); totalItemCount = linearLayoutManager.getItemCount(); lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition(); if (!loading &amp;&amp; totalItemCount &lt;= (lastVisibleItem + visibleThreshold)) { // End has been reached // Do something if (onLoadMoreListener != null) { onLoadMoreListener.onLoadMore(); } loading = true; } } }); } } @Override public int getItemViewType(int position) { return mDataset.get(position) != null ? VIEW_ITEM : VIEW_PROG; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { RecyclerView.ViewHolder vh; if (viewType == VIEW_ITEM) { View v = LayoutInflater.from(parent.getContext()) .inflate(android.R.layout.simple_list_item_1, parent, false); vh = new TextViewHolder(v); } else { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.progress_item, parent, false); vh = new ProgressViewHolder(v); } return vh; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof TextViewHolder) { ((TextViewHolder) holder).mTextView.setText(mDataset.get(position).toString()); } else { ((ProgressViewHolder) holder).progressBar.setIndeterminate(true); } } public void setLoaded() { loading = false; } @Override public int getItemCount() { return mDataset.size(); } public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) { this.onLoadMoreListener = onLoadMoreListener; } public interface OnLoadMoreListener { void onLoadMore(); } public static class TextViewHolder extends RecyclerView.ViewHolder { public TextView mTextView; public TextViewHolder(View v) { super(v); mTextView = (TextView) v.findViewById(android.R.id.text1); } } public static class ProgressViewHolder extends RecyclerView.ViewHolder { public ProgressBar progressBar; public ProgressViewHolder(View v) { super(v); progressBar = (ProgressBar) v.findViewById(R.id.progressBar); } } } </code></pre></li> <li><p>Change code in Activity class</p> <pre><code>mAdapter = new MyAdapter&lt;String&gt;(myDataset, mRecyclerView); mRecyclerView.setAdapter(mAdapter); mAdapter.setOnLoadMoreListener(new MyAdapter.OnLoadMoreListener() { @Override public void onLoadMore() { //add progress item myDataset.add(null); mAdapter.notifyItemInserted(myDataset.size() - 1); handler.postDelayed(new Runnable() { @Override public void run() { //remove progress item myDataset.remove(myDataset.size() - 1); mAdapter.notifyItemRemoved(myDataset.size()); //add items one by one for (int i = 0; i &lt; 15; i++) { myDataset.add("Item" + (myDataset.size() + 1)); mAdapter.notifyItemInserted(myDataset.size()); } mAdapter.setLoaded(); //or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged(); } }, 2000); System.out.println("load"); } }); </code></pre></li> </ol> <p>The rest remains unchanged, let me know if this works for you.</p>
43,556,311
Reading settings from a Azure Function
<p>I'm new to <a href="https://docs.microsoft.com/en-us/azure/azure-functions/" rel="noreferrer">Azure's function</a>... I've created a new timer function (will be fired every 30 minutes) and it has to perform a query on a URL, then push data on the buffer..</p> <p>I've done</p> <pre><code>public static void Run(TimerInfo myTimer, TraceWriter log) { var s = CloudConfigurationManager.GetSetting(&quot;url&quot;); log.Info(s); } </code></pre> <p>And in my function settings I've</p> <p><a href="https://i.stack.imgur.com/YOART.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/YOART.jpg" alt="enter image description here" /></a></p> <p>What am I doing wrong? Thanks</p>
53,171,338
6
0
null
2017-04-22 07:02:41.85 UTC
8
2022-08-22 14:41:39.713 UTC
2021-11-30 16:13:53.473 UTC
null
4,294,399
null
1,278,204
null
1
32
c#|azure|azure-functions
37,281
<p>You can use <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables" rel="noreferrer"><code>System.Environment.GetEnvironmentVariable</code></a> like this: </p> <pre class="lang-cs prettyprint-override"><code>var value = Environment.GetEnvironmentVariable("your_key_here") </code></pre> <p>This gets settings whenever you're working locally or on Azure.</p>
585,913
C++ member function virtual override and overload at the same time
<p>If I have a code like this:</p> <pre><code>struct A { virtual void f(int) {} virtual void f(void*) {} }; struct B : public A { void f(int) {} }; struct C : public B { void f(void*) {} }; int main() { C c; c.f(1); return 0; } </code></pre> <p>I get an error that says that I am trying to do an invalid conversion from int to void*. Why can't compiler figure out that he has to call B::f, since both functions are declared as virtual?</p> <hr> <p>After reading jalf's answer I went and reduced it even further. This one does not work as well. Not very intuitive.</p> <pre><code>struct A { virtual void f(int) {} }; struct B : public A { void f(void*) {} }; int main() { B b; b.f(1); return 0; } </code></pre>
585,932
3
0
null
2009-02-25 13:04:55.48 UTC
13
2014-04-01 21:49:24.91 UTC
2009-02-25 13:47:38.777 UTC
bombardier
23,766
bombardier
23,766
null
1
30
c++|inheritance|polymorphism|virtual
10,572
<p>The short answer is "because that's how overload resolution works in C++".</p> <p>The compiler searches for functions F inside the C class, and if it finds any, it stops the search, and tries to pick a candidate among those. It only looks inside base classes if no matching functions were found in the derived class.</p> <p>However, you can explicitly introduce the base class functions into the derived class' namespace:</p> <pre><code>struct C : public B { void f(void*) {} using B::f; // Add B's f function to C's namespace, allowing it to participate in overload resolution }; </code></pre>
648,083
SQL error: misuse of aggregate
<p>SQLite version 3.4.0 What's wrong with aggregate functions? Additionally, I suspect that ORDER BY won't work as well. How to rewrite this? </p> <pre><code>sqlite&gt; SELECT p1.domain_id, p2.domain_id, COUNT(p1.domain_id) AS d1, COUNT(p2.domain_id) AS d2 ...&gt; FROM PDB as p1, Interacting_PDBs as i1, PDB as p2, Interacting_PDBs as i2 ...&gt; WHERE p1.id = i1.PDB_first_id ...&gt; AND p2.id = i2.PDB_second_id ...&gt; AND i1.id = i2.id ...&gt; AND d1&gt;100 ...&gt; AND d2&gt;100 ...&gt; ORDER BY d1, d2; SQL error: misuse of aggregate: sqlite&gt; </code></pre>
648,089
3
0
null
2009-03-15 16:29:40.623 UTC
8
2022-09-14 20:42:40.763 UTC
null
null
null
piobyz
78,305
null
1
31
sql|sqlite
62,747
<p>When using an aggregate function (sum / count / ... ), you also have to make use of the GROUP BY clause.</p> <p>Next to that, when you want to filter on the result of an aggregate , you cannot do that in the WHERE clause, but you have to do that in the HAVING clause.</p> <pre><code>SELECT p1.domain_id, p2.domain_id, COUNT(p1.domain_id) AS d1, COUNT(p2.domain_id) AS d2 FROM PDB as p1, Interacting_PDBs as i1, PDB as p2, Interacting_PDBs as i2 WHERE p1.id = i1.PDB_first_id AND p2.id = i2.PDB_second_id AND i1.id = i2.id GROUP BY p1.domain_Id, p2.domain_Id HAVING d1 &gt; 100 AND d2 &gt; 100 ORDER BY d1, d2; </code></pre>
858,225
configSource doesn't work in system.serviceModel *or* its subsections
<p>I'm trying to split an app.config file into multiple files to make it easier to manage the differences needed for different environments. With some sections it was easy...</p> <pre class="lang-xml prettyprint-override"><code>&lt;system.diagnostics&gt; various stuff &lt;/system.diagnostics&gt; </code></pre> <p>became</p> <pre class="lang-xml prettyprint-override"><code>&lt;system.diagnostics configSource="ConfigFiles\system.diagnostics.dev" /&gt; </code></pre> <p>with the "various stuff" moved to the system.diagnostics.dev file.</p> <p>But for the <code>system.serviceModel</code> section this doesn't seem to work.</p> <p>Now I've read suggestions that it doesn't work for <code>system.serviceModel</code> itself, but it works for the sections underneath it: <code>bindings</code>, <code>client</code>, <code>diagnostics</code>, etc. But the same thing happens to me when I try to use configSource with one of them. When I put in</p> <pre class="lang-xml prettyprint-override"><code>&lt;system.serviceModel&gt; &lt;bindings configSource="ConfigFiles\whateverFile.dev" /&gt; </code></pre> <p>I get:</p> <p><strong>The 'configSource' attribute is not declared.</strong></p> <p>Has anyone else seen this? Do you know a solution? (Perhaps I have an out-of-date schema or something?)</p>
858,320
3
2
null
2009-05-13 14:18:29.9 UTC
9
2016-07-27 11:20:47.223 UTC
2016-07-27 11:20:47.223 UTC
null
672,891
null
5,486
null
1
35
c#|.net|winforms|wcf|configuration
16,407
<p>VS.NET's editor moans about the config, but it works.</p> <p>I have config like this...</p> <pre class="lang-xml prettyprint-override"><code>&lt;system.serviceModel&gt; &lt;behaviors configSource="config\system.servicemodel.behaviors.config" /&gt; &lt;bindings configSource="config\system.servicemodel.bindings.config" /&gt; &lt;client configSource="config\system.servicemodel.client.config" /&gt; &lt;/system.serviceModel&gt; </code></pre> <p>... which works fine.</p>
34,401
Send email from Elmah?
<p>Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by * * *. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine?</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;sectionGroup name="elmah"&gt; &lt;section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/&gt; &lt;section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/&gt; &lt;section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/&gt; &lt;/sectionGroup&gt; &lt;/configSections&gt; &lt;appSettings/&gt; &lt;connectionStrings&gt; &lt;add name="elmah-sql" connectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***" /&gt; &lt;/connectionStrings&gt; &lt;elmah&gt; &lt;errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sql" &gt; &lt;/errorLog&gt; &lt;errorMail from="[email protected]" to="[email protected]" subject="Application Exception" async="false" smtpPort="25" smtpServer="***" userName="***" password="***"&gt; &lt;/errorMail&gt; &lt;/elmah&gt; &lt;system.web&gt; &lt;customErrors mode="RemoteOnly" defaultRedirect="CustomError.aspx"&gt; &lt;error statusCode="403" redirect="NotAuthorized.aspx" /&gt; &lt;!--&lt;error statusCode="404" redirect="FileNotFound.htm" /&gt;--&gt; &lt;/customErrors&gt; &lt;httpHandlers&gt; &lt;remove verb="*" path="*.asmx"/&gt; &lt;add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/&gt; &lt;add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" /&gt; &lt;/httpHandlers&gt; &lt;httpModules&gt; &lt;add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; &lt;add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/&gt; &lt;/httpModules&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre>
34,435
3
0
null
2008-08-29 14:56:47.68 UTC
33
2012-05-11 14:11:15.1 UTC
null
null
null
Mark Struzinski
1,284
null
1
90
.net|asp.net|elmah
34,114
<p>You need the ErrorMail httpModule.</p> <p>add this line inside the &lt;httpModules&gt; section</p> <pre><code>&lt;add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" /&gt; </code></pre> <p>If you're using a remote SMTP server (which it looks like you are) you don't need SMTP on the server.</p>
6,733,684
Run ant from Java
<p>Is there a tutorial on how to run Ant from Java? I got some code from here: <a href="https://stackoverflow.com/questions/652053/setting-java-home-when-running-ant-from-java">Setting JAVA_HOME when running Ant from Java</a></p> <p>But haven't been able to make it work. I've been trying to find an example or tutorial on how to actually use it.</p> <p>Here's what I have so far:</p> <pre> Project p = new Project(); p.setUserProperty("ant.file", buildFile.getAbsolutePath()); p.fireBuildStarted(); p.init(); p.executeTarget("default"); </pre> <p>But I guess this error:</p> <pre> Exception in thread "main" Target "default" does not exist in the project "null". at org.apache.tools.ant.Project.tsort(Project.java:1912) at org.apache.tools.ant.Project.topoSort(Project.java:1820) at org.apache.tools.ant.Project.topoSort(Project.java:1783) at org.apache.tools.ant.Project.executeTarget(Project.java:1368) at com.arthrocare.vss2svn.VSS2SVN.newProcess(VSS2SVN.java:128) at com.arthrocare.vss2svn.VSS2SVN.main(VSS2SVN.java:52) Java Result: 1 </pre> <p>I tried specifying the project with:</p> <pre> p.setUserProperty("ant.project.name", "VSS Project"); </pre> <p>But no luck.</p> <p>The ant file specified is correct as it works perfectly from the command line.</p> <p><strong>UPDATE</strong></p> <p>After some more searching I got here: <a href="http://onjava.com/pub/a/onjava/2002/07/24/antauto.html?page=1" rel="noreferrer">http://onjava.com/pub/a/onjava/2002/07/24/antauto.html?page=1</a></p> <p>It is a great tutorial.</p> <p>Here's the code I got a little bit earlier than seeing the code in the answer below:</p> <pre> Project project = new Project(); ProjectHelper.configureProject(project, buildFile); DefaultLogger consoleLogger = new DefaultLogger(); consoleLogger.setErrorPrintStream(System.err); consoleLogger.setOutputPrintStream(System.out); consoleLogger.setMessageOutputLevel(Project.MSG_INFO); project.addBuildListener(consoleLogger); project.init(); project.executeTarget(project.getDefaultTarget()); </pre> <p>But for some reason the task still fails! I'm using a Visual Source Safe task that needs to read an environment value at runtime but it doesn't see it with this approach. Running the build.xml file manually and with the following code works:</p> <pre> ProcessBuilder pb = new ProcessBuilder(); Map env = pb.environment(); String path = env.get("ANT_HOME"); System.out.println(path); pb.directory(new File(System.getProperty("user.home"))); pb.command(path + System.getProperty("file.separator") + "bin" + System.getProperty("file.separator") + "ant.bat"); try { Process p = pb.start(); } catch (IOException ex) { // } </pre>
6,733,831
1
0
null
2011-07-18 13:31:54.51 UTC
15
2013-07-26 12:35:39.937 UTC
2017-05-23 12:24:58.297 UTC
null
-1
null
198,108
null
1
15
java|ant
35,046
<blockquote> <p>Is there a tutorial on how to run Ant from Java?</p> </blockquote> <p>Part of my answer to <a href="https://stackoverflow.com/questions/6440295/is-it-possible-to-call-ant-or-nsis-script-via-java-code/6440342#6440342">this question</a> might help:</p> <blockquote> <p>See <a href="http://ant.apache.org/manual/running.html#viajava" rel="noreferrer">this article</a> and <a href="http://www.ibm.com/developerworks/websphere/library/techarticles/0502_gawor/0502_gawor.html#sec2b" rel="noreferrer">this article</a>:</p> <pre><code> File buildFile = new File("build.xml"); Project p = new Project(); p.setUserProperty("ant.file", buildFile.getAbsolutePath()); p.init(); ProjectHelper helper = ProjectHelper.getProjectHelper(); p.addReference("ant.projectHelper", helper); helper.parse(p, buildFile); p.executeTarget(p.getDefaultTarget()); </code></pre> </blockquote>
36,645,698
Error Message: "Project build error: Non-parseable POM
<pre><code>&lt;project &gt;xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.cucumber&lt;/groupId&gt; &lt;artifactId&gt;MavenCucumberPrototype&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;MavenCucumberPrototype&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;/properties&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.11&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;info.cukes&lt;/groupId&gt; &lt;artifactId&gt;cucumber-java&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;info.cukes&lt;/groupId&gt; &lt;artifactId&gt;cucumber-picocontainer&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;info.cukes&lt;/groupId&gt; &lt;artifactId&gt;cucumber-junit&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/project&gt; </code></pre>
36,645,817
5
2
null
2016-04-15 11:17:07.263 UTC
3
2020-01-07 10:09:02.037 UTC
2016-04-15 11:38:54.077 UTC
null
3,365,750
null
6,208,815
null
1
4
java|maven
44,655
<p>You've got an end-tag <em>dependencies</em> but no start-tag <em>dependencies</em></p> <p>(missing tag should be between properties-tag and firts dependency)</p>
42,655,177
How can I delete a file only if it exists?
<p>I have a shell script and I want to add a line or two where it would remove a log file only if it exists. Currently my script simply does:</p> <pre><code>rm filename.log </code></pre> <p>However if the filename doesn't exist I get a message saying filename.log does not exist, cannot remove. This makes sense but I don't want to keep seeing that every time I run the script. Is there a smarter way with an IF statement I can get this done?</p>
42,655,267
4
1
null
2017-03-07 18:02:05.93 UTC
2
2018-11-30 05:35:18.147 UTC
2017-03-07 18:21:48.8 UTC
null
6,862,601
null
7,649,922
null
1
35
shell
47,057
<p>Pass the <code>-f</code> argument to <code>rm</code>, which will cause it to treat the situation where the named file does not exist as success, and will suppress any error message in that case:</p> <pre><code>rm -f -- filename.log </code></pre> <p>What you <em>literally</em> asked for would be more like:</p> <pre><code>[ -e filename.log ] &amp;&amp; rm -- filename.log </code></pre> <p>but it's more to type and adds extra failure modes. (If something else deleted the file after <code>[</code> tests for it but before <code>rm</code> deletes it, then you're back at having a failure again).</p> <p>As an aside, the <code>--</code>s cause the filename to be treated as literal even if it starts with a leading dash; you should use these habitually if your names are coming from variables or otherwise not strictly controlled.</p>
20,056,847
JPQL: The state field path cannot be resolved to a valid type
<p>I can't make this query work: </p> <pre><code>Query query = eManager.createQuery("select c FROM News c WHERE c.NEWSID = :id",News.class); return (News)query.setParameter("id", newsId).getSingleResult(); </code></pre> <p>and I got this exception: </p> <pre><code>Exception Description: Problem compiling [select c FROM News c WHERE c.NEWSID = :id]. [27, 35] The state field path 'c.NEWSID' cannot be resolved to a valid type.] with root cause Local Exception Stack: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException Exception Description: Problem compiling [select c FROM News c WHERE c.NEWSID = :id]. </code></pre> <p>Why does it happen? :id and named parameter are identical </p> <p><strong>EDIT:</strong> my entity class</p> <pre><code>@Entity @Table(name="NEWS") public class News implements Serializable{ @Id @SequenceGenerator(name = "news_seq_gen", sequenceName = "news_seq") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "news_seq_gen") private int newsId; private String newsTitle; private String newsBrief; private String newsContent; private Date newsDate; @Transient private boolean selected=false; //constructor and getters and setters </code></pre>
20,057,104
3
0
null
2013-11-18 20:08:45.15 UTC
2
2017-03-31 16:56:47.307 UTC
2016-03-03 07:59:02.24 UTC
null
1,471,604
null
1,745,345
null
1
9
jpql
42,470
<p>That happens because <code>News</code> entity does not have persistent attribute named <code>NEWSID</code>. Names of the persistent attributes are case sensitive in JPQL queries and those should be written with exactly same case as they appear in entity.</p> <p>Because entity have persistent attribute named <code>newsId</code>, that should also be used in query instead of <code>NEWSID</code>:</p> <pre><code>select c FROM News c WHERE c.newsId = :id </code></pre>
5,702,931
Convert integer/decimal to hex on an Arduino?
<p>How can an integer or decimal variable be converted into a hex string? I can do the opposite (convert hex to int) but I can't figure out the other way.</p> <p>This is for <code>Serial.print()</code> hex values in an array.</p>
5,703,349
3
0
null
2011-04-18 12:33:01.047 UTC
0
2014-07-01 12:23:23.377 UTC
2011-04-27 14:11:06.91 UTC
null
63,550
null
695,648
null
1
10
arduino
114,068
<p>Take a look at the Arduino String tutorial <a href="http://arduino.cc/en/Tutorial/StringConstructors">here</a>. The code below was taken from that example.</p> <pre><code>// using an int and a base (hexadecimal): stringOne = String(45, HEX); // prints "2d", which is the hexadecimal version of decimal 45: Serial.println(stringOne); </code></pre> <p>There are plenty of other examples on that page, though I think for floating point numbers you'll have to roll your own.</p>
6,306,636
Read ID3 Tags of an MP3 file
<p>I am trying to read ID3 from a mp3 file thats locally stored in the SD card.</p> <p>I want to basically fetch</p> <ol> <li>Title</li> <li>Artist</li> <li>Album</li> <li>Track Length</li> <li>Album Art</li> </ol>
6,306,735
3
0
null
2011-06-10 12:53:05.797 UTC
10
2018-06-28 22:54:38.14 UTC
2013-05-05 20:39:41.393 UTC
null
179,850
null
155,196
null
1
11
android|mp3|id3|id3-tag
23,496
<p>You can get all of this using <a href="http://developer.android.com/reference/android/media/MediaMetadataRetriever.html" rel="noreferrer">MediaMetadataRetriever</a></p> <pre><code>MediaMetadataRetriever mmr = new MediaMetadataRetriever(); mmr.setDataSource(filePath); String albumName = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); </code></pre>
5,690,283
Passing custom data in [UIButton addTarget]
<p>How do I add custom data while specifying a target in a <code>UIButton</code>?</p> <pre><code>id data = getSomeData(); [button addTarget:self action:@selector(buyButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside]; </code></pre> <p>I want the <code>buyButtonTapped</code> function to look like:</p> <pre><code>(void) buyButtonTapped: (UIButton *) button event: (id) event data: (id) data </code></pre>
5,690,329
3
0
null
2011-04-16 23:12:57.74 UTC
10
2013-08-29 12:13:50.35 UTC
null
null
null
null
112,388
null
1
21
iphone|objective-c
23,342
<p>not possible. the action that is triggered by an UIControl can have 3 different signatures.</p> <pre><code>- (void)action - (void)action:(id)sender - (void)action:(id)sender forEvent:(UIEvent *)event </code></pre> <p>None of them allows you to send custom data. </p> <hr> <p>Depending on what you want to do you can access the data in different ways. </p> <p>For example if the button is in a UITableView you could use something like this:</p> <pre><code>- (IBAction)buttonPressed:(UIButton *)sender { CGPoint buttonOriginInTableView = [sender convertPoint:CGPointZero toView:tableView]; NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:buttonOriginInTableView]; NSData *customData = [myDataSource customDataForIndexPath:indexPath]; // do something } </code></pre> <p>There is always a way to get the data without passing it to the button. </p>
6,281,461
Enum to String C++
<p>I commonly find I need to convert an enum to a string in c++</p> <p>I always end up doing:</p> <pre><code>enum Enum{ Banana, Orange, Apple } ; char * getTextForEnum( int enumVal ) { switch( enumVal ) { case Enum::Banana: return "bananas &amp; monkeys"; case Enum::Orange: return "Round and orange"; case Enum::Apple: return "APPLE" ; default: return "Not recognized.."; } } </code></pre> <p>Is there a better or recognized idiom for doing this?</p>
6,281,535
3
2
null
2011-06-08 15:38:59.5 UTC
14
2020-03-07 01:58:27.76 UTC
2020-03-07 01:58:27.76 UTC
null
366,904
null
111,307
null
1
69
c++|enums
156,278
<pre><code>enum Enum{ Banana, Orange, Apple } ; static const char * EnumStrings[] = { "bananas &amp; monkeys", "Round and orange", "APPLE" }; const char * getTextForEnum( int enumVal ) { return EnumStrings[enumVal]; } </code></pre>
5,706,723
windows form .. console.writeline() where is console?
<p>I created a windows form solution and in the constructor of a class I called </p> <p><code>Console.WriteLine("constructer called")</code></p> <p>But I only got the form and not the console.. so where is the output?</p>
5,706,747
4
1
null
2011-04-18 17:44:04.307 UTC
9
2019-06-06 11:48:50.843 UTC
2014-07-08 10:41:06.763 UTC
null
1,627,730
null
106,528
null
1
67
c#|.net|winforms|console-application
111,452
<p>In project settings set application type as Console. Then you will get console window and Windows form.</p>
2,076,468
Cross-browser 'cursor:pointer'
<p>I <a href="http://www.javascriptkit.com/dhtmltutors/csscursors.shtml" rel="noreferrer">found these CSS attributes</a>, that make the cursor look like a hand:</p> <ul> <li><strong>IE</strong> - style="cursor: hand;"</li> <li><strong>NS6/ IE6</strong> - style="cursor: pointer;"</li> <li><strong>Cross Browser</strong> - style="cursor: pointer; cursor: hand;"</li> </ul> <p>However I notice that Stack Overflow is using "cursor: pointer" in its CSS. However, this apparently work also on IE.</p> <p>So ... what gives? What is the correct, browser-independent way to use this CSS item?</p>
2,076,480
2
1
null
2010-01-16 06:51:10.307 UTC
3
2017-09-07 14:08:12.083 UTC
2013-10-26 07:14:43.883 UTC
null
106,224
null
11,236
null
1
28
css
47,568
<p>According to <a href="http://www.quirksmode.org/css/cursor.html" rel="noreferrer">Quirksmode</a>, the only cross-browser syntax is:</p> <pre><code>element { cursor: pointer; cursor: hand; } </code></pre> <p>They give some more information about the cursor as well:</p> <blockquote> <p>In the past the hand value was Microsoft's way of saying pointer; and IE 5.0 and 5.5 only support hand. Because it's the cursor value that's used most often, most other browsers have also implemented hand.</p> <p>Since IE 6 and 7 support pointer, there's no more reason to use hand, except when older IEs are part of your target audience.</p> </blockquote> <p>I think the page you linked to might be a little outdated with the newest browsers.</p>
2,191,890
Conditional operator in Python?
<p>do you know if Python supports some keyword or expression like in C++ to return values based on <code>if</code> condition, all in the same line (The C++ <code>if</code> expressed with the question mark <code>?</code>)</p> <pre><code>// C++ value = ( a &gt; 10 ? b : c ) </code></pre>
2,191,896
2
1
null
2010-02-03 12:44:07.98 UTC
24
2021-02-23 08:21:47.31 UTC
2010-02-03 13:34:07.813 UTC
anon
null
null
245,416
null
1
115
python|syntax
134,749
<p>From Python 2.5 onwards you can do:</p> <pre><code>value = b if a &gt; 10 else c </code></pre> <p>Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:</p> <pre><code>value = [c, b][a &gt; 10] </code></pre> <p>There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on <a href="http://en.wikipedia.org/wiki/%3F:#Python" rel="noreferrer">Wikipedia</a> if you want.</p>
6,300,398
InvalidOperationException in my Lazy<> value factory
<p>I have a class containing something like the following:</p> <pre><code>public static class Config { private static Lazy&lt;ConfigSource&gt; _cfgSrc = new Lazy&lt;ConfigSource&gt;( () =&gt; { /* "ValueFactory" here... */ }, true); public static ConfigSource ConfigSource { get { return _cfgSrc.Value; } } } </code></pre> <p>In accessing the <code>ConfigSource</code> property, I encountered this <code>InvalidOperationException</code>:</p> <blockquote> <p>ValueFactory attempted to access the Value property of this instance.</p> </blockquote> <p>I don't see anything in my "value factory" method that accesses the <code>Value</code> property. Is there anything else that could be triggering this exception? This problem only happens intermittently, but once it does, it takes resetting IIS to clear up the Exception (which appears to be cached once it occurs).</p>
6,510,343
6
10
null
2011-06-09 23:19:42.087 UTC
3
2019-10-14 13:12:51.833 UTC
2011-06-09 23:20:51.397 UTC
null
431,359
null
119,549
null
1
43
c#|.net-4.0|lazy-evaluation
30,603
<p>It turned out that this error only occurred when trying to inspect the <code>Value</code> property of the <code>Lazy&lt;&gt;</code> in the Visual Studio debugger. Doing so appeared to create a deadlock because the accessing of <code>Value</code> then seemed to hang the thread for a long time until the <code>InvalidOperationException</code> finally occurred. I could never intercept the original <code>Exception</code>, so I couldn't see the inner stacktrace.</p> <p>I'm just chalking this up as a bug in Visual Studio or their implementation of <code>Lazy&lt;&gt;</code>.</p>
5,658,369
How to input a regex in string.replace?
<p>I need some help on declaring a regex. My inputs are like the following:</p> <pre class="lang-none prettyprint-override"><code>this is a paragraph with&lt;[1&gt; in between&lt;/[1&gt; and then there are cases ... where the&lt;[99&gt; number ranges from 1-100&lt;/[99&gt;. and there are many other lines in the txt files with&lt;[3&gt; such tags &lt;/[3&gt; </code></pre> <p>The required output is:</p> <pre class="lang-none prettyprint-override"><code>this is a paragraph with in between and then there are cases ... where the number ranges from 1-100. and there are many other lines in the txt files with such tags </code></pre> <p>I've tried this:</p> <pre><code>#!/usr/bin/python import os, sys, re, glob for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')): for line in reader: line2 = line.replace('&lt;[1&gt; ', '') line = line2.replace('&lt;/[1&gt; ', '') line2 = line.replace('&lt;[1&gt;', '') line = line2.replace('&lt;/[1&gt;', '') print line </code></pre> <p>I've also tried this (but it seems like I'm using the wrong regex syntax):</p> <pre><code> line2 = line.replace('&lt;[*&gt; ', '') line = line2.replace('&lt;/[*&gt; ', '') line2 = line.replace('&lt;[*&gt;', '') line = line2.replace('&lt;/[*&gt;', '') </code></pre> <p>I dont want to hard-code the <code>replace</code> from 1 to 99.</p>
5,658,439
7
0
null
2011-04-14 03:59:21.223 UTC
91
2021-08-29 21:13:47.347 UTC
2021-08-09 12:04:54.29 UTC
null
4,621,513
null
610,569
null
1
453
python|regex|string|replace
469,243
<p>This tested snippet should do it:</p> <pre class="lang-py prettyprint-override"><code>import re line = re.sub(r&quot;&lt;/?\[\d+&gt;&quot;, &quot;&quot;, line) </code></pre> <p><strong>Edit:</strong> Here's a commented version explaining how it works:</p> <pre><code>line = re.sub(r&quot;&quot;&quot; (?x) # Use free-spacing mode. &lt; # Match a literal '&lt;' /? # Optionally match a '/' \[ # Match a literal '[' \d+ # Match one or more digits &gt; # Match a literal '&gt;' &quot;&quot;&quot;, &quot;&quot;, line) </code></pre> <p>Regexes are <em>fun!</em> But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: <em>&quot;metacharacters&quot;</em> which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: <a href="http://www.regular-expressions.info/" rel="noreferrer">www.regular-expressions.info</a>. The time you spend there will pay for itself many times over. Happy regexing!</p>
5,765,186
How to add icons to Preference
<p>I'm making an app that extends the PreferenceActivity and I want to add an icon to each Preference.</p> <p>I read a similar question, and this is the answer with more reputation:</p> <p><strong>CommonsWare Say:</strong></p> <blockquote> <p>The Settings application uses a private custom PreferenceScreen subclass to have the icon -- IconPreferenceScreen. It is 51 lines of code, including the comments, though it also requires some custom attributes. The simplest option is to clone all of that into your project, even though you do not like that.</p> </blockquote> <p>But I can't make it work. For now I cloned the class IconPreferenceScreen to my project. And I don't know what I have to do after this. I'm trying to make a new IconPreferenceScreen I can't make it work..</p> <pre><code> IconPreferenceScreen test = new IconPreferenceScreen(); test.setIcon(icon); </code></pre>
5,793,624
9
1
null
2011-04-23 15:49:49.74 UTC
14
2020-12-08 06:51:31.173 UTC
2011-11-28 04:35:40.747 UTC
null
710,274
null
710,274
null
1
28
android|icons|screen|preferences
36,976
<p>After many tests and many mistakes I could get it!</p> <p><strong>I had to do this:</strong></p> <p><strong>1 -</strong> Clone the class IconPreferenceScreen from the Android native Settings app (thanks CommonWare)</p> <p><strong>2 -</strong> Clone the layout file preference_icon.xml from the Android Settings app.</p> <p><strong>3 -</strong> Declare the IconPreferenceScreen styleable in the file attrs.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;declare-styleable name="IconPreferenceScreen"&gt; &lt;attr name="icon" format="reference" /&gt; &lt;/declare-styleable&gt; &lt;/resources&gt; </code></pre> <p><strong>4 -</strong> Declare the IconPreferenceScreen in the preference.xml file:</p> <pre><code>&lt;com.app.example.IconPreferenceScreen android:title="IconPreferenceScreen Title" android:summary="IconPreferenceScreen Summary" android:key="key1" /&gt; </code></pre> <p><strong>5 -</strong> Finally set the icon for the preference, in the preference class:</p> <pre><code>addPreferencesFromResource(R.xml.example); IconPreferenceScreen test = (IconPreferenceScreen) findPreference("key1"); Resources res = getResources(); Drawable icon = res.getDrawable(R.drawable.icon1); test.setIcon(icono1); </code></pre> <p>Thanks again to CommonsWare for tell me where to start, and for his explanation.</p> <p><strong>This is the cloned IconPreferenceScreen class:</strong></p> <pre><code>package com.app.example; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; public class IconPreferenceScreen extends Preference { private Drawable mIcon; public IconPreferenceScreen(Context context, AttributeSet attrs) { this(context, attrs, 0); } public IconPreferenceScreen(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setLayoutResource(R.layout.preference_icon); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IconPreferenceScreen, defStyle, 0); mIcon = a.getDrawable(R.styleable.IconPreferenceScreen_icon); } @Override public void onBindView(View view) { super.onBindView(view); ImageView imageView = (ImageView) view.findViewById(R.id.icon); if (imageView != null &amp;&amp; mIcon != null) { imageView.setImageDrawable(mIcon); } } public void setIcon(Drawable icon) { if ((icon == null &amp;&amp; mIcon != null) || (icon != null &amp;&amp; !icon.equals(mIcon))) { mIcon = icon; notifyChanged(); } } public Drawable getIcon() { return mIcon; } } </code></pre> <p><strong>And this is the cloned preference_icon.xml layout:</strong></p> <pre><code>&lt;LinearLayout android:id="@+android:id/iconpref" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?android:attr/listPreferredItemHeight" android:gravity="center_vertical" android:paddingRight="?android:attr/scrollbarSize"&gt; &lt;ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="6dip" android:layout_marginRight="6dip" android:layout_gravity="center" /&gt; &lt;RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="2dip" android:layout_marginRight="6dip" android:layout_marginTop="6dip" android:layout_marginBottom="6dip" android:layout_weight="1"&gt; &lt;TextView android:id="@+android:id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:textAppearance="?android:attr/textAppearanceLarge" android:ellipsize="marquee" android:fadingEdge="horizontal" /&gt; &lt;TextView android:id="@+android:id/summary" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@android:id/title" android:layout_alignLeft="@android:id/title" android:textAppearance="?android:attr/textAppearanceSmall" android:maxLines="2" /&gt; &lt;/RelativeLayout&gt; &lt;/LinearLayout&gt; </code></pre>
5,686,825
How to remove unused imports from Eclipse
<p>Is there any way to automatically remove all unused imports (signaled with a warning) of a project with Eclipse IDE?</p>
5,686,855
10
6
null
2011-04-16 13:33:21.657 UTC
37
2018-11-20 09:32:43.453 UTC
2014-08-24 14:27:28.547 UTC
null
560,648
null
587,884
null
1
157
eclipse
123,774
<p>I just found the way. Right click on the desired package then <code>Source</code> -> <code>Organize Imports</code>.</p> <p>Shortcut keys:</p> <ul> <li>Windows: <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>O</kbd></li> <li>Mac: <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>O</kbd></li> </ul>
5,618,925
Convert php array to Javascript
<p>How can I convert a PHP array in a format like this</p> <pre><code>Array ( [0] =&gt; 001-1234567 [1] =&gt; 1234567 [2] =&gt; 12345678 [3] =&gt; 12345678 [4] =&gt; 12345678 [5] =&gt; AP1W3242 [6] =&gt; AP7X1234 [7] =&gt; AS1234 [8] =&gt; MH9Z2324 [9] =&gt; MX1234 [10] =&gt; TN1A3242 [11] =&gt; ZZ1234 ) </code></pre> <p>to a Javascript array in the format below?</p> <pre><code>var cities = [ "Aberdeen", "Ada", "Adamsville", "Addyston", "Adelphi", "Adena", "Adrian", "Akron", "Albany" ]; </code></pre>
5,619,163
20
1
null
2011-04-11 08:54:20.78 UTC
59
2021-09-27 05:20:11.323 UTC
2013-02-22 22:09:26.903 UTC
null
1,608,072
null
663,878
null
1
214
php|javascript|arrays
469,500
<p><strong><a href="https://stackoverflow.com/a/5619038/367456">Spudley's answer is fine</a>.</strong></p> <blockquote> <p><strong>Security Notice:</strong> <em>The following should not be necessary any longer for you</em></p> </blockquote> <p>If you don't have PHP 5.2 you can use something like this:</p> <pre><code>function js_str($s) { return '"' . addcslashes($s, "\0..\37\"\\") . '"'; } function js_array($array) { $temp = array_map('js_str', $array); return '[' . implode(',', $temp) . ']'; } echo 'var cities = ', js_array($php_cities_array), ';'; </code></pre>
39,359,465
Android 7.0 Notification Sound from File Provider Uri not playing
<p>I'm changing my app code for supporting Android 7, but in my NotificationCompat.Builder.setSound(Uri) passing the Uri from FileProvider the Notification don't play any sound, in Android 6 using the Uri.fromFile() worked properly.</p> <p>The mp3 file is in:</p> <blockquote> <p>/Animeflv/cache/.sounds/</p> </blockquote> <p>This is my Notification Code:</p> <blockquote> <p>knf.animeflv.RequestBackground</p> </blockquote> <pre><code>NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_not_r) .setContentTitle(NotTit) .setContentText(mess); ... mBuilder.setVibrate(new long[]{100, 200, 100, 500}); mBuilder.setSound(UtilSound.getSoundUri(not)); //int </code></pre> <p>This is my UtilSound.getSoundUri(int)</p> <pre><code>public static Uri getSoundUri(int not) { switch (not) { case 0: return RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); default: try { File file=new File(Environment.getExternalStorageDirectory()+"/Animeflv/cache/.sounds",getSoundsFileName(not)); if (file.exists()) { file.setReadable(true,false); if (Build.VERSION.SDK_INT&gt;=Build.VERSION_CODES.N){ return FileProvider.getUriForFile(context, "knf.animeflv.RequestsBackground",file); }else { return Uri.fromFile(file); } }else { Log.d("Sound Uri","Not found"); return getSoundUri(0); } }catch (Exception e){ e.printStackTrace(); return getSoundUri(0); } } } </code></pre> <p>In AndroidManifest.xml:</p> <pre><code>&lt;provider android:name="android.support.v4.content.FileProvider" android:authorities="knf.animeflv.RequestsBackground" android:exported="false" android:grantUriPermissions="true"&gt; &lt;meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/&gt; &lt;/provider&gt; </code></pre> <p>provider_paths.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;external-path name="_.sounds" path="Animeflv/cache/.sounds/"/&gt; &lt;/paths&gt; </code></pre>
39,375,749
1
1
null
2016-09-07 00:02:28.277 UTC
11
2016-09-07 17:11:29.693 UTC
null
null
null
null
4,696,393
null
1
6
java|android|android-studio|android-fileprovider|android-7.0-nougat
4,476
<p>The following is from <a href="https://commonsware.com/blog/2016/09/07/notifications-sounds-android-7p0-aggravation.html" rel="noreferrer">a blog post</a> that I just published, reproduced here because, hey, why not?</p> <hr> <p>You can put a custom ringtone on a <code>Notification</code>, via methods like <code>setSound()</code> on <code>NotificationCompat.Builder</code>. This requires a <code>Uri</code>, and that causes problems on Android 7.0, as is reported by <a href="https://stackoverflow.com/q/39359465/115145">a few people</a> on <a href="https://stackoverflow.com/questions/39285228/how-to-set-audio-as-ringtone-programmatically-above-android-n?noredirect=1#comment66048508_39285228">Stack Overflow</a>.</p> <p>If you were using <code>file:</code> <code>Uri</code> values, they no longer work on Android 7.0 if your <code>targetSdkVersion</code> is 24 or higher, as the sound <code>Uri</code> is checked for compliance with <a href="https://commonsware.com/blog/2016/03/14/psa-file-scheme-ban-n-developer-preview.html" rel="noreferrer">the ban on <code>file:</code> <code>Uri</code> values</a>.</p> <p>However, if you try a <code>content:</code> <code>Uri</code> from, say, <code>FileProvider</code>, your sound will not be played... because Android does not have read access to that content.</p> <p>Here are some options for addressing this.</p> <p><strong>The Scalpel: <code>grantUriPermissions()</code></strong></p> <p>You can always grant permissions for content to other apps via <code>grantUriPermissions()</code>, a method available on <code>Context</code>. The challenge is in knowing <em>who</em> to grant the permissions to.</p> <p>What works on a Nexus 6P (Android 6.0... still...) and a Nexus 9 (Android 7.0) is:</p> <pre><code>grantUriPermission("com.android.systemui", sound, Intent.FLAG_GRANT_READ_URI_PERMISSION); </code></pre> <p>(where <code>sound</code> is the <code>Uri</code> that you are using with <code>setSound()</code>)</p> <p>Whether this will hold up for all devices and all Android OS versions, I cannot say.</p> <p><strong>The Guillotine: No More User Files</strong></p> <p><code>android.resource</code> as a scheme works fine for <code>Uri</code> values for <code>setSound()</code>. Instead of allowing users to choose their own ringtone from a file, you only allow them to choose one of several ringtones that you ship as raw resources in your app. If this represents a loss of app functionality, though, your users may be unimpressed.</p> <p><strong>The Axe: Use a Custom <code>ContentProvider</code></strong></p> <p><code>FileProvider</code> cannot be used when it is exported &mdash; it crashes on startup. However, for this case, the only <code>content:</code> <code>Uri</code> that will work without other issues is one where the provider is <code>exported</code> and has no read access permissions (or happens to require some permission that <code>com.android.systemui</code> or the equivalent happens to hold).</p> <p>Eventually, I'll add options for this to <a href="https://github.com/commonsguy/cwac-provider" rel="noreferrer">my <code>StreamProvider</code></a>, as part of some "read only" provider functionality.</p> <p>But, you could roll your own provider for this.</p> <p><strong>The Chainsaw: Ban the Ban</strong></p> <p>The following code snippet blocks all <code>StrictMode</code> checks related to VM behavior (i.e., stuff other than main application thread behavior), including the ban on <code>file:</code> <code>Uri</code> values:</p> <pre><code>StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().build()); </code></pre> <p>Alternatively, you could configure your own <code>VmPolicy</code> with whatever rules you want, just without calling <code>detectFileUriExposure()</code>.</p> <p>This allows you to use <code>file:</code> <code>Uri</code> values anywhere. There are good reasons why Google is banning the <code>file:</code> <code>Uri</code>, and so trying to avoid the ban may bite you in unfortunate body parts in the long term.</p> <p><strong>The Nuke: Use a Lower <code>targetSdkVersion</code></strong></p> <p>This also removes the ban on <code>file:</code> <code>Uri</code> values, along with all other behavior that a <code>targetSdkVersion</code> of 24+ opts into. Of note, this will cause your app to display a "may not work with split-screen" <code>Toast</code> if the user enters split-screen multi-window mode.</p> <p><strong>The Real Solution: A Fix in Android</strong></p> <p>The <code>NotificationManager</code> should be calling <code>grantUriPermissions()</code> for us, or there should be some other way for us to associate <code>FLAG_GRANT_READ_URI_PERMISSION</code> with the <code>Uri</code> that we use for custom <code>Notification</code> sounds. <a href="http://code.google.com/p/android/issues/detail?id=221899" rel="noreferrer">Stay tuned for further developments</a>.</p>
44,247,099
Click Command Line Interfaces: Make options required if other optional option is unset
<p>When writing a command-line interface (CLI) with the Python <a href="http://click.pocoo.org/6/" rel="noreferrer">click library</a>, is it possible to define e.g. three options where the second and third one are only required if the first (optional) one was left unset?</p> <p>My use case is a log-in system which allows me to authenticate either via an <code>authentication token</code> (option 1), or, alternatively, via <code>username</code> (option 2) and <code>password</code> (option 3). </p> <p>If the token was given, there is no need to check for <code>username</code> and <code>password</code> being defined or prompting them. Otherwise, if the token was omitted then <code>username</code> and <code>password</code> become required and must be given.</p> <p>Can this be done somehow using callbacks?</p> <p>My code to get started which of course does not reflect the intended pattern:</p> <pre><code>@click.command() @click.option('--authentication-token', prompt=True, required=True) @click.option('--username', prompt=True, required=True) @click.option('--password', hide_input=True, prompt=True, required=True) def login(authentication_token, username, password): print(authentication_token, username, password) if __name__ == '__main__': login() </code></pre>
44,349,292
3
0
null
2017-05-29 16:39:51.537 UTC
13
2020-05-08 17:19:38.963 UTC
2017-06-03 23:02:31.38 UTC
null
7,311,767
null
2,545,732
null
1
29
python|command-line-interface|python-click
18,815
<p>This can be done by building a custom class derived from <code>click.Option</code>, and in that class over riding the <code>click.Option.handle_parse_result()</code> method like:</p> <h3>Custom Class:</h3> <pre><code>import click class NotRequiredIf(click.Option): def __init__(self, *args, **kwargs): self.not_required_if = kwargs.pop('not_required_if') assert self.not_required_if, "'not_required_if' parameter required" kwargs['help'] = (kwargs.get('help', '') + ' NOTE: This argument is mutually exclusive with %s' % self.not_required_if ).strip() super(NotRequiredIf, self).__init__(*args, **kwargs) def handle_parse_result(self, ctx, opts, args): we_are_present = self.name in opts other_present = self.not_required_if in opts if other_present: if we_are_present: raise click.UsageError( "Illegal usage: `%s` is mutually exclusive with `%s`" % ( self.name, self.not_required_if)) else: self.prompt = None return super(NotRequiredIf, self).handle_parse_result( ctx, opts, args) </code></pre> <h3>Using Custom Class:</h3> <p>To use the custom class, pass the <code>cls</code> parameter to <code>click.option</code> decorator like:</p> <pre><code>@click.option('--username', prompt=True, cls=NotRequiredIf, not_required_if='authentication_token') </code></pre> <h3>How does this work?</h3> <p>This works because click is a well designed OO framework. The <code>@click.option()</code> decorator usually instantiates a <code>click.Option</code> object but allows this behavior to be overridden with the <code>cls</code> parameter. So it is a relatively easy matter to inherit from <code>click.Option</code> in our own class and over ride the desired methods.</p> <p>In this case we over ride <code>click.Option.handle_parse_result()</code> and disable the need to <code>user/password</code> if <code>authentication-token</code> token is present, and complain if both <code>user/password</code> are <code>authentication-token</code> are present.</p> <p>Note: This answer was inspired by <a href="https://stackoverflow.com/a/37491504/7311767">this answer</a></p> <h3>Test Code:</h3> <pre><code>@click.command() @click.option('--authentication-token') @click.option('--username', prompt=True, cls=NotRequiredIf, not_required_if='authentication_token') @click.option('--password', prompt=True, hide_input=True, cls=NotRequiredIf, not_required_if='authentication_token') def login(authentication_token, username, password): click.echo('t:%s u:%s p:%s' % ( authentication_token, username, password)) if __name__ == '__main__': login('--username name --password pword'.split()) login('--help'.split()) login(''.split()) login('--username name'.split()) login('--authentication-token token'.split()) </code></pre> <h3>Results:</h3> <p>from <code>login('--username name --password pword'.split())</code>:</p> <pre><code>t:None u:name p:pword </code></pre> <p>from <code>login('--help'.split())</code>:</p> <pre><code>Usage: test.py [OPTIONS] Options: --authentication-token TEXT --username TEXT NOTE: This argument is mutually exclusive with authentication_token --password TEXT NOTE: This argument is mutually exclusive with authentication_token --help Show this message and exit. </code></pre>
24,942,751
Generating Android build with Gitlab CI
<p>I just installed Gitlab as repository for my projects and I want to take advantages of their Gitlab CI system. I want to automatically generate a distribution and debug Apk after each commit. I googled but I didn't find anything as a tutorial or similar cases. If someone could guide me in some way, it would be great.</p> <p>Thanks!</p>
39,263,422
2
1
null
2014-07-24 19:51:07.723 UTC
8
2019-04-25 12:58:16.743 UTC
null
null
null
null
1,760,526
null
1
24
android|gitlab-ci
5,539
<p>I've just written a blog post on <a href="http://www.greysonparrelli.com/post/setting-up-android-builds-in-gitlab-ci-using-shared-runners/" rel="noreferrer">how to setup Android builds in Gitlab CI using shared runners</a>.</p> <p>The quickest way would be to have a <code>.gitlab-ci.yml</code> with the following contents:</p> <pre class="lang-yaml prettyprint-override"><code>image: openjdk:8-jdk variables: ANDROID_TARGET_SDK: "24" ANDROID_BUILD_TOOLS: "24.0.0" ANDROID_SDK_TOOLS: "24.4.1" before_script: - apt-get --quiet update --yes - apt-get --quiet install --yes wget tar unzip lib32stdc++6 lib32z1 - wget --quiet --output-document=android-sdk.tgz https://dl.google.com/android/android-sdk_r${ANDROID_SDK_TOOLS}-linux.tgz - tar --extract --gzip --file=android-sdk.tgz - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter android-${ANDROID_TARGET_SDK} - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter platform-tools - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter build-tools-${ANDROID_BUILD_TOOLS} - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter extra-android-m2repository - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter extra-google-google_play_services - echo y | android-sdk-linux/tools/android --silent update sdk --no-ui --all --filter extra-google-m2repository - export ANDROID_HOME=$PWD/android-sdk-linux - chmod +x ./gradlew build: script: - ./gradlew assembleDebug artifacts: paths: - app/build/outputs/ </code></pre> <p>This starts off using the Java 8 Docker image, then proceeds to download and install the necessary bits of the Android SDK before your build runs. My post also goes into detail as to how you can build this into a Docker image and host it on Gitlab itself.</p> <p>Hopefully that helps!</p> <p><strong>UPDATE - 4/10/2017</strong></p> <p>I wrote the canonical blog post for setting up Android builds in Gitlab CI back in November '16 for the official Gitlab blog. Includes details on how to run tests and such as well. Linking here.</p> <p><a href="https://about.gitlab.com/2016/11/30/setting-up-gitlab-ci-for-android-projects/" rel="noreferrer">https://about.gitlab.com/2016/11/30/setting-up-gitlab-ci-for-android-projects/</a></p>
24,558,916
Loop in Ruby on Rails html.erb file
<p>everybody I'm brand new with Ruby on Rails and I need to understand something. I have an instance variable (@users) and I need to loop over it inside an html.erb file a limitated number of times. I already used this:</p> <pre><code>&lt;% @users.each do |users| %&gt; &lt;%= do something %&gt; &lt;%end %&gt; </code></pre> <p>But I need to limitate it to, let's say, 10 times. What can I do?</p>
24,559,141
3
1
null
2014-07-03 16:24:30.527 UTC
5
2020-02-19 21:41:23.957 UTC
null
null
null
null
3,802,533
null
1
37
html|ruby-on-rails|ruby|loops|erb
58,556
<p>If <code>@users</code> has more elements than you want to loop over, you can use <code>first</code> or <code>slice</code>:</p> <p>Using <code>first</code></p> <pre><code>&lt;% @users.first(10).each do |users| %&gt; &lt;%= do something %&gt; &lt;% end %&gt; </code></pre> <p>Using <code>slice</code></p> <pre><code>&lt;% @users.slice(0, 10).each do |users| %&gt; &lt;%= do something %&gt; &lt;% end %&gt; </code></pre> <p>However, if you don't actually need the rest of the users in the @users array, you should only load as many as you need by using <code>limit</code>:</p> <pre><code>@users = User.limit(10) </code></pre>