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
27,474,907
Why would a call to fmt.Sprint(e) inside the Error() method result in an infinite loop?
<p>I am going through <a href="https://tour.golang.org/methods/20" rel="noreferrer">"A Tour of Go"</a> tutorial.</p> <p>I would like to check the answer to this question:</p> <blockquote> <p><strong>Note:</strong> a call to <code>fmt.Sprint(e)</code> inside the <code>Error</code> method will send the program into an infinite loop. You can avoid this by converting <code>e</code> first: <code>fmt.Sprint(float64(e))</code>. Why?</p> </blockquote> <p><br> I believe this is because when the <code>Sprint</code> function is called, since the error is non-nil, the <code>Error function()</code> will again be called, and so forth, resulting in an infinite loop. </p>
27,475,316
2
1
null
2014-12-14 22:32:04.733 UTC
16
2020-12-14 04:26:19.213 UTC
2019-08-28 21:02:45.467 UTC
null
814,702
null
2,457,967
null
1
68
go
7,334
<p><code>fmt.Sprint(e)</code> will call <code>e.Error()</code> to convert the value <code>e</code> to a <code>string</code>. If the <code>Error()</code> method calls <code>fmt.Sprint(e)</code>, then the program recurses until out of memory.</p> <p>You can break the recursion by converting the <code>e</code> to a value without a <code>String</code> or <code>Error</code> method.</p>
9,623,334
iOS: how to reduce size of large PNG files
<p>I'm currently optimizing my iOS app for <em>the new iPad</em>. Unfortunately by adding launch images for the iPad retina display the size of my <em>ipa</em> grows from 1.2MB to 5.5MB, mainly because of the two PNG images in 1536 x 2008 (portrait) and 2048 x 1496 (landscape). The size of these images are respectivly 1.9MB and 1.7MB.</p> <p>The portrait can be seen here: <a href="http://uploads.demaweb.dk/iPadPortrait.png">http://uploads.demaweb.dk/iPadPortrait.png</a>.</p> <p>As you may notice, the background is a fixed pattern but sadly it seems that this is not very compressible. I've further tried to compress the images using <a href="http://imageoptim.com/">ImageOptim</a>, but it does not make any difference after Xcode has compressed the images during the archive. Searching the web I've noticed, that some people are dissuading to turn off PNG compressing in Xcode.</p> <p>Are there anything I can do? It is not a solution to change the pattern in the image to a solid color, as it should look like the background in my iOS view. But it seems odd, that supporting <em>the new iPad</em> increase the size by ~4MB.</p>
9,623,449
3
0
null
2012-03-08 19:04:40.35 UTC
10
2013-11-24 10:21:40.25 UTC
null
null
null
null
617,413
null
1
9
objective-c|cocoa-touch|ipad|ios5|png
11,042
<p>Ive struggled with this too, unfortunately not much can be done. </p> <blockquote> <p>In an effort to dramatically increase drawing performance of iOS apps, Xcode re-compresses PNG files as it builds. It premultiplies the alpha channel and byte swaps the red, green and blue channels to be sequenced blue, green and red. The result is optimised for iOS’s purpose, but as a side effect, ImageOptim’s work gets undone…</p> </blockquote> <p><a href="http://bjango.com/articles/pngcompression/">Source</a></p>
9,177,814
KnockoutJS if statement inside foreach loop
<p>Here I have this code:</p> <pre><code>&lt;tbody data-bind="foreach: entries"&gt; &lt;tr&gt; &lt;td&gt;&lt;i class="icon-file"&gt;&lt;/i&gt; &lt;a href="#" data-bind="text: name, click: $parent.goToPath"&gt;&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>I would like to have something like this (it's pseudocode):</p> <pre><code>&lt;tbody data-bind="foreach: entries"&gt; &lt;tr&gt; &lt;td&gt;&lt;i class="{{ if type == 'file' }} icon-file {{/if}}{{else}} icon-folder {{/else}}"&gt;&lt;/i&gt; &lt;a href="#" data-bind="text: name, click: {{ if type == 'file' }} $parent.showFile {{/if}}{{else}} $parent.goToPath {{/else}}"&gt;&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>Is it possible to write something like this on KnockoutJS?</p>
9,178,123
2
0
null
2012-02-07 14:16:22.367 UTC
5
2012-02-07 14:42:36.48 UTC
null
null
null
null
331,000
null
1
28
knockout.js
41,702
<p>One option is to do something like:</p> <pre><code>&lt;tbody data-bind="foreach: entries"&gt; &lt;tr&gt; &lt;td&gt; &lt;!-- ko if: type === 'file' --&gt; &lt;i class="icon-file"&gt;&lt;/i&gt; &lt;a href="#" data-bind="text: name, click: $parent.showFile"&gt;&lt;/a&gt; &lt;!-- /ko --&gt; &lt;!-- ko if: type !== 'file' --&gt; &lt;i class="icon-folder"&gt;&lt;/i&gt; &lt;a href="#" data-bind="text: name, click: $parent.goToPath"&gt;&lt;/a&gt; &lt;!-- /ko --&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>Sample here: <a href="http://jsfiddle.net/rniemeyer/9DHHh/" rel="noreferrer">http://jsfiddle.net/rniemeyer/9DHHh/</a></p> <p>Otherwise, you can simplify your view by moving some logic into your view model like:</p> <pre><code>&lt;tbody data-bind="foreach: entries"&gt; &lt;tr&gt; &lt;td&gt; &lt;i data-bind="attr: { 'class': $parent.getClass($data) }"&gt;&lt;/i&gt; &lt;a href="#" data-bind="text: name, click: $parent.getHandler($data)"&gt;&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>Then, add methods on your view model to return the appropriate value:</p> <pre><code>var ViewModel = function() { var self = this; this.entries = [ { name: "one", type: 'file' }, { name: "two", type: 'folder' }, { name: "three", type: 'file'} ]; this.getHandler = function(entry) { console.log(entry); return entry.type === 'file' ? self.showFile : self.goToPath; }; this.getClass = function(entry) { return entry.type === 'file' ? 'icon-file' : 'icon-filder'; }; this.showFile = function(file) { alert("show file: " + file.name); }; this.goToPath = function(path) { alert("go to path: " + path.name); }; }; </code></pre> <p>Sample here: <a href="http://jsfiddle.net/rniemeyer/9DHHh/1/" rel="noreferrer">http://jsfiddle.net/rniemeyer/9DHHh/1/</a></p>
9,227,014
Convert PDF to JPEG with PHP and ImageMagick
<p>I'm using a litte script to convert PDF to JPG. That works but the quality is very poor.</p> <p>The script:</p> <pre><code>$im = new imagick( 'document.pdf[ 0]' ); $im-&gt;setImageColorspace(255); $im-&gt;setResolution(300, 300); $im-&gt;setCompressionQuality(95); $im-&gt;setImageFormat('jpeg'); $im-&gt;writeImage('thumb.jpg'); $im-&gt;clear(); $im-&gt;destroy(); </code></pre> <p>One more thing, I want to keep the original size of the PDF but the conversion crops the size of the JPG.</p>
12,407,686
6
0
null
2012-02-10 11:23:00.073 UTC
13
2022-04-05 13:19:26.153 UTC
2012-09-18 13:45:45.843 UTC
null
359,307
null
1,010,865
null
1
32
php|pdf|imagemagick|jpeg
93,848
<p>It can be done using <code>setResolution</code>, but you need to do it before loading an image. Try something like this:</p> <pre><code>// instantiate Imagick $im = new Imagick(); $im-&gt;setResolution(300,300); $im-&gt;readimage('document.pdf[0]'); $im-&gt;setImageFormat('jpeg'); $im-&gt;writeImage('thumb.jpg'); $im-&gt;clear(); $im-&gt;destroy(); </code></pre>
9,456,419
Easy way to suppress output of fabric run?
<p>I am running a command on the remote machine:</p> <pre class="lang-py prettyprint-override"><code>remote_output = run('mysqldump --no-data --user=username --password={0} database'.format(password)) </code></pre> <p>I would like to capture the output, but not have it all printed to the screen. What's the easiest way to do this?</p>
9,621,835
5
0
null
2012-02-26 19:32:33.82 UTC
4
2022-01-01 23:33:13.753 UTC
2012-03-08 20:39:58.337 UTC
null
631,612
null
64,421
null
1
33
python|fabric
32,997
<p>It sounds like <a href="http://docs.fabfile.org/en/1.4.0/usage/output_controls.html" rel="noreferrer">Managing output</a> section is what you're looking for.</p> <p>To hide the output from the console, try something like this:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import with_statement from fabric.api import hide, run, get with hide('output'): run('mysqldump --no-data test | tee test.create_table') get('~/test.create_table', '~/test.create_table') </code></pre> <p>Belows is the sample results:</p> <pre><code>No hosts found. Please specify (single) host string for connection: 192.168.6.142 [192.168.6.142] run: mysqldump --no-data test | tee test.create_table [192.168.6.142] download: /home/quanta/test.create_table &lt;- /home/quanta/test.create_table </code></pre>
34,071,875
Replace a value NA with the value from another column in R
<p>I want to replace the NA value in dfABy from the column A, with the value from the column B, based on the year of column year. For example, my df is: </p> <pre><code> &gt;dfABy A B Year 56 75 1921 NA 45 1921 NA 77 1922 67 41 1923 NA 65 1923 </code></pre> <p>The result what I will attend is: </p> <pre><code> &gt; dfABy A B Year 56 75 1921 *45* 45 1921 *77* 77 1922 67 41 1923 *65* 65 1923 </code></pre> <p>P.S: with the * the value replacing in column A from column B for every year </p>
34,073,008
5
1
null
2015-12-03 16:59:16.017 UTC
14
2020-12-18 19:23:45.787 UTC
2018-09-03 13:35:41.363 UTC
null
4,752,675
null
5,595,661
null
1
28
r|replace|na
48,978
<p>Perhaps the easiest to read/understand answer in R lexicon is to use ifelse. So borrowing Richard's dataframe we could do:</p> <pre><code>df &lt;- structure(list(A = c(56L, NA, NA, 67L, NA), B = c(75L, 45L, 77L, 41L, 65L), Year = c(1921L, 1921L, 1922L, 1923L, 1923L)),.Names = c("A", "B", "Year"), class = "data.frame", row.names = c(NA, -5L)) df$A &lt;- ifelse(is.na(df$A), df$B, df$A) </code></pre>
10,284,004
Minimal Cover and functional dependencies
<p>Given the following functional dependencies how would I compute the minimal cover:</p> <p><code>A -&gt; B, ABCD -&gt; E, EF -&gt; GH, ACDF -&gt; EG</code></p> <p>In the lecture notes it gives the derivation for the minimal cover but I do not understand it.</p> <p>For example for getting rid of <strong>ACDF -> E</strong>:</p> <p><code>A -&gt; B =&gt; AACD -&gt; BACD -&gt; E =&gt; ACD -&gt; E =&gt; ACDF -&gt; E</code></p> <p>And then they say, similarly we do not keep <strong>ACDF -> G</strong></p> <p>And then I understand that <strong>ABCD -> E</strong> is deduced to <strong>ACD -> E</strong> because <strong>A -> B</strong>, but I do not understand the formal process of how to get to that.</p> <p>So my question is, can anyone provide an explanation of how to generate the minimal cover for a set functional dependencies? </p>
10,284,538
2
1
null
2012-04-23 15:58:40.037 UTC
25
2018-11-19 09:53:55.623 UTC
2014-07-22 03:54:37.847 UTC
null
-1
null
503,901
null
1
32
database|functional-dependencies
80,694
<p>To get the minimal cover, you have to make two steps. To demonstrate, I'll first split the dependencies into multiple (only one attribute on the right side) to make it more clean:</p> <pre><code>A -&gt; B ABCD -&gt; E EF -&gt; G EF -&gt; H ACDF -&gt; E ACDF -&gt; G </code></pre> <p>The following steps <em>must</em> be done in this order (#1 and then #2), otherwise you can get incorrect result.</p> <p>1) get rid of redundant attributes (reduce left sides):</p> <p>Take each left side and try to remove one each attribute one at a time, then try to deduce the right side (which is now only one attribute for all dependencies). If you suceed you can then remove that letter from the left side, then continue. Note that there might be more than one correct result, it depends on the order in which you do the reduction.</p> <p>You will find out, that you can remove <code>B</code> from the dependency <code>ABCD -&gt; E</code>, because <code>ACD -&gt; ABCD</code> (use first dep.) and from <code>ABCD -&gt; E</code>. You can use the full dep. you are currently reducing, this is sometimes confusing at first, but if you think about it, it will become clear that you can do that.</p> <p>Similarly, you can remove <code>F</code> from <code>ACDF -&gt; E</code>, because <code>ACD -&gt; ABCD -&gt; ABCDE -&gt; E</code> (you can obviously deduce a single letter from the letter itself). After this step you get:</p> <pre><code>A -&gt; B ACD -&gt; E EF -&gt; G EF -&gt; H ACD -&gt; E ACDF -&gt; G </code></pre> <p>These rules still represent the same dependencies as the original. Note that now we have a duplicate rule <code>ACD -&gt; E</code>. If you look at the whole thing as a set (in the mathematical sense), then of course you can't have the same element twice in one set. For now, I'm just leaving it twice here, because the next step will get rid of it anyway.</p> <p>2) get rid of redundant dependencies</p> <p>Now for each rule, try to remove it, and see if you deduce the same rule by only using others. In this step you, of course, cannot use the dep. you're currently trying to remove (you could in the previous step).</p> <p>If you take the left side of the first rule <code>A -&gt; B</code>, hide it for now, you see you can't deduce anything from <code>A</code> alone. Therefore this rule is not redundant. Do the same for all others. You'll find out, that you can (obviously) remove one of the duplicate rules <code>ACD -&gt; E</code>, but strictly speaking, you can use the algorithm also. Hide only one of the two same rules, then take the left side (<code>ACD</code>), and use the other to deduce the right side. Therefore you can remove <code>ACD -&gt; E</code> (only once of course).</p> <p>You'll also see you can remove <code>ACDF -&gt; G</code>, because <code>ACDF -&gt; ACDFE -&gt; G</code>. Now the result is:</p> <pre><code>A -&gt; B EF -&gt; G EF -&gt; H ACD -&gt; E </code></pre> <p>Which is the minimal cover of the original set.</p>
10,673,503
Is it a bad practice to use negative margins in Android?
<h3>Demo of negative margin:</h3> <p>                         <a href="https://i.stack.imgur.com/Od3u5l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Od3u5l.png" alt="enter image description here" /></a></p> <h3>The scenario</h3> <p>Overlapping views by setting a negative margin to one of them so that it invades the bounding box of another view.</p> <h3>Thoughts</h3> <p>It seems to work the way you'd expect with overlapping of the layouts if they should. But I don't want to run into a bigger problem for unknowingly not doing things right. Emulators, physical devices, you name it, when you use negative margins everything seems to work correctly, one view invades another's views bounding box and depending on how it's declared in the layout it will be above or below the other view.</p> <p>I'm also aware that since API 21 we can set the <a href="http://developer.android.com/intl/es/reference/android/R.attr.html#translationZ" rel="noreferrer"><code>translationZ</code></a> and <a href="http://developer.android.com/intl/es/reference/android/R.attr.html#translationZ" rel="noreferrer"><code>elevation</code></a> attributes to make view appear above or below other views but <strong>my concern</strong> basically comes from the fact that <a href="http://developer.android.com/intl/es/reference/android/R.attr.html#layout_margin" rel="noreferrer">in the documentation</a> for the <code>layout_margin</code> attributes it's clearly specified that <strong>margin values should be positive</strong>, let me quote:</p> <blockquote> <p><strong>Excerpt:</strong><br/> <em>Specifies extra space on the left, top, right and bottom sides of this view. This space is outside this view's bounds. <strong>Margin values should be positive</strong>. Must be a dimension value, which is a floating point number appended with a unit such as &quot;14.5sp&quot;. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters)...</em></p> </blockquote> <p>In the years since originally asking this question I haven't had any issues with negative margins, did try to avoid using them as much as possible, but did <strong>not</strong> encounter any issues, so even though the documentation states that, I'm not too worried about it.</p>
10,673,572
8
1
null
2012-05-20 12:43:51.64 UTC
30
2022-08-12 13:59:24.683 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
363,262
null
1
135
android|android-layout|user-interface|overlap|margins
89,569
<p>In 2010, @RomainGuy (core Android engineer) stated that <a href="https://groups.google.com/group/android-developers/browse_thread/thread/daf7c7c42df78ed2" rel="nofollow noreferrer">negative margins had unspecified behavior</a>.</p> <p>In 2011, @RomainGuy stated that <a href="https://stackoverflow.com/a/5293636/115145">you can use negative margins on <code>LinearLayout</code> and <code>RelativeLayout</code></a>.</p> <p>In 2016, @RomainGuy stated that <a href="https://issuetracker.google.com/issues/37103660" rel="nofollow noreferrer">they have never been officially supported and won't be supported by <code>ConstraintLayout</code></a>.</p> <p>In December 2020(v2.1.0, official release June 2021), negative margin support for constraints <a href="https://developer.android.com/jetpack/androidx/releases/constraintlayout#constraintlayout-2.1.0-alpha2" rel="nofollow noreferrer">has been added to ConstraintLayout</a>.</p> <p>It is easy to work around this limitation though.</p> <p>Add a helper view (height 0dp, width constrained to parent) at the bottom of your base view, at the bottom add the margin you want.<br /> Then position your view below this one, effectively allowing it to have a &quot;negative&quot; margin but without having to use any unsupported negative value.</p>
22,604,934
HTML5 increase youtube speed 2x from url?
<p>I would like to know how to speed up a youtube video 2x without the user clicking on the HTML5 (of the video), but instead by modifying the URL.</p> <p>For example, I know how to watch video starting at a specific time by appending to the URL the parameter <code>&amp;t=1m1s</code> (for 1 minute and one second). <strong>Is it possible to use a similar method to speed up the video 2x?</strong></p> <p>What parameters should I add to the URL to watch video in double speed (I'm using html5)?</p>
25,283,118
3
2
null
2014-03-24 09:04:26 UTC
8
2019-09-08 17:08:31.237 UTC
2015-02-03 22:09:19.927 UTC
null
415,551
null
1,500,655
null
1
34
html|youtube|send
39,209
<p>There's no way to change playback speed by URL arguments.</p> <p>Anyway, if you're working with HTML, you can take advantage of the YouTube Player iFrame API.</p> <p>Here's how to configure your player with all the JavaScript: <a href="https://developers.google.com/youtube/iframe_api_reference#Getting_Started" rel="noreferrer">https://developers.google.com/youtube/iframe_api_reference#Getting_Started</a></p> <p>And here's the function you're looking for to set playback speed: <a href="https://developers.google.com/youtube/iframe_api_reference#Playback_rate" rel="noreferrer">https://developers.google.com/youtube/iframe_api_reference#Playback_rate</a></p> <p>So you can edit your onPlayerReady function like this:</p> <pre><code>function onPlayerReady(event) { player.setPlaybackRate(2); // This is what you're looking for event.target.playVideo(); } </code></pre> <p>You can of course pass on step 5 of the documentation as this will stop your video from playing after six seconds.</p> <p>If you have trouble setting that up, I'll edit a JSFiddle later (couldn't do it at work as my Flash plugin won't launch).</p> <h2><strong>Update :</strong></h2> <p>Here's the JSFiddle working fine with this code exactly: <a href="http://jsfiddle.net/jpreynat/e11oy0eu/" rel="noreferrer">http://jsfiddle.net/jpreynat/e11oy0eu/</a></p>
22,452,930
Terminating a Java Program
<p>I found out ways to terminate (shut-down or stop) my Java programs. I found two solutions for it.</p> <ol> <li><p>using <strong>return;</strong><br/>When I want to quit or terminate my program execution , I add this.</p> </li> <li><p>using <strong>System.exit()</strong> ; <br> Sometimes I used it. I read about <strong>System.exit()</strong> from <a href="https://stackoverflow.com/questions/3715967/when-should-we-call-system-exit-in-java">this question</a>.</p> </li> </ol> <p>So, I know a little on both them. But I am still confused as to how they actually work. Please check below codes...<br/></p> <pre><code>public class Testing { public static void main(String... str) { System.out.println(1); System.exit(0); System.out.println(2); return; } } </code></pre> <p>I am sure that <strong>2</strong> will not appear. I would like to know is why <code>return;</code> or other codes can write below the statement of <code>System.exit(0);</code> and what was real definition for <code>return;</code> (<em>because it is strange thing for me <code>return</code> without any variables or values</em>) ?</p>
22,453,082
7
2
null
2014-03-17 11:19:04.167 UTC
33
2021-08-08 13:45:32.347 UTC
2021-08-08 13:45:32.347 UTC
null
-1
null
1,531,064
null
1
92
java
560,954
<p>Calling <code>System.exit(0)</code> (or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the <code>java</code> process will return to the operating system. You can make this call from anywhere in your program - and the result will always be the same - JVM terminates. As this is simply calling a static method in <code>System</code> class, the compiler does not know what it will do - and hence does not complain about unreachable code.</p> <p><code>return</code> statement simply aborts execution of the current method. It literally means <em>return the control to the calling method</em>. If the method is declared as <code>void</code> (as in your example), then you do not need to specify a value, as you'd need to return <code>void</code>. If the method is declared to return a particular type, then you must specify the value to return - and this value must be of the specified type.</p> <p><code>return</code> would cause the program to exit only if it's inside the <code>main</code> method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:</p> <pre><code>public static void main(String... str) { System.out.println(1); return; System.out.println(2); System.exit(0); } </code></pre> <p>will not compile with most compiler - producing <code>unreachable code</code> error pointing to the second <code>System.out.println</code> call.</p>
57,875,550
How to detect live changes on TextField in SwiftUI?
<p>I have a simple TextField that binds to the state 'location' like this,</p> <pre><code>TextField("Search Location", text: $location) </code></pre> <p>I want to call a function each time this field changes, something like this:</p> <pre><code>TextField("Search Location", text: $location) { self.autocomplete(location) } </code></pre> <p>However this doesn't work. I know that there are callbacks, onEditingChanged - however this only seems to be triggered when the field is focussed.</p> <p>How can I get this function to call each time the field is updated?</p>
57,875,903
6
0
null
2019-09-10 17:16:11.833 UTC
18
2022-09-13 21:07:09.47 UTC
2020-02-25 12:55:21.07 UTC
null
4,546,390
null
4,184,982
null
1
82
ios|textfield|swiftui
49,846
<p>You can create a binding with a custom closure, like this:</p> <pre class="lang-swift prettyprint-override"><code>struct ContentView: View { @State var location: String = "" var body: some View { let binding = Binding&lt;String&gt;(get: { self.location }, set: { self.location = $0 // do whatever you want here }) return VStack { Text("Current location: \(location)") TextField("Search Location", text: binding) } } } </code></pre>
23,401,701
Asp.net MVC Ajax call not calling controller method
<p>I am making an ASP.net MVC application And I would like it so when a user clicks on a link it performs an ajax call sending data to the controller and then returning other data back to the view. </p> <p>This is the method I would like to call in my controller:</p> <pre><code>public JsonResult GetImage(string url) { Image image = Image.FromFile(url, true); byte[] byteImage = converter.ImageToBytes(image); return Json(new { byteImage }, JsonRequestBehavior.AllowGet); } </code></pre> <p>And here is the controllers location:</p> <pre><code>08983ClassLibrary\EpostASP\Controllers\CustomerController.cs </code></pre> <p>This is my Ajax Call:</p> <pre><code>$.ajax({ url: "~/Controllers/CustomerController/GetImage/", type: 'POST', contentType: 'application/json', data: "url="+url, success: function (image) { document.getElementById("image").src = "data:image/png;base64," + image; showImage(); } }); </code></pre> <p>When i place my breakpoints in the code I can see it hitting the ajax call then stepping over it never reaches the controller and doesnt give any errors. Any ideas?</p>
23,402,008
8
1
null
2014-05-01 03:45:33.48 UTC
1
2019-10-05 07:17:27.177 UTC
null
null
null
null
1,379,704
null
1
5
c#|jquery|asp.net|ajax|asp.net-mvc
55,170
<p>The main issue is here - </p> <pre><code>url: "~/Controllers/CustomerController/GetImage/", </code></pre> <p>You see, <code>~</code> is a server side literal, in other words, when you use this in a ASP.net server side path, it is replaced by the current server application folder location. This was the traditional ASP.Net way. This line has 2 errors - </p> <ol> <li><p>This url will never work. Because its inside a string in JS and thus ASP.net does not know that it has to replace it with server path. Now comes the second error, even if ASP.net could detect and convert it, it will still not work. Because of the point I described at 2 - </p></li> <li><p>Since you are using ASP.net MVC, it's not a good practice. The more conventional MVC way is to create routes and use those routes. Because in ASP.net you have the option to link to a page (.aspx, .ascx) directly. But MVC controller actions cannot be linked like that. So you have to create routes in your route config (check <code>Global.asax</code>) and then use that route as the url in here. BY default MVC apps will support the following format - </p> <p><code>&lt;host&gt;/{controller}/action</code></p> <p>example - </p> <pre><code>'localhost/Home/Index` </code></pre></li> </ol> <p>Notice that I didn't write <code>HomeController</code>, because by default controllers are supposed to ignore the trailing string <code>Controller</code>.</p> <p>I hope this helped and just incase you are looking for a solution for your current situation try this (I haven't tested but it should be like this) - </p> <pre><code> $.ajax({ url: "Customer/GetImage", type: 'POST', contentType: 'application/json', data: "url="+url, success: function (image) { document.getElementById("image").src = "data:image/png;base64," + image; showImage(); } }); </code></pre> <p>but to be on the safe side, make sure you use - </p> <pre><code>[HttpPost] public JsonResult GetImage(string url) { } </code></pre> <p>UPDATE: the maproute (as requested in comment ) will work with any of these routes. But can also work with different routes config. Route config is very very flexible, it is just a matter to setup the routes the way it works for you. - </p> <pre><code> public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( "...", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); routes.MapRoute( "...", // Route name "{controller}/{action}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); routes.MapRoute( "...", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Customer", action = "GetImage", id = "" } // Parameter defaults ); routes.MapRoute( "...", // Route name "Customer/GetImage/{id}", // URL with parameters new { controller = "Customer", action = "GetImage", id = "" } // Parameter defaults ); ..... //all of these mentioned route will land on the same url } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); } </code></pre>
32,024,954
Cache.properties (The system cannot find the file specified)
<p>I just started using Android Studio 1.3 sdk 24 and it has worked fine until today. I get this error message about cache.properties and I delete that cache file but now I am getting this error message: </p> <blockquote> <p>Error:C:\Users\user1.gradle\caches\2.4\scripts\asLocalRepo15_dhjxrnvsgiyg1ow3dfj4myl7\InitScript\initscript\cache.properties (The system cannot find the file specified) </p> </blockquote> <p>I try file/invalidate caches/restart.. and rebuild project but am still getting this error message. How do I fix it?</p>
32,413,965
16
1
null
2015-08-15 12:59:37.937 UTC
8
2018-10-25 07:42:39.713 UTC
2016-07-15 14:45:47.133 UTC
null
3,830,876
null
1,718,042
null
1
57
android|android-studio
53,490
<p>You don't have to delete all <code>.gradle</code> folders and no need to reinstall Android Studio.</p> <p>I have the latest version of Android Studio and I faced that problem, the only thing that worked for me is to:</p> <ol> <li><p>Navigate to <code>C:\Users\user\.gradle\caches\2.x\</code></p></li> <li><p>Copy the folder <strong>scripts</strong> , <strong>scripts-remapped</strong> and paste it somewhere safe just in case anything went wrong you will place it back</p></li> <li><p>Delete this folder <strong>scripts</strong> and <strong>scripts-remapped</strong> from the directory <code>C:\Users\user\.gradle\caches\2.x\</code></p></li> <li><p>Sync Project with Gradle Files and you are done.</p></li> </ol> <p><a href="https://i.stack.imgur.com/DUHEi.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/DUHEi.jpg" alt="enter image description here"></a></p> <p>When you sync your project Android Studio will generate new cache files.</p> <p>You also need to delete buildOutputCleanup.lock from projectLocation/.gradle/buildOutputCleanup in case the above 4 steps do not work out.</p> <p>It worked for me I hope it will work for you.</p>
18,928,164
Android studio cannot find aapt
<p>Hi I am having trouble compiling, I get this error:</p> <p>Gradle: Execution failed for task ':ElectronicComponentInventorySearch:mergeDebugResources'.</p> <blockquote> <p>java.io.IOException: Cannot run program "/opt/android-studio/sdk/build-tools/android- 4.2.2/aapt": error=2, No such file or directory</p> </blockquote> <p>When I use locate: /opt/android-studio/sdk/build-tools/android-4.2.2/aapt</p> <p>Before I tried anything I made sure to chown the whole android-studio directory to my account and set permissions for everything to 775.</p> <p>Whats up?</p>
18,930,424
5
1
null
2013-09-21 02:02:00.02 UTC
12
2016-10-15 22:00:27.927 UTC
2014-04-19 21:56:33.723 UTC
null
1,683,988
null
1,422,843
null
1
37
android-studio|32bit-64bit|aapt
21,931
<p>Aapt is a 32bit application. I am running ubuntu 64bit. I needed some additional libraries. First thing I did was update to 13.04 from 12.10. It broke chrome but <a href="http://www.omgchrome.com/install-google-chrome-in-ubuntu-13-10/" rel="noreferrer">this should help</a>.</p> <p>To get aapt working (this fixed my issues with the avd as well) just run these two commands:</p> <pre><code>sudo apt-get install lib32stdc++6 sudo apt-get install lib32z1 </code></pre> <p>From this <a href="https://askubuntu.com/questions/147400/problems-with-eclipse-and-android-sdk">post.</a></p> <p>Now no more problems.</p>
21,406,265
How to give System property to my test via Gradle and -D
<p>I have a a Java program which reads a System property</p> <pre><code>System.getProperty("cassandra.ip"); </code></pre> <p>and I have a Gradle build file that I start with </p> <pre><code>gradle test -Pcassandra.ip=192.168.33.13 </code></pre> <p>or </p> <pre><code>gradle test -Dcassandra.ip=192.168.33.13 </code></pre> <p>however <strong>System.getProperty</strong> will always return <strong>null</strong>.</p> <p>The only way I found was to add that in my Gradle build file via</p> <pre><code>test { systemProperty "cassandra.ip", "192.168.33.13" } </code></pre> <p>How Do I do it via -D</p>
21,406,600
6
2
null
2014-01-28 13:02:03.263 UTC
26
2021-07-05 18:03:31.06 UTC
2014-01-28 13:13:51.347 UTC
null
621,427
null
621,427
null
1
130
java|testing|gradle
85,820
<p>The -P flag is for gradle properties, and the -D flag is for JVM properties. Because the test may be forked in a new JVM, the -D argument passed to gradle will not be propagated to the test - it sounds like that is the behavior you are seeing.</p> <p>You can use the systemProperty in your <code>test</code> block as you have done but base it on the incoming gradle property by passing it with it -P:</p> <pre><code>test { systemProperty "cassandra.ip", project.getProperty("cassandra.ip") } </code></pre> <p>or alternatively, if you are passing it in via -D</p> <pre><code>test { systemProperty "cassandra.ip", System.getProperty("cassandra.ip") } </code></pre>
47,881,223
Running http-server in background from an npm script
<p>How do you start <code>http-server</code> in the background from an <strong>npm</strong> script so that another <strong>npm</strong> script, such as a <a href="https://github.com/dnajs/load-web-page-jsdom-mocha" rel="noreferrer">Mocha test using jsdom</a>, can make an HTTP request to <code>http-server</code>?</p> <p>The <code>http-server</code> package was installed with:</p> <pre><code>npm install http-server --save-dev </code></pre> <p>The <code>package.json</code> file contains:</p> <pre><code>&quot;scripts&quot;: { &quot;pretest&quot;: &quot;gulp build-httpdocs&quot;, &quot;test&quot;: &quot;http-server -p 7777 httpdocs/ &amp;&amp; mocha spec.js&quot; }, </code></pre> <p>Running <code>npm test</code> successfully starts the <code>http-server</code>, but of course the command hangs after showing:</p> <pre><code>Starting up http-server, serving httpdocs/ Available on: http://127.0.0.1:7777 http://192.168.1.64:7777 Hit CTRL-C to stop the server </code></pre> <p>Is there an easy way to start the web server so it does not block the Mocha tests?</p> <p><em>Bonus:</em> How do you shut down <code>http-server</code> after the Mocha tests have run?</p>
47,882,218
2
4
null
2017-12-19 06:32:51.243 UTC
4
2021-12-12 03:16:48.217 UTC
2021-12-12 03:16:48.217 UTC
null
1,553,812
null
1,553,812
null
1
31
javascript|node.js|npm|background-process|httpserver
18,438
<p>You can run a process in background by appending <code>&amp;</code> in the end. And then use the <code>postscript</code> hook that npm offers us, in order to kill the background process.</p> <pre><code>"scripts": { "web-server": "http-server -p 7777 httpdocs &amp;", "pretest": "gulp build-httpdocs &amp;&amp; npm run web-server", "test": "mocha spec.js", "posttest": "pkill -f http-server" } </code></pre> <p><strong>But what if I have multiple <code>http-server</code> running?</strong></p> <p>You can kill a process by specifying its port in the <code>posttest</code> script:</p> <pre><code> "posttest": "kill $(lsof -t -i:7777)" </code></pre> <p>Now for Windows, syntax is different and as far as I know npm doesn't support multiple OS scripts. For supporting multiple my best bet would be a gulp task that will handle each OS different.</p>
2,113,261
Using lock statement within a loop in C#
<p>Lets take the sample class SomeThread where we are attempting to prevent the DoSomething methods from being called after the Running property is set to false and Dispose is called by the OtherThread class because if they are called after the Dispose method is the world would end as we know it.</p> <p>It feels like there is a chance for something evil to happen because of the loop. That at the point where it starts the next loop and before the lock is taken before calling the DoSomething methods, Running could be changed to false, and Disposed called before it hits the lock. In this scenario life would not be good. </p> <p>I was looking at ways to handle this when using a loop in a simple easy to maintain method. For the record I did considered the Double Lock Check patterned, however it is does not seem to be recommend for C#. </p> <p><strong><em>Warning:</strong> This is a simplified example to try to make it easy to focus on the issue with the loop and locking within one. If I didn't elaborate enough some place please let me know and I will do my best to fill in any details.</em> </p> <pre><code>public class SomeThread : IDisposable { private object locker = new object(); private bool running = false; public bool Running { get { lock(locker) { return running; } } set { lock(locker) { running = value; } } } public void Run() { while (Running) { lock(locker) { DoSomething1(); DoSomething2(); } } } private void DoSomething1() { // something awesome happens here } private void DoSomething2() { // something more awesome happens here } public void Dispose() { lock (locker) { Dispose1(); Dispose2(); } } private void Dispose1() { // something awesome happens here } private void Dispose2() { // something more awesome happens here } } public class OtherThread { SomeThread st = new SomeThread(); public void OnQuit() { st.Running = false; st.Dispose(); Exit(); } } </code></pre>
2,118,236
3
1
null
2010-01-21 21:59:35.787 UTC
19
2017-05-09 21:59:09.743 UTC
null
null
null
null
196,020
null
1
15
c#|loops|multithreading|locking
16,725
<p>Take a step back.</p> <p>Start by specifying all the desirable and undesirable characteristics <em>before</em> you start to write a solution. A few that come immediately to mind:</p> <ul> <li>The "work" is done on thread W. The "UI" is done on thread U.</li> <li>The work is done in "units of work". Each unit of work is "short" in duration, for some definition of "short". Let's call the method that does the work M().</li> <li>The work is done continuously by W, in a loop, until U tells it to stop.</li> <li>U calls a cleanup method, D(), when all the work is done.</li> <li>D() must not ever run before or while M() is running.</li> <li>Exit() must be called after D(), on thread U. </li> <li>U must never block for a "long" time; it is acceptable for it to block for a "short" time.</li> <li>No deadlocks, and so on.</li> </ul> <p>Does this sum up the problem space? </p> <p>First off, I note that it <em>seems</em> at first glance that the problem is that U must be the caller of D(). If W were the caller of D(), then you wouldn't have to worry; you'd just signal W to break out of the loop, and then W would call D() after the loop. But that just trades one problem for another; presumably in this scenario, U must wait for W to call D() before U calls Exit(). So moving the call to D() from U to W doesn't actually make the problem easier.</p> <p>You've said that you don't want to use double-checked locking. You should be aware that as of CLR v2, the double-checked locking pattern is known to be safe. The memory model guarantees were strengthened in v2. So it is probably safe for you to use double-checked locking. </p> <p>UPDATE: You asked for information on (1) why is double-checked locking safe in v2 but not in v1? and (2) why did I use the weasel-word "probably"?</p> <p>To understand why double-checked locking is unsafe in the CLR v1 memory model but safe in the CLR v2 memory model, read this:</p> <p><a href="http://web.archive.org/web/20150326171404/https://msdn.microsoft.com/en-us/magazine/cc163715.aspx" rel="noreferrer">http://web.archive.org/web/20150326171404/https://msdn.microsoft.com/en-us/magazine/cc163715.aspx</a></p> <p>I said "probably" because as Joe Duffy wisely says:</p> <blockquote> <p>once you venture even slightly outside of the bounds of the few "blessed" lock-free practices [...] you are opening yourself up to the worst kind of race conditions.</p> </blockquote> <p>I do not know if you are planning on using double-checked locking correctly, or if you're planning on writing your own clever, broken variation on double-checked locking that in fact dies horribly on IA64 machines. Hence, it will <em>probably</em> work for you, if your problem is actually amenable to double checked locking <em>and</em> you write the code correctly.</p> <p>If you care about this you should read Joe Duffy's articles:</p> <p><a href="http://www.bluebytesoftware.com/blog/2006/01/26/BrokenVariantsOnDoublecheckedLocking.aspx" rel="noreferrer">http://www.bluebytesoftware.com/blog/2006/01/26/BrokenVariantsOnDoublecheckedLocking.aspx</a></p> <p>and</p> <p><a href="http://www.bluebytesoftware.com/blog/2007/02/19/RevisitedBrokenVariantsOnDoubleCheckedLocking.aspx" rel="noreferrer">http://www.bluebytesoftware.com/blog/2007/02/19/RevisitedBrokenVariantsOnDoubleCheckedLocking.aspx</a></p> <p>And this SO question has some good discussion:</p> <p><a href="https://stackoverflow.com/questions/1964731/the-need-for-volatile-modifier-in-double-checked-locking-in-net">The need for volatile modifier in double checked locking in .NET</a></p> <p>Probably it is best to find some other mechanism other than double-checked locking.</p> <p>There is a mechanism for waiting for one thread which is shutting down to complete -- thread.Join. You could join from the UI thread to the worker thread; when the worker thread is shut down, the UI thread wakes up again and does the dispose.</p> <p>UPDATE: Added some information on Join.</p> <p>"Join" basically means "thread U tells thread W to shut down, and U goes to sleep until that happens". Brief sketch of the quit method:</p> <pre><code>// do this in a thread-safe manner of your choosing running = false; // wait for worker thread to come to a halt workerThread.Join(); // Now we know that worker thread is done, so we can // clean up and exit Dispose(); Exit(); </code></pre> <p>Suppose you didn't want to use "Join" for some reason. (Perhaps the worker thread needs to keep running in order to do something else, but you still need to know when it is done using the objects.) We can build our own mechanism that works like Join by using wait handles. What you need now are <em>two</em> locking mechanisms: one that lets U send a signal to W that says "stop running now" and then another that <em>waits</em> while W finishes off the last call to M(). </p> <p>What I would do in this circumstance is: </p> <ul> <li>make a thread-safe flag "running". Use whatever mechanism you are comfortable with to make it thread safe. I would personally start with a lock dedicated to it; if you decide later that you can go with lock-free interlocked operations on it then you can always do that later.</li> <li>make an AutoResetEvent to act as a gate on the dispose. </li> </ul> <p>So, brief sketch:</p> <p>UI thread, startup logic:</p> <pre><code>running = true waithandle = new AutoResetEvent(false) start up worker thread </code></pre> <p>UI thread, quit logic:</p> <pre><code>running = false; // do this in a thread-safe manner of your choosing waithandle.WaitOne(); // WaitOne is robust in the face of race conditions; if the worker thread // calls Set *before* WaitOne is called, WaitOne will be a no-op. (However, // if there are *multiple* threads all trying to "wake up" a gate that is // waiting on WaitOne, the multiple wakeups will be lost. WaitOne is named // WaitOne because it WAITS for ONE wakeup. If you need to wait for multiple // wakeups, don't use WaitOne. Dispose(); waithandle.Close(); Exit(); </code></pre> <p>worker thread:</p> <pre><code>while(running) // make thread-safe access to "running" M(); waithandle.Set(); // Tell waiting UI thread it is safe to dispose </code></pre> <p>Notice that this relies on the fact that M() is short. If M() takes a long time then you can wait a long time to quit the application, which seems bad.</p> <p>Does that make sense?</p> <p>Really though, you shouldn't be doing this. If you want to wait for the worker thread to shut down before you dispose an object it is using, just join it. </p> <p>UPDATE: Some additional questions raised:</p> <blockquote> <p>is it a good idea to wait without a timeout?</p> </blockquote> <p>Indeed, note that in my example with Join and my example with WaitOne, I do not use the variants on them that wait for a specific amount of time before giving up. Rather, I call out that my assumption is that the worker thread shuts down cleanly and quickly. Is this the correct thing to do?</p> <p>It depends! It depends on just how badly the worker thread behaves and what it is doing when it is misbehaving.</p> <p>If you can guarantee that the work is short in duration, for whatever 'short' means to you, then you don't need a timeout. If you cannot guarantee that, then I would suggest first rewriting the code so that you <em>can</em> guarantee that; life becomes much easier if you know that the code will terminate quickly when you ask it to.</p> <p>If you cannot, then what's the right thing to do? The assumption of this scenario is that the worker is ill-behaved and does not terminate in a timely manner when asked to. So now we've got to ask ourselves "is the worker <em>slow by design</em>, <em>buggy</em>, or <em>hostile</em>?" </p> <p>In the first scenario, the worker is simply doing something that takes a long time and for whatever reason, cannot be interrupted. What's the right thing to do here? I have no idea. This is a terrible situation to be in. Presumably the worker is not shutting down quickly because doing so is dangerous or impossible. In that case, what are you going to do when the timeout times out??? You've got something that is dangerous or impossible to shut down, and its not shutting down in a timely manner. Your choices seem to be (1) do nothing, (2) do something dangerous, or (3) do something impossible. Choice three is probably out. Choice one is equivalent to waiting forever, whcih we've already rejected. That leaves "do something dangerous".</p> <p>Knowing what the right thing to do in order to minimize harm to user data depends upon the exact circumstances that are causing the danger; analyse it carefully, understand all the scenarios, and figure out the right thing to do.</p> <p>Now suppose the worker is supposed to be able to shut down quickly, but does not because it has a bug. Obviously, if you can, fix the bug. If you cannot fix the bug -- perhaps it is in code you do not own -- then again, you are in a terrible fix. You have to understand what the consequences are of not waiting for already-buggy-and-therefore-unpredictable code to finish before disposing of the resources that you know it is using right now on another thread. And you have to know what the consequences are of terminating an application while a buggy worker thread is still busy doing heaven only knows what to operating system state. </p> <p>If the code is <em>hostile</em> and is <em>actively resisting being shut down</em> then you have already lost. You cannot halt the thread by normal means, and you cannot even thread abort it. There is no guarantee whatsoever that aborting a hostile thread actually terminates it; the owner of the hostile code that you have foolishly started running in your process could be doing all of its work in a finally block or other constrained region which prevents thread abort exceptions. </p> <p>The best thing to do is to never get into this situation in the first place; if you have code that you think is hostile, either do not run it at all, or run it in its own process, and terminate <em>the process</em>, not <em>the thread</em> when things go badly. </p> <p>In short, there's no good answer to the question "what do I do if it takes too long?" You are in a <em>terrible</em> situation if that happens and there is no easy answer. Best to work hard to ensure you don't get into it in the first place; only run cooperative, benign, safe code that always shuts itself down cleanly and rapidly when asked.</p> <blockquote> <p>What if the worker throws an exception?</p> </blockquote> <p>OK, so what if it does? Again, better to not be in this situation in the first place; write the worker code so that it does not throw. If you cannot do that, then you have two choices: handle the exception, or don't handle the exception. </p> <p>Suppose you don't handle the exception. As of I think CLR v2, an unhandled exception in a worker thread shuts down the whole application. The reason being, in the past what would happen is you'd start up a bunch of worker threads, they'd all throw exceptions, and you'd end up with a running application with no worker threads left, doing no work, and not telling the user about it. It is better to force the author of the code to handle the situation where a worker thread goes down due to an exception; doing it the old way effectively hides bugs and makes it easy to write fragile applications.</p> <p>Suppose you do handle the exception. Now what? Something threw an exception, which is by definition an unexpected error condition. You now have no clue whatsoever that any of your data is consistent or any of your program invariants are maintained in any of your subsystems. So what are you going to do? There's hardly anything safe you can do at this point. </p> <p>The question is "what is best for the user in this unfortunate situation?" It depends on what the application is doing. It is entirely possible that the best thing to do at this point is to simply aggressively shut down and tell the user that something unexpected failed. That might be better than trying to muddle on and possibly making the situation worse, by, say, accidentally destroying user data while trying to clean up.</p> <p>Or, it is entirely possible that the best thing to do is to make a good faith effort to preserve the user's data, tidy up as much state as possible, and terminate as normally as possible.</p> <p>Basically, both your questions are "what do I do when my subsystems do not behave themselves?" If your subsystems are unreliable, either <em>make them reliable</em>, or <em>have a policy for how you deal with an unreliable subsystem, and implement that policy</em>. That's a vague answer I know, but that's because dealing with an unreliable subsystem is an inherently awful situation to be in. How you deal with it depends on the nature of its unreliability, and the consequences of that unreliability to the user's valuable data.</p>
1,971,798
Data Mapper and Relationships: Implementation strategies?
<p>I've almost finished my Data Mapper, but now I'm at the point where it comes to relationships.</p> <p>I will try to illustrate my ideas here. I wasn't able to find good articles / informations on this topic, so maybe I'm re-inventing the wheel (for sure I am, I could just use a big framework - but I want to learn by doing it).</p> <p><strong>1:1 Relationships</strong></p> <p>First, lets look at 1:1 relationships. In general, when we've got an domain class called "Company" and one called "Address", our Company class will have something like address_id. Lets say in most cases we just display a list of Companies, and the address is only needed when someone looks at the details. In that case, my Data Mapper (CompanyDataMapper) simply loads lazily, meaning it will just fetch that address_id from the database, but will not do a join to get the address data as well.</p> <p>In general, I have an getter method for every Relationship. So in this case, there's an getAddress(Company companyObject) method. It takes an company object, looks for it's address property and - if it's NULL - fetches the corresponding Address object from the database, using the Mapper class for that Address object (AddressDataMapper), and assigns that address object to the address property of the specified company object.</p> <p><em>Important: Is a Data Mapper allowed to use another Data Mapper?</em></p> <p>Lets say in most cases you need both the company object AND the address object, because you always display it in a list all together. In this case, the CompanyDataMapper not only fetches company objects, but does an SQL query with JOIN to also get all the fields of the address object. Finally, it iterates over the record set and feeds new objects with their corresponding values, assigning the address object to the company object.</p> <p>Sounds simple, so far.</p> <p><strong>1:n Relationships</strong></p> <p>How about these? The only difference to 1:1 is, that an Company may have multiple Address objects. Lets have a look: When we're most of the time only interested in the Company, the Data Mapper would just set the addresses property of the company object to NULL. The addresses property is an array which may reference none, one or multiple addresses. But we don't know yet, since we load lazily, so it's just NULL. But what, if we would need all the addresses in most cases as well? If we would display a big list with all companys together with all their addresses? In this case, things start to get really ugly. First, we can't join the address table fifty times for every address object (I strongly believe that's impossible, and if it is, performance would be below zero). So, when we think this further down the road, it's impossible to NOT load lazily in this case. </p> <p><em>Important: Is this true? Must I send out 100 queries to get 100 address objects, if I have 10 companies with each 10 addresses?</em></p> <p><strong>m:n Relationships</strong></p> <p>Lets say an address object only contains the country, state, city, road and house number. But one house could be a big business tower with lots of companies in them. Like one of those modern office buildings where anyone can rent a small rom to show off that tower on its website. So: Many companies can share the same address.</p> <p>I have no plans yet to deal with that kind of problem. </p> <p><em>Important: Probably it's not a bigger problem than the 1:n Relationships?</em></p> <p>If anyone knows a good ressource that goes into details about solving / implementing this, I would be happy about a link!</p>
1,971,904
3
0
null
2009-12-28 22:03:06.947 UTC
13
2014-01-15 14:29:31.943 UTC
null
null
null
null
221,023
null
1
21
design-patterns|oop|datamapper
3,270
<p>I am looking forward to any answers you'll get on this topic, but in the meantime why not just hop over to Amazon (or your local books dealer) and finally buy</p> <ul> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="nofollow noreferrer" rel="nofollow noreferrer">Design Patterns: Elements of Reusable Object-Oriented Software</a>, Gang of Four</li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0321127420" rel="nofollow noreferrer" rel="nofollow noreferrer">Patterns of Enterprise Architecture</a>, Martin Fowler</li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0321125215" rel="nofollow noreferrer" rel="nofollow noreferrer">Domain-Driven Design: Tackling Complexity in the Heart of Software</a>, Eric Evans</li> </ul> <p>These book contain the original patterns you have been pointed at in various of your questions and are considered reference works in Design Patterns and Software Architecture.</p>
2,023,210
Cannot access protected member 'object.MemberwiseClone()'
<p>I'm trying to use <code>.MemberwiseClone()</code> on a custom class of mine, but it throws up this error:</p> <pre><code>Cannot access protected member 'object.MemberwiseClone()' via a qualifier of type 'BLBGameBase_V2.Enemy'; the qualifier must be of type 'BLBGameBase_V2.GameBase' (or derived from it) </code></pre> <p>What does this mean? Or better yet, how can I clone an <code>Enemy</code> class?</p>
2,023,231
3
0
null
2010-01-07 19:55:18.71 UTC
5
2013-05-12 12:50:21.853 UTC
2013-04-09 15:22:25.277 UTC
null
505,893
null
158,109
null
1
31
c#|clone
27,438
<p>Within any class <code>X</code>, you can only call <code>MemberwiseClone</code> (or any other protected method) on an instance of <code>X</code>. (Or a class derived from <code>X</code>)</p> <p>Since the <code>Enemy</code> class that you're trying to clone doesn't inherit the <code>GameBase</code> class that you're trying to clone it in, you're getting this error.</p> <p>To fix this, add a public <code>Clone</code> method to <code>Enemy</code>, like this:</p> <pre><code>class Enemy : ICloneable { //... public Enemy Clone() { return (Enemy)this.MemberwiseClone(); } object ICloneable.Clone() { return Clone(); } } </code></pre>
1,504,871
Options for initializing a string array
<p>What options do I have when initializing <code>string[]</code> object?</p>
1,504,902
3
0
null
2009-10-01 16:05:03.47 UTC
6
2013-09-03 15:29:43.067 UTC
2013-09-03 15:29:43.067 UTC
null
661,933
null
68,183
null
1
118
c#|arrays|initialization
178,908
<p>You have several options:</p> <pre><code>string[] items = { "Item1", "Item2", "Item3", "Item4" }; string[] items = new string[] { "Item1", "Item2", "Item3", "Item4" }; string[] items = new string[10]; items[0] = "Item1"; items[1] = "Item2"; // ... </code></pre>
39,804,861
What is a concise way to create a 2D slice in Go?
<p>I am learning Go by going through <a href="https://go.dev/tour/moretypes/18" rel="noreferrer">A Tour of Go</a>. One of the exercises there asks me to create a 2D slice of <code>dy</code> rows and <code>dx</code> columns containing <code>uint8</code>. My current approach, which works, is this:</p> <pre><code>a:= make([][]uint8, dy) // initialize a slice of dy slices for i:=0;i&lt;dy;i++ { a[i] = make([]uint8, dx) // initialize a slice of dx unit8 in each of dy slices } </code></pre> <p>I think that iterating through each slice to initialize it is too verbose. And if the slice had more dimensions, the code would become unwieldy. Is there a concise way to initialize 2D (or n-dimensional) slices in Go?</p>
39,806,983
4
0
null
2016-10-01 09:11:00.83 UTC
45
2022-04-08 15:21:50.307 UTC
2022-04-08 15:21:50.307 UTC
null
4,591,810
null
4,591,810
null
1
171
go|slice
150,807
<p>There isn't a more concise way, what you did is the "right" way; because slices are always one-dimensional but may be composed to construct higher-dimensional objects. See this question for more details: <a href="https://stackoverflow.com/questions/39561140/go-how-is-two-dimensional-arrays-memory-representation">Go: How is two dimensional array&#39;s memory representation</a>.</p> <p>One thing you can simplify on it is to use the <code>for range</code> construct:</p> <pre><code>a := make([][]uint8, dy) for i := range a { a[i] = make([]uint8, dx) } </code></pre> <p>Also note that if you initialize your slice with a <a href="https://golang.org/ref/spec#Composite_literals" rel="noreferrer">composite literal</a>, you get this for "free", for example:</p> <pre><code>a := [][]uint8{ {0, 1, 2, 3}, {4, 5, 6, 7}, } fmt.Println(a) // Output is [[0 1 2 3] [4 5 6 7]] </code></pre> <p>Yes, this has its limits as seemingly you have to enumerate all the elements; but there are some tricks, namely you don't have to enumerate all values, only the ones that are not the <a href="https://golang.org/ref/spec#The_zero_value" rel="noreferrer">zero values</a> of the element type of the slice. For more details about this, see <a href="https://stackoverflow.com/questions/36302441/keyed-items-in-golang-array-initialization">Keyed items in golang array initialization</a>.</p> <p>For example if you want a slice where the first 10 elements are zeros, and then follows <code>1</code> and <code>2</code>, it can be created like this:</p> <pre><code>b := []uint{10: 1, 2} fmt.Println(b) // Prints [0 0 0 0 0 0 0 0 0 0 1 2] </code></pre> <p>Also note that if you'd use <a href="https://golang.org/ref/spec#Array_types" rel="noreferrer">arrays</a> instead of <a href="https://golang.org/ref/spec#Slice_types" rel="noreferrer">slices</a>, it can be created very easily:</p> <pre><code>c := [5][5]uint8{} fmt.Println(c) </code></pre> <p>Output is:</p> <pre><code>[[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]] </code></pre> <p>In case of arrays you don't have to iterate over the "outer" array and initialize "inner" arrays, as arrays are not descriptors but values. See blog post <a href="https://blog.golang.org/slices" rel="noreferrer">Arrays, slices (and strings): The mechanics of 'append'</a> for more details.</p> <p>Try the examples on the <a href="https://play.golang.org/p/YN4K-vqybs" rel="noreferrer">Go Playground</a>.</p>
39,454,962
kubectl logs - continuously
<pre><code>kubectl logs &lt;pod-id&gt; </code></pre> <p>gets latest logs from my deployment - I am working on a bug and interested to know the logs at runtime - How can I get continuous stream of logs ?</p> <p>edit: corrected question at the end.</p>
39,455,930
12
0
null
2016-09-12 16:39:07.753 UTC
20
2022-05-30 12:50:54.723 UTC
2016-09-12 16:57:15.507 UTC
null
5,230,894
null
5,230,894
null
1
186
kubernetes|google-kubernetes-engine|kubectl
155,182
<pre><code>kubectl logs -f &lt;pod-id&gt; </code></pre> <p>You can use the <code>-f</code> flag:</p> <p><code>-f, --follow=false: Specify if the logs should be streamed.</code></p> <p><a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#logs" rel="noreferrer">https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#logs</a></p>
21,587,036
Using putty to scp from windows to Linux
<p>I'm trying to test some C code that I'm writing. The only issue is that the code needs to be executed on a remote machine. My laptop is pretty old, and there is no driver for my wireless card available for Ubuntu, so booting into Linux to circumvent this problem isn't an option. Here's my question: </p> <p>I'm using putty to SSH into the remote machine, and I'm writing my code on Notepad++. The location of my file is: <code>C:\Users\Admin\Desktop\WMU\5260\A2.c</code></p> <p>My problem is that when I use the command <code>scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~</code> I get the error <code>could not resolve hostname C:. Name or service not known".</code></p> <p>I've also tried <code>scp Users\Admin\Desktop\WMU\5260\A2.c ~</code> which gives me the error <code>Cannot stat 'Users\Admin\Desktop\WMU\5260\A2.c': no such file or directory</code></p> <p>What am I doing incorrectly?</p>
26,763,637
3
0
null
2014-02-05 19:48:30.947 UTC
16
2019-05-05 12:25:46.997 UTC
2015-05-18 09:55:55.83 UTC
null
2,216,929
null
1,833,878
null
1
68
linux|windows|ssh|putty|scp
419,862
<p>You need to tell <code>scp</code> where to send the file. In your command that is not working:</p> <pre><code>scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~ </code></pre> <p>You have not mentioned a remote server. <code>scp</code> uses <code>:</code> to delimit the host and path, so it thinks you have asked it to download a file at the path <code>\Users\Admin\Desktop\WMU\5260\A2.c</code> from the host <code>C</code> to your local home directory.</p> <p>The correct upload command, based on your comments, should be something like:</p> <pre><code>C:\&gt; pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]: </code></pre> <p>If you are running the command from your home directory, you can use a relative path:</p> <pre><code>C:\Users\Admin&gt; pscp Desktop\WMU\5260\A2.c [email protected]: </code></pre> <p>You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below: </p> <pre><code>C:/&gt; pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/ </code></pre>
21,839,676
How to write a DownloadHandler for scrapy that makes requests through socksipy?
<p>I'm trying to use scrapy over Tor. I've been trying to get my head around how to write a DownloadHandler for scrapy that uses socksipy connections.</p> <p>Scrapy's HTTP11DownloadHandler is here: <a href="https://github.com/scrapy/scrapy/blob/master/scrapy/core/downloader/handlers/http11.py" rel="noreferrer">https://github.com/scrapy/scrapy/blob/master/scrapy/core/downloader/handlers/http11.py</a></p> <p>Here is an example for creating a custom download handler: <a href="https://github.com/scrapinghub/scrapyjs/blob/master/scrapyjs/dhandler.py" rel="noreferrer">https://github.com/scrapinghub/scrapyjs/blob/master/scrapyjs/dhandler.py</a></p> <p>Here's the code for creating a SocksiPyConnection class: <a href="http://blog.databigbang.com/distributed-scraping-with-multiple-tor-circuits/" rel="noreferrer">http://blog.databigbang.com/distributed-scraping-with-multiple-tor-circuits/</a></p> <pre><code>class SocksiPyConnection(httplib.HTTPConnection): def __init__(self, proxytype, proxyaddr, proxyport = None, rdns = True, username = None, password = None, *args, **kwargs): self.proxyargs = (proxytype, proxyaddr, proxyport, rdns, username, password) httplib.HTTPConnection.__init__(self, *args, **kwargs) def connect(self): self.sock = socks.socksocket() self.sock.setproxy(*self.proxyargs) if isinstance(self.timeout, float): self.sock.settimeout(self.timeout) self.sock.connect((self.host, self.port)) </code></pre> <p>With the complexity of twisted reactors in the scrapy code, I can't figure out how plug socksipy into it. Any thoughts?</p> <p>Please do not answer with privoxy-like alternatives or post answers saying "scrapy doesn't work with socks proxies" - I know that, which is why I'm trying to write a custom Downloader that makes requests using socksipy.</p>
21,866,779
2
0
null
2014-02-17 21:32:27.453 UTC
8
2016-04-06 08:22:14.393 UTC
null
null
null
null
913,914
null
1
7
python|web-scraping|scrapy|twisted|socks
4,169
<p>I was able to make this work with <a href="https://github.com/habnabit/txsocksx" rel="noreferrer">https://github.com/habnabit/txsocksx</a>.</p> <p>After doing a <code>pip install txsocksx</code>, I needed to replace scrapy's <code>ScrapyAgent</code> with <code>txsocksx.http.SOCKS5Agent</code>.</p> <p>I simply copied the code for <code>HTTP11DownloadHandler</code> and <code>ScrapyAgent</code> from <code>scrapy/core/downloader/handlers/http.py</code>, subclassed them and wrote this code:</p> <pre><code>class TorProxyDownloadHandler(HTTP11DownloadHandler): def download_request(self, request, spider): """Return a deferred for the HTTP download""" agent = ScrapyTorAgent(contextFactory=self._contextFactory, pool=self._pool) return agent.download_request(request) class ScrapyTorAgent(ScrapyAgent): def _get_agent(self, request, timeout): bindaddress = request.meta.get('bindaddress') or self._bindAddress proxy = request.meta.get('proxy') if proxy: _, _, proxyHost, proxyPort, proxyParams = _parse(proxy) scheme = _parse(request.url)[0] omitConnectTunnel = proxyParams.find('noconnect') &gt;= 0 if scheme == 'https' and not omitConnectTunnel: proxyConf = (proxyHost, proxyPort, request.headers.get('Proxy-Authorization', None)) return self._TunnelingAgent(reactor, proxyConf, contextFactory=self._contextFactory, connectTimeout=timeout, bindAddress=bindaddress, pool=self._pool) else: _, _, host, port, proxyParams = _parse(request.url) proxyEndpoint = TCP4ClientEndpoint(reactor, proxyHost, proxyPort, timeout=timeout, bindAddress=bindaddress) agent = SOCKS5Agent(reactor, proxyEndpoint=proxyEndpoint) return agent return self._Agent(reactor, contextFactory=self._contextFactory, connectTimeout=timeout, bindAddress=bindaddress, pool=self._pool) </code></pre> <p>In settings.py, something like this is needed:</p> <pre><code>DOWNLOAD_HANDLERS = { 'http': 'crawler.http.TorProxyDownloadHandler' } </code></pre> <p>Now proxying with Scrapy with work through a socks proxy like Tor.</p>
30,202,755
React-Router open Link in new tab
<p>Is there a way to get <a href="https://github.com/rackt/react-router" rel="noreferrer">React Router</a> to open a link in new tab? I tried this and it did not work.</p> <pre><code>&lt;Link to="chart" target="_blank" query={{test: this.props.test}} &gt;Test&lt;/Link&gt; </code></pre> <p>It's possible to fluff it by adding something like <code>onClick="foo"</code> to the Link like what I have above, but there would be a console error. </p> <p>Thanks.</p>
30,520,525
14
0
null
2015-05-12 22:50:25.61 UTC
21
2022-05-28 09:45:40.98 UTC
2015-05-12 23:05:14.463 UTC
null
4,527,337
null
1,072,661
null
1
147
reactjs|react-router
282,540
<p>I think Link component does not have the props for it.</p> <p>You can have alternative way by create a tag and use the makeHref method of Navigation mixin to create your url</p> <pre><code>&lt;a target='_blank' href={this.makeHref(routeConsts.CHECK_DOMAIN, {}, { realm: userStore.getState().realms[0].name })}&gt; Share this link to your webmaster &lt;/a&gt; </code></pre>
29,960,764
What does 'extended' mean in express 4.0?
<p>I'm using express and also body-parser in my app.</p> <pre><code>app.use(bodyParser.urlencoded({ extended: false })); </code></pre> <p>But, What does 'extended' mean in express 4.0?</p> <p>I found this </p> <pre><code>extended - parse extended syntax with the qs module. </code></pre> <p>However, I still can't understrand what it means.</p>
39,779,840
3
0
null
2015-04-30 06:42:20.407 UTC
39
2022-06-26 11:22:20.44 UTC
null
null
null
null
4,836,234
null
1
122
node.js|express|body-parser
67,320
<p>If <code>extended</code> is <code>false</code>, you can not post "nested object"</p> <pre><code>person[name] = 'cw' // Nested Object = { person: { name: cw } } </code></pre> <p>If <code>extended</code> is <code>true</code>, you can do whatever way that you like.</p>
35,213,592
NumPy calculate square of norm 2 of vector
<p>I have vector <code>a</code>.<br> I want to calculate <code>np.inner(a, a)</code><br> But I wonder whether there is prettier way to calc it.</p> <p>[The disadvantage of this way, that if I want to calculate it for <code>a-b</code> or a bit more complex expression, I have to do that with one more line. <code>c = a - b</code> and <code>np.inner(c, c)</code> instead of <code>somewhat(a - b)</code>]</p>
35,213,951
4
0
null
2016-02-04 23:19:08.107 UTC
3
2020-06-04 09:58:33.753 UTC
null
null
null
null
5,604,430
null
1
9
python|numpy|inner-product
40,664
<p>Honestly there's probably not going to be anything faster than <code>np.inner</code> or <code>np.dot</code>. If you find intermediate variables annoying, you could always create a lambda function:</p> <pre><code>sqeuclidean = lambda x: np.inner(x, x) </code></pre> <p><code>np.inner</code> and <code>np.dot</code> leverage BLAS routines, and will almost certainly be faster than standard elementwise multiplication followed by summation. </p> <pre><code>In [1]: %%timeit -n 1 -r 100 a, b = np.random.randn(2, 1000000) ((a - b) ** 2).sum() ....: The slowest run took 36.13 times longer than the fastest. This could mean that an intermediate result is being cached 1 loops, best of 100: 6.45 ms per loop In [2]: %%timeit -n 1 -r 100 a, b = np.random.randn(2, 1000000) np.linalg.norm(a - b, ord=2) ** 2 ....: 1 loops, best of 100: 2.74 ms per loop In [3]: %%timeit -n 1 -r 100 a, b = np.random.randn(2, 1000000) sqeuclidean(a - b) ....: 1 loops, best of 100: 2.64 ms per loop </code></pre> <p><code>np.linalg.norm(..., ord=2)</code> uses <code>np.dot</code> internally, and gives very similar performance to using <code>np.inner</code> directly.</p>
37,050,316
Unable to marshal type as XML element because @XmlRootElement annotation is missing
<p>I want to marshal object to XML. </p> <p>However, it fails with exception:</p> <pre><code>javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.SAXException2: unable to marshal type "FreightOfferDetail" as an element because it is missing an @XmlRootElement annotation] at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:331) at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:257) at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:96) at com.wktransportservices.fx.test.util.jaxb.xmltransformer.ObjectTransformer.toXML(ObjectTransformer.java:27) at com.wktransportservices.fx.test.sampler.webservice.connect.FreightOfferToConnectFreight.runTest(FreightOfferToConnectFreight.java:59) at org.apache.jmeter.protocol.java.sampler.JavaSampler.sample(JavaSampler.java:191) at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:429) at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:257) at java.lang.Thread.run(Thread.java:662) Caused by: com.sun.istack.SAXException2: unable to marshal type "FreightOfferDetail" as an element because it is missing an @XmlRootElement annotation at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:244) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:303) at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:490) at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:328) </code></pre> <p>In fact, this annotation is present (for parent and delivered class):</p> <pre><code>@XmlRootElement(name = "Freight_Offer") @XmlAccessorType(XmlAccessType.FIELD) @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_EMPTY) public class FreightOffer { @JsonIgnore @XmlTransient private String freightId; private String id; private String externalSystemId; private AddressLocation pickUp; private AddressLocation delivery; private FreightDescription freightDescription; private ListContacts contacts; private Customer customer; private ListSla slas; private String pushId; private CompanyProfile company; private Route route; private String href; private Lifecycle lifecycle; private Visibility visibility; private Boolean unfoldedVXMatching; // getters / setters </code></pre> <p>Child class:</p> <pre><code>@XmlAccessorType(XmlAccessType.PROPERTY) public class FreightOfferDetail extends FreightOffer { private List&lt;Contact&gt; contact; @XmlElement(name = "contacts") @JsonProperty("contacts") public List&lt;Contact&gt; getContact() { return contact; } public void setContact(List&lt;Contact&gt; contact) { this.contact = contact; } </code></pre> <p>It fails exactly at this method <code>toXML()</code>:</p> <pre><code>public class ObjectTransformer&lt;T&gt; implements Transformer&lt;T&gt; { protected final JAXBContext context; protected final Marshaller marshaller; protected final int okStatusCode = 200; protected final String okSubErrorCode = "OK"; public ObjectTransformer(JAXBContext context) throws JAXBException { this.context = context; marshaller = context.createMarshaller(); marshaller.setProperty("jaxb.encoding", "UTF-8"); marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE); } public String toXML(T object) throws JAXBException { StringWriter writer = new StringWriter(); marshaller.marshal(object, writer); String xmlOffer = writer.toString(); return xmlOffer; } </code></pre> <p>It should work, but it shouldn't. </p> <p>I couldn't find what is missed or wrong here.</p> <p><strong><em>UPDATE:</em></strong></p> <p>Here is snippet from test:</p> <pre><code>public SampleResult runTest(JavaSamplerContext context) { AbstractSamplerResults results = new XMLSamplerResults(new SampleResult()); results.startAndPauseSampler(); if (failureCause != null) { results.setExceptionFailure("FAILED TO INSTANTIATE connectTransformer", failureCause); } else { FreightOfferDTO offer = null; FreightOffer freightOffer = null; try { results.resumeSampler(); RouteInfo routeDTO = SamplerUtils.getRandomRouteFromRepo(context.getIntParameter(ROUTES_TOUSE_KEY)); offer = FreightProvider.createRandomFreight(routeDTO, createUserWithLoginOnly(context)); freightOffer = connectTransformer.fromDTO(offer); String xmlOfferString = connectTransformer.toXML(freightOffer); // &lt;- it fails here. </code></pre> <p>I take the date from <strong><em>CSV</em></strong> file and converting to <strong><em>DTO</em></strong> object. This method returns to me <code>FreightOfferDetail.</code></p> <p>Here is snippet from this method:</p> <pre><code>public FreightOfferDetail freightFromDTO(FreightOfferDTO freightDTO, boolean fullFormat){ FreightOfferDetail freight = new FreightOfferDetail(); freight.setFreightId(freightDTO.getIds().getAtosId()); freight.setId(freightDTO.getIds().getFxId()); // ... </code></pre> <p><strong><em>How to marshal object to XML file, at this case?</em></strong></p>
37,115,701
4
0
null
2016-05-05 12:11:53.723 UTC
null
2021-12-10 11:24:27.987 UTC
2016-05-05 15:49:20.34 UTC
null
1,498,427
null
1,498,427
null
1
13
java|xml|jaxb|marshalling
44,075
<pre><code>public String toXML(T object) throws JAXBException { StringWriter stringWriter = new StringWriter(); JAXBContext jaxbContext = JAXBContext.newInstance(T.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // format the XML output jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); QName qName = new QName(&quot;com.yourModel.t&quot;, &quot;object&quot;); JAXBElement&lt;T&gt; root = new JAXBElement&lt;Bbb&gt;(qName, T.class, object); jaxbMarshaller.marshal(root, stringWriter); String result = stringWriter.toString(); LOGGER.info(result); return result; } </code></pre> <p>Here is the article I use when I have to marshal/unmarshal without @XmlRootElement: <a href="http://www.source4code.info/2013/07/jaxb-marshal-unmarshal-with-missing.html" rel="nofollow noreferrer">http://www.source4code.info/2013/07/jaxb-marshal-unmarshal-with-missing.html</a></p> <p>All the best hope it helps :)</p>
36,992,855
Keras : How should I prepare input data for RNN?
<p>I'm having trouble with preparing input data for RNN on Keras.</p> <p>Currently, my training data dimension is: <code>(6752, 600, 13)</code></p> <ul> <li>6752: number of training data </li> <li>600: number of time steps </li> <li>13: size of feature vectors (the vector is in float)</li> </ul> <p><code>X_train</code> and <code>Y_train</code> are both in this dimension.</p> <p>I want to prepare this data to be fed into <code>SimpleRNN</code> on Keras. Suppose that we're going through time steps, from step #0 to step #599. Let's say I want to use <code>input_length = 5</code>, which means that I want to use recent 5 inputs. (e.g. step #10, #11,#12,#13,#14 @ step #14).</p> <p>How should I reshape <code>X_train</code>?</p> <p>should it be <code>(6752, 5, 600, 13)</code> or should it be <code>(6752, 600, 5, 13)</code>?</p> <p>And what shape should <code>Y_train</code> be in?</p> <p>Should it be <code>(6752, 600, 13)</code> or <code>(6752, 1, 600, 13)</code> or <code>(6752, 600, 1, 13)</code>?</p>
37,009,670
2
0
null
2016-05-02 22:51:32.713 UTC
16
2021-03-01 14:51:48.027 UTC
2020-08-28 11:34:33 UTC
null
10,375,049
null
5,513,231
null
1
21
tensorflow|keras|deep-learning|lstm|recurrent-neural-network
13,883
<p>If you only want to predict the output using the most recent 5 inputs, there is no need to ever provide the full 600 time steps of any training sample. My suggestion would be to pass the training data in the following manner:</p> <pre><code> t=0 t=1 t=2 t=3 t=4 t=5 ... t=598 t=599 sample0 |---------------------| sample0 |---------------------| sample0 |----------------- ... sample0 ----| sample0 ----------| sample1 |---------------------| sample1 |---------------------| sample1 |----------------- .... .... sample6751 ----| sample6751 ----------| </code></pre> <p>The total number of training sequences will sum up to</p> <pre><code>(600 - 4) * 6752 = 4024192 # (nb_timesteps - discarded_tailing_timesteps) * nb_samples </code></pre> <p>Each training sequence consists of 5 time steps. At each time step of every sequence you pass all 13 elements of the feature vector. Subsequently, the shape of the training data will be (4024192, 5, 13).</p> <p>This loop can reshape your data:</p> <pre class="lang-py prettyprint-override"><code>input = np.random.rand(6752,600,13) nb_timesteps = 5 flag = 0 for sample in range(input.shape[0]): tmp = np.array([input[sample,i:i+nb_timesteps,:] for i in range(input.shape[1] - nb_timesteps + 1)]) if flag==0: new_input = tmp flag = 1 else: new_input = np.concatenate((new_input,tmp)) </code></pre>
24,110,769
How to correctly initialize an UnsafePointer in Swift?
<p>I'm trying to use <code>CTFontCreatePathForGlyph(font: CTFont?, glyph: CGGlyph, transform: CConstPointer&lt;CGAffineTransform&gt;)</code>:</p> <pre><code>let myFont = CTFontCreateWithName("Helvetica", 12, nil) let myGlyph = CTFontGetGlyphWithName(myFont, "a") let myTransform = CGAffineTransformIdentity </code></pre> <p>But how do I correctly pass <code>myTransform</code> to <code>CTFontCreatePathForGlyph</code>?</p> <p>I've tried creating a <code>myTransformPointer</code> to pass to the function like so:</p> <pre><code>var myTransformPointer: UnsafePointer&lt;CGAffineTransform&gt; = UnsafePointer().initialize(newvalue: myTransform) </code></pre> <p>but I get this error:</p> <pre><code>Playground execution failed: error: &lt;REPL&gt;:20:76: error: '()' is not convertible to 'UnsafePointer&lt;CGAffineTransform&gt;' var myTransformPointer: UnsafePointer&lt;CGAffineTransform&gt; = UnsafePointer().initialize(newvalue: myTransform) </code></pre> <p>so then I tried explicitly naming the type:</p> <pre><code>var myTransformPointer: UnsafePointer&lt;CGAffineTransform&gt; = UnsafePointer&lt;CGAffineTransform&gt;().initialize(newvalue: myTransform) </code></pre> <p>and then I get a different error:</p> <pre><code>Playground execution failed: error: &lt;REPL&gt;:20:95: error: could not find an overload for 'init' that accepts the supplied arguments var myTransformPointer: UnsafePointer&lt;CGAffineTransform&gt; = UnsafePointer&lt;CGAffineTransform&gt;().initialize(newvalue: myTransform) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </code></pre> <p>The auto-complete suggests this should work?</p>
24,111,251
1
0
null
2014-06-08 20:59:48.483 UTC
9
2014-06-08 21:55:55.853 UTC
null
null
null
null
637,562
null
1
22
swift
12,820
<p>The simplest solution is using <code>withUnsafePointer</code> function:</p> <pre><code>let myFont = CTFontCreateWithName("Helvetica", 12, nil) let myGlyph = CTFontGetGlyphWithName(myFont, "a") var myTransform = CGAffineTransformIdentity var path = withUnsafePointer(&amp;myTransform) { (pointer: UnsafePointer&lt;CGAffineTransform&gt;) -&gt; (CGPath) in return CTFontCreatePathForGlyph(myFont, myGlyph, pointer) } </code></pre> <p>The <code>initialize</code> is not a constructor. You would have to <code>alloc</code> a new memory using <code>UnsafePointer&lt;T&gt;.alloc</code>, then <code>initialize</code> and then <code>dealloc</code>. Function <code>withUnsafePointer</code> does that all for you.</p> <p>Note that <code>myTransform</code> cannot be a constant (<code>var</code> not <code>let</code>) otherwise you cannot use it for an <code>inout</code> param (<code>&amp;myTransform</code>).</p>
30,712,638
TypeScript export imported interface
<p>I use AMD modules and I want to hide a complex interface behind one file that loads several other files and chooses what to expose and how. It works, I use this solution but it feels kinda ugly, mostly with the interfaces. </p> <pre><code>import Types = require('./message-types'); import MessageBaseImport = require('./message-base'); export interface IMessage extends Types.IMessage {} // This is an interface export var MessageBase = MessageBaseImport; // This is a class </code></pre> <p>Usage:</p> <pre><code>import Message = require('message'); import { * } as Message from 'message'; // Or with ES6 style var mb = new Message.MessageBase(); // Using the class var msg: Message.IMessage = null; // Using the interface </code></pre> <p>Any better solutions out there? I don't want to put everything into a single file but I want to <code>import</code> a single file. </p>
30,714,301
3
0
null
2015-06-08 15:01:44.757 UTC
30
2020-09-11 07:14:50.053 UTC
null
null
null
null
1,165,203
null
1
155
typescript
114,964
<p>There is an export import syntax for legacy modules, and a standard export format for modern ES6 modules:</p> <pre><code>// export the default export of a legacy (`export =`) module export import MessageBase = require('./message-base'); // export the default export of a modern (`export default`) module export { default as MessageBase } from './message-base'; // when '--isolatedModules' flag is provided it requires using 'export type'. export type { default as MessageBase } from './message-base'; // export an interface from a legacy module import Types = require('./message-types'); export type IMessage = Types.IMessage; // export an interface from a modern module export { IMessage } from './message-types'; </code></pre>
34,668,012
Combine URL paths with path.Join()
<p>Is there a way in Go to combine URL paths similarly as we can do with filepaths using <code>path.Join()</code>?</p> <p>For example see e.g. <a href="https://stackoverflow.com/q/13078314/772000">Combine absolute path and relative path to get a new absolute path</a>. </p> <p>When I use <code>path.Join("http://foo", "bar")</code>, I get <code>http:/foo/bar</code>. </p> <p>See in <a href="https://play.golang.org/p/VPaiToD_XO" rel="noreferrer">Golang Playground</a>.</p>
34,668,130
6
0
null
2016-01-08 01:16:20.287 UTC
12
2022-08-08 13:49:57.33 UTC
2017-05-23 12:17:53.783 UTC
null
-1
null
772,000
null
1
82
url|go|path
72,880
<p>The function <a href="https://pkg.go.dev/path#Join" rel="noreferrer">path.Join</a> expects a path, not a URL. <a href="https://pkg.go.dev/net/url#Parse" rel="noreferrer">Parse</a> the URL to get a path and join with that path:</p> <pre><code>u, err := url.Parse(&quot;http://foo&quot;) if err != nil { log.Fatal(err) } u.Path = path.Join(u.Path, &quot;bar.html&quot;) s := u.String() fmt.Println(s) // prints http://foo/bar.html </code></pre> <p>Use the <a href="https://pkg.go.dev/net/[email protected]#JoinPath" rel="noreferrer">url.JoinPath</a> function in Go 1.19 or later:</p> <pre><code>s, err := url.JoinPath(&quot;http://foo&quot;, &quot;bar.html&quot;) if err != nil { log.Fatal(err) } fmt.Println(s) // prints http://foo/bar.html </code></pre> <p>Use <a href="https://pkg.go.dev/net/url#URL.ResolveReference" rel="noreferrer">ResolveReference</a> if you are <strong>resolving a URI reference from a base URL</strong>. This operation is different from a simple path join: an absolute path in the reference replaces the entire base path; the base path is trimmed back to the last slash before the join operation.</p> <pre><code>base, err := url.Parse(&quot;http://foo/quux.html&quot;) if err != nil { log.Fatal(err) } ref, err := url.Parse(&quot;bar.html&quot;) if err != nil { log.Fatal(err) } u := base.ResolveReference(ref) fmt.Println(u.String()) // prints http://foo/bar.html </code></pre> <p>Notice how quux.html in the base URL does not appear in the resolved URL.</p>
29,327,219
How to run React-Native Examples?
<p>I can't find any instructions on how to install and run one of the other Examples provided in '<a href="https://github.com/facebook/react-native/tree/master/Examples">https://github.com/facebook/react-native/tree/master/Examples</a>' such as '<a href="https://github.com/facebook/react-native/tree/master/Examples/Movies">https://github.com/facebook/react-native/tree/master/Examples/Movies</a>'.</p> <p>The tutorial only tells you to do</p> <p><code>react-native init AwesomeProject</code></p> <p>which grabs '<a href="https://github.com/facebook/react-native/tree/master/Examples/SampleApp">https://github.com/facebook/react-native/tree/master/Examples/SampleApp</a>'.</p> <hr> <p>If I clone the entire 'react-native' repository, and then run</p> <pre><code>npm install npm start </code></pre> <p>From the root folder (i.e. '/react-native'), and then open '/react-native/Examples/Movies/Movies.xcodeproj' in Xcode, and Run the project, it seems to build fine. The Simulator comes up, shows a "Movies" intro screen for the app, but then the red screen of death appears with a print out of:</p> <pre><code>:0 </code></pre> <p>and Terminal, where 'npm start' is running at the root folder, prints out:</p> <pre><code>Error: EISDIR, read at Error (native) [02:35:02] &lt;START&gt; request:/Examples/Movies/MoviesApp.includeRequire.runModule.bundle </code></pre>
29,334,953
9
0
null
2015-03-29 08:45:19.157 UTC
10
2017-04-26 15:25:53.843 UTC
2015-03-29 20:26:17.727 UTC
null
1,203,703
null
1,203,703
null
1
14
ios|facebook|reactjs|react-native
39,323
<p>It should work just by following the <a href="http://facebook.github.io/react-native/docs/getting-started.html#content">Getting Started Tutorial</a>, except that you have to run <code>npm install</code> inside your react-native directory.</p> <p>Then just run for example the Movie Project with Xcode.</p> <p>If you want to "isolate" the MovieProject or another react-native example project, the easy way is to init a new react native app (<code>react-native init MyAppName</code>) and just copy the JS files from the example project (in the example below the Movie Project) into the new app folder.</p> <p>And then don't forget to edit your iOS/AppDelegate.m file.</p> <p>You have to edit 2 lines:</p> <pre><code>jsCodeLocation = [NSURL URLWithString:@"http:/localhost:8081/index.ios.bundle"]; </code></pre> <p>By:</p> <pre><code>jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/MoviesApp.bundle"]; </code></pre> <p>AND</p> <pre><code>RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"MyAppName" launchOptions:launchOptions]; </code></pre> <p>By:</p> <pre><code>RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"MoviesApp" launchOptions:launchOptions]; </code></pre> <hr>
70,329,808
Is Logback also affected by the Log4j zero-day vulnerability issue in Spring Boot?
<p>As I understand it, Logback is written by the same authors. Our applications are using Logback instead. Is there a chance that Logback is also affected by the exploit in Log4j?</p> <p>This is critical for our organisation.</p>
70,331,097
1
1
null
2021-12-13 04:02:21.807 UTC
3
2022-08-19 12:15:04.047 UTC
2022-01-02 21:04:59.26 UTC
null
63,550
null
3,520,404
null
1
42
spring-boot|log4j|logback
23,216
<p>From the <a href="https://spring.io/blog/2021/12/10/log4j2-vulnerability-and-spring-boot" rel="nofollow noreferrer">Spring blog</a>:</p> <blockquote> <p>Spring Boot users are only affected by this vulnerability if they have switched the default logging system to Log4J2. The <code>log4j-to-slf4j</code> and <code>log4j-api</code> jars that we include in <code>spring-boot-starter-logging</code> cannot be exploited on their own. Only applications using <code>log4j-core</code> and including user input in log messages are vulnerable.</p> </blockquote> <p><em>Useful explanation points:</em></p> <p><code>log4j-to-slf4j</code> is an adapter between the <a href="https://en.wikipedia.org/wiki/Log4j" rel="nofollow noreferrer">Log4j</a> API and <a href="https://en.wikipedia.org/wiki/SLF4J" rel="nofollow noreferrer">SLF4J</a>. It indeed brings <code>log4j-api</code>, but it does not bring <code>log4j-core</code>, so our starter is not affected by this vulnerability.</p>
27,026,323
Show loading gif after clicking form submit using jQuery
<p>I'm trying to simply show a loading gif once the form is submitted. My code is not working correctly for the loading gif to show. You'll see my image for the gif is set to <code>visibility: hidden</code>.</p> <pre><code>&lt;script src="js/jquery-1.11.1.min.js"&gt;&lt;/script&gt; &lt;div class="" style="width: 480px; margin: 0 auto; margin-top: 20px;" id="form_wrapper"&gt; &lt;img src="img/loader.gif" id="gif" style="display: block; margin: 0 auto; width: 100px; visibility: hidden;"&gt; &lt;div class="fade" id="form"&gt; &lt;form action="process_login.php" method="POST" name="simplelogin" id="login_form"&gt;&lt;br /&gt; &lt;label for="username"&gt;&amp;nbsp; Username:&lt;/label&gt; &lt;input type="username" name="username" id="username" size="30" required&gt;&lt;br&gt;&lt;br&gt; &lt;label for="password"&gt;&amp;nbsp; Password:&lt;/label&gt; &lt;input type="password" name="password" id="password" size="30" required&gt;&lt;br&gt;&lt;br&gt; &lt;input class="load_button" type="submit" name="submit" id="submit" value="Submit" placeholder="Submit"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="fifty"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; $('.load_button').submit(function() { $('#gif').show(); return true; }); &lt;/script&gt; </code></pre>
27,026,355
4
2
null
2014-11-19 20:25:45.303 UTC
2
2019-04-17 16:27:03.763 UTC
2016-06-11 22:31:35.687 UTC
null
519,413
null
2,415,481
null
1
17
javascript|jquery|forms|gif
115,935
<p>The <code>show()</code> method only affects the <code>display</code> CSS setting. If you want to set the visibility you need to do it directly. Also, the <code>.load_button</code> element is a button and does not raise a <code>submit</code> event. You would need to change your selector to the <code>form</code> for that to work:</p> <pre><code>$('#login_form').submit(function() { $('#gif').css('visibility', 'visible'); }); </code></pre> <p>Also note that <code>return true;</code> is redundant in your logic, so it can be removed.</p>
27,384,093
Fastest way to write huge data in file
<p>I am trying to create a random real, integers, alphanumeric, alpha strings and then writing to a file till the file size reaches <strong>10MB</strong>.</p> <p>The code is as follows.</p> <pre><code>import string import random import time import sys class Generator(): def __init__(self): self.generate_alphabetical_strings() self.generate_integers() self.generate_alphanumeric() self.generate_real_numbers() def generate_alphabetical_strings(self): return ''.join(random.choice(string.ascii_lowercase) for i in range(12)) def generate_integers(self): return ''.join(random.choice(string.digits) for i in range(12)) def generate_alphanumeric(self): return ''.join(random.choice(self.generate_alphabetical_strings() + self.generate_integers()) for i in range(12)) def _insert_dot(self, string, index): return string[:index].__add__('.').__add__(string[index:]) def generate_real_numbers(self): rand_int_string = ''.join(random.choice(self.generate_integers()) for i in range(12)) return self._insert_dot(rand_int_string, random.randint(0, 11)) from time import process_time import os a = Generator() t = process_time() inp = open("test.txt", "w") lt = 10 * 1000 * 1000 count = 0 while count &lt;= lt: inp.write(a.generate_alphanumeric()) count += 39 inp.close() elapsed_time = process_time() - t print(elapsed_time) </code></pre> <p>It takes around <strong>225.953125 seconds</strong> to complete. How can i improve the speed of this program? Please provide some code insights? </p>
27,384,379
3
3
null
2014-12-09 16:37:20.71 UTC
7
2014-12-09 17:14:50.057 UTC
null
null
null
null
1,112,163
null
1
21
python|performance|file
74,013
<p>Two major reasons for observed "slowness":</p> <ul> <li>your while loop is slow, it has about a million iterations.</li> <li>You do not make proper use of I/O buffering. Do not make so many system calls. Currently, you are calling <code>write()</code> about one million times.</li> </ul> <p>Create your data in a Python data structure first and call <code>write()</code> only <em>once</em>.</p> <p>This is faster:</p> <pre><code>t0 = time.time() open("bla.txt", "wb").write(''.join(random.choice(string.ascii_lowercase) for i in xrange(10**7))) d = time.time() - t0 print "duration: %.2f s." % d </code></pre> <p>Output: <code>duration: 7.30 s.</code></p> <p>Now the program spends most of its time generating the data, i.e. in <code>random</code> stuff. You can easily see that by replacing <code>random.choice(string.ascii_lowercase)</code> with e.g. <code>"a"</code>. Then the measured time drops to below one second on my machine.</p> <p>And if you want to get even closer to seeing how fast your machine really is when writing to disk, use Python's fastest (?) way to generate largish data before writing it to disk:</p> <pre><code>&gt;&gt;&gt; t0=time.time(); chunk="a"*10**7; open("bla.txt", "wb").write(chunk); d=time.time()-t0; print "duration: %.2f s." % d duration: 0.02 s. </code></pre>
677,481
Create and Save XML file to Server Using PHP
<p>I'm using PHP to extract data from a MySQL database. I am able to build an XML file using DOM functions. Then using <code> echo $dom->saveXML(); </code>, I am able to return the XML from an AJAX call. Instead of using AJAX to get the XML, how would I save the XML file to a spot on the server? Thanks </p>
677,501
4
0
null
2009-03-24 13:49:54.52 UTC
3
2016-07-05 13:27:43.193 UTC
null
null
null
null
217,378
null
1
4
php|xml
38,115
<p>Use the <a href="http://docs.php.net/manual/en/domdocument.save.php" rel="noreferrer"><code>DOMDocument::save()</code> method</a> to save the XML document into a file:</p> <pre><code>$dom-&gt;save('document.xml'); </code></pre>
52,103
Can I use SQL Server Management Studio 2005 for 2008 DB?
<p>I am looking to manage a SQL Server 2008 DB using Management Studio 2005. The reason for this is because our server is a 64-bit machine and we only have the 64-bit version of the software. </p> <p>Is this possible? </p> <p>How about managing a SQL Server 2005 DB using Management Studio 2008?</p>
52,106
4
0
null
2008-09-09 15:05:53.21 UTC
6
2015-05-12 14:05:44.443 UTC
2015-05-12 14:05:44.443 UTC
Andy Lester
1,118,488
jinsungy
1,316
null
1
24
sql-server-2008|sql-server-2005|ssms
64,311
<p>UPDATE: You can use <a href="http://support.microsoft.com/kb/943656" rel="noreferrer">Cumulative update package 5</a> for SQL Server 2005 Service Pack 2 to connect to 2008.</p> <p>FIX: 50002151 946127 (<a href="http://support.microsoft.com/kb/946127/" rel="noreferrer">http://support.microsoft.com/kb/946127/</a>) FIX: You may experience problems when you use SQL Server Management Studio in SQL Server 2005 to connect to an instance of SQL Server 2008 </p>
944,608
WPF vs Silverlight
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/629927/what-is-the-difference-between-wpf-and-silverlight-application">What is the difference between WPF and Silverlight application?</a> </p> </blockquote> <p>What are the exact differences between WPF and Silverlight? </p>
944,826
4
1
null
2009-06-03 13:00:39.973 UTC
57
2013-01-04 07:20:09.06 UTC
2017-05-23 12:10:15.103 UTC
null
-1
null
88,096
null
1
126
wpf|silverlight
57,230
<p>That's an extremely broad question. My company recently wrote a whitepaper outlining the differences between the two technologies, and it's around 70 pages. Unfortunately, it's not published yet, or I'd give you the link.</p> <blockquote> <p><b>EDIT: As promised, here's the link to the whitepaper on Codeplex:<br><br> <a href="http://wpfslguidance.codeplex.com/" rel="noreferrer">http://wpfslguidance.codeplex.com/</a> </b></p> </blockquote> <p>However, I'll try to summarize.</p> <ol> <li><p>WPF is a thick Windows client platform that has access to the full .Net Framework. Silverlight is a browser-based technology that has access to a subset of the .Net Framework (called the CoreCLR). So, you'll notice differences using seemingly every day methods and objects within the framework. For instance, the Split() method on the String class has 3 overrides in Silverlight, but 6 in the .Net Framework. You'll see differences like this a lot.</p></li> <li><p>Within WPF, all visually rendering elements derive from the Visual base class. Within Silverlight, they do not; instead, they derive from Control. Both technologies, however, eventual derive from the DependencyObject class up the hierarchy.</p></li> <li><p>WPF, currently, ships or has available more user controls than Silverlight; though this difference is being mitigated through the Silverlight Toolkit and the upcoming release of Silverlight 3.</p></li> <li><p>WPF supports 3 types of routed events (direct, bubbling, and tunneling). Silverlight supports direct and bubbling only.</p></li> <li><p>There's quite a few data-binding differences that will be somewhat mitigated with the next version of Silverlight. Currently, Silverlight doesn't support the binding mode, OneWayToSource, or Explict UpdateSourceTriggers. In addition, Silverlight defaults to OneWay databinding if none is set, while WPF uses the default mode specified by the dependency property.</p></li> <li><p>Silveright doesn't support MultiBinding. </p></li> <li><p>Silverlight supports the XmlDataProvider but not the ObjectDataProvider. WPF supports both.</p></li> <li><p>Silverlight can only make asynchronous network calls. WPF has access to the full .Net networking stack and can make any type of call. Also, currently, Silverlight supports SOAP, but can not handle SOAP fault exceptions natively (this may change in Silverlight 3).</p></li> <li><p>There are huge differences in Cryptography (Silverlight has 20 classes in the namespace, while WPF has access to 107). Basically, Silverlight supports only 4 hashing algorithms and the AES encryption protocol.</p></li> <li><p>Silverlight doesn't yet support: Commanding, Validation, Printing, XPS Documents, Speech, 3D, Freezable objects, or InterOp with the Windows Desktop; all of which are available in WPF.</p></li> <li><p>Silverlight supports browser interop, more media streaming options including timeline markers, and Deep Zoom. WPF doesn't support these features yet.</p></li> </ol> <p>This is by no means complete as I was trying to reduce a 70-page document into bullet points. </p> <p>Finally, even with all these differences, Microsoft is trying to close the gap between the two technologies. The Silverlight Toolkit and the WPF Toolkit both address some of the shortcomings of each technology. Silverlight 3 will be adding many features not currently available (such as element-to-element data binding). However, due to the differences in the core libraries, there will always be some Framework differences.</p>
17,479,465
Python: IndexError: list index out of range Error
<p><strong>Updated, look bottom!</strong></p> <p>I am stuck! I get a IndexError: list index out of range Error.</p> <pre><code>def makeInverseIndex(strlist): numStrList = list(enumerate(strlist)) n = 0 m = 0 dictionary = {} while (n &lt; len(strList)-1): while (m &lt; len(strlist)-1): if numStrList[n][1].split()[m] not in dictionary: dictionary[numStrList[n][1].split()[m]] = {numStrList[n][0]} m = m+1 elif {numStrList[n][0]} not in dictionary[numStrList[n][1].split()[m]]: dictionary[numStrList[n][1].split()[m]]|{numStrList[n][0]} m = m+1 n = n+1 return dictionary </code></pre> <p>it gives me this error</p> <pre><code>&gt;&gt;&gt; makeInverseIndex(s) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "./inverse_index_lab.py", line 23, in makeInverseIndex if numStrList[n][1].split()[m] not in dictionary: IndexError: list index out of range </code></pre> <p>I don't get it... what causes this? It happens even when I change the conditions of the while loop. I don't get what is the problem. I am pretty new at this, so explain it like you would if a piece of broccoli asked you this question.</p> <p><strong>Edit:</strong></p> <p>Thanks guys, I forgot to mention examples of input, I want to input something like this:</p> <pre><code> L=['A B C', 'B C E', 'A E', 'C D A'] </code></pre> <p>and get this as output:</p> <pre><code>D={'A':{0,2,3}, 'B':{0,1}, 'C':{0,3}, 'D':{3}, 'E':{1,2}} </code></pre> <p>so to create a dictionary that shows where in the list you might find a 'A' for example. It should work with a huge list. Do anyone have any tips? I want it to iterate and pick out each letter and then assign them a dictionary value.</p> <p><strong>Edit number two:</strong></p> <p>Thanks to great help from you guys my code looks beautiful like this:</p> <pre><code>def makeInverseIndex(strList): numStrList = list(enumerate(strList)) n = 0 dictionary = {} while (n &lt; len(strList)): for word in numStrList[n][1].split(): if word not in dictionary: dictionary[word] = {numStrList[n][0]} elif {numStrList[n][0]} not in dictionary[word]: dictionary[word]|={numStrList[n][0]} n = n+1 return dictionary </code></pre> <p>But I still manage to get this error when I try to run the module:</p> <pre><code> &gt;&gt;&gt; makeInverseIndex(L) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "./inverse_index_lab.py", line 21, in makeInverseIndex for word in numStrList[n][1].split(): NameError: global name 'StrList' is not defined </code></pre> <p>I do not see where the error can come from.</p>
17,479,804
3
3
null
2013-07-05 00:08:32.89 UTC
1
2018-05-09 18:44:40.063 UTC
2013-07-05 02:06:23.663 UTC
null
1,631,582
null
1,631,582
null
1
1
python|list|python-3.x
59,150
<p>Good to see some smart veggies programming.</p> <p>First, your question. Like @Vasiliy said, you have 3 indices. The <code>n</code> is alright, since you protect it with your <code>while</code> condition. The <code>1</code> is fine since <code>enumerate</code> always generates 2 things. That just leaves <code>m</code>. This is your problem.</p> <p>Let's say you have <code>N</code> elements in <code>strlist</code>. For each element <code>e</code> in <code>strlist</code>, you apply <code>split()</code> to it. The number of elements in <code>e.split()</code> is not always equal to <code>N</code>. The while condition for <code>m</code> guards against <code>N</code>, not against <code>len(e.split())</code>, hence the index out of range. </p> <p>To solve this, split the string first, and then loop through it. While you're at it, might as well get rid of <code>m</code> altogether, splitting the string only once, and gain some performance. Plus, you never reset your <code>m</code>, which just grows and grows. </p> <pre><code>while (n &lt; len(strList)): for word in numStrList[n][1].split(): if word not in dictionary: dictionary[word] = {numStrList[n][0]} elif {numStrList[n][0]} not in dictionary[word]: dictionary[word]|={numStrList[n][0]} n = n+1 </code></pre> <p>Second, your <code>while</code> conditions are too restrictive. <code>n &lt; len(strlist)</code> is fine. </p>
60,485,038
ng server - listen EACCES: permission denied 127.0.0.1:4200
<p>I have no problem in do ng serve using 127.0.0.1:4200.</p> <p>But today, when I do ng serve An unhandled exception occurred: listen EACCES: permission denied 127.0.0.1:4200</p> <p>Is there a way to solve this problem permanently? </p>
60,485,223
7
1
null
2020-03-02 08:33:39.45 UTC
8
2022-02-11 00:50:18.087 UTC
null
null
null
null
12,876,683
null
1
36
angular
32,228
<p>It sounds like your port is taken already.</p> <p>You should kill the use in port 4200.</p>
37,322,451
Difference between Admob Ads and Firebase Ads
<p>I'm trying to migrate from Google analytics to the new Firebase analytics but I noticed there are libraries for ads too. Are firebase ads going to replace admob ads as well? Should I keep using admob via google play services? Or make a switch to the Firebase SDK? What's the difference anyways?</p>
37,327,832
3
2
null
2016-05-19 11:54:48.063 UTC
2
2017-01-03 04:19:36.8 UTC
null
null
null
null
2,722,870
null
1
40
android|firebase|admob
18,770
<p>Happily, these are the same thing! The 'firebase-ads' dependency just brings in the existing 'play-services-ads' library and the 'firebase-analytics' library. The Firebase SDK is part of Google Play services, so no need to worry about migrating, just update to the latest version.</p> <p>Exactly as Kastriot says, the main integration is between Firebase Analytics and AdMob, but the AdMob SDK is still the same service you're already familiar with.</p>
20,686,099
How do I add multiple elements to an array?
<p>I can easily add one element to an existing array:</p> <pre><code>arr = [1] arr &lt;&lt; 2 # =&gt; [1, 2] </code></pre> <p>How would I add <strong>multiple</strong> elements to my array?</p> <p>I'd like to do something like <code>arr &lt;&lt; [2, 3]</code>, but this adds an array to my array <code>#=&gt; [1, [2, 3]]</code></p>
20,686,155
7
1
null
2013-12-19 15:56:15.35 UTC
8
2018-12-14 10:48:18.85 UTC
2018-12-14 10:48:18.85 UTC
null
2,235,594
null
2,235,594
null
1
64
arrays|ruby
47,003
<p>Using <code>+=</code> operator:</p> <pre><code>arr = [1] arr += [2, 3] arr # =&gt; [1, 2, 3] </code></pre>
32,589,087
Difference between views and viewsets?
<p>Maybe relevant: <a href="https://stackoverflow.com/q/32430689/11573842">What does django rest framework mean trade offs between view vs viewsets?</a></p> <p>What is the difference between <code>views</code> and <code>viewsets</code>? And what about <code>router</code> and <code>urlpatterns</code>?</p>
32,589,879
1
3
null
2015-09-15 14:47:55.093 UTC
36
2021-09-04 07:53:40.89 UTC
2021-09-04 07:48:49.72 UTC
null
11,573,842
null
2,154,440
null
1
84
django-rest-framework
30,182
<p><code>ViewSets</code> and <code>Routers</code> are simple tools to speed up the implementation of your API if you're aiming for standard behaviour and standard URLs.</p> <p>Using <code>ViewSet</code> you don't have to create separate views for getting a list of objects and detail of one object. <code>ViewSet</code> will handle for you in a consistent way both list and detail.</p> <p>Using <code>Router</code> will connect your <code>ViewSet</code> into &quot;standarized&quot; (it's not standard in any global way, just some structure that was implemented by creators of Django REST framework) structure of URLs. That way you don't have to create your <code>urlpatterns</code> by hand and you're guaranteed that all of your URLs are consistent (at least on the layer that <code>Router</code> is responsible for).</p> <p>It looks like not much, but when implementing some huge API where you will have many and many <code>urlpatterns</code> and views, using <code>ViewSets</code> and <code>Routers</code> will make big difference.</p> <p>For better explanation: this is code using <code>ViewSets</code> and <code>Routers</code>:</p> <p><code>views.py</code>:</p> <pre><code>from snippets.models import Article from rest_framework import viewsets from yourapp.serializers import ArticleSerializer class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer </code></pre> <p><code>urls.py</code>:</p> <pre><code>from django.conf.urls import url, include from yourapp import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'articles', views.ArticleViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] </code></pre> <p>And equivalent result using normal <code>Views</code> and no <code>routers</code>:</p> <p><code>views.py</code>:</p> <pre><code>from snippets.models import Article from snippets.serializers import ArticleSerializer from rest_framework import generics class ArticleList(generics.ListCreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer class ArticleDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer </code></pre> <p><code>urls.py</code></p> <pre><code>from django.conf.urls import url, include from yourapp import views urlpatterns = [ url(r'articles/^', views.ArticleList.as_view(), name=&quot;article-list&quot;), url(r'articles/(?P&lt;pk&gt;[0-9]+)/^', views.ArticleDetail.as_view(), name=&quot;article-detail&quot;), ] </code></pre>
4,839,657
How are threads tied to requests through Http.sys, IIS and ASP.NET
<p>I'm currently reading a lot about node.js. There is a frequent comparison between servers using a traditional thread per request model (Apache), and servers that use an event loop (Nginx, node, Tornado).</p> <p>I would like to learn in detail about how a request is processed in ASP.NET - from the point it is received in http.sys all the way up to it being processed in ASP.NET itself. I've found the MSDN documentation on http.sys and IIS a little lacking, but perhaps my google-fu is weak today. So far, the best resource I have found is a post on <a href="http://blogs.msdn.com/b/tmarq/archive/2007/07/21/asp-net-thread-usage-on-iis-7-0-and-6-0.aspx" rel="noreferrer">Thomas Marquardt's Blog</a>.</p> <p>Could anyone shed more light on the topic, or point me to any other resources?</p> <p>(For the purposes of this question I'm only interested in IIS7 with a typical integrated pipeline)</p>
4,841,725
1
2
null
2011-01-29 21:46:47.433 UTC
12
2011-01-30 08:09:47.633 UTC
2011-01-29 21:53:36.723 UTC
null
26,401
null
26,401
null
1
21
asp.net|multithreading|iis|http.sys
3,636
<p>From my research so far, its my understanding that when a request comes in it gets put into a kernel-mode request queue. According to <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/a2a45c42-38bc-464c-a097-d7a202092a54.mspx?mfr=true" rel="nofollow noreferrer">this</a>, this avoids many of the problems with context switching when there are massive amounts of requests (or processes or threads...), providing similar benefits to evented IO. Quoted from the article: </p> <blockquote> <p>"Each request queue corresponds to one application pool. An application pool corresponds to one request queue within HTTP.sys and one or more worker processes."</p> </blockquote> <p>So according to that, every request queue may have more than one "<a href="http://webcache.googleusercontent.com/search?q=cache:AWL9sOagVXUJ:technet.microsoft.com/en-us/library/cc735084(WS.10).aspx+worker+process&amp;cd=1&amp;hl=en&amp;ct=clnk&amp;gl=us&amp;source=www.google.com" rel="nofollow noreferrer">Worker Process</a>." (Google cache) <a href="http://www.codeproject.com/KB/aspnet/aspwp.aspx" rel="nofollow noreferrer">More on worker processes</a></p> <p>From my understanding: </p> <ul> <li>IIS Opens creates a request queue (see the http.sys api below)</li> <li>A "Web Site" configured in IIS corresponds to one Worker Process</li> <li>A Web Site/Worker Process <a href="http://madskristensen.net/post/Done28099t-use-the-ThreadPool-in-ASPNET.aspx#id_d9c9863f-d624-4ade-bdcc-0e990589380c" rel="nofollow noreferrer">shares</a> the Thread Pool.</li> <li>A thread is handed a request from the request queue.</li> </ul> <p>Here is a lot of great information about <a href="http://learn.iis.net/page.aspx/101/introduction-to-iis-7-architecture/" rel="nofollow noreferrer">IIS7's architecture</a> </p> <p>Here is some more information about <a href="http://msdn.microsoft.com/en-us/library/aa364621(v=vs.85).aspx" rel="nofollow noreferrer">http.sys</a>.</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ff384268(v=VS.85).aspx" rel="nofollow noreferrer">HTTP Server I/O Completion Stuff</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/aa364641(v=VS.85).aspx" rel="nofollow noreferrer">Typical Server Tasks</a></li> </ul> <p>Open questions i still have: </p> <ul> <li>How the heck does IIS change the Server header if it Uses HTTP.SYS? (<a href="https://stackoverflow.com/questions/427326/httplistener-server-header-c">See this question</a>)</li> </ul> <hr> <p>Note: I am not sure if/how a "Kernel-mode request queue" corresponds to an <a href="http://en.wikipedia.org/wiki/Input/output_completion_port" rel="nofollow noreferrer">IO completion port</a>, I would assume that each request would have its own but I don't know, so I truly hope someone will answer this more thoroughly. I just stumbled on <a href="https://stackoverflow.com/questions/4577193/using-httpapi-with-i-o-completion-ports">this question</a> and it seems that http.sys does in fact use IO Completion ports, which should provide nearly all of the same benifits that evented IO (node.js, nginx, lighttpd, C10K, etc...) have. </p>
60,217,202
Copy text to clipboard now that execCommand("copy") is obsolete
<p>I just saw on the Mozilla page that execCommand() is obsolete <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand</a></p> <p><em>"This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it."</em></p> <p>This is what I currently use to copy text to the user's clipboard when the user clicks a "copy text" button. Is there another way to do it?</p> <pre><code> var input = // input element with the text input.focus(); input.setSelectionRange(0,99999); document.execCommand("copy"); input.blur(); </code></pre> <p>Edit: This <a href="https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript">How do I copy to the clipboard in JavaScript?</a> does not answer the question. It suggests the same obsolete solution.</p>
60,239,236
1
3
null
2020-02-13 22:07:54.177 UTC
4
2020-02-15 14:47:53.163 UTC
2020-02-13 22:28:55.443 UTC
null
984,003
null
984,003
null
1
30
javascript
12,553
<p>From Klaycon's comment to the question. The replacement is the Clipboard API. It is not implemented in all browsers, but most.</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API</a></p> <pre><code>// In this example, the text to copy would be in an element with id = textcopy var text_to_copy = document.getElementById("textcopy").innerHTML; if (!navigator.clipboard){ // use old commandExec() way } else{ navigator.clipboard.writeText(text_to_copy).then( function(){ alert("yeah!"); // success }) .catch( function() { alert("err"); // error }); } </code></pre> <p>For some browsers (like Firefox) this only works when initiated by a user action. So, put the code inside a button listener, for example.</p> <p>I tested this (Feb 2020) in (Windows) Chrome, Firefox, new Edge, Opera, iOS Safari, iOS Chrome, iOS app webview. Clipboard writeText works great. </p>
26,715,783
ReSharper function shows "Files still read-only"
<p>When I try to "Remove Unused References" on some projects, resharper shows a window with a message: Refactoring failed "Files still read-only" Files are not read-only, I can edit them. VS2013, with update 3.</p>
26,751,384
7
0
null
2014-11-03 13:53:01.953 UTC
1
2022-08-15 16:32:16.163 UTC
2021-10-04 06:40:57.807 UTC
null
66,207
null
35,150
null
1
31
visual-studio|visual-studio-2013|resharper
5,614
<p>Change a value to None for &quot;Current source control plug-in:&quot; combobox here Tools | Options | Source Control | Plugin Selection. It seems as if &quot;Microsoft Git provider&quot; is selected there now. And it is <a href="https://youtrack.jetbrains.com/issue/RSRP-338404" rel="nofollow noreferrer">a known issue</a> due to a bug in &quot;Microsoft Git provider&quot; shipped with VS 2013.</p> <p><a href="https://i.stack.imgur.com/VRcqS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VRcqS.png" alt="enter image description here" /></a></p> <p>[August 2022] Update for users of VS2019: If you have recently started experiencing this issue, please follow <a href="https://youtrack.jetbrains.com/issue/RSRP-485369/Refactoring-failed-Files-still-read-only#focus=Comments-27-6352457.0-0" rel="nofollow noreferrer">this workaround</a>.</p>
26,637,660
How do I use FIDO U2F to allow users to authenticate with my website?
<p>With all the recent buzz around the FIDO U2F specification, I would like to implement FIDO U2F test-wise on a testbed to be ready for the forthcoming roll out of the final specification.</p> <p>So far, I have a FIDO U2F security key produced by Yubico and the FIDO U2F (Universal 2nd Factor) extension installed in Chrome. I have also managed to set up the security key to work with my Google log-in.</p> <p>Now, I'm not sure how to make use of this stuff for my own site. I have looked through Google's Github page for the U2F project and I have checked their <a href="https://github.com/google/u2f-ref-code/blob/master/u2f-ref-code/html/enroll.html">web app front-end</a>. It looks really simple (JavaScript only). So is implementing second factor auth with FIDO as simple as implementing a few JavaScript calls? All that seems to be happening for the registration in the example is this:</p> <pre><code> var registerRequest = { appId: enrollData.appId, challenge: enrollData.challenge, version: enrollData.version }; u2f.register([registerRequest], [], function (result) { if (result.errorCode) { document.getElementById('status') .innerHTML = "Failed. Error code: " + result.errorCode; return; } document.location = "/enrollFinish" + "?browserData=" + result.clientData + "&amp;enrollData=" + result.registrationData + "&amp;challenge=" + enrollData.challenge + "&amp;sessionId=" + enrollData.sessionId; }); </code></pre> <p>But how can I use that for an implementation myself? Will I be able to use the callback from this method call for the user registration?</p>
26,640,348
2
0
null
2014-10-29 18:07:37.157 UTC
32
2017-03-24 20:15:26.297 UTC
2015-05-28 04:14:18.797 UTC
null
3,558,960
null
4,195,277
null
1
37
google-chrome|authentication|fido-u2f
20,991
<p>What you are trying to do is implement a so called "relying party", meaning that your web service will rely on the identity assertion provided by the FIDO U2F token.</p> <p>You will need to understand the <a href="https://fidoalliance.org/specifications/download" rel="noreferrer">U2F specifications</a> to do that. Especially how the challenge-response paradigm is to be implemented and how app ids and facets work. This is described in the spec in detail.</p> <p>You are right: The actual code necessary to work with FIDO U2F from the front end of you application is almost trivial (that is, if you use the "high-level" JavaScript API as opposed to the "low-level" MessagePort API). Your application will however need to work with the messages generated by the token and validate them. This is not trivial.</p> <p>To illustrate how you could pursue implementing a relying party site, I will give a few code examples, taken from a <a href="https://github.com/mplatt/virtual-u2f" rel="noreferrer">Virtual FIDO U2F Token Extension</a> that I have programmed lately for academic reasons. You can see the page for the full example code.</p> <hr> <p>Before your users can use their FIDO U2F tokens to authenticate, they need to <strong>register</strong> it with you. In order to allow them to do so, you need to call <code>window.u2f.register</code> in their browser. To do that, you need to provide a few parameters (again; read the spec for details). Among them a <em>challenge</em> and the <em>id</em> of your app. For a web app, this <em>id</em> must be the web origin of the web page triggering the FIDO operation. Let's assume it is <code>example.org</code>:</p> <pre class="lang-js prettyprint-override"><code>window.u2f.register([ { version : "U2F_V2", challenge : "YXJlIHlvdSBib3JlZD8gOy0p", appId : "http://example.org", sessionId : "26" } ], [], function (data) { }); </code></pre> <p>Once the user performs a "user presence test" (e.g. by touching the token), you will receive a response, which is a JSON object (see spec for more details)</p> <pre class="lang-js prettyprint-override"><code>dictionary RegisterResponse { DOMString registrationData; DOMString clientData; }; </code></pre> <p>This data contains several elements that your application needs to work with.</p> <p><img src="https://i.stack.imgur.com/dApXP.png" alt="Register Map of a FIDO U2F Registration Response Message"></p> <ol> <li>The public key of the generated key pair -- You need to store this for future authentication use.</li> <li>The key handle of the generated key pair -- You also need to store this for future use.</li> <li>The certificate -- You need to check whether you trust this certificate and the CA.</li> <li>The signature -- You need to check whether the signature is valid (i.e. confirms to the key stored with the certificate) and whether the data signed is the data expected.</li> </ol> <p>I have prepared a <a href="https://github.com/mplatt/virtual-u2f#rp-server-side" rel="noreferrer">rough implementation draft</a> for the relying party server in Java that shows how to extract and validate this information lately.</p> <hr> <p>Once the registration is complete and you have <em>somehow</em> stored the details of the generated key, you can <strong>sign</strong> requests.</p> <p>As you said, this can be initiated short and sweet through the high-level JavaScript API:</p> <pre class="lang-js prettyprint-override"><code>window.u2f.sign([{ version : "U2F_V2", challenge : "c3RpbGwgYm9yZWQ/IQ", app_id : "http://example.org", sessionId : "42", keyHandle: "ZHVtbXlfa2V5X2hhbmRsZQ" }], function (data) { }); </code></pre> <p>Here, you need to provide the key handle, <em>you have obtained during registration</em>. Once again, after the user performs a "user presence test" (e.g. by touching the token), you will receive a response, which is a JSON object (again, see spec for more details)</p> <pre class="lang-js prettyprint-override"><code>dictionary SignResponse { DOMString keyHandle; DOMString signatureData; DOMString clientData; }; </code></pre> <p>You the need to validate the signature data contained herein.</p> <p><img src="https://i.stack.imgur.com/4s1WE.png" alt="Register Map of a FIDO U2F Authentication Response Message"></p> <ol> <li>You need to make sure that the signature matches the public key you have obtained before.</li> <li>You also need to validate that the string signed is appropriate.</li> </ol> <p>Once you have performed these validations, you can consider the user authenticated. A brief example implementation of the server side code for that is also contained in my <a href="https://github.com/mplatt/virtual-u2f#rp-server-side-1" rel="noreferrer">server example</a>.</p>
6,356,074
iPhone browser defaulting to uppercase for first letter of password fields
<p>I'm writing a login page for a mobile version of my webapp and I have a simple HTML password field like so:</p> <pre><code>&lt;input id="password" type="password" /&gt; </code></pre> <p>The only problem is that the iPhone Safari browser capitalizes the first letter of the input by default, which is confusing my users as the password is case sensitive and they do not always realise this is the case.</p> <p>Does anyone know of a method, tag or otherwise to stop this happening and force the iPhone input to lowercase unless the user specifies otherwise? Or is this simply a feature of the platform that can't be changed?</p>
6,356,275
2
1
null
2011-06-15 10:07:43.423 UTC
15
2015-11-16 15:47:52.643 UTC
2013-12-12 15:28:49.183 UTC
null
1,709,587
null
744,306
null
1
87
iphone|html|user-interface|safari
30,481
<pre><code>&lt;input type="text" name="test1" autocapitalize="none"/&gt; </code></pre> <p>The docs can be found here: <a href="https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html#//apple_ref/doc/uid/TP40008058-autocapitalize" rel="noreferrer">Supported Attributes: autocapitalize</a></p>
7,514,021
Android AsyncTask and SQLite DB instance
<p>I have a problem and I am not sure how to approach it. An activity in my app has multiple <code>AsyncTask</code>s which access single <code>SQLiteOpenHelper</code>. I initialize and open the helper in <code>onCreate()</code> and I am closing it in <code>onStop()</code>. I also check if it has been initialized in <code>onResume()</code>.</p> <p>Since I have published my app I received number of errors with Null Exception in <code>doInBackground</code> where I try to access the DB helper. I know that this is happens because the DB is closed ( <code>onStop()</code> ) just before the <code>doInBackground</code> is called, fair enough.</p> <p>My question is, where should I close the DB connection? Is it right to use a single instance of the DB helper in the Activity and access it from multiple threads(<code>AsyncTasks</code>)? Or I should use separate DB helper instance for each <code>AsyncTask</code>?</p> <p>This is a simplified skeleton of my activity:</p> <pre><code>public class MyActivity extends Activity{ private DbHelper mDbHelper; private ArrayList&lt;ExampleObject&gt; objects; @Override public void onStop(){ super.onStop(); if(mDbHelper != null){ mDbHelper.close(); mDbHelper = null; } } @Override public void onResume(){ super.onResume(); if(mDbHelper == null){ mDbHelper = new DbHelper(this); mDbHelper.open(); } } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); DbHelper mDbHelper = new DbHelper(this); mDbHelper.open(); } private class DoSomething extends AsyncTask&lt;String, Void, Void&gt; { @Override protected Void doInBackground(String... arg0) { objects = mDbHelper.getMyExampleObjects(); return null; } @Override protected void onPostExecute(final Void unused){ //update UI with my objects } } private class DoSomethingElse extends AsyncTask&lt;String, Void, Void&gt; { @Override protected Void doInBackground(String... arg0) { objects = mDbHelper.getSortedObjects(); return null; } @Override protected void onPostExecute(final Void unused){ //update UI with my objects } } } </code></pre>
7,514,440
3
0
null
2011-09-22 11:29:34.537 UTC
12
2015-06-22 09:13:04.677 UTC
2012-08-06 15:56:21.04 UTC
null
403,455
null
400,493
null
1
8
android|sqlite|android-asynctask|sqliteopenhelper
12,673
<p>You mentioned that you cancel the AsyncTask before closing the DB. But you should keep in mind that cancelling the AsyncTask just signals the task to be cancelled and you need to check isCancelled() in doInBackground() and do the needful to stop DB operations.</p> <p>Before closing the DB, you then need to check getStatus() to be sure that the AsyncTask has stopped.</p>
7,281,045
Why do I get org.hibernate.HibernateException: No CurrentSessionContext configured
<p>I'm writing a simple project, a business app written in Swing, using Hibernate for back-end. I come from Spring, that gave me easy ways to use hibernate and transactions. Anyway I managed to have Hibernate working. Yesterday, while writing some code to delete a bean from DB, I got this: </p> <pre><code>org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions </code></pre> <p>The deletion code is simply:</p> <pre><code> Session sess = HibernateUtil.getSession(); Transaction tx = sess.beginTransaction(); try { tx.begin(); sess.delete(ims); } catch (Exception e) { tx.rollback(); throw e; } tx.commit(); sess.flush(); </code></pre> <p>and my <code>HibernateUtil.getSession()</code> is:</p> <pre><code> public static Session getSession() throws HibernateException { Session sess = null; try { sess = sessionFactory.getCurrentSession(); } catch (org.hibernate.HibernateException he) { sess = sessionFactory.openSession(); } return sess; } </code></pre> <p>additional details: I never close a hibernate session in my code, just on application closing. Is this wrong? Why do I get this on delete (only for that bean, others do work), and I don't on other operations (Insert, query, update)?</p> <p>I read around and I tried to modify my <code>getSession</code> method simply in a <code>sessionFactory.getCurrentSessionCall()</code>, but I got: <code>org.hibernate.HibernateException: No CurrentSessionContext configured!</code></p> <p>Hibernat conf:</p> <pre><code>&lt;hibernate-configuration&gt; &lt;session-factory &gt; &lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt; &lt;property name="hibernate.connection.driver_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt; &lt;property name="hibernate.connection.url"&gt;jdbc:mysql://localhost/joptel&lt;/property&gt; &lt;property name="hibernate.connection.username"&gt;root&lt;/property&gt; &lt;property name="hibernate.connection.password"&gt;******&lt;/property&gt; &lt;property name="hibernate.connection.pool_size"&gt;1&lt;/property&gt; &lt;property name="show_sql"&gt;true&lt;/property&gt; &lt;property name="hibernate.hbm2ddl.auto"&gt;update&lt;/property&gt; ..mappings.. &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre>
7,293,252
3
1
null
2011-09-02 08:38:42.247 UTC
5
2015-11-19 08:44:09.213 UTC
2013-03-31 21:10:32.237 UTC
null
544,277
null
138,606
null
1
21
java|hibernate
63,304
<p>I wanted to ask you one thing, why are you trying to use "OpenSession" method?</p> <pre><code>public static Session getSession() throws HibernateException { Session sess = null; try { sess = sessionFactory.getCurrentSession(); } catch (org.hibernate.HibernateException he) { sess = sessionFactory.openSession(); } return sess; } </code></pre> <p>You don't have to call <code>openSession()</code>, because <code>getCurrentSession()</code> method is always returns current session (Thread in case if you have configured it to be). </p> <p>I got it!... You have to specify current context in your hibernate.cfg.xml file</p> <p>it should be: </p> <pre><code>&lt;property name="hibernate.current_session_context_class"&gt;thread&lt;/property&gt; </code></pre>
7,206,978
How to pass an array via $_GET in php?
<p>How can I pass one or more variables of type array to another page via $_GET?</p> <p>I always passed variable values in the form <code>?a=1&amp;b=2&amp;c=3</code></p> <p>What about passing <code>a=[1,2,3]</code> ?</p> <p>Do I need to write a for loop and append all the values?</p> <p>Thanks</p>
7,207,010
4
1
null
2011-08-26 15:21:27.013 UTC
13
2016-02-14 07:04:25.72 UTC
2011-08-26 15:24:19.267 UTC
null
576,875
null
231,740
null
1
43
php|arrays|get
81,649
<p>You can use the <code>[]</code> syntax to pass arrays through _GET:</p> <pre><code>?a[]=1&amp;a[]=2&amp;a[]=3 </code></pre> <p>PHP understands this syntax, so <code>$_GET['a']</code> will be equal to <code>array(1, 2, 3)</code>.</p> <p>You can also specify keys:</p> <pre><code>?a[42]=1&amp;a[foo]=2&amp;a[bar]=3 </code></pre> <p>Multidimentional arrays work too:</p> <pre><code>?a[42][b][c]=1&amp;a[foo]=2 </code></pre> <p><a href="http://php.net/http_build_query" rel="noreferrer"><code>http_build_query()</code></a> does this automatically:</p> <pre><code>http_build_query(array('a' =&gt; array(1, 2, 3))) // "a[]=1&amp;a[]=2&amp;a[]=3" http_build_query(array( 'a' =&gt; array( 'foo' =&gt; 'bar', 'bar' =&gt; array(1, 2, 3), ) )); // "a[foo]=bar&amp;a[bar][]=1&amp;a[bar][]=2&amp;a[bar][]=3" </code></pre> <hr> <p>An alternative would be to pass json encoded arrays:</p> <pre><code>?a=[1,2,3] </code></pre> <p>And you can parse <code>a</code> with <code>json_decode</code>:</p> <pre><code>$a = json_decode($_GET['a']); // array(1, 2, 3) </code></pre> <p>And encode it again with json_encode:</p> <pre><code>json_encode(array(1, 2, 3)); // "[1,2,3]" </code></pre> <hr> <p><strong>Dont ever use <code>serialize()</code> for this purpose</strong>. Serialize allows to serialize objects, and there is ways to make them execute code. So you should never deserialize untrusted strings.</p>
7,860,362
How can I use openssl/md5 in C++ to hash a string?
<p>I need to hash with md5 algorithm a string in my program. There is the lib openssl but I'm a newbie about it. How is possible hash a string using that and where I can find a good doc that teach me how to use this lib, also with other function like aes?</p> <p>I've tried this code:</p> <pre><code>int main() { unsigned char result[MD5_DIGEST_LENGTH]; const unsigned char* str; str = (unsigned char*)&quot;hello&quot;; unsigned int long_size = 100; MD5(str,long_size,result); } </code></pre> <p>But the compiler told me: undefined reference to <code>MD5</code>.</p> <p>Why is there and undefined reference to <code>MD5</code>?</p>
7,860,412
1
4
null
2011-10-22 14:51:18.41 UTC
3
2021-03-14 19:20:07.143 UTC
2021-03-14 19:20:07.143 UTC
user840718
10,514,096
user840718
null
null
1
4
c|openssl|aes|md5
41,430
<p>You should take a look at the <a href="https://www.openssl.org/docs/man1.0.2/crypto/md5.html" rel="noreferrer">documentation</a>. An option is to use this function:</p> <pre><code>#include &lt;openssl/md5.h&gt; unsigned char *MD5(const unsigned char *d, unsigned long n, unsigned char *md); </code></pre> <p>To which they state: </p> <blockquote> <p>MD2(), MD4(), and MD5() compute the MD2, MD4, and MD5 message digest of the <code>n</code> bytes at <code>d</code> and place it in <code>md</code> (which must have space for MD2_DIGEST_LENGTH == MD4_DIGEST_LENGTH == MD5_DIGEST_LENGTH == 16 bytes of output). If <code>md</code> is NULL, the digest is placed in a static array.</p> </blockquote> <p>As for AES, if you also want to use OpenSSL, then take a look at <a href="https://www.openssl.org/docs/man1.0.2/crypto/evp.html" rel="noreferrer">EVP doc</a> and <a href="https://github.com/saju/misc/blob/master/misc/openssl_aes.c" rel="noreferrer">this example</a> of how to use it. Just note that you have to add</p> <pre><code>#define AES_BLOCK_SIZE 16 </code></pre> <p>In the top of the file for it to work, though.</p> <p>Btw. I can really recommend the <a href="http://www.cryptopp.com/" rel="noreferrer">Crypto++ library</a> since it's great and has all kinds of cryptographic primitives; AES, Elliptic Curves, MAC, public-key crypto and so on. </p>
7,765,484
Xcode 4.2 - declaration of '...' will not be visible outside of this function warning
<p>I use Apple Reachability class from Apple Sample code <a href="http://developer.apple.com/library/ios/#samplecode/Reachability/Listings/ReadMe_txt.html" rel="noreferrer">Reachability</a></p> <p>in Xcode 4.2 and new Apple 3.0 compiler I get warning in this class that</p> <pre><code>+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress; </code></pre> <p><em>declaration of 'struct sockaddr_in</em>' will not be visible outside of this function* </p> <p>I am not good at classic C %) so I dont understand how I can fix this warning or may be I can ignore it at all. </p> <p>Thx</p>
7,765,622
1
1
null
2011-10-14 09:14:08.373 UTC
29
2013-06-18 10:17:55.627 UTC
2013-06-18 10:17:55.627 UTC
null
1,411,844
null
237,734
null
1
160
iphone|ios|xcode4|ios5
22,234
<p>Add <code>#import &lt;netinet/in.h&gt;</code> in Reachability.h to get away with this</p>
1,652,995
In Oracle, is it possible to INSERT or UPDATE a record through a view?
<p>In Oracle, is it possible to INSERT or UPDATE a record (a row) through a view?</p>
1,653,192
4
1
null
2009-10-31 00:46:17.58 UTC
11
2016-02-02 10:46:00.583 UTC
2009-10-31 01:01:16.35 UTC
null
196,526
null
196,526
null
1
41
sql|oracle|plsql|views
140,490
<p>Views in Oracle <em>may</em> be updateable under specific conditions. It can be tricky, and <em>usually</em> is not advisable.</p> <p>From the <a href="http://download.oracle.com/docs/cd/B14117_01/server.101/b10759/statements_8004.htm" rel="noreferrer">Oracle 10g SQL Reference</a>:</p> <p>Notes on Updatable Views</p> <p>An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.</p> <p>To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:</p> <ul> <li>Each column in the view must map to a column of a single table. For example, if a view column maps to the output of a TABLE clause (an unnested collection), then the view is not inherently updatable.</li> <li>The view must not contain any of the following constructs: <ul> <li>A set operator</li> <li>a DISTINCT operator</li> <li>An aggregate or analytic function</li> <li>A GROUP BY, ORDER BY, MODEL, CONNECT BY, or START WITH clause</li> <li>A collection expression in a SELECT list</li> <li>A subquery in a SELECT list</li> <li>A subquery designated WITH READ ONLY</li> <li>Joins, with some exceptions, as documented in Oracle Database Administrator's Guide</li> </ul></li> </ul> <p>In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.</p> <p>If you want a join view to be updatable, then all of the following conditions must be true:</p> <ul> <li>The DML statement must affect only one table underlying the join.</li> <li>For an INSERT statement, the view must not be created WITH CHECK OPTION, and all columns into which values are inserted must come from a key-preserved table. A key-preserved table is one for which every primary key or unique key value in the base table is also unique in the join view.</li> <li>For an UPDATE statement, all columns updated must be extracted from a key-preserved table. If the view was created WITH CHECK OPTION, then join columns and columns taken from tables that are referenced more than once in the view must be shielded from UPDATE.</li> <li>For a DELETE statement, if the join results in more than one key-preserved table, then Oracle Database deletes from the first table named in the FROM clause, whether or not the view was created WITH CHECK OPTION.</li> </ul>
52,712,063
build failing during merge resources with Android Gradle plugin 3.3.0
<p>I have a lot of different flavors for my build that have specific resources and I don't want to clutter my src directory in my project with a bunch of flavor-specific directories, so I add the source sets from another folder in my project prior to the mergeResources task (mergeResources.doFirst). This has always worked for the past several versions of the Android Gradle plug-in (3.1.0-3.2.0 and some of the 3.3.0-alpha versions), but at a certain point, the 3.3.0-alpha AGP started causing build failures during this mergeResources task. </p> <p>Now I keep getting:</p> <blockquote> <p>BUILD FAILED in 35s 16 actionable tasks: 15 executed, 1 up-to-date Exception in thread "ForkJoinPool.commonPool-worker-6" java.lang.IllegalStateException: AAPT Process manager cannot be shut down while daemons are in use at com.android.builder.internal.aapt.v2.Aapt2DaemonManager.shutdown(Aapt2DaemonManager.kt:96) at com.android.build.gradle.internal.res.namespaced.RegisteredAaptService.shutdown(Aapt2DaemonManagerService.kt:61) at com.android.build.gradle.internal.workeractions.WorkerActionServiceRegistry$shutdownAllRegisteredServices$1$1.run(WorkerActionServiceRegistry.kt:96) at java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1402) at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289) at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056) at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692) at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)</p> </blockquote> <p>My stacktrace is:</p> <blockquote> <p>Execution failed for task ':app:mergeMainReleaseResources'. java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.3.0-alpha13-5013011-windows Daemon #0: Unexpected error during compile 'C:\Users\Alex\Documents\Work\Android\project\app\productio n_resources\categories\fitness\res\drawable-xxxhdpi\background_4.png', attempting to stop daemon. This should not happen under normal circumstances, please file an issue if it does.</p> <p>Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeMainReleaseResources'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77) at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59) at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101) at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44) at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91) at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51) at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300) at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292) at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174) at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90) at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46) at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:277) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:262) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)</p> <p>Caused by: org.gradle.internal.UncheckedException: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.3.0-alpha13-5013011-windows Daemon #0: Unexpected error during compile 'C:\Users\Alex \Documents\Work\Android\project\app\production_resources\categories\fitness\res\drawable-xxxhdpi\background_4.png', attempting to stop daemon. This should not happen under normal circumstances, please file an issue if it does. at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:63) at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:40) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:76) at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131) at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300) at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292) at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174) at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90) at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99) ... 31 more Caused by: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.3.0-alpha13-5013011-windows Daemon #0: Unexpected error during compile 'C:\Users\Alex\Documents\Work\Android\project\app\ production_resources\categories\fitness\res\drawable-xxxhdpi\background_4.png', attempting to stop daemon. This should not happen under normal circumstances, please file an issue if it does. at com.android.ide.common.workers.ExecutorServiceAdapter.close(ExecutorServiceAdapter.kt:56) at com.android.build.gradle.internal.aapt.WorkerExecutorResourceCompilationService.close(WorkerExecutorResourceCompilationService.kt:67) at com.android.build.gradle.tasks.MergeResources.doFullTaskAction(MergeResources.java:268) at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:106) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73) ... 42 more</p> <p>Caused by: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.3.0-alpha13-5013011-windows Daemon #0: Unexpected error during compile 'C:\Users\Alex\Documents\Work\Android\project\app\production_resources\categories\fitness\res\drawable-xxxhdpi\background_4.png', attempting to stop daemon. This should not happen under normal circumstances, please file an issue if it does. at com.android.builder.internal.aapt.v2.Aapt2Daemon.handleError(Aapt2Daemon.kt:148) at com.android.builder.internal.aapt.v2.Aapt2Daemon.compile(Aapt2Daemon.kt:88) at com.android.builder.internal.aapt.v2.Aapt2DaemonManager$LeasedAaptDaemon.compile(Aapt2DaemonManager.kt:170) at com.android.build.gradle.internal.res.Aapt2CompileWithBlameRunnable$run$1.invoke(Aapt2CompileWithBlameRunnable.kt:37) at com.android.build.gradle.internal.res.Aapt2CompileWithBlameRunnable$run$1.invoke(Aapt2CompileWithBlameRunnable.kt:28) at com.android.build.gradle.internal.res.namespaced.Aapt2DaemonManagerService.useAaptDaemon(Aapt2DaemonManagerService.kt:71) at com.android.build.gradle.internal.res.namespaced.Aapt2DaemonManagerService.useAaptDaemon$default(Aapt2DaemonManagerService.kt:69) at com.android.build.gradle.internal.res.Aapt2CompileWithBlameRunnable.run(Aapt2CompileWithBlameRunnable.kt:34) at com.android.ide.common.workers.ExecutorServiceAdapter$submit$submission$1.run(ExecutorServiceAdapter.kt:39)</p> <p>Caused by: java.io.IOException: AAPT2 process unexpectedly exit. Error output: at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl$WaitForTaskCompletion.err(Aapt2DaemonImpl.kt:309) at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl$processOutput$1.err(Aapt2DaemonImpl.kt:75) at com.android.utils.GrabProcessOutput$1.run(GrabProcessOutput.java:104)</p> </blockquote> <p>I thought maybe the PNG file was corrupted or incorrectly labeled, but I've run it through a whole bunch of conversions and I get the same error.</p> <p>During testing, it works fine, but during the release builds is when I get this error. I've resorted to building using AS 3.2 and AGP 3.2.0 for my production builds, which works fine. Also, this is Windows only. It works fine on my Mac.</p> <p>My build.gradle is:</p> <pre><code>apply plugin: 'com.android.application' apply plugin: 'io.fabric' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion '28.0.3' defaultConfig { applicationId "com.project.test" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 37 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" multiDexEnabled true } dexOptions { jumboMode true javaMaxHeapSize "4g" preDexLibraries = false } sourceSets { debug.setRoot('build-types/debug') release.setRoot('build-types/release') androidTest.setRoot('tests') } signingConfigs { key { storeFile file(RELEASE_STORE_FILE) storePassword RELEASE_STORE_PASSWORD keyAlias RELEASE_KEY_ALIAS keyPassword RELEASE_KEY_PASSWORD } } buildTypes { debug { minifyEnabled false } release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' signingConfig signingConfigs.key } } flavorDimensions "default" productFlavors { main { versionName "0" buildConfigField "String", "CATEGORY", "\"fitness\"" buildConfigField "String", "BUILD_VERSION", "\"$config.buildVersion\"" dimension "default" } flavors.each { name, flavor -&gt; "$name" { applicationId = config.applicationId + "." + "$name" versionName = config.versionName versionCode = flavor.versionCode buildConfigField "String", "CATEGORY", "\"${flavor.category}\"" buildConfigField "String", "BUILD_VERSION", "\"$config.buildVersion\"" buildConfigField "String", "APP_ID", "\"$name\"" resValue "string", "APP_NAME", flavor.appName dimension "default" } } } packagingOptions { exclude 'META-INF/rxjava.properties' } configurations.all { resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', { exclude group: 'com.android.support', module: 'support-annotations' }) androidTestImplementation('com.android.support.test:runner:1.0.1', { exclude group: 'com.android.support', module: 'support-annotations' }) implementation 'com.google.code.findbugs:jsr305:3.0.2' implementation "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion" implementation "com.android.support:support-v4:$rootProject.supportLibraryVersion" implementation "com.android.support:design:$rootProject.supportLibraryVersion" implementation "com.android.support:cardview-v7:$rootProject.supportLibraryVersion" implementation "com.android.support:customtabs:$rootProject.supportLibraryVersion" implementation 'com.android.support:multidex:1.0.3' implementation 'com.android.billingclient:billing:1.1' implementation "com.squareup.retrofit2:retrofit:$rootProject.retrofitVersion" implementation "com.squareup.retrofit2:converter-gson:$rootProject.retrofitVersion" implementation "com.squareup.retrofit2:adapter-rxjava2:$rootProject.retrofitVersion" implementation 'com.squareup.okhttp3:okhttp:3.11.0' implementation 'com.google.code.gson:gson:2.8.5' implementation "com.facebook.fresco:fresco:$rootProject.frescoVersion" implementation "com.facebook.fresco:animated-gif:$rootProject.frescoVersion" implementation "com.google.android.gms:play-services-auth:$rootProject.playServicesVersion" implementation "com.google.android.gms:play-services-gcm:$rootProject.playServicesVersion" implementation "com.google.android.gms:play-services-base:$rootProject.playServicesVersion" implementation "com.google.android.gms:play-services-ads:$rootProject.playServicesVersion" implementation('com.crashlytics.sdk.android:crashlytics:2.9.4@aar') { transitive = true } implementation 'com.mixpanel.android:mixpanel-android:5.2.1' implementation "com.google.dagger:dagger:$rootProject.daggerVersion" implementation "com.google.dagger:dagger-android-support:$rootProject.daggerVersion" annotationProcessor "com.google.dagger:dagger-compiler:$rootProject.daggerVersion" implementation "com.jakewharton:butterknife:$rootProject.butterknifeVersion" annotationProcessor "com.jakewharton:butterknife-compiler:$rootProject.butterknifeVersion" implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' implementation 'io.reactivex.rxjava2:rxjava:2.2.0' implementation 'com.github.JakeWharton:ViewPagerIndicator:2.4.1' implementation "com.google.android.exoplayer:exoplayer-core:$rootProject.exoPlayerVersion" implementation "com.google.android.exoplayer:exoplayer-hls:$rootProject.exoPlayerVersion" implementation "com.google.android.exoplayer:exoplayer-ui:$rootProject.exoPlayerVersion" testImplementation 'junit:junit:4.12' } android.applicationVariants.all { variant -&gt; def category variant.productFlavors.each { flavor -&gt; flavor.buildConfigFields.each { key, value -&gt; if (key == "CATEGORY") { category = value.value.substring(1, value.value.length() - 1) } } } variant.mergeResources.doFirst { android.sourceSets."${variant.productFlavors.get(0).name}".res.srcDirs = ["production_resources/flavors/${variant.productFlavors.get(0).name}/res", "production_resources/categories/${category}/res"] } } afterEvaluate { tasks.matching { it.name.startsWith('dex') }.each { dx -&gt; if (dx.additionalParameters == null) { dx.additionalParameters = [] } dx.additionalParameters += '--multi-dex' dx.additionalParameters += "--main-dex-list=$projectDir/&lt;filename&gt;".toString() } } apply plugin: 'com.google.gms.google-services' </code></pre>
54,615,423
12
5
null
2018-10-09 01:19:30.617 UTC
15
2021-08-30 07:22:11.443 UTC
2018-10-12 18:52:01.28 UTC
null
3,000,393
null
3,000,393
null
1
40
android|gradle|android-gradle-plugin|gradle-plugin
63,714
<p><strong>Updated 19th April, 2019</strong></p> <p>This issue has been fixed in <code>Android Gradle Plugin 3.4.0</code>.</p> <p>After upgrading to Android Studio 3.4.0, the temporary fix suggested in the original answer can be removed. Hurray!</p> <p><strong>Original</strong></p> <p>This is a bug in AAPT2 in Android Gradle Plugin 3.3.0, when building a project with larger png's (around 2-3 mb and up).</p> <p>@akong9759 created an issue for this on Googles issue tracker and it has been fixed.</p> <p><a href="https://issuetracker.google.com/issues/117900475" rel="noreferrer">https://issuetracker.google.com/issues/117900475</a></p> <p>The problem has been fixed in Android Gradle Plugin 3.5.0-alpha03 and the fix is scheduled to be released in version 3.4.0.</p> <p>A temporary fix for Android Gradle Plugin 3.3.0 has been suggested on the issue. Add the following to the project <code>build.gradle</code>:</p> <pre><code>allprojects { // Workaround for https://issuetracker.google.com/117900475 // Remove when upgrading to AGP 3.4 or higher. configurations.matching { it.name == '_internal_aapt2_binary' }.all { config -&gt; config.resolutionStrategy.eachDependency { details -&gt; details.useVersion("3.5.0-alpha03-5252756") } } } </code></pre>
7,451,468
Contenteditable DIV - how can I determine if the cursor is at the start or end of the content
<p>I have a contenteditable div which contains typical wysiwyg editor html (bold, anchors, lists).</p> <p>I need to determine if the current cursor is, onKeyDown, at the start and at the end of the div. The reason for this is, based on the cursor position, and the key pressed, I might want to merge this div with the previous div on a backspace, or create a new following div on enter.</p> <p>I've been fiddling around with ranges, but when you're working with html inside the element, things get pretty complicated.</p> <p>I'm hoping I must be overlooking some simple solution. </p> <p>Is there a relatively simple way to determine this - I'm open to using a library like Rangy.</p> <p>Thanks!</p> <p>Edit: I'm thinking something along these lines:</p> <pre><code>$('.mycontenteditable').bind('keydown', handle_keydown) handle_keydown = function(e) { range = window.getSelection().getRangeAt(0) start_range = document.createRange() start_range.selectNodeContents(this.firstChild) start_range.collapse(true) // collapse to start is_start = start_range.compareBoundaryPoints(Range.START_TO_START,range) end_range = document.createRange() end_range.selectNodeContents(this.lastChild) end_range.collapse(false) is_end = end_range.compareBoundaryPoints(Range.END_TO_END,range) } </code></pre> <p>Am I going to run into any odd issues with something like this?</p>
7,473,638
5
0
null
2011-09-16 23:53:22.6 UTC
9
2019-06-05 11:52:51.803 UTC
2011-09-17 00:13:27.41 UTC
null
267,404
null
267,404
null
1
19
javascript|html|dom|contenteditable|rangy
7,850
<p>This is how I ended up solving this. My proposed solution above worked sometimes but there were way to many edge cases, so I ended up considering how much text was before or after the cursor, and if that was 0 characters, then I was at the start or end:</p> <pre><code>handle_keydown = function(e) { // Get the current cusor position range = window.getSelection().getRangeAt(0) // Create a new range to deal with text before the cursor pre_range = document.createRange(); // Have this range select the entire contents of the editable div pre_range.selectNodeContents(this); // Set the end point of this range to the start point of the cursor pre_range.setEnd(range.startContainer, range.startOffset); // Fetch the contents of this range (text before the cursor) this_text = pre_range.cloneContents(); // If the text's length is 0, we're at the start of the div. at_start = this_text.textContent.length === 0; // Rinse and repeat for text after the cursor to determine if we're at the end. post_range = document.createRange(); post_range.selectNodeContents(this); post_range.setStart(range.endContainer, range.endOffset); next_text = post_range.cloneContents(); at_end = next_text.textContent.length === 0; } </code></pre> <p>Still not entirely sure there are any other edge cases, as I'm not entirely sure how to unit test this, since it requires mouse interaction - there's probably a library to deal with this somewhere.</p>
7,382,602
What is the difference between 127.0.0.1 and localhost
<p>Assuming the following is defined in <code>.../hosts</code>:</p> <pre><code>127.0.0.1 localhost </code></pre> <p>What, if any, are the actual differences between using <code>127.0.0.1</code> and <code>localhost</code> as the server name, especially when hitting processes running locally that are listening for connections? </p>
7,382,629
5
2
null
2011-09-12 01:45:41.87 UTC
45
2019-02-24 07:59:04.3 UTC
2013-08-19 12:26:32.65 UTC
null
256,196
null
256,196
null
1
203
sockets|networking|dns|localhost
163,568
<p>Well, the most likely difference is that you still have to do an actual <em>lookup</em> of <code>localhost</code> somewhere.</p> <p>If you use <code>127.0.0.1</code>, then (intelligent) software will just turn that directly into an IP address and use it. Some implementations of <code>gethostbyname</code> will detect the dotted format (and presumably the equivalent IPv6 format) and not do a lookup at all.</p> <p>Otherwise, the name has to be resolved. And there's no guarantee that your <code>hosts</code> file will actually be <em>used</em> for that resolution (first, or at all) so <code>localhost</code> may become a totally <em>different</em> IP address.</p> <p>By that I mean that, on some systems, a local <code>hosts</code> file can be bypassed. The <a href="http://tldp.org/LDP/nag/node82.html" rel="noreferrer"><code>host.conf</code></a> file controls this on Linux (and many other Unices).</p>
7,323,958
Are PUT and POST requests required/expected to have a request body?
<p>I'm writting a RESTful api, and at I'm thinking about the process of a user creating a key. I have the following possibilities:</p> <ul> <li>GET request to <code>/new/&lt;keyname&gt;</code> - although it's very easy I think I won't use this, because I heard GET is for retrieving and/or listing information;</li> <li>POST request to <code>/&lt;keyname&gt;</code> - This seemed to me easy and simple enough, but does not pass any data in the request body. Can I do it this way ? Is this weird ?</li> <li>POST request to <code>/keys</code> passing in the request body <code>"keyname=SomeKey"</code> - Is this the correct way ?</li> </ul> <p>I looked at <a href="https://api.no.de/v1" rel="noreferrer">this API from joyent</a> and in all their PUT and POST requests they pass some data in the request body. Is this expected ? Is it really wrong not to require a request body in a PUT and POST request ?</p>
7,326,648
6
0
null
2011-09-06 17:45:12.167 UTC
4
2019-07-09 02:59:23.187 UTC
null
null
null
null
618,756
null
1
32
http|rest|post|httpwebrequest|put
43,882
<p>I asked this question on the Http-WG. This was the most precise answer I got <a href="http://lists.w3.org/Archives/Public/ietf-http-wg/2010JulSep/0276.html">http://lists.w3.org/Archives/Public/ietf-http-wg/2010JulSep/0276.html</a></p> <p>In summary, POST does not require a body. I would expect the same justification can be applied to PUT.</p>
7,464,724
An array of List in c#
<p>I want to have an array of Lists. In c++ I do like:</p> <pre><code>List&lt;int&gt; a[100]; </code></pre> <p>which is an array of 100 Lists. each list can contain many elements. I don't know how to do this in c#. Can anyone help me?</p>
7,464,744
7
0
null
2011-09-18 21:51:50.217 UTC
5
2020-12-15 22:42:01.187 UTC
null
null
null
null
585,874
null
1
61
c#|arrays|list
167,082
<p>You do like this:</p> <pre><code>List&lt;int&gt;[] a = new List&lt;int&gt;[100]; </code></pre> <p>Now you have an array of type <code>List&lt;int&gt;</code> containing 100 null references. You have to create lists and put in the array, for example:</p> <pre><code>a[0] = new List&lt;int&gt;(); </code></pre>
7,643,308
How to Automatically Close Alerts using Twitter Bootstrap
<p>I'm using twitter's bootstrap CSS framework (which is fantastic). For some messages to users I am displaying them using the alerts Javascript JS and CSS. </p> <p>For those interested, it can be found here: <a href="http://getbootstrap.com/javascript/#alerts">http://getbootstrap.com/javascript/#alerts</a></p> <p>My issue is this; after I've displayed an alert to a user I'd like it to just go away after some time interval. Based on twitter's docs and the code I've looked through it looks like this is not baked in:</p> <ul> <li>My first question is a request for confirmation that this is indeed NOT baked into Bootstrap</li> <li>Secondly, how can I achieve this behavior? </li> </ul>
7,643,366
10
1
null
2011-10-04 04:26:49.327 UTC
33
2019-07-15 07:28:52.337 UTC
2019-07-15 07:28:52.337 UTC
null
1,000,551
null
365,858
null
1
91
javascript|jquery|css|twitter-bootstrap|alert
146,792
<p>Calling <a href="https://developer.mozilla.org/en/window.setTimeout"><code>window.setTimeout(function, delay)</code></a> will allow you to accomplish this. Here's an example that will automatically close the alert 2 seconds (or 2000 milliseconds) after it is displayed.</p> <pre><code>$(".alert-message").alert(); window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000); </code></pre> <p>If you want to wrap it in a nifty function you could do this.</p> <pre><code>function createAutoClosingAlert(selector, delay) { var alert = $(selector).alert(); window.setTimeout(function() { alert.alert('close') }, delay); } </code></pre> <p>Then you could use it like so...</p> <pre><code>createAutoClosingAlert(".alert-message", 2000); </code></pre> <p>I am certain there are more elegant ways to accomplish this.</p>
13,832,321
Compare part of an input string using strcmp() in C
<p>Normally strcmp is used with two arguments [e.g. strcmp(str1,"garden")], and it will return 0 if both are the same.</p> <p>Is it possible to compare part of the input, say the first five character of the input? (for example, <code>strcmp(str1,"garde",5)</code>)</p> <pre><code>#include &lt;stdio.h&gt; #include&lt;string.h&gt; int main(void) { char str1[] = "garden"; if (strcmp(str1, "garden") == 0) { printf("1"); } if (strcmp(str1, "garden", 6) == 0) { printf("2"); } if (strcmp(str1, "garde", 5) == 0) { printf("3"); } return 0; } </code></pre>
13,832,351
2
1
null
2012-12-12 03:32:18.527 UTC
1
2017-06-02 19:51:42.06 UTC
2017-06-02 19:51:42.06 UTC
null
63,550
null
1,872,384
null
1
10
c|strcmp
38,102
<p>Use strncmp:</p> <pre><code>if (strncmp(str, "test", 4) == 0) { printf("it matches!"); } </code></pre> <p>See <a href="http://www.cplusplus.com/reference/cstring/strncmp/">http://www.cplusplus.com/reference/cstring/strncmp/</a> for more info.</p>
14,275,249
How can I animate a progressive drawing of svg path?
<p>I want to animate a progressive drawing of a line using only css with svg/canvas and js maximum. An idea of the line I want to draw can be found <a href="http://jsfiddle.net/6btNN/" rel="noreferrer">here</a></p> <pre><code>&lt;svg width="640" height="480" xmlns="http://www.w3.org/2000/svg"&gt; &lt;!-- Created with SVG-edit - http://svg-edit.googlecode.com/ --&gt; &lt;g&gt; &lt;title&gt;Layer 1&lt;/title&gt; &lt;path d="m33,104c1,0 2.1306,-0.8037 23,3c9.07012,1.65314 10,2 24,2c7,0 29,0 33,0c8,0 9,0 11,0c2,0 8,0 11,0c9,0 17,0 18,0c10,0 12,0 20,0c1,0 6,0 7,0c2,0 3.07613,0.38268 4,0c2.61313,-1.08239 2,-3 2,-6c0,-1 0,-2 0,-3c0,-1 0,-2 0,-3c0,-1 0,-2 0,-3c0,-1 0.30745,-3.186 -1,-5c-0.8269,-1.14727 -0.09789,-2.82443 -2,-4c-0.85065,-0.52573 -2.82443,-0.09789 -4,-2c-0.52573,-0.85065 -2.58578,-0.58578 -4,-2c-0.70711,-0.70711 -1.81265,-1.20681 -4,-3c-2.78833,-2.28588 -3.64749,-2.97251 -8,-4c-2.91975,-0.68926 -4.82375,-2.48626 -7,-3c-2.91975,-0.68926 -5.15224,-0.23463 -7,-1c-1.30656,-0.5412 -4.38687,-1.91761 -7,-3c-1.84776,-0.76537 -5.03609,0.37821 -7,0c-5.28799,-1.01837 -8,-3 -9,-3c-2,0 -5.0535,-0.54049 -7,-1c-2.17625,-0.51374 -4.15224,-0.23463 -6,-1c-1.30656,-0.54119 -3,-1 -4,-1c-2,0 -5,-1 -6,-1c-1,0 -3,-2 -6,-2c-2,0 -5,-2 -6,-2c-2,0 -2.02583,-0.67963 -4,-1c-3.12144,-0.50654 -4.15224,-0.23463 -6,-1c-1.30656,-0.54119 -2,-1 -3,-1c-2,0 -3,0 -5,0c-1,0 -2,0 -3,0c-1,0 -2,0 -3,0c-1,0 -2,0 -3,0c-2,0 -3.85273,0.1731 -5,1c-1.81399,1.30745 -5.18601,1.69255 -7,3c-1.14727,0.8269 -1.82375,2.48626 -4,3c-0.97325,0.22975 -1.69344,1.45881 -3,2c-0.92388,0.38268 -1.45951,1.0535 -1,3c0.51374,2.17625 3.07844,2.78985 6,4c2.06586,0.85571 3.38688,1.91761 6,3c1.84776,0.76537 5.2987,-1.05146 7,0c1.90211,1.17557 3.82375,2.48626 6,3c0.97325,0.22975 3.29289,0.29289 4,1c0.70711,0.70711 4,2 9,4c5,2 8,4 11,4c2,0 5,0 7,0c3,0 5,0 7,0c2,0 4,0 7,0c2,0 4,0 8,0c3,0 7,0 10,0c4,0 7,0 12,0c3,0 5,0 6,0c2,0 3,0 5,0c1,0 1.09789,-0.82443 3,-2c0.85065,-0.52573 3.07613,0.38268 4,0c1.30656,-0.5412 0.71022,-2.04291 1,-3c1.04483,-3.45084 2.84723,-5.04132 4,-9c0.88414,-3.03616 1.85194,-5.22836 3,-8c0.5412,-1.30656 1.5405,-2.0535 2,-4c0.51375,-2.17625 2.71413,-4.21167 5,-7c2.68979,-3.28101 4,-6 5,-7c1,-1 2,-2 2,-4c0,-1 0.70711,-2.29289 0,-3c-0.70711,-0.70711 -2.07613,0.38268 -3,0c-1.30656,-0.54119 -2,-1 -4,-1c-3,0 -6.87856,-2.49346 -10,-3c-2.96126,-0.48055 -6.71201,-0.98162 -12,-2c-2.94586,-0.56732 -5,-1 -9,-1c-3,0 -6,-1 -8,-1c-2,0 -5,-3 -7,-3c-2,0 -5.38687,-0.91761 -8,-2c-0.92388,-0.38268 -3.0535,-0.54049 -5,-1c-2.17625,-0.51374 -4.58578,0.41421 -6,-1c-0.70711,-0.70711 -1,-1 -2,-1c-1,0 -2,0 -3,0c-1,0 -2,0 -4,0c-1,0 -2,0 -3,0c-1,0 -2,0 -4,0c-1,0 -2,0 -3,0c-2,0 -3,0 -5,0c-1,0 -2,0 -3,0c-1,0 -3,0 -4,0c-3,0 -5,0 -7,0c-2,0 -4,0 -6,0c-2,0 -3,0 -5,0c-1,0 -2,0 -3,0c-2,0 -4,0 -5,0c-1,0 -2,0 -4,0c-1,0 -2,0 -3,1l-1,0" id="svg_1" stroke-width="5" stroke="#000000" fill="none"/&gt; &lt;/g&gt; &lt;/svg&gt; </code></pre>
14,282,391
4
2
null
2013-01-11 09:36:34.24 UTC
20
2014-12-01 20:11:55.583 UTC
2014-12-01 20:11:55.583 UTC
null
1,079,075
null
1,820,097
null
1
15
javascript|css|canvas|svg
43,078
<p>There are three techniques listed in this answer:</p> <hr> <p>There is an all-SVG solution that involves progressively modifying the <code>stroke-dasharray</code> for the shape to draw a longer and longer 'dash' followed by an enormous gap.</p> <h3>Demo: <a href="http://phrogz.net/svg/progressively-drawing-svg-path-via-dasharray.html" rel="noreferrer">http://phrogz.net/svg/progressively-drawing-svg-path-via-dasharray.html</a></h3> <p>Relevant code:</p> <pre class="lang-js prettyprint-override"><code>var distancePerPoint = 1; var drawFPS = 60; var orig = document.querySelector('path'), length, timer; orig.addEventListener('mouseover',startDrawingPath,false); orig.addEventListener('mouseout', stopDrawingPath, false); function startDrawingPath(){ length = 0; orig.style.stroke = '#f60'; timer = setInterval(increaseLength,1000/drawFPS); } function increaseLength(){ var pathLength = orig.getTotalLength(); length += distancePerPoint; orig.style.strokeDasharray = [length,pathLength].join(' '); if (length &gt;= pathLength) clearInterval(timer); } function stopDrawingPath(){ clearInterval(timer); orig.style.stroke = ''; orig.style.strokeDasharray = ''; } </code></pre> <hr> <p>Alternatively, you can still use all SVG and choose to build the SVG path one command at a time:</p> <h3>Demo: <a href="http://phrogz.net/svg/progressively-cloning-svg-path.html" rel="noreferrer">http://phrogz.net/svg/progressively-cloning-svg-path.html</a></h3> <p>Relevant code:</p> <pre class="lang-js prettyprint-override"><code>// Assumes 'orig' and dup' are SVG paths function addNextPathSegment(){ var nextIndex = dup.pathSegList.numberOfItems; if (nextIndex&lt;orig.pathSegList.numberOfItems){ var nextSegment = orig.pathSegList.getItem(nextIndex); var segmentDup = cloneSVGPathSeg( dup, nextSegment ); dup.pathSegList.appendItem( segmentDup ); } } function cloneSVGPathSeg( path, seg ){ switch(seg.pathSegTypeAsLetter){ case 'M': return path.createSVGPathSegMovetoAbs(seg.x,seg.y); break; case 'm': return path.createSVGPathSegMovetoRel(seg.x,seg.y); break; case 'L': return path.createSVGPathSegLinetoAbs(seg.x,seg.y); break; case 'l': return path.createSVGPathSegLinetoRel(seg.x,seg.y); break; case 'H': return path.createSVGPathSegLinetoHorizontalAbs(seg.x); break; case 'h': return path.createSVGPathSegLinetoHorizontalRel(seg.x); break; case 'V': return path.createSVGPathSegLinetoVerticalAbs(seg.y); break; case 'v': return path.createSVGPathSegLinetoVerticalRel(seg.y); break; case 'C': return path.createSVGPathSegCurvetoCubicAbs(seg.x,seg.y,seg.x1,seg.y1,seg.x2,seg.y2); break; case 'c': return path.createSVGPathSegCurvetoCubicRel(seg.x,seg.y,seg.x1,seg.y1,seg.x2,seg.y2); break; case 'S': return path.createSVGPathSegCurvetoCubicSmoothAbs(seg.x,seg.y,seg.x2,seg.y2); break; case 's': return path.createSVGPathSegCurvetoCubicSmoothRel(seg.x,seg.y,seg.x2,seg.y2); break; case 'Q': return path.createSVGPathSegCurvetoQuadraticAbs(seg.x,seg.y,seg.x1,seg.y1); break; case 'q': return path.createSVGPathSegCurvetoQuadraticRel(seg.x,seg.y,seg.x1,seg.y1); break; case 'T': return path.createSVGPathSegCurvetoQuadraticSmoothAbs(seg.x,seg.y); break; case 't': return path.createSVGPathSegCurvetoQuadraticSmoothRel(seg.x,seg.y); break; case 'A': return path.createSVGPathSegArcAbs(seg.x,seg.y,seg.r1,seg.r2,seg.angle,seg.largeArcFlag,seg.sweepFlag); break; case 'a': return path.createSVGPathSegArcRel(seg.x,seg.y,seg.r1,seg.r2,seg.angle,seg.largeArcFlag,seg.sweepFlag); break; case 'z': case 'Z': return path.createSVGPathSegClosePath(); break; } } </code></pre> <hr> <p>Finally, you may choose to draw your path to an HTML5 canvas by sampling the SVG path periodically and drawing to the canvas. (Note that the SVG path does not need to be displayed for this to happen; you can build an SVG path element entirely in JavaScript and sample it):</p> <h3>Demo: <a href="http://phrogz.net/svg/progressively-drawing-svg-path.html" rel="noreferrer">http://phrogz.net/svg/progressively-drawing-svg-path.html</a></h3> <p>Relevant code:</p> <pre class="lang-js prettyprint-override"><code>function startDrawingPath(){ points = []; timer = setInterval(buildPath,1000/drawFPS); } // Assumes that 'orig' is an SVG path function buildPath(){ var nextPoint = points.length * distancePerPoint; var pathLength = orig.getTotalLength(); if (nextPoint &lt;= pathLength){ points.push(orig.getPointAtLength(nextPoint)); redrawCanvas(); } else stopDrawingPath(); } function redrawCanvas(){ clearCanvas(); ctx.beginPath(); ctx.moveTo(points[0].x,points[0].y); for (var i=1;i&lt;points.length;i++) ctx.lineTo(points[i].x,points[i].y); ctx.stroke(); } </code></pre>
14,123,917
The database [dbName] is not accessible. (ObjectExplorer)
<p>I have an issue in regards to using SQL Server 2008 R2. </p> <p>I recently had an issue with my computer and therefore I had to reboot windows and had to grant permission from one user to another user (using the security feature in the properties). When giving permission initially though, it through a "Access Denied" message.</p> <p>After much research, it stopped producing this error (the user which I needed to grant permission too wasn't available), which then caused another issue to occur, but this time within SQL Server. It produces this message; </p> <blockquote> <p>The database [dbName] is not accessible. (ObjectExplorer) </p> </blockquote> <p>This error occurs when I try to select the drop down option to see the list of tables and stored procedures of the database within SQL Server. I found an explanation for this on the following link;</p> <p><a href="http://www.microsoft.com/products/ee/transform.aspx?ProdName=Microsoft+SQL+Server&amp;ProdVer=10.50.1617&amp;EvtSrc=MSSQLServer&amp;EvtID=916">http://www.microsoft.com/products/ee/transform.aspx?ProdName=Microsoft+SQL+Server&amp;ProdVer=10.50.1617&amp;EvtSrc=MSSQLServer&amp;EvtID=916</a></p> <p>And I then tried to implement like so;</p> <pre><code> USE msdb; GO GRANT CONNECT TO [DBName\MyName] ; CREATE DATABASE [DBNAME] ON PRIMARY </code></pre> <p>Using a script I created (luckily before this problem occurred) it through a whole lot of messages;</p> <blockquote> <p><em>Msg 15151, Level 16, State 1, Line 1<br> Cannot find the user 'DBName\MyName', because it does not exist or you do not have permission.<br> Msg 262, Level 14, State 1, Line 2<br> CREATE DATABASE permission denied in database 'master'.<br> Msg 5011, Level 14, State 9, Line 1<br> User does not have permission to alter database 'DBName', the database does not exist, or the database is not in a state that allows access checks.<br> Msg 5069, Level 16, State 1, Line 1 ...</em></p> </blockquote> <p>After this bunch of errors, I have become unstuck and therefore would much be grateful if anyone could give me some feedback in regards to what I could do to resolve this issue. Cheers.</p>
14,124,037
4
2
null
2013-01-02 14:37:46.563 UTC
1
2019-01-03 08:34:15.887 UTC
2013-01-02 15:06:59.027 UTC
null
13,302
null
1,829,286
null
1
15
sql|sql-server|sql-server-2008
91,982
<p>Generally it is a bad idea to grant permissions directly to logins. You should create role objects in the database, and all permissions in the database should be assigned to the roles.</p> <p>Then when moving the database to another computer (or reinstalling) the only things you have to modify are server logins and role assignments.</p>
13,881,548
Sticky footer hiding content
<p>I made the following sticky footer using CSS. The bottom page content is currently hidden behind the footer (see the attached screenshot). How can I adjust my CSS so that all of the body content is visible and the footer remains stuck to the bottom of the browser window? Thank you!</p> <p><img src="https://i.stack.imgur.com/FKELf.png" alt="enter image description here"></p> <p>CSS:</p> <pre><code>.fo { position: absolute; left: 0; bottom: 0; height:65px; width: 100%; color: #eaeaea; margin-left: -8px; } </code></pre>
13,883,285
7
2
null
2012-12-14 15:26:25.907 UTC
8
2020-07-11 15:27:43.82 UTC
2019-11-02 13:02:59.807 UTC
null
9,475,813
null
1,420,296
null
1
43
html|css
55,647
<p>I came across this answer out on the internet in the past. Works great:</p> <p>HTML</p> <pre><code>&lt;div id="container"&gt; &lt;div id="header"&gt;&lt;/div&gt; &lt;div id="body"&gt;&lt;/div&gt; &lt;div id="footer"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code> html, body { margin:0; padding:0; height:100%; } #container { min-height:100%; position:relative; } #header { background:#ff0; padding:10px; } #body { padding:10px; padding-bottom:60px; /* Height of the footer */ } #footer { position:absolute; bottom:0; width:100%; height:60px; /* Height of the footer */ background:#6cf; } /* IE 6 and down: #container { height:100%; } </code></pre>
13,979,150
Why is sin_addr inside the structure in_addr?
<p>My doubt is related to the following structure of sockets in UNIX :</p> <pre><code>struct sockaddr_in { short sin_family; // e.g. AF_INET, AF_INET6 unsigned short sin_port; // e.g. htons(3490) struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // zero this if you want to }; </code></pre> <p>Here the member <code>sin_addr</code> is of type <code>struct in_addr</code>.</p> <p>But I don't get why someone would like to do that as all <code>struct inaddr</code> has is : </p> <pre><code>struct in_addr { unsigned long s_addr; // load with inet_pton() }; </code></pre> <p>All <code>in_addr</code> has is just one member <code>s_addr</code>. Why cannot we have something like this :</p> <pre><code>struct sockaddr_in { short sin_family; // e.g. AF_INET, AF_INET6 unsigned short sin_port; // e.g. htons(3490) unsigned long s_addr ; char sin_zero[8]; // zero this if you want to }; </code></pre>
13,979,177
3
4
null
2012-12-20 19:29:17.593 UTC
20
2015-09-25 12:03:57.763 UTC
2015-09-25 12:03:57.763 UTC
null
1,009,479
null
1,222,542
null
1
61
c|sockets|unix
61,526
<p><code>struct in_addr</code> is sometimes very different than that, depending on what system you're on. On <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms738571%28v=vs.85%29.aspx">Windows</a> for example:</p> <pre><code>typedef struct in_addr { union { struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b; struct { u_short s_w1,s_w2; } S_un_w; u_long S_addr; } S_un; } IN_ADDR, *PIN_ADDR, FAR *LPIN_ADDR; </code></pre> <p>The only <em>requirement</em> is that it contain a member <code>s_addr</code>.</p>
14,132,122
Open URL in new window with JavaScript
<p>I'm making a "share button" to share the current page. I would like to take the current page URL and open it in a new window. I have the current URL part working, but can't seem to get the next part working. </p> <p>I'm struggling with the syntax. I would like to specify the new window size to <code>width=520, height=570</code>.</p> <p>Something like: </p> <pre><code>&lt;a target="_blank" href="https://www.linkedin.com/cws/share?mini=true&amp;amp;url=[sub]" onclick="this.href = this.href.replace('[sub]',window.location)"&gt; LinkedIn &lt;/a&gt; </code></pre> <p>Any ideas?</p>
14,132,265
5
1
null
2013-01-03 02:03:46.16 UTC
30
2022-06-21 17:04:50.737 UTC
2020-03-10 09:34:18.567 UTC
null
814,702
null
1,357,459
null
1
170
javascript|new-window
551,853
<p>Use <code>window.open()</code>:</p> <pre><code>&lt;a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');"&gt; Share Page &lt;/a&gt; </code></pre> <p>This will create a link titled <code>Share Page</code> which opens the current url in a new window with a height of 570 and width of 520.</p>
47,519,768
How do I set the default browser as chrome in Visual Studio Code?
<p>I am setting up my VS Code environment for the first time, but I can't figure out how to set Chrome as the default browser for the workspace.</p>
47,520,320
16
6
null
2017-11-27 21:04:41.397 UTC
8
2022-09-16 18:23:08.39 UTC
2018-12-27 13:12:19.92 UTC
null
2,631,715
null
1,876,851
null
1
65
visual-studio-code|vscode-settings
160,816
<p>The other StackOverflow questions regarding the browser, had to do with opening a specific file. Here are the steps to creating a tasks.json file in a brand new environment.</p> <ol> <li>From the Tasks menu, Select 'Configure Tasks'</li> <li>The entry field prompts you for 'Select a task to configure'</li> <li>Choose 'Create tasks.json file from template'</li> <li>Edit the file to include the following block: </li> </ol> <hr> <pre><code>{ "version": "0.1.0", "command": "Chrome", "windows": { "command": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe" }, "args": ["${file}"] } </code></pre>
44,703,646
Determine the OS version, Linux and Windows from Powershell
<p>How can I determine the OS type, (Linux, Windows) using Powershell from within a script?</p> <p>The ResponseUri isn't recognised when this part of my script is ran on a Linux host. </p> <pre><code>$UrlAuthority = $Request.BaseResponse | Select-Object -ExpandProperty ResponseUri | Select-Object -ExpandProperty Authority </code></pre> <p>So I want an <code>If</code> statement to determine the OS type that would look similar to this:</p> <pre><code>If ($OsType -eq "Linux") { $UrlAuthority = ($Request.BaseResponse).RequestMessage | Select-Object -ExpandProperty RequestUri | Select-Object -ExpandProperty host } Else $UrlAuthority = $Request.BaseResponse | Select-Object -ExpandProperty ResponseUri | Select-Object -ExpandProperty Authority </code></pre> <p>I could use <code>Get-CimInstance Win32_OperatingSystem</code> but it would fail on Linux as it's not recognised. </p>
44,703,836
10
3
null
2017-06-22 15:28:01.503 UTC
8
2022-01-24 15:01:23.187 UTC
2020-11-24 14:03:29.587 UTC
null
8,188,846
null
3,014,860
null
1
38
linux|windows|powershell|operating-system|powershell-core
36,029
<p>Aren't there environment variables you can view on the other platforms for the OS?</p> <pre><code>Get-ChildItem -Path Env: </code></pre> <p>Particularly, on Windows at least, there's an OS environment variable, so you <em>should</em> be able to accomplish this by using <code>$Env:OS</code>.</p> <hr /> <p>Since some time has passed and the <em>PowerShell Core</em> (v6) product is GA now (the <em>Core</em> branding has been dropped as of v7), you can more accurately determine your platform based on the following automatic boolean variables:</p> <pre><code>$IsMacOS $IsLinux $IsWindows </code></pre>
44,445,778
Are GAN's unsupervised or supervised?
<p>I hear from some sources that Generative adversarial networks are unsupervised ML, but i dont get it. Are Generative adversarial networks not in fact supervised?</p> <p>1) 2-class case Real-against-Fake </p> <p>Indeed one has to supply training data to the discriminator and this has to be "real" data, meaning data which i would label with f.e. 1. Even though one doesnt label the data explicit, one does so implicitly by presenting the discriminator in the first steps with training data, which you tell the discriminator is authentic. In that way you somehow tell the discriminator a labeling of the training data. And on the contrary a labeling of the noise data that is generated at the first steps of the generator, which the generator knows to be unauthentic.</p> <p>2) Multi-class case</p> <p>But it gets really strange in the multi class case. One has to supply descriptions in the training data. The obvious contradiction is that one supplies a response to an unsupervised ML algorithm.</p>
44,446,164
2
3
null
2017-06-08 21:22:07.267 UTC
13
2020-02-10 16:48:55.257 UTC
null
null
null
null
2,514,425
null
1
32
machine-learning|neural-network|classification
19,193
<p>GANs are unsupervised learning algorithms that use a supervised loss as part of the training. The later appears to be where you are getting hung-up. </p> <p>When we talk about supervised learning, we are usually talking about learning to predict a label associated with the data. The <em>goal</em> is for the model to generalize to new data. </p> <p>In the GAN case, you don't have either of these components. The data comes in with no labels, and we are not trying to generalize any kind of prediction to new data. The <em>goal</em> is for the GAN to model what the data looks like (i.e., density estimation), and be able to generate new examples of what it has learned. </p> <p>The GAN sets up a supervised learning problem in order to do unsupervised learning, generates fake / random looking data, and tries to determine if a sample is generated fake data or real data. This is a supervised component, yes. But it is not the <em>goal</em> of the GAN, and the labels are trivial. </p> <p>The idea of using a supervised component for an unsupervised task is not particularly new. Random Forests have done this for a long time for outlier detection (also trained on random data vs real data), and the One-Class SVM for outlier detection is technically trained in supervised fashion with the original data being the real class and a single point at the origin of the space (i.e., the zero vector) treated as the outlier class. </p>
35,036,669
Bootstrap pull-right not working as expected
<p>Simple question here using <code>Bootstrap3</code>. I wanted to create a sort of small filter that reloads the page below it. My requirement was to <strong>align</strong> this filter (two inputs and a small button) with the content sitting below it, making it fall <strong>to the rightest position possible</strong>.</p> <p>I tried using <code>pull-right</code> class and indeed it pulled the filter right but there's still more room to fill. If you check the example I provided below, you'll see that <strong>my objective is to align the button with the right side of the purple row</strong>, but it fails.</p> <p>I don't really understand why this happens, but I assume that it's related to some margin/padding issues with the rows.. I'm looking for an answer explaining why this happens so I can understand the problem and won't deal with it again :).</p> <p>You can check my markup <a href="http://www.bootply.com/d3ITPWzgX2" rel="noreferrer">by clicking here on bootply</a></p> <p>Also I'll post my markup right here:</p> <pre><code>&lt;div class="container"&gt; &lt;div class="row" style="background:slateblue;"&gt; &lt;div class="col-xs-12"&gt; &lt;form role="form" class="form-horizontal"&gt; &lt;div class="form-group pull-right"&gt; &lt;div class="col-xs-4"&gt; &lt;input type="text" class="form-control text-center"&gt; &lt;/div&gt; &lt;div class="col-xs-4"&gt; &lt;input type="text" class="form-control text-center"&gt; &lt;/div&gt; &lt;div class="col-xs-2 col-sm-2" style="margin-top:3px;"&gt; &lt;button type="submit" class="btn btn-success"&gt; &lt;span class="glyphicon glyphicon-refresh"&gt;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt;&lt;!-- main col 12--&gt; &lt;/div&gt;&lt;!--row--&gt; &lt;div class="row" style="background:slategrey; height:200px;"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
35,037,042
6
4
null
2016-01-27 11:53:53.15 UTC
3
2021-12-12 10:44:56.683 UTC
null
null
null
null
3,736,964
null
1
20
html|css|twitter-bootstrap-3
45,184
<p>Your form-group is aligned as far to the right as possible – but the content within it is not. You have only 4+4+2 wide columns in there, so you are “two columns short”, in the 12-column grid used by bootstrap.</p> <p>You might want to simply offset the first one of those by 2, by adding <code>col-xs-offset-2</code> class – then the alignment should be closer to what you want to achieve.</p>
951,009
SQL Reporting Services - Print Button not shown in Mozilla
<p>I am using <strong>SQL Reporting services</strong>, it's working perfectly and shows a print button in <em>IE</em>, but not shown in Mozilla Firefox.</p> <p>Does anyone have any idea?</p> <p>I have checked out this solution, but it's not working:</p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/vsreportcontrols/thread/7bdf431d-70db-419d-8e98-ef41cad8e2d8" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vsreportcontrols/thread/7bdf431d-70db-419d-8e98-ef41cad8e2d8</a></p>
2,411,071
5
3
null
2009-06-04 14:39:02.04 UTC
10
2016-05-26 08:32:41.417 UTC
2009-10-08 11:09:49.51 UTC
null
97,010
null
97,010
null
1
15
asp.net|firefox|reporting-services
66,549
<p>I don't think it uses ActiveX, because in the table onclick event there is a simple:</p> <pre><code>ReportFramerpvReport.GetReportFrame().contentWindow.print() </code></pre> <p>Anyway, i replaced this print stuff with my own print function, because this code above wasn't working on FF..</p> <p>I know it's ugly...but it works! (just replace the ControlName value with your ControlID and be sure to add jQuery lib in your page)</p> <pre><code> $(document).ready(function() { if ($.browser.mozilla) { try { var ControlName = 'RptDespesas'; var innerScript = '&lt;scr' + 'ipt type="text/javascript"&gt;document.getElementById("' + ControlName + '_print").Controller = new ReportViewerHoverButton("' + ControlName + '_print", false, "", "", "", "#ECE9D8", "#DDEEF7", "#99BBE2", "1px #ECE9D8 Solid", "1px #336699 Solid", "1px #336699 Solid");&lt;/scr' + 'ipt&gt;'; var innerTbody = '&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;input type="image" style="border-width: 0px; padding: 2px; height: 16px; width: 16px;" alt="Print" src="/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;amp;Version=9.0.30729.1&amp;amp;Name=Microsoft.Reporting.WebForms.Icons.Print.gif" title="Print"&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;'; var innerTable = '&lt;table title="Print" onmouseout="this.Controller.OnNormal();" onmouseover="this.Controller.OnHover();" onclick="PrintFunc(\'' + ControlName + '\'); return false;" id="' + ControlName + '_print" style="border: 1px solid rgb(236, 233, 216); background-color: rgb(236, 233, 216); cursor: default;"&gt;' + innerScript + innerTbody + '&lt;/table&gt;' var outerScript = '&lt;scr' + 'ipt type="text/javascript"&gt;document.getElementById("' + ControlName + '_print").Controller.OnNormal();&lt;/scr' + 'ipt&gt;'; var outerDiv = '&lt;div style="display: inline; font-size: 8pt; height: 30px;" class=" "&gt;&lt;table cellspacing="0" cellpadding="0" style="display: inline;"&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td height="28px"&gt;' + innerTable + outerScript + '&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/div&gt;'; $("#" + ControlName + " &gt; div &gt; div").append(outerDiv); } catch (e) { alert(e); } } }); function PrintFunc(ControlName) { setTimeout('ReportFrame' + ControlName + '.print();', 100); } </code></pre>
847,962
What alternate session managers are available for Emacs?
<p>I have read <a href="http://www.emacswiki.org/emacs/SessionManagement" rel="nofollow noreferrer">the page in Emacs wiki</a> which contains a list of session manager plugins. But after trying all of these, I am still not happy with any of them.</p> <p>By comparison, <a href="http://www.vim.org/scripts/script.php?script_id=2010" rel="nofollow noreferrer">the VIM session manager</a> saves and loads sessions by name, which is one of the most important features for me.</p> <p>In particular, I want a session manager for Emacs that:</p> <ul> <li>Managing sessions by name</li> <li>Saving tabs, screens, frames etc..</li> </ul> <p>I'm trying to use Emacs because it has got really good features but a good session manager is important to my workflow.</p> <hr> <p>Related:</p> <ul> <li><a href="https://stackoverflow.com/questions/803812/emacs-reopen-buffers-from-last-session-on-startup">Emacs: reopen buffers from last session on startup?</a></li> <li><a href="https://stackoverflow.com/questions/392314/saving-window-configurations-in-emacs">Saving Window Configurations in Emacs</a></li> </ul>
849,180
5
4
null
2009-05-11 12:52:29.163 UTC
10
2012-12-05 02:37:32.673 UTC
2017-05-23 12:32:29.127 UTC
null
-1
null
76,693
null
1
16
session|emacs
3,334
<p>Since you don't like the base functionality of desktop.el, throw some elisp around it:</p> <pre><code>(defvar my-desktop-session-dir (concat (getenv "HOME") "/.emacs.d/desktop-sessions/") "*Directory to save desktop sessions in") (defvar my-desktop-session-name-hist nil "Desktop session name history") (defun my-desktop-save (&amp;optional name) "Save desktop with a name." (interactive) (unless name (setq name (my-desktop-get-session-name "Save session as: "))) (make-directory (concat my-desktop-session-dir name) t) (desktop-save (concat my-desktop-session-dir name) t)) (defun my-desktop-read (&amp;optional name) "Read desktop with a name." (interactive) (unless name (setq name (my-desktop-get-session-name "Load session: "))) (desktop-read (concat my-desktop-session-dir name))) (defun my-desktop-get-session-name (prompt) (completing-read prompt (and (file-exists-p my-desktop-session-dir) (directory-files my-desktop-session-dir)) nil nil nil my-desktop-session-name-hist)) </code></pre> <p><strong>EDIT</strong>:</p> <p>Getting some votes, so add niceties like completing-read and history</p>
986,892
How do I use custom roles/authorities in Spring Security?
<p>While migrating a legacy application to spring security I got the following exception:</p> <pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterChainProxy': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterChainList': Cannot resolve reference to bean '_filterSecurityInterceptor' while setting bean property 'filters' with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterSecurityInterceptor': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Unsupported configuration attributes: [superadmin] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) </code></pre> <p>In the old application there are roles like "superadmin", "editor", "helpdesk" etc. But in all Spring Security examples I only see roles like "ROLE_" ("ROLE_ADMIN" etc). When I rename "superadmin" to "ROLE_ADMIN" and only use this role in the config, everything works.</p> <p>Doesn't work:</p> <pre><code> &lt;http auto-config="true"&gt; &lt;intercept-url pattern="/restricted/**" access="superadmin"/&gt; &lt;form-login authentication-failure-url="/secure/loginAdmin.do?error=true" login-page="/secure/loginAdmin.do" /&gt; &lt;/http&gt; </code></pre> <p>Works:</p> <pre><code>&lt;http auto-config="true"&gt; &lt;intercept-url pattern="/restricted/**" access="ROLE_ADMIN"/&gt; &lt;form-login authentication-failure-url="/secure/loginAdmin.do?error=true" login-page="/secure/loginAdmin.do" /&gt; &lt;/http&gt; </code></pre> <p>Is possible to use custom role names? </p>
987,383
5
1
null
2009-06-12 14:20:25.207 UTC
22
2014-04-24 05:56:32.62 UTC
null
null
null
null
61,530
null
1
33
java|spring|spring-security
70,396
<p>You are using the default configuration which expects that roles starts with the <code>"ROLE_"</code> prefix. You will have to add a custom security configuration and set <code>rolePrefix</code> to "";</p> <p><a href="http://forum.springsource.org/archive/index.php/t-53485.html" rel="noreferrer">http://forum.springsource.org/archive/index.php/t-53485.html</a></p>
354,002
Mysql select where not in table
<p>I have 2 tables (A and B) with the same primary keys. I want to select all row that are in A and not in B. The following works:</p> <pre><code>select * from A where not exists (select * from B where A.pk=B.pk); </code></pre> <p>however it seems quite bad (~2 sec on only 100k rows in A and 3-10k less in B)</p> <p>Is there a better way to run this? Perhaps as a left join?</p> <pre><code>select * from A left join B on A.x=B.y where B.y is null; </code></pre> <p>On my data this seems to run slightly faster (~10%) but what about in general?</p>
354,185
5
1
null
2008-12-09 19:52:13.54 UTC
20
2015-12-14 10:36:29.61 UTC
2008-12-09 20:17:12.743 UTC
BCS
1,343
BCS
1,343
null
1
56
mysql|join|not-exists
70,253
<p>I use queries in the format of your second example. A join is usually more scalable than a correlated subquery.</p>
377,202
Which should I use, -awakeFromNib or -viewDidLoad?
<p>I recently had a problem in my app where some of the subviews I was creating in a UIViewController subclass's <code>-awakeFromNib</code> method were disappearing from the view. After some poking around I found that moving the code I had put in <code>-awakeFromNib</code> to <code>-viewDidLoad</code> solved the problem. Seems that <code>-awakeFromNib</code> gets called only once when the UIViewController is unarchived from the nib, and <code>-viewDidLoad</code> gets called every time the view is unarchived.</p> <p>So what's the best practice? It looks like UIViewController's <code>-awakeFromNib</code> shouldn't be adding any views to the view, that kind of stuff should be done in <code>-viewDidLoad</code>. Am I understanding this correctly? Or am I more confused than I thought?</p>
377,390
5
1
null
2008-12-18 08:28:31.347 UTC
31
2019-01-22 00:10:26.207 UTC
2008-12-29 08:26:11.417 UTC
Chris Hanson
714
Mike Akers
17,188
null
1
58
cocoa-touch
50,065
<p><code>awakeFromNib</code> is called when the <strong>controller</strong> itself is unarchived from a nib. <code>viewDidLoad</code> is called when the <strong>view</strong> is created/unarchived. This distinction is especially important when the controller's view is stored in a separate nib file.</p>
856,772
How to create Java webapp installer (.exe) that includes Tomcat and MySQL?"
<p>How to create a installer using Java that combine tomcat, mysql and war file and come out a final exe?</p>
856,855
6
3
null
2009-05-13 08:31:56.583 UTC
15
2017-07-19 19:07:07.01 UTC
2014-04-03 10:56:46.52 UTC
null
3,270,575
null
77,229
null
1
16
java|tomcat|installation|web-applications
21,904
<p>You could use any installer, really. I personally have used <a href="http://www.innosetup.com/isinfo.php" rel="noreferrer">InnoSetup</a>, which is quite simple, but can still perform almost any task at installation time.</p> <p>In your case, you probably want to place the Tomcat files somewhere, webapp included. Customize some configuration files and run the MySQL installer in silent mode. All of which is perfectly possible with InnoSetup.</p> <p>If you need more flexibility, you can look at <a href="http://nsis.sourceforge.net/Main_Page" rel="noreferrer">NSIS</a>, another very simple but very powerful installer app.</p>
421,049
SQL Server UNION - What is the default ORDER BY Behaviour
<p>If I have a few UNION Statements as a contrived example:</p> <pre><code>SELECT * FROM xxx WHERE z = 1 UNION SELECT * FROM xxx WHERE z = 2 UNION SELECT * FROM xxx WHERE z = 3 </code></pre> <p><strong>What is the default <code>order by</code> behaviour?</strong></p> <p>The test data I'm seeing essentially does not return the data in the order that is specified above. I.e. the data is ordered, but I wanted to know what are the rules of precedence on this.</p> <p>Another thing is that in this case xxx is a View. The view joins 3 different tables together to return the results I want.</p>
421,076
6
0
null
2009-01-07 16:43:19.4 UTC
4
2014-07-22 12:18:36.177 UTC
2012-02-06 21:17:41.087 UTC
null
894,284
Ray Booysen
42,124
null
1
39
sql|sql-server|union|sql-order-by
27,994
<p>There is no default order.</p> <p>Without an <strong>Order By</strong> clause the order returned is undefined. That means SQL Server can bring them back in any order it likes.</p> <p>EDIT: Based on what I have seen, without an Order By, the order that the results come back in depends on the query plan. So if there is an index that it is using, the result may come back in that order but again there is no guarantee. </p>
386,040
What's wrong with nullable columns in composite primary keys?
<p>ORACLE does not permit NULL values in any of the columns that comprise a primary key. It appears that the same is true of most other "enterprise-level" systems.</p> <p>At the same time, most systems also allow <em>unique</em> contraints on nullable columns.</p> <p>Why is it that unique constraints can have NULLs but primary keys can not? Is there a fundamental logical reason for this, or is this more of a technical limitation?</p>
386,061
6
1
null
2008-12-22 11:33:55.363 UTC
26
2019-10-17 16:23:21.587 UTC
2008-12-23 20:47:02.627 UTC
null
33,080
null
33,080
null
1
177
database|database-design
125,392
<p>Primary keys are for uniquely identifying rows. This is done by comparing all parts of a key to the input. </p> <p>Per definition, NULL cannot be part of a successful comparison. Even a comparison to itself (<code>NULL = NULL</code>) will fail. This means a key containing NULL would not work.</p> <p>Additonally, NULL is allowed in a foreign key, to mark an optional relationship.<sup>(*)</sup> Allowing it in the PK as well would break this.</p> <hr> <p><sup>(*)</sup>A word of caution: Having nullable foreign keys is not clean relational database design.</p> <p>If there are two entities <code>A</code> and <code>B</code> where <code>A</code> can optionally be related to <code>B</code>, the clean solution is to create a resolution table (let's say <code>AB</code>). That table would link <code>A</code> with <code>B</code>: If there <em>is</em> a relationship then it would contain a record, if there <em>isn't</em> then it would not.</p>
13,267,236
How disable and enable usb port via command prompt?
<p>How disable and enable usb port via command prompt? or using batch script ? or using vb script in windows 7?</p>
13,267,533
3
2
null
2012-11-07 09:55:21.353 UTC
8
2017-03-03 08:44:32.4 UTC
null
null
null
null
1,263,451
null
1
5
windows|batch-file|vbscript
104,581
<p>You can use batch which gives you a couple of options. You can edit the registry key to disable usb devices from being used</p> <pre><code>reg add HKLM\SYSTEM\CurrentControlSet\Services\UsbStor /v "Start" /t REG_DWORD /d "4" /f </code></pre> <p>To enable change value to <code>3</code>.</p> <p>Or you can deny access to the files <code>Usbstor.pnf</code> and <code>Usbstor.inf</code></p> <pre><code>cacls %windir%\Inf\Usbstor.pnf /d user cacls %windir%\Inf\Usbstor.inf /d user </code></pre> <p>Where <code>user</code> is the user account that you want to deny access for.</p> <p>To enable use</p> <pre><code>cacls %windir%\Inf\Usbstor.pnf /p user:R cacls %windir%\Inf\Usbstor.inf /p user:R </code></pre> <p>Both commands will need admin rights.</p> <p>Hope this helps</p>
48,981,833
Issues with getting started with webpack 4
<p>I am following the tutorial exactly as given <a href="https://webpack.js.org/guides/getting-started/" rel="noreferrer">here</a> . But I am amazed that the docs seems outdated. e.g</p> <p><code>npx webpack src/index.js dist/bundle.js</code> fails with:</p> <blockquote> <p>The CLI moved into a separate package: webpack-cli. Please install 'webpack-cli' in addition to webpack itself to use the CLI. -> When using npm: npm install webpack-cli -D -> When using yarn: yarn add webpack-cli -D</p> </blockquote> <p>If I install webpack-cli and try again I see this error:</p> <blockquote> <p>Hash: af9bc06fd641eb0ffd1e Version: webpack 4.0.0 Time: 3865ms Built at: 2018-2-26 05:10:45 1 asset Entrypoint main = main.js <a href="https://webpack.js.org/guides/getting-started/" rel="noreferrer">1</a> (webpack)/buildin/module.js 519 bytes {0} [built] <a href="https://gist.github.com/gricard/e8057f7de1029f9036a990af95c62ba8" rel="noreferrer">2</a> (webpack)/buildin/global.js 509 bytes {0} [built] [3] ./src/index.js 212 bytes {0} [built] [4] multi ./src/index.js dist/bundle.js 40 bytes {0} [built] + 1 hidden module</p> <p>WARNING in configuration The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment. </p> <p>ERROR in multi ./src/index.js dist/bundle.js Module not found: Error: Can't resolve 'dist/bundle.js' in '/var/app/webpack_demo' @ multi ./src/index.js dist/bundle.js</p> </blockquote> <p>I hope I am not doing something crazy, given the popularity of webpack the documentation should reflect the actual behavior. Let me know if I am doing something wrong.</p> <h1>Edit</h1> <p>A details description of upgrade to <a href="https://gist.github.com/gricard/e8057f7de1029f9036a990af95c62ba8" rel="noreferrer">webpack 4</a>,that might be helpful </p>
49,178,441
6
8
null
2018-02-26 05:14:16.793 UTC
7
2020-08-26 17:04:11.957 UTC
2018-03-19 05:41:00.907 UTC
null
416,100
null
416,100
null
1
32
node.js|webpack|webpack-4
31,209
<p><s>The Webpack team is working on updating the package docs asap.</s> New guides and docs are available in the <a href="https://webpack.js.org" rel="noreferrer">webpack.js.org</a> official site.</p> <p><s>In the meantime,</s> You can also read related posts on medium:</p> <ul> <li><a href="https://medium.com/webpack/webpack-4-mode-and-optimization-5423a6bc597a" rel="noreferrer">webpack 4: mode and optimization</a></li> <li><a href="https://medium.com/webpack/webpack-4-released-today-6cdb994702d4" rel="noreferrer">webpack 4: released today!!</a></li> </ul> <p>Check on GitHub this <a href="https://github.com/carloluis/webpack-demo" rel="noreferrer">Webpack-Demo</a> project intended to be a <strong>Webpack 4 tutorial</strong>. Previous and others links to helpful resources used in the webpack configs are included in the project's <code>Readme</code>. It has two zero-config builds (using the new webpack <code>mode</code> option which includes a sets of defaults), and another two using custom configs.</p> <hr /> <p>Since <a href="/questions/tagged/webpack-4" class="post-tag" title="show questions tagged &#39;webpack-4&#39;" rel="tag">webpack-4</a>, the CLI has been move to <code>webpack-cli</code> therefore you need to install also this package in your <code>devDependencies</code>. Also, <a href="/questions/tagged/webpack" class="post-tag" title="show questions tagged &#39;webpack&#39;" rel="tag">webpack</a> expect the new <code>mode</code> configuration to be set either on the CLI run or the config object.</p> <p>CLI usage in your <code>npm</code> scripts:</p> <pre><code>&quot;scripts&quot;: { &quot;dev&quot;: &quot;webpack --mode development&quot;, &quot;prod&quot;: &quot;webpack --mode production&quot; } </code></pre> <p>Set <code>mode</code> property in your webpack config object:</p> <pre><code>{ mode: 'production' // | 'development' | 'none' } </code></pre> <p>If mode value isn't specified, webpack uses the <code>production</code> value (defaulted option). But warns you in the output with:</p> <blockquote> <p>WARNING in configuration</p> <p>The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.</p> </blockquote> <p>Webpack <code>mode</code> reduce the required configuration for an useful build by using a set of defaults (default values for configuration properties depending the <code>mode</code> value):</p> <ul> <li><code>production</code> enables all kind of optimizations to generate optimized bundles</li> <li><code>development</code> enables useful error messages and is optimized for speed</li> <li><code>none</code> is a hidden mode which disables everything</li> </ul> <p>Read more on <a href="https://github.com/webpack/webpack/releases/tag/v4.0.0" rel="noreferrer">release notes &amp; changelog</a></p>
20,927,980
Using HTML and PHP to send form data to an email
<p>Like the title says, sending a form to my email. I get no errors, but the email never comes. Here's my HTML form (I don't think you'll need anything else, but there is also some formatting and Java verification in the file).</p> <pre><code>&lt;form method="POST" name="contactform" action="contact-form-handler.php"&gt; &lt;p&gt; &lt;label for='name'&gt;Your Name:&lt;/label&gt; &lt;br&gt; &lt;input type="text" name="name"&gt; &lt;/p&gt; &lt;p&gt; &lt;label for='email'&gt;Email Address:&lt;/label&gt; &lt;br&gt; &lt;input type="text" name="email"&gt; &lt;br&gt; &lt;/p&gt; &lt;p&gt; &lt;label for='message'&gt;Message:&lt;/label&gt; &lt;br&gt; &lt;textarea name="message"&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;input type="submit" value="Submit"&gt; &lt;br&gt; &lt;/form&gt; </code></pre> <p>And here's my PHP. Obviously I took my email out and put in EMAIL instead, but other than that this is my complete PHP file. The thank you PHP file pulls up the submitted page just fine, and I get no errors. Just no email either.</p> <pre><code>&lt;?php $errors = ''; $myemail = '[email protected]'; if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message'])) { $errors .= "\n Error: all fields are required"; } $name = $_POST['name']; $email_address = $_POST['email']; $message = $_POST['message']; if (!preg_match( "/ ^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email_address)) { $errors .= "\n Error: Invalid email address"; } if( empty($errors)) { $to = '$myemail'; $email_subject = "Contact form submission: $name"; $email_body = "You have received a new message. ". " Here are the details:\n Name: $name \n ". "Email: $email_address\n Message \n $message"; $headers = "From: $myemail\n"; $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); //redirect to the 'thank you' page header('Location: contact-form-thank-you.html'); } ?&gt; </code></pre> <p>Thanks ahead of time for any help you can provide! I can give the rest of my HTML file or my other PHP file if you need it, this is where all the real functionality lies though.</p>
21,381,798
4
4
null
2014-01-04 23:23:33.26 UTC
3
2018-03-31 13:05:42.59 UTC
2014-01-04 23:28:52.42 UTC
null
186,535
null
3,161,439
null
1
2
php|html|forms|email
72,955
<p>*<em>PHP to send form data to an email i have used this code as well as its work for me .you can try *</em></p> <pre><code>&lt;?PHP $email = $_POST["emailaddress"]; $to = "[email protected]"; $subject = "New Email Address for Mailing List"; $headers = "From: $email\n"; $message = "A visitor to your site has sent the following email address to be added to your mailing list.\n Email Address: $email"; $user = "$email"; $usersubject = "Thank You"; $userheaders = "From: [email protected]\n"; $usermessage = "Thank you for subscribing to our mailing list."; mail($to,$subject,$message,$headers); mail($user,$usersubject,$usermessage,$userheaders); ?&gt; </code></pre> <p>after that you can addded your futher code </p>
21,170,493
When are higher kinded types useful?
<p>I've been doing dev in F# for a while and I like it. However one buzzword I know doesn't exist in F# is higher-kinded types. I've read material on higher-kinded types, and I think I understand their definition. I'm just not sure why they're useful. Can someone provide some examples of what higher-kinded types make easy in Scala or Haskell, that require workarounds in F#? Also for these examples, what would the workarounds be without higher-kinded types (or vice-versa in F#)? Maybe I'm just so used to working around it that I don't notice the absence of that feature.</p> <p>(I think) I get that instead of <code>myList |&gt; List.map f</code> or <code>myList |&gt; Seq.map f |&gt; Seq.toList</code> higher kinded types allow you to simply write <code>myList |&gt; map f</code> and it'll return a <code>List</code>. That's great (assuming it's correct), but seems kind of petty? (And couldn't it be done simply by allowing function overloading?) I usually convert to <code>Seq</code> anyway and then I can convert to whatever I want afterwards. Again, maybe I'm just too used to working around it. But is there any example where higher-kinded types <em>really</em> saves you either in keystrokes or in type safety?</p>
21,170,809
7
5
null
2014-01-16 18:58:15.2 UTC
45
2021-09-02 07:57:25.797 UTC
2014-01-16 19:12:27.723 UTC
null
1,288,448
null
1,288,448
null
1
94
scala|haskell|types|f#|higher-kinded-types
11,261
<p>So the kind of a type is its simple type. For instance <code>Int</code> has kind <code>*</code> which means it's a base type and can be instantiated by values. By some loose definition of higher-kinded type (and I'm not sure where F# draws the line, so let's just include it) <em>polymorphic containers</em> are a great example of a higher-kinded type.</p> <pre><code>data List a = Cons a (List a) | Nil </code></pre> <p>The type constructor <code>List</code> has kind <code>* -&gt; *</code> which means that it must be passed a concrete type in order to result in a concrete type: <code>List Int</code> can have inhabitants like <code>[1,2,3]</code> but <code>List</code> itself cannot.</p> <p>I'm going to assume that the benefits of polymorphic containers are obvious, but more useful kind <code>* -&gt; *</code> types exist than just the containers. For instance, the relations</p> <pre><code>data Rel a = Rel (a -&gt; a -&gt; Bool) </code></pre> <p>or parsers</p> <pre><code>data Parser a = Parser (String -&gt; [(a, String)]) </code></pre> <p>both also have kind <code>* -&gt; *</code>.</p> <hr /> <p>We can take this further in Haskell, however, by having types with even higher-order kinds. For instance we could look for a type with kind <code>(* -&gt; *) -&gt; *</code>. A simple example of this might be <code>Shape</code> which tries to fill a container of kind <code>* -&gt; *</code>.</p> <pre><code>data Shape f = Shape (f ()) Shape [(), (), ()] :: Shape [] </code></pre> <p>This is useful for characterizing <code>Traversable</code>s in Haskell, for instance, as they can always be divided into their shape and contents.</p> <pre><code>split :: Traversable t =&gt; t a -&gt; (Shape t, [a]) </code></pre> <hr /> <p>As another example, let's consider a tree that's parameterized on the kind of branch it has. For instance, a normal tree might be</p> <pre><code>data Tree a = Branch (Tree a) a (Tree a) | Leaf </code></pre> <p>But we can see that the branch type contains a <code>Pair</code> of <code>Tree a</code>s and so we can extract that piece out of the type parametrically</p> <pre><code>data TreeG f a = Branch a (f (TreeG f a)) | Leaf data Pair a = Pair a a type Tree a = TreeG Pair a </code></pre> <p>This <code>TreeG</code> type constructor has kind <code>(* -&gt; *) -&gt; * -&gt; *</code>. We can use it to make interesting other variations like a <code>RoseTree</code></p> <pre><code>type RoseTree a = TreeG [] a rose :: RoseTree Int rose = Branch 3 [Branch 2 [Leaf, Leaf], Leaf, Branch 4 [Branch 4 []]] </code></pre> <p>Or pathological ones like a <code>MaybeTree</code></p> <pre><code>data Empty a = Empty type MaybeTree a = TreeG Empty a nothing :: MaybeTree a nothing = Leaf just :: a -&gt; MaybeTree a just a = Branch a Empty </code></pre> <p>Or a <code>TreeTree</code></p> <pre><code>type TreeTree a = TreeG Tree a treetree :: TreeTree Int treetree = Branch 3 (Branch Leaf (Pair Leaf Leaf)) </code></pre> <hr /> <p>Another place this shows up is in &quot;algebras of functors&quot;. If we drop a few layers of abstractness this might be better considered as a fold, such as <code>sum :: [Int] -&gt; Int</code>. Algebras are parameterized over the <em>functor</em> and the <em>carrier</em>. The <em>functor</em> has kind <code>* -&gt; *</code> and the carrier kind <code>*</code> so altogether</p> <pre><code>data Alg f a = Alg (f a -&gt; a) </code></pre> <p>has kind <code>(* -&gt; *) -&gt; * -&gt; *</code>. <code>Alg</code> useful because of its relation to datatypes and recursion schemes built atop them.</p> <pre><code>-- | The &quot;single-layer of an expression&quot; functor has kind `(* -&gt; *)` data ExpF x = Lit Int | Add x x | Sub x x | Mult x x -- | The fixed point of a functor has kind `(* -&gt; *) -&gt; *` data Fix f = Fix (f (Fix f)) type Exp = Fix ExpF exp :: Exp exp = Fix (Add (Fix (Lit 3)) (Fix (Lit 4))) -- 3 + 4 fold :: Functor f =&gt; Alg f a -&gt; Fix f -&gt; a fold (Alg phi) (Fix f) = phi (fmap (fold (Alg phi)) f) </code></pre> <hr /> <p>Finally, though they're theoretically possible, I've never see an <em>even</em> higher-kinded type constructor. We sometimes see functions of that type such as <code>mask :: ((forall a. IO a -&gt; IO a) -&gt; IO b) -&gt; IO b</code>, but I think you'll have to dig into type prolog or dependently typed literature to see that level of complexity in types.</p>
46,947,557
Do yarn workspaces work with npm, too?
<p>I checked out a repo which uses yarn instead of npm as build tool.</p> <p>in the package.json, it defines workspaces to deal with multiple sub-projects:</p> <pre><code>{ "workspaces": [ "packages/*" ], "dependencies": [], "devDependencies": [ // long list ] } </code></pre> <p>As a result, the root <code>package.json</code> does not contain any runtime dependency. Just the <code>packages/*/package.json</code> contain those.</p> <p>To compile (and start in dev mode) I do:</p> <pre><code>yarn install yarn start </code></pre> <p>I have found no documentation, that <code>workspaces</code> is also recognized and correctly used by npm. </p> <p>Is there a way to make it work with npm, too?</p>
64,476,853
5
5
null
2017-10-26 06:48:51.26 UTC
6
2021-08-10 14:25:47.797 UTC
2017-10-26 06:58:33.887 UTC
null
978,392
null
978,392
null
1
36
npm|package.json|yarnpkg
27,100
<p>Now that npm v7.0.0 is out, npm supports <code>workspaces</code>. You can manage multiple packages from within a singular top-level, root package. See more at <a href="https://github.blog/2020-10-13-presenting-v7-0-0-of-the-npm-cli/" rel="noreferrer">https://github.blog/2020-10-13-presenting-v7-0-0-of-the-npm-cli/</a></p> <p>Your workflows will not get <strong>npm v7.0.0</strong> by default unless you install it using <code>npm install -g npm@7</code>.</p>
2,179,958
django - pisa : adding images to PDF output
<p>I'm using a standard example from the web (<a href="http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html" rel="noreferrer">http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html</a>) to convert a django view / template into a PDF.</p> <p>Is there an "easy" way to include images (either from a url or a reference on the server) in the template so they will show on the PDF?</p>
2,180,417
7
1
null
2010-02-01 20:48:13.457 UTC
16
2018-10-19 05:57:42.367 UTC
2013-03-08 18:24:46.487 UTC
null
1,159,478
null
263,834
null
1
35
django|pdf|image|pdf-generation|pisa
26,806
<p>I got the images working. the code is as follows:</p> <pre><code>from django.http import HttpResponse from django.template.loader import render_to_string from django.template import RequestContext from django.conf import settings import ho.pisa as pisa import cStringIO as StringIO import cgi import os def dm_monthly(request, year, month): html = render_to_string('reports/dmmonthly.html', { 'pagesize' : 'A4', }, context_instance=RequestContext(request)) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources ) if not pdf.err: return HttpResponse(result.getvalue(), mimetype='application/pdf') return HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html)) def fetch_resources(uri, rel): path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) return path </code></pre> <p>This was taken liberally from <a href="http://groups.google.com/group/xhtml2pdf/browse_thread/thread/4cf4e5e0f4c99f55" rel="noreferrer">http://groups.google.com/group/xhtml2pdf/browse_thread/thread/4cf4e5e0f4c99f55</a></p>
1,743,467
WPF UI element naming conventions
<p>Although <a href="http://en.wikipedia.org/wiki/Hungarian_notation" rel="noreferrer">Hungarian notation</a> is considered bad practice nowadays, it is still quite common to encode the type in the name of <em>user interface elements</em>, either by using a prefix (<code>lblTitle</code>, <code>txtFirstName</code>, ...) or a suffix (<code>TitleLabel</code>, <code>FirstNameTextBox</code>, ...).</p> <p>In my company, we also do this, since it makes code written by co-workers (or by yourself a long time ago) easier to read (in my experience). The argument usually raised against doing this -- you have to change the name of the variable if the type changes -- is not very strong, since changing the type of a UI element usually requires rewriting all parts of the code were it is referenced anyway.</p> <p>So, I'm thinking about keeping this practice when starting with WPF development (hmmm... should we use the <code>txt</code> prefix for TextBlocks or TextBoxes?). Is there any big disadvantage that I have missed? This is your chance to say "Don't do this, because ...".</p> <p>EDIT: I know that with databinding the need to name UI elements decreases. Nevertheless, it's necessary sometimes, e.g. when developing custom controls...</p>
1,743,609
8
2
null
2009-11-16 17:02:45.133 UTC
11
2014-11-04 07:39:30.723 UTC
2013-03-04 23:21:07.14 UTC
null
918,414
null
87,698
null
1
34
wpf|coding-style
26,988
<p>Personally, I find that WPF changes the rules when it comes to this. Often, you can get away with little or no code behind, so having the prefixes to distinguish names makes things more confusing instead of less confusing.</p> <p>In Windows Forms, every control was referenced by name in code. With a large UI, the semi-hungarian notation was useful - it was easier to distinguish what you were working with.</p> <p>In WPF, though, it's a rare control that needs a name. When you do have to access a control via code, it's often best to use attached properties or behaviors to do so, in which case you're never dealing with more than a single control. If you're working in the UserControl or Window code-behind, I'd just use "Title" and "Name" instead of "txtTitle", especially since now you'll probably only be dealing with a few, limited controls, instead of all of them.</p> <p>Even custom controls shouldn't need names, in most cases. You'll want templated names following convention (ie: PART_Name), but not actual x:Name elements for your UIs...</p>
2,020,496
How to set a border for an HTML div tag
<p>I am trying to define a border around a div tag in HTML. In some browsers the border does not appear.</p> <p><strong>Here is my HTML code:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="divActivites" name="divActivites" style="border:thin"&gt; &lt;textarea id="inActivities" name="inActivities" style="border:solid"&gt; &lt;/textarea&gt; &lt;/div&gt; </code></pre> </div> </div> </p> <p>How do I set a border for an HTML div tag?</p>
2,020,515
8
0
null
2010-01-07 13:16:10.103 UTC
34
2021-08-08 15:24:32.853 UTC
2017-02-17 18:27:49.473 UTC
null
244,537
null
194,328
null
1
253
html|css|border
833,316
<p>Try being explicit about all the border properties. For example:</p> <pre><code>border:1px solid black; </code></pre> <p>See <a href="http://www.w3schools.com/css/css_border.asp" rel="noreferrer">Border shorthand property</a>. Although the other bits are optional some browsers don't set the width or colour to a default you'd expect. In your case I'd bet that it's the width that's zero unless specified.</p>
1,600,712
a constructor as a delegate - is it possible in C#?
<p>I have a class like below:</p> <pre><code>class Foo { public Foo(int x) { ... } } </code></pre> <p>and I need to pass to a certain method a delegate like this:</p> <pre><code>delegate Foo FooGenerator(int x); </code></pre> <p>Is it possible to pass the constructor directly as a <code>FooGenerator</code> value, without having to type:</p> <pre><code>delegate(int x) { return new Foo(x); } </code></pre> <p>?</p> <p><strong>EDIT:</strong> For my personal use, the question refers to .NET 2.0, but hints/responses for 3.0+ are welcome as well.</p>
1,600,775
9
4
null
2009-10-21 13:04:51.94 UTC
12
2021-03-18 09:49:59.133 UTC
2009-10-21 14:47:51.763 UTC
null
98,528
null
98,528
null
1
65
c#|delegates|constructor
25,318
<p>Nope, the CLR does not allow binding delegates to <code>ConstructorInfo</code>.</p> <p>You can however just create your own:</p> <pre><code>static T Make&lt;T&gt;(Action&lt;T&gt; init) where T : new() { var t = new T(); init(t); return t; } </code></pre> <p>Usage</p> <pre><code>var t = Make&lt;Foo&gt;( x =&gt; { x.Bar = "bar"; x.Baz = 1; }); </code></pre>
2,033,879
What does threadsafe mean?
<p>Recently I tried to Access a textbox from a thread (other than the UI thread) and an exception was thrown. It said something about the "code not being thread safe" and so I ended up writing a delegate (sample from MSDN helped) and calling it instead.</p> <p>But even so I didn't quite understand why all the extra code was necessary.</p> <p>Update: Will I run into any serious problems if I check </p> <pre><code>Controls.CheckForIllegalCrossThread..blah =true </code></pre>
2,033,896
12
4
2010-01-09 16:24:10.37 UTC
2010-01-09 15:43:35.04 UTC
68
2021-08-16 13:47:19.317 UTC
2016-12-06 22:34:08.413 UTC
null
951,349
null
242,888
null
1
150
multithreading|thread-safety|definition
97,882
<p><a href="https://stackoverflow.com/users/88656/eric-lippert">Eric Lippert</a> has a nice blog post entitled <a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/what-is-this-thing-you-call-thread-safe" rel="noreferrer">What is this thing you call &quot;thread safe&quot;?</a> about the definition of thread safety as found of Wikipedia.</p> <p>3 important things extracted from the links :</p> <blockquote> <p>“A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads.”</p> <p>“In particular, it must satisfy the need for multiple threads to access the same shared data, …”</p> <p>“…and the need for a shared piece of data to be accessed by only one thread at any given time.”</p> </blockquote> <p>Definitely worth a read!</p>
1,500,646
Eclipse 3.5 Unable to install plugins
<p>I really don't know what's going on with Eclipse 3.5 (3.5.0 or 3.5.1, same issues), but it's been now 2 days that I'm struggling with Eclipse to find a way to make the plugins installation work via the "Install New Software screen"!!! I have visited a lot of forums and blogs, tried many solutions but in vain: each time the current problem disappears and a new one appears.</p> <p>I'm trying to make it work at my office, so behind proxy. The best advice I got so far is the one regarding the known issue with NTLM proxies: <a href="http://wiki.eclipse.org/ECF_Filetransfer_Support_for_NTLMv2_Proxies" rel="noreferrer">http://wiki.eclipse.org/ECF_Filetransfer_Support_for_NTLMv2_Proxies</a>. I put in place the hint, but now I have a new error message: Eclipse cannot find the repositories at all... For instance here is what I get now with the Galileo update site itself:</p> <pre><code>org.eclipse.equinox.internal.provisional.p2.core.ProvisionException: No repository found at http://download.eclipse.org/releases/galileo. at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.fail(AbstractRepositoryManager.java:380) at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.loadRepository(AbstractRepositoryManager.java:606) at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:92) at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:88) at org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil.loadMetadataRepository(ProvisioningUtil.java:88) at org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager.doLoadRepository(QueryableMetadataRepositoryManager.java:55) at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadRepository(QueryableRepositoryManager.java:195) at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadAll(QueryableRepositoryManager.java:108) at org.eclipse.equinox.internal.p2.ui.sdk.PreloadingRepositoryHandler$2.run(PreloadingRepositoryHandler.java:71) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) </code></pre> <p>Samething with <a href="http://download.eclipse.org/eclipse/updates/3.5" rel="noreferrer">http://download.eclipse.org/eclipse/updates/3.5</a>, or <a href="http://download.eclipse.org/tools/mylyn/update/e3.4/" rel="noreferrer">http://download.eclipse.org/tools/mylyn/update/e3.4/</a> and whatever the site: no one works.</p> <p>Please somebody help!</p> <p>PS: Some more details below:</p> <p>I have the same issue with third party software too... for instance: <a href="http://www.epic-ide.org/updates/testing/site.xml" rel="noreferrer">http://www.epic-ide.org/updates/testing/site.xml</a>.... same error message.</p> <p>If I go to Preferences > Install / Updates > Available Software Sites, click on whatever the site and on Test Connection I get a ProvisionException with this error message (when I click on details):</p> <p>Unable to read repository at <a href="http://download.eclipse.org/technology/epp/packages/galileo/site.xml" rel="noreferrer">http://download.eclipse.org/technology/epp/packages/galileo/site.xml</a>. Unable to read repository at <a href="http://download.eclipse.org/technology/epp/packages/galileo/site.xml" rel="noreferrer">http://download.eclipse.org/technology/epp/packages/galileo/site.xml</a>. Server redirected too many times (20)</p> <p><strong>the solution is:</strong> add following lines to your <code>eclipse.ini</code> file (before <code>-vmargs</code>): (verified on 3.5 ; 3.5.1; 3.6.2)</p> <pre><code>-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient -Dhttp.proxyPort=8080 -Dhttp.proxyHost=myproxy -Dhttp.proxyUser=mydomain\myusername -Dhttp.proxyPassword=mypassword -Dhttp.nonProxyHosts=localhost|127.0.0.1 </code></pre>
1,503,328
17
5
null
2009-09-30 21:01:56.677 UTC
13
2018-10-12 10:08:34.527 UTC
2011-07-25 09:59:59.793 UTC
null
131,120
null
180,782
null
1
30
java|eclipse|ide|eclipse-3.5
114,094
<p>We had tons of issues here, namely with the proxy support. We ended-up using Pulse: <a href="http://www.poweredbypulse.com/" rel="noreferrer">http://www.poweredbypulse.com/</a></p> <p>Pulse has built-in support for a few plugin, however, you can add third-party plugin and even local jar file quite easily.</p> <p>Strangely it does not always use the built-in Eclipse feature, so sometimes when Eclipse become difficult ( like in our case for the proxy business ), you can work-around it with Pulse.</p>
1,627,018
Most difficult programming explanation
<p>Recently I tried to explain some poorly designed code to my project manager. All of the manager classes are singletons ("and that's why I can't easily change this") and the code uses event dispatching everywhere that a function call would have sufficed ("and that's why it's so hard to debug"). Sadly it just came out as a fumbling mess of English.</p> <p>Whats the most difficult thing you've had to convey to a non-technical person as a programmer? Did you find any analogies or ways of explaining that made it clearer?</p>
1,627,030
26
3
2009-10-26 20:08:47.617 UTC
2009-10-26 20:03:42.34 UTC
10
2019-05-04 01:08:08.743 UTC
2012-04-29 20:45:15.753 UTC
user257111
null
null
115,503
null
1
19
theory
5,065
<p>Thread Synchronization and Dead-Locking.</p>
8,766,739
show an alert dialog in broadcast receiver after a system reboot
<p>Good day, I am trying to show an alert dialog after a system reboot in a broadcast receiver. I have added the receiver in my manifest and called the required permission, but am getting an error in showing the dialog. Please How can i implement this correctly?.. Thank you</p> <p>my code:</p> <pre><code>public void onReceive(final Context context, Intent intent) { Log.d(TAG, "received boot completed broadcast receiver... starting settings"); String settings = context.getResources().getString(R.string.restart_setting); String yes = context.getResources().getString(R.string.Settings); String no = context.getResources().getString(R.string.Cancel); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(settings) .setCancelable(false) .setPositiveButton(yes, new DialogInterface.OnClickListener() { public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) Intent config = new Intent(context, WeatherConfigure.class) context.startActivity(config); } }) .setNegativeButton(no, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) { dialog.cancel(); } }); final AlertDialog alert = builder.create(); alert.show(); } </code></pre> <p>am getting this log error:</p> <pre><code>01-07 01:42:01.559: ERROR/AndroidRuntime(2004): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 01-07 01:42:01.559: ERROR/AndroidRuntime(2004): at android.view.ViewRoot.setView(ViewRoot.java:548) 01-07 01:42:01.559: ERROR/AndroidRuntime(2004):at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177) 01-07 01:42:01.559: ERROR/AndroidRuntime(2004): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91) 01-07 01:42:01.559: ERROR/AndroidRuntime(2004):at android.app.Dialog.show(Dialog.java:288) 01-07 01:42:01.559: ERROR/AndroidRuntime(2004):at com.MuaaApps.MyWeatherUpdate.myWeatherBroadcastReceiver.onReceive(MyWeatherBroadcastReceiver.java:59) 01-07 01:42:01.559: ERROR/AndroidRuntime(2004): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1994) </code></pre>
8,766,864
7
2
null
2012-01-07 02:07:06.93 UTC
16
2021-04-24 07:31:15.493 UTC
null
null
null
null
316,843
null
1
36
android
76,635
<p>The problem is you are trying to show an <code>AlertDialog</code> from a <code>BroadcastReceiver</code>, which isn't allowed. You can't show an <code>AlertDialog</code> from a <code>BroadcastReceiver</code>. Only activities can display dialogs.</p> <p>You should do something else, have the <code>BroadcastReceiver</code> start on boot as you do and start an activity to show the dialog.</p> <p>Here is a <a href="http://commonsware.com/blog/2010/08/11/activity-notification-ordered-broadcast.html" rel="noreferrer">blog post</a> more on this.</p> <p>EDIT:</p> <p>Here is how I would recommend doing it. From your <code>BroadcastReceiver</code> start an <code>Activity</code> with an <code>AlertDialog</code> as such..</p> <pre><code>public class NotifySMSReceived extends Activity { private static final String LOG_TAG = "SMSReceiver"; public static final int NOTIFICATION_ID_RECEIVED = 0x1221; static final String ACTION = "android.provider.Telephony.SMS_RECEIVED"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); IntentFilter filter = new IntentFilter(ACTION); this.registerReceiver(mReceivedSMSReceiver, filter); } private void displayAlert() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to exit?").setCancelable( false).setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } private final BroadcastReceiver mReceivedSMSReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION.equals(action)) { //your SMS processing code displayAlert(); } } } } </code></pre> <p>As you see here I NEVER called <code>setContentView()</code>. This is because the activity will have a transparent view and only the alert dialog will show.</p>
8,647,769
What is Eclipse doing when it says that it's updating indexes?
<p>When I load up a workspace (for Android Java development), Eclipse says in the status bar that it's updating indexes. The Progress tab reports that it's hitting maven.org.</p> <p>I read up on Maven - seems like a build manager. What I don't understand is why my Android workspace needs it or why it's hitting the server in the cloud. Do I need it? If not, how do I safely remove it?</p> <p><img src="https://i.stack.imgur.com/z6aXC.png" alt="enter image description here"></p>
8,647,790
1
2
null
2011-12-27 18:05:54.973 UTC
10
2011-12-27 18:16:33.893 UTC
2011-12-27 18:16:33.893 UTC
null
751,158
null
9,382
null
1
53
java|android|eclipse|maven|m2e
31,072
<p>This is a general step that happens when m2e/m2eclipse (Maven integration for Eclipse) is installed, whether projects are actively using it or not.</p> <p>This step can be disabled through the Eclipse preferences: Window / Preferences / Maven / "Download repository index updates on startup". This option is on the main "Maven" preference page (not a child page). Just uncheck the box to prevent this from happening.</p> <p><img src="https://i.stack.imgur.com/BQgZ6.png" alt="Eclipse m2e Disable repository index updates on startup"></p> <p>The file that this is downloading is an index of all the available dependencies available in the Maven central repository for use in Maven-enabled projects, allowing them to be easily chosen and searched against within the Eclipse UI. It is mainly a user convenience, and isn't mandatory.</p>
8,529,390
Is there a quiet version of subprocess.call?
<p>Is there a variant of <code>subprocess.call</code> that can run the command without printing to standard out, or a way to block out it's standard out messages? </p>
8,529,412
4
2
null
2011-12-16 03:23:23.717 UTC
4
2020-10-14 21:45:47.327 UTC
2018-05-25 21:24:36.48 UTC
null
42,223
null
826,477
null
1
73
python|subprocess|silent
45,272
<p>Yes. Redirect its <code>stdout</code> to <code>/dev/null</code>.</p> <pre><code>process = subprocess.call([&quot;my&quot;, &quot;command&quot;], stdout=open(os.devnull, 'wb')) </code></pre>
18,017,466
Hibernate + spring version compatibility
<p>H, I want to upgrade Spring libraries in my web app. Since I am using Hibernate as well, I wanted to know if there is a way I could find which version of Hibernate is compatible with a specific version of Spring.</p> <p>I have already searched google and read similar posts of SO, but I want to know if there is a way to compare different versions of libraries/framework. </p> <p>My current setup: </p> <pre><code>Spring V2.5 Hibernate : org.hibernate.hibernate 3.2.6.ga org.hibernate.hibernate-annotations 3.3.1.ga </code></pre> <p>The latest version of Hibernate available in my repository is <code>3.5.4-FINAL</code> and <code>3.5.6-FINAL</code> for the above artifacts</p> <p><strong>UPDATE</strong> I am getting this error after upgrading Hibernate to 3.5.4 from 3.2 with Spring 2.5 (unchanged)</p> <pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in class path resource [applicationContext-hibernate.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-hibernate.xml]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Implementing class at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:881) at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:597) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:366) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1079) at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:1002) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:506) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1317) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1065) at org.apache.catalina.core.StandardHost.start(StandardHost.java:840) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463) at org.apache.catalina.core.StandardService.start(StandardService.java:525) at org.apache.catalina.core.StandardServer.start(StandardServer.java:754) at org.apache.catalina.startup.Catalina.start(Catalina.java:595) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) </code></pre>
18,019,758
4
0
null
2013-08-02 12:57:06.4 UTC
9
2022-01-11 10:01:12.187 UTC
2013-08-05 04:21:44.3 UTC
null
813,618
null
813,618
null
1
24
java|spring|hibernate|spring-mvc
49,618
<p>You can check this out in the <code>spring-orm</code> Maven POM.</p> <p>For example to check the version of Hibernate used by Spring 3.2.3.RELEASE, you can issue the following shell command:</p> <pre><code>grep -A 1 hibernate- ~/.m2/repository/org/springframework/spring-orm/3.2.3.RELEASE/spring-orm-3.2.3.RELEASE.pom </code></pre> <p>The command above would result in the following output:</p> <pre><code> &lt;artifactId&gt;hibernate-annotations&lt;/artifactId&gt; &lt;version&gt;3.4.0.GA&lt;/version&gt; -- &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;4.1.9.Final&lt;/version&gt; -- &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;3.3.2.GA&lt;/version&gt; -- &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt; &lt;version&gt;4.1.9.Final&lt;/version&gt; -- &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt; &lt;version&gt;3.4.0.GA&lt;/version&gt; </code></pre> <p>And from the output above we can deduce that Spring 3.2.3.RELEASE supports Hibernate 4.1.9.Final and 3.3.2.GA .</p> <p>Of course you can try to use Spring with different version of Hibernate, but the versions from the POM are the less likely to give you some issues.</p>
17,871,338
keep getting implicit declaration error
<p>I keep getting these errors when compiling. I modified the code that runs on an arduino to run on my raspberry pi.</p> <pre><code>test1.c: In function ‘loop’: test1.c:24:3: warning: implicit declaration of function ‘rotateDeg’ [-Wimplicit-function-declaration] test1.c:33:3: warning: implicit declaration of function ‘rotate’ [-Wimplicit-function-declaration] test1.c: At top level: test1.c:42:6: warning: conflicting types for ‘rotate’ [enabled by default] test1.c:33:3: note: previous implicit declaration of ‘rotate’ was here test1.c: In function ‘rotate’: test1.c:46:3: warning: implicit declaration of function ‘abs’ [-Wimplicit-function-declaration] test1.c: At top level: test1.c:61:6: warning: conflicting types for ‘rotateDeg’ [enabled by default] test1.c:24:3: note: previous implicit declaration of ‘rotateDeg’ was here /usr/lib/gcc/arm-linux-gnueabihf/4.6/../../../arm-linux-gnueabihf/crt1.o: In function `_start': (.text+0x34): undefined reference to `main' collect2: ld returned 1 exit status </code></pre> <p>Here is my source code:</p> <pre><code>#include &lt;wiringPi.h&gt; #include &lt;stdio.h&gt; #include &lt;stdio.h&gt; #define DIR_PIN 0 #define STEP_PIN 3 void setup() { pinMode(DIR_PIN, OUTPUT); pinMode(STEP_PIN, OUTPUT); } void loop(){ rotateDeg(360, 1); delay(1000); rotateDeg(-360, .1); //reverse delay(1000); rotate(1600, .5); delay(1000); rotate(-1600, .25); //reverse delay(1000); } void rotate(int steps, float speed){ //rotate a specific number of microsteps (8 microsteps per step) - (negitive for reverse movement) //speed is any number from .01 -&gt; 1 with 1 being fastest - Slower is stronger int dir = (steps &gt; 0)? HIGH:LOW; steps = abs(steps); digitalWrite(DIR_PIN,dir); float usDelay = (1/speed) * 70; for(int i=0; i &lt; steps; i++){ digitalWrite(STEP_PIN, HIGH); delayMicroseconds(usDelay); digitalWrite(STEP_PIN, LOW); delayMicroseconds(usDelay); } } void rotateDeg(float deg, float speed){ //rotate a specific number of degrees (negitive for reverse movement) //speed is any number from .01 -&gt; 1 with 1 being fastest - Slower is stronger int dir = (deg &gt; 0)? HIGH:LOW; digitalWrite(DIR_PIN,dir); int steps = abs(deg)*(1/0.225); float usDelay = (1/speed) * 70; for(int i=0; i &lt; steps; i++){ digitalWrite(STEP_PIN, HIGH); delayMicroseconds(usDelay); digitalWrite(STEP_PIN, LOW); delayMicroseconds(usDelay); } } </code></pre>
17,873,142
5
0
null
2013-07-26 01:16:10.707 UTC
4
2013-07-26 09:33:28.827 UTC
2013-07-26 01:41:01.583 UTC
null
1,009,479
null
1,748,918
null
1
8
c|arduino|raspberry-pi
91,039
<p>You get an implicit declaration warning when there is an implicitly declared function.</p> <blockquote> <p>An implicitly declared function is a function which has neither a prototype nor a definition and that's why a compiler cannot verify that what do you want to do with the function.</p> </blockquote> <p>If no prior declaration of a function is available then its first instance is assumed to be a declaration implicitly with return type <code>int</code> and nothing is assumed about the parameters.</p> <p>Just leave a declaration of functions <code>rotate</code> and <code>rotatedeg</code> like this :</p> <pre><code>void rotate (int , float ); </code></pre> <p>and </p> <pre><code>void rotateDeg (float , float ); </code></pre> <p>Before using it in loop :</p> <pre><code>void loop(){ rotateDeg(360, 1); .... .... rotate(1600, .5); ... rotate(-1600, .25); //reverse delay(1000); } </code></pre> <p>Also use <code>#include&lt;math.h&gt;</code> before using any mathematical functions like <code>abs();</code> .</p> <p>The bottom line is , you have to make your compiler know about the functions you are using.</p>
6,920,285
Ruby - remove pattern from string
<p>I have a string pattern that, as an example, looks like this:</p> <pre><code>WBA - Skinny Joe vs. Hefty Hal </code></pre> <p>I want to truncate the pattern "WBA - " from the string and return just "Skinny Joe vs. Hefty Hal".</p>
6,920,297
3
1
null
2011-08-03 00:16:43.487 UTC
5
2015-08-04 09:52:51.517 UTC
2011-08-03 00:18:34.127 UTC
null
182,590
null
251,257
null
1
29
ruby|regex|string
47,148
<p>Assuming that the "WBA" spot will be a sequence of any letter or number, followed by a space, dash, and space:</p> <pre><code>str = "WBA - Skinny Joe vs. Hefty Hal" str.sub /^\w+\s-\s/, '' </code></pre> <p>By the way — <a href="http://regexpal.com/" rel="noreferrer">RegexPal</a> is a great tool for testing regular expressions like these.</p>
6,395,978
Is D2 language ready for production?
<p>I've been eagerly learning D language these last days. It looks like a dream for me as a supporter of several millions lines of C++ code. We support heavy performance low latency system and it is clear that C++ was the only option in the last ten years. Now, I see D.</p> <p>So, my questions are pretty obvious. Can I start thinking about migration commercial software product to D language? Is there any example of such migration or existing big commercial software product written on D from the scratch? </p> <p>How is it safe to invest in this language now? Do we have production quality compiler and debugger? Can we assume that they will be supported and developed?</p> <p>If you have any experience in migration from C++ to D, it would be great to hear about it from you.</p> <p>PS. By D I mean D2</p> <p>Thank you</p>
6,405,361
3
8
null
2011-06-18 12:25:25.317 UTC
10
2011-06-20 20:14:08.553 UTC
2011-06-20 06:17:38.82 UTC
null
470,560
null
194,635
null
1
30
d
3,099
<p>I wouldn't consider D2 to be production ready yet, but it's getting close. The language definition is fairly stable. Very few breaking changes should be happening at this point (though some additive changes intended to iron out key issues in the language may occur). Development on the compiler is moving forward very quickly, and a lot of bugs are getting fixed. But at this point, if you use D2 heavily, you <em>will</em> run into compiler bugs, particularly if you use newer language features. And not all of those features have been fully implemented yet (e.g. <code>alias this</code> and <code>inout</code>), so while <a href="https://rads.stackoverflow.com/amzn/click/com/0321635361" rel="noreferrer" rel="nofollow noreferrer">TDPL</a> is mostly correct, dmd is still somewhat behind it.</p> <p>Also, while the standard library, Phobos, is very good overall and much of it is stable, it's still very much a work in progress. We're trying to avoid causing immediate breaking changes by putting stuff that we're removing through the proper deprecation path (generally 6 months as scheduled for deprecation and 6 months as deprecated before complete removal), but sometimes immediate breaking changes <em>do</em> occur (and sometimes the compiler causes breaking changes as it's worked on). In some cases, entire modules are going to be overhauled (e.g. std.xml and std.stream). Possibly the biggest annoyance in that regard is std.container, which is fairly new, doesn't have a whole lot in it yet, and could have a significant redesign as Andrei Alexandrescu sorts out how we're going to deal with memory management in it. So, container support is improving but generally lacking. All in all, a lot of Phobos is fairly stable, but it's definitely not set in stone.</p> <p>There is definitely support for both dmd and Phobos in that if you post things to <a href="http://d.puremagic.com/issues" rel="noreferrer">bugzilla</a> or discuss them on <a href="http://digitalmars.com/NewsGroup.html" rel="noreferrer">the newsgroup</a>, people will generally be quite helpful and devs will try and fix bugs in a timely manner, but most of the people working on it do so in their free time, so sometimes it can take a while. The switch to <a href="https://github.com/D-Programming-Language" rel="noreferrer">github</a> has definitely improved matters though. I know that <a href="http://digitalmars.com/" rel="noreferrer">Digital Mars</a> provides additional support for dmc if you pay for it, but I don't know if they'll do the same for dmd. I expect that there's a good chance that they will though (certainly, if they don't now, I would expect them to do so in the future).</p> <p>As for the quality of the compiler, dmd uses Digital Mars' dmc as its backend, and dmc is the newest incarnation of the first C++ compiler to compile code natively (as opposed to translating it to C first), and Walter Bright, the creator of D, has been working on it ever since he created it. He's one of the best compiler writers out there and has created a number of optimizations which have become standard in C++ compilers (such as <a href="http://en.wikipedia.org/wiki/Return_value_optimization" rel="noreferrer">Return Value Optimization</a>), but dmc doesn't have a lot of people working on it, and there are some areas in which it has fallen behind (such as floating point optimizations), and D is new enough that there's a lot of work to be done in optimizing it. As the bugs are fixed, I'm sure that more focus will eventually shift towards optimizing the language, and it will eventually be on par with C++ in most circumstances (and better in some), but right now it really depends on your code. Sometimes D is on par; sometimes it isn't.</p> <p>Some people <em>do</em> use D2 in production code (in particular, I know that Adam D. Ruppe uses it for web development with the companies that he works with - he's a frequent poster on the D newsgroup), but I don't think that there are very many of them, and they generally avoid the newer, fancier features of the language (which is generally where the worst bugs are). How stable it's going to be is really going to depend on what you do with the language.</p> <p><a href="http://www.prowiki.org/wiki4d/wiki.cgi?LanguageDevel" rel="noreferrer">The wiki</a> has some good information on the work remaining to be done, and <a href="http://www.digitalmars.com/d/archives/digitalmars/D/What_remains_to_be_done_for_D2_138480.html" rel="noreferrer">this recent thread</a> on the newsgroup has some good info as well.</p> <p>D is definitely approaching the point where I would consider it production ready, but there's definitely some risk at this point. It's <em>great</em> for hobby stuff, but if your livelihood depends on it, I don't know if the risk is worth it quite yet. It's getting close though. It's probably worth your time to look into it, try it out, experiment with it, etc. But I wouldn't just dive in with your production code and convert it all to D. It might work out great, but it might not. I expect that a year from now, I'll be able to say that D2 is production ready, but I don't know how much sooner than that I'll feel comfortable in saying so.</p>
6,701,023
What is the strong property attribute
<p>I am using the Xcode beta for developers, and am noticing some subtle differences. Among them is a new attribute for declared properties.</p> <pre><code>@property(strong)IBOutlet NSArrayController *arrayControl; </code></pre> <p>My question is: what does the strong attribute mean?? Does it replace some older one, or is it something entirely new? I have searched through google and the developer documentation and havent been able to find anything. Until i know what it is i am hesitant to use it.</p> <p>Thanks in advance</p>
6,701,058
3
3
null
2011-07-14 23:09:16.797 UTC
17
2012-12-02 19:19:57.07 UTC
null
null
null
null
397,313
null
1
80
iphone|objective-c|ios|cocoa|macos
36,698
<p>It's a replacement for the <code>retain</code> attribute, as part of <a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html" rel="noreferrer">Objective-C Automated Reference Counting (ARC)</a>. In non-ARC code it's just a synonym for <code>retain</code>.</p>
6,880,817
ios avplayer trigger streaming is out of buffer
<p>I want to reconnect to the server when the streaming buffer is empty.</p> <p>How can I trigger a method when the <code>AVPlayer</code> or <code>AVPlayerItem</code> buffer is empty?</p> <p>I know there are <code>playbackLikelyToKeepUp</code>, <code>playbackBufferEmpty</code> and <code>playbackBufferFull</code> methods to check the buffer status, but those are not callbacks.</p> <p>Are there any callback functions, or any observers I should add?</p>
7,195,954
4
0
null
2011-07-30 02:59:13.283 UTC
21
2016-11-21 00:13:33.59 UTC
2016-11-21 00:13:33.59 UTC
null
1,524,136
null
870,280
null
1
16
ios|audio-streaming|avplayer
18,210
<p>you can add observer for those keys:</p> <pre><code>[playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil]; [playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil]; </code></pre> <p>The first one will warn you when your buffer is empty and the second when your buffer is good to go again.</p> <p>Then to handle the key change you can use this code:</p> <pre><code>- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (!player) { return; } else if (object == playerItem &amp;&amp; [keyPath isEqualToString:@"playbackBufferEmpty"]) { if (playerItem.playbackBufferEmpty) { //Your code here } } else if (object == playerItem &amp;&amp; [keyPath isEqualToString:@"playbackLikelyToKeepUp"]) { if (playerItem.playbackLikelyToKeepUp) { //Your code here } } } </code></pre>