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
8,881,712
skip certain validation method in Model
<p>I am using <strong>Rails v2.3</strong></p> <p>If I have a <strong>model</strong>:</p> <pre><code>class car &lt; ActiveRecord::Base validate :method_1, :method_2, :method_3 ... # custom validation methods def method_1 ... end def method_2 ... end def method_3 ... end end </code></pre> <p>As you see above, I have <strong>3 custom validation methods</strong>, and I use them for model validation.</p> <p>If I have another method in this model class which save an new instance of the model like following:</p> <pre><code># "flag" here is NOT a DB based attribute def save_special_car flag new_car=Car.new(...) new_car.save #how to skip validation method_2 if flag==true end </code></pre> <p>I would like to skip the validation of <code>method_2</code> in this particular method for saving new car, <strong>how to skip the certain validation method?</strong></p>
8,881,906
5
4
null
2012-01-16 14:54:25.82 UTC
10
2022-03-02 07:37:29.353 UTC
2012-01-16 15:13:34.72 UTC
null
959,734
null
959,734
null
1
40
ruby-on-rails|ruby-on-rails-3|ruby-on-rails-3.1
32,711
<p>Update your model to this</p> <pre><code>class Car &lt; ActiveRecord::Base # depending on how you deal with mass-assignment # protection in newer Rails versions, # you might want to uncomment this line # # attr_accessible :skip_method_2 attr_accessor :skip_method_2 validate :method_1, :method_3 validate :method_2, unless: :skip_method_2 private # encapsulation is cool, so we are cool # custom validation methods def method_1 # ... end def method_2 # ... end def method_3 # ... end end </code></pre> <p>Then in your controller put:</p> <pre><code>def save_special_car new_car=Car.new(skip_method_2: true) new_car.save end </code></pre> <p>If you're getting <code>:flag</code> via params variable in your controller, you can use</p> <pre><code>def save_special_car new_car=Car.new(skip_method_2: params[:flag].present?) new_car.save end </code></pre>
8,819,842
Best way to Format a Double value to 2 Decimal places
<p>I am dealing with lot of double values in my application, is there is any easy way to handle the formatting of decimal values in Java?</p> <p>Is there any other better way of doing it than </p> <pre><code> DecimalFormat df = new DecimalFormat("#.##"); </code></pre> <p>What i want to do basically is format double values like </p> <pre><code>23.59004 to 23.59 35.7 to 35.70 3.0 to 3.00 9 to 9.00 </code></pre>
8,819,889
2
4
null
2012-01-11 13:11:28.56 UTC
59
2020-01-31 06:45:02.393 UTC
2017-05-23 12:18:26.857 UTC
null
-1
null
828,077
null
1
318
java
718,260
<p>No, there is no better way.</p> <p>Actually you have an error in your pattern. What you want is:</p> <pre><code>DecimalFormat df = new DecimalFormat("#.00"); </code></pre> <p>Note the <code>"00"</code>, meaning <em>exactly</em> two decimal places.</p> <p>If you use <code>"#.##"</code> (<code>#</code> means "optional" digit), it will drop trailing zeroes - ie <code>new DecimalFormat("#.##").format(3.0d);</code> prints just <code>"3"</code>, not <code>"3.00"</code>.</p>
8,659,808
How does HTTP file upload work?
<p>When I submit a simple form like this with a file attached:</p> <pre><code>&lt;form enctype="multipart/form-data" action="http://localhost:3000/upload?upload_progress_id=12344" method="POST"&gt; &lt;input type="hidden" name="MAX_FILE_SIZE" value="100000" /&gt; Choose a file to upload: &lt;input name="uploadedfile" type="file" /&gt;&lt;br /&gt; &lt;input type="submit" value="Upload File" /&gt; &lt;/form&gt; </code></pre> <p>How does it send the file internally? Is the file sent as part of the HTTP body as data? In the headers of this request, I don't see anything related to the name of the file. </p> <p>I just would like the know the internal workings of the HTTP when sending a file.</p>
8,660,740
5
4
null
2011-12-28 18:34:34.23 UTC
261
2020-05-14 12:48:14.2 UTC
2014-10-13 17:01:45.483 UTC
null
1,709,587
null
903,643
null
1
689
http|file-upload
785,041
<p>Let's take a look at what happens when you select a file and submit your form (I've truncated the headers for brevity):</p> <pre><code>POST /upload?upload_progress_id=12344 HTTP/1.1 Host: localhost:3000 Content-Length: 1325 Origin: http://localhost:3000 ... other headers ... Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L ------WebKitFormBoundaryePkpFF7tjBAqx29L Content-Disposition: form-data; name=&quot;MAX_FILE_SIZE&quot; 100000 ------WebKitFormBoundaryePkpFF7tjBAqx29L Content-Disposition: form-data; name=&quot;uploadedfile&quot;; filename=&quot;hello.o&quot; Content-Type: application/x-object ... contents of file goes here ... ------WebKitFormBoundaryePkpFF7tjBAqx29L-- </code></pre> <p><strong>NOTE: each boundary string must be prefixed with an extra <code>--</code>, just like in the end of the last boundary string. The example above already includes this, but it can be easy to miss. See comment by @Andreas below.</strong></p> <p>Instead of URL encoding the form parameters, the form parameters (including the file data) are sent as sections in a multipart document in the body of the request.</p> <p>In the example above, you can see the input <code>MAX_FILE_SIZE</code> with the value set in the form, as well as a section containing the file data. The file name is part of the <code>Content-Disposition</code> header.</p> <p>The full details are <a href="https://www.rfc-editor.org/rfc/rfc7578" rel="noreferrer">here</a>.</p>
4,939,508
Get value of c# dynamic property via string
<p>I'd like to access the value of a <code>dynamic</code> c# property with a string:</p> <p><code>dynamic d = new { value1 = "some", value2 = "random", value3 = "value" };</code></p> <p>How can I get the value of d.value2 ("random") if I only have "value2" as a string? In javascript, I could do d["value2"] to access the value ("random"), but I'm not sure how to do this with c# and reflection. The closest I've come is this:</p> <p><code>d.GetType().GetProperty("value2")</code> ... but I don't know how to get the actual value from that.</p> <p>As always, thanks for your help!</p>
4,939,524
13
3
null
2011-02-08 22:59:33.163 UTC
39
2021-11-27 11:05:48.403 UTC
null
null
null
null
199,210
null
1
221
c#|dynamic
312,253
<p>Once you have your <code>PropertyInfo</code> (from <code>GetProperty</code>), you need to call <code>GetValue</code> and pass in the instance that you want to get the value from. In your case:</p> <pre><code>d.GetType().GetProperty("value2").GetValue(d, null); </code></pre>
12,322,289
KDB+ like asof join for timeseries data in pandas?
<p>kdb+ has an <a href="https://code.kx.com/q/ref/aj/" rel="nofollow noreferrer">aj</a> function that is usually used to join tables along time columns.</p> <p>Here is an example where I have trade and quote tables and I get the prevailing quote for every trade.</p> <pre><code>q)5# t time sym price size ----------------------------- 09:30:00.439 NVDA 13.42 60511 09:30:00.439 NVDA 13.42 60511 09:30:02.332 NVDA 13.42 100 09:30:02.332 NVDA 13.42 100 09:30:02.333 NVDA 13.41 100 q)5# q time sym bid ask bsize asize ----------------------------------------- 09:30:00.026 NVDA 13.34 13.44 3 16 09:30:00.043 NVDA 13.34 13.44 3 17 09:30:00.121 NVDA 13.36 13.65 1 10 09:30:00.386 NVDA 13.36 13.52 21 1 09:30:00.440 NVDA 13.4 13.44 15 17 q)5# aj[`time; t; q] time sym price size bid ask bsize asize ----------------------------------------------------- 09:30:00.439 NVDA 13.42 60511 13.36 13.52 21 1 09:30:00.439 NVDA 13.42 60511 13.36 13.52 21 1 09:30:02.332 NVDA 13.42 100 13.34 13.61 1 1 09:30:02.332 NVDA 13.42 100 13.34 13.61 1 1 09:30:02.333 NVDA 13.41 100 13.34 13.51 1 1 </code></pre> <p>How can I do the same operation using pandas? I am working with trade and quote dataframes where the index is datetime64.</p> <pre><code>In [55]: quotes.head() Out[55]: bid ask bsize asize 2012-09-06 09:30:00.026000 13.34 13.44 3 16 2012-09-06 09:30:00.043000 13.34 13.44 3 17 2012-09-06 09:30:00.121000 13.36 13.65 1 10 2012-09-06 09:30:00.386000 13.36 13.52 21 1 2012-09-06 09:30:00.440000 13.40 13.44 15 17 In [56]: trades.head() Out[56]: price size 2012-09-06 09:30:00.439000 13.42 60511 2012-09-06 09:30:00.439000 13.42 60511 2012-09-06 09:30:02.332000 13.42 100 2012-09-06 09:30:02.332000 13.42 100 2012-09-06 09:30:02.333000 13.41 100 </code></pre> <p>I see that pandas has an asof function but that is not defined on the DataFrame, only on the Series object. I guess one could loop through each of the Series and align them one by one, but I am wondering if there is a better way?</p>
12,326,113
3
1
null
2012-09-07 16:49:21.49 UTC
9
2021-07-16 05:04:49.573 UTC
2021-07-16 05:04:49.573 UTC
null
459,863
null
220,120
null
1
14
python|join|time-series|pandas|kdb
8,181
<p>As you mentioned in the question, looping through each column should work for you:</p> <pre><code>df1.apply(lambda x: x.asof(df2.index)) </code></pre> <p>We could potentially create a faster NaN-naive version of DataFrame.asof to do all the columns in one shot. But for now, I think this is the most straightforward way.</p>
12,573,596
What is the purpose of vendor/bundle? Heroku tells me to remove it
<p>Upon pushing some changes to Heroku, I noticed a warning about <code>vendor/bundle</code> (see <strong>WARNING</strong> below).</p> <p>What is the purpose of this directory if, according to the warning, it should be "removed" from Git tracking?</p> <p>Why isn't <code>vendor/bundle</code> automatically <code>.gitignore</code>'d by default by Rails?</p> <p>Should I run <code>bundle pack</code>? (Is it actually <code>bundle package</code>??)</p> <p>What are the pros and cons around <code>bundle pack</code> (relative to both <code>development</code> and <code>production</code>)?</p> <p>To make this even more confusing, there's a popular blog post, by Ryan McGeary, titled <a href="http://ryan.mcgeary.org/2011/02/09/vendor-everything-still-applies/">"Vendor Everything" Still Applies</a> that strongly argues for running <code>bundle install --path vendor</code> and <code>echo 'vendor/ruby' &gt;&gt; .gitignore</code> and packaging gems in <code>vendor/cache</code> by running <code>bundle package</code>. Any light shed on this relative to my other concerns would be greatly appreciated.</p> <p>Thank you.</p> <pre><code>-bash&gt; git push production master ... -----&gt; Heroku receiving push -----&gt; Ruby/Rails app detected -----&gt; WARNING: Removing `vendor/bundle`. Checking in `vendor/bundle` is not supported. Please remove this directory and add it to your .gitignore. To vendor your gems with Bundler, use `bundle pack` instead. -----&gt; Installing dependencies using Bundler version 1.2.1 Running: bundle install --without development:test --path vendor/bundle --binstubs bin/ --deployment Using rake (0.9.2.2) Using i18n (0.6.0) ... </code></pre>
12,601,935
1
0
null
2012-09-24 22:06:44.87 UTC
11
2020-10-05 18:05:58.42 UTC
2012-09-24 23:39:11.98 UTC
null
664,833
null
664,833
null
1
30
ruby-on-rails|heroku|ruby-on-rails-3.2|bundler
24,808
<p>If you have the <code>vendor/bundle</code> directory in your project then at some point <a href="https://bundler.io/v2.1/man/bundle-install.1.html" rel="noreferrer">you must have run the <code>bundle</code> command with the <code>--path vendor/bundle</code> argument</a>. This will load the files for all your project's gems (listed in <code>Gemfile</code>) into the <code>vendor/bundle</code> directory in your local project rather than to a system gem location. You would do this to completely isolate a project's gems from any other project.</p> <p>Bundler is good at resolving all dependencies so it isn't necessary to use the <code>--path</code> but some people choose to do so as they wish to keep their gems separate and organised with their project. It also means that bundler on your local machine is set up the same way that Heroku uses bundler.</p> <p>With this option you are still downloading all gems from the <a href="https://rubygems.org/" rel="noreferrer"><code>rubygems</code></a> servers every time you run the <code>bundle</code> command.</p> <p><a href="http://gembundler.com/bundle_package.html" rel="noreferrer"><code>bundle package</code></a> takes it a step further and actually downloads the original gem files from <code>rubygems</code> and caches them into the <code>vendor/cache</code> directory. This means that you no longer need a connection to <code>rubygems</code> to run the bundle command as it will use the packaged files as the source. If you need to update a gem version then it will need to connect to <code>rubygems</code> to collect the new version the first time it is requested. Using <code>bundle package</code> will of course require additional disc space which may or may not be an issue depending on the situation. It would also increase deploy time and bandwidth requirements every time you pushed to Heroku.</p> <p>Heroku runs the <code>bundle</code> command every time you <code>git push</code>, reading your <code>Gemfile.lock</code> and installing the gems required for the application to work. By default the <code>--path vendor/bundle</code> option is used. This is so that each application has a set of gem files separate from all other apps on Heroku. If you have the <code>vendor/bundle</code> directory in your source control and you push it to Heroku then you can see that there is the potential for significant conflict as it then attempts to load gems into <code>vendor/bundle</code> directory which already exists. If it is pushed then Heroku removes the <code>vendor/bundle</code> directory before it runs <code>bundle install</code> to remove these potential conflicts. If this is the case then you will be wasting deploy time and bandwidth by leaving <code>vendor/bundle</code> under version control, it's better to add it to your <code>.gitignore</code>.</p> <p>If you want complete control over your gems on Heroku then use the <code>bundle package</code> command and make sure that the <code>vendor/cache</code> directory is under source control. When Heroku runs <code>bundle install</code> it will use the contents of <code>vendor/cache</code> as the gem source rather than using <code>rubygems</code>. Whether this is useful or not will be a matter of personal preference, the type of app that you are building and how often you update your gems. The Ryan McGeary post suggests that using <code>bundle package</code> is useful in case an old gem becomes unavailable at some point in the future. This would appear to be a bigger issue to projects/apps which are not regularly kept up to date.</p> <p>From my perspective, I generally use <code>--path vendor/bundle</code> to keep my local setup as close as possible to Heroku's. I put <code>vendor/bundle</code> into my project's <code>.gitignore</code> file, and I don't <em>package</em> gems, as my projects are updated relatively regularly.</p> <p>Rails has a very limited <code>.gitignore</code> file. You are effectively expected to build up what you need yourself, which is why <code>vendor/bundle</code> is not included by default.</p> <p>I assume that Heroku means <code>bundle package</code> when they say <code>bundle pack</code>.</p>
12,502,365
How to create 1024x1024 RGB bitmap image of white?
<p>It's embarrassing to ask this question but can't find an answer.</p> <p>I tried this in vain.</p> <pre><code>Image resultImage = new Bitmap(image1.Width, image1.Height, PixelFormat.Format24bppRgb); using (Graphics grp = Graphics.FromImage(resultImage)) { grp.FillRectangle( Brushes.White, 0, 0, image1.Width, image1.Height); resultImage = new Bitmap(image1.Width, image1.Height, grp); } </code></pre> <p>I basically want to fill a 1024x1024 RGB bitmap image with white in C#. How can I do that?</p>
12,502,396
5
1
null
2012-09-19 20:27:59.333 UTC
4
2021-01-16 23:25:37.067 UTC
2017-01-08 15:10:26.203 UTC
null
107,625
null
749,973
null
1
41
c#
71,621
<p>You are assigning a new image to <code>resultImage</code>, thereby overwriting your previous attempt at creating a white image (which should succeed, by the way).</p> <p>So just remove the line</p> <pre><code>resultImage = new Bitmap(image1.Width, image1.Height, grp); </code></pre>
12,380,478
Bits counting algorithm (Brian Kernighan) in an integer time complexity
<p>Can someone explains why Brian Kernighan's algorithm takes O(log N) to count set bits (1s) in an integer. A simple implementation of this algorithm is below (in JAVA)</p> <pre class="lang-java prettyprint-override"><code>int count_set_bits(int n){ int count = 0; while(n != 0){ n &amp;= (n-1); count++; } return count; } </code></pre> <p>I understand how it works by clearing the rightmost set bit one by one until it becomes 0, but I just don't know how we get O(log N).</p>
12,381,102
3
5
null
2012-09-12 02:31:58.147 UTC
24
2016-11-08 14:20:54.487 UTC
2016-10-13 20:59:33.003 UTC
null
1,062,471
null
1,389,813
null
1
42
algorithm|bit-manipulation
25,825
<p>This algorithm goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop. In the worst case, it will pass once per bit. An integer <code>n</code> has <code>log(n)</code> bits, hence the worst case is <code>O(log(n))</code>. Here's your code annotated at the important bits (pun intended):</p> <pre><code> int count_set_bits(int n){ int count = 0; // count accumulates the total bits set while(n != 0){ n &amp;= (n-1); // clear the least significant bit set count++; } } </code></pre>
12,054,825
Jquery, How to unselect all radio button in radio group
<p>Anyone know how to unselect all radio buttons in a radio group ?</p> <p><strong>HTML:</strong></p> <pre><code>&lt;div id="emptimfields"&gt; &lt;label id="lbl_emptim"&gt;How regulary do you employ people to help cultivate your land? &lt;/label&gt;&lt;br/&gt;&lt;br/&gt; &lt;fieldset data-role="controlgroup" data-type="vertical" id="emptim"&gt; &lt;input name="emptim" id="radio1" value="fromtimetotime" type="radio" openmrs-valuecoded="" /&gt; &lt;label for="radio1"&gt; From time to time &lt;/label&gt; &lt;input name="emptim" id="radio2" value="allthetime" type="radio" openmrs-valuecoded="" /&gt; &lt;label for="radio2"&gt;All the time&lt;/label&gt; &lt;input name="emptim" id="radio3" value="dontknow" type="radio" openmrs-valuecoded="" /&gt; &lt;label for="radio3"&gt; Don't know &lt;/label&gt; &lt;/fieldset&gt; &lt;/div&gt; </code></pre> <p><strong>JQuery side:</strong></p> <pre><code>$('input:radio[name=emptim]:checked').prop('checked', false); // doesn't work </code></pre> <p>I'm certainly missing something basic, but I can't figure out what is the problem.</p> <p>First, I check Yes and then check a value of the second radio group : </p> <p><img src="https://i.stack.imgur.com/dI8UA.png" alt="enter image description here"></p> <p>Then, I check No to hide the second radio group:</p> <p><img src="https://i.stack.imgur.com/aS6E1.png" alt="enter image description here"></p> <p>Then, If I click on next, I get the value of what I've checked (but I checked no previously, so here I don't want an alert, I want the radioButton "From time to time" to be unchecked) :</p> <p><img src="https://i.stack.imgur.com/rvTfS.png" alt="enter image description here"></p> <p>Finally, if I come back, nothing happend :</p> <p><img src="https://i.stack.imgur.com/qXyMr.png" alt="enter image description here"></p>
12,054,892
5
9
null
2012-08-21 12:26:52.143 UTC
3
2021-11-16 10:25:21.613 UTC
2016-03-19 20:14:01.523 UTC
null
573,032
null
1,587,046
null
1
56
jquery|html|jquery-mobile|jquery-selectors
99,872
<p>You can give them a classname and try:</p> <pre><code>$('.classname').prop('checked', false); </code></pre> <p>When you use an older version of jQuery than 1.6 it has to be:</p> <pre><code> $('&lt;selector&gt;').attr('checked', false); </code></pre> <p><strong>EDIT :</strong></p> <p>Call the method <code>.checkboxradio("refresh");</code> has also worked for me.</p>
12,574,668
Change color of sibling elements on hover using CSS
<p>In my HTML below, when I hover on the <code>&lt;a&gt;</code> element I want to change the colour of the <code>&lt;h1&gt;</code> element using only CSS. Is there a way to achieve this?</p> <pre class="lang-html prettyprint-override"><code>&lt;h1&gt;Heading&lt;/h1&gt; &lt;a class=&quot;button&quot; href=&quot;#&quot;&gt;&lt;/a&gt; </code></pre> <p>What if I wrap a div around it with an id in it?</p> <pre class="lang-html prettyprint-override"><code>&lt;div id=&quot;banner&quot;&gt; &lt;h1&gt;Heading&lt;/h1&gt; &lt;a class=&quot;button&quot; href=&quot;#&quot;&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Will this help?</p>
12,574,716
10
1
null
2012-09-25 00:16:52.073 UTC
16
2022-08-08 20:07:00.777 UTC
2021-06-03 14:52:33.243 UTC
null
1,264,804
null
1,567,428
null
1
70
html|css
111,012
<p>There is no <a href="http://www.w3.org/TR/CSS2/selector.html" rel="noreferrer">CSS selector</a> that can do this (<a href="http://www.w3.org/TR/css3-selectors/" rel="noreferrer">in CSS3, even</a>). Elements, in CSS, are never aware of their parent, so you cannot do <code>a:parent h1</code> (for example). Nor are they aware of their siblings (in most cases), so you cannot do <code>#container a:hover { /* do something with sibling h1 */ }</code>. <em>Basically, CSS properties cannot modify anything but elements and their children (they cannot access parents or siblings).</em></p> <p>You could contain the <code>h1</code> <em>within</em> the <code>a</code>, but this would make your <code>h1</code> hoverable as well.</p> <p>You will only be able to achieve this using JavaScript (<a href="http://jsfiddle.net/P3Ew6/" rel="noreferrer">jsFiddle proof-of-concept</a>). This would look something like:</p> <pre><code>$("a.button").hover(function() { $(this).siblings("h1").addClass("your_color_class"); }, function() { $(this).siblings("h1").removeClass("your_color_class"); }); </code></pre>
12,409,299
How to get current formatted date dd/mm/yyyy in Javascript and append it to an input
<p>I would like to add a current date to a hidden HTML tag so that it can be sent to the server:</p> <pre><code>&lt;input type="hidden" id="DATE" name="DATE" value="WOULD_LIKE_TO_ADD_DATE_HERE"&gt; </code></pre> <p>How can I add a formatted date to the VALUE attribute?</p>
12,409,344
7
4
null
2012-09-13 15:04:39.667 UTC
89
2022-07-10 10:44:30.363 UTC
2016-03-07 13:44:39.457 UTC
null
440,237
null
1,651,575
null
1
395
javascript|html|input|tags|hidden
1,570,151
<p>I hope this is what you want:</p> <pre><code>const today = new Date(); const yyyy = today.getFullYear(); let mm = today.getMonth() + 1; // Months start at 0! let dd = today.getDate(); if (dd &lt; 10) dd = '0' + dd; if (mm &lt; 10) mm = '0' + mm; const formattedToday = dd + '/' + mm + '/' + yyyy; document.getElementById('DATE').value = formattedToday; </code></pre> <p><a href="https://stackoverflow.com/questions/1531093/how-to-get-current-date-in-javascript">How do I get the current date in JavaScript?</a></p>
24,181,992
Round up a CGFloat in Swift
<p>How can I round up a CGFloat in Swift? I've tried <code>ceil(CDouble(myCGFloat))</code> but that only works on iPad Air &amp; iPhone 5S.</p> <p>When running on another simulated device I get an error saying <code>'NSNumber' is not a subtype of 'CGFloat'</code></p>
24,182,426
7
4
null
2014-06-12 10:20:08.327 UTC
14
2022-03-25 14:26:57.277 UTC
2019-03-11 11:39:29.21 UTC
null
1,966,109
null
1,523,238
null
1
98
swift|rounding|cgfloat|ceil
103,791
<p><strong>Update</strong>: Apple have now defined some CGFloat-specific versions of common functions like <code>ceil</code>:</p> <pre><code>func ceil(x: CGFloat) -&gt; CGFloat </code></pre> <p>...specifically to cope with the 32/64-bit difference. If you simply use <code>ceil</code> with a CGFloat argument it should now work on all architectures.</p> <p>My original answer:</p> <p>This is pretty horrible, I think, but can anyone think of a better way? <code>#if</code> doesn't seem to work for <code>CGFLOAT_IS_DOUBLE</code>; I think you're limited to build configurations, from what <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-XID_21">I can see in the documentation for conditional compilation</a>.</p> <pre><code>var x = CGFloat(0.5) #if arch(x86_64) || arch(arm64) var test = ceil(x) #else var test = ceilf(x) #endif </code></pre>
3,536,465
Debugging a Deadlock with Windbg's !clrstack command
<p>When I issued clrstack command, I got the following output. It is the callstack of a blocking thread which owns a deadlock and results in a deadlock. Is that its exact purpose? Does it have any other purposes (without any parameters). Where can I get more information?</p> <pre><code>!clrstack OS Thread Id: 0x1b2c (6956) ESP EIP 0012f370 7c90e514 [HelperMethodFrame: 0012f370] System.Threading.Thread.SleepInternal(Int32) 0012f3c4 79299275 System.Threading.Thread.Sleep(Int32) 0012f3c8 00e0030f testlock.LockTest.Test() 0012f420 00e00146 testlock.Program.Main(System.String[]) 0012f69c 79e71b4c [GCFrame: 0012f69c] </code></pre>
3,536,501
3
2
null
2010-08-21 05:26:18.04 UTC
13
2021-06-21 06:13:32.203 UTC
2010-08-21 05:49:41.553 UTC
null
16,076
null
382,485
null
1
10
c#|debugging|deadlock|windbg
25,154
<p><a href="https://web.archive.org/web/20150623063242/http://blogs.msdn.com:80/b/mohamedg/archive/2010/01/29/how-to-debug-deadlocks-using-windbg.aspx" rel="nofollow noreferrer">How to: Debug Deadlocks Using Windbg?</a></p> <p><a href="https://web.archive.org/web/20201024041713/http://geekswithblogs.net/.NETonMyMind/archive/2006/03/14/72262.aspx" rel="nofollow noreferrer">WinDbg / SOS Cheat Sheet</a></p> <blockquote> <p><a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/sos-dll-sos-debugging-extension" rel="nofollow noreferrer">CLRStack</a> [-a] [-l] [-p] [-n] Provides a stack trace of managed code only.</p> <ul> <li><p>The -p option shows arguments to the managed function.</p> </li> <li><p>The -l option shows information on local variables in a frame. The SOS Debugging Extension cannot retrieve local names, so the output for local names is in the format = .</p> </li> <li><p>The -a(all) option is a shortcut for -l and -pcombined.</p> </li> <li><p>The -n option disables the display of source file names and line numbers. If the debugger has the option SYMOPT_LOAD_LINES specified, SOS will look up the symbols for every managed frame and if successful will display the corresponding source file name and line number. The -n (No line numbers) parameter can be specified to disable this behavior.</p> </li> </ul> <p>The SOS Debugging Extension does not display transition frames on x64 and IA-64-based platforms.</p> </blockquote> <p><strong>Update</strong>: (Thanks to @Liran): To see the call stacks for all the threads in your application, run the following command:</p> <pre><code> ~*e!clrstack </code></pre> <p>(which basically means, &quot;iterate over all of the threads, and execute the command '!clrstack' on every one of them&quot;).</p>
3,437,885
How can I list all modules in a CVS repository?
<p>Is there a command that returns a list of module names contained within a CVS repository?</p> <p>Being a newbie to CVS, I imagine that there should be something along the lines of</p> <pre><code>cvs -d /usr/local/cvs listmodules </code></pre> <p>What should I substitute <code>listmodules</code> with to get a list of all modules within the CVS repository?</p> <hr> <p>To address Dewfy's comment, <code>cvs --help-commands</code> returns the following:</p> <blockquote> <pre><code> add Add a new file/directory to the repository admin Administration front end for rcs annotate Show last revision where each line was modified checkout Checkout sources for editing commit Check files into the repository diff Show differences between revisions edit Get ready to edit a watched file editors See who is editing a watched file export Export sources from CVS, similar to checkout history Show repository access history import Import sources into CVS, using vendor branches init Create a CVS repository if it doesn't exist kserver Kerberos server mode log Print out history information for files login Prompt for password for authenticating server logout Removes entry in .cvspass for remote repository pserver Password server mode rannotate Show last revision where each line of module was modified rdiff Create 'patch' format diffs between releases release Indicate that a Module is no longer in use remove Remove an entry from the repository rlog Print out history information for a module rtag Add a symbolic tag to a module server Server mode status Display status information on checked out files tag Add a symbolic tag to checked out version of files unedit Undo an edit command update Bring work tree in sync with repository version Show current CVS version(s) watch Set watches watchers See who is watching a file </code></pre> </blockquote> <p>The CVS version is <strong>1.11.22</strong>.</p>
3,448,891
3
1
null
2010-08-09 06:55:09.407 UTC
3
2013-09-18 20:50:12.85 UTC
2010-08-09 08:54:56.233 UTC
null
133,939
null
133,939
null
1
21
cvs
51,963
<p>As already described in <a href="https://stackoverflow.com/questions/889378/how-can-i-list-files-in-cvs-without-an-initial-checkout/896764#896764">this answer</a> there are basically three ways to go about this. Which one suits your situation depends firstly on what versions of CVS you are using on both client and server and secondly on your definition of "modules".</p> <ol> <li><p>If you are referring to modules as they were originally thought of by the CVS authors, i.e. as entries in the <code>CVSROOT/modules</code> file then <code>cvs co -c</code> or <code>cvs co -s</code> will give you that, the only difference between the two being that the latter will sort the output by "status". You can read about the modules file here: <a href="http://cvsbook.red-bean.com/cvsbook.html#modules" rel="noreferrer">http://cvsbook.red-bean.com/cvsbook.html#modules</a></p></li> <li><p>If you are using at least CVS 1.12.8 or CVSNT and your idea of modules corresponds more to actual directories inside the repository, then <code>cvs ls</code> should be what you want.</p></li> <li><p>Finally, if you are indeed after a remote directory listing but your server is running an older version of CVS, then there's the trick of first performing a "fake" checkout and then simulating a recursive update:</p> <p>cvs -d [CVSROOT] co -l .</p> <p>cvs -n up -d</p></li> </ol>
3,400,922
How do I retrieve an error string from WSAGetLastError()?
<p>I'm porting some sockets code from Linux to Windows.</p> <p>In Linux, I could use <code>strerror()</code> to convert an errno code into a human-readable string.</p> <p>MSDN documentation shows equivalent strings for each error code returned from <code>WSAGetLastError()</code>, but I don't see anything about how to retrieve those strings. Will <code>strerror()</code> work here too?</p> <p>How can I retrieve human-readable error strings from Winsock?</p>
3,400,999
3
0
null
2010-08-03 21:34:10.697 UTC
4
2017-09-07 20:17:31.547 UTC
null
null
null
null
23,934
null
1
31
c|winapi|sockets|winsock
28,156
<p>As the documentation for <a href="http://msdn.microsoft.com/en-us/library/ms741580%28VS.85%29.aspx" rel="noreferrer"><code>WSAGetLastError</code></a> says you can use <a href="http://msdn.microsoft.com/en-us/library/ms679351%28v=VS.85%29.aspx" rel="noreferrer"><code>FormatMessage</code></a> to obtain a text version of the error message.</p> <p>You need to set <code>FORMAT_MESSAGE_FROM_SYSTEM</code> in the <code>dwFlags</code> parameter and pass the error code as the <code>dwMessage</code> parameter.</p>
3,475,262
What causes a Sigtrap in a Debug Session
<p>In my c++ program I'm using a library which will "send?" a Sigtrap on a certain operations when I'm debugging it (using gdb as a debugger). I can then choose whether I wish to Continue or Stop the program. If I choose to continue the program works as expected, but setting custom breakpoints after a Sigtrap has been caught causes the debugger/program to crash.</p> <p>So here are my questions:</p> <ol> <li>What causes such a Sigtrap? Is it a leftover line of code that can be removed, or is it caused by the debugger when he "finds something he doesn't like" ?</li> <li>Is a sigtrap, generally speaking, a bad thing, and if so, why does the program run flawlessly when I compile a Release and not a Debug Version?</li> <li>What does a Sigtrap indicate?</li> </ol> <p><em>This is a more general approach to a question I posted yesterday</em> <a href="https://stackoverflow.com/questions/3469463/boost-filesystem-recursive-directory-iterator-constructor-causes-sigtraps-and-de">Boost Filesystem: recursive_directory_iterator constructor causes SIGTRAPS and debug problems</a>.<br> I think my question was far to specific, and I don't want you to solve my problem but help me (and hopefully others) to understand the background.</p> <p>Thanks a lot.</p>
3,475,444
3
2
null
2010-08-13 08:47:23.543 UTC
5
2021-04-04 09:51:20.103 UTC
2017-05-23 12:25:24.347 UTC
null
-1
null
418,578
null
1
39
c++|debugging|gdb
71,589
<p>With processors that support instruction breakpoints or data watchpoints, the debugger will ask the CPU to watch for instruction accesses to a specific address, or data reads/writes to a specific address, and then run full-speed.</p> <p>When the processor detects the event, it will trap into the kernel, and the kernel will send SIGTRAP to the process being debugged. Normally, SIGTRAP would kill the process, but because it is being debugged, the debugger will be notified of the signal and handle it, mostly by letting you inspect the state of the process before continuing execution.</p> <p>With processors that don't support breakpoints or watchpoints, the entire debugging environment is probably done through code interpretation and memory emulation, which is immensely slower. (I imagine clever tricks could be done by setting pagetable flags to forbid reading or writing, whichever needs to be trapped, and letting the kernel fix up the pagetables, signaling the debugger, and then restricting the page flags again. This could probably support near-arbitrary number of watchpoints and breakpoints, and run only marginally slower for cases when the watchpoint or breakpoint aren't frequently accessed.)</p> <p>The question I placed into the comment field looks apropos here, only because Windows isn't actually sending a SIGTRAP, but rather signaling a breakpoint in its own native way. I assume when you're debugging programs, that debug versions of system libraries are used, and ensure that memory accesses appear to make sense. You might have a bug in your program that is papered-over at runtime, but may in fact be causing further problems elsewhere.</p> <p>I haven't done development on Windows, but perhaps you could get further details by looking through your Windows Event Log?</p>
3,801,681
Good or bad practice for Dialogs in wpf with MVVM?
<p>I lately had the problem of creating add and edit dialogs for my wpf app.</p> <p>All I want to do in my code was something like this. (I mostly use viewmodel first approach with mvvm)</p> <p>ViewModel which calls a dialog window:</p> <pre><code>var result = this.uiDialogService.ShowDialog("Dialogwindow Title", dialogwindowVM); // Do anything with the dialog result </code></pre> <p>How does it work?</p> <p>First, I created a dialog service:</p> <pre><code>public interface IUIWindowDialogService { bool? ShowDialog(string title, object datacontext); } public class WpfUIWindowDialogService : IUIWindowDialogService { public bool? ShowDialog(string title, object datacontext) { var win = new WindowDialog(); win.Title = title; win.DataContext = datacontext; return win.ShowDialog(); } } </code></pre> <p><code>WindowDialog</code> is a special but simple window. I need it to hold my content:</p> <pre><code>&lt;Window x:Class="WindowDialog" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Title="WindowDialog" WindowStyle="SingleBorderWindow" WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight"&gt; &lt;ContentPresenter x:Name="DialogPresenter" Content="{Binding .}"&gt; &lt;/ContentPresenter&gt; &lt;/Window&gt; </code></pre> <p>A problem with dialogs in wpf is the <code>dialogresult = true</code> can only be achieved in code. That's why I created an interface for my <code>dialogviewmodel</code> to implement it. </p> <pre><code>public class RequestCloseDialogEventArgs : EventArgs { public bool DialogResult { get; set; } public RequestCloseDialogEventArgs(bool dialogresult) { this.DialogResult = dialogresult; } } public interface IDialogResultVMHelper { event EventHandler&lt;RequestCloseDialogEventArgs&gt; RequestCloseDialog; } </code></pre> <p>Whenever my ViewModel thinks it's time for <code>dialogresult = true</code>, then raise this event.</p> <pre><code>public partial class DialogWindow : Window { // Note: If the window is closed, it has no DialogResult private bool _isClosed = false; public DialogWindow() { InitializeComponent(); this.DialogPresenter.DataContextChanged += DialogPresenterDataContextChanged; this.Closed += DialogWindowClosed; } void DialogWindowClosed(object sender, EventArgs e) { this._isClosed = true; } private void DialogPresenterDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { var d = e.NewValue as IDialogResultVMHelper; if (d == null) return; d.RequestCloseDialog += new EventHandler&lt;RequestCloseDialogEventArgs&gt; (DialogResultTrueEvent).MakeWeak( eh =&gt; d.RequestCloseDialog -= eh;); } private void DialogResultTrueEvent(object sender, RequestCloseDialogEventArgs eventargs) { // Important: Do not set DialogResult for a closed window // GC clears windows anyways and with MakeWeak it // closes out with IDialogResultVMHelper if(_isClosed) return; this.DialogResult = eventargs.DialogResult; } } </code></pre> <p>Now at least I have to create a <code>DataTemplate</code> in my resource file(<code>app.xaml</code> or something):</p> <pre><code>&lt;DataTemplate DataType="{x:Type DialogViewModel:EditOrNewAuswahlItemVM}" &gt; &lt;DialogView:EditOrNewAuswahlItem/&gt; &lt;/DataTemplate&gt; </code></pre> <p>Well thats all, I can now call dialogs from my viewmodels:</p> <pre><code> var result = this.uiDialogService.ShowDialog("Dialogwindow Title", dialogwindowVM); </code></pre> <p>Now my question, do you see any problems with this solution?</p> <p>Edit: for completeness. The ViewModel should implement <code>IDialogResultVMHelper</code> and then it can raise it within a <code>OkCommand</code> or something like this:</p> <pre><code>public class MyViewmodel : IDialogResultVMHelper { private readonly Lazy&lt;DelegateCommand&gt; _okCommand; public MyViewmodel() { this._okCommand = new Lazy&lt;DelegateCommand&gt;(() =&gt; new DelegateCommand(() =&gt; InvokeRequestCloseDialog( new RequestCloseDialogEventArgs(true)), () =&gt; YourConditionsGoesHere = true)); } public ICommand OkCommand { get { return this._okCommand.Value; } } public event EventHandler&lt;RequestCloseDialogEventArgs&gt; RequestCloseDialog; private void InvokeRequestCloseDialog(RequestCloseDialogEventArgs e) { var handler = RequestCloseDialog; if (handler != null) handler(this, e); } } </code></pre> <p>EDIT 2: I used the code from here to make my EventHandler register weak:<br> <a href="http://diditwith.net/2007/03/23/SolvingTheProblemWithEventsWeakEventHandlers.aspx" rel="noreferrer">http://diditwith.net/2007/03/23/SolvingTheProblemWithEventsWeakEventHandlers.aspx</a><br> (Website no longer exists, <a href="http://web.archive.org/web/20140319163345/http://diditwith.net/2007/03/23/SolvingTheProblemWithEventsWeakEventHandlers.aspx" rel="noreferrer">WebArchive Mirror</a>)</p> <pre><code>public delegate void UnregisterCallback&lt;TE&gt;(EventHandler&lt;TE&gt; eventHandler) where TE : EventArgs; public interface IWeakEventHandler&lt;TE&gt; where TE : EventArgs { EventHandler&lt;TE&gt; Handler { get; } } public class WeakEventHandler&lt;T, TE&gt; : IWeakEventHandler&lt;TE&gt; where T : class where TE : EventArgs { private delegate void OpenEventHandler(T @this, object sender, TE e); private readonly WeakReference mTargetRef; private readonly OpenEventHandler mOpenHandler; private readonly EventHandler&lt;TE&gt; mHandler; private UnregisterCallback&lt;TE&gt; mUnregister; public WeakEventHandler(EventHandler&lt;TE&gt; eventHandler, UnregisterCallback&lt;TE&gt; unregister) { mTargetRef = new WeakReference(eventHandler.Target); mOpenHandler = (OpenEventHandler)Delegate.CreateDelegate( typeof(OpenEventHandler),null, eventHandler.Method); mHandler = Invoke; mUnregister = unregister; } public void Invoke(object sender, TE e) { T target = (T)mTargetRef.Target; if (target != null) mOpenHandler.Invoke(target, sender, e); else if (mUnregister != null) { mUnregister(mHandler); mUnregister = null; } } public EventHandler&lt;TE&gt; Handler { get { return mHandler; } } public static implicit operator EventHandler&lt;TE&gt;(WeakEventHandler&lt;T, TE&gt; weh) { return weh.mHandler; } } public static class EventHandlerUtils { public static EventHandler&lt;TE&gt; MakeWeak&lt;TE&gt;(this EventHandler&lt;TE&gt; eventHandler, UnregisterCallback&lt;TE&gt; unregister) where TE : EventArgs { if (eventHandler == null) throw new ArgumentNullException("eventHandler"); if (eventHandler.Method.IsStatic || eventHandler.Target == null) throw new ArgumentException("Only instance methods are supported.", "eventHandler"); var wehType = typeof(WeakEventHandler&lt;,&gt;).MakeGenericType( eventHandler.Method.DeclaringType, typeof(TE)); var wehConstructor = wehType.GetConstructor(new Type[] { typeof(EventHandler&lt;TE&gt;), typeof(UnregisterCallback&lt;TE&gt;) }); IWeakEventHandler&lt;TE&gt; weh = (IWeakEventHandler&lt;TE&gt;)wehConstructor.Invoke( new object[] { eventHandler, unregister }); return weh.Handler; } } </code></pre>
3,806,655
3
12
null
2010-09-27 06:56:36.877 UTC
119
2018-02-02 12:39:33.287 UTC
2018-02-02 12:39:33.287 UTC
null
6,795
null
355,239
null
1
156
c#|.net|wpf|mvvm|modal-dialog
72,619
<p>This is a good approach and I used similar ones in the past. Go for it!</p> <p>One minor thing I'd definitely do is make the event receive a boolean for when you need to set "false" in the DialogResult.</p> <pre><code>event EventHandler&lt;RequestCloseEventArgs&gt; RequestCloseDialog; </code></pre> <p>and the EventArgs class:</p> <pre><code>public class RequestCloseEventArgs : EventArgs { public RequestCloseEventArgs(bool dialogResult) { this.DialogResult = dialogResult; } public bool DialogResult { get; private set; } } </code></pre>
37,072,185
Wrong line numbers in stack trace
<h2>The problem</h2> <p>On our ASP .net website I keep getting wrong line numbers in stack traces of exceptions. I am talking about our live environment. There seems to be a pattern: The stack trace will always point to the line that contains the method's closing curly brackets.</p> <p>For Example:</p> <pre><code>public class Foo { public void Bar() { object someObject = null; someObject.ToString(); /* arbitrarily more lines of code */ } // this line will be the one that the stack trace points to } </code></pre> <h2>More details</h2> <ul> <li><p>To be clear: This does not only happen for some method(s), it happens for every exception that we log. So I would rule out (JIT) optimizations here, that might lead to line numbers being seemingly randomly off. What bothers me is, that the wrong line numbers seem to consistently point to the closing curly brackets of the containing method.</p></li> <li><p>Note that before .net 4.6 there actually was a bug in the framework, such that if you compiled targeting x64, exactly this would happen. However, Microsoft confirmed that this has been fixed. Also running a minimal example app for this, reaffirms their claim. But for some reason it still happens on the web servers.</p></li> <li><p>It puzzles me even more that it does not happen in our test and development environments. The test and live systems are pretty similarly set up. The only real difference is that live we are running Windows Server 2012, while on the test system we are still using Windows Server 2008.</p></li> </ul> <h2>What I have checked</h2> <ul> <li>pdb files are valid (tested with chkmatch)</li> <li>Compile time code optimizations are not the issue</li> <li>The aforementioned bug in .net before 4.6 cannot be reproduced with a minimal example</li> <li>.NET versions are exactly the same</li> <li>Build comes from the same deploy script</li> </ul> <p>Any clues towards solving this problem are highly appreciated. If you know anything that we could check, please let me know. </p>
38,374,576
3
14
null
2016-05-06 12:14:51.597 UTC
4
2022-05-18 17:27:43.8 UTC
2016-05-06 13:17:32.967 UTC
null
4,679,589
null
4,679,589
null
1
31
c#|asp.net|.net
13,622
<p>Thanks everyone for your help! We found out that the <a href="https://blogs.msdn.microsoft.com/lagler-gruener/2014/01/17/scom-apm-configuration/" rel="noreferrer">SCOM APM agent</a> running on the machines in production caused our application to log wrong line numbers in the stack traces. As soon as we deactivated the agent, the line numbers were correct.</p>
23,981,391
How exactly does the callstack work?
<p>I'm trying to get a deeper understanding of how the low level operations of programming languages work and especially how they interact with the OS/CPU. I've probably read every answer in every stack/heap related thread here on Stack&nbsp;Overflow, and they are all brilliant. But there is still one thing that I didn't fully understand yet.</p> <p>Consider this function in pseudo code which tends to be valid Rust code ;-)</p> <pre><code>fn foo() { let a = 1; let b = 2; let c = 3; let d = 4; // line X doSomething(a, b); doAnotherThing(c, d); } </code></pre> <p>This is how I assume the stack to look like on line X:</p> <pre><code>Stack a +-------------+ | 1 | b +-------------+ | 2 | c +-------------+ | 3 | d +-------------+ | 4 | +-------------+ </code></pre> <p>Now, everything I've read about how the stack works is that it strictly obeys LIFO rules (last in, first out). Just like a stack datatype in .NET, Java or any other programming language.</p> <p>But if that's the case, then what happens after line X? Because obviously, the next thing we need is to work with <code>a</code> and <code>b</code>, but that would mean that the OS/CPU (?) has to pop out <code>d</code> and <code>c</code> first to get back to <code>a</code> and <code>b</code>. But then it would shoot itself in the foot, because it needs <code>c</code> and <code>d</code> in the next line.</p> <p>So, I wonder what <strong>exactly</strong> happens behind the scenes?</p> <p>Another related question. Consider we pass a reference to one of the other functions like this:</p> <pre><code>fn foo() { let a = 1; let b = 2; let c = 3; let d = 4; // line X doSomething(&amp;a, &amp;b); doAnotherThing(c, d); } </code></pre> <p>From how I understand things, this would mean that the parameters in <code>doSomething</code> are essentially pointing to the same memory address like <code>a</code> and <code>b</code> in <code>foo</code>. But then again this means that there is no <em>pop up the stack until we get to <code>a</code> and <code>b</code></em> happening.</p> <p>Those two cases make me think that I haven't fully grasped how <strong>exactly</strong> the stack works and how it strictly follows the <em>LIFO</em> rules.</p>
23,981,489
7
18
null
2014-06-01 15:27:06.287 UTC
80
2021-05-20 01:08:54.843 UTC
2014-09-12 09:56:44.643 UTC
null
183,120
null
288,703
null
1
120
assembly|cpu|callstack|low-level|calling-convention
35,284
<p>The call stack could also be called a frame stack.<br> <strong>The things that are <em>stacked</em> after the LIFO principle are not the local variables but the entire stack frames ("calls") of the functions being called</strong>. The local variables are pushed and popped together with those frames in the so-called <a href="http://en.wikipedia.org/wiki/Function_prologue" rel="noreferrer">function prologue</a> and <a href="http://en.wikipedia.org/wiki/Function_epilogue#Epilogue" rel="noreferrer">epilogue</a>, respectively.</p> <p>Inside the frame the order of the variables is completely unspecified; Compilers <a href="https://stackoverflow.com/questions/1102049/order-of-local-variable-allocation-on-the-stack">"reorder" the positions of local variables inside a frame</a> appropriately to optimize their alignment so the processor can fetch them as quickly as possible. The crucial fact is that <strong>the offset of the variables relative to some fixed address is constant throughout the lifetime of the frame</strong> - so it suffices to take an anchor address, say, the address of the frame itself, and work with offsets of that address to the variables. Such an anchor address is actually contained in the so-called <strong>base</strong> or <strong>frame pointer</strong> which is stored in the EBP register. The offsets, on the other hand, are clearly known at compile time and are therefore hardcoded into the machine code.</p> <p>This graphic from <a href="https://en.wikipedia.org/wiki/Call_stack#/media/File:Call_stack_layout.svg" rel="noreferrer">Wikipedia</a> shows what the typical call stack is structured like<sup>1</sup>:</p> <p><img src="https://i.stack.imgur.com/uiCRx.png" alt="Picture of a stack"></p> <p>Add the offset of a variable we want to access to the address contained in the frame pointer and we get the address of our variable. So shortly said, the code just accesses them directly via constant compile-time offsets from the base pointer; It's simple pointer arithmetic.</p> <h2>Example</h2> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; int main() { char c = std::cin.get(); std::cout &lt;&lt; c; } </code></pre> <p><a href="http://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4QHsDOAXATggQwFsA%2BAKDPGySIPAAoBKMgbzKQ6QgAsDcukAXiQ44ALjERwAOgDmCbEwDc7TqIkR0MaihRcVAXzJAAA%3D%3D%22%2C%22compiler%22%3A%22%2Fopt%2Fgcc-4.9.0%2Fbin%2Fg%2B%2B%22%2C%22options%22%3A%22%22%7D%5D%7D" rel="noreferrer">gcc.godbolt.org</a> gives us</p> <pre><code>main: pushq %rbp movq %rsp, %rbp subq $16, %rsp movl std::cin, %edi call std::basic_istream&lt;char, std::char_traits&lt;char&gt; &gt;::get() movb %al, -1(%rbp) movsbl -1(%rbp), %eax movl %eax, %esi movl std::cout, %edi call [... the insertion operator for char, long thing... ] movl $0, %eax leave ret </code></pre> <p>.. for <code>main</code>. I divided the code into three subsections. The function prologue consists of the first three operations:</p> <ul> <li>Base pointer is pushed onto the stack.</li> <li>The stack pointer is saved in the base pointer</li> <li>The stack pointer is subtracted to make room for local variables.</li> </ul> <p>Then <code>cin</code> is moved into the EDI register<sup>2</sup> and <code>get</code> is called; The return value is in EAX.</p> <p>So far so good. Now the interesting thing happens:</p> <p>The low-order byte of EAX, designated by the 8-bit register AL, is taken and <strong>stored in the byte right after the base pointer</strong>: That is <code>-1(%rbp)</code>, the offset of the base pointer is <code>-1</code>. <strong>This byte is our variable <code>c</code></strong>. The offset is negative because the stack grows downwards on x86. The next operation stores <code>c</code> in EAX: EAX is moved to ESI, <code>cout</code> is moved to EDI and then the insertion operator is called with <code>cout</code> and <code>c</code> being the arguments.</p> <p>Finally,</p> <ul> <li>The return value of <code>main</code> is stored in EAX: 0. That is because of the implicit <code>return</code> statement. You might also see <code>xorl rax rax</code> instead of <code>movl</code>.</li> <li>leave and return to the call site. <code>leave</code> is abbreviating this epilogue and implicitly <ul> <li>Replaces the stack pointer with the base pointer and</li> <li>Pops the base pointer. </li> </ul></li> </ul> <p>After this operation and <code>ret</code> have been performed, the frame has effectively been popped, although the caller still has to clean up the arguments as we're using the cdecl calling convention. Other conventions, e.g. stdcall, require the callee to tidy up, e.g. by passing the amount of bytes to <code>ret</code>.</p> <h3>Frame Pointer Omission</h3> <p>It is also possible not to use offsets from the base/frame pointer but from the stack pointer (ESB) instead. This makes the EBP-register that would otherwise contain the frame pointer value available for arbitrary use - but it can make <a href="https://gcc.gnu.org/onlinedocs/gcc-4.9.0/gcc/Optimize-Options.html" rel="noreferrer">debugging impossible on some machines</a>, and will be <a href="http://www.nynaeve.net/?p=91" rel="noreferrer">implicitly turned off for some functions</a>. It is particularly useful when compiling for processors with only few registers, including x86.</p> <p>This optimization is known as FPO (frame pointer omission) and set by <code>-fomit-frame-pointer</code> in GCC and <code>-Oy</code> in Clang; note that it is implicitly triggered by every optimization level > 0 if and only if debugging is still possible, since it doesn't have any costs apart from that. For further information see <a href="https://stackoverflow.com/questions/14666665/trying-to-understand-gcc-option-fomit-frame-pointer">here</a> and <a href="https://stackoverflow.com/questions/1942801/when-should-i-omit-the-frame-pointer">here</a>.</p> <hr> <p><sup>1</sup> As pointed out in the comments, the frame pointer is presumably meant to point to the address after the return address.</p> <p><sup>2</sup> Note that the registers that start with R are the 64-bit counterparts of the ones that start with E. EAX designates the four low-order bytes of RAX. I used the names of the 32-bit registers for clarity.</p>
22,552,958
Handling back press when using fragments in Android
<p>I am using Android Sliding Menu using Navigation Drawer in my application and Fragments are used in the app instead of Activities. When I open the drawer, click on an item a Fragment appears. I move from one fragment to another fragment using the following code:</p> <pre><code>Fragment fragment = null; fragment = new GalleryFragment(selectetdMainMenu.getCategoryID()); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.addToBackStack("menuFrag"); ft.add(R.id.frame_container, fragment, "menuFrag"); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); </code></pre> <p>In this way I can go from one fragment to another but I fail to come to the previous fragment on back button press. I managed to come up with this code to handle back press in MainActivity where Drawer is Initialized:</p> <pre><code>@Override public boolean onKeyDown(int keyCode, KeyEvent event) { super.onKeyDown(keyCode, event); if (keyCode == KeyEvent.KEYCODE_BACK) { Fragment fragment_byTag = fragmentManager.findFragmentByTag("menuFrag"); Fragment menuFragment_by_tag = fragmentManager.findFragmentByTag("galleryFrag"); Fragment commentsFrag_by_tag = fragmentManager.findFragmentByTag("commentsFrag"); Fragment dealDetail = fragmentManager.findFragmentByTag("promoFrag"); if(commentsFrag_by_tag != null){ if (commentsFrag_by_tag.isVisible()) { Log.e("comments back ", " clicked"); //menuDetailsFrag.onBackPressed(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().remove(commentsFrag_by_tag).commit(); fragmentManager.beginTransaction().show(menuFragment_by_tag).commit(); } }else if(menuFragment_by_tag.isVisible()){ Log.e("menu back ", " clicked"); menuDetailsFrag.onBackPressed(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().remove(menuFragment_by_tag).commit(); fragmentManager.beginTransaction().show(fragment_byTag).commit(); } } return false; } </code></pre> <p>This works at times but fails most of the time. I would greatly appreciate if a better way to navigate back can be shown.</p>
22,553,481
5
4
null
2014-03-21 07:41:54.487 UTC
16
2020-09-22 09:26:52.02 UTC
null
null
null
null
1,852,924
null
1
12
android|android-fragments|navigation|back|navigation-drawer
52,722
<p>I usually set an <code>onKeyListener</code> to the <code>View</code> in <code>onResume</code>. From what I learned you have to take care to set <code>setFocusableInTouchMode()</code> and <code>requestFocus</code> on the <code>View</code>.</p> <p>This is a sample of what I use for this purpose:</p> <pre><code>@Override public void onResume() { super.onResume(); getView().setFocusableInTouchMode(true); getView().requestFocus(); getView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP &amp;&amp; keyCode == KeyEvent.KEYCODE_BACK){ // handle back button return true; } return false; } }); } </code></pre>
22,502,118
Is ReactPHP truly asynchronous?
<p>I've been doing some tests on ReactPHP because it looks pretty awesome. I've tested it with the following <a href="https://github.com/reactphp/socket" rel="noreferrer">react/socket</a> code, for a simple socket server.</p> <pre><code>$loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $socket-&gt;on('connection', function ($conn) { echo 'New client !'; $conn-&gt;on('data', function ($data) use ($conn) { $conn-&gt;write("Wow, some data, such cool\n"); $conn-&gt;close(); }); }); $socket-&gt;listen(1337); $loop-&gt;run(); </code></pre> <p>Until this point there's no problem. The server shows <code>New client !</code> when a client is connected and the client receives the response.</p> <p>But I done a new test, with more processing on the <code>data</code> event. To illustrate my words, I'll add a <code>for</code> loop that will take a few milliseconds to complete :</p> <pre><code>$conn-&gt;on('data', function ($data) use ($conn) { $conn-&gt;write("Wow, some data, such cool\n"); for ($i=0; $i&lt;10000000; $i++); // here $conn-&gt;close(); }); </code></pre> <p>In this case, with 10 clients, the client will show the text <code>Wow, some data, such cool</code> after all clients processing <strong>(so ~2 seconds)</strong>, but server will show <code>New client !</code> without waiting.</p> <p>So here my lack of understanding, ReactPHP is an asynchronous I/O, but PHP is <strong>single-threaded</strong>, and if there is a lot of processing between input and output, that will block all clients.</p>
24,067,776
1
5
null
2014-03-19 09:58:42.453 UTC
14
2020-12-31 16:48:34.93 UTC
2017-04-18 13:53:27.853 UTC
null
199,700
null
1,305,306
null
1
37
php|sockets|asynchronous|reactphp
21,956
<blockquote> <p>ReactPHP is an asynchronous I/O, but PHP is single-threaded, and if there is a lot of processing between input and output, that will block all clients.</p> </blockquote> <p>Yes.</p> <p>ReactPHP is very much inspired by node.js, which follows the same principle. The goal of such event-based patterns is not to exploit your server 16 CPU's, but to exploit fully your processor by processing HTTP request B while your controller for request A, which has made request to database, is paused until the 'database request success' event is called.</p> <p>Your test is going exactly against the assumption made by node.js and ReactPHP: "computation is fast, I/O are slow", so if we do computation during I/O (and not between I/O), then CPU time will always be available in higher quantity than needed.</p> <p>With node.js or ReactPHP if you want to use your server 16 CPU, you just launch 16 server process on 16 port and put a load balancer like nginx in front of them.</p> <p>But keep in mind ReactPHP is still experimental and not ready for production.</p>
20,873,972
How to override the django admin translation?
<p>I'm trying to override the default translations of Django's admin site. </p> <p>I'm using Django 1.6. My <code>settings.py</code> contains:</p> <pre><code>import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # ... LANGUAGE_CODE = 'nl' USE_I18N = True USE_L10N = True LOCALE_PATHS = (os.path.join(BASE_DIR, "locale"),) </code></pre> <p>I have copied the file <code>django/contrib/admin/locale/nl/LC_MESSAGES/django.po</code> to <code>my_project/locale/nl/LC_MESSAGES/django.po</code> and I've made some changes to it.</p> <p>Next, I have run <code>python manage.py compilemessages</code> and <code>python manage.py runserver</code>.</p> <p>When I visit <code>localhost:8000/admin</code>, however, I'm still seeing Django's default admin translations. What am I doing wrong?</p> <p><strong>Edit - I found the problem:</strong></p> <p>The above description is the correct way to override app translations. I followed my own instructions and they work. The reason for my problem was that I accidentally omitted the <code>nl</code> subdirectory the first time. I am a dumb person.</p>
60,118,546
1
7
null
2014-01-01 22:31:18.557 UTC
null
2020-02-10 21:21:54.907 UTC
2019-11-11 09:08:52.813 UTC
null
7,758,804
null
1,324,356
null
1
38
python|django|localization|internationalization|django-admin
4,115
<p>I'm providing an answer, even though @hedgie mostly answered their own question. I'll add a bit of context and description of what's happening. This answer is still applicable as of Django 3.0.</p> <p>Just as you can override a Django-provided admin template by duplicating the template's name and directory structure within our own project, you can override Django-provided admin translations by duplicating a <code>.po</code> file's name and directory structure within our project.</p> <p>Django's admin translations live in <code>django/contrib/admin/locale/</code> and are organized by language in directories named <code>[language code]/LC_MESSAGES/</code>. These individual language directories contain two <code>.po</code> files, <code>django.po</code> and <code>djangojs.po</code>, and their respective compiled <code>.mo</code> files. You will be overriding the <code>.po</code> files, and compiling our own <code>.mo</code> files.</p> <p>The first thing you have to do is enable translations in settings, and tell Django where you store our translation files.</p> <p><strong>settings.py</strong></p> <pre class="lang-py prettyprint-override"><code>import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # ... LANGUAGE_CODE = 'nl-NL' USE_I18N = True USE_L10N = True LOCALE_PATHS = (os.path.join(BASE_DIR, "locale"),) # our custom translations will go here </code></pre> <p>Note that although the directory Django uses is <code>nl</code>, the full language identifier for Dutch in the Netherlands is <code>nl-NL</code>. You can find a full list of identifiers organized by country <a href="http://www.i18nguy.com/unicode/language-identifiers.html" rel="noreferrer">here</a>.</p> <p>Next, you'll mimic Django's directory structure and create two files in a new directory:</p> <p><code>my_project/locale/nl/LC_MESSAGES/django.po</code></p> <p><code>my_project/locale/nl/LC_MESSAGES/djangojs.po</code></p> <p>Note that this path must also match what you provided in <code>settings.py</code>.</p> <p>Copy and paste the contents of <a href="https://github.com/django/django/tree/master/django/contrib/admin/locale/nl/LC_MESSAGES" rel="noreferrer">Django's translation files</a>. You can now edit the translations for whichever strings you like. For example:</p> <p><strong>django.po</strong></p> <pre><code>msgid "Are you sure?" --- msgstr "Weet u het zeker?" +++ msgstr "Weet u het zeker?!" </code></pre> <p>Now you need to compile the messages with:</p> <p><code>python manage.py compilemessages</code></p> <p>This command compiles your <code>.po</code> files into <code>.mo</code> files, which Django will use to translate any matching gettext calls. You should now see your custom translations in the admin interface.</p>
22,386,030
Cannot checkout, file is unmerged
<p>I am trying to remove the file from my working directory but after using the following command </p> <pre><code>git checkout file_Name.txt </code></pre> <p>I got the following error message</p> <pre><code>error: path 'first_Name.txt' is unmerged </code></pre> <p>What is that and how to resolve it?</p> <p>Following is my git status </p> <pre><code>$ git status On branch master You are currently reverting commit f200bf5. (fix conflicts and run "git revert --continue") (use "git revert --abort" to cancel the revert operation) Unmerged paths: (use "git reset HEAD &lt;file&gt;..." to unstage) (use "git add &lt;file&gt;..." to mark resolution) both modified: first_file.txt Untracked files: (use "git add &lt;file&gt;..." to include in what will be committed) explore_california/ no changes added to commit (use "git add" and/or "git commit -a") </code></pre>
22,388,567
8
8
null
2014-03-13 17:14:15.153 UTC
19
2021-03-26 13:09:20.737 UTC
2020-02-24 16:51:19.22 UTC
null
10,871,900
null
2,908,528
null
1
115
git|version-control|merge-conflict-resolution
156,451
<p>To remove tracked files (first_file.txt) from git:</p> <pre><code>git rm first_file.txt </code></pre> <p>And to remove untracked files, use:</p> <pre><code>rm -r explore_california </code></pre>
10,992,921
How to remove emoji code using javascript?
<p>How do I remove emoji code using JavaScript? I thought I had taken care of it using the code below, but I still have characters like .</p> <pre class="lang-js prettyprint-override"><code>function removeInvalidChars() { return this.replace(/[\uE000-\uF8FF]/g, ''); } </code></pre>
10,999,907
16
3
null
2012-06-12 08:22:05.36 UTC
17
2022-03-22 14:34:32.34 UTC
2019-10-30 01:13:14.257 UTC
null
8,757,967
null
188,477
null
1
51
javascript|unicode|emoji
84,260
<p>The range you have selected is the Private Use Area, containing non-standard characters. Carriers used to encode emoji as different, inconsistent values inside this range.</p> <p>More recently, the emoji have been given standardised 'unified' codepoints. Many of these are outside of the Basic Multilingual Plane, in the block U+1F300–U+1F5FF, including your example U+1F534 Large Red Circle.</p> <p>You could detect these characters with <code>[\U0001F300-\U0001F5FF]</code> in a regex engine that supported non-BMP characters, but JavaScript's <code>RegExp</code> is not such a beast. Unfortunately the JS string model is based on UTF-16 code units, so you'd have to work with the UTF-16 surrogates in a regexp:</p> <pre><code>return this.replace(/([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])/g, '') </code></pre> <p>However, note that there are other characters in the Basic Multilingual Plane that are used as emoji by phones but which long predate emoji. For example U+2665 is the traditional Heart Suit character ♥, but it may be rendered as an emoji graphic on some devices. It's up to you whether you treat this as emoji and try to remove it. See <a href="http://code.iamcal.com/php/emoji/" rel="noreferrer">this list</a> for more examples.</p>
11,267,154
Fit cell width to content
<p>Given the following markup, how could I use CSS to force one cell (all cells in column) to fit to the width of the content within it rather than stretch (which is the default behaviour)?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>td.block { border: 1px solid black; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table style="width: 100%;"&gt; &lt;tr&gt; &lt;td class="block"&gt;this should stretch&lt;/td&gt; &lt;td class="block"&gt;this should stretch&lt;/td&gt; &lt;td class="block"&gt;this should be the content width&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>I realize I could hard code the width, but I'd rather not do that, as the content which will go in that column is dynamic.</p> <p>Looking at the image below, the first image is what the markup produces. The second image is what I want.</p> <p><img src="https://i.stack.imgur.com/stdKt.png" alt="enter image description here" /></p>
11,267,268
6
1
null
2012-06-29 18:33:49.617 UTC
60
2022-06-28 15:06:06.837 UTC
2022-06-28 14:55:48.87 UTC
null
1,264,804
null
1,324,019
null
1
365
html|css|html-table
606,971
<p>I'm not sure if I understand your question, but I'll take a stab at it:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>td { border: 1px solid #000; } tr td:last-child { width: 1%; white-space: nowrap; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table style="width: 100%;"&gt; &lt;tr&gt; &lt;td class="block"&gt;this should stretch&lt;/td&gt; &lt;td class="block"&gt;this should stretch&lt;/td&gt; &lt;td class="block"&gt;this should be the content width&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
11,085,308
Changing the background drawable of the searchview widget
<p>I'm trying to change the drawable that sits in the Android actionbar searchview widget.</p> <p>Currently it looks like this: <img src="https://i.stack.imgur.com/FwEUY.png" alt="enter image description here"></p> <p>but I need to change the blue background drawable to a red colour.</p> <p>I've tried many things short of rolling my own search widget, but nothing seems to work.</p> <p>Can somebody point me in the right direction to changing this?</p>
11,669,808
12
5
null
2012-06-18 14:48:02.903 UTC
115
2020-06-28 12:03:04.823 UTC
2012-07-27 22:37:31.067 UTC
null
54,964
null
264,276
null
1
126
android|styles|android-actionbar|searchview|background-drawable
80,659
<h2>Intro</h2> <p>Unfortunately there's no way to set <code>SearchView</code> text field style using themes, styles and inheritance in XML as you <a href="https://stackoverflow.com/questions/9019512/how-can-i-change-the-touch-effect-color-of-the-actionbar-in-android-3-0-and-high">can do with background of items in ActionBar dropdown</a>. This is because <code>selectableItemBackground</code> <a href="http://developer.android.com/reference/android/R.styleable.html#Theme_selectableItemBackground" rel="noreferrer">is listed as styleable</a> in <code>R.stylable</code>, whereas <code>searchViewTextField</code> (theme attribute that we're interested in) is not. Thus, we cannot access it easily from within XML resources (you'll get a <code>No resource found that matches the given name: attr 'android:searchViewTextField'</code> error).</p> <h2>Setting SearchView text field background from code</h2> <p>So, the only way to properly substitute background of <code>SearchView</code> text field is to get into it's internals, acquire access to view that has background set based on <code>searchViewTextField</code> and set our own.</p> <p><strong>NOTE:</strong> Solution below depends only on id (<code>android:id/search_plate</code>) of element within <code>SearchView</code>, so it's more SDK-version independent than children traversal (e.g. using <code>searchView.getChildAt(0)</code> to get to the right view within <code>SearchView</code>), but it's not bullet-proof. Especially if some manufacturer decides to reimplement internals of <code>SearchView</code> and element with above-mentioned id is not present - the code won't work.</p> <p>In SDK, the background for text field in <code>SearchView</code> is declared through <a href="http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch" rel="noreferrer">nine-patches</a>, so we'll do it the same way. You can find original <em>png</em> images in <a href="https://github.com/android/platform_frameworks_base/tree/master/core/res/res/drawable-mdpi" rel="noreferrer">drawable-mdpi</a> directory of <a href="https://github.com/android/platform_frameworks_base" rel="noreferrer">Android git repository</a>. We're interested in two image. One for state when text field is selected (named <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable-mdpi/textfield_search_selected_holo_light.9.png" rel="noreferrer">textfield_search_selected_holo_light.9.png</a>) and one for where it's not (named <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable-mdpi/textfield_search_default_holo_light.9.png" rel="noreferrer">textfield_search_default_holo_light.9.png</a>).</p> <p>Unfortunately, you'll have to create local copies of both images, even if you want to customize only <em>focused</em> state. This is because <code>textfield_search_default_holo_light</code> is not present in <a href="http://developer.android.com/reference/android/R.drawable.html" rel="noreferrer">R.drawable</a>. Thus it's not easily accessible through <code>@android:drawable/textfield_search_default_holo_light</code>, which could be used in selector shown below, instead of referencing local drawable.</p> <p><strong>NOTE:</strong> I was using <em>Holo Light</em> theme as base, but you can do the same with <em>Holo Dark</em>. It seems that there's no real difference in <em>selected state</em> 9-patches between <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable-xhdpi/textfield_search_selected_holo_light.9.png" rel="noreferrer">Light</a> and <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable-xhdpi/textfield_search_selected_holo_dark.9.png" rel="noreferrer">Dark</a> themes. However, there's a difference in 9-patches for <em>default state</em> (see <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable-xhdpi/textfield_search_default_holo_light.9.png" rel="noreferrer">Light</a> vs <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable-xhdpi/textfield_search_default_holo_dark.9.png" rel="noreferrer">Dark</a>). So, probably there's no need to make local copies of 9-patches for <em>selected state</em>, for both <em>Dark</em> and <em>Light</em> themes (assuming that you want to handle both, and make them both look the same as in <em>Holo Theme</em>). Simply make one local copy and use it in <em>selector drawable</em> for both themes.</p> <p>Now, you'll need to edit downloaded nine-patches to your need (i.e. changing blue color to red one). You can take a look at file using <a href="http://developer.android.com/tools/help/draw9patch.html" rel="noreferrer">draw 9-patch tool</a> to check if it is correctly defined after your edit.</p> <p>I've edited files using <a href="http://www.gimp.org/" rel="noreferrer">GIMP</a> with one-pixel pencil tool (pretty easy) but you'll probably use the tool of your own. Here's my customized 9-patch for <em>focused state</em>:</p> <p><img src="https://i.stack.imgur.com/ON8mG.png" alt="enter image description here"></p> <p><strong>NOTE:</strong> For simplicity, I've used only images for <em>mdpi</em> density. You'll have to create <em>9-patches</em> for multiple screen densities if, you want the best result on any device. Images for <em>Holo</em> <code>SearchView</code> can be found in <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable-mdpi/textfield_search_selected_holo_light.9.png" rel="noreferrer">mdpi</a>, <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable-hdpi/textfield_search_selected_holo_light.9.png" rel="noreferrer">hdpi</a> and <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable-xhdpi/textfield_search_selected_holo_light.9.png" rel="noreferrer">xhdpi</a> drawable.</p> <p>Now, we'll need to create drawable selector, so that proper image is displayed based on view state. Create file <code>res/drawable/texfield_searchview_holo_light.xml</code> with following content:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_focused="true" android:drawable="@drawable/textfield_search_selected_holo_light" /&gt; &lt;item android:drawable="@drawable/textfield_search_default_holo_light" /&gt; &lt;/selector&gt; </code></pre> <p>We'll use the above created drawable to set background for <code>LinearLayout</code> view that holds text field within <code>SearchView</code> - its id is <code>android:id/search_plate</code>. So here's how to do this quickly in code, when creating options menu:</p> <pre><code>public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); // Getting SearchView from XML layout by id defined there - my_search_view in this case SearchView searchView = (SearchView) menu.findItem(R.id.my_search_view).getActionView(); // Getting id for 'search_plate' - the id is part of generate R file, // so we have to get id on runtime. int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null); // Getting the 'search_plate' LinearLayout. View searchPlate = searchView.findViewById(searchPlateId); // Setting background of 'search_plate' to earlier defined drawable. searchPlate.setBackgroundResource(R.drawable.textfield_searchview_holo_light); return super.onCreateOptionsMenu(menu); } } </code></pre> <h2>Final effect</h2> <p>Here's the screenshot of the final result:</p> <p><img src="https://i.stack.imgur.com/XqcZ4.png" alt="enter image description here"></p> <h2>How I got to this</h2> <p>I think it's worth metioning how I got to this, so that this approach can be used when customizing other views.</p> <h3>Checking out view layout</h3> <p>I've checked how <code>SearchView</code> layout looks like. In <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.4_r1.2/android/widget/SearchView.java/#248" rel="noreferrer">SearchView contructor</a> one can find a line that inflates layout:</p> <pre><code>inflater.inflate(R.layout.search_view, this, true); </code></pre> <p>Now we know that <code>SearchView</code> layout is in file named <code>res/layout/search_view.xml</code>. Looking into <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/layout/search_view.xml#L75" rel="noreferrer">search_view.xml</a> we can find an inner <code>LinearLayout</code> element (with id <code>search_plate</code>) that has <code>android.widget.SearchView$SearchAutoComplete</code> inside it (looks like ours search view text field):</p> <pre><code> &lt;LinearLayout android:id="@+id/search_plate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_gravity="center_vertical" android:orientation="horizontal" android:background="?android:attr/searchViewTextField"&gt; </code></pre> <p>Now, we now that the background is set based on current theme's <code>searchViewTextField</code> attribute.</p> <h3>Investigating attribute (is it easily settable?)</h3> <p>To check how <code>searchViewTextField</code> attribute is set, we investigate <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml#L343" rel="noreferrer">res/values/themes.xml</a>. There's a group of attributes related to <code>SearchView</code> in default <code>Theme</code>:</p> <pre><code>&lt;style name="Theme"&gt; &lt;!-- (...other attributes present here...) --&gt; &lt;!-- SearchView attributes --&gt; &lt;item name="searchDropdownBackground"&gt;@android:drawable/spinner_dropdown_background&lt;/item&gt; &lt;item name="searchViewTextField"&gt;@drawable/textfield_searchview_holo_dark&lt;/item&gt; &lt;item name="searchViewTextFieldRight"&gt;@drawable/textfield_searchview_right_holo_dark&lt;/item&gt; &lt;item name="searchViewCloseIcon"&gt;@android:drawable/ic_clear&lt;/item&gt; &lt;item name="searchViewSearchIcon"&gt;@android:drawable/ic_search&lt;/item&gt; &lt;item name="searchViewGoIcon"&gt;@android:drawable/ic_go&lt;/item&gt; &lt;item name="searchViewVoiceIcon"&gt;@android:drawable/ic_voice_search&lt;/item&gt; &lt;item name="searchViewEditQuery"&gt;@android:drawable/ic_commit_search_api_holo_dark&lt;/item&gt; &lt;item name="searchViewEditQueryBackground"&gt;?attr/selectableItemBackground&lt;/item&gt; </code></pre> <p>We see that for default theme the value is <code>@drawable/textfield_searchview_holo_dark</code>. For <code>Theme.Light</code> value <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml#L461" rel="noreferrer">is also set in that file</a>.</p> <p>Now, it would be great if this attribute was accessible through <a href="http://developer.android.com/reference/android/R.styleable.html" rel="noreferrer">R.styleable</a>, but, unfortunately it's not. For comparison, see other <em>theme</em> attributes which are present both in <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml" rel="noreferrer">themes.xml</a> and <a href="http://developer.android.com/reference/android/R.attr.html" rel="noreferrer">R.attr</a> like <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml#L60" rel="noreferrer">textAppearance</a> or <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml#L118" rel="noreferrer">selectableItemBackground</a>. If <code>searchViewTextField</code> was present in <code>R.attr</code> (and <code>R.stylable</code>) we could simply use our drawable selector when defining theme for our whole application in XML. For example:</p> <pre><code>&lt;resources xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;style name="AppTheme" parent="android:Theme.Light"&gt; &lt;item name="android:searchViewTextField"&gt;@drawable/textfield_searchview_holo_light&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <h3>What should be modified?</h3> <p>Now we know, that we'll have to access <code>search_plate</code> through code. However, we still don't know how it should look like. In short, we search for drawables used as values in default themes: <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable/textfield_searchview_holo_dark.xml" rel="noreferrer">textfield_searchview_holo_dark.xml</a> and <a href="https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable/textfield_searchview_holo_light.xml" rel="noreferrer">textfield_searchview_holo_light.xml</a>. Looking at content we see that the drawable is <code>selector</code> which reference two other drawables (which occur to be 9-patches later on) based on view state. You can find aggregated 9-patch drawables from (almost) all version of Android on <a href="http://androiddrawables.com/widget.html" rel="noreferrer">androiddrawables.com</a></p> <h3>Customizing</h3> <p>We recognize the blue line in <a href="https://github.com/android/platform_frameworks_base/raw/android-4.0.1_r1.2/core/res/res/drawable-mdpi/textfield_search_selected_holo_dark.9.png" rel="noreferrer">one of the 9-patches</a>, so we create local copy of it and change colors as desired.</p>
48,411,897
Severe performance drop with MongoDB Change Streams
<p>I want to get real-time updates about MongoDB database changes in Node.js.</p> <p>A single MongoDB change stream sends update notifications almost instantly. But when I open multiple (10+) streams, there are massive delays (up to several minutes) between database writes and notification arrival.</p> <p>That's how I set up a change stream:</p> <pre class="lang-js prettyprint-override"><code>let cursor = collection.watch([ {$match: {"fullDocument.room": roomId}}, ]); cursor.stream().on("data", doc =&gt; {...}); </code></pre> <p>I tried an alternative way to set up a stream, but it's just as slow:</p> <pre><code>let cursor = collection.aggregate([ {$changeStream: {}}, {$match: {"fullDocument.room": roomId}}, ]); cursor.forEach(doc =&gt; {...}); </code></pre> <p>An automated process inserts tiny documents into the collection while collecting performance data. </p> <p>Some additional details:</p> <ul> <li>Open stream cursors count: 50</li> <li>Write speed: 100 docs/second (batches of 10 using <code>insertMany</code>)</li> <li>Runtime: 100 seconds</li> <li>Average delay: 7.1 seconds</li> <li>Largest delay: 205 seconds <em>(not a typo, over three minutes)</em></li> <li>MongoDB version: 3.6.2</li> <li>Cluster setup #1: MongoDB Atlas M10 (3 replica set)</li> <li>Cluster setup #2: DigitalOcean Ubuntu box + single instance mongo cluster in Docker</li> <li>Node.js CPU usage: &lt;1%</li> </ul> <p>Both setups produce the same issue. What could be going on here?</p>
48,530,042
1
10
null
2018-01-23 22:30:12.193 UTC
12
2021-11-19 07:59:33.9 UTC
2018-01-24 00:22:23.803 UTC
null
1,043,137
null
1,043,137
null
1
45
mongodb
11,642
<p>The <a href="http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#.connect" rel="nofollow noreferrer">default connection pool size</a> in the Node.js client for MongoDB is 5. Since <strong>each change stream cursor opens a new connection</strong>, the connection pool needs to be at least as large as the number of cursors.</p> <p>In version 3.x of the Node Mongo Driver use 'poolSize':</p> <pre><code>const mongoConnection = await MongoClient.connect(URL, {poolSize: 100}); </code></pre> <p>In <a href="https://docs.mongodb.com/drivers/node/master/fundamentals/connection/#connection-options" rel="nofollow noreferrer">version 4.x</a> of the Node Mongo Driver use 'minPoolSize' and 'maxPoolSize':</p> <pre><code>const mongoConnection = await MongoClient.connect(URL, {minPoolSize: 100, maxPoolSize: 1000}); </code></pre> <p>(Thanks to MongoDB Inc. for investigating <a href="https://jira.mongodb.org/browse/SERVER-32946" rel="nofollow noreferrer">this issue</a>.)</p>
13,060,467
Difference between 24:00 and 00:00?
<p>What is the difference between 24:00 clock and 00:00 clock. IMO 24:00 clock is the day before and 00:00 clock is the beginning of the new day. But I'm not really convinced and I'm new to date programming</p> <p>Update: Here is what wikipedia article say about military time and style guide about how to deal with 24:00 and 00:00 confusion: <a href="http://en.m.wikipedia.org/wiki/24-hour_clock#section_1" rel="noreferrer">http://en.m.wikipedia.org/wiki/24-hour_clock#section_1</a>. </p>
13,060,541
7
10
null
2012-10-25 01:47:13.183 UTC
3
2016-11-25 10:34:40.107 UTC
2016-01-02 08:54:25.413 UTC
null
340,457
null
340,457
null
1
7
php|date
53,443
<p>After 23:59 comes 0:00, not 24:00 Please see the code below, in php, as you put the 'php' tag:</p> <pre><code>echo date('G:i:s', mktime(0,0,0)) . "\n" ; echo date('G:i:s', mktime(0,0,0)-1) . "\n" ; </code></pre> <p>It will display:</p> <pre><code>0:00:00 23:59:59 </code></pre>
12,855,952
Bitmap.createBitmap(Bitmap source, int x, int y, int width, int height) return wrong bitmap
<p>I have to crop a bitmap image. For this, I am using </p> <pre><code>Bitmap bitmap = Bitmap.createBitmap(imgView.getWidth(),imgView.getHeight(), Bitmap.Config.RGB_565); Bitmap result =Bitmap.createBitmap(bitmap,imgView.getLeft()+10, imgView.getTop()+50, imgView.getWidth()-20, imgView.getHeight()-100); bitmap.recycle(); Canvas canvas = new Canvas(result); imgView.draw(canvas); </code></pre> <p>But it cuts the bottom and right of the bitmap. Top and Left part of the bitmap exists in the output. That means x and y position has no effect.</p> <p>I am searched for good documentation. But I couldn't.</p> <p>Thanks in Advance</p> <p>What is the problem here and how to solve?</p>
12,856,062
1
0
null
2012-10-12 09:21:43.55 UTC
null
2019-05-13 09:28:35.093 UTC
2019-05-13 09:28:35.093 UTC
null
7,832,102
null
1,711,265
null
1
8
android|image
48,323
<p>Basically your problem arises form the fact that you create a bitmap. You don't put anything in it. You then create a smaller bitmap and then you render an imageView to that smaller bitmap.</p> <p>This cuts off the bottom 100 pixels and right 20 pixels.</p> <p>You need to Create the large bitmap. Add the imageview data to that bitmap. Then resize it.</p> <p>The following code should work:</p> <pre><code>Bitmap bitmap = Bitmap.createBitmap(imgView.getWidth(),imgView.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); imgView.draw(canvas); Bitmap result =Bitmap.createBitmap(bitmap,imgView.getLeft()+10, imgView.getTop()+50, imgView.getWidth()-20, imgView.getHeight()-100); bitmap.recycle(); </code></pre>
12,822,810
Structuring CSS (SASS, LESS) files by elements, by function and by media queries: 3D code structure?
<h2>Zero-D</h2> <p>Everybody starts using CSS with a single file that contains all the styles.</p> <ul> <li><code>style.css</code></li> </ul> <h2>1D</h2> <p>Soon it becomes bulky and one decides to group CSS in a number of files by page elements:</p> <ul> <li><code>html_elements.css</code></li> <li><code>header.css</code></li> <li><code>main-area.css</code></li> <li><code>footer.css</code></li> </ul> <p>Some may find this not convenient enough and group styles by function:</p> <ul> <li><code>typography.css</code></li> <li><code>layout.css</code></li> <li><code>sticky-footer.css</code> (contains declarations for many elements, not footer only)</li> </ul> <h2>2D</h2> <p>When a project has a lot of CSS, it might require using both groupings simultaneously. CSS files structure becomes two-dimensional:</p> <p><code>layout/</code></p> <ul> <li><code>grid-system.css</code></li> <li><code>header.css</code></li> <li><code>sidebars.css</code></li> </ul> <p><code>look/</code></p> <ul> <li><code>typography/</code> <ul> <li><code>main.css</code></li> <li><code>headers.css</code></li> <li><code>lists.css</code></li> </ul></li> <li><code>backgrounds/</code> <ul> <li><code>html_elements.css</code></li> <li><code>header.css</code></li> <li><code>main-area.css</code></li> <li><code>footer.css</code></li> </ul></li> </ul> <p>Okay, the example is fabricated, but you sure do understand what i mean.</p> <p>Up to this point everything is fine.</p> <h2>Enter Media Query</h2> <p>This is where my CSS structure gets funked up.</p> <p>In addition to the 2D structure described above, i have to structure my code by media queries:</p> <ul> <li>Some of my styles are universal (applied everywhere)</li> <li>Some are applied to certain screen size only: <ul> <li>small;</li> <li>medium;</li> <li>large;</li> <li>extra large.</li> </ul></li> <li>Some are applied to certain groups of screen sizes: <ul> <li>everything except small (non-mobile styles);</li> <li>small and medium (where sidebars aren't at the sides)</li> <li>large and xlarge (where you do have sidebars)</li> </ul></li> </ul> <p>I tried to overcome the issue by scattering media queried styles among existing CSS files. The <a href="https://github.com/canarymason/breakpoint" rel="noreferrer">breakpoint</a> Compass extension helps a lot, but the stylesheets become too messy. Finding a certain style when it's not portrayed in the files structures a lot of pain.</p> <p>I tried grouping by media queries, then by elements and function. But files structure is two dimensional, so you can't add a new dimension, you can only add another level of hierarchy. So, it's not graceful. Also, it's very bulky.</p> <p>So i end up with a 2D structure with media queries on one axis and an ugly mix of elements and functions on the other axis.</p> <p>I'm absolutely not satisfied with that but i just fail to come up with a graceful solution. Please suggest one.</p>
12,824,576
4
2
null
2012-10-10 15:17:43.817 UTC
10
2012-10-10 16:58:47.167 UTC
2012-10-10 16:06:13.81 UTC
null
901,944
null
901,944
null
1
16
css|coding-style|sass|less
4,715
<p>CSS is already a structured language. For better or worse, the order of your code changes it's meaning. Because of that, it's important that any CSS organization scheme is dictated primarily by the cascade. The other structural aspect of CSS is semantics. Use it to your advantage. The concern of organization is keeping things meaningful and maintainable. The best thing you can do to retain meaning is to show relationships. Relationships are already expressed by semantics.</p> <p>Put those things together, and you end up with code organized by <strong>specificity</strong> first and then <strong>semantics</strong>, but never by external concepts such as type vs. layout or screen-size. Here's my naming scheme:</p> <pre><code>base/ - Sass imports and settings - no CSS output. - e.g _grid, _colors, _rhythm, etc. general/ - Initial CSS baseline with resets, defaults, font imports, and classes to extend. - e.g. _reset, _root, _fonts, _icons, _defaults, etc. layout/ - The rough outline of the site structure. - Not "layout" as a set of properties excluding type, "layout" as the overall site template which might well include typography. - e.g. _banner, _nav, _main, _contentinfo, etc. modules/ - All the details. First by effect (classes/general), then by widget (ids/specifics). - e.g. _users, _admin, _product-lists etc. </code></pre> <p><strong>Media-queries should stay as close as possible to the code they affect.</strong> When possible, they go directly inline (with Sass media bubbling). If that becomes bulky, they move outside the block, but <em>never outside the partial</em>. MQ's are overrides. When you override code, it is especially important that you are able to see exactly what is being overridden.</p> <p>On some sites, you may take this structure farther. I've occasionally added two folders at the end: <code>plugins/</code> to manage 3rd-party code, and <code>overrides/</code> to handle unavoidable (try to avoid them!) location-specific overrides to a widget. I've also gone deeper, adding a <code>fonts/</code> folder with partials for each font family, or a <code>users/</code> folder with partials for adding, editing, viewing, etc. The specifics are flexible, but the basic organization remains the same:</p> <ul> <li>Start general.</li> <li>Move towards specifics as slowly as possible.</li> <li><strong>Never</strong> divide based on any external concepts (type/layout, screen-sizes, etc).</li> </ul>
37,281,928
Making a copy of an entire namespace?
<p>I'd like to make a copy of an entire namespace while replacing some functions with dynamically constructed versions.</p> <p>In other words, starting with namespace (<code>import tensorflow as tf</code>), I want to make a copy of it, replace some functions with my own versions, and update <code>__globals__</code> of all the symbols to stay within the new namespace. This needs to be done in topological order of dependency.</p> <p>I started doing something like it <a href="https://docs.google.com/document/d/1tPCaS89mb83lNTHSAa9-tC94s42aWpXw8MaZEhLZzVE/edit">here</a> but now I'm starting to wonder if I'm reinventing the wheel. Care is needed to deal with circular dependencies in system modules, functions/types/objects need to be updated differently, etc.</p> <p>Can anyone point to existing code that solves a similar task?</p>
37,378,018
3
9
null
2016-05-17 16:38:18.847 UTC
9
2016-05-22 19:09:35.13 UTC
2016-05-21 18:10:41.727 UTC
null
419,116
null
419,116
null
1
9
python
1,425
<p>To patch a set of functions while importing second instances of a set of functions, you can override the standard Python import hook and apply the patches directly at import time. This will make sure that no other module will ever see the unpatched versions of any of the modules, so even if they import functions from another module directly by name, they will only see the patched functions. Here is a proof-of-concept implementation:</p> <pre><code>import __builtin__ import collections import contextlib import sys @contextlib.contextmanager def replace_import_hook(new_import_hook): original_import = __builtin__.__import__ __builtin__.__import__ = new_import_hook yield original_import __builtin__.__import__ = original_import def clone_modules(patches, additional_module_names=None): """Import new instances of a set of modules with some objects replaced. Arguments: patches - a dictionary mapping `full.module.name.symbol` to the new object. additional_module_names - a list of the additional modules you want new instances of, without replacing any objects in them. Returns: A dictionary mapping module names to the new patched module instances. """ def import_hook(module_name, *args): result = original_import(module_name, *args) if module_name not in old_modules or module_name in new_modules: return result # The semantics for the return value of __import__() are a bit weird, so we need some logic # to determine the actual imported module object. if len(args) &gt;= 3 and args[2]: module = result else: module = reduce(getattr, module_name.split('.')[1:], result) for symbol, obj in patches_by_module[module_name].items(): setattr(module, symbol, obj) new_modules[module_name] = module return result # Group patches by module name patches_by_module = collections.defaultdict(dict) for dotted_name, obj in patches.items(): module_name, symbol = dotted_name.rsplit('.', 1) # Only allows patching top-level objects patches_by_module[module_name][symbol] = obj try: # Remove the old module instances from sys.modules and store them in old_modules all_module_names = list(patches_by_module) if additional_module_names is not None: all_module_names.extend(additional_module_names) old_modules = {} for name in all_module_names: old_modules[name] = sys.modules.pop(name) # Re-import modules to create new patched versions with replace_import_hook(import_hook) as original_import: new_modules = {} for module_name in all_module_names: import_hook(module_name) finally: sys.modules.update(old_modules) return new_modules </code></pre> <p>And here some test code for this implementation:</p> <pre><code>from __future__ import print_function import math import random def patched_log(x): print('Computing log({:g})'.format(x)) return math.log(x) patches = {'math.log': patched_log} cloned_modules = clone_modules(patches, ['random']) new_math = cloned_modules['math'] new_random = cloned_modules['random'] print('Original log: ', math.log(2.0)) print('Patched log: ', new_math.log(2.0)) print('Original expovariate: ', random.expovariate(2.0)) print('Patched expovariate: ', new_random.expovariate(2.0)) </code></pre> <p>The test code has this output:</p> <pre><code>Computing log(4) Computing log(4.5) Original log: 0.69314718056 Computing log(2) Patched log: 0.69314718056 Original expovariate: 0.00638038735379 Computing log(0.887611) Patched expovariate: 0.0596108277801 </code></pre> <p>The first two lines of output result from <a href="https://hg.python.org/cpython/file/2.7/Lib/random.py#l60" rel="nofollow">these two lines in <code>random</code></a>, which are executed at import time. This demonstrates that <code>random</code> sees the patched function right away. The rest of the output demonstrates that the original <code>math</code> and <code>random</code> still use the unpatched version of <code>log</code>, while the cloned modules both use the patched version.</p> <p>A cleaner way of overriding the import hook might be to use a <em>meta import hook</em> as defined in <a href="https://www.python.org/dev/peps/pep-0302/" rel="nofollow">PEP 302</a>, but providing a full implementation of that approach is beyond the scope of StackOverflow.</p>
37,304,897
How to find out which thread holds the monitor?
<p>My application is using <code>Gson 2.2</code> for converting <code>POJOs</code> to <code>JSON</code>. When I was making a load test I stumbled upon a lot of threads blocked in <code>Gson</code> constructor:</p> <pre><code>"http-apr-28201-exec-28" #370 daemon prio=5 os_prio=0 tid=0x0000000001ee7800 nid=0x62cb waiting for monitor entry [0x00007fe64df9a000] java.lang.Thread.State: BLOCKED (on object monitor) at com.google.gson.Gson.&lt;init&gt;(Gson.java:200) at com.google.gson.Gson.&lt;init&gt;(Gson.java:179) </code></pre> <p>Thread dump does NOT show any threads holding <code>[0x00007fe64df9a000] monitor</code>. <strong>How can I find out who holds it?</strong></p> <p><code>Gson</code> code <a href="http://grepcode.com/file/repo1.maven.org/maven2/com.google.code.gson/gson/2.2/com/google/gson/Gson.java?av=f#200">at line 200</a> looks pretty innocent:</p> <pre><code>// built-in type adapters that cannot be overridden factories.add(TypeAdapters.STRING_FACTORY); factories.add(TypeAdapters.INTEGER_FACTORY); </code></pre> <p>I'm using <code>JRE 1.8.0_91</code> on <code>Linux</code></p>
37,385,506
2
12
null
2016-05-18 16:09:42.96 UTC
4
2021-06-06 04:34:41.92 UTC
2016-05-22 17:44:11.23 UTC
null
2,293,534
null
504,452
null
1
31
java|multithreading|gson|thread-dump
3,695
<p><strong>tl;dr</strong> I think you are running into GC-related behavior, where threads are being put in waiting state to allow for garbage collection.</p> <hr /> <p>I do not have the whole truth but I hope to provide some pieces of insight.</p> <p><strong>First</strong> thing to realize is that the number in brackets, <code>[0x00007fe64df9a000]</code>, is not the address of a monitor. The number in brackets can be seen for all threads in a dump, even threads that are in running state. The number also does not change. Example from my test dump:</p> <pre><code>main&quot; #1 prio=5 os_prio=0 tid=0x00007fe27c009000 nid=0x27e5c runnable [0x00007fe283bc2000] java.lang.Thread.State: RUNNABLE at Foo.main(Foo.java:12) </code></pre> <p>I am not sure what the number means, but <a href="http://www.oracle.com/technetwork/java/javase/felog-138657.html" rel="nofollow noreferrer">this page</a> hints that it is:</p> <blockquote> <p>... the pointer to the Java VM internal thread structure. It is generally of no interest unless you are debugging a live Java VM or core file.</p> </blockquote> <p>Although the format of the trace explained there is a bit different so I am not sure I am correct.</p> <p>The way a dump looks when the address of the actual monitor is shown:</p> <pre><code>&quot;qtp48612937-70&quot; #70 prio=5 os_prio=0 tid=0x00007fbb845b4800 nid=0x133c waiting for monitor entry [0x00007fbad69e8000] java.lang.Thread.State: BLOCKED (on object monitor) at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:233) - waiting to lock &lt;0x00000005b8d68e90&gt; (a java.lang.Object) </code></pre> <p>Notice the <code>waiting to lock</code> line in the trace and that the address of the monitor is different from the number in brackets.</p> <p>The fact that we cannot see the address of the monitor involved indicates that the monitor exists only in native code.</p> <p><strong>Secondly</strong>, the Gson code involved does not contain any synchronization at all. The code just adds an element to an <code>ArrayList</code> (assuming no bytecode manipulation has been done and nothing fishy is being done at low level). I.e., it would not make sense to see the thread waiting for a standard synchronization monitor at this call.</p> <p>I found <a href="https://stackoverflow.com/q/7067058/423991">some</a>, <a href="https://stackoverflow.com/questions/4016356/java-blocking-issue-why-would-jvm-block-threads-in-many-different-classes-metho">indications</a> that threads can be shown as waiting for a monitor entry when there is a lot of GC going on.</p> <p>I wrote a simple test program to try to reproduce it by just adding a lot of elements to an array list:</p> <pre><code>List&lt;String&gt; l = new ArrayList&lt;&gt;(); while (true) { for (int i = 0; i &lt; 100_100; i++) { l.add(&quot;&quot; + i); } l = new ArrayList&lt;&gt;(); } </code></pre> <p>Then I took thread dumps of this program. Occasionally I ran into the following trace:</p> <pre><code>&quot;main&quot; #1 prio=5 os_prio=0 tid=0x00007f35a8009000 nid=0x12448 waiting on condition [0x00007f35ac335000] java.lang.Thread.State: RUNNABLE at Foo.main(Foo.java:10) &lt;--- Line of l.add() </code></pre> <p>While not identical to the OP's trace, it is interesting to have a thread <code>waiting on condition</code> when no synchronization is involved. I experienced it more frequently with a smaller heap, indicating that it might be GC related.</p> <p>Another possibility could be that code that contains synchronization has been JIT compiled and that prevents you from seeing the actual address of the monitor. However, I think that is less likely since you experience it on <code>ArrayList.add</code>. If that is the case, I know of no way to find out the actual holder of the monitor.</p>
17,065,175
Issue with MoveFile method to overwrite file in Destination in vbscript?
<p>I have a vbscript that I have written to move files from a source directory to a destination directory. The way the script works at the moment is that I have a mapping file which is read in (maps id's to folder type). Each file being moved begins with the id and the destination will be based on what the id is mapped to. I read in the mapping file and build up the destination path for each file being moved. This all works as expected, the problem is when I try to move a file that already exists in the destination directory, the files are not moved from the source directory. Essentially I would like it to overwrite a file in the destination directory if it already exists. At the moment, my main command is this:</p> <pre><code>fso.MoveFile ObjFile.Path, archiveTo &amp; "\" &amp; yearValue &amp; "\" &amp; monthValue &amp; "\" &amp; ObjFile.Name </code></pre> <p>Is there a way to default this to always overwrite a file in the destionation directory if it already exists?</p>
17,065,729
3
0
null
2013-06-12 12:11:27.227 UTC
2
2019-10-28 07:34:09.52 UTC
2014-09-12 17:44:04.463 UTC
null
321,731
null
1,587,060
null
1
17
file-io|vbscript|fso
70,488
<p>Unfortunately, the VBScript <code>MoveFile</code> method works only when the target file does not exist. It can't overwrite such file when exists, just throw error.</p> <p>So the only option is to use CopyFile (which does have option to overwrite) then DeleteFile:</p> <pre><code>fso.CopyFile ObjFile.Path, archiveTo &amp; "\" &amp; yearValue &amp; "\" &amp; monthValue &amp; "\" &amp; ObjFile.Name, True fso.DeleteFile ObjFile.Path </code></pre>
17,096,934
Check if a variable is undef in puppet template
<p>What is the proper way to check if a variable is undef in a puppet template?</p> <p>In the manifest the variable is defined as follows</p> <pre><code>$myvar = undef </code></pre> <p>How is this checked in the template?</p> <p>Is saw the following two variants</p> <pre><code>&lt;% if @myvar -%&gt; &lt;% end -%&gt; </code></pre> <p>and</p> <pre><code>&lt;% if not @myvar.nil? and @myvar -%&gt; &lt;% end -%&gt; </code></pre> <p>They both seem to work in my case, but I wonder if the first approach fails in on certain cases?</p>
24,724,628
3
0
null
2013-06-13 20:56:33.38 UTC
3
2019-05-10 05:19:02.33 UTC
null
null
null
null
1,832,409
null
1
22
erb|puppet
47,082
<p>The Puppet documentation (at the time of writing this answer) explains it very well: <a href="https://puppet.com/docs/puppet/latest/lang_template_erb.html#concept-5365" rel="nofollow noreferrer">https://puppet.com/docs/puppet/latest/lang_template_erb.html#concept-5365</a></p> <p>Since <code>undef</code> is not the same as <code>false</code>, just using an <code>if</code> is not a good way to check for it. Also when a variable is defined, but has a value of <code>false</code> or <code>nil</code> it is also impossible to check with a simple <code>if</code>.</p> <p>This is why you want to use <code>scope.lookupvar(‘variable’)</code> and check its return value for <code>:undef</code> or <code>:undefined</code> (or <code>nil</code>) to know if it was set to <code>undef</code>, or never set at all.</p>
16,905,061
last-child and last-of-type not working in SASS
<p><strong>How would you write this to be SASS compliant?</strong></p> <pre><code>.fader { display: inline-block; } .fader img:last-child { position: absolute; top: 0; left: 0; display: none; }​ </code></pre> <p>Basically I'm just replicating this example of fading in one image over another <a href="https://stackoverflow.com/questions/10039174/jquery-hover-image-change-animation"><strong>(found here.)</strong></a></p> <p>His JFiddle example: <a href="http://jsfiddle.net/Xm2Be/3/" rel="noreferrer">http://jsfiddle.net/Xm2Be/3/</a></p> <p>However his example is straight CSS, I'm working on a project in SASS and am not sure about how to correctly translate it.</p> <h2>My Code</h2> <p>Note in my example below, the img hover isn't working correctly (both images are showing up and no rollover fadein action happens)</p> <p><strong>My CodePen:</strong> <a href="http://codepen.io/leongaban/pen/xnjso" rel="noreferrer">http://codepen.io/leongaban/pen/xnjso</a></p> <p>I tried</p> <pre><code>.try-me img:last-child &amp; .tryme img:last-of-type </code></pre> <p>But the : throws SASS compile errors, the code below works</p> <pre><code>.try-me img last-of-type { position: absolute; top: 0; left: 0; display: none; } </code></pre> <p>However it spits out CSS which doesn't help me:</p> <pre><code>.container .home-content .try-me img last-of-type { position: absolute; top: 0; left: 0; display: none; } </code></pre> <hr> <h2>UPDATE: Working Codepen:</h2> <p><a href="http://codepen.io/leongaban/pen/xnjso" rel="noreferrer">http://codepen.io/leongaban/pen/xnjso</a></p>
16,905,216
3
0
null
2013-06-03 20:12:51.72 UTC
3
2018-09-12 15:35:34.33 UTC
2017-05-23 11:47:09.04 UTC
null
-1
null
168,738
null
1
26
css|sass|css-selectors
79,265
<p>Nesting is not a requirement with Sass. Don't feel obligated to do so if there's no need to break up the selectors.</p> <pre class="lang-css prettyprint-override"><code>.try-me img:last-of-type { position: absolute; top: 0; left: 0; display: none; } </code></pre> <p>If you are applying styles to the image and then specific styles to the last-of-type, then this what it would look like when you nest it:</p> <pre class="lang-css prettyprint-override"><code>.try-me img { // styles &amp;:last-of-type { position: absolute; top: 0; left: 0; display: none; } } </code></pre>
17,009,774
Quadratic Program (QP) Solver that only depends on NumPy/SciPy?
<p>I would like students to solve a quadratic program in an assignment without them having to install extra software like cvxopt etc. Is there a python implementation available that only depends on NumPy/SciPy?</p>
19,770,058
5
3
null
2013-06-09 12:50:55.457 UTC
16
2018-11-10 11:48:30.62 UTC
2015-07-21 23:49:19.977 UTC
null
1,461,210
null
2,050,944
null
1
38
python|numpy|scipy|mathematical-optimization
53,001
<p>I ran across a good solution and wanted to get it out there. There is a python implementation of LOQO in the ELEFANT machine learning toolkit out of NICTA (<a href="http://elefant.forge.nicta.com.au" rel="noreferrer">http://elefant.forge.nicta.com.au</a> as of this posting). Have a look at optimization.intpointsolver. This was coded by Alex Smola, and I've used a C-version of the same code with great success.</p>
17,052,344
Access Asset Catalog programmatically
<p>I know it's a new feature and this may not be possible, but I would love to be able to use an Asset Catalog to organize my assets, but I access all of my images programmatically. How would I access my images, now? Do I still access them by their file names like so:</p> <p><code>[UIImage imageNamed:@"my-asset-name.png"];</code></p> <p>Seemingly, the Asset Catalog doesn't reference the extension, so would it be more efficient to access it without the ".png"?</p> <p>The reason I am asking instead of testing for myself is that even after removing my assets and Asset Catalog, then cleaning the build folder, I can still access my assets in my application. This is preventing me from testing the Asset Catalog, when I implement it.</p> <p>After looking through the Asset Catalog, I found the "Contents.json" for each asset and it's formatted like so:</p> <pre><code>{ "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "scale" : "2x", "filename" : "[email protected]" } ], "info" : { "version" : 1, "author" : "xcode" } } </code></pre> <p>I'm still unsure of how I should be accessing it, but maybe this will help?</p>
17,071,194
4
0
null
2013-06-11 19:39:25.68 UTC
14
2018-10-09 08:39:28.833 UTC
2013-06-12 18:38:13.523 UTC
null
1,292,230
null
1,292,230
null
1
99
ios|objective-c|xcode|assets
98,451
<p>In order to access the image from the Asset Catalog, you only need to access the name of the asset group without any extensions.</p> <p>So, if you add an image named <code>@"[email protected]"</code> to the Asset Catalog, it will create an asset group called <code>my-button</code>.</p> <p>Now, all you have to do is access the image like so:</p> <pre><code>// Objective-C [UIImage imageNamed:@"my-button"]; // Swift UIImage(named: "my-button") </code></pre> <p>Also, you can edit the asset group by renaming it (without renaming the images) or changing it's individual components. This will allow you to follow easier naming conventions as well as show completely different assets between different <code>UIScreen</code> <code>scale</code>s without any <code>scale</code> checks.</p> <p>In order to incorporate images for different device sizes, you may need to toggle it under the "Devices" subheading in the Asset Catalog Group's options. <a href="http://i.imgur.com/lYRWWJt.png">Here is an example of that toggle (available by right clicking the group).</a></p>
4,276,218
How do you set different scale limits for different facets?
<p>Some sample data:</p> <pre><code>dfr &lt;- data.frame( x = rep.int(1:10, 2), y = runif(20), g = factor(rep(letters[1:2], each = 10)) ) </code></pre> <p>A simple scatterplot with two facets:</p> <pre><code>p &lt;- ggplot(dfr, aes(x, y)) + geom_point() + facet_wrap(~ g, scales = "free_y") </code></pre> <p>I can set the axis limits for all panels with</p> <pre><code>p + scale_y_continuous(limits = c(0.2, 0.8)) </code></pre> <p>(or a wrapper for this like <code>ylim</code>)</p> <p>but how do I set different axis limits for different facets?</p> <p>The latticey way to do it would be to pass a list to this argument, e.g.,</p> <pre><code>p + scale_y_continuous(limits = list(c(0.2, 0.8), c(0, 0.5))) </code></pre> <p>Unfortunately that just throws an error in the ggplot2 case.</p> <p><strong>EDIT:</strong></p> <p>Here's a partial hack. If you want to extend the range of the scales then you can add columns to your dataset specifying the limits, then draw them with <code>geom_blank</code>.</p> <p>Modified dataset:</p> <pre><code>dfr &lt;- data.frame( x = rep.int(1:10, 2), y = runif(20), g = factor(rep(letters[1:2], each = 10)), ymin = rep(c(-0.6, 0.3), each = 10), ymax = rep(c(1.8, 0.5), each = 10) ) </code></pre> <p>Updated plot:</p> <pre><code>p + geom_blank(aes(y = ymin)) + geom_blank(aes(y = ymax)) </code></pre> <p>Now the scales are different and the left hand one is correct. Unfortunately, the right hand scale doesn't contract since it needs to make room for the points.</p> <p>In case it helps, we can now rephrase the question as "is it possible to draw points without the scales being recalculated and without explicitly calling <code>scale_y_continuous</code>?"</p>
4,276,750
2
0
null
2010-11-25 10:53:59.217 UTC
2
2015-02-04 14:18:25.473 UTC
2010-11-25 13:22:02.193 UTC
null
134,830
null
134,830
null
1
29
r|ggplot2
7,511
<p>I don't think this is possible yet in ggplot2. This <a href="http://groups.google.com/group/ggplot2/browse_thread/thread/703ccbff21dec342/a49a69bad79767f5?lnk=gst&amp;q=limit+scale+facet&amp;pli=1" rel="noreferrer">discussion</a> from January suggests the issue is under consideration.</p>
4,481,301
Tail call optimization in Mathematica?
<p>While formulating an <a href="https://stackoverflow.com/questions/4130161/performance-of-fibonacci/4481218#4481218">answer to another SO question</a>, I came across some strange behaviour regarding tail recursion in Mathematica.</p> <p>The <a href="http://reference.wolfram.com/mathematica/tutorial/ControllingInfiniteEvaluation.html" rel="noreferrer">Mathematica documentation</a> hints that <a href="http://en.wikipedia.org/wiki/Tail_call" rel="noreferrer">tail call optimization</a> might be performed. But my own experiments give conflicting results. Contrast, for example, the following two expressions. The first crashes the 7.0.1 kernel, presumably due to stack exhaustion:</p> <pre><code>(* warning: crashes the kernel! *) Module[{f, n = 0}, f[x_] := (n += 1; f[x + 1]); TimeConstrained[Block[{$RecursionLimit = Infinity}, f[0]], 300, n] ] </code></pre> <p>The second runs to completion, appearing to exploit tail call optimization to return a meaningful result:</p> <pre><code>Module[{f, n = 0}, f[x_] := Null /; (n += 1; False); f[x_] := f[x + 1]; TimeConstrained[Block[{$IterationLimit = Infinity}, f[0]], 300, n] ] </code></pre> <p>Both expressions define a tail recursive function <code>f</code>. In the case of the first function, Mathematica apparently regards the presence of a compound statement enough to defeat any chance of tail call optimization. Also note that the first expression is governed by <code>$RecursionLimit</code> and the second by <code>$IterationLimit</code> -- a sign that Mathematica is treating the two expressions differently. (Note: the SO answer referenced above has a less contrived function that successfully exploits tail call optimization).</p> <p><strong>So, the question is</strong>: does anyone know the circumstances under which Mathematica performs tail-call optimization of recursive functions? A reference to a definitive statement in the Mathematica documentation or other <a href="http://www.wolfram.com/" rel="noreferrer">WRI</a> material would be ideal. Speculation is also welcome.</p>
4,627,671
2
4
null
2010-12-19 02:22:26.68 UTC
21
2013-03-20 22:29:37.363 UTC
2017-05-23 11:54:13.583 UTC
null
-1
null
211,232
null
1
29
recursion|wolfram-mathematica|tail-recursion|tail-call-optimization
3,125
<p>I can summarize the conclusions I was led to by my personal experience, with a disclaimer that what follows may not be the entirely right explanation. The anwer seems to lie in the differences between Mathematica call stack and traditional call stacks, which originates from Mathematica pattern-defined functions being really rules. So, there are no real function calls. Mathematica needs a stack for a different reason: since normal evaluation happens from the bottom of an expression tree, it must keep intermediate expressions in case when deeper and deeper parts of (sub)expressions get replaced as a result of rule application (some parts of an expression grow from the bottom). This is the case, in particular, for rules defining what we'd call non tail-recursive functions in other languages. So, once again, the stack in Mathematica is a stack of intermediate expressions, not function calls.</p> <p>This means that if, as a result of rule application, an (sub)expression can be rewritten in its entirety, the expression branch need not be kept on the expression stack. This is probably what is referred as tail call optimization in Mathematica - and this is why in such cases we have iteration rather than recursion (this is one very good example of the differences between rule applications and function calls). Rules like <code>f[x_]:=f[x+1]</code> are of this type. If, however, some sub-expression get rewritten, producing more expression structure, then expression must be stored on the stack. The rule <code>f[x_ /; x &lt; 5] := (n += 1; f[x + 1])</code> is of this type, which is a bit hidden until we recall that <code>()</code>stand for <code>CompoundExpression[]</code>. Schematically what happens here is <code>f[1] -&gt; CompoundExpression[n+=1, f[2]] -&gt; CompoundExpression[n+=1,CompoundExpression[n+=1,f[3]]]-&gt;etc</code>. Even though the call to f is the last every time, it happens before the full <code>CompoundExpression[]</code> executes, so this still must be kept on the expression stack. One could perhaps argue that this is a place where optimization could be made, to make an exception for CompoundExpression, but this is probably not easy to implement.</p> <p>Now, to illustrate the stack accumulation process which I schematically described above, let us limit the number of recursive calls:</p> <pre><code>Clear[n, f, ff, fff]; n = 0; f[x_ /; x &lt; 5] := (n += 1; f[x + 1]); ff[x_] := Null /; (n += 1; False); ff[x_ /; x &lt; 5] := ff[x + 1]; fff[x_ /; x &lt; 5] := ce[n += 1, fff[x + 1]]; </code></pre> <p>Tracing the evaluation:</p> <pre><code>In[57]:= Trace[f[1],f] Out[57]= {f[1],n+=1;f[1+1],{f[2],n+=1;f[2+1],{f[3],n+=1;f[3+1],{f[4],n+=1;f[4+1]}}}} In[58]:= Trace[ff[1],ff] Out[58]= {ff[1],ff[1+1],ff[2],ff[2+1],ff[3],ff[3+1],ff[4],ff[4+1],ff[5]} In[59]:= Trace[fff[1],fff] Out[59]= {fff[1],ce[n+=1,fff[1+1]],{fff[2],ce[n+=1,fff[2+1]],{fff[3],ce[n+=1,fff[3+1]], {fff[4],ce[n+=1,fff[4+1]]}}}} </code></pre> <p>What you can see from this is that the expression stack accumulates for <code>f</code> and <code>fff</code> (the latter used just to show that this is a general mechanism, with <code>ce[]</code> just some arbitrary head), but not for <code>ff</code>, because, for the purposes of pattern matching, the first definition for <code>ff</code> is a rule tried but not matched, and the second definition rewrites <code>ff[arg_]</code> in its entirety, and does not generate deeper sub-parts that need further rewriting. So, the bottom line seems that you should analyze your function and see if its recursive calls will grow the evaluated expression from the bottom or not. If yes, it is not tail-recursive as far as Mathematica is concerned.</p> <p>My answer would not be complete without showing how to do the tail call optimization manually. As an example, let us consider recursive implementation of Select. We will work with Mathematica linked lists to make it reasonably efficient rather than a toy. Below is the code for the non tail-recursive implementation:</p> <pre><code>Clear[toLinkedList, test, selrecBad, sel, selrec, selTR] toLinkedList[x_List] := Fold[{#2, #1} &amp;, {}, Reverse[x]]; selrecBad[fst_?test, rest_List] := {fst,If[rest === {}, {}, selrecBad @@ rest]}; selrecBad[fst_, rest_List] := If[rest === {}, {}, selrecBad @@ rest]; sel[x_List, testF_] := Block[{test = testF}, Flatten[selrecBad @@ toLinkedList[x]]] </code></pre> <p>The reason I use Block and selrecBad is to make it easier to use Trace. Now, this blows the stack on my machine: </p> <pre><code>Block[{$RecursionLimit = Infinity}, sel[Range[300000], EvenQ]] // Short // Timing </code></pre> <p>You can trace on small lists to see why:</p> <pre><code>In[7]:= Trace[sel[Range[5],OddQ],selrecBad] Out[7]= {{{selrecBad[1,{2,{3,{4,{5,{}}}}}],{1,If[{2,{3,{4,{5,{}}}}}==={},{},selrecBad@@{2,{3,{4, {5,{}}}}}]},{selrecBad[2,{3,{4,{5,{}}}}],If[{3,{4,{5,{}}}}==={},{},selrecBad@@{3,{4,{5, {}}}}],selrecBad[3,{4,{5,{}}}],{3,If[{4,{5,{}}}==={},{},selrecBad@@{4,{5,{}}}]},{selrecBad[4, {5,{}}],If[{5,{}}==={},{},selrecBad@@{5,{}}],selrecBad[5,{}],{5,If[{}==={},{},selrecBad@@{}]}}}}}} </code></pre> <p>What happens is that the result gets accumulated deeper and deeper in the list. The solution is to not grow the depth of the resulting expression, and one way to achieve that is to make selrecBad accept one extra parameter, which is the (linked) list of accumulated results:</p> <pre><code>selrec[{fst_?test, rest_List}, accum_List] := If[rest === {}, {accum, fst}, selrec[rest, {accum, fst}]]; selrec[{fst_, rest_List}, accum_List] := If[rest === {}, accum, selrec[rest, accum]] </code></pre> <p>And modify the main function accordingly:</p> <pre><code>selTR[x_List, testF_] := Block[{test = testF}, Flatten[selrec[toLinkedList[x], {}]]] </code></pre> <p>This will pass our power test just fine:</p> <pre><code>In[14]:= Block[{$IterationLimit= Infinity},selTR[Range[300000],EvenQ]]//Short//Timing Out[14]= {0.813,{2,4,6,8,10,12,14,16,18,20, &lt;&lt;149981&gt;&gt;,299984,299986,299988,299990,299992,299994,299996,299998,300000}} </code></pre> <p>(note that here we had to modify $IterationLimit, which is a good sign). And using Trace reveals the reason:</p> <pre><code>In[15]:= Trace[selTR[Range[5],OddQ],selrec] Out[15]= {{{selrec[{1,{2,{3,{4,{5,{}}}}}},{}],If[{2,{3,{4,{5,{}}}}}==={},{{},1},selrec[{2,{3,{4, {5,{}}}}},{{},1}]],selrec[{2,{3,{4,{5,{}}}}},{{},1}],If[{3,{4,{5,{}}}}==={},{{},1},selrec[{3, {4,{5,{}}}},{{},1}]],selrec[{3,{4,{5,{}}}},{{},1}],If[{4,{5,{}}}==={},{{{},1},3},selrec[{4, {5,{}}},{{{},1},3}]],selrec[{4,{5,{}}},{{{},1},3}],If[{5,{}}==={},{{{},1},3},selrec[{5, {}},{{{},1},3}]],selrec[{5,{}},{{{},1},3}],If[{}==={},{{{{},1},3},5},selrec[{},{{{{},1},3},5}]]}}} </code></pre> <p>which is, this version does not accumulate the depth of the intermediate expression, since the results are kept in a separate list.</p>
10,097,192
How to change entire copyright notice template for Xcode?
<p>I've found a few answers on how to change your company name, but is there any way to change the entire copyright template in Xcode? </p> <p><strong>For example:</strong></p> <p><em>Change :</em></p> <pre><code>(c) 2012 MyCoolCompany </code></pre> <p><em>to :</em></p> <pre><code>(c) 2012 MyCoolCompany, unauthorized reproduction is prohibited, contact [email protected] for details, etc. </code></pre>
10,097,202
1
0
null
2012-04-10 22:09:17.513 UTC
10
2016-09-07 15:42:08.137 UTC
2012-10-12 09:02:02.17 UTC
null
493,939
null
251,825
null
1
13
xcode|cocoa|xcode4|xcode-template|copyright-display
7,007
<p><strong>Go to :</strong></p> <pre><code>/Developer/Library/Xcode/Templates/File Templates </code></pre> <p>or if you're using the newer self contained <code>Xcode.app</code>,</p> <pre><code>/Applications/Xcode.app/Contents/Developer/Library/Xcode/Tem‌​plates/File Templates </code></pre> <p>To avoid the templates from being clobbered by Xcode updates, make a copy of the template that you want to edit and move it to your home library folder–</p> <pre><code>~/Library/Application Support/Developer/Shared/Xcode/File Templates </code></pre> <p>If - let's say - it's the Objective-C class template you want to change then, go to the following subdirectory :</p> <pre><code>/Cocoa/Objective-C class.xctemplate </code></pre> <p>Open :</p> <pre><code>NSObject/___FILEBASENAME___.h NSObject/___FILEBASENAME___.m </code></pre> <p>And edit them.</p> <hr> <p><strong><em>Hint :</strong> You'll have to tweak as many template files as you need (e.g. if you need your copyright header to be valid for NSDocument subclasses, then make sure you edit those files too... ;-))</em></p> <hr> <p><strong>An example (of what my <code>___FILEBASENAME___</code> files look like) :</strong></p> <pre><code>/****************************************************** | ___PROJECTNAME___ |****************************************************** | File : ___FILENAME___ | | Created on ___DATE___ | By Ioannis Zafeiropoulos (a.k.a. Dr.Kameleon) |********************************************************************* | Copyright (c) ___YEAR___ InSili.co.uk. All rights reserved. |*********************************************************************/ </code></pre>
10,073,483
Disable rotation in UIImagePicker
<p>Hello I need to disable the rotation of the UIImagePicker.<br> If the user takes picture when the iPhone is on "landscape" the buttons will rotate and the picture taken will also be rotated. I want to disable that option so the accelerometer will not work and it will always take picture like in portrait mode.<br> How can I do that?<br> Thanks, Matan Radomski.</p>
10,161,273
4
1
null
2012-04-09 12:53:31.967 UTC
10
2014-05-02 02:54:25.577 UTC
2012-04-09 18:37:04.787 UTC
null
866,193
null
1,321,887
null
1
13
iphone|objective-c|ios5|uiimagepickercontroller
13,493
<p>Here's the solution: <a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/occ/instm/UIDevice/endGeneratingDeviceOrientationNotifications" rel="nofollow noreferrer">[UIDevice endGeneratingDeviceOrientationNotifications]</a>.</p> <p>Why was it so hard to find? Two reasons:</p> <ol> <li>The <code>UIDevice</code> keeps count of how many times orientation notifications are switched on or off. If it has been switched on more times than it's been switched off, notifications will still be issued.</li> <li>The <code>UIImagePickerController</code> switches these notifications on when it is presented.</li> </ol> <p>So, calling this method once did nothing to the image picker. To make sure orientation notifications are off and <em>stay</em> off, you need to switch them off before <em>and</em> after the picker is presented.</p> <p>This does not affect iOS or other apps. It doesn't even fully affect your own app: as with the other method I suggested, the camera buttons continue responding to orientation changes, and the photos taken are also orientation aware. This is curious, because the device orientation hardware is supposed to be switched off if it isn't needed.</p> <pre><code>@try { // Create a UIImagePicker in camera mode. UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease]; picker.sourceType = UIImagePickerControllerSourceTypeCamera; picker.delegate = self; // Prevent the image picker learning about orientation changes by preventing the device from reporting them. UIDevice *currentDevice = [UIDevice currentDevice]; // The device keeps count of orientation requests. If the count is more than one, it continues detecting them and sending notifications. So, switch them off repeatedly until the count reaches zero and they are genuinely off. // If orientation notifications are on when the view is presented, it may slide on in landscape mode even if the app is entirely portrait. // If other parts of the app require orientation notifications, the number "end" messages sent should be counted. An equal number of "begin" messages should be sent after the image picker ends. while ([currentDevice isGeneratingDeviceOrientationNotifications]) [currentDevice endGeneratingDeviceOrientationNotifications]; // Display the camera. [self presentModalViewController:picker animated:YES]; // The UIImagePickerController switches on notifications AGAIN when it is presented, so switch them off again. while ([currentDevice isGeneratingDeviceOrientationNotifications]) [currentDevice endGeneratingDeviceOrientationNotifications]; } @catch (NSException *exception) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Camera" message:@"Camera is not available" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; [alert release]; } </code></pre> <p>As noted above, the pictures taken may still be in the wrong orientation. If you want them oriented consistently, check their aspect ratio and rotate accordingly. I recommend <a href="https://stackoverflow.com/a/7721814/1318452">this answer to How to Rotate a UIImage 90 degrees?</a></p> <pre><code>//assume that the image is loaded in landscape mode from disk UIImage * landscapeImage = [UIImage imageNamed: imgname]; UIImage * portraitImage = [[UIImage alloc] initWithCGImage: landscapeImage.CGImage scale:1.0 orientation: UIImageOrientationLeft] autorelease]; </code></pre>
10,048,004
Integrating Jetty with JAX-RS-Jersey
<p>After an exhaustive search of the web and Stackoverflow, I am still stuck with trying to figure out how to integrate a RESTlet style interface provided by Jersey with Jetty. </p> <p>I have my Jetty server up and running and as such Jersey seems pretty easy to use as well, does anyone know how to tie the two together? Any concrete links would help — I am a little new to servlet programming as well.</p>
10,049,432
2
0
null
2012-04-06 19:02:04.45 UTC
13
2016-01-07 04:32:02.69 UTC
2013-07-04 13:17:43.407 UTC
null
745,188
null
943,522
null
1
17
java|servlets|jetty|jersey|jax-rs
26,465
<p>I created an app using Jetty and Jersey a while back. It's just a standard webapp really:</p> <p>web.xml:</p> <pre><code>&lt;servlet&gt; &lt;servlet-name&gt;rest.service&lt;/servlet-name&gt; &lt;servlet-class&gt; com.sun.jersey.spi.spring.container.servlet.SpringServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.config.property.resourceConfigClass&lt;/param-name&gt; &lt;param-value&gt;com.sun.jersey.api.core.PackagesResourceConfig&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.config.property.packages&lt;/param-name&gt; &lt;param-value&gt;your.package.with.jersey.resources&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;rest.service&lt;/servlet-name&gt; &lt;url-pattern&gt;/service/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>A rest resource:</p> <pre><code>package your.package.with.jersey.resources; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.SecurityContext; @Path("login") public class LoginResource { @Context private SecurityContext security; @GET @Produces(MediaType.APPLICATION_XML) public String login() { String email = security.getUserPrincipal().getName(); return "ok"; } } </code></pre> <p>Jetty starter:</p> <pre><code>public class StartJetty { public static void main(String[] args) throws Exception { Server server = new Server(); SocketConnector connector = new SocketConnector(); // Set some timeout options to make debugging easier. connector.setMaxIdleTime(1000 * 60 * 60); connector.setSoLingerTime(-1); connector.setPort(8080); server.setConnectors(new Connector[] { connector }); WebAppContext bb = new WebAppContext(); bb.setServer(server); bb.setContextPath("/"); bb.setWar("src/main/webapp"); server.addHandler(bb); try { System.out.println("&gt;&gt;&gt; STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP"); server.start(); while (System.in.available() == 0) { Thread.sleep(5000); } server.stop(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(100); } } } </code></pre> <p>pom.xml:</p> <pre><code>&lt;!-- Jetty --&gt; &lt;dependency&gt; &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt; &lt;artifactId&gt;jetty&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt; &lt;artifactId&gt;jetty-util&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt; &lt;artifactId&gt;jetty-management&lt;/artifactId&gt; &lt;/dependency&gt; &lt;!-- Jersey (JAX-RS) --&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt; &lt;artifactId&gt;jersey-server&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.jersey.contribs&lt;/groupId&gt; &lt;artifactId&gt;jersey-spring&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.ws.rs&lt;/groupId&gt; &lt;artifactId&gt;jsr311-api&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt; &lt;artifactId&gt;jersey-test-framework&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.grizzly&lt;/groupId&gt; &lt;artifactId&gt;grizzly-servlet-webserver&lt;/artifactId&gt; &lt;/dependency&gt; (...) &lt;plugin&gt; &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt; &lt;artifactId&gt;maven-jetty-plugin&lt;/artifactId&gt; &lt;/plugin&gt; </code></pre> <p>Hope these snippets point you in the right direction. </p>
9,671,126
How to read a file from a certain offset in Java?
<p>Hey I'm trying to open a file and read just from an offset for a certain length! I read this topic: <a href="https://stackoverflow.com/questions/2312756/in-java-how-to-read-from-a-file-a-specific-line-given-the-line-number">How to read a specific line using the specific line number from a file in Java?</a> in there it said that it's not to possible read a certain line without reading the lines before, but I'm wondering about bytes! </p> <pre><code>FileReader location = new FileReader(file); BufferedReader inputFile = new BufferedReader(location); // Read from bytes 1000 to 2000 // Something like this inputFile.read(1000,2000); </code></pre> <p>Is it possible to read certain bytes from a known offset?</p>
9,671,162
2
3
null
2012-03-12 16:39:28.203 UTC
5
2018-04-05 12:40:41.86 UTC
2018-04-05 12:40:19.83 UTC
null
895,245
null
1,029,483
null
1
28
java|file-io
40,652
<p><a href="http://docs.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html" rel="noreferrer">RandomAccessFile</a> exposes a function: </p> <pre><code>seek(long pos) Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. </code></pre>
9,884,381
How to get "Project Id" to create a Direct Link?
<p>I have my project name, but not the numeric Project Id. The latter is needed to use HTML Direct Links.I'm using JIRA 5.0.1</p> <p>How do I get the numeric Project Id for a given project name?</p> <p>I've searched the Project Administration area, several other places, the documentation, Google, etc but still can't find a way to get that value.</p> <p>Thanks. </p>
9,916,696
4
2
null
2012-03-27 06:28:08.883 UTC
10
2017-06-28 21:33:58.78 UTC
2015-05-06 17:54:32.167 UTC
null
296,974
null
1,281,187
null
1
36
jira
26,702
<p>The easiest way is to do it from the web browser:</p> <ol> <li>Go to the Administration page.</li> <li>Select the Project from the menu.</li> <li>Hover over 'Edit Project' link and check the link href (in the status bar).<br> It should be something like <code>http://servername:8080/secure/project/EditProject!default.jspa?pid=10040</code></li> </ol> <p>Where pid is the id you are looking for.</p> <p>For Jira 6.x:</p> <ul> <li>place the cursor on EDIT Project button and</li> <li>look at the url being redirected at bottom left of the screen</li> </ul>
9,978,444
How can I style the border and title bar of a window in WPF?
<p>We are developing a WPF application which uses Telerik's suite of controls and everything works and looks fine. Unfortunately, we recently needed to replace the base class of all our dialogs, changing RadWindow by the standard WPF window (reason is irrelevant to this discussion). In doing so, we ended up having an application which still looked pretty on all developer's computers (Windows 7 with Aero enabled) but was ugly when used in our client's environment (Terminal Services under Windows Server 2008 R2).</p> <p>Telerik's RadWindow is a standard user control that mimicks a dialog's behaviour so styling it was not an issue. With WPF's Window though, I have a hard time changing its "border". What I mean by "border" here is both the title bar with the icon and the 3 standard buttons (Minimize, Maximize/Restore, Close) and the resize grip around the window.</p> <p>How can I change the looks of these items:</p> <ul> <li>Title bar color</li> <li>3 standard buttons</li> <li>Window's real border color</li> </ul> <p>With round corners if possible.</p>
9,978,757
5
0
null
2012-04-02 14:41:53.257 UTC
12
2021-09-08 19:45:42.753 UTC
null
null
null
null
197,371
null
1
40
wpf|xaml|styling
143,218
<p>Those are "non-client" areas and are controlled by Windows. <a href="https://msdn.microsoft.com/en-us/library/ms748948(v=vs.100).aspx" rel="noreferrer">Here is the MSDN docs on the subject</a> (the pertinent info is at the top).</p> <p>Basically, you set your Window's WindowStyle="None", then build your own window interface. (<a href="https://stackoverflow.com/questions/6792275/how-to-create-custom-window-chrome-in-wpf">similar question on SO</a>)</p>
9,878,475
Django ModelForm override widget
<p>Disclaimer: I am a beginner with python and Django but have Drupal programming experience.</p> <p>How can I override the default widget of this:</p> <pre><code>#models.py class Project(models.Model): color_mode = models.CharField(max_length=50, null=True, blank=True, help_text='colors - e.g black and white, grayscale') </code></pre> <p>in my form with a select box? Is the following OK or am I missing something?</p> <pre><code>#forms.py from django.forms import ModelForm, Select class ProjectForm(ModelForm): class Meta: model = Project fields = ('title', 'date_created', 'path', 'color_mode') colors = ( ('mixed', 'Mixed (i.e. some color or grayscale, some black and white)'), ('color_grayscale', 'Color / Grayscale'), ('black_and_white', 'Black and White only'), ) widgets = {'color_mode': Select(choices=colors)} </code></pre> <p>After reading <a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets">https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets</a>, I am lost since the example only discusses TextArea and the widgets discussion seems to exclude ModelForm.</p> <p>Thanks!</p>
22,250,192
1
0
null
2012-03-26 19:31:18.45 UTC
8
2021-07-02 12:28:29.747 UTC
2019-05-15 09:07:23.507 UTC
null
3,124,746
null
1,231,693
null
1
46
django|django-models
54,782
<p>If you want to override the widget for a formfield in general, the best way is to set the <code>widgets</code> attribute of the <code>ModelForm Meta</code> class:</p> <p>To specify a custom widget for a field, use the widgets attribute of the inner Meta class. This should be a dictionary mapping field names to widget classes or instances.</p> <p>For example, if you want the a CharField for the name attribute of Author to be represented by a <code>&lt;textarea&gt;</code> instead of its default <code>&lt;input type=&quot;text&quot;&gt;</code>, you can override the field’s widget:</p> <pre><code>from django.forms import ModelForm, Textarea from myapp.models import Author class AuthorForm(ModelForm): class Meta: model = Author fields = ('name', 'title', 'birth_date') widgets = { 'name': Textarea(attrs={'cols': 80, 'rows': 20}), } </code></pre> <p>The widgets dictionary accepts either widget instances (e.g., Textarea(...)) or classes (e.g., Textarea).</p> <p><a href="https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/#overriding-the-default-fields" rel="noreferrer">https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/#overriding-the-default-fields</a></p>
50,834,117
Why use “b < a ? a : b” instead of “a < b ? b : a” to implement max template?
<p><a href="http://www.tmplbook.com/" rel="noreferrer">C++ Templates - The Complete Guide, 2nd Edition</a> introduces the <a href="http://www.tmplbook.com/code/basics/max1.hpp.html" rel="noreferrer">max</a> template: </p> <pre><code>template&lt;typename T&gt; T max (T a, T b) { // if b &lt; a then yield a else yield b return b &lt; a ? a : b; } </code></pre> <p>And it explains using <code>“b &lt; a ? a : b”</code> instead of <code>“a &lt; b ? b : a”</code>: </p> <blockquote> <p>Note that the max() template according to [StepanovNotes] intentionally returns “b &lt; a ? a : b” instead of “a &lt; b ? b : a” to ensure that the function behaves correctly even if the two values are equivalent but not equal.</p> </blockquote> <p>How to understand "<code>even if the two values are equivalent but not equal.</code>"? <code>“a &lt; b ? b : a”</code> seems have the same result for me.</p>
50,835,839
3
8
null
2018-06-13 09:46:39.773 UTC
20
2018-06-13 16:15:37.917 UTC
2018-06-13 10:09:36.993 UTC
null
2,106,207
null
2,106,207
null
1
158
c++|templates
13,231
<p><code>std::max(a, b)</code> is indeed specified to return <code>a</code> when the two are equivalent. </p> <p>That's considered a mistake by <a href="http://stepanovpapers.com/notes.pdf#page=62" rel="noreferrer">Stepanov</a> and others because it breaks the useful property that given <code>a</code> and <code>b</code>, you can always sort them with <code>{min(a, b), max(a, b)}</code>; for that, you'd want <code>max(a, b)</code> to return <code>b</code> when the arguments are equivalent.</p>
10,077,155
How to add Done button to the keyboard?
<p>UPDATE:</p> <p>I also tried implementing UITextViewDelegate delegate and then doing in my controller:</p> <pre><code>- (BOOL)textViewShouldEndEditing:(UITextView *)textView { [textView resignFirstResponder]; return YES; } </code></pre> <p>I also set the delegate of the text view to be self (controller view instance).</p> <p>Clicking the Done button still inserts just a new line :(</p> <hr> <p>UPDATE:</p> <p>What I have done so far. I have implemented a UITextFieldDelegate by my view controller.</p> <p>I have connected the text view to the view controller via outlet.</p> <p>Then I did:</p> <hr> <pre><code>self.myTextView.delegate = self; </code></pre> <p>And:</p> <pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } </code></pre> <p>But when I click on Done button, it just adds a new line.</p> <p>So I have a UITextView element on my scene and when a user taps it, keyboard appears and it can be edited.</p> <p>However, I cannot dismiss the keyboard.</p> <p>How can I add Done button to the keyboard so it can be dismissed?</p>
10,077,175
9
4
null
2012-04-09 17:31:21.17 UTC
13
2018-01-25 06:45:49.297 UTC
2014-05-13 18:52:40.647 UTC
null
1,358,722
null
95,944
null
1
60
ios|iphone|objective-c|xcode|programmatically-created
103,638
<p>thats quite simple :)</p> <pre><code>[textField setReturnKeyType:UIReturnKeyDone]; </code></pre> <p>for dismissing the keyboard implement the <code>&lt;UITextFieldDelegate&gt;</code> protocol in your class, set</p> <pre><code>textfield.delegate = self; </code></pre> <p>and use </p> <pre><code>- (void)textFieldDidEndEditing:(UITextField *)textField { [textField resignFirstResponder]; } </code></pre> <p>or</p> <pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } </code></pre>
10,126,871
Entity Framework - Generating Classes
<p>I have an existing database. I was hoping there was a way to generate class files from this database. However, I seem to see a lot of generating the database from the class files.</p> <p>Is there a way to generate class files from an existing database using the Entity Framework? If so how? Can someone point me to a tutorial?</p>
10,132,947
4
1
null
2012-04-12 15:33:34.653 UTC
27
2017-04-08 07:45:38.663 UTC
2015-06-24 15:22:48.197 UTC
null
3,340,627
null
1,267,087
null
1
64
c#|entity-framework
136,918
<p>1) First you need to generate <code>EDMX</code> model using your database. To do that you should add new item to your project:</p> <ul> <li>Select <code>ADO.NET Entity Data Model</code> from the Templates list. </li> <li>On the Choose Model Contents page, select the Generate from Database option and click Next. </li> <li>Choose your database. </li> <li>On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need. </li> </ul> <p>So now you have <code>Model1.edmx</code> file in your project.</p> <p>2) To generate classes using your model:</p> <ul> <li>Open your <code>EDMX</code> model designer.</li> <li>On the design surface Right Click –> Add Code Generation Item… </li> <li>Select Online templates.</li> <li>Select <code>EF 4.x DbContext Generator for C#</code>.</li> <li>Click ‘Add’.</li> </ul> <p>Notice that two items are added to your project: </p> <ul> <li><code>Model1.tt</code> (This template generates very simple POCO classes for each entity in your model) </li> <li><code>Model1.Context.tt</code> (This template generates a derived DbContext to use for querying and persisting data)</li> </ul> <p>3) Read/Write Data example:</p> <pre><code> var dbContext = new YourModelClass(); //class derived from DbContext var contacts = from c in dbContext.Contacts select c; //read data contacts.FirstOrDefault().FirstName = "Alex"; //edit data dbContext.SaveChanges(); //save data to DB </code></pre> <p>Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=8363">Entity Framework 4.1</a>.</p>
10,205,464
What is the difference between background and background-color
<p>What's the difference between specifying a background color using <code>background</code> and <code>background-color</code>?</p> <p><strong>Snippet #1</strong></p> <pre><code>body { background-color: blue; } </code></pre> <p><strong>Snippet #2</strong></p> <pre><code>body { background: blue; } </code></pre>
10,205,500
17
0
null
2012-04-18 08:15:06.947 UTC
71
2020-06-30 08:05:56.79 UTC
2016-01-29 12:41:34.153 UTC
null
4,802,649
null
98,299
null
1
322
css|background|background-color
151,721
<p>Premising that those are two distinct properties, in your specific example there's no difference in the result, since <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background" rel="noreferrer"><code>background</code></a> actually is a shorthand for</p> <blockquote> <pre><code>background-color background-image background-position background-repeat background-attachment background-clip background-origin background-size </code></pre> </blockquote> <p>Thus, besides the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background-color" rel="noreferrer"><code>background-color</code></a>, using the <code>background</code> shorthand you could also add one or more values without repeating any other <code>background-*</code> property more than once.</p> <p>Which one to choose is essentially up to you, but it could also depend on specific conditions of your style declarations (e.g if you need to override just the <code>background-color</code> when inheriting other related <code>background-*</code> properties from a parent element, or if you need to remove all the values except the <code>background-color</code>).</p>
9,964,371
How to detect first time app launch on an iPhone
<p>How can I detect the very first time launch of </p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // if very first launch than perform actionA // else perform actionB } </code></pre> <p>method?</p>
9,964,400
17
1
null
2012-04-01 12:28:27.737 UTC
93
2021-11-22 20:34:52.53 UTC
2019-04-22 18:40:25.313 UTC
null
2,272,431
null
1,497,488
null
1
168
ios|iphone|launch|launching-application
95,757
<pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if (![[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"]) { [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"]; [[NSUserDefaults standardUserDefaults] synchronize]; } return YES; } </code></pre>
9,706,688
What does the 'Z' mean in Unix timestamp '120314170138Z'?
<p>I have an X.509 certificate which has the following 2 timestamps:</p> <pre><code>['validFrom'] = String(13) "120314165227Z" ['validTo'] = String(13) "130314165227Z" </code></pre> <p>What does the postfix character 'Z' mean. Does it specify the timezone?</p>
9,706,777
3
3
null
2012-03-14 17:09:58.943 UTC
29
2021-02-25 17:57:51.123 UTC
null
null
null
null
1,255,524
null
1
187
timezone|x509certificate|unix-timestamp|timestamp
192,372
<p>Yes. 'Z' stands for Zulu time, which is also GMT and UTC.</p> <p>From <a href="http://en.wikipedia.org/wiki/Coordinated_Universal_Time" rel="noreferrer">http://en.wikipedia.org/wiki/Coordinated_Universal_Time</a>:</p> <blockquote> <p>The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.</p> </blockquote> <p>Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.</p> <p>From wikipedia again, <a href="http://en.wikipedia.org/wiki/Nautical_time" rel="noreferrer">http://en.wikipedia.org/wiki/Nautical_time</a>:</p> <blockquote> <p>Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.</p> </blockquote>
11,956,622
Securely serving files from Amazon S3
<p>I have an app that uploads user files to S3. At the moment, the ACL for the folders and files is set to private.</p> <p>I have created a db table (called docs) that stores the following info:</p> <pre><code>id user_id file_name (original file as specified by the user) hash_name (random hash used to save the file on amazon) </code></pre> <p>So, when a user wants to download a file, I first check in the db table that they have access to file. I'd prefer to not have the file first downloaded to my server and then sent to the user - I'd like them to be able to grab the file directly from Amazon.</p> <p>Is it OK to rely on a very very long hashname (making it basically impossible for anyone to randomly guess a filename)? In this case, I can set the ACL for each file to public-read. </p> <p>Or, are there other options that I can use to serve the files whilst keeping them private?</p>
11,956,714
2
0
null
2012-08-14 16:21:50.457 UTC
9
2014-04-08 21:55:13.477 UTC
null
null
null
null
423,880
null
1
8
php|amazon-s3
4,951
<p>Remember, once the link is out there, nothing prevents a user from sharing that link with others. Then again, nothing prevents the user from saving the file elsewhere and sharing a link to the copy of the file.</p> <p>The best approach depends on your specific needs.</p> <p><strong>Option 1 - Time Limited Download URL</strong></p> <p>If applicable to your scenario, you can also create expiring (time-limited) custom links to the S3 contents. That would allow the user to download content for a limited amount of time, after which they would have to obtain a new link.</p> <p><a href="http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_QSAuth.html">http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_QSAuth.html</a></p> <p><strong>Option 2 - Obfuscated URL</strong></p> <p>If you value avoiding running the file through your web server over the risk that a URL, however obscure, might be intentionally shared, then use the hard-to-guess link name. This would allow a link to remain valid "forever", which means the link can be shared "forever".</p> <p><strong>Option 3 - Download through your server</strong></p> <p>If you are concerned about the link being shared and certainly want users to authenticate through your website, then serve the content through your website after verifying user credentials.</p> <p>This option also allows the link to remain valid "forever" but require the user to log in (or perhaps just have an authentication cookie in the browser) to access the link.</p>
11,876,290
c++ fastest way to read only last line of text file?
<p>I would like to read only the last line of a text file (I'm on UNIX, can use Boost). All the methods I know require scanning through the entire file to get the last line which is not efficient at all. Is there an efficient way to get only the last line?</p> <p>Also, I need this to be robust enough that it works even if the text file in question is constantly being appended to by another process.</p>
11,877,478
7
2
null
2012-08-09 03:16:50.63 UTC
5
2019-02-07 16:50:09.933 UTC
null
null
null
null
788,171
null
1
12
c++|iostream|seek
50,118
<p>Use seekg to jump to the end of the file, then read back until you find the first newline. Below is some sample code off the top of my head using MSVC.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; using namespace std; int main() { string filename = "test.txt"; ifstream fin; fin.open(filename); if(fin.is_open()) { fin.seekg(-1,ios_base::end); // go to one spot before the EOF bool keepLooping = true; while(keepLooping) { char ch; fin.get(ch); // Get current byte's data if((int)fin.tellg() &lt;= 1) { // If the data was at or before the 0th byte fin.seekg(0); // The first line is the last line keepLooping = false; // So stop there } else if(ch == '\n') { // If the data was a newline keepLooping = false; // Stop at the current position. } else { // If the data was neither a newline nor at the 0 byte fin.seekg(-2,ios_base::cur); // Move to the front of that data, then to the front of the data before it } } string lastLine; getline(fin,lastLine); // Read the current line cout &lt;&lt; "Result: " &lt;&lt; lastLine &lt;&lt; '\n'; // Display it fin.close(); } return 0; } </code></pre> <p>And below is a test file. It succeeds with empty, one-line, and multi-line data in the text file.</p> <pre><code>This is the first line. Some stuff. Some stuff. Some stuff. This is the last line. </code></pre>
11,762,629
Pass information from javascript to django app and back
<p>So I'm trying to basically set up a webpage where a user chooses an id, the webpage then sends the id information to python, where python uses the id to query a database, and then returns the result to the webpage for display.</p> <p>I'm not quite sure how to do this. I know how to use an ajax call to call the data generated by python, but I'm unsure of how to communicate the initial id information to the django app. Is it possible to say, query a url like ./app/id (IE /app/8), and then use the url information to give python the info? How would I go about editing urls.py and views.py to do that?</p> <p>Thanks,</p>
11,763,954
3
2
null
2012-08-01 15:32:20.857 UTC
12
2012-08-01 16:52:34.573 UTC
null
null
null
null
1,541,441
null
1
13
javascript|python|ajax|django
11,037
<p>You're talking about AJAX. AJAX always requires 3 pieces (technically, just two: Javascript does double-duty).</p> <ol> <li>Client (Javascript in this case) makes request</li> <li>Server (Django view in this case) handles request and returns response</li> <li>Client (again, Javascript) receives response and does something with it</li> </ol> <p>You haven't specified a preferred framework, but you'd be insane to do AJAX without a Javascript framework of some sort, so I'm going to pick jQuery for you. The code can pretty easily be adapted to any Javascript framework:</p> <pre><code>$.getJSON('/url/to/ajax/view/', {foo: 'bar'}, function(data, jqXHR){ // do something with response }); </code></pre> <p>I'm using <code>$.getJSON</code>, which is a jQuery convenience method that sends a GET request to a URL and automatically parses the response as JSON, turning it into a Javascript object passed as <code>data</code> here. The first parameter is the URL the request will be sent to (more on that in a bit), the second parameter is a Javascript object containing data that should be sent along with the request (it can be omitted if you don't need to send any data), and the third parameter is a callback function to handle the response from the server on success. So this simple bit of code covers parts 1 and 3 listed above.</p> <p>The next part is your handler, which will of course in this case be a Django view. The only requirement for the view is that it must return a JSON response:</p> <pre><code>from django.utils import simplejson def my_ajax_view(request): # do something return HttpResponse(simplejson.dumps(some_data), mimetype='application/json') </code></pre> <p>Note that this view doesn't take any arguments other than the required <code>request</code>. This is a bit of a philosophical choice. IMHO, in true REST fashion, data should be passed with the request, not in the URL, but others can and do disagree. The ultimate choice is up to you.</p> <p>Also, note that here I've used Django's simplejson library which is optimal for common Python data structures (lists, dicts, etc.). If you want to return a Django model instance or a queryset, you should use the serializers library instead.</p> <pre><code>from django.core import serializers ... data = serializers.serialize('json', some_instance_or_queryset) return HttpResponse(data, mimetype='application/json') </code></pre> <p>Now that you have a view, all you need to do is wire it up into Django's urlpatterns so Django will know how to route the request.</p> <pre><code>urlpatterns += patterns('', (r'^/url/to/ajax/view/$', 'myapp.views.my_ajax_view'), ) </code></pre> <p>This is where that philosophical difference comes in. If you choose to pass data through the URL itself, you'll need to capture it in the urlpattern:</p> <pre><code>(r'^/url/to/ajax/view/(?P&lt;some_data&gt;[\w-]+)/$, 'myapp.views.my_ajax_view'), </code></pre> <p>Then, modify your view to accept it as an argument:</p> <pre><code>def my_ajax_view(request, some_data): </code></pre> <p>And finally, modify the Javascript AJAX method to include it in the URL:</p> <pre><code>$.getJSON('/url/to/ajax/view/'+some_data+'/', function(data, jqXHR){ </code></pre> <p>If you go the route of passing the data with the request, then you need to take care to retreive it properly in the view:</p> <pre><code>def my_ajax_view(request): some_data = request.GET.get('some_data') if some_data is None: return HttpResponseBadRequest() </code></pre> <p>That should give you enough to take on just about any AJAX functionality with Django. Anything else is all about how your view retrieves the data (creates it manually, queries the database, etc.) and how your Javascript callback method handles the JSON response. A few tips on that:</p> <ol> <li><p>The <code>data</code> object will <em>generally</em> be a list, even if only one item is included. If you know there's only one item, you can just use <code>data[0]</code>. Otherwise, use a for loop to access each item:</p> <pre><code>form (var i=0; i&lt;data.length; i++) { // do something with data[i] } </code></pre></li> <li><p>If <code>data</code> or <code>data[i]</code> is an object (AKA dictionary, hash, keyed-array, etc.), you can access the values for the keys by treating the keys as attributes, i.e.:</p> <pre><code>data[i].some_key </code></pre></li> <li><p>When dealing with JSON responses and AJAX in general, it's usually best to try it directly in a browser first so you can view the exact response and/or verify the structure of the response. To view JSON responses in your browser, you'll most likely need an exstention. JSONView (available for both <a href="https://addons.mozilla.org/en-us/firefox/addon/jsonview/" rel="noreferrer">Firefox</a> and <a href="https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc" rel="noreferrer">Chrome</a>) will enable it to understand JSON and display it like a webpage. If the request is a GET, you can pass data to the URL in normal GET fashion using a querystring, i.e. <code>http://mydomain.com/url/to/ajax/view/?some_data=foo</code>. If it's a POST, you'll need some sort of REST test client. <a href="https://addons.mozilla.org/en-us/firefox/addon/restclient/" rel="noreferrer">RESTClient</a> is a good addon for Firefox. For Chrome you can try <a href="https://chrome.google.com/webstore/detail/fdmmgilgnpjigdojojpjoooidkmcomcm" rel="noreferrer">Postman</a>. These are also great for learning 3rd-party APIs from Twitter, Facebook, etc.</p></li> </ol>
11,878,805
eclipse doesn't compile the project
<p>I had running project opened in eclipse. After an accidental restart of windows, now when I open the eclipse I see my project is marked with a little red cross. Now when I run the main method I get a <code>java.lang.NoClassDefFoundError</code>.</p> <p>I have tried restarting eclipse, Project -> Clean but it doesn't solve the problem.</p> <p>When I checked the project directory, inside 'target' folder there are no compiled .class files. I tried building the project but I can't get the compiled class files, which is the reason for the error.</p> <p>How do I solve this?</p>
11,880,522
8
5
null
2012-08-09 07:40:46.573 UTC
1
2022-08-16 17:12:58.837 UTC
null
null
null
null
601,357
null
1
19
java|eclipse|build|noclassdeffounderror
55,430
<p>Maybe Eclipse's workspace files have become corrupted. Restart Eclipse and choose a new workspace folder (or choose Switch workspace from the menu). Then import the project files into a new project.</p>
11,957,677
html - how to get custom attribute of option tag in dropdown?
<p>If I have this code:</p> <pre><code> &lt;select onchange="alert('?');" name="myname" class="myclass"&gt; &lt;option isred="-1" value="hi"&gt;click&lt;/option&gt; &lt;/select&gt; </code></pre> <p>How can I get the value '-1' from the custom attribute isred ? I don't want to use the value property. And I dont want to target the option tag by a name or id.</p> <p>I want something like <code>onchange="alert(this.getselectedoptionID.getAttribute('isred'));"</code></p> <p>Can anyone help?</p> <p>Also I don't want to use jquery.</p>
11,957,764
7
1
null
2012-08-14 17:32:49.847 UTC
11
2019-05-03 09:38:09.913 UTC
2012-08-14 17:35:39.667 UTC
null
763,468
null
1,497,454
null
1
43
javascript|html|select
109,185
<p>You need to figure out what the selectedIndex is, then <code>getAttribute</code> from that options[] Array.</p> <pre><code>&lt;select onchange="alert(this.options[this.selectedIndex].getAttribute('isred'));" name="myname" class="myclass"&gt; &lt;option isred="-1" value="hi"&gt;click&lt;/option&gt; &lt;option isred="-5" value="hi"&gt;click&lt;/option&gt; &lt;/select&gt;​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ </code></pre> <p><a href="http://jsfiddle.net/sp6dQ/" rel="noreferrer"><strong>jsFiddle DEMO</strong></a></p> <h2><strong>As a side note:</strong></h2> <p><strong>Don't use inline javascript</strong> in your <code>HTML</code>. You want to separate your business logic from your UI. Create a javascript event handlers instead to handle this. (jQuery / Angular / etc)</p>
11,985,228
MongoDB Node check if objectid is valid
<p>How can I check whether an ObjectID is valid using Node's driver</p> <p>I tried :</p> <pre><code>var BSON = mongo.BSONPure; console.log("Validity: " + BSON.ObjectID.isValid('ddsd')) </code></pre> <p>But I keep getting an exception instead of a true or false. (The exception is just a 'throw e; // process.nextTick error, or 'error' event on first tick'</p>
11,989,159
8
0
null
2012-08-16 10:26:47.82 UTC
8
2020-10-24 10:26:56.647 UTC
null
null
null
null
950,147
null
1
64
node.js|mongodb
63,918
<p><strong>This is a simple check</strong> - is not 100% foolproof</p> <p>You can use this Regular Expression if you want to check for a string of 24 hex characters.</p> <pre class="lang-js prettyprint-override"><code>var checkForHexRegExp = new RegExp(&quot;^[0-9a-fA-F]{24}$&quot;) checkForHexRegExp.test(&quot;i am a bad boy&quot;) // false checkForHexRegExp.test(&quot;5e63c3a5e4232e4cd0274ac2&quot;) // true </code></pre> <p>Regex taken from <a href="https://github.com/mongodb/js-bson/blob/v4.2.0/src/objectid.ts#L9" rel="noreferrer">github.com/mongodb/js-bson/.../objectid.ts</a></p> <hr /> <p>For a better check use:</p> <pre class="lang-js prettyprint-override"><code>var ObjectID = require(&quot;mongodb&quot;).ObjectID ObjectID.isValid(&quot;i am a bad boy&quot;) // false ObjectID.isValid(&quot;5e63c3a5e4232e4cd0274ac2&quot;) // true </code></pre> <p><code>isValid</code> code <a href="https://github.com/mongodb/js-bson/blob/v4.2.0/src/objectid.ts#L301" rel="noreferrer">github.com/mongodb/js-bson/.../objectid.ts</a></p>
11,831,555
Get Nth element of an array that returns from "string_to_array()" function
<p>I am searching for a way to access to the Nth element of an array which is a result of <code>string_to_array()</code> function in PostgreSQL. For example,</p> <p>Assume that a cell contains the string value: "A simple example" . If I use <code>string_to_array()</code> function, I will have an array of three strings as ('A','simple','example'). Now, without storing (I mean, on the fly) I want to access the 2nd element of this array, which is 'simple'.</p> <p>During my googling, I saw an example to access the last element of the array but this barely solved my problem.</p> <p>Is there a way to do this?</p>
11,831,799
1
0
null
2012-08-06 15:44:06.553 UTC
6
2019-02-06 21:18:49.057 UTC
2019-02-06 21:18:49.057 UTC
null
1,376,472
null
1,376,472
null
1
84
arrays|postgresql
70,765
<pre><code>select (string_to_array('1,2,3,4',','))[2]; </code></pre>
11,931,566
How to set the time zone in Amazon EC2?
<p>I want to change the time zone set in my Amazon EC2 instance running Ubuntu Linux to local time? </p> <p><strong>My Question</strong></p> <p>How to change the time zone in Amazon EC2?</p>
11,931,955
12
0
null
2012-08-13 09:34:04.803 UTC
33
2022-02-28 13:56:16.14 UTC
2019-03-06 16:14:03.54 UTC
null
47,407
null
932,307
null
1
86
amazon-web-services|ubuntu|amazon-ec2
103,798
<p>it should be no different than your desktop Ubuntu process. See <a href="https://help.ubuntu.com/community/UbuntuTime#Using_the_Command_Line_.28terminal.29" rel="noreferrer">here</a></p> <ol> <li>SSH to your EC2 server</li> <li><p>execute the following (to set timezone to <code>Australia/Adelaide</code>)</p> <pre><code>$ echo "Australia/Adelaide" | sudo tee /etc/timezone Australia/Adelaide $ sudo dpkg-reconfigure --frontend noninteractive tzdata Current default time zone: 'Australia/Adelaide' Local time is now: Sat May 8 21:19:24 CST 2010. Universal Time is now: Sat May 8 11:49:24 UTC 2010. </code></pre></li> </ol> <p><strong>Update</strong></p> <p>You can use <code>tzselect</code> utility to browse through. See here: <a href="http://manpages.ubuntu.com/manpages/precise/man1/tzselect.1.html" rel="noreferrer">http://manpages.ubuntu.com/manpages/precise/man1/tzselect.1.html</a></p> <p>It's an interactive software. My Ubuntu (11.10) has it.</p> <p>You could also refer this <a href="http://en.wikipedia.org/wiki/List_of_IANA_time_zones" rel="noreferrer">Wikipedia article</a></p> <p>Brazil</p> <pre><code>Brazil/Acre Brazil/DeNoronha Brazil/East Brazil/West </code></pre>
11,961,902
nodejs - http.createServer seems to call twice
<p>If I write the following program in node:</p> <pre><code> http.createServer(function (req, res) { if( req.method == 'GET' ) { var body = ''; req.on('data', function(data) { body += data }); req.on('end', function() { console.log('request ended') }); } res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('142\n'); }).listen(3500); </code></pre> <p>And then hit the server with <code>http://xxx.xx.xxx.xx:35010</code> I see a <code>request ended</code> twice on my console -- I'm not sure why a single HTTP request is causing this to execute twice.</p>
11,961,918
3
2
null
2012-08-14 22:46:47.193 UTC
12
2021-02-13 02:37:38.447 UTC
null
null
null
null
422,109
null
1
87
node.js
19,291
<p>That is normal - your browser makes more than one call.</p> <p>Most browsers make a call to grab <code>/favicon.ico</code> for example.</p> <p>Try to log the url:</p> <pre><code>console.log(req.url); </code></pre> <p>and you'll see what's being called.</p>
19,918,734
Transitioning between transparent navigation bar to translucent
<p>In Apple's recently released Remote app I noticed the way in which the navigation bar behaves is unique and I haven't been able reproduce it. When popping the Now Playing view controller the navigation bar remains transparent for the Now Playing view controller and the navigation bar for the library view controller also stays translucent (Screenshot 1). I'm trying to figure out if they are using two navigation controllers or only one. Personally I feel they're using just one for two reasons (1) the interactive pop gesture is enabled; (2) when you press the 'Now Playing' button in the library view controller, just before the now playing screen has finished 'push view controller' animation the navigation bar becomes transparent (Screenshot 2). This is the behaviour I experience when pushing my view controller (which sets the navigation bar to transparent). So my question is: How does Apple present both navigation bars of the two view controllers as if they were individual (as with Screenshot 1), even the bar buttons, navigation title etc... are 100% in opacity when switching (usually when pushing/popping the buttons and titles of the previous view controller fade as the new controller is being pushed). I've tried playing around with the bar tint colour in <code>viewDidAppear</code> and <code>viewWillAppear</code> in both view controllers but cannot reproduce the same behaviour, and cannot prevent the bar buttons from fading.</p> <p>Gosh I hope I've explained this well, I get confused just thinking about it!</p> <p>Screenshot 1 (Popping): <img src="https://i.stack.imgur.com/EC7cf.png" alt="Screenshot 1"></p> <p>Screenshot 2 (Pushing): <img src="https://i.stack.imgur.com/pHPq8.png" alt="Screenshot 2"></p>
20,817,513
2
4
null
2013-11-12 00:29:41.42 UTC
27
2018-07-11 17:47:36.657 UTC
null
null
null
null
1,064,869
null
1
27
ios|uinavigationcontroller|uinavigationbar
16,580
<p>I just downloaded the application to make sure. Two different navigation bars are used. You can see this by using the interactive pop gesture. Notice how the navigation bar on the bottom view controller slides in and out. During normal push and pop transitions, the navigation items just fade in and out on the existing bar, while the bar is stationary. This is what happens up until the point where the now playing view controller is pushed.</p> <p>If you look quickly, during the now playing view controller animation, you can see the bottom navigation bar disappear.</p> <p>From my experience with UIKit behavior and what I see in the app, here is what I think happens:</p> <p><code>album_vc</code> = the bottom, list view controller <code>nowplaying_vc</code> = the top view controller</p> <ul> <li><p>On <code>nowplaying_vc</code>'s <code>viewWillAppear:</code></p> <ul> <li>Set the navigation bar to hidden using <code>[self.navigationController setNavigationBarHidden:YES animated:YES];</code>. Since this is in animation block, this will make the navigation bar slide out during the push animation.</li> <li>Set <code>[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;</code> Pretty sure about this, because notice there is no animation in the transition of the status bar styles. It just becomes white.</li> </ul></li> <li><p>On <code>nowplaying_vc</code>'s <code>viewWillDisappear:</code></p> <ul> <li>Set the navigation bar to shown using <code>[self.navigationController setNavigationBarHidden:NO animated:YES];</code>. Since this is in animation block, this will make the navigation bar slide in during the pop animation.</li> <li>Set <code>[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;</code> Again, notice how during interactive pop gesture, the status bar just changes with no animation.</li> </ul></li> </ul> <p>To achieve the transparent look of the navigation bar of <code>nowplaying_vc</code>, you can use an empty image (<code>[UIImage alloc]</code>) with <code>setBackgroundImage:forBarPosition:barMetrics:</code>.</p> <p>Since the application does not rotate, we can't be sure if the navigation bar on <code>nowplaying_vc</code> is part of another navigation controller or just a navigation bar on the top with a position of <code>UIBarPositionTopAttached</code>. For all we know, there isn't even a navigation bar there but just a back chevron image view (back bar button is comprised of an image view and a button).</p> <p>I think the status bar style is changed in <code>viewWillAppear:</code> and <code>viewWillDisappear:</code> due to the unnatural feel there is during interactive pop gesture. I would recommend using an animated transition, or even better, use the new view controller-based status bar style, which the system animates transitions by itself.</p> <hr> <p>Update for modern API:</p> <p>You should use the <code>animateAlongsideTransition:completion:</code> or <code>animateAlongsideTransitionInView:animation:completion:</code> API, rather than relying on the implicit animations of <code>viewWillAppear:</code> and <code>viewWillDisappear:</code>.</p>
3,943,553
Can setTimeout ever return 0 as the id?
<p>I am writing a check to see if a timeout is active. I was thinking of doing this:</p> <pre><code>var a = setTimeout(fn, 10); // ... Other code ... where clearTimeout(a) can be called and set to null if (a != null) { // do soemthing } </code></pre> <p>I was wondering if it would ever be possible that a will be 0. In that case I would use <code>a !== null</code></p>
3,943,636
4
0
null
2010-10-15 15:11:43.867 UTC
3
2021-02-23 21:26:41.26 UTC
2010-10-15 16:16:40.833 UTC
null
195,486
null
195,486
null
1
39
javascript|html|settimeout
7,071
<p>First: 0 isn't the same as null, (0 == null) would be false in every case';</p> <p>if you want to test 'a' against something: define 'a' first and later assign the settimeout to 'a'. then check against the type of 'a'. If its 'undefined', the timer hasn't triggered yet</p>
3,869,821
How do I create a persistent vs a non-persistent cookie?
<p>I can't seem to figure out how to create a persistent vs a non-persistent cookie. How do they differ, say, in the HTTP headers that are sent back?</p>
3,869,950
4
0
null
2010-10-06 05:57:55.093 UTC
24
2019-12-10 05:22:46.023 UTC
null
null
null
null
317,015
null
1
62
http|cookies
92,995
<p>Cookies have an expiration date implicitly or explicitly set which controls how long they last (subject to the user agent actually enforcing it). A cookie may persist only for the duration of the session (or an even shorter period).</p> <p>If a cookie is valid, it will be passed along with the HTTP request to the domain that it originated from. Only the domain that set the cookie can read the cookie (though there are ways to exploit this, such as cross-site scripting).</p> <ul> <li><p>If you want a cookie to expire at a specific time, set an expiration date on it using the client or server-side language of your choice.</p> </li> <li><p>If you want the cookie to expire when the session ends, don't set an expiration date.</p> </li> </ul> <p><a href="https://www.rfc-editor.org/rfc/rfc2965" rel="nofollow noreferrer">From the RFC (emphasis mine):</a></p> <blockquote> <p>The cookie setter can specify a deletion date, in which case the cookie will be removed on that date.</p> <p><strong>If the cookie setter does not specify a date, the cookie is removed once the user quits his or her browser.</strong></p> <p>As a result, specifying a date is a way for making a cookie survive across sessions. <strong>For this reason, cookies with an expiration date are called persistent.</strong></p> <p>As an example application, a shopping site can use persistent cookies to store the items users have placed in their basket. (In reality, the cookie may refer to an entry in a database stored at the shopping site, not on your computer.) This way, if users quit their browser without making a purchase and return later, they still find the same items in the basket so they do not have to look for these items again. If these cookies were not given an expiration date, they would expire when the browser is closed, and the information about the basket content would be lost.</p> </blockquote>
3,613,284
c++ std::string to boolean
<p>I am currently reading from an ini file with a key/value pair. i.e.</p> <pre><code>isValid = true </code></pre> <p>When get the key/value pair I need to convert a string of 'true' to a bool. Without using boost what would be the best way to do this?</p> <p>I know I can so a string compare on the value (<code>"true"</code>, <code>"false"</code>) but I would like to do the conversion without having the string in the ini file be case sensitive.</p> <p>Thanks</p>
3,613,424
5
0
null
2010-08-31 21:15:54.46 UTC
3
2010-08-31 22:03:55.813 UTC
null
null
null
null
318,724
null
1
24
c++
60,737
<p>Another solution would be to use <code>tolower()</code> to get a lower-case version of the string and then compare or use string-streams:</p> <pre><code>#include &lt;sstream&gt; #include &lt;string&gt; #include &lt;iomanip&gt; #include &lt;algorithm&gt; #include &lt;cctype&gt; bool to_bool(std::string str) { std::transform(str.begin(), str.end(), str.begin(), ::tolower); std::istringstream is(str); bool b; is &gt;&gt; std::boolalpha &gt;&gt; b; return b; } // ... bool b = to_bool("tRuE"); </code></pre>
3,684,269
Component of a quaternion rotation around an axis
<p>I'm having trouble finding any good information on this topic. Basically I want to find the component of a quaternion rotation, that is around a given axis (not necessarily X, Y or Z - any arbitrary unit vector). Sort of like projecting a quaternion onto a vector. So if I was to ask for the rotation around some axis parallel to the quaternion's axis, I'd get the same quaternion back out. If I was to ask for the rotation around an axis orthogonal to the quaternion's axis, I'd get out an identity quaternion. And in-between... well, that's what I'd like to know how to work out :)</p>
4,341,489
5
2
null
2010-09-10 11:34:13.86 UTC
24
2020-10-30 21:57:44.15 UTC
2011-10-01 09:36:50.48 UTC
null
40,834
null
40,834
null
1
44
rotation|quaternions
35,786
<p>I spent the other day trying to find the exact same thing for an animation editor; here is how I did it:</p> <ol> <li>Take the axis you want to find the rotation around, and find an orthogonal vector to it.</li> <li>Rotate this new vector using your quaternion.</li> <li>Project this rotated vector onto the plane the normal of which is your axis</li> <li><p>The acos of the dot product of this projected vector and the original orthogonal is your angle.</p> <pre><code>public static float FindQuaternionTwist(Quaternion q, Vector3 axis) { axis.Normalize(); // Get the plane the axis is a normal of Vector3 orthonormal1, orthonormal2; ExMath.FindOrthonormals(axis, out orthonormal1, out orthonormal2); Vector3 transformed = Vector3.Transform(orthonormal1, q); // Project transformed vector onto plane Vector3 flattened = transformed - (Vector3.Dot(transformed, axis) * axis); flattened.Normalize(); // Get angle between original vector and projected transform to get angle around normal float a = (float)Math.Acos((double)Vector3.Dot(orthonormal1, flattened)); return a; } </code></pre></li> </ol> <p>Here is the code to find the orthonormals however you can probably do much better if you only want the one for the above method:</p> <pre><code>private static Matrix OrthoX = Matrix.CreateRotationX(MathHelper.ToRadians(90)); private static Matrix OrthoY = Matrix.CreateRotationY(MathHelper.ToRadians(90)); public static void FindOrthonormals(Vector3 normal, out Vector3 orthonormal1, out Vector3 orthonormal2) { Vector3 w = Vector3.Transform(normal, OrthoX); float dot = Vector3.Dot(normal, w); if (Math.Abs(dot) &gt; 0.6) { w = Vector3.Transform(normal, OrthoY); } w.Normalize(); orthonormal1 = Vector3.Cross(normal, w); orthonormal1.Normalize(); orthonormal2 = Vector3.Cross(normal, orthonormal1); orthonormal2.Normalize(); } </code></pre> <p>Though the above works you may find it doesn't behave as you'd expect. For example, if your quaternion rotates a vector 90 deg. around X and 90 deg. around Y you'll find if you decompose the rotation around Z it will be 90 deg. as well. If you imagine a vector making these rotations then this makes perfect sense but depending on your application it may not be desired behaviour. For my application - constraining skeleton joints - I ended up with a hybrid system. Matrices/Quats used throughout but when it came to the method to constrain the joints I used euler angles internally, decomposing the rotation quat to rotations around X, Y, Z each time. </p> <p>Good luck, Hope that helped.</p>
4,028,889
Testing floating point equality
<p>Is there a function to test floating point approximate equality in python? Something like,</p> <pre><code> def approx_equal(a, b, tol): return abs(a - b) &lt; tol </code></pre> <p>My use case is similar to how Google's C++ testing library, gtest.h, defines <code>EXPECT_NEAR</code>.</p> <p>Here is an example:</p> <pre><code>def bernoulli_fraction_to_angle(fraction): return math.asin(sqrt(fraction)) def bernoulli_angle_to_fraction(angle): return math.sin(angle) ** 2 def test_bernoulli_conversions(): assert(approx_equal(bernoulli_angle_to_fraction(pi / 4), 0.5, 1e-4)) assert(approx_equal( bernoulli_fraction_to_angle(bernoulli_angle_to_fraction(0.1)), 0.1, 1e-4)) </code></pre>
4,102,600
6
6
null
2010-10-26 23:38:37.627 UTC
9
2021-03-16 20:32:35.843 UTC
2016-10-08 16:29:13.55 UTC
null
355,230
null
99,989
null
1
37
python|comparison|floating-point
35,153
<ul> <li>For comparing numbers, there is <code>math.isclose</code>.</li> <li>For comparing numbers or arrays, there is <code>numpy.allclose</code>.</li> <li>For testing numbers or arrays, there is <code>numpy.testing.assert_allclose</code></li> </ul>
3,455,985
Range out of order in character class
<p>I'm getting this odd error in the preg_match() function:</p> <p>Warning: preg_match(): Compilation failed: range out of order in character class at offset 54</p> <p>The line which is causing this is:</p> <pre><code>preg_match("/&lt;!--GSM\sPER\sNUMBER\s-\s$gsmNumber\s-\sSTART--&gt;(.*)&lt;!--GSM\sPER\sNUMBER\s-\s$gsmNumber\s-\sEND--&gt;/s", $fileData, $matches); </code></pre> <p>What this regular expression does is parse an HTML file, extracting only the part between:</p> <pre><code>&lt;!--GSM PER NUMBER - 5550101 - START--&gt; </code></pre> <p>and:</p> <pre><code>&lt;!--GSM PER NUMBER - 5550101 - END--&gt; </code></pre> <p>Do you have a hint about what could be causing this error?</p>
3,456,053
7
3
null
2010-08-11 06:56:17.263 UTC
null
2016-07-12 00:43:33.593 UTC
null
null
null
null
54,522
null
1
31
php|regex
51,525
<p>If <code>$gsmNumber</code> contains a square bracket, backslash or various other special characters it might trigger this error. If that's possible, you might want to validate that to make sure it actually is a number before this point.</p> <p><strong>Edit 2016:</strong></p> <p>There exists a PHP function that can escape special characters inside regular expressions: <a href="https://secure.php.net/manual/en/function.preg-quote.php" rel="noreferrer"><code>preg_quote()</code></a>.</p> <p>Use it like this:</p> <pre><code>preg_match( '/&lt;!--GSM\sPER\sNUMBER\s-\s' . preg_quote($gsmNumber, '/') . '\s-\sSTART--&gt;(.*)&lt;!--GSM\sPER\sNUMBER\s-\s' . preg_quote($gsmNumber, '/') . '\s-\sEND--&gt;/s', $fileData, $matches); </code></pre> <p>Obviously in this case because you've used the same string twice you could assign the quoted version to a variable first and re-use that.</p>
3,545,018
Selected text event trigger in Javascript
<p>How to <strong>trigger a JavaScript function when someone selects a given text fragment</strong> on a page using mouse?<br> Also, is there any way to <strong>find the position of selected text</strong> on the page?</p> <p>Update: To be more clear, text fragment can be part of a sentence or a word or a phrase or whole a paragraph.</p>
3,545,073
10
0
null
2010-08-23 05:48:49.627 UTC
32
2021-09-25 10:46:42.9 UTC
2019-05-06 05:36:07.037 UTC
null
912,046
user178841
null
null
1
89
javascript|jquery
96,535
<p>There is no "<em>Text was selected</em>" <code>(DOM)</code> event, but you can bind a <code>mouseup</code> event to the <code>document.body</code>. Within that event handler, you might just check the </p> <pre><code>document.selection.createRange().text </code></pre> <p>or</p> <pre><code>window.getSelection() </code></pre> <p>methods. There are several topics on Stackoverflow, like this one <a href="https://stackoverflow.com/questions/845390/javascript-to-get-paragraph-of-selected-text-in-web-page">javascript to get paragraph of selected text in web page</a>.</p> <p>I'm not sure what you mean with "finding the position", but to stay in my example world you could use the <code>event propertys</code> for X+Y mouse positions.</p> <p>Example: <a href="http://www.jsfiddle.net/2C6fB/1/" rel="noreferrer">http://www.jsfiddle.net/2C6fB/1/</a></p>
8,210,935
Creating a C++ namespace in header and source (cpp)
<p>Is there any difference between wrapping both header and cpp file contents in a namespace or wrapping just the header contents and then doing <strong>using namespace</strong> in the cpp file?</p> <p>By difference I mean any sort performance penalty or slightly different semantics that can cause problems or anything I need to be aware of.</p> <p>Example:</p> <pre><code>// header namespace X { class Foo { public: void TheFunc(); }; } // cpp namespace X { void Foo::TheFunc() { return; } } </code></pre> <p>VS</p> <pre><code>// header namespace X { class Foo { public: void TheFunc(); }; } // cpp using namespace X; { void Foo::TheFunc() { return; } } </code></pre> <p>If there is no difference what is the preferred form and why?</p>
8,211,024
9
0
null
2011-11-21 11:19:52.533 UTC
21
2022-01-20 14:13:00.453 UTC
2012-09-17 02:15:00.137 UTC
null
1,172,709
null
840,974
null
1
99
c++|namespaces
109,312
<p>Namespace is just a way to mangle function signature so that they will not conflict. Some prefer the first way and other prefer the second version. Both versions do not have any effect on compile time performance. Note that namespaces are just a compile time entity.</p> <p>The only problem that arises with using namespace is when we have same nested namespace names (i.e) <code>X::X::Foo</code>. Doing that creates more confusion with or without using keyword.</p>
4,365,224
MongoDB limit memory
<p>I am using mongo for storing log files. Both mongoDB and mysql are running on the same machine, virtualizing mongo env is not an option. I am afraid I will soon run into perf issues as the logs table grows very fast. Is there a way to limit resident memory for mongo so that it won't eat all available memory and excessively slow down the mysql server?</p> <p>DB machine: Debian 'lenny' 5</p> <p>Other solutions (please comment):</p> <ul> <li><p>As we need all historical data, we can not use capped collections, but I am also considering using a cron script that dumps and deletes old data</p></li> <li><p>Should I also consider using smaller keys, as suggested on other forums?</p></li> </ul>
4,370,642
3
0
null
2010-12-06 10:04:15.587 UTC
9
2016-12-02 08:32:30.98 UTC
null
null
null
null
145,248
null
1
20
performance|ubuntu|mongodb|debian
41,870
<p>Hey Vlad, you have a couple of simple strategies here regarding logs.</p> <p>The first thing to know is that Mongo can generally handle lots of successive inserts without a lot of RAM. The reason for this is simple, you only insert or update recent stuff. So the index size grows, but the data will be constantly paged out.</p> <p>Put another way, you can break out the RAM usage into two major parts: index &amp; data.</p> <p>If you're running typical logging, the data portion is constantly being flushed away, so only the index really stays in RAM.</p> <p>The second thing to know is that you can mitigate the index issue by putting logs into smaller buckets. Think of it this way. If you collect all of the logs into a date-stamped collection (call it <code>logs20101206</code>), then you can also control the size of the index in RAM.</p> <p>As you roll over days, the old index will flush from RAM and it won't be accessed again, so it will simply go away.</p> <blockquote> <p>but I am also considering using a cron script that dumps and deletes old data</p> </blockquote> <p>This method of logging by days also helps delete old data. In three months when you're done with the data you simply do <code>db.logs20101206.drop()</code> and the collection instantly goes away. Note that you don't reclaim disk space (it's all pre-allocated), but new data will fill up the empty spot.</p> <blockquote> <p>Should I also consider using smaller keys, as suggested on other forums?</p> </blockquote> <p>Yes.</p> <p>In fact, I have it built into my data objects. So I access data using <code>logs.action</code> or <code>logs-&gt;action</code>, but underneath, the data is actually saved to <code>logs.a</code>. It's really easy to spend more space on "fields" than on "values", so it's worth shrinking the "fields" and trying to abstract it away elsewhere.</p>
4,087,919
How can I improve my paw detection?
<p>After my previous question on <a href="https://stackoverflow.com/questions/3684484">finding toes within each paw</a>, I started loading up other measurements to see how it would hold up. Unfortunately, I quickly ran into a problem with one of the preceding steps: recognizing the paws.</p> <p>You see, my proof of concept basically took the maximal pressure of each sensor over time and would start looking for the sum of each row, until it finds on that != 0.0. Then it does the same for the columns and as soon as it finds more than 2 rows with that are zero again. It stores the minimal and maximal row and column values to some index.</p> <p><img src="https://i.stack.imgur.com/j6eWv.png" alt="alt text"></p> <p>As you can see in the figure, this works quite well in most cases. However, there are a lot of downsides to this approach (other than being very primitive):</p> <ul> <li><p>Humans can have 'hollow feet' which means there are several empty rows within the footprint itself. Since I feared this could happen with (large) dogs too, I waited for at least 2 or 3 empty rows before cutting off the paw. </p> <p>This creates a problem if another contact made in a different column before it reaches several empty rows, thus expanding the area. I figure I could compare the columns and see if they exceed a certain value, they must be separate paws.</p></li> <li><p>The problem gets worse when the dog is very small or walks at a higher pace. What happens is that the front paw's toes are still making contact, while the hind paw's toes just start to make contact within the same area as the front paw!</p> <p>With my simple script, it won't be able to split these two, because it would have to determine which frames of that area belong to which paw, while currently I would only have to look at the maximal values over all frames.</p></li> </ul> <p>Examples of where it starts going wrong:</p> <p><img src="https://i.stack.imgur.com/kPTj3.png" alt="alt text"> <img src="https://i.stack.imgur.com/xKLOq.png" alt="alt text"></p> <p><strong>So now I'm looking for a better way of recognizing and separating the paws</strong> (after which I'll get to the problem of deciding which paw it is!).</p> <p><strong>Update:</strong></p> <p>I've been tinkering to get Joe's (awesome!) answer implemented, but I'm having difficulties extracting the actual paw data from my files.</p> <p><img src="https://i.stack.imgur.com/83Xx5.png" alt="alt text"></p> <p>The coded_paws shows me all the different paws, when applied to the maximal pressure image (see above). However, the solution goes over each frame (to separate overlapping paws) and sets the four Rectangle attributes, such as coordinates or height/width. </p> <p>I can't figure out how to take these attributes and store them in some variable that I can apply to the measurement data. Since I need to know for each paw, what its location is during which frames and couple this to which paw it is (front/hind, left/right).</p> <p><strong>So how can I use the Rectangles attributes to extract these values for each paw?</strong></p> <p>I have the measurements I used in the question setup in my public Dropbox folder (<a href="http://dl.dropbox.com/u/5207386/Examples/Normal%20measurement" rel="noreferrer">example 1</a>, <a href="http://dl.dropbox.com/u/5207386/Examples/Grouped%20up%20paws" rel="noreferrer">example 2</a>, <a href="http://dl.dropbox.com/u/5207386/Examples/Overlapping%20paws" rel="noreferrer">example 3</a>). <a href="http://flipserd.com/blog" rel="noreferrer">For anyone interested I also set up a blog</a> to keep you up to date :-)</p>
4,092,160
3
4
null
2010-11-03 14:13:05.677 UTC
99
2013-01-28 16:54:01.52 UTC
2017-05-23 12:03:01.573 UTC
null
-1
null
77,595
null
1
201
python|image-processing
15,138
<p>If you're just wanting (semi) contiguous regions, there's already an easy implementation in Python: <a href="http://en.wikipedia.org/wiki/SciPy">SciPy</a>'s <a href="http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html">ndimage.morphology</a> module. This is a fairly common <a href="http://en.wikipedia.org/wiki/Mathematical_morphology">image morphology</a> operation. </p> <hr> <p>Basically, you have 5 steps:</p> <pre><code>def find_paws(data, smooth_radius=5, threshold=0.0001): data = sp.ndimage.uniform_filter(data, smooth_radius) thresh = data &gt; threshold filled = sp.ndimage.morphology.binary_fill_holes(thresh) coded_paws, num_paws = sp.ndimage.label(filled) data_slices = sp.ndimage.find_objects(coded_paws) return object_slices </code></pre> <ol> <li><p>Blur the input data a bit to make sure the paws have a continuous footprint. (It would be more efficient to just use a larger kernel (the <code>structure</code> kwarg to the various <code>scipy.ndimage.morphology</code> functions) but this isn't quite working properly for some reason...) </p></li> <li><p>Threshold the array so that you have a boolean array of places where the pressure is over some threshold value (i.e. <code>thresh = data &gt; value</code>)</p></li> <li><p>Fill any internal holes, so that you have cleaner regions (<code>filled = sp.ndimage.morphology.binary_fill_holes(thresh)</code>)</p></li> <li><p>Find the separate contiguous regions (<code>coded_paws, num_paws = sp.ndimage.label(filled)</code>). This returns an array with the regions coded by number (each region is a contiguous area of a unique integer (1 up to the number of paws) with zeros everywhere else)).</p></li> <li><p>Isolate the contiguous regions using <code>data_slices = sp.ndimage.find_objects(coded_paws)</code>. This returns a list of tuples of <code>slice</code> objects, so you could get the region of the data for each paw with <code>[data[x] for x in data_slices]</code>. Instead, we'll draw a rectangle based on these slices, which takes slightly more work.</p></li> </ol> <hr> <p>The two animations below show your "Overlapping Paws" and "Grouped Paws" example data. This method seems to be working perfectly. (And for whatever it's worth, this runs much more smoothly than the GIF images below on my machine, so the paw detection algorithm is fairly fast...)</p> <p><img src="https://i.stack.imgur.com/1CRA6.gif" alt="Overlapping Paws"> <img src="https://i.stack.imgur.com/ct8ub.gif" alt="Grouped Paws"></p> <hr> <p>Here's a full example (now with much more detailed explanations). The vast majority of this is reading the input and making an animation. The actual paw detection is only 5 lines of code.</p> <pre><code>import numpy as np import scipy as sp import scipy.ndimage import matplotlib.pyplot as plt from matplotlib.patches import Rectangle def animate(input_filename): """Detects paws and animates the position and raw data of each frame in the input file""" # With matplotlib, it's much, much faster to just update the properties # of a display object than it is to create a new one, so we'll just update # the data and position of the same objects throughout this animation... infile = paw_file(input_filename) # Since we're making an animation with matplotlib, we need # ion() instead of show()... plt.ion() fig = plt.figure() ax = fig.add_subplot(111) fig.suptitle(input_filename) # Make an image based on the first frame that we'll update later # (The first frame is never actually displayed) im = ax.imshow(infile.next()[1]) # Make 4 rectangles that we can later move to the position of each paw rects = [Rectangle((0,0), 1,1, fc='none', ec='red') for i in range(4)] [ax.add_patch(rect) for rect in rects] title = ax.set_title('Time 0.0 ms') # Process and display each frame for time, frame in infile: paw_slices = find_paws(frame) # Hide any rectangles that might be visible [rect.set_visible(False) for rect in rects] # Set the position and size of a rectangle for each paw and display it for slice, rect in zip(paw_slices, rects): dy, dx = slice rect.set_xy((dx.start, dy.start)) rect.set_width(dx.stop - dx.start + 1) rect.set_height(dy.stop - dy.start + 1) rect.set_visible(True) # Update the image data and title of the plot title.set_text('Time %0.2f ms' % time) im.set_data(frame) im.set_clim([frame.min(), frame.max()]) fig.canvas.draw() def find_paws(data, smooth_radius=5, threshold=0.0001): """Detects and isolates contiguous regions in the input array""" # Blur the input data a bit so the paws have a continous footprint data = sp.ndimage.uniform_filter(data, smooth_radius) # Threshold the blurred data (this needs to be a bit &gt; 0 due to the blur) thresh = data &gt; threshold # Fill any interior holes in the paws to get cleaner regions... filled = sp.ndimage.morphology.binary_fill_holes(thresh) # Label each contiguous paw coded_paws, num_paws = sp.ndimage.label(filled) # Isolate the extent of each paw data_slices = sp.ndimage.find_objects(coded_paws) return data_slices def paw_file(filename): """Returns a iterator that yields the time and data in each frame The infile is an ascii file of timesteps formatted similar to this: Frame 0 (0.00 ms) 0.0 0.0 0.0 0.0 0.0 0.0 Frame 1 (0.53 ms) 0.0 0.0 0.0 0.0 0.0 0.0 ... """ with open(filename) as infile: while True: try: time, data = read_frame(infile) yield time, data except StopIteration: break def read_frame(infile): """Reads a frame from the infile.""" frame_header = infile.next().strip().split() time = float(frame_header[-2][1:]) data = [] while True: line = infile.next().strip().split() if line == []: break data.append(line) return time, np.array(data, dtype=np.float) if __name__ == '__main__': animate('Overlapping paws.bin') animate('Grouped up paws.bin') animate('Normal measurement.bin') </code></pre> <hr> <p><strong>Update:</strong> As far as identifying which paw is in contact with the sensor at what times, the simplest solution is to just do the same analysis, but use all of the data at once. (i.e. stack the input into a 3D array, and work with it, instead of the individual time frames.) Because SciPy's ndimage functions are meant to work with n-dimensional arrays, we don't have to modify the original paw-finding function at all.</p> <pre><code># This uses functions (and imports) in the previous code example!! def paw_regions(infile): # Read in and stack all data together into a 3D array data, time = [], [] for t, frame in paw_file(infile): time.append(t) data.append(frame) data = np.dstack(data) time = np.asarray(time) # Find and label the paw impacts data_slices, coded_paws = find_paws(data, smooth_radius=4) # Sort by time of initial paw impact... This way we can determine which # paws are which relative to the first paw with a simple modulo 4. # (Assuming a 4-legged dog, where all 4 paws contacted the sensor) data_slices.sort(key=lambda dat_slice: dat_slice[2].start) # Plot up a simple analysis fig = plt.figure() ax1 = fig.add_subplot(2,1,1) annotate_paw_prints(time, data, data_slices, ax=ax1) ax2 = fig.add_subplot(2,1,2) plot_paw_impacts(time, data_slices, ax=ax2) fig.suptitle(infile) def plot_paw_impacts(time, data_slices, ax=None): if ax is None: ax = plt.gca() # Group impacts by paw... for i, dat_slice in enumerate(data_slices): dx, dy, dt = dat_slice paw = i%4 + 1 # Draw a bar over the time interval where each paw is in contact ax.barh(bottom=paw, width=time[dt].ptp(), height=0.2, left=time[dt].min(), align='center', color='red') ax.set_yticks(range(1, 5)) ax.set_yticklabels(['Paw 1', 'Paw 2', 'Paw 3', 'Paw 4']) ax.set_xlabel('Time (ms) Since Beginning of Experiment') ax.yaxis.grid(True) ax.set_title('Periods of Paw Contact') def annotate_paw_prints(time, data, data_slices, ax=None): if ax is None: ax = plt.gca() # Display all paw impacts (sum over time) ax.imshow(data.sum(axis=2).T) # Annotate each impact with which paw it is # (Relative to the first paw to hit the sensor) x, y = [], [] for i, region in enumerate(data_slices): dx, dy, dz = region # Get x,y center of slice... x0 = 0.5 * (dx.start + dx.stop) y0 = 0.5 * (dy.start + dy.stop) x.append(x0); y.append(y0) # Annotate the paw impacts ax.annotate('Paw %i' % (i%4 +1), (x0, y0), color='red', ha='center', va='bottom') # Plot line connecting paw impacts ax.plot(x,y, '-wo') ax.axis('image') ax.set_title('Order of Steps') </code></pre> <p><img src="https://i.stack.imgur.com/XmY3A.png" alt="alt text"></p> <hr> <p><img src="https://i.stack.imgur.com/JWyK3.png" alt="alt text"></p> <hr> <p><img src="https://i.stack.imgur.com/Hbcia.png" alt="alt text"></p>
4,331,532
Multiple Select in Spring 3.0 MVC
<p>Ok so I've been trying to accomplish multiple selects in Spring MVC for a while and have had no luck.</p> <p>Basically what I have is a Skill class:</p> <pre><code>public class Skill { private Long id; private String name; private String description; //Getters and Setters } </code></pre> <p>And an Employee who has multiple Skills:</p> <pre><code>public class Employee { private Long id; private String firstname; private String lastname; private Set&lt;Skill&gt; skills; //Getters and Setters } </code></pre> <p>All of these are mapped to Hibernate but that shouldn't be an issue.</p> <p>Now I would like to be able to do in the JSP is to select Skills for an Employee from a <code>&lt;select multiple="true"&gt;</code> element. </p> <p>I have tried this in the JSP with no luck:</p> <pre><code>&lt;form:select multiple="true" path="skills"&gt; &lt;form:options items="skillOptionList" itemValue="name" itemLabel="name"/&gt; &lt;form:select&gt; </code></pre> <p>Here is my Controller:</p> <pre><code>@Controller @SessionAttributes public class EmployeeController { @Autowired private EmployeeService service; @RequestMapping(value="/addEmployee", method = RequestMethod.POST) public String addSkill(@ModelAttribute("employee") Employee emp, BindingResult result, Map&lt;String, Object&gt; map) { employeeService.addEmployee(emp); return "redirect:/indexEmployee.html"; } @RequestMapping("/indexEmployee") public String listEmployees(@RequestParam(required=false) Integer id, Map&lt;String, Object&gt; map) { Employee emp = (id == null ? new Employee() : employeeService.loadById(id)); map.put("employee", emp); map.put("employeeList", employeeService.listEmployees()); map.put("skillOptionList", skillService.listSkills()); return "emp"; } } </code></pre> <p>But this does not seem to work. I get the following Exception:</p> <pre><code>SEVERE: Servlet.service() for servlet jsp threw exception javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items </code></pre> <p>I feel like it should be possible where we can have a form for a Model that has multiple select from a list of options provided. What is the best practice to have <code>form:select</code> and <code>form:options</code> in Spring 3.0 MVC?</p> <p>Thanks!</p> <p><strong>Solution:</strong></p> <p>Ok so just in case anyone wonders what the solution is. In addition to user 01001111 fix:</p> <pre><code>&lt;form:select multiple="true" path="skills"&gt; &lt;form:options items="${skillOptionList}" itemValue="name" itemLabel="name"/&gt; &lt;form:select&gt; </code></pre> <p>We need to add a <code>CustomCollectionEditor</code> to the controller as follows:</p> <pre><code>@Controller @SessionAttributes public class EmployeeController { @Autowired private EmployeeeService employeeService; @Autowired private SkillService skillService; @InitBinder protected void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Set.class, "skills", new CustomCollectionEditor(Set.class) { @Override protected Object convertElement(Object element) { Long id = null; if(element instanceof String &amp;&amp; !((String)element).equals("")){ //From the JSP 'element' will be a String try{ id = Long.parseLong((String) element); } catch (NumberFormatException e) { System.out.println("Element was " + ((String) element)); e.printStackTrace(); } } else if(element instanceof Long) { //From the database 'element' will be a Long id = (Long) element; } return id != null ? employeeService.loadSkillById(id) : null; } }); } } </code></pre> <p>This allows Spring to add Sets of Skills between the JSP and Model.</p>
4,331,647
4
0
null
2010-12-02 03:56:58.537 UTC
13
2013-07-23 11:25:10.283 UTC
2010-12-02 08:02:20.073 UTC
null
91,866
null
91,866
null
1
26
spring|jsp|select|spring-mvc
55,547
<p>You need to treat the items attribute as a variable, not just reference the variable name:</p> <pre><code>&lt;form:select multiple="true" path="skills"&gt; &lt;form:options items="${skillOptionList}" itemValue="name" itemLabel="name"/&gt; &lt;/form:select&gt; </code></pre> <p>put <code>${skillOptionList}</code> instead of <code>skillOptionList</code></p>
4,687,609
Maven not setting classpath for dependencies properly
<p>OS name: "linux" version: "2.6.32-27-generic" arch: "i386" Family: "unix"</p> <p>Apache Maven 2.2.1 (r801777; 2009-08-06 12:16:01-0700)</p> <p>Java version: 1.6.0_20</p> <p>I am trying to use the mysql dependency in with maven in ubuntu. If I move the "mysql-connector-java-5.1.14.jar" file that maven downloaded into my $JAVA_HOME/jre/lib/ext/ folder, everything is fine when I run the jar.</p> <p>I think I should be able to just specify the dependency in the pom.xml file and maven should take care of setting the classpath for the dependency jars automatically. Is this incorrect?</p> <p>My pom.xml file looks like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.ion.common&lt;/groupId&gt; &lt;artifactId&gt;TestPreparation&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;TestPrep&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;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;archive&gt; &lt;manifest&gt; &lt;addClasspath&gt;true&lt;/addClasspath&gt; &lt;mainClass&gt;com.ion.common.App&lt;/mainClass&gt; &lt;/manifest&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;dependencies&gt; &lt;!-- JUnit testing dependency --&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- MySQL database driver --&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.14&lt;/version&gt; &lt;scope&gt;compile&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/project&gt; </code></pre> <p>The command "mvn package" builds it without any problems, and I can run it, but when the application attempts to access the database, this error is presented:</p> <pre><code>java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at java.net.URLClassLoader$1.run(URLClassLoader.java:217) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:321) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:186) at com.ion.common.Functions.databases(Functions.java:107) at com.ion.common.App.main(App.java:31) </code></pre> <p>The line it is failing on is:</p> <pre><code>Class.forName("com.mysql.jdbc.Driver"); </code></pre> <p>Can anyone tell me what I'm doing wrong or how to fix it?</p>
4,688,647
4
0
null
2011-01-14 03:05:51.41 UTC
9
2019-05-23 14:52:44.567 UTC
2013-04-25 12:33:31.153 UTC
null
384,674
null
298,212
null
1
27
dependencies|maven|classpath
77,129
<p>Raghuram gave me a push in the right direction. The way to get maven to take care of copying the jars automatically is to add this code inside the tag in the pom.xml file:</p> <pre class="lang-xml prettyprint-override"><code> &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;copy-dependencies&lt;/id&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy-dependencies&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt;${project.build.directory}&lt;/outputDirectory&gt; &lt;overWriteReleases&gt;false&lt;/overWriteReleases&gt; &lt;overWriteSnapshots&gt;true&lt;/overWriteSnapshots&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>More details on this can be found here: <a href="https://maven.apache.org/plugins/maven-dependency-plugin/usage.html" rel="noreferrer">https://maven.apache.org/plugins/maven-dependency-plugin/usage.html</a></p> <p>Getting maven to package the jars together would be nice, but this is good enough to answer this question. Related answers on stackoverflow:</p> <p><a href="https://stackoverflow.com/questions/1814526/problem-building-executable-jar-with-maven">Building executable jar with maven?</a></p> <p><a href="https://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven">How can I create an executable JAR with dependencies using Maven?</a></p>
4,807,572
Jquery Ajax error handling to ignore aborted
<p>I want to have a global error handling method for ajax calls, this is what I have now:</p> <pre><code>$.ajaxSetup({ error: function (XMLHttpRequest, textStatus, errorThrown) { displayError(); } }); </code></pre> <p>I need to ignore the error of <code>aborted</code>. <code>errorThrown</code> is null and <code>textStatus</code> is <code>error</code>. How do I check for <code>aborted</code>?</p>
15,141,116
9
5
null
2011-01-26 17:11:13.177 UTC
18
2019-03-05 07:09:32.437 UTC
2016-09-05 11:34:19.197 UTC
null
648,265
null
400,861
null
1
90
jquery|ajax|error-handling
46,793
<p>I had to deal with the same use case today. The app I am working on has these long-running ajax calls that can be interrupted by 1) the user navigating away or 2) some kind of temporary connection/server failure. I want the error handler to run only for connection/server failure and not for the user navigating away.</p> <p>I first tried Alastair Pitts' answer, but it did not work because both aborted requests and connection failure set status code and readyState to 0. Next, I tried sieppl's answer; also did not work because in both cases, no response is given, thus no header.</p> <p>The only solution that worked for me is to set a listener for window.onbeforeunload, which sets a global variable to indicate that the page has been unloaded. The error handler can then check and only call the error handler only if the page has not been unloaded.</p> <pre><code>var globalVars = {unloaded:false}; $(window).bind('beforeunload', function(){ globalVars.unloaded = true; }); ... $.ajax({ error: function(jqXHR,status,error){ if (globalVars.unloaded) return; } }); </code></pre>
4,231,789
is there something like isset of php in javascript/jQuery?
<p>Is there something in javascript/jQuery to check whether variable is set/available or not? In php, we use <code>isset($variable)</code> to check something like this.</p> <p>thanks.</p>
4,231,805
11
4
null
2010-11-20 08:01:39.447 UTC
15
2016-10-20 03:12:40.723 UTC
2016-10-20 03:12:40.723 UTC
null
1,218,980
null
417,143
null
1
80
javascript|php|jquery|isset
166,820
<p>Try this expression:</p> <pre><code>typeof(variable) != "undefined" &amp;&amp; variable !== null </code></pre> <p>This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.</p> <p>You can use it like this:</p> <pre><code>if(typeof(variable) != "undefined" &amp;&amp; variable !== null) { bla(); } </code></pre>
14,502,510
How to organize a set of scientific experiments using Git
<p>I'm running experiments on a model, with a workflow like this:</p> <ul> <li>I work in a model (a software in Python)</li> <li>I change some parameters and run an experiment</li> <li>Then, I will store the results of the experiment (as a pickle).</li> <li>Then, I will analyze the (pickled) results using another software (IPython Notebooks).</li> </ul> <p>I'm using <a href="http://computersandbuildings.com/git-and-scientific-reproducibility/">Git and Scientific Reproducibility</a> as a guide , where the results of an experiment are stored in a table along the hash of the commit. I would like to store the results in a directory instead, naming the directories as hashes.</p> <p>Thinking about version control, I would like to isolate the <code>code</code> and <code>analysis</code>. For example, a change of the color in a plot in a IPython notebook in <code>analysis</code> shouldn't change anything in <code>code</code></p> <p>The approach I'm thinking:</p> <p>A directory structure like this:</p> <pre><code>model - code - simulation_results - a83bc4 - 23e900 - etc - analysis </code></pre> <p>and different Git repositories for <code>code</code> and <code>analysis</code>, leaving <code>simulation_results</code> out of Git.</p> <p>Any comments? A better solution? Thanks.</p>
14,505,057
1
4
null
2013-01-24 13:29:40.503 UTC
11
2013-01-31 08:48:44.073 UTC
null
null
null
null
182,172
null
1
18
git|scientific-computing
1,736
<p>That seems sound, and your structure would be a good fit for using <strong><a href="http://git-scm.com/book/en/Git-Tools-Submodules" rel="nofollow"><code>git submodules</code></a></strong>, <code>model</code> becoming a parent git repo.</p> <p>That way, you will link together <code>code</code>, and <code>analysis</code> SHA1 within the <code>model</code> repo.</p> <p>That means you can create your directory within the private (ie not versioned) directory <code>model/simulation_results</code> based on the SHA1 of <code>model</code> repo (the "parent" repo): that SHA1 links the SHA1 of both <code>project</code> and <code>analysis</code> submodules, which means you can reproduce the experiment <em>exactly</em> (based on the exact content of both <code>project</code> and <code>analysis</code>).</p>
14,589,516
Basic draggable with AngularJS?
<p>I don't want draggable sortable elements or anything fancy, just a draggable element, like a normal jQuery div draggable object:</p> <pre><code>$("#draggable").draggable(); </code></pre> <p>What is the proper way to do this through Angular? Do I still use jQueryUI, or is there anything in AngularUI I can use? I looked through both Angular libraries but didn't find anything specifically addressing draggable objects.</p>
14,589,611
1
0
null
2013-01-29 18:16:01.69 UTC
8
2013-04-24 02:22:53.797 UTC
null
null
null
null
16,631
null
1
24
javascript|jquery|angularjs
24,713
<p>Use a directive.</p> <p>Example:</p> <pre><code>angular.module("myApp").directive('andyDraggable', function() { return { restrict: 'A', link: function(scope, elm, attrs) { var options = scope.$eval(attrs.andyDraggable); //allow options to be passed in elm.draggable(options); } }; }); </code></pre> <p>HTML</p> <pre><code>&lt;div andy-draggable&gt;Drag me!&lt;/div&gt; &lt;div andy-draggable="{key: value}"&gt;Drag me with options!&lt;/div&gt; </code></pre> <p>Documentation on directives: <a href="http://docs.angularjs.org/guide/directive">http://docs.angularjs.org/guide/directive</a></p> <p>You could also create data-binding for the element's current position during the drag, hook up events, etc. But this is a really basic version.</p>
14,890,129
jackson deserialization json to java-objects
<p>Here is my Java code which is used for the de-serialization, i am trying to convert json string into java object. In doing so i have used the following code:</p> <pre><code>package ex1jackson; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class Ex1jackson { public static void main(String[] args) { ObjectMapper mapper = new ObjectMapper(); try { String userDataJSON = "[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"}," + "{\"id\": \"value21\",\"name\":\"value22\",\"qty\": \"value23\"}]"; product userFromJSON = mapper.readValue(userDataJSON, product.class); System.out.println(userFromJSON); } catch (JsonGenerationException e) { System.out.println(e); } catch (JsonMappingException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } } } </code></pre> <p>and my product.java class</p> <pre><code>package ex1jackson; public class product { private String id; private String name; private String qty; @Override public String toString() { return "Product [id=" + id+ ", name= " + name+",qty="+qty+"]"; } } </code></pre> <p>i am getting the following error.</p> <pre><code>com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "id" (class ex1jackson.product), not marked as ignorable (0 known properties: ]) at [Source: java.io.StringReader@16f76a8; line: 1, column: 8] (through reference chain: ex1jackson.product["id"]) BUILD SUCCESSFUL (total time: 0 seconds) </code></pre> <p>help me to solve this,</p>
14,890,770
4
0
null
2013-02-15 07:38:09.507 UTC
5
2020-08-20 22:06:31.283 UTC
2017-07-31 21:50:14.54 UTC
null
1,576,238
null
1,179,916
null
1
29
java|json|object|jackson|deserialization
131,635
<p>It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces <code>{}</code> but your JSON actually starts with square brackets <code>[]</code> designating an array.</p> <p>What you actually have is a <code>List&lt;product&gt;</code> To describe generic types, due to Java's type erasure, you must use a <code>TypeReference</code>. Your deserialization could read: <code>myProduct = objectMapper.readValue(productJson, new TypeReference&lt;List&lt;product&gt;&gt;() {});</code></p> <p>A couple of other notes: your classes should always be PascalCased. Your main method can just be <code>public static void main(String[] args) throws Exception</code> which saves you all the useless <code>catch</code> blocks.</p>
2,394,176
Android: Populating a listview with array items
<p>I'm new to Android and I think I'm trying to do something really basic: I have a 5 strings in my Array (say 'One', 'Two', ...). I want to add these 5 strings to my list view in my listactivity.</p> <p>My List: </p> <pre><code>&lt;ListView android:id="@+id/android:list" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>My List Row:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"&gt; &lt;TextView android:id="@+id/homeItemName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>Basically, I want to bind the Array items to the TextView homeItemName. I might add other items in my row later, so I can't just bind the listview to the entries.</p> <p>Thanks!</p>
2,395,270
2
1
null
2010-03-06 21:31:51.877 UTC
6
2010-03-07 05:13:23.51 UTC
null
null
null
null
406,322
null
1
28
java|android|arrays|listview
73,513
<p>For code, take a quick look at this <a href="http://developer.android.com/intl/de/resources/tutorials/views/hello-listview.html" rel="noreferrer">step-by-step tutorial</a></p> <pre><code>setListAdapter(new ArrayAdapter&lt;String&gt;(this, R.layout.list_item, COUNTRIES)); ListView lv = getListView(); </code></pre> <p>It shows a basic implementation of an ArrayAdapter:</p> <p>R.layout.list_item : is the xml layout (list_item.xml) that will be used for every ROW of your listview. COUNTRIES is the array of Strings.</p>
2,579,657
Ctor not allowed return type
<p>Having code:</p> <pre><code>struct B { int* a; B(int value):a(new int(value)) { } B():a(nullptr){} B(const B&amp;); } B::B(const B&amp; pattern) { } </code></pre> <p>I'm getting err msg:<br> 'Error 1 error C2533: 'B::{ctor}' : constructors not allowed a return type'</p> <p>Any idea why?<br> P.S. I'm using VS 2010RC</p>
2,579,665
2
2
null
2010-04-05 16:57:35.9 UTC
1
2016-07-19 14:33:41.64 UTC
null
null
null
null
207,177
null
1
46
c++|constructor
30,150
<p>You're missing a semicolon after your <code>struct</code> definition.</p> <hr> <p>The error is correct, constructors have no return type. Because you're missing a semicolon, that entire struct definition is seen as a return type for a function, as in:</p> <pre><code>// vvv return type vvv struct { /* stuff */ } foo(void) { } </code></pre> <p>Add your semicolon:</p> <pre><code>struct B { int* a; B(int value):a(new int(value)) { } B():a(nullptr){} B(const B&amp;); }; // end class definition // ah, no return type B::B(const B&amp; pattern) { } </code></pre>
2,866,764
How to count number of occurrences for all different values in database column?
<p>I have a Postgre database that has say 10 columns. The fifth column is called <code>column5</code>. There are 100 rows in the database and possible values of <code>column5</code> are <code>c5value1, c5value2, c5value3...c5value29, c5value30</code>. I would like to print out a table that shows how many times each value occurs. </p> <p>So the table would look like this:</p> <pre><code>Value(of column5) number of occurrences of the value c5value1 1 c5value2 5 c5value3 3 c5value4 9 c5value5 1 c5value6 1 . . . . . . </code></pre> <p>What is the command that does that?</p>
2,866,775
2
0
null
2010-05-19 15:08:46.19 UTC
10
2017-04-15 15:35:25.303 UTC
2017-04-15 15:35:25.303 UTC
null
1,033,581
null
311,865
null
1
55
sql|database|postgresql
91,068
<p>Group by the column you are interested in and then use count to get the number of rows in each group:</p> <pre><code>SELECT column5, COUNT(*) FROM table1 GROUP BY column5 </code></pre>
23,403,352
return default if pandas dataframe.loc location doesn't exist
<p>I find myself often having to check whether a column or row exists in a dataframe before trying to reference it. For example I end up adding a lot of code like:</p> <pre><code>if 'mycol' in df.columns and 'myindex' in df.index: x = df.loc[myindex, mycol] else: x = mydefault </code></pre> <p>Is there any way to do this more nicely? For example on an arbitrary object I can do <code>x = getattr(anobject, 'id', default)</code> - is there anything similar to this in pandas? Really any way to achieve what I'm doing more gracefully?</p>
23,404,657
2
0
null
2014-05-01 06:50:28.067 UTC
3
2019-10-30 03:41:30.53 UTC
null
null
null
null
3,427,777
null
1
53
python|pandas
30,061
<p>There is a method for <a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.Series.get.html#pandas.Series.get"><code>Series</code></a>:</p> <p>So you could do: </p> <pre><code>df.mycol.get(myIndex, NaN) </code></pre> <p>Example:</p> <pre><code>In [117]: df = pd.DataFrame({'mycol':arange(5), 'dummy':arange(5)}) df Out[117]: dummy mycol 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 [5 rows x 2 columns] In [118]: print(df.mycol.get(2, NaN)) print(df.mycol.get(5, NaN)) 2 nan </code></pre>
47,508,564
Migrating create-react-app from javascript to typescript
<p>I started a react project using create-react-app few months ago and I'm interesting in migrating the project from Javascript to Typescript.</p> <p>I saw that there is a way to create react app with typescript using the flag:</p> <pre><code>--scripts-version=react-scripts-ts </code></pre> <p>But I didn't find any explanation how can I migrate an existing JS project to TS. I need it to be done incrementally so I can work with both .js and .ts files so I can do the transformation over time. Does anyone has any experience with this migration? What are the required steps that should be done to make this work?</p>
47,674,979
4
0
null
2017-11-27 10:19:00.153 UTC
18
2021-05-23 20:08:17.01 UTC
null
null
null
null
2,103,462
null
1
53
javascript|reactjs|typescript|create-react-app
22,117
<p><strong>UPDATE:</strong> create-react-app version 2.1.0 support typescript so for those of you who are starting from scratch you can use it to create new application with typescript, and according to the <a href="https://github.com/facebook/create-react-app/releases/tag/v2.1.0" rel="noreferrer">documentation</a> it should be done with the following command:</p> <pre><code>$ npx create-react-app my-app --typescript </code></pre> <p>For existing projects, after updating to version 2.1.0, add the following packages to your project's dependencies with the following command:</p> <pre><code>$ npm install --save typescript @types/node @types/react @types/react-dom @types/jest </code></pre> <p>and then you can simply rename .js to .ts files.</p> <hr /> <p>I found a solution to migrate create-react-app from javascript to typescript, this way <strong>doesn't require</strong> eject.</p> <ol> <li>Create a temporary react project with typescript by running the command <code>create-react-app --scripts-version=react-scripts-ts</code> (Note - requires <code>create-react-app</code> to be installed globally)</li> <li>In your own project - under <code>package.json</code> file remove the <code>react-scripts</code></li> <li>Add <code>react-scripts-ts</code> to your project by running the command <code>yarn add react-scripts-ts</code> or if your are using npm then <code>npm install react-scripts-ts</code>. Or, add <code>&quot;react-scripts-ts&quot;: &quot;2.8.0&quot;</code> to package.json.</li> <li>From the project you created in step 1 copy the files: <code>tsconfig.json, tsconfig.test.json tslint.json</code> to your own project</li> <li>Under your own project, in <code>package.json</code>, under scripts section, change <code>react-scripts</code> instances to <code>react-scripts-ts</code> (should be under <code>start</code>, <code>build</code>, <code>test</code> and <code>eject</code></li> <li>Install the typings for react by installing the following modules using yarn or npm: <code>@types/node</code>, <code>@types/react</code> and <code>@types/react-dom</code>. Put in <code>devDependencies</code> section if using package.json.</li> <li>Change <code>index.js</code> file name to <code>index.tsx</code></li> <li>In your tsconfig.json file add the following configuration: <code>&quot;allowSyntheticDefaultImports&quot;: true</code> - <a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html" rel="noreferrer">for more info</a></li> </ol> <p><strong>NOTE</strong> step 7 might require additional modification depends on what you have in your index.js file (if it depends on JS modules in the project).</p> <p>Now you can run your project and it might work, for those of you who are getting error that contains <code>You may need an appropriate loader to handle this file type</code> regarding .js files, it happens because babel doesn't know how to load .js file from .tsx files. What we need to do is to change the project configuration. The way I found doing it without running <code>eject</code> is using <a href="https://github.com/timarney/react-app-rewired" rel="noreferrer">react-app-rewired</a> package. This package lets you configure external configuration which will be added/override the default project settings. What we'll do is using babel to load these type of files. Let's moved on:</p> <ol> <li><p>Install the package <code>react-app-rewired</code> using yarn or npm</p> </li> <li><p>In your root folder (where <code>package.json</code> is located) create a new file with the name <code>config-overrides.js</code></p> </li> <li><p>Put this code in <code>config-overrides</code> file:</p> <pre><code>var paths = require('react-scripts-ts/config/paths') module.exports = function override(config) { config.module.rules.push({ test: /\.(js|jsx)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { babelrc: false, presets: [require.resolve('babel-preset-react-app')], cacheDirectory: true, }, }) return config } </code></pre> </li> </ol> <p>Edit package.json so the <code>start/start-js</code>, <code>build</code>, <code>test</code>, and <code>eject</code> scripts use react-app-rewired as shown in the <a href="https://github.com/timarney/react-app-rewired#2-custom-scripts-versions" rel="noreferrer">project readme</a>. E.g. <code>&quot;test&quot;: &quot;react-app-rewired test --scripts-version react-scripts-ts --env=jsdom&quot;</code>.</p> <p>Now you can start you the project and the problem should be solved. You might need additional modifications depending on your project (additional types and so).</p> <p>Hope it helps</p> <p>As suggested here in the comments, it's possible to define: <code>&quot;compilerOptions&quot;: { &quot;allowJs&quot;: true}</code> in your tsconfig.json file, so you can mix JS and TS without react-app-rewired. Thanks for mention this!</p>
49,818,415
Android 3.1.1 - Failed resolution of: Lcom/google/android/gms/common/internal/zzbq;
<p>since I've updated to Android Studio 3.1, my project is not running anymore. I have searched for a solution all over the internet with no positive results. Here's the error I get in the Logcat: </p> <pre><code> --------- beginning of crash 04-13 13:33:55.466 12720-12720/? E/AndroidRuntime: FATAL EXCEPTION: main Process: woopy.domain.com.woopy, PID: 12720 java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzbq; at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source:2) at android.app.ActivityThread.installProvider(ActivityThread.java:6239) at android.app.ActivityThread.installContentProviders(ActivityThread.java:5805) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5722) at android.app.ActivityThread.-wrap1(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzbq" on path: DexPathList[[zip file "/data/app/woopy.domain.com.woopy-KqNv1gE1ZomaesHCq33DJw==/base.apk"],nativeLibraryDirectories=[/data/app/woopy.domain.com.woopy-KqNv1gE1ZomaesHCq33DJw==/lib/x86, /system/lib, /vendor/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125) at java.lang.ClassLoader.loadClass(ClassLoader.java:379) at java.lang.ClassLoader.loadClass(ClassLoader.java:312) at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source:2)  at android.app.ActivityThread.installProvider(ActivityThread.java:6239)  at android.app.ActivityThread.installContentProviders(ActivityThread.java:5805)  at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5722)  at android.app.ActivityThread.-wrap1(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6494)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)  04-13 13:33:55.567 12720-12727/? I/zygote: Debugger is no longer active </code></pre> <p><strong>Here's my build.gradle (Module:app) file:</strong></p> <pre><code>android { compileSdkVersion 27 buildToolsVersion "27.0.3" defaultConfig { applicationId "woopy.domain.com.woopy" minSdkVersion 21 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" // Enabling multidex support. multiDexEnabled true aaptOptions { cruncherEnabled = false } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } dexOptions { javaMaxHeapSize "4g" } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.squareup.okhttp3:okhttp:3.10.0' //noinspection GradleCompatible implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support:support-v4:27.1.1' implementation 'com.android.support:design:27.1.1' testImplementation 'junit:junit:4.12' implementation 'com.parse:parse-android:+' implementation 'com.parse.bolts:bolts-android:1.+' //noinspection GradleCompatible implementation 'com.google.android.gms:play-services-maps:+' implementation 'com.google.android.gms:play-services-auth:12.0.1' implementation 'com.google.android.gms:play-services-location:12.0.1' implementation 'com.google.android.gms:play-services:+' implementation 'com.google.android.gms:play-services-ads:+' implementation 'de.hdodenhof:circleimageview:2.2.0' implementation 'com.facebook.android:facebook-android-sdk:4.+' implementation 'com.parse:parsefacebookutils-v4-android:1.10.3@aar' implementation 'com.commit451:PhotoView:1.2.4' } </code></pre> <p><strong>And here's my build.gradle (Project: appname):</strong></p> <pre><code>buildscript { repositories { jcenter() maven { url 'https://maven.google.com' } google() } dependencies { classpath 'com.android.tools.build:gradle:3.1.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() maven { url "https://maven.google.com" } maven { url 'https://maven.google.com/' name 'Google' } } } task clean(type: Delete) { delete rootProject.buildDir } </code></pre> <p>The Build is successful, but the app crashes at startup.</p> <p><strong>EDIT:</strong> It doesn't build successful anymore now, it throws this absolutely weird error in the Build message console:</p> <pre><code>AGPBI: {"kind":"error","text":"Program type already present: com.google.android.gms.location.places.zza","sources":[{}],"tool":"D8"} :app:transformDexArchiveWithExternalLibsDexMergerForDebug FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug' </code></pre> <p>.</p>
49,818,668
10
3
null
2018-04-13 13:40:51.643 UTC
2
2020-05-16 02:21:46.007 UTC
2018-04-13 15:35:02.183 UTC
null
3,724,800
null
3,724,800
null
1
26
android|build.gradle|android-studio-3.1
54,927
<p>Try adding this dependency to your gradle file:</p> <pre><code>implementation 'com.android.support:multidex:1.0.3' </code></pre> <p>Also you should use the same versions for the support and play services libraries. And you should avoid using <strong>"+"</strong> for latest version. Change this part:</p> <pre><code>implementation 'com.google.android.gms:play-services-maps:+' implementation 'com.google.android.gms:play-services-auth:12.0.1' implementation 'com.google.android.gms:play-services-location:12.0.1' implementation 'com.google.android.gms:play-services:+' implementation 'com.google.android.gms:play-services-ads:+' </code></pre> <p>into this:</p> <pre><code>implementation 'com.google.android.gms:play-services-maps:12.0.1' implementation 'com.google.android.gms:play-services-auth:12.0.1' implementation 'com.google.android.gms:play-services-location:12.0.1' implementation 'com.google.android.gms:play-services:12.0.1' implementation 'com.google.android.gms:play-services-ads:12.0.1' </code></pre> <blockquote> <p><strong>EDIT:</strong> You may also add this part to your app level gradle file and try again. I did not see anyone tried this but it may work.</p> </blockquote> <pre><code>allprojects { repositories { //... } subprojects { project.configurations.all { resolutionStrategy.eachDependency { details -&gt; if (details.requested.group == 'com.google.android.gms' &amp;&amp; !details.requested.name.contains('multidex') ) { details.useVersion "12.0.1" } } } } } </code></pre> <blockquote> <p><strong>2ND UPDATE:</strong> Just seen this, the dependency below, covers all the others, then it may cause a duplication issue. Remove the other dependencies and leave this one:</p> </blockquote> <pre><code>implementation 'com.google.android.gms:play-services:12.0.1' </code></pre>
30,235,551
Laravel query builder - re-use query with amended where statement
<p>My application dynamically builds and runs complex queries to generate reports. In some instances I need to get multiple, somewhat arbitrary date ranges, with all other parameters the same. </p> <p>So my code builds the query with a bunch of joins, wheres, sorts, limits etc and then runs the query. What I then want to do is jump into the Builder object and change the where clauses which define the date range to be queried. </p> <p>So far, I have made it so that the date range is setup before any other wheres and then tried to manually change the value in the relevant attribute of the wheres array. Like this;</p> <pre><code>$this-&gt;data_qry-&gt;wheres[0]['value'] = $new_from_date; $this-&gt;data_qry-&gt;wheres[1]['value'] = $new_to_date; </code></pre> <p>Then I do (having already done it once already)</p> <pre><code>$this-&gt;data_qry-&gt;get(); </code></pre> <p>Doesn't work though. The query just runs with the original date range. Even if my way worked, I still wouldn't like it though as it seems to be shot through with a precarious dependence (some sort of coupling?). Ie; if the date wheres aren't set up first then it all falls apart. </p> <p>I <em>could</em> set the whole query up again from scratch, just with a different date range, but that seems ott as everything else in the query needs to be the same as the previous time it was used. </p> <p>Any ideas for how to achieve this in the correct / neatest way are very welcome. </p> <p>Thanks,</p> <p>Geoff</p>
30,235,755
3
0
null
2015-05-14 10:55:34.997 UTC
13
2022-04-04 13:31:09.193 UTC
null
null
null
null
1,800,061
null
1
79
php|mysql|laravel|query-builder
36,187
<p>You can use <code>clone</code> to duplicate the query and then run it with different where statements. First, build the query without the from-to constraints, then do something like this:</p> <pre><code>$query1 = $this-&gt;data_qry; $query2 = clone $query1; $result1 = $query1-&gt;where('from', $from1)-&gt;where('to', $to1)-&gt;get(); $result2 = $query2-&gt;where('from', $from2)-&gt;where('to', $to2)-&gt;get(); </code></pre>
31,871,806
Laravel Homestead Swift Cannot send message without a sender address
<p>I get this error with stock email settings in Laravel 5.1 Homestead when I try to send a password reset mail. </p> <pre><code>Swift_TransportException in AbstractSmtpTransport.php line 162:Cannot send message without a sender address </code></pre> <p>The address is filled in app/config/mail.php: </p> <pre><code>'from' =&gt; array('address' =&gt; '[email protected]', 'name' =&gt; 'hawle'), </code></pre>
31,872,058
21
0
null
2015-08-07 07:20:26.203 UTC
8
2022-07-21 15:14:09.743 UTC
null
null
null
null
704,170
null
1
52
php|laravel|laravel-5.1
141,392
<p>In your <code>.env</code> file you will need to set the email address and password of your email account. You also need to set the host and port of the mail server you are using.</p> <pre><code>MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=25 MAIL_USERNAME= ***USER NAME*** MAIL_PASSWORD= ***PASSWORD*** MAIL_ENCRYPTION=tls </code></pre> <p>Or make sure that everything is complete in your <code>mail.php</code> file (see note below). </p> <pre><code>'host' =&gt; env('MAIL_HOST', 'smtp.gmail.com'), /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to deliver e-mails to | users of the application. Like the host we have set this value to | stay compatible with the Mailgun e-mail application by default. | */ 'port' =&gt; env('MAIL_PORT', 25), /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' =&gt; ['address' =&gt; '[email protected]', 'name' =&gt; 'hawle'], /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' =&gt; env('MAIL_ENCRYPTION', 'tls'), </code></pre> <p><strong>Note: It's better to use the <code>.env</code> file, as you most likely will have a different configuration in your production environment.</strong></p> <p>If everything is completed and it still doesn't work, it might be caching. You can clear the config cache with this:</p> <pre><code>php artisan config:cache </code></pre> <p>Also note: </p> <ul> <li>Port 465 is for Gmail. If it does not work, you can use 25. </li> <li>The <code>mail.php</code> file is located at <code>/app/config/mail.php</code> (as OP said). </li> <li>The <code>.env</code> file is located at the root of your project. </li> <li>Mailtrap.io is a service for testing SMTP. It does not really send emails. </li> </ul> <p><strong>As Viktorminator mentioned:</strong> <em>Take into consideration creating app passwords and not using your usual pass for this needs. Link for creating passwords <a href="https://myaccount.google.com/apppasswords" rel="noreferrer">myaccount.google.com/apppasswords</a></em> </p>
26,024,582
maven : Failed to install metadata project Could not parse metadata maven-metadata-local.xml: only whitespace content allowed before start tag
<p>Got this error when I was trying to build a project which I just downloaded from SVN.</p> <blockquote> <p>Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-install) on project : Failed to install metadata project:1.0-SNAPSHOT/maven-metadata.xml: Could not parse metadata C:\Users.m2\project\1.0-SNAPSHOT\maven-metadata-local.xml: only whitespace content allowed before start tag and not \u0 (position: START_DOCUMENT seen \u0... @1:1) -> [Help 1]</p> </blockquote>
26,024,633
4
0
null
2014-09-24 19:07:19.307 UTC
9
2019-11-19 10:15:16.597 UTC
2017-05-02 01:24:38.36 UTC
null
1,119,381
null
1,535,917
null
1
37
java|xml|maven|installation
42,049
<p>I just wanted to document this error on the internet. There was no much help or I didn't search properly. </p> <p><strong>Answer</strong> : </p> <p>Go to the the path where the <code>maven-metadata-local.xml</code> is. Delete the project folder along with the <code>xml</code> and build the project. </p> <p>It worked for me!</p>
26,942,604
Celery and transaction.atomic
<p>In some Django views, I used a pattern like this to save changes to a model, and then to do some asynchronous updating (such as generating images, further altering the model) based on the new model data. <code>mytask</code> is a celery task:</p> <pre><code>with transaction.atomic(): mymodel.save() mytask.delay(mymodel.id).get() </code></pre> <p>The problem is that the task never returns. Looking at celery's logs, the task gets queued (I see "Received task" in the log), but it never completes. If I move the <code>mytask.delay...get</code> call out of the transaction, it completes successfully.</p> <p>Is there some incompatibility between <code>transaction.atomic</code> and celery? Is it possible in Django 1.6 or 1.7 for me to have both regular model updates and updates from a separate task process under one transaction?</p> <p>My database is postgresql 9.1. I'm using celery==3.1.16 / django-celery 3.1.16, amqp==1.4.6, Django==1.6.7, kombu==3.0.23. The broker backend is amqp, and rabitmq as the queue.</p>
31,030,040
3
0
null
2014-11-15 04:39:59.133 UTC
8
2018-03-14 12:43:15.967 UTC
null
null
null
null
85,461
null
1
22
django|postgresql|transactions|celery
13,158
<p>"Separate task" = something that is ran by a worker. </p> <p>"Celery worker" = another process.</p> <p>I am not aware of any method that would let you have a single database transaction shared between 2 or more processess. What you want is to run the task in a synchronous way, in that transaction, and wait for the result... but, if that's what you want, why do you need a task queue anyway? </p>
24,830,079
Firebase rate limiting in security rules?
<p>I launched my first open repository project, <a href="https://github.com/bmmayer/ephchat" rel="noreferrer">EphChat</a>, and people promptly started flooding it with requests.</p> <p>Does Firebase have a way to rate limit requests in the security rules? I assume there's a way to do it using the time of the request and the time of previously written data, but can't find anything in the documentation about how I would do this.</p> <p>The current security rules are as follows.</p> <pre><code>{ &quot;rules&quot;: { &quot;rooms&quot;: { &quot;$RoomId&quot;: { &quot;connections&quot;: { &quot;.read&quot;: true, &quot;.write&quot;: &quot;auth.username == newData.child('FBUserId').val()&quot; }, &quot;messages&quot;: { &quot;$any&quot;: { &quot;.write&quot;: &quot;!newData.exists() || root.child('rooms').child(newData.child('RoomId').val()).child('connections').hasChild(newData.child('FBUserId').val())&quot;, &quot;.validate&quot;: &quot;newData.hasChildren(['RoomId','FBUserId','userName','userId','message']) &amp;&amp; newData.child('message').val().length &gt;= 1&quot;, &quot;.read&quot;: &quot;root.child('rooms').child(data.child('RoomId').val()).child('connections').hasChild(data.child('FBUserId').val())&quot; } }, &quot;poll&quot;: { &quot;.write&quot;: &quot;auth.username == newData.child('FBUserId').val()&quot;, &quot;.read&quot;: true } } } } } </code></pre> <p>I would want to rate-limit writes (and reads?) to the db for the entire Rooms object, so only 1 request can be made per second (for example).</p>
24,841,859
4
0
null
2014-07-18 16:47:02.963 UTC
32
2021-01-04 12:40:49.633 UTC
2021-01-04 12:37:49.1 UTC
null
2,359,227
null
1,288,611
null
1
47
firebase|firebase-realtime-database|firebase-security|rate-limiting
17,690
<p>The trick is to keep an audit of the last time a user posted a message. Then you can enforce the time each message is posted based on the audit value:</p> <pre><code>{ "rules": { // this stores the last message I sent so I can throttle them by timestamp "last_message": { "$user": { // timestamp can't be deleted or I could just recreate it to bypass our throttle ".write": "newData.exists() &amp;&amp; auth.uid === $user", // the new value must be at least 5000 milliseconds after the last (no more than one message every five seconds) // the new value must be before now (it will be since `now` is when it reaches the server unless I try to cheat) ".validate": "newData.isNumber() &amp;&amp; newData.val() === now &amp;&amp; (!data.exists() || newData.val() &gt; data.val()+5000)" } }, "messages": { "$message_id": { // message must have a timestamp attribute and a sender attribute ".write": "newData.hasChildren(['timestamp', 'sender', 'message'])", "sender": { ".validate": "newData.val() === auth.uid" }, "timestamp": { // in order to write a message, I must first make an entry in timestamp_index // additionally, that message must be within 500ms of now, which means I can't // just re-use the same one over and over, thus, we've effectively required messages // to be 5 seconds apart ".validate": "newData.val() &gt;= now - 500 &amp;&amp; newData.val() === data.parent().parent().parent().child('last_message/'+auth.uid).val()" }, "message": { ".validate": "newData.isString() &amp;&amp; newData.val().length &lt; 500" }, "$other": { ".validate": false } } } } } </code></pre> <p>See it in action <a href="http://jsfiddle.net/firebase/VBmA5/" rel="noreferrer">in this fiddle</a>. Here's the gist of what's in the fiddle:</p> <pre><code>var fb = new Firebase(URL); var userId; // log in and store user.uid here // run our create routine createRecord(data, function (recordId, timestamp) { console.log('created record ' + recordId + ' at time ' + new Date(timestamp)); }); // updates the last_message/ path and returns the current timestamp function getTimestamp(next) { var ref = fb.child('last_message/' + userId); ref.set(Firebase.ServerValue.TIMESTAMP, function (err) { if (err) { console.error(err); } else { ref.once('value', function (snap) { next(snap.val()); }); } }); } function createRecord(data, next) { getTimestamp(function (timestamp) { // add the new timestamp to the record data var data = { sender: userId, timestamp: timestamp, message: 'hello world' }; var ref = fb.child('messages').push(data, function (err) { if (err) { console.error(err); } else { next(ref.name(), timestamp); } }); }) } </code></pre>
37,853,903
Can I send files via email using MailKit?
<p>As the title, is MailKit supported to send file?<br/> If yes, how can I do it?</p>
37,860,224
3
0
null
2016-06-16 08:32:32.633 UTC
16
2021-10-04 07:42:54.333 UTC
2019-03-01 14:02:19.887 UTC
null
2,024,157
null
4,995,112
null
1
72
c#|email-attachments|mailkit|mimekit
53,581
<p>Yes. This is explained in the documentation as well as the <a href="https://github.com/jstedfast/MailKit/blob/master/FAQ.md#CreateAttachments" rel="noreferrer">FAQ</a>.</p> <p>From the FAQ:</p> <h3>How do I create a message with attachments?</h3> <p>To construct a message with attachments, the first thing you'll need to do is create a <code>multipart/mixed</code> container which you'll then want to add the message body to first. Once you've added the body, you can then add MIME parts to it that contain the content of the files you'd like to attach, being sure to set the <code>Content-Disposition</code> header value to the attachment. You'll probably also want to set the <code>filename</code> parameter on the <code>Content-Disposition</code> header as well as the <code>name</code> parameter on the <code>Content-Type</code> header. The most convenient way to do this is to simply use the <a href="http://www.mimekit.net/docs/html/P_MimeKit_MimePart_FileName.htm" rel="noreferrer">MimePart.FileName</a> property which will set both parameters for you as well as setting the <code>Content-Disposition</code> header value to <code>attachment</code> if it has not already been set to something else.</p> <pre><code>var message = new MimeMessage (); message.From.Add (new MailboxAddress (&quot;Joey&quot;, &quot;[email protected]&quot;)); message.To.Add (new MailboxAddress (&quot;Alice&quot;, &quot;[email protected]&quot;)); message.Subject = &quot;How you doin?&quot;; // create our message text, just like before (except don't set it as the message.Body) var body = new TextPart (&quot;plain&quot;) { Text = @&quot;Hey Alice, What are you up to this weekend? Monica is throwing one of her parties on Saturday. I was hoping you could make it. Will you be my +1? -- Joey &quot; }; // create an image attachment for the file located at path var attachment = new MimePart (&quot;image&quot;, &quot;gif&quot;) { Content = new MimeContent (File.OpenRead (path)), ContentDisposition = new ContentDisposition (ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, FileName = Path.GetFileName (path) }; // now create the multipart/mixed container to hold the message text and the // image attachment var multipart = new Multipart (&quot;mixed&quot;); multipart.Add (body); multipart.Add (attachment); // now set the multipart/mixed as the message body message.Body = multipart; </code></pre> <p>A simpler way to construct messages with attachments is to take advantage of the <a href="http://www.mimekit.net/docs/html/T_MimeKit_BodyBuilder.htm" rel="noreferrer">BodyBuilder</a> class.</p> <pre><code>var message = new MimeMessage (); message.From.Add (new MailboxAddress (&quot;Joey&quot;, &quot;[email protected]&quot;)); message.To.Add (new MailboxAddress (&quot;Alice&quot;, &quot;[email protected]&quot;)); message.Subject = &quot;How you doin?&quot;; var builder = new BodyBuilder (); // Set the plain-text version of the message text builder.TextBody = @&quot;Hey Alice, What are you up to this weekend? Monica is throwing one of her parties on Saturday. I was hoping you could make it. Will you be my +1? -- Joey &quot;; // We may also want to attach a calendar event for Monica's party... builder.Attachments.Add (@&quot;C:\Users\Joey\Documents\party.ics&quot;); // Now we just need to set the message body and we're done message.Body = builder.ToMessageBody (); </code></pre> <p>For more information, see <a href="http://www.mimekit.net/docs/html/Creating-Messages.htm" rel="noreferrer">Creating Messages</a>.</p>
35,692,506
How to get login with different database table column name in Laravel 5.2?
<p>I have to implement login functionality in Laravel 5.2. I have successfully done so using the official Laravel documentation except that I do not know how to authenticate the user using different database table column names, namely <code>st_username</code>and <code>st_password</code>.</p> <p>I have searched the Internet for clues but to no avail. I don't know which class I need to use (like, use Illuminate.......) for Auth. If any one knows the answer, please let me know. </p> <p>Here is my code:</p> <p>Login View</p> <pre><code>@extends('layouts.app') @section('content') &lt;div class="contact-bg2"&gt; &lt;div class="container"&gt; &lt;div class="booking"&gt; &lt;h3&gt;Login&lt;/h3&gt; &lt;div class="col-md-4 booking-form" style="margin: 0 33%;"&gt; &lt;form method="post" action="{{ url('/login') }}"&gt; {!! csrf_field() !!} &lt;h5&gt;USERNAME&lt;/h5&gt; &lt;input type="text" name="username" value="abcuser"&gt; &lt;h5&gt;PASSWORD&lt;/h5&gt; &lt;input type="password" name="password" value="abcpass"&gt; &lt;input type="submit" value="Login"&gt; &lt;input type="reset" value="Reset"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt;&lt;/div&gt; @endsection </code></pre> <p>AuthController</p> <pre><code>namespace App\Http\Controllers\Auth; use App\User; use Validator; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; class AuthController extends Controller { use AuthenticatesAndRegistersUsers, ThrottlesLogins; protected $redirectTo = '/home'; public function __construct() { $this-&gt;middleware('guest', ['except' =&gt; 'logout']); $this-&gt;username = 'st_username'; $this-&gt;password = 'st_password'; } protected function validator(array $data) { return Validator::make($data, [ 'name' =&gt; 'required|max:255', 'email' =&gt; 'required|email|max:255|unique:users', 'password' =&gt; 'required|confirmed|min:6', ]); } </code></pre> <p>Route File</p> <pre><code>Route::get('/', function () { return view('index'); }); Route::group(['middleware' =&gt; 'web'], function () { Route::auth(); Route::get('/home', 'HomeController@index'); }); </code></pre> <p>config/auth.php</p> <pre><code>return [ 'defaults' =&gt; [ 'guard' =&gt; 'web', 'passwords' =&gt; 'users', ], 'guards' =&gt; [ 'web' =&gt; [ 'driver' =&gt; 'session', 'provider' =&gt; 'users', ], 'api' =&gt; [ 'driver' =&gt; 'token', 'provider' =&gt; 'users', ], ], 'providers' =&gt; [ 'users' =&gt; [ 'driver' =&gt; 'eloquent', 'model' =&gt; App\User::class, ], // 'users' =&gt; [ // 'driver' =&gt; 'database', // 'table' =&gt; 'users', // ], ], 'passwords' =&gt; [ 'users' =&gt; [ 'provider' =&gt; 'users', 'email' =&gt; 'auth.emails.password', 'table' =&gt; 'password_resets', 'expire' =&gt; 60, ], ], ]; </code></pre>
35,824,963
3
0
null
2016-02-29 05:23:24.883 UTC
8
2019-04-01 00:17:21.83 UTC
2019-04-01 00:17:21.83 UTC
null
633,440
null
4,545,911
null
1
9
php|laravel|laravel-5|laravel-5.2
14,674
<p>I searched a lot how to customize <strong>Laravel 5.2</strong> authorisation form and this is what is working for me 100%. Here is from bottom to top solution.</p> <p>This solution is originally from here: <a href="https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication" rel="noreferrer">https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication</a></p> <p>but i had to make couple changes to make it work.</p> <p>My web app is for the DJs so my custom column names are with 'dj_', for example name is dj_name</p> <ol> <li><p>config/auth.php</p> <pre><code>// change this 'driver' =&gt; 'eloquent', // to this 'driver' =&gt; 'custom', </code></pre></li> <li><p>in config/app.php add your custom provider to the list ...</p> <pre><code>'providers' =&gt; [ ... // add this on bottom of other providers App\Providers\CustomAuthProvider::class, ... ], </code></pre></li> <li><p>Create CustomAuthProvider.php inside folder app\Providers <pre><code>namespace App\Providers; use Illuminate\Support\Facades\Auth; use App\Providers\CustomUserProvider; use Illuminate\Support\ServiceProvider; class CustomAuthProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { Auth::provider('custom', function($app, array $config) { // Return an instance of Illuminate\Contracts\Auth\UserProvider... return new CustomUserProvider($app['custom.connection']); }); } /** * Register the application services. * * @return void */ public function register() { // } } </code></pre></li> <li><p>Create CustomUserProvider.php also inside folder app\Providers</p> <pre><code>&lt;?php namespace App\Providers; use App\User; use Carbon\Carbon; use Illuminate\Auth\GenericUser; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Log; class CustomUserProvider implements UserProvider { /** * Retrieve a user by their unique identifier. * * @param mixed $identifier * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveById($identifier) { // TODO: Implement retrieveById() method. $qry = User::where('dj_id','=',$identifier); if($qry-&gt;count() &gt;0) { $user = $qry-&gt;select('dj_id', 'dj_name', 'first_name', 'last_name', 'email', 'password')-&gt;first(); $attributes = array( 'id' =&gt; $user-&gt;dj_id, 'dj_name' =&gt; $user-&gt;dj_name, 'password' =&gt; $user-&gt;password, 'email' =&gt; $user-&gt;email, 'name' =&gt; $user-&gt;first_name . ' ' . $user-&gt;last_name, ); return $user; } return null; } /** * Retrieve a user by by their unique identifier and "remember me" token. * * @param mixed $identifier * @param string $token * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveByToken($identifier, $token) { // TODO: Implement retrieveByToken() method. $qry = User::where('dj_id','=',$identifier)-&gt;where('remember_token','=',$token); if($qry-&gt;count() &gt;0) { $user = $qry-&gt;select('dj_id', 'dj_name', 'first_name', 'last_name', 'email', 'password')-&gt;first(); $attributes = array( 'id' =&gt; $user-&gt;dj_id, 'dj_name' =&gt; $user-&gt;dj_name, 'password' =&gt; $user-&gt;password, 'email' =&gt; $user-&gt;email, 'name' =&gt; $user-&gt;first_name . ' ' . $user-&gt;last_name, ); return $user; } return null; } /** * Update the "remember me" token for the given user in storage. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @param string $token * @return void */ public function updateRememberToken(Authenticatable $user, $token) { // TODO: Implement updateRememberToken() method. $user-&gt;setRememberToken($token); $user-&gt;save(); } /** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveByCredentials(array $credentials) { // TODO: Implement retrieveByCredentials() method. $qry = User::where('email','=',$credentials['email']); if($qry-&gt;count() &gt; 0) { $user = $qry-&gt;select('dj_id','dj_name','email','password')-&gt;first(); return $user; } return null; } /** * Validate a user against the given credentials. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @param array $credentials * @return bool */ public function validateCredentials(Authenticatable $user, array $credentials) { // TODO: Implement validateCredentials() method. // we'll assume if a user was retrieved, it's good // DIFFERENT THAN ORIGINAL ANSWER if($user-&gt;email == $credentials['email'] &amp;&amp; Hash::check($credentials['password'], $user-&gt;getAuthPassword()))//$user-&gt;getAuthPassword() == md5($credentials['password'].\Config::get('constants.SALT'))) { //$user-&gt;last_login_time = Carbon::now(); $user-&gt;save(); return true; } return false; } } </code></pre></li> <li><p>in App/Http/Controllers/Auth/AuthController.php change all 'name' to 'dj_name' and add your custom fields if you have them...you can also change 'email' to your email column name</p></li> <li><p>In Illuminate\Foundation\Auth\User.php add</p> <pre><code>protected $table = 'djs'; protected $primaryKey = 'dj_id'; </code></pre></li> <li><p>In App/User.php change 'name' to 'dj_name' and add your custom fields. For changing 'password' column to your custom column name add</p> <pre><code>public function getAuthPassword(){ return $this-&gt;custom_password_column_name; } </code></pre></li> <li><p>Now backend is all done, so you only have to change layouts login.blade.php, register.blade.php, app.blade.php...here you only have to change 'name' to 'dj_name', email, or your custom fields... <strong>!!! password field NEEDS to stay named password !!!</strong></p></li> </ol> <p>Also, to make unique email validation change AuthController.php</p> <pre><code>'custom_email_field' =&gt; 'required|email|max:255|unique:users', to 'custom_email_field' =&gt; 'required|email|max:255|unique:custom_table_name', </code></pre> <p>Also, if you want to make custom created_at an updated_at fields change global variables in Illuminate\Database\Eloquent\Model.php</p> <pre><code>const CREATED_AT = 'dj_created_at'; const UPDATED_AT = 'dj_updated_at'; </code></pre>
43,003,012
Class JavaLaunchHelper is implemented in two places
<p>Today I upgraded my Intellij Idea on macOS Sierra, and now, when I run apps in console I have this error:</p> <blockquote> <p>objc[3648]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/java (0x10d19c4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x10ea194e0). One of the two will be used. Which one is undefined.</p> </blockquote>
43,003,231
7
0
null
2017-03-24 15:10:21.957 UTC
103
2018-04-19 14:01:35.263 UTC
2017-07-19 17:16:38.45 UTC
null
3,745,896
null
7,703,134
null
1
307
java|macos|intellij-idea
208,828
<p>You can find all the details here:</p> <ul> <li><a href="https://youtrack.jetbrains.com/issue/IDEA-170117" rel="noreferrer">IDEA-170117</a> "objc: Class JavaLaunchHelper is implemented in both ..." warning in Run consoles</li> </ul> <p>It's the <a href="https://bugs.openjdk.java.net/browse/JDK-8022291" rel="noreferrer">old bug in Java</a> on Mac that <a href="https://github.com/JetBrains/intellij-community/commit/4fde1be3df5f7c145f943a969eb261e32bf72ef6" rel="noreferrer">got triggered by the Java Agent</a> being used by the IDE when starting the app. This message is harmless and is safe to ignore. Oracle developer's comment:</p> <blockquote> <p>The message is benign, there is no negative impact from this problem since both copies of that class are identical (compiled from the exact same source). It is purely a cosmetic issue.</p> </blockquote> <p>The <a href="https://bugs.openjdk.java.net/browse/JDK-8022291" rel="noreferrer">problem is fixed</a> in <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk9-downloads-3848520.html" rel="noreferrer">Java 9</a> and in <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html" rel="noreferrer">Java 8 update 152</a>.</p> <p>If it annoys you or affects your apps in any way (it shouldn't), the workaround for IntelliJ IDEA is to disable <code>idea_rt</code> launcher agent by adding <code>idea.no.launcher=true</code> into <code>idea.properties</code> (<code>Help</code> | <code>Edit Custom Properties...</code>). The workaround will take effect on the next restart of the IDE. </p> <p>I don't recommend disabling IntelliJ IDEA launcher agent, though. It's used for such features as graceful shutdown (Exit button), thread dumps, workarounds a problem with too long command line exceeding OS limits, etc. Losing these features just for the sake of hiding the harmless message is probably not worth it, but it's up to you.</p>
65,677,156
Could not transfer artifact from/to central intellij
<p>My Spring boot project using Maven. When i build it using Intellij Community, i get the error</p> <blockquote> <p>Could not transfer artifact com.jolira:hickory:pom:1.0.0 from/to central (<a href="https://repo.maven.apache.org/maven2" rel="nofollow noreferrer">https://repo.maven.apache.org/maven2</a>): Transfer failed for <a href="https://repo.maven.apache.org/maven2/com/jolira/hickory/1.0.0/hickory-1.0.0.pom" rel="nofollow noreferrer">https://repo.maven.apache.org/maven2/com/jolira/hickory/1.0.0/hickory-1.0.0.pom</a></p> </blockquote> <p>I can build this project success using cmd command line.</p> <p>My Intellij Community version is:</p> <blockquote> <p>IntelliJ IDEA 2020.3.1 (Community Edition) Build #IC-203.6682.168, built on December 29, 2020 Runtime version: 11.0.9.1+11-b1145.63 amd64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o. Windows 10 10.0 GC: ParNew, ConcurrentMarkSweep Memory: 1945M Cores: 8</p> </blockquote> <p>my pom.xml file</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.3.5.RELEASE&lt;/version&gt; &lt;relativePath /&gt; &lt;/parent&gt; &lt;groupId&gt;com.super.banana&lt;/groupId&gt; &lt;!-- Always write artifactId with underscore _ --&gt; &lt;artifactId&gt;banana_parent&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;packaging&gt;pom&lt;/packaging&gt; &lt;name&gt;bananas_parent&lt;/name&gt; &lt;description&gt;banana Parent&lt;/description&gt; &lt;modules&gt; &lt;module&gt;bananas-mt&lt;/module&gt; &lt;module&gt;bananas-web&lt;/module&gt; &lt;/modules&gt; &lt;properties&gt; &lt;java.version&gt;11&lt;/java.version&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;commons-io.version&gt;2.6&lt;/commons-io.version&gt; &lt;commons-lang.version&gt;3.10&lt;/commons-lang.version&gt; &lt;org.mapstruct.version&gt;1.3.1.Final&lt;/org.mapstruct.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;/dependencies&gt; &lt;/project&gt; </code></pre> <p>How to fix this issue ?</p>
65,694,931
7
0
null
2021-01-12 02:17:16.147 UTC
2
2022-07-21 06:14:23.743 UTC
2021-01-12 02:26:17.78 UTC
null
2,234,250
null
2,234,250
null
1
4
spring-boot|maven
40,400
<p><strong>Solution 1</strong>: I have fixed this issue, in menu choose File -&gt; Setting -&gt; Build, Execution, Deployment -&gt;Build Tools -&gt; Maven. In section User setting file stick Override and browse to <code>settings.xml</code> of Maven (in my case the <code>settings.xml</code> file in directory ..\apache-maven-3.6.3\conf .</p> <p>I have proxy configuration in <code>settings.xml</code>) <a href="https://i.stack.imgur.com/78qh3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/78qh3.png" alt="enter image description here" /></a></p> <p><strong>Solution 2</strong>:</p> <p>In my case I have problem with <code>com/jolira/hickory/1.0.0/hickory-1.0.0.pom</code></p> <p><strong>Similar your case with <strong>another library</strong></strong></p> <p>I go to repository of <code>hickory</code> on <a href="https://mvnrepository.com" rel="nofollow noreferrer">https://mvnrepository.com</a></p> <p><a href="https://i.stack.imgur.com/6nM9b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6nM9b.png" alt="enter image description here" /></a></p> <p>I download .jar file and .pom file from maven page</p> <p><a href="https://i.stack.imgur.com/T5IqH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T5IqH.png" alt="enter image description here" /></a></p> <p>go to {your .m2 directory home}.m2\repository\com\jolira\hickory\1.0.0 and past the <code>hickory-1.0.0.jar</code> and the <code>hickory-1.0.0.pom</code> to there</p> <p><a href="https://i.stack.imgur.com/gBJ5P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gBJ5P.png" alt="enter image description here" /></a></p> <p>open command line and run mvn <code>clean install again</code>. It should sucessful</p>
7,140,741
Backbone.js model with collection
<p>I have 2 models and one collection. <code>JobSummary</code> is a model, <code>JobSummaryList</code> is a collection of <code>JobSummary</code> items, and then I have a <code>JobSummarySnapshot</code> model that contains a <code>JobSummaryList</code>:</p> <pre><code>JobSummary = Backbone.Model.extend({}); JobSummaryList = Backbone.Collection.extend({ model: JobSummary }); JobSummarySnapshot = Backbone.Model.extend({ url: '/JobSummaryList', defaults: { pageNumber: 1, summaryList: new JobSummaryList() } }); </code></pre> <p>When I call <code>fetch</code> on the <code>JobSummarySnapshot</code> object, it gets everything... Except when I move through the <code>summaryList</code> collection they are all of type <code>object</code> and not <code>JobSummary</code>.</p> <p>I suppose this makes sense since other than the <code>defaults</code> object, it doesn't know that the <code>summaryList</code> should be of type <code>JobSummaryList</code>. I can go through each item and convert it to a <code>JobSummary</code> object, but I was hoping there was a way to do it without having to do it manually. </p> <p>Here's my test code (working <a href="http://jsfiddle.net/vbfischer/NSEVe/" rel="noreferrer">jsfiddle here</a>):</p> <pre><code>var returnData = { pageNumber: 3, summaryList: [ { id: 5, name: 'name1'}, { id: 6, name: 'name2'} ] }; var fakeserver = sinon.fakeServer.create(); fakeserver.respondWith('GET', '/JobSummaryList', [200, { 'Content-Type': 'application/json'}, JSON.stringify(returnData)]); var callback = sinon.spy(); var summarySnapshot = new JobSummarySnapshot(); summarySnapshot.bind('change', callback); summarySnapshot.fetch(); fakeserver.respond(); var theReturnedList = callback.getCall(0).args[0].attributes.summaryList; _.each(theReturnedList, function(item) { console.log('Original Item: '); console.log(item instanceof JobSummary); // IS FALSE var convertedItem = new JobSummary(item); console.log('converted item: '); console.log(convertedItem instanceof JobSummary); // IS TRUE }); </code></pre> <p>UPDATE: It occurred to me that I could override the parse function and set it that way... I have this now:</p> <pre><code>JobSummarySnapshot = Backbone.Model.extend({ url: '/JobSummaryList', defaults: { pageNumber: 1, summaryList: new JobSummaryList() }, parse: function(response) { this.set({pageNumber: response.pageNumber}); var summaryList = new JobSummaryList(); summaryList.add(response.summaryList); this.set({summaryList: summaryList}); } }); </code></pre> <p>This works so far. Leaving the question open in case someone has comment on it....</p>
7,141,040
1
0
null
2011-08-21 19:58:54.077 UTC
12
2013-08-30 10:14:48.64 UTC
2013-08-30 10:14:48.64 UTC
null
2,442,466
null
450,139
null
1
37
javascript|ajax|json|backbone.js
30,138
<p>Your <code>parse()</code> function shouldn't <code>set()</code> anything, its a better practice to just return the attributes, Backbone will take care of setting it. e.g.</p> <pre><code>parse: function(response) { response.summaryList = new JobSummaryList(response.summaryList); return response; } </code></pre> <p>Whatever you return from <code>parse()</code> is <a href="https://github.com/documentcloud/backbone/blob/master/backbone.js#L284" rel="noreferrer">passed to <code>set()</code></a>.</p> <p>Not returning anything (which is like returning <code>undefined</code>) is the same as calling <code>set(undefined)</code>, which could cause it not to pass validation, or some other unexpected results if your custom <code>validate()</code>/<code>set()</code> methods expects to get an object. If your validation or <code>set()</code> method fails because of that, the <code>options.success</code> callback passed to <code>Backbone.Model#fetch()</code> won't be called.</p> <p>Also, to make this more generic, so that <code>set()</code>ing to a plain object from other places (and not only from the server response) also effects it, you might want to override <code>set()</code> instead:</p> <pre><code>set: function(attributes, options) { if (attributes.summaryList !== undefined &amp;&amp; !(attributes.summaryList instanceof JobSummaryList)) { attributes.summaryList = new JobSummaryList(attributes.summaryList); } return Backbone.Model.prototype.set.call(this, attributes, options); } </code></pre> <p>You might also find <a href="https://github.com/PaulUithol/Backbone-relational" rel="noreferrer">Backbone-relational</a> interesting - it makes it much easier to deal with collections/models nested inside models.</p> <p><strong>edit</strong> I forgot to return from the set() method, the code is now updated</p>
24,672,341
How to debug app when launch by push notification in Xcode
<p>I am using Xcode 5. I am working with push notifications in iOS. I am getting satisfying results for background mode and foreground mode that can be debugged easily on an iOS device.</p> <p>But problem is when app is in closed state and launched by push notification tap but I don't know how to debug in this situation. I know the solution for Xcode 4 but not for Xcode 5. </p> <p>So is there any solution for Xcode 5 and debugging the app when launching it by push notifications? Provide steps to debug in this situation.</p>
24,672,592
3
0
null
2014-07-10 08:57:03.167 UTC
18
2021-09-13 11:33:38.207 UTC
2018-05-08 13:26:59.913 UTC
null
1,033,581
null
3,824,626
null
1
67
ios|xcode|debugging|push-notification|xcode5
19,142
<p>Edit your project scheme and set &quot;Launch&quot; to &quot;Wait for *.app to be launched manually&quot;. Then Run the project or hit &quot;cmd+R&quot;. The app will not be launched automatically, but the debugger will attach to the process as soon as the app launches. So send your test push notification, and launch the app from the push.<br /> Here you go!</p> <p><a href="https://i.stack.imgur.com/jGiR1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jGiR1.png" alt="enter image description here" /></a></p>
39,065,786
Auto increment a value in firebase with javascript
<p>Hello I'm working on some firebase project and i can save my datas via javascript into firebase database. But i couldn't figure it out to auto increment child value (my child value is duyuru, you can see the details in the below) of my database. I'm sharing my code in below can you give me hints to solve this issue.</p> <pre><code> &lt;script&gt; // Initialize Firebase var config = { apiKey: "sample1", authDomain: "sample2", databaseURL: "sample3", storageBucket: "sample4", }; firebase.initializeApp(config); var database = firebase.database(); firebase.initializeApp(config); var database = firebase.database(); function writeUserData(userId, name, email, imageUrl) { var kategori1 = document.getElementById("kategori").value; var duyuru1 = document.getElementById("duyuru").value; var name1 = document.getElementById("name").value; var email1 = document.getElementById("email").value; var imageUrl1 = document.getElementById("imageUrl").value; firebase.database().ref(kategori1 +"/" + duyuru1).set({ username: name1, email: email1, profile_picture : imageUrl1 }); } &lt;/script&gt; </code></pre> <p>and the out is like this</p> <pre><code>{ "duyuru1": { "email": "kjfdlkl", "profile_picture": "dsfsd", "username": "meraha" } } </code></pre> <p>I want to output data like;</p> <pre><code>{ "duyuru1": { "email": "kjfdlkl", "profile_picture": "dsfsd", "username": "meraha" }, "duyuru2": { "email": "kjfdlkl", "profile_picture": "dsfsd", "username": "meraha" } } </code></pre> <p>duyuru (child value) section should be auto increment, That's what i wanted for. Thank you for your answers</p>
39,065,899
5
0
null
2016-08-21 15:19:30.057 UTC
5
2020-08-25 15:22:57.047 UTC
2016-08-21 15:27:16.593 UTC
null
209,103
null
3,527,111
null
1
16
javascript|firebase|firebase-realtime-database|auto-increment
48,868
<p>Firebase has no auto-incrementing keys, since those don't work well in massively multi-user systems where clients can be offline for prolonged periods.</p> <p>Instead, Firebase has its own type of auto-generated keys called push IDs. These push IDs have the same important properties of sequences in many relational databases: they are ordered and sequential. But in addition, they can be calculated client-side, even when the client is not connected to the Firebase servers.</p> <p>See the <a href="https://firebase.google.com/docs/database/web/lists-of-data" rel="noreferrer">Firebase documentation on saving data in lists</a>, this legacy <a href="https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html" rel="noreferrer">blog post on why arrays don't work well in Firebase</a> and this <a href="https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html" rel="noreferrer">post on how push ids work</a>.</p>
67,631,879
Nuxtjs vuetify throwing lots of `Using / for division is deprecated and will be removed in Dart Sass 2.0.0.`
<p>Nuxtjs using vuetify throwing lots of error <code>Using / for division is deprecated and will be removed in Dart Sass 2.0.0.</code> during yarn dev</p> <p>Nuxtjs: v2.15.6 @nuxtjs/vuetify&quot;: &quot;1.11.3&quot;, &quot;sass&quot;: &quot;1.32.8&quot;, &quot;sass-loader&quot;: &quot;10.2.0&quot;,</p> <p>Anyone know how to fix it ?</p> <pre><code>: Using / for division is deprecated and will be removed in Dart Sass 2.0.0. Recommendation: math.div($grid-gutter, 3) More info and automated migrator: https://sass-lang.com/d/slash-div ╷ 63 │ 'md': $grid-gutter / 3, │ ^^^^^^^^^^^^^^^^ ╵ node_modules/vuetify/src/styles/settings/_variables.scss 63:11 @import node_modules/vuetify/src/styles/settings/_index.sass 1:9 @import node_modules/vuetify/src/styles/styles.sass 2:9 @import node_modules/vuetify/src/components/VIcon/_variables.scss 1:9 @import node_modules/vuetify/src/components/VIcon/VIcon.sass 2:9 root stylesheet : Using / for division is deprecated and will be removed in Dart Sass 2.0.0. Recommendation: math.div($grid-gutter * 2, 3) More info and automated migrator: https://sass-lang.com/d/slash-div ╷ 64 │ 'lg': $grid-gutter * 2/3, │ ^^^^^^^^^^^^^^^^^^ ╵ node_modules/vuetify/src/styles/settings/_variables.scss 64:11 @import node_modules/vuetify/src/styles/settings/_index.sass 1:9 @import node_modules/vuetify/src/styles/styles.sass 2:9 @import node_modules/vuetify/src/components/VIcon/_variables.scss 1:9 @import node_modules/vuetify/src/components/VIcon/VIcon.sass 2:9 root stylesheet </code></pre> <pre><code>&quot;dependencies&quot;: { &quot;@nuxtjs/apollo&quot;: &quot;^4.0.1-rc.5&quot;, &quot;@nuxtjs/auth-next&quot;: &quot;5.0.0-1617968180.f699074&quot;, &quot;@nuxtjs/axios&quot;: &quot;^5.4.1&quot;, &quot;@nuxtjs/gtm&quot;: &quot;^2.3.0&quot;, &quot;axios-extensions&quot;: &quot;^3.0.6&quot;, &quot;global&quot;: &quot;^4.4.0&quot;, &quot;googleapis&quot;: &quot;^71.0.0&quot;, &quot;graphql-tag&quot;: &quot;^2.10.3&quot;, &quot;jszip&quot;: &quot;^3.2.1&quot;, &quot;jwt-decode&quot;: &quot;^3.1.2&quot;, &quot;leaflet&quot;: &quot;1.6.0&quot;, &quot;leaflet-draw&quot;: &quot;^1.0.4&quot;, &quot;leaflet-editablecirclemarker&quot;: &quot;^1.0.4&quot;, &quot;leaflet-geosearch&quot;: &quot;2.5.1&quot;, &quot;leaflet.gridlayer.googlemutant&quot;: &quot;0.9.0&quot;, &quot;leaflet.heat&quot;: &quot;^0.2.0&quot;, &quot;lodash&quot;: &quot;^4.17.15&quot;, &quot;lodash-webpack-plugin&quot;: &quot;^0.11.5&quot;, &quot;lru-cache&quot;: &quot;^6.0.0&quot;, &quot;multi-download&quot;: &quot;^3.0.0&quot;, &quot;nuxt&quot;: &quot;^2.6.3&quot;, &quot;nuxt-i18n&quot;: &quot;^6.20.1&quot;, &quot;nuxt-leaflet&quot;: &quot;^0.0.21&quot;, &quot;reiko-parser&quot;: &quot;^1.0.8&quot;, &quot;sass&quot;: &quot;1.32.8&quot;, &quot;sass-loader&quot;: &quot;10.2.0&quot;, &quot;sortablejs&quot;: &quot;1.13.0&quot;, &quot;style&quot;: &quot;^0.0.3&quot;, &quot;style-loader&quot;: &quot;^2.0.0&quot;, &quot;svgo&quot;: &quot;^2.3.0&quot;, &quot;vue&quot;: &quot;^2.6.6&quot;, &quot;vue-mqtt&quot;: &quot;^2.0.3&quot;, &quot;vue-recaptcha&quot;: &quot;^1.1.1&quot;, &quot;vue-upload-component&quot;: &quot;^2.8.19&quot;, &quot;vuedraggable&quot;: &quot;willhoyle/Vue.Draggable&quot; }, &quot;devDependencies&quot;: { &quot;@aceforth/nuxt-optimized-images&quot;: &quot;^1.0.1&quot;, &quot;@babel/preset-env&quot;: &quot;^7.13.15&quot;, &quot;@babel/runtime-corejs3&quot;: &quot;^7.13.10&quot;, &quot;@mdi/font&quot;: &quot;^5.9.55&quot;, &quot;@nuxtjs/eslint-config&quot;: &quot;^6.0.0&quot;, &quot;@nuxtjs/vuetify&quot;: &quot;^1.11.3&quot;, &quot;@storybook/addon-essentials&quot;: &quot;^6.2.8&quot;, &quot;@storybook/vue&quot;: &quot;^6.2&quot;, &quot;@vue/cli-plugin-eslint&quot;: &quot;^4.5.12&quot;, &quot;babel-core&quot;: &quot;^6.26.3&quot;, &quot;babel-eslint&quot;: &quot;^10.0.1&quot;, &quot;babel-loader&quot;: &quot;^8.0.6&quot;, &quot;babel-plugin-lodash&quot;: &quot;^3.3.4&quot;, &quot;babel-plugin-transform-pug-html&quot;: &quot;^0.1.3&quot;, &quot;babel-plugin-transform-runtime&quot;: &quot;^6.23.0&quot;, &quot;babel-polyfill&quot;: &quot;^6.26.0&quot;, &quot;babel-preset-vue&quot;: &quot;^2.0.2&quot;, &quot;core-js&quot;: &quot;3&quot;, &quot;css-loader&quot;: &quot;^5.2.1&quot;, &quot;eslint&quot;: &quot;^7.24.0&quot;, &quot;eslint-config-prettier&quot;: &quot;^8.2.0&quot;, &quot;eslint-config-standard&quot;: &quot;^16.0.2&quot;, &quot;eslint-loader&quot;: &quot;^4.0.2&quot;, &quot;eslint-plugin-html&quot;: &quot;^6.1.2&quot;, &quot;eslint-plugin-import&quot;: &quot;^2.16.0&quot;, &quot;eslint-plugin-node&quot;: &quot;^11.1.0&quot;, &quot;eslint-plugin-prettier&quot;: &quot;^3.4.0&quot;, &quot;eslint-plugin-promise&quot;: &quot;^5.1.0&quot;, &quot;eslint-plugin-standard&quot;: &quot;^5.0.0&quot;, &quot;eslint-plugin-vue&quot;: &quot;^7.9.0&quot;, &quot;googleapis&quot;: &quot;^71.0.0&quot;, &quot;image-webpack-loader&quot;: &quot;^7.0.1&quot;, &quot;imagemin-mozjpeg&quot;: &quot;^9.0.0&quot;, &quot;imagemin-pngquant&quot;: &quot;^9.0.2&quot;, &quot;minify-css-string&quot;: &quot;^1.0.0&quot;, &quot;plop&quot;: &quot;^2.4.0&quot;, &quot;prettier&quot;: &quot;^2.2.1&quot;, &quot;sass-migrator&quot;: &quot;^1.3.9&quot;, &quot;storybook&quot;: &quot;^6.2.8&quot;, &quot;storybook-readme&quot;: &quot;^5.0.9&quot;, &quot;stylus&quot;: &quot;^0.54.8&quot;, &quot;stylus-loader&quot;: &quot;^4.0.0&quot;, &quot;vue-loader&quot;: &quot;^15.9.6&quot;, &quot;vue-recaptcha&quot;: &quot;^1.1.1&quot;, &quot;vue-template-compiler&quot;: &quot;^2.6.6&quot;, &quot;vue2-leaflet&quot;: &quot;2.5.2&quot;, &quot;vue2-leaflet-editablecirclemarker&quot;: &quot;^1.0.5&quot;, &quot;vue2-leaflet-geosearch&quot;: &quot;1.0.6&quot;, &quot;vue2-leaflet-googlemutant&quot;: &quot;^2.0.0&quot;, &quot;vue2-leaflet-markercluster&quot;: &quot;^3.1.0&quot;, &quot;vuetify-loader&quot;: &quot;^1.7.2&quot; }, &quot;browserslist&quot;: { &quot;production&quot;: [ &quot;&gt;0.2%&quot;, &quot;not dead&quot;, &quot;not op_mini all&quot;, &quot;ie 11&quot; ] } } </code></pre>
67,654,524
9
1
null
2021-05-21 06:33:30.807 UTC
6
2022-02-16 12:41:26.743 UTC
null
null
null
null
11,413,740
null
1
91
sass|vuetify.js|nuxtjs
28,212
<h1>Quick fix</h1> <p>Change your sass version to use the tilde <code>~</code> and it should work. This is because it will prohibit updated minor versions from being used, and allow only patches.</p> <p>Example package.json line:</p> <pre><code>&quot;sass&quot;: &quot;~1.32.6&quot; </code></pre> <p>See <a href="https://nodesource.com/blog/semver-tilde-and-caret/" rel="noreferrer">https://nodesource.com/blog/semver-tilde-and-caret/</a></p> <h1>Future-compatible fix</h1> <p>For those of you who want to refactor your use of <code>/</code>, you need to get the <a href="https://www.npmjs.com/package/@nuxtjs/style-resources" rel="noreferrer">style-resources module</a>. With it, once adding <code>'@nuxtjs/style-resources'</code> to your Nuxt config <code>buildModules</code>, you can set <code>hoistUseStatements: true</code> in a <code>styleResources</code> property in the config. This will allow you to <code>@use 'sass:math';</code> in your style block where you will change <code>a/b</code> to <code>math.div(a, b)</code></p>
2,575,837
Unit testing framework for a Swing UI
<p>Testing UI is difficult. What do you think is the best unit testing framework for Swing?</p>
2,579,631
3
0
null
2010-04-04 20:50:38.997 UTC
11
2010-11-02 23:50:38.603 UTC
null
null
null
null
27,198
null
1
18
java|unit-testing|swing
4,716
<p>Currently the best in my opinion is <a href="http://docs.codehaus.org/display/FEST/Home" rel="noreferrer">FEST</a>.</p>
2,555,363
Deserializing JSON into an object with Json.NET
<p>I'm playing a little bit with the new <a href="https://blog.stackoverflow.com/2010/03/stack-overflow-api-private-beta-starts/">StackOverflow API</a>. Unfortunately, my JSON is a bit weak, so I need some help.</p> <p>I'm trying to deserialize this JSON of a User:</p> <pre><code> {&quot;user&quot;:{ &quot;user_id&quot;: 1, &quot;user_type&quot;: &quot;moderator&quot;, &quot;creation_date&quot;: 1217514151, &quot;display_name&quot;: &quot;Jeff Atwood&quot;, ... &quot;accept_rate&quot;: 100 }} </code></pre> <p>into an object which I've decorated with <code>JsonProperty</code> attributes:</p> <pre><code>[JsonObject(MemberSerialization.OptIn)] public class User { [JsonProperty(&quot;user_id&quot;, Required = Required.Always)] public virtual long UserId { get; set; } [JsonProperty(&quot;display_name&quot;, Required = Required.Always)] public virtual string Name { get; set; } ... } </code></pre> <p>I get the following exception:</p> <blockquote> <p>Newtonsoft.Json.JsonSerializationException: Required property 'user_id' not found in JSON.</p> </blockquote> <p>Is this because the JSON object is an array? If so, how can I deserialize it to the one User object?</p> <p>Thanks in advance!</p>
2,555,871
3
1
null
2010-03-31 18:15:02.993 UTC
6
2013-01-25 17:47:45.637 UTC
2021-01-18 12:38:11.483 UTC
null
-1
null
8,205
null
1
25
c#|.net|json|serialization|json.net
52,968
<p>As Alexandre Jasmin said in the comments of your question, the resulting JSON has a wrapper around the actual <code>User</code> object you're trying to deserialize.</p> <p>A work-around would be having said wrapper class:</p> <pre><code>public class UserResults { public User user { get; set; } } </code></pre> <p>Then the deserialization will work:</p> <pre><code>using (var sr = new StringReader(json)) using (var jr = new JsonTextReader(sr)) { var js = new JsonSerializer(); var u = js.Deserialize&lt;UserResults&gt;(jr); Console.WriteLine(u.user.display_name); } </code></pre> <p>There will be future metadata properties on this wrapper, e.g. response timestamp, so it's not a bad idea to use it!</p>