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
33,208,518
Difference between 0x0A and 0x0D
<p>I was studying about bluetooth and I was trying to write the code to keep listening to the input stream while connected and i came across this following code snippet:</p> <pre><code>int data = mmInStream.read(); if(data == 0x0A) { } else if(data == 0x0D) { buffer = new byte[arr_byte.size()]; for(int i = 0 ; i &lt; arr_byte.size() ; i++) { buffer[i] = arr_byte.get(i).byteValue(); } // Send the obtained bytes to the UI Activity mHandler.obtainMessage(BluetoothState.MESSAGE_READ , buffer.length, -1, buffer).sendToTarget(); arr_byte = new ArrayList&lt;Integer&gt;(); } else { arr_byte.add(data); } </code></pre> <p>Can someone explain what is the difference between 0x0A and 0x0D. And also give a brief explanation about this code. Kindly share your views. </p>
33,208,588
3
1
null
2015-10-19 07:07:58.14 UTC
4
2022-07-01 08:13:28.193 UTC
2015-10-19 07:24:58.59 UTC
null
5,199,989
null
5,350,816
null
1
14
java|bluetooth|hex|character|buffer
61,396
<p>The values starting <code>0x</code> are hexadecimals. <code>0x0A</code> is <code>\n</code> newline character and <code>0x0D</code> is <code>\r</code> return character. You can read more about how to convert them <a href="http://www.javamex.com/tutorials/conversion/decimal_hexadecimal.shtml" rel="noreferrer">here</a>, or use the <a href="http://www.bluesock.org/~willg/dev/ascii.html" rel="noreferrer">conversion chart</a></p> <p>The code essentially runs different blocks of logic depending on what value of <code>data</code> is read from the <code>mmInStream</code></p> <p>Briefly:</p> <ul> <li>when the <code>data</code> is <code>0x0A</code>, the newline character <code>\n</code>, it is skipped and not added to the <code>arr_byte</code></li> <li>when the <code>data</code> is <code>0x0D</code>, the return character <code>\r</code>, it builds a buffer from <code>arr_byte</code> and send the buffer to the UI Activity</li> <li>when the <code>data</code> is any other character, it is added to <code>arr_byte</code></li> </ul> <p>Hope this helps.</p>
9,225,300
denyhosts keeps adding back my IP
<p>I am trying to unblock an IP from which I was doing some tests. I have followed the tutorials on the net:</p> <pre><code>$ sudo /etc/init.d/denyhosts stop $ sudo vim /etc/deny.hosts [remove the last line where I can see my IP to clear] $ cd /var/lib/denyhosts/ $ sudo vim * [remove any occurences of my IP to clear] $ sudo /etc/init.d/denyhosts start </code></pre> <p>At this moment my IP appears back into /etc/deny.hosts. I tried also:</p> <pre><code>$ cd /var/lib/denyhosts/ $ echo '123.456.789.122' &gt;&gt; /var/lib/denyhosts/allowed-hosts </code></pre> <p>I also tried:</p> <pre><code>$ echo 'my.ip.to.clear' &gt;&gt; /etc/hosts.allow </code></pre> <p>Unfortunately the hosts.deny always takes precedence, and refuse ssh connection, as can be seen from the log file:</p> <blockquote> <p>Feb 10 10:06:24 ks123456 sshd[22875]: refused connect from 123.456.789.122 (123.456.789.122)</p> </blockquote> <p>ref: debian/6.0.4, denyhosts 2.6-10</p>
11,634,558
9
0
null
2012-02-10 09:10:03.177 UTC
16
2020-05-19 23:44:22.543 UTC
null
null
null
null
136,285
null
1
24
ssh
37,275
<p>The instructions to remove an entry for denyhosts can be found here: <a href="http://www.cyberciti.biz/faq/linux-unix-delete-remove-ip-address-that-denyhosts-blocked/">http://www.cyberciti.biz/faq/linux-unix-delete-remove-ip-address-that-denyhosts-blocked/</a>. In Ubuntu the denyhosts data files are located at <code>/var/lib/denyhosts</code>.</p> <ol> <li>Make sure there are not entries that represent the domain name for your IP address in denyhosts.</li> <li>After removing all occurrences of your IP address, and domain name from /etc/deny.hosts (/etc/hosts.deny for Ubuntu) if you are still unable to log in, check the authentication log usually in: <code>/var/log/auth.log</code> It may give you clues to what your problem is.</li> <li>If you are running linux on both the server and client, you may want to use ssh-copy-id so that you don't need a password to login to prevent locking yourself out by using the wrong password too many times in the future.</li> </ol> <p>I had problems myself because I had a location saved in Dolphin on KDE to my sever using sftp. Dolphin uses your current username to try logging in which was getting my IP added to the hosts.deny file.</p>
9,205,000
bash: defining a file-local variable invisible to sourcing script
<p>Say I have a bash script file <code>config.sh</code>. It's meant to be source'd by other scripts and variables defined is used as customization of the upper-level scripts.</p> <p>The problem is, if <code>config.sh</code> has a temporary variable and its name conflicts with upper-level scripts' variable, it breaks the upper-level one.</p> <p>config.sh:</p> <pre><code>TMP1=abc CONFIG_INPUT_DIR="$TMP1"/in CONFIG_OUTPUT_DIR="$TMP1"/out </code></pre> <p>upper-level script:</p> <pre><code>TMP1=def source config.sh echo $TMP1 </code></pre> <p>The last <code>echo</code> prints <code>abc</code>, not <code>def</code>.</p> <h1>Solution 1</h1> <p>My current solution is to append a random string to the temporary variable name to make it almost impossible to conflict. e.g:</p> <pre><code>TMP1_vFc9Uiew=abc CONFIG_INPUT_DIR="$TMP1_vFc9Uiew"/in CONFIG_OUTPUT_DIR="$TMP1_vFc9Uiew"/out unset TMP1_vFc9Uiew </code></pre> <p>which is painful and makes the code hard to read, in addition not to be perfect.</p> <h1>Solution 2 using <code>local</code> keyword</h1> <p>After some searching, I've come to know <code>local</code> keyword. But when I simply declare <code>TMP1</code> as <code>local</code>, bash complains that <code>config.sh: line 1: local: can only be used in a function</code>.</p> <p>So my another solution is to enclose whole config script as a function:</p> <pre><code>function config_func_rZ0Yqkpm() { local TMP1=abc CONFIG_INPUT_DIR="$TMP1"/in CONFIG_OUTPUT_DIR="$TMP1"/out } config_func_rZ0Yqkpm unset config_func_rZ0Yqkpm </code></pre> <p>which is better than previous solution in maintainability and readability, but there's some possibility to conflict as well as solution 1.</p> <h1>Question</h1> <p>I want to know more robust and smart solution without any possibility to conflict.</p> <p>Thanks.</p>
9,205,183
4
0
null
2012-02-09 03:25:38.407 UTC
6
2012-02-09 23:04:09.887 UTC
null
null
null
null
402,996
null
1
33
bash
9,565
<p>A trick I learned from the <a href="http://en.gentoo-wiki.com/wiki/Keychain" rel="noreferrer"><code>keychain</code></a> utility is using one program to build a <code>source</code>-able file containing just the variables that you want to export from your program. You could modify your script to <code>echo</code> the variables you want to set and then source the <em>output</em> from your program:</p> <pre><code>$ echo $FOO $ source &lt;(echo FOO=bar) $ echo $FOO bar $ </code></pre> <p>I used <code>echo FOO=bar</code> to simulate the larger script; your program is probably more involved. The important part is that you must modify your program to output the variables and values you would like to set, rather than just setting them. This lets you decide which variables to expose and which ones to hold private at the cost of another shell process.</p>
10,694,661
document.getElementById().value return undefined in chrome
<pre><code>&lt;div id="hour" style="display: none"&gt;2&lt;/div&gt; </code></pre> <p>JavaScript code:</p> <pre><code>&lt;script type="text/javascript"&gt; var _h = document.getElementById('hour').value alert(_h); &lt;/script&gt; </code></pre> <p>Chrome returns <code>undefined</code>. What is the problem?</p>
10,694,721
4
1
null
2012-05-22 01:23:02.26 UTC
7
2021-02-05 01:35:09.8 UTC
2015-07-30 13:12:18.39 UTC
null
1,015,495
null
1,368,957
null
1
14
javascript
59,179
<p>The <code>.value</code> property applies to form elements (inputs), not divs. The simplest way to get the contents of your div element is with <code>.innerHTML</code>:</p> <pre><code>document.getElementById('hour').innerHTML; </code></pre>
10,828,863
What is the use of Custom Class Loader
<p>Recently I came accross the java custom class loader api. I found one use over here, <a href="http://kamranzafar.org/weblog/2006/12/25/loading-classes-directly-from-jar-files/" rel="noreferrer">kamranzafar's blog</a> I am a bit new to the class loader concept. Can any one explain in detail, what are the different scenarios where we may need it or we should use it?</p>
10,829,369
3
1
null
2012-05-31 07:02:33.06 UTC
15
2020-06-11 15:29:16.03 UTC
2015-12-21 07:41:14.447 UTC
null
1,207,049
null
1,392,956
null
1
28
java|classloader
15,513
<p>Custom class loaders are useful in larger architectures consisting of several module/applications. Here are the advantages of the custom class loader:</p> <ul> <li><strong>Provides Modular architecture</strong> Allows to define multiple class loader allowing modular architecture.</li> <li><strong>Avoiding conflicts</strong> Clearly defines the scope of the class to within the class loader. </li> <li><strong>Support Versioning</strong> Supports different versions of class within same VM for different modules.</li> <li><strong>Better Memory Management</strong> Unused modules can be removed which unloads the classes used by that module, which cleans up memory.</li> <li><strong>Load classes from anywhere</strong> Classes can be loaded from anywhere, <strong>for ex, Database, Networks, or even define it on the fly</strong>.</li> <li><strong>Add resources or classes dynamically</strong> All the above features allows you add classes or resources dynamically.</li> <li><strong>Runtime Reloading Modified Classes</strong> Allows you to reload a class or classes runtime by creating a child class loader to the actual class loader, which contains the modified classes.</li> </ul>
22,512,992
How to use the 'main' parameter in package.json?
<p>I have done quite some search already. However, still having doubts about the 'main' parameter in the package.json of a Node project.</p> <ol> <li>How would filling in this field help? Asking in another way, can I start the module in a different style if this field presents?</li> <li>Can I have more than one script filled into the main parameter? If yes, would they be started as two threads? If no, how can I start two scripts in a module and having them run in parallel?</li> </ol> <p>I know that the second question is quite weird. It is because I have hosted a Node.js application on OpenShift but the application consists of two main components. One being a REST API and one being a notification delivering service.</p> <p>I am afraid that the notification delivering process would block the REST API if they were implemented as a single thread. However, they have to connect to the same MongoDB cartridge. Moreover, I would like to save one gear if both the components could be serving in the same gear if possible.</p> <p>Any suggestions are welcome.</p>
22,513,200
8
1
null
2014-03-19 16:59:26.96 UTC
41
2022-08-21 14:14:04.983 UTC
2022-08-21 14:14:04.983 UTC
null
4,344,438
null
2,621,216
null
1
218
javascript|node.js|rest|asynchronous
154,455
<p>From <a href="https://docs.npmjs.com/files/package.json#main">the npm documentation</a>:</p> <blockquote> <p>The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.</p> <p>This should be a module ID relative to the root of your package folder.</p> <p>For most modules, it makes the most sense to have a main script and often not much else.</p> </blockquote> <p>To put it short:</p> <ol> <li>You only need a <code>main</code> parameter in your <code>package.json</code> if the entry point to your package differs from <code>index.js</code> in its root folder. For example, people often put the entry point to <code>lib/index.js</code> or <code>lib/&lt;packagename&gt;.js</code>, in this case the corresponding script must be described as <code>main</code> in <code>package.json</code>.</li> <li>You can't have two scripts as <code>main</code>, simply because the entry point <code>require('yourpackagename')</code> must be defined unambiguously.</li> </ol>
22,621,754
How can I merge two maps in go?
<p>I have a recursive function that creates objects representing file paths (the keys are paths and the values are info about the file). It's recursive as it's only meant to handle files, so if a directory is encountered, the function is recursively called on the directory.</p> <p>All that being said, I'd like to do the equivalent of a set union on two maps (i.e. the "main" map updated with the values from the recursive call). Is there an idiomatic way to do this aside from iterating over one map and assigning each key, value in it to the same thing in the other map?</p> <p>That is: given <code>a,b</code> are of type <code>map [string] *SomeObject</code>, and <code>a</code> and <code>b</code> are eventually populated, is there any way to update <code>a</code> with all the values in <code>b</code>?</p>
22,621,838
5
2
null
2014-03-24 22:17:51.03 UTC
12
2022-07-17 13:01:23.257 UTC
2022-05-17 12:55:17.567 UTC
null
2,541,573
null
301,749
null
1
115
dictionary|go|union
112,966
<p>There is no built in way, nor any method in the standard packages to do such a merge.</p> <p>The idomatic way is to simply iterate:</p> <pre><code>for k, v := range b { a[k] = v } </code></pre>
31,790,344
Determine if a point reside inside a leaflet polygon
<p>Suppose I Draw a polygan using leaflet like in the follow demo: <a href="http://leaflet.github.io/Leaflet.draw/" rel="noreferrer">http://leaflet.github.io/Leaflet.draw/</a></p> <p>My question is how I can determine if a given point reside inside the polygon or not.</p>
31,813,714
3
2
null
2015-08-03 14:47:31.583 UTC
14
2019-10-02 17:53:43.017 UTC
2015-08-04 16:25:15.183 UTC
null
725,573
null
5,084,891
null
1
29
leaflet|polygon|point-in-polygon
29,835
<p>Use the Ray Casting algorithm for checking if a point (marker) lies inside of a polygon:</p> <pre><code>function isMarkerInsidePolygon(marker, poly) { var polyPoints = poly.getLatLngs(); var x = marker.getLatLng().lat, y = marker.getLatLng().lng; var inside = false; for (var i = 0, j = polyPoints.length - 1; i &lt; polyPoints.length; j = i++) { var xi = polyPoints[i].lat, yi = polyPoints[i].lng; var xj = polyPoints[j].lat, yj = polyPoints[j].lng; var intersect = ((yi &gt; y) != (yj &gt; y)) &amp;&amp; (x &lt; (xj - xi) * (y - yi) / (yj - yi) + xi); if (intersect) inside = !inside; } return inside; }; </code></pre> <p>See <a href="http://jsfiddle.net/guspersson/6s1np2n4/" rel="noreferrer">jsfiddle</a> for example.</p> <p>Original source for the code: <a href="https://github.com/substack/point-in-polygon/blob/master/index.js" rel="noreferrer">https://github.com/substack/point-in-polygon/blob/master/index.js</a></p> <hr> <p>See also 2014's similar answer, <a href="https://stackoverflow.com/a/41138512/287948">https://stackoverflow.com/a/41138512/287948</a> </p>
37,054,469
Nuget Package - feed (VSTS) :Exception 'System.AggregateException' thrown when trying to add source
<p>I have created a new feed with in Package Release hub (VSTS), installed the credentials, then added the package source. </p> <p>Now, I am using Visual Studio 2015 to install Micrososft.Aspnet.mvc to a project, however it gives the following error:</p> <pre><code>Exception 'System.AggregateException' thrown when trying to add source 'https://mysite.pkgs.visualstudio.com/DefaultCollection/_packaging/MyLogUtils/nuget/v3/index.json'. Please verify all your online package sources are available. </code></pre> <p>I need to install NuGet packages normally, so I removed the feed from VSTS. However, the problem persists. How can this problem be resolved?</p>
37,154,554
13
2
null
2016-05-05 15:29:42.68 UTC
6
2021-12-28 10:58:47.77 UTC
2018-09-11 21:39:08.64 UTC
null
-1
null
1,682,401
null
1
47
visual-studio|nuget|azure-devops|nuget-package|azure-artifacts
41,415
<p>I met this issue today and fix it by following:</p> <p>If you have delete the feed from VSTS, then you need to delete it from VS\Tools\Options\Nuget Package Manager\Package Sources: <a href="https://i.stack.imgur.com/ugH3F.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ugH3F.jpg" alt="enter image description here"></a></p> <p>If you didn't delete the feed in VSTS and want to use it, sign in with your VSTS team project account from VS upper right corner and restart VS:</p> <p><a href="https://i.stack.imgur.com/SxGYo.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/SxGYo.jpg" alt="enter image description here"></a></p>
17,742,651
Column chart: how to show all labels on horizontal axis
<p>I've been trying to show all labels on the horizonal axis of my chart, but I haven't been able to do that!</p> <p>I tried using <strong>hAxis.showTextEvery=1</strong> but does not work </p> <p>(see <a href="https://developers.google.com/chart/interactive/docs/gallery/columnchart" rel="noreferrer">https://developers.google.com/chart/interactive/docs/gallery/columnchart</a>).</p> <p><img src="https://i.stack.imgur.com/P5Qmb.png" alt="enter image description here"></p> <p>Basically, <strong>I would like to also show numbers "5", "7" and "9" that are currently missing in the above chart.</strong></p> <p>Here the JavaScript code, thanks a lot.</p> <pre><code>&lt;script type="text/javascript"&gt; google.setOnLoadCallback(drawChart1); function drawChart1(){ var data = new google.visualization.DataTable( { "cols":[ {"id":"","label":"ratings","type":"number"}, {"id":"","label":"# of movies","type":"number"}], "rows":[ {"c":[{"v":9},{"v":26}]}, {"c":[{"v":8},{"v":64}]}, {"c":[{"v":10},{"v":5}]}, {"c":[{"v":7},{"v":50}]}, {"c":[{"v":6},{"v":38}]}, {"c":[{"v":5},{"v":10}]}, {"c":[{"v":2},{"v":1}]}, {"c":[{"v":4},{"v":1}]} ]}); var options = { "title":"Rating distribution", "vAxis":{"title":"# of movies","minValue":0}, "hAxis":{"title":"Ratings","maxValue":10},"legend":"none","is3D":true,"width":800,"height":400,"colors":["red"] }; var chart = new google.visualization.ColumnChart(document.getElementById('chart_movies_per_rating'));chart.draw(data, options); } &lt;/script&gt; </code></pre> <p><strong>UPDATE:</strong> this is the solution I developed, following the answer below (thanks again!). <a href="http://jsfiddle.net/mdt86/x8dafm9u/104/" rel="noreferrer">http://jsfiddle.net/mdt86/x8dafm9u/104/</a></p> <pre><code>&lt;script type="text/javascript"&gt; google.setOnLoadCallback(drawChart1); function drawChart1(){ var data = new google.visualization.DataTable( {"cols": [{"id":"","label":"ratings","type":"string"}, {"id":"","label":"# of movies","type":"number"}], "rows": [{"c":[{"v":"0"},{"v":0}]}, {"c":[{"v":" 1"},{"v":0}]}, {"c":[{"v":" 2"},{"v":1}]}, {"c":[{"v":" 3"},{"v":0}]}, {"c":[{"v":" 4"},{"v":1}]}, {"c":[{"v":" 5"},{"v":10}]}, {"c":[{"v":" 6"},{"v":38}]}, {"c":[{"v":" 7"},{"v":50}]}, {"c":[{"v":" 8"},{"v":64}]}, {"c":[{"v":" 9"},{"v":26}]}, {"c":[{"v":" 10"},{"v":5}]} ] } ); var options = {"title":"Rating distribution", "vAxis":{"title":"# of movies","minValue":0}, "hAxis":{"title":"Ratings","maxValue":10}, "legend":"none", "is3D":true, "width":800, "height":400, "colors":["CC0000"]}; var chart = new google.visualization.ColumnChart(document.getElementById('chart_movies_per_rating')); chart.draw(data, options); } &lt;/script&gt; </code></pre>
17,747,324
2
2
null
2013-07-19 09:30:06.587 UTC
5
2016-12-14 09:48:59.523 UTC
2016-12-14 09:48:59.523 UTC
null
2,560,293
null
2,560,293
null
1
15
google-visualization
48,489
<p>Your problem is related to the continuous versus discrete subtleties in <a href="https://developers.google.com/chart/interactive/docs/gallery/columnchart" rel="noreferrer"><code>ColumnChart</code></a>. Basically, you have continuous values for labels on your <code>hAxis</code>, and the <code>showTextEvery</code> only works for discrete ones. To fix this, I would do the following:</p> <ol> <li>Have all your missing ratings inserted into the chart (ie, if there are no values at rating '3', insert a zero).</li> <li>Order the ratings in the chart. (Google charts could sort this for you, but it's likely easier to just order them.)</li> <li>Change the ratings to <code>{"id":"","label":"ratings","type":"string"},</code></li> <li>Use the showTextEvery:1 in the options</li> </ol> <p>Below is some code that demonstrates this:</p> <pre><code>var data = new google.visualization.DataTable( { "cols":[ {"id":"","label":"ratings","type":"string"}, {"id":"","label":"# of movies","type":"number"}], "rows":[ {"c":[{"v":'10'},{"v":5}]}, {"c":[{"v":'9'}, {"v":26}]}, {"c":[{"v":'8'}, {"v":64}]}, {"c":[{"v":'7'}, {"v":50}]}, {"c":[{"v":'6'}, {"v":38}]}, {"c":[{"v":'5'}, {"v":10}]}, {"c":[{"v":'4'}, {"v":1}]}, {"c":[{"v":'3'}, {"v":0}]}, {"c":[{"v":'2'}, {"v":1}]}, {"c":[{"v":'1'}, {"v":0}]}, ]}); var options = { "title":"Rating distribution", "vAxis":{"title":"# of movies","minValue":0}, "hAxis":{"title":"Ratings",showTextEvery:1}, "legend":"none", "width":800,"height":400,"colors":["red"] }; </code></pre>
17,710,209
How to run make from Cygwin environment?
<p>I am trying to run linux driver on linux environment .. Following instruction to run winkvm .. stuck on point run make command using cygwin environment .. like </p> <ol> <li><p>Building original KVM drivers using Cygwin environment:</p> <p>cd kvm/kernel ## Do not type configure make ## you will get id: unrecognised emulation mode: elf_i386 but it's not error make cpobjs ## If you get not a directory message, make it and try again</p></li> </ol> <p>How to run make command .. from which console of cygwin.. getting error bash make command not found .. from cygwin terminal</p>
17,710,292
2
0
null
2013-07-17 21:06:20.17 UTC
1
2018-08-26 13:30:15.977 UTC
2013-07-17 21:12:37.683 UTC
null
827,263
null
2,593,158
null
1
31
cygwin
106,673
<p>You have to install the <code>make</code> command.</p> <p>Run the Cygwin installation/configuration program, <code>setup-x86_64.exe</code> or <code>setup-x86.exe</code> (you should already have it, downloaded from <a href="https://www.cygwin.com/install.html" rel="noreferrer">here</a>). When you get to the screen that lets you select packages to install, find <code>make</code> and select it (it's probably under "Development" or something similar).</p> <p>Then you'll be able to run <code>make</code> from the Cygwin bash command line.</p>
35,488,717
Confused about conv2d_transpose
<p>I'm getting this error message when using <code>conv2d_transpose</code>:</p> <pre><code>W tensorflow/core/common_runtime/executor.cc:1102] 0x7fc81f0d6250 Compute status: Invalid argument: Conv2DBackpropInput: Number of rows of out_backprop doesn't match computed: actual = 32, computed = 4 [[Node: generator/g_h1/conv2d_transpose = Conv2DBackpropInput[T=DT_FLOAT, padding="SAME", strides=[1, 2, 2, 1], use_cudnn_on_gpu=true, _device="/job:localhost/replica:0/task:0/cpu:0"](generator/g_h1/conv2d_transpose/output_shape, generator/g_h1/w/read, _recv_l_0)]] </code></pre> <p>However, it occurs after the graph is built while compiling the loss function (Adam). Any ideas on what would cause this? I suspect it's related to the input dimensions but I'm not sure exactly why.</p> <p>Full error: <a href="https://gist.github.com/jimfleming/75d88e888044615dd6e3">https://gist.github.com/jimfleming/75d88e888044615dd6e3</a></p> <p>Relevant code:</p> <pre><code># l shape: [batch_size, 32, 32, 4] output_shape = [self.batch_size, 8, 8, 128] filter_shape = [7, 7, 128, l.get_shape()[-1]] strides = [1, 2, 2, 1] with tf.variable_scope("g_h1"): w = tf.get_variable('w', filter_shape, initializer=tf.random_normal_initializer(stddev=0.02)) h1 = tf.nn.conv2d_transpose(l, w, output_shape=output_shape, strides=strides, padding='SAME') h1 = tf.nn.relu(h1) output_shape = [self.batch_size, 16, 16, 128] filter_shape = [7, 7, 128, h1.get_shape()[-1]] strides = [1, 2, 2, 1] with tf.variable_scope("g_h2"): w = tf.get_variable('w', filter_shape, initializer=tf.random_normal_initializer(stddev=0.02)) h2 = tf.nn.conv2d_transpose(h1, w,output_shape=output_shape, strides=strides, padding='SAME') h2 = tf.nn.relu(h2) output_shape = [self.batch_size, 32, 32, 3] filter_shape = [5, 5, 3, h2.get_shape()[-1]] strides = [1, 2, 2, 1] with tf.variable_scope("g_h3"): w = tf.get_variable('w', filter_shape, initializer=tf.random_normal_initializer(stddev=0.02)) h3 = tf.nn.conv2d_transpose(h2, w,output_shape=output_shape, strides=strides, padding='SAME') h3 = tf.nn.tanh(h3) </code></pre>
38,059,483
2
1
null
2016-02-18 17:46:09.11 UTC
11
2016-11-08 13:02:36.313 UTC
null
null
null
null
307,401
null
1
22
tensorflow
22,875
<p>Thanks for the question! You're exactly right---the problem is that the input and output dimensions being passed to tf.nn.conv2d_transpose don't agree. (The error may be detected when computing gradients, but the gradient computation isn't the problem.)</p> <p>Let's look at just the first part of your code, and simplify it a little bit:</p> <pre><code>sess = tf.Session() batch_size = 3 output_shape = [batch_size, 8, 8, 128] strides = [1, 2, 2, 1] l = tf.constant(0.1, shape=[batch_size, 32, 32, 4]) w = tf.constant(0.1, shape=[7, 7, 128, 4]) h1 = tf.nn.conv2d_transpose(l, w, output_shape=output_shape, strides=strides, padding='SAME') print sess.run(h1) </code></pre> <p>I replaced the variables with constants --- it's easier to see what's going on.</p> <p>If you try to run this code, you get a similar error:</p> <pre><code>InvalidArgumentError: Conv2DCustomBackpropInput: Size of out_backprop doesn't match computed: actual = 32, computed = 4 [[Node: conv2d_transpose_6 = Conv2DBackpropInput[T=DT_FLOAT, data_format="NHWC", padding="SAME", strides=[1, 2, 2, 1], use_cudnn_on_gpu=true, _device="/job:localhost/replica:0/task:0/cpu:0"](conv2d_transpose_6/output_shape, Const_25, Const_24)]] </code></pre> <p>Now, the error is a little misleading --- it talks about the 'out_backprop' argument to 'Conv2DCustomBackpropInput'. The key is that tf.nn.conv2d_transpose is actually just the gradient of tf.nn.conv2d, so Tensorflow uses the same code internally (Conv2DCustomBackpropInput) to compute the gradient of tf.nn.conv2d and to compute tf.nn.conv2d_transpose.</p> <p>The error means that the 'output_shape' you requested is not possible, given the shapes of 'l' and 'w'.</p> <p>Since tf.nn.conv2d_transpose is the backward (gradient) counterpart of tf.nn.conv2d, one way to see what the correct shapes should be is to use the corresponding forward operation:</p> <pre><code>output = tf.constant(0.1, shape=output_shape) expected_l = tf.nn.conv2d(output, w, strides=strides, padding='SAME') print expected_l.get_shape() # Prints (3, 4, 4, 4) </code></pre> <p>That is, in the forward direction, if you provided a tensor of shape 'output_shape', you would get out a tensor of shape (3, 4, 4, 4). So one way to fix the problem is to change the shape of 'l' to (3, 4, 4, 4); if you change the code above to:</p> <pre><code>l = tf.constant(0.1, shape=[batch_size, 4, 4, 4]) </code></pre> <p>everything works fine.</p> <p>In general, try using tf.nn.conv2d to get a feel for what the relationship between the tensor shapes is. Since tf.nn.conv2d_transpose is its backward counterpart, it has the same relationship between input, output and filter shapes (but with the roles of the input and output reversed.) </p> <p>Hope that helps!</p>
3,290,283
What is a good way to produce a random "site salt" to be used in creating password retrieval tokens?
<p>I would like to create a site-wide hash to be used as salt in creating password retrieval tokens. I have been bouncing around stackoverflow trying to get a sense of the best way to do this. </p> <p>Here's the reset process:</p> <p>When a user requests a password reset email the code generates a retrieval token:</p> <pre><code>$token = hash_hmac('sha256', $reset_hash* , $site_hash) </code></pre> <p>*$reset_hash is a hash created using phpass HashPassword() function, saved in the user table.</p> <p>I then send the token in a URL to the users email address. They click before the token times out in an hour. I match their submission with the a challenge token generated server-side. If it matches, then they are forced to choose a new password, and then login.</p> <p>I would like to know the best way to generate the $site_key. I am thinking of using another HMAC hash that is seeded by random numbers:</p> <pre><code>$site_key = hash_hmac('sha256', MCRYPT_DEV_RANDOM, MCRYPT_DEV_RANDOM); </code></pre> <p>This produces something like this:</p> <pre><code>98bb403abbe62f5552f03494126a732c3be69b41401673b08cbfefa46d9e8999 </code></pre> <p>Will this be a suitably random to be used for this purpose? Am I overcomplicating this, or approaching it the wrong way?</p> <p><a href="https://stackoverflow.com/questions/401656/secure-hash-and-salt-for-php-passwords/401684#401684">I was inspired to use HMAC by this answer</a></p> <p><strong>EDIT:</strong> I am trying to avoid a 'secret question' step urged by some of my coworkers, so I would like the reset link to provide a single step to resetting the password. Therefore, my concern is that this process be secure enough to safeguard a system containing sensitive information.</p> <p><strong>RESOLVED, for now:</strong> I am going to go with a nonce as described by The Rook as the reset token. Thanks everyone for the comments and feedback.</p>
3,291,689
1
7
null
2010-07-20 13:15:28.183 UTC
17
2013-09-18 19:46:35.33 UTC
2017-05-23 10:31:16.713 UTC
null
-1
null
225,014
null
1
15
php|security|passwords|hash|password-protection
11,222
<p>To start with, your not talking about a salt. You're talking about a <a href="http://en.wikipedia.org/wiki/Cryptographic_nonce" rel="noreferrer">Cryptographic Nonce</a>, and when you salt a password you should use a Cryptographic Nonce. In the case of resetting passwords, it should be a random number that is stored in the database. It is not advantageous to have have a "site salt".</p> <p>First and foremost I don't like <a href="http://gcov.php.net/PHP_5_2/lcov_html/standard/uniqid.c.gcov.php" rel="noreferrer">uniqid()</a> because it's a time heavy calculation and <a href="http://cwe.mitre.org/data/definitions/330.html" rel="noreferrer">time is a very weak seed</a>. <a href="http://portfolio.technoized.com/notes/26" rel="noreferrer">rand() vs mt_rand()</a>, spoiler: rand() is total crap.</p> <p>In a web application a good source for secure secrets is non-blocking access to an entropy pool such as <code>/dev/urandom</code>. As of PHP 5.3, PHP applications can use <code>openssl_random_pseudo_bytes()</code>, and the Openssl library will choose the best entropy source based on your operating system, under Linux this means the application will use <code>/dev/urandom</code>. This <a href="http://cwe.mitre.org/data/definitions/330.html" rel="noreferrer">code snip from Scott is pretty good</a>:</p> <pre><code>function crypto_rand_secure($min, $max) { $range = $max - $min; if ($range &lt; 0) return $min; // not so random... $log = log($range, 2); $bytes = (int) ($log / 8) + 1; // length in bytes $bits = (int) $log + 1; // length in bits $filter = (int) (1 &lt;&lt; $bits) - 1; // set all lower bits to 1 do { $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes))); $rnd = $rnd &amp; $filter; // discard irrelevant bits } while ($rnd &gt;= $range); return $min + $rnd; } function getToken($length=32){ $token = ""; $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz"; $codeAlphabet.= "0123456789"; for($i=0;$i&lt;$length;$i++){ $token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))]; } return $token; } </code></pre>
28,032,092
Shutdown netty programmatically
<p>I'm using netty 4.0.24.Final.</p> <p>I need to start/stop netty server programmatically.<br> On starting the server, the thread gets blocked at </p> <p><code>f.channel().closeFuture().sync()</code> </p> <p>Please help with some hints how to do it correctly. Below is the EchoServer that is called by the Main class. Thanks.</p> <pre><code>package nettytests; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; public class EchoServer { private final int PORT = 8007; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; public void start() throws Exception { // Configure the server. bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(1); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer&lt;SocketChannel&gt;() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. Thread gets blocked. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public void stop(){ bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } package nettytests; public class Main { public static void main(String[] args) throws Exception { EchoServer server = new EchoServer(); // start server server.start(); // not called, because the thread is blocked above server.stop(); } } </code></pre> <p><strong>UPDATE:</strong> I changed the EchoServer class in the following way. The idea is to start the server in a new thread and preserve the links to the EventLoopGroups. Is this the right way?</p> <pre><code>package nettytests; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * Echoes back any received data from a client. */ public class EchoServer { private final int PORT = 8007; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; public void start() throws Exception { new Thread(() -&gt; { // Configure the server. bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(1); Thread.currentThread().setName("ServerThread"); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer&lt;SocketChannel&gt;() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }).start(); } public void stop() throws InterruptedException { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } </code></pre>
28,034,689
3
1
null
2015-01-19 19:25:39.413 UTC
11
2020-08-18 12:03:13.987 UTC
2015-01-19 21:21:43.407 UTC
null
2,996,265
null
2,674,027
null
1
17
java|netty|server|shutdown
19,237
<p>One way is to make something like:</p> <pre><code>// once having an event in your handler (EchoServerHandler) // Close the current channel ctx.channel().close(); // Then close the parent channel (the one attached to the bind) ctx.channel().parent().close(); </code></pre> <p>Doing this way will end up the following:</p> <pre><code>// Wait until the server socket is closed. Thread gets blocked. f.channel().closeFuture().sync(); </code></pre> <p>No need for an extra thread on main part. Now the question is: what kind of event? It's up to you... Might be a message in the echo handler as "shutdown" that will be taken as an order of shutdown and not only "quit" which will turn as closing only the client channel. Might be something else...</p> <p>If you do not handle the shutdown from a child channel (so through your handler) but through another process (for instance looking for a stop file existing), then you need an extra thread that will wait for this event and then directly make a <code>channel.close()</code> where channel will be the parent one (from <code>f.channel()</code>) for instance...</p> <p>Many other solutions exist.</p>
2,054,669
__OBJC__ in Objective-C
<p>What does <code>__OBJC__</code> mean in Objective-C?</p> <pre><code>#import &lt;Availability.h&gt; #ifdef __OBJC__ #import &lt;Foundation/Foundation.h&gt; #import &lt;UIKit/UIKit.h&gt; #endif </code></pre>
2,054,717
3
0
null
2010-01-13 05:33:58.203 UTC
9
2022-04-27 11:10:44.607 UTC
2022-04-27 11:10:44.607 UTC
null
1,033,581
null
165,495
null
1
25
objective-c
14,101
<p>This looks like your precompiled header file.</p> <p>The precompiled header is shared between all C-dialect files in your project. It's as if all your .c, .cpp, .m and .mm files have an invisible #include directive as the first line. But the Cocoa header files are pure Objective C - trying to include them in a C/C++ source will yield nothing but syntax errors aplenty. Thus the #ifdef.</p> <p>If your project only contains Objective C files (.m/.mm), which is the typical case, the #ifdef is not really necessary. But Xcode, which generated this header in the first place, protects you all the same.</p> <p>Even if it's not a PCH file, this #ifdef only makes sense if the file is to be included from both Objective C and plain C/C++. But it does not hurt regardless.</p>
2,127,836
Ruby Print Inject Do Syntax
<p>Why is it that the following code runs fine</p> <pre><code>p (1..1000).inject(0) { |sum, i| sum + i } </code></pre> <p>But, the following code gives an error</p> <pre><code>p (1..1000).inject(0) do |sum, i| sum + i end warning: do not use Fixnums as Symbols in `inject': 0 is not a symbol (ArgumentError) </code></pre> <p>Should they not be equivalent?</p>
2,127,854
3
0
null
2010-01-24 16:42:31.197 UTC
7
2014-06-11 17:13:25.72 UTC
2014-06-11 17:13:25.72 UTC
null
1,227,991
null
84,399
null
1
30
ruby|syntax|inject
2,175
<p>The block written using the curly braces binds to the inject method, which is what your intention is, and it will work fine. </p> <p>However, the block that is encapsulated in the do/end block, will bind to the p-method. Because of this, the inject call does not have an associated block. In this case, inject will interpret the argument, in this case 0, as a method name to call on every object. Bacuase 0 is not a symbol that can be converted into a method call, this will yield a warning.</p>
8,516,498
Definition of a method signature?
<p>What is the correct definition of a method signature (or a signature of a method)?</p> <p>On google, I find various definitions:</p> <blockquote> <p>It is the combination of the method name and the parameter list</p> </blockquote> <p>Does that mean <code>method signature = method name + argument list</code>? Then I do not see difference between "<strong>method</strong>" and "<strong>method signature</strong>".</p> <p>If I have a method:</p> <pre><code>public void Foo(int x, int y) { ... } </code></pre> <p>Would my method signature be one of the following, or neither?</p> <ul> <li>Foo</li> <li>Foo(int, int)</li> <li>Foo(int x, int y)</li> <li>Foo(34, 78)</li> </ul> <p>How am I suppose to answer if someone ask me what is the method signature of the method?</p>
8,521,944
7
1
null
2011-12-15 07:27:56.56 UTC
10
2016-07-31 06:28:35.893 UTC
2016-07-31 06:28:35.893 UTC
null
3,375,713
null
529,310
null
1
24
c#|method-signature
33,427
<p>There are a number of correct answer here which define the method signature as the method name, generic arity, formal parameter arity and formal parameter types and kinds, but <em>not</em> the return type or "params" modifier.</p> <p>Though that is correct, there are some subtleties here. The way <em>the C# language</em> defines method signature is different from the way the <em>CLR</em> defines method signature, and that can lead to some interesting problems when interoperating between C# and other languages.</p> <p>For the CLR, a method signature consists of the method name, generic arity, formal parameter arity, formal parameter types and kinds, and return type. So there is the first difference; the CLR considers return type.</p> <p>The CLR also does not consider "out" and "ref" to be of different formal parameter kinds; C# does. </p> <p>The CLR also has an interesting feature called "optional and required type modifiers", usually called "modopts" and "modreqs". It is possible to annotate a type in a method signature with <em>another type</em> that tells you about the "main" type. For example, in C++ these are two different signatures:</p> <pre><code>void M(C const &amp; x); void M(C &amp; x); </code></pre> <p>Both signatures define a method M that takes a parameter of type "reference to C". But because the first one is a const reference and the second is not, the C++ language considers these to be different signatures. The CLR implements this by allowing the C++/CIL compiler to emit a modopt for a special "this is const" type on the formal parameter type. </p> <p>There is no way to read or set a mod in C#, but the C# compiler nevertheless knows about them and will honour them <em>in some ways</em>. For example, if you had a public virtual method declared in C++/CIL like:</p> <pre><code>void V(C const * x) </code></pre> <p>and you override that in a derived class written in C#, the C# compiler will <em>not</em> enforce const correctness for you; the C# compiler has no idea what the const modopt means. But the C# compiler will ensure that the overriding method is emitted into metadata with the modopt in place. This is necessary because the CLR requires signatures of overriding and overridden methods to match; the compiler has to obey the CLR rules for signature matching, not the C# rules.</p>
8,924,896
Java long number too large error?
<p>Why do I get an int number is too large where the long is assigned to min and max?</p> <pre><code>/* long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. */ package Literals; public class Literal_Long { public static void main(String[] args) { long a = 1; long b = 2; long min = -9223372036854775808; long max = 9223372036854775807;//Inclusive System.out.println(a); System.out.println(b); System.out.println(a + b); System.out.println(min); System.out.println(max); } } </code></pre>
8,924,925
2
1
null
2012-01-19 10:59:20.36 UTC
3
2017-06-25 06:11:14.417 UTC
2012-01-19 11:07:13.537 UTC
null
418,556
null
604,864
null
1
26
java
58,602
<p>All literal numbers in java are by default <code>ints</code>, which has range <code>-2147483648</code> to <code>2147483647</code> inclusive.</p> <p>Your literals are outside this range, so to make this compile you need to indicate they're <code>long</code> literals (ie suffix with <code>L</code>):</p> <pre><code>long min = -9223372036854775808L; long max = 9223372036854775807L; </code></pre> <p>Note that java supports both uppercase <code>L</code> and lowercase <code>l</code>, but I recommend <strong>not</strong> using lowercase <code>l</code> because it looks like a <code>1</code>:</p> <pre><code>long min = -9223372036854775808l; // confusing: looks like the last digit is a 1 long max = 9223372036854775807l; // confusing: looks like the last digit is a 1 </code></pre> <p><a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10" rel="noreferrer">Java Language Specification</a> for the same</p> <blockquote> <p>An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).</p> </blockquote>
8,399,184
Convert dip to px in Android
<p>I had written method to get the pixels from dip but it is not working. It give me runtime error.</p> <p>Actually I was running this method in separate class and initialized in my Activity class</p> <pre><code>Board board = new Board(this); board.execute(URL); </code></pre> <p>This code runs asynchronously. Please help me.</p> <pre><code>public float getpixels(int dp){ //Resources r = boardContext.getResources(); //float px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpis, r.getDisplayMetrics()); final float scale = this.boardContext.getResources().getDisplayMetrics().density; int px = (int) (dp * scale + 0.5f); return px; } </code></pre>
8,399,512
4
1
null
2011-12-06 11:28:58.683 UTC
13
2022-02-11 15:47:40.497 UTC
2022-02-11 15:10:28.79 UTC
null
3,501,958
null
961,524
null
1
53
android|density-independent-pixel
59,652
<p>The formula is: <strong>px = dp * (dpi / 160)</strong>, for having on a 160 dpi screen. See <em><a href="https://developer.android.com/training/multiscreen/screendensities#dips-pels" rel="nofollow noreferrer">Convert dp units to pixel units</a></em> for more information.</p> <p>You could try:</p> <pre><code>public static int convertDipToPixels(float dips) { return (int) (dips * appContext.getResources().getDisplayMetrics().density + 0.5f); } </code></pre> <p>Hope this helps...</p>
19,785,001
Custom Method Annotation using Jersey's AbstractHttpContextInjectable not Working
<p>I want to restrict some methods if they are being accessed in a non-secure manner. I'm creating a @Secure annotation that checks whether or not the request was sent over secure channels. However, I cannot create a method injectable that captures the HttpContext of the request.</p> <pre><code>@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Secure { } public class SecureProvider&lt;T&gt; implements InjectableProvider&lt;Secure, AbstractResourceMethod&gt; { @Override public ComponentScope getScope() { return ComponentScope.PerRequest; } @Override public Injectable&lt;?&gt; getInjectable(ComponentContext componentContext, Secure annotation, AbstractResourceMethod method) { return new SecureInjectable(); } } public class SecureInjectable&lt;T&gt; extends AbstractHttpContextInjectable&lt;T&gt; { @Override public T getValue(HttpContext context) { // validation here return null; } } </code></pre> <p>I'm using the Dropwizard framework, so initialization of the Providers should be as easy as:</p> <pre><code>environment.addProvider(new SessionRestrictedToProvider&lt;&gt;(new SessionAuthenticator(), "MySession")); environment.addProvider(new SecureProvider&lt;&gt;()); environment.setSessionHandler(new SessionHandler()); </code></pre> <p>Usage:</p> <pre><code>@Resource @Path("/account") public class AccountResource { @GET @Path("/test_secure") @Secure public Response isSecure() { return Response.ok().build(); } } </code></pre> <p>At this point I'm assuming that a HttpContext Injectable doesn't work on a method, but I'm at a loss as to what other options I could utilize to implement this annotation.</p>
20,618,954
3
2
null
2013-11-05 08:57:11.87 UTC
10
2015-04-16 15:13:14.067 UTC
2013-12-16 10:57:01.837 UTC
null
320,124
null
320,124
null
1
8
java|annotations|jersey|dropwizard
12,556
<p>If you don't want to use AOP, I think you can do this by implementing ResourceMethodDispatchProvider and ResourceMethodDispatchAdapter. </p> <pre><code>public class CustomDispatchProvider implements ResourceMethodDispatchProvider { ResourceMethodDispatchProvider provider; CustomDispatchProvider(ResourceMethodDispatchProvider provider) { this.provider = provider; } @Override public RequestDispatcher create(AbstractResourceMethod abstractResourceMethod) { System.out.println("creating new dispatcher for " + abstractResourceMethod); RequestDispatcher defaultDispatcher = provider.create(abstractResourceMethod); if (abstractResourceMethod.getMethod().isAnnotationPresent(Secure.class)) return new DispatcherDecorator(defaultDispatcher); else return defaultDispatcher; } @Provider public static class CustomDispatchAdapter implements ResourceMethodDispatchAdapter { @Override public ResourceMethodDispatchProvider adapt(ResourceMethodDispatchProvider provider) { return new CustomDispatchProvider(provider); } } public static class DispatcherDecorator implements RequestDispatcher { private RequestDispatcher dispatcher; DispatcherDecorator(RequestDispatcher dispatcher) { this.dispatcher = dispatcher; } public void dispatch(Object resource, HttpContext context) { if (context.getRequest().isSecure()) { System.out.println("secure request detected"); this.dispatcher.dispatch(resource, context); } else { System.out.println("request is NOT secure"); throw new RuntimeException("cannot access this resource over an insecure connection"); } } } } </code></pre> <p>In Dropwizard, add the provider like this: environment.addProvider(CustomDispatchAdapter.class);</p>
1,313,954
plotting two vectors of data on a GGPLOT2 scatter plot using R
<p>I've been experimenting with both <code>ggplot2</code> and <code>lattice</code> to graph panels of data. I'm having a little trouble wrapping my mind around the <code>ggplot2</code> model. In particular, how do I plot a scatter plot with two sets of data on each panel:</p> <p>in <code>lattice</code> I could do this:</p> <pre><code>xyplot(Predicted_value + Actual_value ~ x_value | State_CD, data=dd) </code></pre> <p>and that would give me a panel for each State_CD with each column</p> <p>I can do one column with <code>ggplot2</code>: </p> <pre><code>pg &lt;- ggplot(dd, aes(x_value, Predicted_value)) + geom_point(shape = 2) + facet_wrap(~ State_CD) + opts(aspect.ratio = 1) print(pg) </code></pre> <p>What I can't grok is how to add Actual_value to the ggplot above. </p> <p><strong>EDIT</strong> Hadley pointed out that this really would be easier with a reproducible example. Here's code that seems to work. Is there a better or more concise way to do this with ggplot? Why is the syntax for adding another set of points to ggplot so different from adding the first set of data?</p> <pre><code>library(lattice) library(ggplot2) #make some example data dd&lt;-data.frame(matrix(rnorm(108),36,3),c(rep("A",24),rep("B",24),rep("C",24))) colnames(dd) &lt;- c("Predicted_value", "Actual_value", "x_value", "State_CD") #plot with lattice xyplot(Predicted_value + Actual_value ~ x_value | State_CD, data=dd) #plot with ggplot pg &lt;- ggplot(dd, aes(x_value, Predicted_value)) + geom_point(shape = 2) + facet_wrap(~ State_CD) + opts(aspect.ratio = 1) print(pg) pg + geom_point(data=dd,aes(x_value, Actual_value,group=State_CD), colour="green") </code></pre> <p>The lattice output looks like this: <a href="https://i.stack.imgur.com/G6rf7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G6rf7.png" alt="alt text"></a><br> <sub>(source: <a href="http://www.cerebralmastication.com/wp-content/uploads/2009/08/lattice.png" rel="nofollow noreferrer">cerebralmastication.com</a>)</sub> </p> <p>and ggplot looks like this: <a href="https://i.stack.imgur.com/bQb0N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bQb0N.png" alt="alt text"></a><br> <sub>(source: <a href="http://www.cerebralmastication.com/wp-content/uploads/2009/08/ggplot.png" rel="nofollow noreferrer">cerebralmastication.com</a>)</sub> </p>
1,314,342
4
2
null
2009-08-21 19:58:39.49 UTC
13
2019-04-15 19:48:23.85 UTC
2019-04-15 19:48:17.51 UTC
null
4,751,173
null
37,751
null
1
18
r|plot|ggplot2|lattice
32,735
<p>Just following up on what Ian suggested: for ggplot2 you really want all the y-axis stuff in one column with another column as a factor indicating how you want to decorate it. It is easy to do this with <code>melt</code>. To wit:</p> <pre><code>qplot(x_value, value, data = melt(dd, measure.vars=c("Predicted_value", "Actual_value")), colour=variable) + facet_wrap(~State_CD) </code></pre> <p>Here's what it looks like for me: <a href="https://i.stack.imgur.com/nkXV0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nkXV0.png" alt="alt text"></a><br> <sub>(source: <a href="http://www.cs.princeton.edu/~jcone/example.png" rel="nofollow noreferrer">princeton.edu</a>)</sub> </p> <p>To get an idea of what <code>melt</code> is actually doing, here's the head:</p> <pre><code>&gt; head(melt(dd, measure.vars=c("Predicted_value", "Actual_value"))) x_value State_CD variable value 1 1.2898779 A Predicted_value 1.0913712 2 0.1077710 A Predicted_value -2.2337188 3 -0.9430190 A Predicted_value 1.1409515 4 0.3698614 A Predicted_value -1.8260033 5 -0.3949606 A Predicted_value -0.3102753 6 -0.1275037 A Predicted_value -1.2945864 </code></pre> <p>You see, it "melts" Predicted_value and Actual_value into one column called <code>value</code> and adds another column called <code>variable</code> letting you know what column it originally came from.</p>
785,945
Problem generating Java SOAP web services client with JDK tool wsimport from a WSDL generated by a .NET 2.0 application
<p>I'm trying to generate a client for some SOAP web services using the JDK 6 tool <code>wsimport</code>. The WSDL was generated by a .NET 2.0 application. For .NET 3.X applications, it works fine.</p> <p>When I run</p> <pre><code>wsimport -keep -p mypackage http://myservice?wsdl </code></pre> <p>it shows several error messages like this:</p> <blockquote> <p>[ERROR] A class/interface with the same name "mypackage.SomeClass" is already in use. Use a class customization to resolve this conflict. line ?? of <a href="http://myservice?wsdl" rel="noreferrer">http://myservice?wsdl</a></p> </blockquote> <p>When I generate the web services client using Axis 1.4 (using the Eclipse WebTools plug-in).</p> <p>Does anybody know what can I do in order to use the <code>wsimport</code> tool? I really don't understand what the "class customization" thing is.</p>
1,434,958
4
0
null
2009-04-24 13:54:37.7 UTC
17
2017-08-13 20:12:12.66 UTC
2009-04-24 14:27:49.057 UTC
null
57,752
null
95,504
null
1
42
java|.net|web-services|axis|wsimport
38,029
<p>I don't know if this was ever solved, but I spent some time googling for a solution to this same problem.</p> <p>I found a fix here - <a href="https://jax-ws.dev.java.net/issues/show_bug.cgi?id=228" rel="noreferrer">https://jax-ws.dev.java.net/issues/show_bug.cgi?id=228</a></p> <p>The solution is to run wsimport with the <code>-B-XautoNameResolution</code> (no spaces)</p>
25,927,961
Ensure unique field value in loopback model
<p>How to ensure uniqueness of a particular field in loopback model. Like below is the model Post, I have a field genericId in it, I want it to be unique in the database, and loopback to through an error, on duplicate key insertion.</p> <pre><code>{ "name": "Post", "plural": "Post", "base": "PersistedModel", "properties": { "genericId": { "type": "string", "required":True }, "moderatedAt": { "type": "date" } }, "validations": [], "acls": [], "methods": [] } </code></pre> <p>I have tried searching there documentation, and other examples but no success. One solution which I can think of is, to create a remoteHook for the create function, and validate this field before inserting, but looking for some other way.</p>
27,149,153
3
2
null
2014-09-19 06:48:51.487 UTC
8
2019-10-09 21:14:39.457 UTC
2014-09-19 07:05:13.897 UTC
null
3,892,259
null
922,933
null
1
21
json|node.js|strongloop|loopbackjs
16,411
<p>Set <a href="https://docs.strongloop.com/display/APIC/Validating+model+data" rel="noreferrer">validation</a> rule in your <code>common/models/post.js</code></p> <pre><code>Post.validatesUniquenessOf('genericId'); </code></pre>
30,747,892
''setup cannot find office.en-us\dwtrig20.exe''
<p>During installation of Microsoft office 2010, I get the following error, which really confuses me:</p> <blockquote> <p>setup cannot find office.en-us\dwtrig20. </p> </blockquote> <p>When I choose the folder that the office.en-us where dwtrig.exe file located it displays invalid destination.</p>
30,748,029
2
1
null
2015-06-10 05:37:44.237 UTC
null
2018-04-30 20:18:47.2 UTC
2015-06-16 13:11:37.283 UTC
null
1,118,488
user4993352
null
null
1
1
office-2010
48,792
<p>the reason that makes such ''setup cannot find office.en-us\dwtrig20.exe'' error is that it may have some some fragments from the previously existing Ms Office. </p> <p>please fix it with Fixer <a href="http://go.microsoft.com/?linkid=9737366" rel="nofollow">click here</a> to download and install. follow the instructions of the software.</p>
32,422,593
laravel BelongsTo relationship with different databases not working
<p>I've seen in several places to "stay away" from this, but alas - this is how my DB is built:</p> <pre><code>class Album extends Eloquent { // default connection public function genre() { return $this-&gt;belongsTo('genre'); } </code></pre> <p>and the Genre table:</p> <pre><code>class Genre extends Eloquent { protected $connection = 'Resources'; } </code></pre> <p>My database.php: </p> <pre><code>'Resources' =&gt; array( 'driver' =&gt; 'mysql', 'host' =&gt; 'localhost', 'database' =&gt; 'resources', 'username' =&gt; 'user', 'password' =&gt; 'password', 'charset' =&gt; 'utf8', 'collation' =&gt; 'utf8_unicode_ci', 'prefix' =&gt; '', ), 'mysql' =&gt; array( 'driver' =&gt; 'mysql', 'host' =&gt; 'localhost', 'database' =&gt; 'my_data', 'username' =&gt; 'user', 'password' =&gt; 'password', 'charset' =&gt; 'utf8', 'collation' =&gt; 'utf8_unicode_ci', 'prefix' =&gt; '', ), </code></pre> <p>and when I try to run</p> <pre><code>Album::whereHas('genre', function ($q) { $q-&gt;where('genre', 'German HopScotch'); }); </code></pre> <p>it doesn't select properly (doesn't add the database name to the table "genres"):</p> <pre><code>Next exception 'Illuminate\Database\QueryException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'my_data.genres' doesn't exist </code></pre> <p>Its important to note that this works perfectly: </p> <pre><code>Album::first()-&gt;genre; </code></pre> <p><em>Update</em></p> <p>The best I've found so far is to use the builder's "from" method to specifically name the correct connection. I've discovered that the builder inside the query can receive "from"</p> <pre><code>Album::whereHas('genre', function ($q) { $q-&gt;from('resources.genres')-&gt;where('genre', 'German HopScotch'); }); </code></pre> <p>This is a decent solution but it requires me to dig in the database php and find a good way to get the proper table and database name from the relation 'genre'. </p> <p>I will appreciate if anyone else can build on this solution and make it more general. </p>
33,222,754
12
4
null
2015-09-06 10:33:00.317 UTC
5
2022-06-13 11:01:20.837 UTC
2015-10-19 20:32:27.317 UTC
null
1,503,710
null
1,503,710
null
1
31
laravel
30,214
<p>This is my own solution and it works in general for me but its mega-complicated.</p> <p>I'm using the builder "from" method to set the table and database correctly inside the subquery. I just need to pass the correct information inside.</p> <p>Assume the subquery can be as complicated as "genres.sample" or even deeper (which means albums has a relation to genres, and genres has a relation to samples) this is how</p> <pre><code>$subQuery = 'genres.samples'; $goDeep = (with (new Album)); $tableBreakdown = preg_split('/\./', $subQuery); // = ['genres', 'samples'] // I recurse to find the innermost table $album-&gt;genres()-&gt;getRelated()-&gt;sample()-&gt;getRelated() foreach ($tableBreakdown as $table) $goDeep = $goDeep-&gt;$table()-&gt;getRelated(); // now I have the innermost, get table name and database name $alternativeConnection = Config::get("database.connections." . $goDeep-&gt;getConnectionName() . ".database"); // should be equal to the correct database name $tableName = $goDeep-&gt;getTable(); // I have to use the table name in the "from" method below Album::whereHas($subQuery, function ($q) use ($alternativeConnection, $tableName) { $q-&gt;from("$alternativeConnection.$tableName"); $q-&gt;where(....... yadda yadda); }); </code></pre> <p>tl:dr;</p> <pre><code>Album::whereHas('genres', function ($q) { $q-&gt;from('resources.genres')-&gt;where(....); }); </code></pre>
36,353,532
Angular2 OPTIONS method sent when asking for http.GET
<p>I'm trying to add <a href="https://en.wikipedia.org/wiki/Basic_access_authentication#Client_side" rel="noreferrer">basic authentification</a> to my angular2 app.</p> <pre><code>public login() { // Set basic auth headers this.defaultHeaders.set('Authorization', 'Basic ' + btoa(this.username + ':' + this.password)); console.log('username', this.username) console.log('password', this.password) console.log(this.defaultHeaders) // rest is copy paste from monbanquetapiservice const path = this.basePath + '/api/v1/development/order'; let req = this.http.get(path, { headers: this.defaultHeaders }); req.subscribe( _ =&gt; { }, err =&gt; this.onError(err) ); } </code></pre> <p>What I expect to see is a GET request with the <code>Authorization</code>header I put. </p> <p>But what I see is first a <strong>OPTIONS</strong> with this headers:</p> <pre><code>OPTIONS /api/v1/development/order HTTP/1.1 Host: localhost:8080 Connection: keep-alive Access-Control-Request-Method: GET Origin: http://localhost:3000 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36 Access-Control-Request-Headers: authorization, content-type Accept: */* Referer: http://localhost:3000/ Accept-Encoding: gzip, deflate, sdch Accept-Language: en-GB,en-US;q=0.8,en;q=0.6,fr;q=0.4 </code></pre> <p>Since my server doesn't allow <strong>OPTIONS</strong> on this url, I get an error.</p> <p>I know that some methods like PUT or POST send first an OPTIONS method to preflight the request, but GET doesn't. </p> <p>Why does angular2's http send a OPTIONS first?</p> <p>Thanks.</p>
36,353,822
2
3
null
2016-04-01 10:07:38.237 UTC
20
2016-06-30 03:12:15.573 UTC
2016-04-01 10:41:38.79 UTC
null
3,611,519
null
1,935,318
null
1
53
http|cors|angular
98,174
<p>This is the way CORS works (when using cross domain requests). With CORS, the remote Web application (here the one with domain mydomain.org) chooses if the request can be served thanks to a set of specific headers.</p> <p>The CORS specification distinguishes two distinct use cases:</p> <ul> <li><strong>Simple requests</strong>. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.</li> <li><strong>Preflighted requests</strong>. When the ‘simple requests’ use case doesn’t apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.</li> </ul> <p>It's not Angular2 that sends the OPTIONS request but the browser itself. It's not something related to Angular.</p> <p>For more details, you could have a look at this article:</p> <ul> <li><a href="http://restlet.com/blog/2015/12/15/understanding-and-using-cors/">http://restlet.com/blog/2015/12/15/understanding-and-using-cors/</a></li> </ul>
4,408,819
Adding words to spellchecker dictionary in NetBeans?
<p>My NetBeans dictionary is kind of... illiterate? It's flagging words like "website" and the "doesn" part of <code>doesn't</code>. I right-clicked expecting to see your standard <code>Add to dictionary...</code> option but found none. I browsed the menus and also found nothing.</p> <p>How do I educate my NetBeans spellchecker?</p>
4,643,437
1
1
null
2010-12-10 12:28:38.273 UTC
4
2012-07-28 00:39:18.403 UTC
null
null
null
null
188,930
null
1
34
netbeans|spell-checking
8,562
<p>It looks like the spell checker is a relatively recent addition. There are basic instructions on how to change the dictionary <a href="http://blogs.oracle.com/netbeansphp/entry/spellchecker" rel="noreferrer">here</a>. </p> <p>Adding an unknown word to the dictionary requires <code>alt + enter</code> while the cursor is on the 'misspelled' word. This might take care of the most glaring omissions.</p> <p>If it highlights just 'doesn', then it probably isn't aware of English-style contractions (i.e., it doesn't know that words can span across an apostrophe). Until that is fixed, I would recommend just adding 'doesn' as a separate word using the above method.</p>
25,426,780
How to have stored properties in Swift, the same way I had on Objective-C?
<p>I am switching an application from Objective-C to Swift, which I have a couple of categories with stored properties, for example:</p> <pre><code>@interface UIView (MyCategory) - (void)alignToView:(UIView *)view alignment:(UIViewRelativeAlignment)alignment; - (UIView *)clone; @property (strong) PFObject *xo; @property (nonatomic) BOOL isAnimating; @end </code></pre> <p>As Swift extensions don't accept stored properties like these, I don't know how to maintain the same structure as the Objc code. Stored properties are really important for my app and I believe Apple must have created some solution for doing it in Swift.</p> <p>As said by jou, what I was looking for was actually using associated objects, so I did (in another context):</p> <pre><code>import Foundation import QuartzCore import ObjectiveC extension CALayer { var shapeLayer: CAShapeLayer? { get { return objc_getAssociatedObject(self, "shapeLayer") as? CAShapeLayer } set(newValue) { objc_setAssociatedObject(self, "shapeLayer", newValue, UInt(OBJC_ASSOCIATION_RETAIN)) } } var initialPath: CGPathRef! { get { return objc_getAssociatedObject(self, "initialPath") as CGPathRef } set { objc_setAssociatedObject(self, "initialPath", newValue, UInt(OBJC_ASSOCIATION_RETAIN)) } } } </code></pre> <p>But I get an EXC_BAD_ACCESS when doing:</p> <pre><code>class UIBubble : UIView { required init(coder aDecoder: NSCoder) { ... self.layer.shapeLayer = CAShapeLayer() ... } } </code></pre> <p>Any ideas?</p>
43,056,053
21
2
null
2014-08-21 12:48:42.887 UTC
55
2022-06-21 10:59:18.747 UTC
2016-10-30 22:33:06.877 UTC
null
189,431
null
1,369,924
null
1
141
ios|swift|associated-object
128,168
<p>Associated objects API is a bit cumbersome to use. You can remove most of the boilerplate with a helper class.</p> <pre><code>public final class ObjectAssociation&lt;T: AnyObject&gt; { private let policy: objc_AssociationPolicy /// - Parameter policy: An association policy that will be used when linking objects. public init(policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) { self.policy = policy } /// Accesses associated object. /// - Parameter index: An object whose associated object is to be accessed. public subscript(index: AnyObject) -&gt; T? { get { return objc_getAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque()) as! T? } set { objc_setAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque(), newValue, policy) } } } </code></pre> <p>Provided that you can "add" a property to objective-c class in a more readable manner:</p> <pre><code>extension SomeType { private static let association = ObjectAssociation&lt;NSObject&gt;() var simulatedProperty: NSObject? { get { return SomeType.association[self] } set { SomeType.association[self] = newValue } } } </code></pre> <p>As for the solution:</p> <pre><code>extension CALayer { private static let initialPathAssociation = ObjectAssociation&lt;CGPath&gt;() private static let shapeLayerAssociation = ObjectAssociation&lt;CAShapeLayer&gt;() var initialPath: CGPath! { get { return CALayer.initialPathAssociation[self] } set { CALayer.initialPathAssociation[self] = newValue } } var shapeLayer: CAShapeLayer? { get { return CALayer.shapeLayerAssociation[self] } set { CALayer.shapeLayerAssociation[self] = newValue } } } </code></pre>
25,194,631
Is it possible to always show up/down arrows for input "number"?
<p>I want to always show up/down arrows for input "number" field. Is this possible? So far I haven't had any luck...<br><br> <a href="http://jsfiddle.net/oneeezy/qunbnL6u/">http://jsfiddle.net/oneeezy/qunbnL6u/</a> </p> <p><strong>HTML:</strong></p> <pre><code>&lt;input type="number" /&gt; </code></pre> <p><strong>CSS:</strong> </p> <pre><code>input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: "Always Show Up/Down Arrows"; } </code></pre>
25,210,414
5
3
null
2014-08-08 01:06:51.503 UTC
19
2022-05-05 06:00:16.18 UTC
null
null
null
null
301,250
null
1
101
html|css|input|webkit|shadow-dom
115,085
<p>You can achieve this (in Chrome at least) by using the Opacity property:</p> <pre><code>input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { opacity: 1; } </code></pre> <p>As stated above, this will likely only work in Chrome. So be careful using this code in the wild without a fallback for other browsers. </p>
25,421,479
Clang and undefined symbols when building a library
<p>I'm working on a C++ framework, and there's a few issues when I compile it on OSX with Clang.</p> <p>First of, I'm using some other libraries, such as openssl, and clang complains that some symbols aren't solved when I build the library. They shouldn't be: these libraries will be linked with the final binary, it shouldn't happen on an intermediary.</p> <p>Then, there's also a few methods and variables that are supposed to be implemented in the "client" binary... with GCC, no problems, but Clang also complains that these symbols can't be solved during compilation.</p> <p>How come ? What should I do ?</p> <p>Here's my CMakeLists.txt in case that can be useful:</p> <pre><code>cmake_minimum_required(VERSION 2.8) project(crails_project) set(CMAKE_CXX_FLAGS "-std=c++0x -Wall -Wno-deprecated-declarations -pedantic -DASYNC_SERVER -DSERVER_DEBUG -DUSE_MONGODB_SESSION_STORE") find_package(cppnetlib REQUIRED) include_directories(include /usr/local/include ${CPPNETLIB_INCLUDE_DIRS} .) file(GLOB crails_core src/*.cpp) file(GLOB crails_sql src/sql/*.cpp) file(GLOB crails_mongodb src/mongodb/*.cpp) add_library(crails-core SHARED ${crails_core}) add_library(crails-sql SHARED ${crails_sql}) add_library(crails-mongodb SHARED ${crails_mongodb}) </code></pre> <p>This is the command that crashes:</p> <pre><code>/usr/bin/c++ -std=c++0x -Wall -Wno-deprecated-declarations -pedantic -DASYNC_SERVER -DSERVER_DEBUG -DUSE_MONGODB_SESSION_STORE -dynamiclib -Wl,-headerpad_max_install_names -o libcrails-core.dylib -install_name /Users/michael/Personal/crails/build/libcrails-core.dylib CMakeFiles/crails-core.dir/src/assets.cpp.o CMakeFiles/crails-core.dir/src/cgi2params.cpp.o CMakeFiles/crails-core.dir/src/cipher.cpp.o [...] </code></pre> <p>And here are the two kinds of error I get:</p> <p>Undefined symbols for architecture x86_64:</p> <pre><code> "_BIO_ctrl", referenced from: Cipher::encode_base64(unsigned char*, unsigned int) const in cipher.cpp.o </code></pre> <p>And the second one:</p> <pre><code> NOTE: a missing vtable usually means the first non-inline virtual member function has no definition. "vtable for boost::detail::thread_data_base", referenced from: boost::detail::thread_data_base::thread_data_base() in server.cpp.o </code></pre>
25,442,543
3
3
null
2014-08-21 08:19:46.807 UTC
10
2015-06-19 09:13:18.94 UTC
2014-08-21 08:31:43.803 UTC
null
626,921
null
626,921
null
1
15
c++|cmake|clang
20,978
<p>Solved it ! Clang needs to receive the option <code>-undefined dynamic_lookup</code> to ignore missing symbols when compiling a library.</p> <p>Add this to the CMakeFile.txt to produce the expected effect:</p> <pre><code>if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set(CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS "${CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS} -undefined dynamic_lookup") endif() </code></pre>
39,782,418
Remove punctuations in pandas
<pre><code>code: df['review'].head() index review output: 0 These flannel wipes are OK, but in my opinion </code></pre> <p>I want to remove punctuations from the column of the dataframe and create a new column.</p> <pre><code>code: import string def remove_punctuations(text): return text.translate(None,string.punctuation) df["new_column"] = df['review'].apply(remove_punctuations) Error: return text.translate(None,string.punctuation) AttributeError: 'float' object has no attribute 'translate' </code></pre> <p>I am using python 2.7. Any suggestions would be helpful.</p>
39,782,973
3
2
null
2016-09-30 01:39:04.633 UTC
10
2018-05-23 07:06:32.913 UTC
2018-05-23 07:06:32.913 UTC
null
4,909,087
null
5,927,701
null
1
25
python|string|pandas|replace
71,601
<p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="noreferrer">Pandas str.replace</a> and regex:</p> <pre><code>df["new_column"] = df['review'].str.replace('[^\w\s]','') </code></pre>
31,243,959
Why doesn't click event always fire?
<p><em>If you're revisiting this question I've moved all the updates to the bottom so it actually reads better as a question.</em></p> <h2>The Problem</h2> <p>I've got a bit of a strange problem handling browser events using <code>D3</code>. Unfortunately this sits in quite a large application, and because I'm completely lost on what the cause is I'm struggling to find a small reproduceable example so I'm going to provide as much hopefully useful information as I can.</p> <p>So my problem is that <code>click</code> events don't seem to fire reliably for certain DOM Elements. I have two different sets of elements <strong>Filled</strong> circles and <strong>White</strong> circles. You can see in the screenshot below <em>1002</em> and <em>1003</em> are white circles, while <em>Suppliers</em> is a filled circle.</p> <p><img src="https://i.stack.imgur.com/zrhBN.png" alt="enter image description here"></p> <p>Now this problem <strong>only</strong> occurs for the white circles which I don't understand. The screenshot below shows what happens when I click the circles. The order of clicks is shown via the red numbers, and the logging associated with them. Essentially what you see is:</p> <ul> <li>mousedown</li> <li>mouseup</li> <li>sometimes a click</li> </ul> <p>The issue is a bit sporadic. I had managed to track down a realiable reproduction but after a few refreshes of the browser it's now much harder to reproduce. If I alternate click on <em>1002</em> and <em>1003</em> then I keep getting <code>mousedown</code> and <code>mouseup</code> events but never a <code>click</code>. If I click on one of them a second time then I do get a <code>click</code> event. If I keep clicking on the same one (not shown here) only every other click fires the <code>click</code> event.</p> <p>If I repeat the same process with a filled circle like <em>Suppliers</em> then it works fine and <code>click</code> is fired every single time.</p> <hr> <h2>How the Circles are created</h2> <p>So the circles (aka Planets in my code) have been created as a modular component. There for the data is looped through and an instance for each is created</p> <pre><code>data.enter() .append("g") .attr("class", function (d) { return d.promoted ? "collection moon-group" : "collection planet-group"; }) .call(drag) .attr("transform", function (d) { var scale = d.size / 150; return "translate(" + [d.x, d.y] + ") scale(" + [scale] + ")"; }) .each(function (d) { // Create a new planet for each item d.planet = new d3.landscape.Planet() .data(d, function () { return d.id; }) .append(this, d); }); </code></pre> <p>This doesn't tell you all that much, underneath a <code>Force Directed</code> graph is being used to calculate positions. The code within the <code>Planet.append()</code> function is as follows:</p> <pre><code>d3.landscape.Planet.prototype.append = function (target) { var self = this; // Store the target for later self.__container = target; self.__events = new custom.d3.Events("planet") .on("click", function (d) { self.__setSelection(d, !d.selected); }) .on("dblclick", function (d) { self.__setFocus(d, !d.focused); self.__setSelection(d, d.focused); }); // Add the circles var circles = d3.select(target) .append("circle") .attr("data-name", function (d) { return d.name; }) .attr("class", function(d) { return d.promoted ? "moon" : "planet"; }) .attr("r", function () { return self.__animate ? 0 : self.__planetSize; }) .call(self.__events); </code></pre> <p>Here we can see the circles being appended (note each Planet is actually just a single circle). The custom.d3.Events is constructed and called for the circle that has just been added to the DOM. This code is used for both the filled and the white circles, the only difference is a slight variation in the classes. The DOM produced for each looks like:</p> <h3>Filled</h3> <pre class="lang-html prettyprint-override"><code>&lt;g class="collection planet-group" transform="translate(683.080338895066,497.948470463691) scale(0.6666666666666666,0.6666666666666666)"&gt; &lt;circle data-name="Suppliers" class="planet" r="150"&gt;&lt;/circle&gt; &lt;text class="title" dy=".35em" style="font-size: 63.1578947368421px;"&gt;Suppliers&lt;/text&gt; &lt;/g&gt; </code></pre> <h3>White</h3> <pre class="lang-html prettyprint-override"><code>&lt;g class="collection moon-group" transform="translate(679.5720546510213,92.00957926233855) scale(0.6666666666666666,0.6666666666666666)"&gt; &lt;circle data-name="1002" class="moon" r="150"&gt;&lt;/circle&gt; &lt;text class="title" dy=".35em" style="font-size: 75px;"&gt;1002&lt;/text&gt; &lt;/g&gt; </code></pre> <hr> <h2>What does custom.d3.events do?</h2> <p>The idea behind this is to provide a richer event system than you get by default. For example allowing double-clicks (that don't trigger single clicks) and long clicks etc.</p> <p>When events is called with the <code>circle</code> container is executes the following, setting up some <code>raw</code> events using D3. These aren't the same ones that have been hooked up to in the <code>Planet.append()</code> function, because the <code>events</code> object exposes it's own custom dispatch. These are the events however that I'm using for debugging/logging;</p> <pre><code>custom.d3.Events = function () { var dispatch = d3.dispatch("click", "dblclick", "longclick", "mousedown", "mouseup", "mouseenter", "mouseleave", "mousemove", "drag"); var events = function(g) { container = g; // Register the raw events required g.on("mousedown", mousedown) .on("mouseenter", mouseenter) .on("mouseleave", mouseleave) .on("click", clicked) .on("contextmenu", contextMenu) .on("dblclick", doubleClicked); return events; }; // Return the bound events return d3.rebind(events, dispatch, "on"); } </code></pre> <p>So in here, I hook up to a few events. Looking at them in reverse order:</p> <h3>click</h3> <p>The click function is set to simply log the value that we're dealing with</p> <pre><code> function clicked(d, i) { console.log("clicked", d3.event.srcElement); // don't really care what comes after } </code></pre> <h3>mouseup</h3> <p>The mouseup function essentially logs, and clear up some global window objects, that will be discussed next.</p> <pre><code> function mouseup(d, i) { console.log("mouseup", d3.event.srcElement); dispose_window_events(); } </code></pre> <h3>mousedown</h3> <p>The mousedown function is a little more complex and I'll include the entirety of it. It does a number of things:</p> <ul> <li>Logs the mousedown to console</li> <li>Sets up window events (wires up mousemove/mouseup on the window object) so mouseup can be fired even if the mouse is no longer within the circle that triggered mousedown</li> <li>Finds the mouse position and calculates some thresholds</li> <li>Sets up a timer to trigger a long click</li> <li><p>Fires the mousedown dispatch that lives on the custom.d3.event object</p> <pre><code>function mousedown(d, i) { console.log("mousedown", d3.event.srcElement); var context = this; dragging = true; mouseDown = true; // Wire up events on the window setup_window_events(); // Record the initial position of the mouse down windowStartPosition = getWindowPosition(); position = getPosition(); // If two clicks happened far apart (but possibly quickly) then suppress the double click behaviour if (windowStartPosition &amp;&amp; windowPosition) { var distance = mood.math.distanceBetween(windowPosition.x, windowPosition.y, windowStartPosition.x, windowStartPosition.y); supressDoubleClick = distance &gt; moveThreshold; } windowPosition = windowStartPosition; // Set up the long press timer only if it has been subscribed to - because // we don't want to suppress normal clicks otherwise. if (events.on("longclick")) { longTimer = setTimeout(function () { longTimer = null; supressClick = true; dragging = false; dispatch.longclick.call(context, d, i, position); }, longClickTimeout); } // Trigger a mouse down event dispatch.mousedown.call(context, d, i); if(debug) { console.log(name + ": mousedown"); } } </code></pre></li> </ul> <hr> <p><strong>Update 1</strong></p> <p>I should add that I have experienced this in Chrome, IE11 and Firefox (although this seems to be the most reliable of the browsers). </p> <p>Unfortunately after some refresh and code change/revert I've struggled getting the reliable reproduction. What I have noticed however which is odd is that the following sequence can produce different results:</p> <ul> <li>F5 Refresh the Browser</li> <li>Click on <code>1002</code></li> </ul> <p>Sometimes this triggeres <code>mousedown</code>, <code>mouseup</code> and then <code>click</code>. Othertimes it misses off the <code>click</code>. It seems quite strange that this issue can occur sporadically between two different loads of the same page.</p> <p>I should also add that I've tried the following:</p> <ul> <li>Caused <code>mousedown</code> to fail and verify that <code>click</code> still fires, to ensure a sporadic error in <code>mousedown</code> could not be causing the problem. I can confirm that <code>click</code> will fire event if there is an error in <code>mousedown</code>.</li> <li>Tried to check for timing issues. I did this by inserting a long blocking loop in <code>mousedown</code> and can confirm that the <code>mouseup</code> and <code>click</code> events will fire after a considerable delay. So the events do look to be executing sequentially as you'd expect.</li> </ul> <hr> <p><strong>Update 2</strong></p> <p>A quick update after @CoolBlue's comment is that adding a namespace to my event handlers doesn't seem to make any difference. The following still experiences the problem sporadically:</p> <pre><code>var events = function(g) { container = g; // Register the raw events required g.on("mousedown.test", mousedown) .on("mouseenter.test", mouseenter) .on("mouseleave.test", mouseleave) .on("click.test", clicked) .on("contextmenu.test", contextMenu) .on("dblclick.test", doubleClicked); return events; }; </code></pre> <p>Also the <code>css</code> is something that I've not mentioned yet. The css should be similar between the two different types. The complete set is shown below, in particular the <code>point-events</code> are set to <code>none</code> just for the label in the middle of the circle. I've taken care to avoid clicking on that for some of my tests though and it doesn't seem to make much difference as far as I can tell.</p> <pre><code>/* Mixins */ /* Comment here */ .collection .planet { fill: #8bc34a; stroke: #ffffff; stroke-width: 2px; stroke-dasharray: 0; transition: stroke-width 0.25s; -webkit-transition: stroke-width 0.25s; } .collection .title { fill: #ffffff; text-anchor: middle; pointer-events: none; -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; font-weight: normal; } .collection.related .planet { stroke-width: 10px; } .collection.focused .planet { stroke-width: 22px; } .collection.selected .planet { stroke-width: 22px; } .moon { fill: #ffffff; stroke: #8bc34a; stroke-width: 1px; } .moon-container .moon { transition: stroke-width 1s; -webkit-transition: stroke-width 1s; } .moon-container .moon:hover circle { stroke-width: 3px; } .moon-container text { fill: #8bc34a; text-anchor: middle; } .collection.moon-group .title { fill: #8bc34a; text-anchor: middle; pointer-events: none; font-weight: normal; } .collection.moon-group .moon { stroke-width: 3px; transition: stroke-width 0.25s; -webkit-transition: stroke-width 0.25s; } .collection.moon-group.related .moon { stroke-width: 10px; } .collection.moon-group.focused .moon { stroke-width: 22px; } .collection.moon-group.selected .moon { stroke-width: 22px; } .moon:hover { stroke-width: 3px; } </code></pre> <hr> <p><strong>Update 3</strong></p> <p>So I've tried ruling different things out. One is to change the CSS such that the <code>white</code> circles <em>1002</em> and <em>1003</em> now use the same class and therefore same CSS as <em>Suppliers</em> which is the one that worked. You can see the image and CSS below as proof:</p> <p><img src="https://i.stack.imgur.com/EjyFh.png" alt="enter image description here"></p> <pre class="lang-html prettyprint-override"><code>&lt;g class="collection planet-group" transform="translate(1132.9999823040162,517.9999865702812) scale(0.6666666666666666,0.6666666666666666)"&gt; &lt;circle data-name="1003" class="planet" r="150"&gt;&lt;/circle&gt; &lt;text class="title" dy=".35em" style="font-size: 75px;"&gt;1003&lt;/text&gt; &lt;/g&gt; </code></pre> <p>I also decided to modify the <code>custom.d3.event</code> code as this is the most complex bit of eventing. I stripped it right back down to simply just logging:</p> <pre><code>var events = function(g) { container = g; // Register the raw events required g.on("mousedown.test", function (d) { console.log("mousedown.test"); }) .on("click.test", function (d) { console.log("click.test"); }); return events; }; </code></pre> <p>Now it seems that this still didn't solve the problem. Below is a trace (now I'm not sure why I get two click.test events fired each time - appreciate if anyone can explain it... but for now taking that as the norm). What you can see is that on the ocassion highlighted, the <code>click.test</code> did not get logged, I had to click again - hence the double <code>mousedown.test</code> before the click was registered.</p> <p><img src="https://i.stack.imgur.com/8i6HP.png" alt="enter image description here"></p> <hr> <p><strong>Update 4</strong></p> <p>So after a suggestion from @CoolBlue I tried looking into the <code>d3.behavior.drag</code> that I've got set up. I've tried removing the wireup of the drag behaviour and I can't see any issues after doing so - which could indicate a problem in there. This is designed to allow the circles to be dragged within a force directed graph. So I've added some logging in the drag so I can keep an eye on whats going on:</p> <pre><code>var drag = d3.behavior.drag() .on("dragstart", function () { console.log("dragstart"); self.__dragstart(); }) .on("drag", function (d, x, y) { console.log("drag", d3.event.sourceEvent.x, d3.event.sourceEvent.y); self.__drag(d); }) .on("dragend", function (d) { console.log("dragend"); self.__dragend(d); }); </code></pre> <p>I was also pointed to the <code>d3</code> code base for the <a href="https://github.com/mbostock/d3/blob/master/src/event/drag.js">drag event</a> which has a <code>suppressClick</code> flag in there. So I modified this slightly to see if this was suppressing the click that I was expecting.</p> <pre><code>return function (suppressClick) { console.log("supressClick = ", suppressClick); w.on(name, null); ... } </code></pre> <p>The results of this were a bit strange. I've merged all the logging together to illustrate 4 different examples:</p> <ul> <li>Blue: The click fired correctly, I noted that <code>suppressClick</code> was false.</li> <li>Red: The click didn't fire, it looks like I'd accidentally triggered a move but <code>suppressClick</code> was still false.</li> <li>Yellow: The click did fire, <code>suppressClick</code> was still false but there was an accidental move. I don't know why this differs from the previous red one.</li> <li>Green: I deliberately moved slightly when clicking, this set <code>suppressClick</code> to true and the click didn't fire.</li> </ul> <p><img src="https://i.stack.imgur.com/6a7Dt.png" alt="enter image description here"></p> <hr> <p><strong>Update 5</strong></p> <p>So looking in depth at the <code>D3</code> code a bit more, I really can't explain the inconsistencies that I see in the behavior that I detailed in update 4. I just tried something different on the off-chance to see if it did what I expected. Basically I'm forcing <code>D3</code> to <strong>never</strong> suppress the click. So in the <a href="https://github.com/mbostock/d3/blob/master/src/event/drag.js">drag event</a></p> <pre><code>return function (suppressClick) { console.log("supressClick = ", suppressClick); suppressClick = false; w.on(name, null); ... } </code></pre> <p>After doing this I still managed to get a fail, which raises questions as to whether it really is the suppressClick flag that is causing it. This might also explain the inconsistencies in the console via update #4. I also tried upping the <code>setTimeout(off, 0)</code> in there and this didn't prevent <em>all</em> of the clicks from firing like I'd expect.</p> <p>So I believe this suggests maybe the <code>suppressClick</code> isn't actually the problem. Here's a console log as proof (and I also had a colleague double check to ensure that I'm not missing anything here):</p> <p><img src="https://i.stack.imgur.com/JthxM.png" alt="enter image description here"></p> <hr> <p><strong>Update 6</strong></p> <p>I've found another bit of code that may well be relevant to this problem (but I'm not 100% sure). Where I hook up to the <code>d3.behavior.drag</code> I use the following:</p> <pre><code> var drag = d3.behavior.drag() .on("dragstart", function () { self.__dragstart(); }) .on("drag", function (d) { self.__drag(d); }) .on("dragend", function (d) { self.__dragend(d); }); </code></pre> <p>So I've just been looking into the <code>self.__dragstart()</code> function and noticed a <code>d3.event.sourceEvent.stopPropagation();</code>. There isn't much more in these functions (generally just starting/stopping the force directed graph and updating positions of lines). </p> <p>I'm wondering if this could be influencing the click behavior. If I take this <code>stopPropagation</code> out then my whole surface begins to pan, which isn't desirable so that's probably not the answer, but could be another avenue to investigate.</p> <hr> <p><strong>Update 7</strong></p> <p>One possible glaring emissions that I forgot to add to the original question. The visualization also supports zooming/panning. </p> <pre><code> self.__zoom = d3.behavior .zoom() .scaleExtent([minZoom, maxZoom]) .on("zoom", function () { self.__zoomed(d3.event.translate, d3.event.scale); }); </code></pre> <p>Now to implement this there is actually a large rectangle over the top of everything. So my top level <code>svg</code> actually looks like:</p> <pre class="lang-html prettyprint-override"><code>&lt;svg class="galaxy"&gt; &lt;g width="1080" height="1795"&gt; &lt;rect class="zoom" width="1080" height="1795" style="fill: none; pointer-events: all;"&gt;&lt;/rect&gt; &lt;g class="galaxy-background" width="1080" height="1795" transform="translate(-4,21)scale(1)"&gt;&lt;/g&gt; &lt;g class="galaxy-main" width="1080" height="1795" transform="translate(-4,21)scale(1)"&gt; ... all the circles are within here &lt;/g&gt; &lt;/svg&gt; </code></pre> <p>I remembered this when I turned off the <code>d3.event.sourceEvent.stopPropagation();</code> in the callback for the <code>drag</code> event on <code>d3.behaviour.drag</code>. This stopped any click events getting through to my circles which confused me somewhat, then I remembered the large rectangle when inspecting the DOM. I'm not quite sure why re-enabling the propagation prevents the click at the moment.</p>
39,410,041
3
31
null
2015-07-06 10:51:05.493 UTC
3
2016-09-09 10:58:29.563 UTC
2015-07-09 08:31:38.207 UTC
null
21,061
null
21,061
null
1
32
javascript|events|d3.js
5,700
<p>I recently came across this again, and fortunately have managed to isolate the problem and work around it.</p> <p>It was actually due to something being registered in the <code>mousedown</code> event, which was moving the DOM element <code>svg:circle</code> to the top based on a z-order. It does this by taking it out the DOM and re-inserting it at the appropriate place.</p> <p>This produces something that flows like this:</p> <ul> <li>mouseenter</li> <li>mousedown <ul> <li>(move DOM element but keep same event wrapper)</li> <li>mouseup</li> </ul></li> </ul> <p>The problem is, as far as the browser is concerned the <code>mousedown</code> and <code>mouseup</code> occurred almost on different elements in the DOM, moving it has messed up the event model.</p> <p>Therefore in my case I've applied a fix by firing the <code>click</code> event manually on <code>mouseup</code> if the original <code>mousedown</code> occured within the same element. </p>
20,340,268
Get request object in Passport strategy callback
<p>So here is my configuration for passport-facebook strategy:</p> <pre><code> passport.use(new FacebookStrategy({ clientID: ".....", clientSecret: ".....", callbackURL: "http://localhost:1337/register/facebook/callback", }, facebookVerificationHandler )); </code></pre> <p>And here is facebookVerificationHandler:</p> <pre><code>var facebookVerificationHandler = function (accessToken, refreshToken, profile, done) { process.nextTick(function () { ....... }); }; </code></pre> <p>Is there a way to access to the request object in facebookVerificationHandler?</p> <p>Users are registered to my site with a LocalStrategy but then they will be able to add their social accounts and associate those account with their local accounts. When the callback above is called, the user who is currently logged in is already available in req.user so I need to access req to associate the user with the facebook account.</p> <p>Is this the correct way to implement it or should I consider another way of doing it?</p> <p>Thanks.</p>
20,341,863
3
0
null
2013-12-02 23:57:38.017 UTC
7
2015-11-02 18:27:35.063 UTC
2015-01-06 14:50:10.18 UTC
null
1,266,650
null
365,266
null
1
48
node.js|passport.js|passport-facebook
23,033
<p>For this reason instead of setting up the strategy when the application starts I usually setup the strategy when there is a request. for instance:</p> <pre><code>app.get( '/facebook/login' ,passport_setup_strategy() ,passport.authenticate() ,redirect_home() ); var isStrategySetup = false; var passport_setup_strategy = function(){ return function(req, res, next){ if(!isStrategySetup){ passport.use(new FacebookStrategy({ clientID: ".....", clientSecret: ".....", callbackURL: "http://localhost:1337/register/facebook/callback", }, function (accessToken, refreshToken, profile, done) { process.nextTick(function () { // here you can access 'req' ....... }); } )); isStrategySetup = true; } next(); }; } </code></pre> <p>Using this you will have access to the request in your verification handler.</p>
6,399,924
Getting node's text in PHP DOM
<p>How could I extract the string "text" from this markup using the PHP DOM?</p> <pre><code>&lt;div&gt;&lt;span&gt;notthis&lt;/span&gt;text&lt;/div&gt; </code></pre> <p><code>$div-&gt;nodeValue</code> includes "notthis"</p>
6,399,930
2
0
null
2011-06-19 01:05:12.08 UTC
4
2011-06-19 01:27:10.483 UTC
null
null
null
null
378,622
null
1
35
php|html|xml|dom
44,464
<p>So long as you can affect the DOM, you could remove that <code>span</code>.</p> <pre><code>$span = $div-&gt;getElementsByTagName('span')-&gt;item(0); $div-&gt;removeChild($span); $nodeValue = $div-&gt;nodeValue; </code></pre> <p>Alternatively, just access the text node of <code>$div</code>.</p> <pre><code>foreach($div-&gt;childNodes as $node) { if ($node-&gt;nodeType != XML_TEXT_NODE) { continue; } $nodeValue = $node; } </code></pre> <p>If you end up with more text nodes and only want the first, you can <code>break</code> after the first assignment of <code>$nodeValue</code>.</p>
6,783,365
ASP.NET MVC - how to get a full path to an action
<p>Inside of a View can I get a full route information to an action? </p> <p>If I have an action called DoThis in a controller MyController. Can I get to a path of <code>"/MyController/DoThis/"</code>? </p>
6,783,381
2
0
null
2011-07-21 22:02:06.393 UTC
4
2018-01-10 05:04:48.017 UTC
null
null
null
null
37,759
null
1
38
asp.net-mvc|asp.net-mvc-routing
31,172
<p>You mean like using the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action.aspx">Action</a> method on the Url helper:</p> <pre><code>&lt;%= Url.Action("DoThis", "MyController") %&gt; </code></pre> <p>or in Razor:</p> <pre><code>@Url.Action("DoThis", "MyController") </code></pre> <p>which will give you a relative url (<code>/MyController/DoThis</code>).</p> <p>And if you wanted to get an absolute url (<code>http://localhost:8385/MyController/DoThis</code>):</p> <pre><code>&lt;%= Url.Action("DoThis", "MyController", null, Request.Url.Scheme, null) %&gt; </code></pre>
14,539,328
How to get a string from another class?
<p>Searched everywhere trying to find how to do this. I want to get a string from one class that i set the variable before going into the second class and allow me to use it as a string in this class. </p> <p>Basically there's a String called LastName that i want to use in another class.</p> <p>Here's my code if needed.</p> <p>First Login Class:</p> <pre><code>import java.util.Scanner; public class Login { public void LoginScreen() { Agent AgentObject = new Agent(); Citizen CitizenObject = new Citizen(); String FirstName; String LastName; Scanner input = new Scanner(System.in); System.out.println("Welcome!"); System.out.print("Please Enter Last Name: "); LastName = input.next(); System.out.print("Please Enter First Name: "); FirstName = input.next(); System.out.println("Hello " + FirstName + " " + LastName); System.out.print("Enter Password: "); String userinput = input.next(); if (userinput.equals("Timmo")) { AgentObject.WelcomeAgent(); } else { CitizenObject.WelcomeCitizen(); } } } </code></pre> <p>Second Agent Class:</p> <pre><code>public class Agent { public void WelcomeAgent() { Welcome WelcomeObject = new Welcome(); Login LoginObject = new Login(); System.out.println("Access Granted"); System.out.print("Loading Data "); int progress = 0; while (progress &lt;= 100) { System.out.print(progress + " "); progress++; } System.out.println(" Data Loaded"); System.out.println("Welcome Agent " + LastName); LoginObject.LoginScreen(); } } </code></pre> <p>Any help is incredibly appreciated. Thanks </p>
14,539,388
3
3
null
2013-01-26 17:07:42.74 UTC
3
2013-01-26 17:28:59.31 UTC
2013-01-26 17:20:01.05 UTC
null
1,888,770
null
1,888,770
null
1
1
java|string|class
41,781
<p>I can see you are probably quite new to Java - so you may be lacking a few fundamentals.</p> <p>Probably best to just pass the string in as a parameter to the method in your case e.g.</p> <pre><code>public void WelcomeAgent(String lastName) { </code></pre> <p>and when you call the method, send that value in e.g.</p> <pre><code>AgentObject.WelcomeAgent(userinput); </code></pre> <p>Btw, a few convention tips. Variables and functions should start with a lower case . e.g.</p> <pre><code>String lastName; </code></pre> <p>and</p> <pre><code>Citizen citizen = new Citizen(); </code></pre>
7,480,437
ASP.Net - App_Data & App_Code folders?
<p>What is the point of having <code>App_code</code> &amp; <code>App_data</code> folders?</p> <p>Why doesn't my objectDataSource detect classes unless files are in App_Code?</p> <p>Please provide as much detail as you can, I'm new to ASP.Net</p>
7,480,545
3
0
null
2011-09-20 05:11:58.84 UTC
3
2017-08-24 06:23:26.287 UTC
2011-09-20 05:28:58.067 UTC
null
142,822
null
242,769
null
1
31
asp.net|app-code|app-data
56,441
<p>These folders have special purpose. From this article - <a href="http://msdn.microsoft.com/en-us/library/ex526337.aspx" rel="noreferrer">ASP.NET Web project folder structure.</a> </p> <p>App_Code</p> <hr> <p>App_Code contains source code for shared classes and business objects (for example, ..cs, and .vb files) that you want to compile as part of your application. In a dynamically compiled Web site project, ASP.NET compiles the code in the App_Code folder on the initial request to your application. Items in this folder are then recompiled when any changes are detected.</p> <p>Note : You can add any type of class file to the App_Code folder in order to create strongly typed objects that represent those classes. For example, if you put Web service files (.wsdl and .xsd files) in the App_Code folder, ASP.NET creates strongly typed proxies for those classes.</p> <p>Code in the App_Code folder is referenced automatically in your application. The App_Code folder can contain sub-directories of files, which can include class files that in different programming languages. </p> <p>App_Data</p> <hr> <p>Contains application data files including .mdf database files, XML files, and other data store files. The App_Data folder is used by ASP.NET to store an application's local database, such as the database for maintaining membership and role information. </p>
7,382,149
What's the purpose of Django setting ‘SECRET_KEY’?
<p>I did a few google searches and checked out the docs ( <a href="https://docs.djangoproject.com/en/dev/ref/settings/#secret-key" rel="noreferrer">https://docs.djangoproject.com/en/dev/ref/settings/#secret-key</a> ), but I was looking for a more in-depth explanation of this, and why it is required.</p> <p>For example, what could happen if the key was compromised / others knew what it was?</p>
7,382,198
3
4
null
2011-09-11 23:59:01.74 UTC
26
2020-11-23 06:34:07.63 UTC
2020-11-23 06:34:07.63 UTC
null
1,038,379
null
651,174
null
1
228
python|django|security|encryption
102,067
<p>It is used for making hashes. Look:</p> <pre><code>&gt;grep -Inr SECRET_KEY * conf/global_settings.py:255:SECRET_KEY = '' conf/project_template/settings.py:61:SECRET_KEY = '' contrib/auth/tokens.py:54: hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) + contrib/comments/forms.py:86: info = (content_type, object_pk, timestamp, settings.SECRET_KEY) contrib/formtools/utils.py:15: order, pickles the result with the SECRET_KEY setting, then takes an md5 contrib/formtools/utils.py:32: data.append(settings.SECRET_KEY) contrib/messages/storage/cookie.py:112: SECRET_KEY, modified to make it unique for the present purpose. contrib/messages/storage/cookie.py:114: key = 'django.contrib.messages' + settings.SECRET_KEY contrib/sessions/backends/base.py:89: pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() contrib/sessions/backends/base.py:95: if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: contrib/sessions/backends/base.py:134: # Use settings.SECRET_KEY as added salt. contrib/sessions/backends/base.py:143: settings.SECRET_KEY)).hexdigest() contrib/sessions/models.py:16: pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() contrib/sessions/models.py:59: if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: core/management/commands/startproject.py:32: # Create a random SECRET_KEY hash, and put it in the main settings. core/management/commands/startproject.py:37: settings_contents = re.sub(r"(?&lt;=SECRET_KEY = ')'", secret_key + "'", settings_contents) middleware/csrf.py:38: % (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest() middleware/csrf.py:41: return md5_constructor(settings.SECRET_KEY + session_id).hexdigest() </code></pre>
7,336,354
Subtracting n Days from a date using SQL
<p>I am quite a beginner when it comes to Oracle. I am having trouble figuring out how to do something similar to this :</p> <pre><code>SELECT ID, NAME, TO_CHAR(DATEBIRTH, 'DD/MM/YYYY HH24:MI:SS') FROM PEOPLE WHERE DATEBIRTH &gt;= ANOTHERDATE - NDAY </code></pre> <p>To put it short, I want to select everyone who were born N days before a specific date and time but I am not quite sure that this is the way to do it nor that it would give me the results I expect.</p> <p>PS: I am developping under oracle8i.</p>
7,336,402
4
6
null
2011-09-07 15:20:02.64 UTC
1
2016-08-31 06:13:54.387 UTC
2011-09-07 16:36:10.04 UTC
null
146,325
null
932,614
null
1
7
sql|oracle|date-arithmetic|oracle8i
60,510
<p>Your query looks correct to me. That's how you subtract days from dates in Oracle. This link holds some more insight for you, should you want to add months or years:</p> <p><a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1157035034361" rel="noreferrer">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1157035034361</a></p>
7,799,438
Simple Maths with jQuery - division
<p>I've got two inputs in a div that I want to divide one by the other.</p> <pre><code>&lt;div&gt; &lt;input type="number" id="a"&gt; / &lt;input type="number" id="b"&gt; &lt;input type="submit"&gt; &lt;p class="result"&gt;RESULT HERE&lt;/p&gt; &lt;/div&gt; </code></pre> <p>How can the maths of this be done with jquery?</p>
7,799,465
2
3
null
2011-10-17 20:52:54.783 UTC
null
2011-10-17 21:18:28.203 UTC
2011-10-17 21:01:05.877 UTC
null
137,041
null
137,041
null
1
0
javascript|jquery|math|division
47,091
<p>It really depends when you want the calculation to take place, but the maths itself is incredibly simple. Just use the standard <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators">division operator</a>, <code>/</code>:</p> <pre><code>var num1 = $("input[label='a']").val(), num2 = $("input[label='b']").val(), result = parseInt(num1, 10) / parseInt(num2, 10); $(".result").text(result); </code></pre> <p>I guess it also depends if you only want to support integer division (that's why I've used <code>parseInt</code> - you could use <code>parseFloat</code> if necessary).</p> <p>Also, as mentioned in the comments on your question, <code>label</code> is not a valid attribute. A better option would be to use <code>id</code>, or if you need to use an arbitrarily named attribute, use HTML5 <a href="http://www.w3.org/TR/html5/elements.html#embedding-custom-non-visible-data-with-the-data-attributes"><code>data-*</code></a> attributes.</p> <p><strong>Update</strong> based on comments</p> <p>As you have stated that you want the code to run when a button is clicked, all you need to do is bind to the <code>click</code> event:</p> <pre><code>$("#someButton").click(function() { //Do stuff when the button is clicked. }); </code></pre>
2,118,578
Any practical coding dojo/kata ideas?
<p>I've been asked to run a workshop and coding dojo soon for people to try out Scala and try to build something with it. The attendees are all going to be new to Scala, and could come from any of a number of languages (I'm presuming they can code in at least one mainstream language - I'm including syntax comparisons with Java, C#, Python and Ruby).</p> <p>Part of the appeal of Scala is that it's practical - you can use it as a drop-in "power Java" (Java with less syntactical clutter, closures, immutability, FP, traits, singleton objects, nifty XML handling, type inference etc.) that still runs on the JVM (and on the .NET CLR supposedly) and doesn't require you to change build tools, server infrastructure, libraries, IDEs and so on. Most of the katas I've seen have been fun but not 'real world' - mathematical challenges like Project Euler and so on. These don't seem appropriate as we're trying to explore the use of it as a practical, real world language that people could consider using for both hacking and work, and because people aren't necessarily going to be too familiar with either the deeper parts of the Scala syntax or necessarily of the concepts behind functional programming.</p> <p>So, has anyone come across any more practical, everyday katas rather than arithmetical 'problem solving' ones? Katas, that is, that can test whether the language, libraries and tools can satisfy the use cases of the actual day-to-day programming most people have to do rather than testing out. (Not that the impractical ones aren't fun, but just not appropriate for the kind of thing I've been asked to run.)</p> <p>If I can't find good examples, I'm thinking that it might be useful to try and build something like a library catalogue - the event is for programmers who primarily work on building infrastructure for universities (and in education and culture - museums, galleries, schools, libraries and so on). It's a bit boring though, but it's the sort of thing that the attendees work on in their day-to-day existence. Any suggestions?</p>
2,118,645
4
2
2010-01-22 17:53:51.057 UTC
2010-01-22 16:08:49.05 UTC
15
2018-03-12 00:41:26.367 UTC
2015-01-23 17:39:56.217 UTC
null
1,014,938
null
167,435
null
1
18
scala
6,522
<p>There is a creative commons licensed introductory training course with hands-on exercises here:</p> <p><a href="http://github.com/javaBin/scala-training-slides" rel="noreferrer">http://github.com/javaBin/scala-training-slides</a></p> <p><a href="http://github.com/javaBin/scala-training-code" rel="noreferrer">http://github.com/javaBin/scala-training-code</a></p> <p>The slides are in Open Office format. If you don't have this installed, you can upload them to SlideShare, which will convert them for online viewing.</p>
52,689,049
Flutter - Navigate to a new screen, and clear all the previous screens
<p>I used <code>Navigator.push</code> up to 6 screens to get to the payment page. After Payment, I want to push to the "Payment Successful" page then remove all the previous screens i.e using the back button will return to the very first screen.</p> <p>NOTE: I have tried <code>pushReplacementNamed</code> and it doesn't work.</p>
52,689,158
4
4
null
2018-10-07 13:39:44 UTC
11
2022-04-14 10:47:56.193 UTC
null
null
null
null
4,083,636
null
1
43
android|dart|flutter
48,585
<p>I figured it out. It was the <code>Navigator.pushAndRemoveUntil</code> function. Where i had to pass the <code>PaymentSuccessful</code> widget as the <code>newRoute</code>, and the <code>"/Home"</code> route as the predicate</p> <pre><code> _navPaymentSuccessful(){ Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) =&gt; PaymentSuccessful() ), ModalRoute.withName("/Home") ); } </code></pre>
49,482,753
sdl2 - ImportError: DLL load failed: The specified module could not be found and [CRITICAL] [App] Unable to get a Window, abort
<ul> <li>Python: 3.6.4</li> <li>OS: Windows 10</li> <li>Kivy: 1.10.0</li> </ul> <h3>Kivy Installation Method</h3> <pre><code>python -m pip install --upgrade pip wheel setuptools python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew python -m pip install kivy.deps.gstreamer python -m pip install kivy.deps.angle python -m pip install kivy python -m pip install kivy_examples python -m pip install Pillow python -m pip install cython python -m pip install PyEnchant </code></pre> <h3>Description</h3> <p>Hi, I am trying to run the example code from the install Kivy. The following is the error I receive back. Any help would be great. I have tried looking at previous enquiries about similar problems, but nothing suggested on them has worked so far. </p> <pre><code>[INFO ] [Logger ] Record log in C:\Users\DoddJ\.kivy\logs\kivy_18-03-26_52.txt [INFO ] [Kivy ] v1.10.0 [INFO ] [Python ] v3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] [INFO ] [Factory ] 194 symbols loaded [INFO ] [Image ] Providers: img_tex, img_dds, img_pil, img_gif (img_sdl2, img_ffpyplayer ignored) [INFO ] [Text ] Provider: pil(['text_sdl2'] ignored) [CRITICAL] [Window ] Unable to find any valuable Window provider. sdl2 - ImportError: DLL load failed: The specified module could not be found. File "C:\Users\dev.DoddJ\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib fromlist=[modulename], level=0) File "C:\Users\dev.DoddJ\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\core\window\window_sdl2.py", line 26, in &lt;module&gt; from kivy.core.window._window_sdl2 import _WindowSDL2Storage [CRITICAL] [App ] Unable to get a Window, abort. Exception ignored in: 'kivy.properties.dpi2px' Traceback (most recent call last): File "C:\Users\dev.DoddJ\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\utils.py", line 496, in __get__ retval = self.func(inst) File "C:\Users\dev.DoddJ\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\metrics.py", line 174, in dpi EventLoop.ensure_window() File "C:\Users\dev.DoddJ\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\base.py", line 127, in ensure_window sys.exit(1) SystemExit: 1 [CRITICAL] [App ] Unable to get a Window, abort. </code></pre> <h3>Code and Logs</h3> <p>Code that I am trying to run:</p> <pre><code>import kivy kivy.require('1.10.0') # replace with your current kivy version ! from kivy.app import App from kivy.uix.label import Label class MyApp(App): def build(self): return Label(text='Hello world') if __name__ == '__main__': MyApp().run() </code></pre>
51,241,411
7
4
null
2018-03-26 01:28:39.02 UTC
11
2021-12-15 00:02:48.09 UTC
null
null
null
null
9,550,081
null
1
21
python|dll|kivy|sdl-2
26,114
<p>I had the same problem. I solved this by removing Kivy and its dependencies first.</p> <pre><code>python -m pip uninstall kivy python -m pip uninstall kivy.deps.sdl2 python -m pip uninstall kivy.deps.glew python -m pip uninstall kivy.deps.gstreamer python -m pip uninstall image </code></pre> <p>Now reinstalling everything except gstreamer.</p> <pre><code>python -m pip install --upgrade pip wheel setuptools python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew --extra-index-url https://kivy.org/downloads/packages/simple/ python -m pip install kivy </code></pre> <p>It solved the error. Credits to <a href="https://groups.google.com/forum/#!topic/kivy-users/HzdUhSPPul8" rel="noreferrer">Ben R's</a> Answer.</p>
49,457,787
How to Export a Multi-line Environment Variable in Bash/Terminal e.g: RSA Private Key
<p>One of our Apps <a href="https://github.com/dwyl/github-backup" rel="noreferrer"><code>github-backup</code></a> requires the use of an RSA Private Key as an Environment Variable.</p> <p>Simply attempting to export the key it in the terminal e.g: <code>text export PRIVATE_KEY=-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA04up8hoqzS1+ ... l48DlnUtMdMrWvBlRFPzU+hU9wDhb3F0CATQdvYo2mhzyUs8B1ZSQz2Vy== -----END RSA PRIVATE KEY----- </code></p> <p>Does not work ... because of the line breaks.</p> <p>I did a bit of googling but did not find a workable solution ... <br /> e.g: <a href="https://stackoverflow.com/questions/43082918/how-to-sett-multiline-rsa-private-key-environment-variable-for-aws-elastic-beans">How to set multiline RSA private key environment variable for AWS Elastic Beans</a></p> <p><img src="https://user-images.githubusercontent.com/194400/37850998-2f87b140-2ed5-11e8-8350-c003c2768e1f.png" alt="image"></p> <p>Error: <code> -----END RSA PRIVATE KEY-----': not a valid identifier </code></p> <p>followed the instructions in: <a href="http://blog.vawter.com/2016/02/10/Create-an-Environment-Variable-from-a-Private-Key" rel="noreferrer">http://blog.vawter.com/2016/02/10/Create-an-Environment-Variable-from-a-Private-Key</a> </p> <p>Created a file called <code>keytoenvar.sh</code> with the following lines:</p> <pre><code>#!/usr/bin/env bash file=$2 name=$1 export $name="$(awk 'BEGIN{}{out=out$0"\n"}END{print out}' $file| sed 's/\n$//')" </code></pre> <p><img src="https://user-images.githubusercontent.com/194400/37851077-76edb4da-2ed5-11e8-8872-ea75be0217a0.png" alt="image"> then ran the following command:</p> <pre><code>source keytoenvar.sh PRIVATE_KEY ./gitbu.2018-03-23.private-key.pem </code></pre> <p>That <em>works</em> but it seems like a "<em>long-winded</em>" approach ... </p> <p>Does anyone know of a <em>simpler</em> way of doing this? <br /> (<em>I'm hoping for a "<strong>beginner friendly</strong>" solution without too many "steps"...</em>) </p>
49,489,260
7
5
null
2018-03-23 20:24:13.643 UTC
16
2021-09-26 12:04:31.84 UTC
2020-08-19 20:07:52.457 UTC
null
9,205,413
null
1,148,249
null
1
84
bash|shell|environment-variables|multiline|private-key
93,516
<p><strong>export the key</strong></p> <pre><code>export PRIVATE_KEY=`cat ./gitbu.2018-03-23.private-key.pem` </code></pre> <p><strong>test.sh</strong></p> <pre><code>#!/bin/bash echo &quot;$PRIVATE_KEY&quot;; </code></pre> <p>If you want to save the key to a <code>.env</code> file with the rest of your environment variables, all you needed to do is &quot;wrap&quot; the private key string in <em>single quotes</em> in the <code>.env</code> file ... e.g: <code>sh exports HELLO_WORLD='-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA04up8hoqzS1+APIB0RhjXyObwHQnOzhAk5Bd7mhkSbPkyhP1 ... iWlX9HNavcydATJc1f0DpzF0u4zY8PY24RVoW8vk+bJANPp1o2IAkeajCaF3w9nf q/SyqAWVmvwYuIhDiHDaV2A== -----END RSA PRIVATE KEY-----' </code> So the following command will work:</p> <pre><code>echo &quot;export PRIVATE_KEY='`cat ./gitbu.2018-03-23.private-key.pem`'&quot; &gt;&gt; .env </code></pre> <p>Followed by:</p> <pre><code>source .env </code></pre> <p>Now the key will be in your .env file and whenever you source .env it will be exported.</p>
26,082,444
how to work around Travis CIs 4MB output limit?
<p>I have a Travis CI build that produces more than 4MB of output which exceeds Travis CIs limit.</p> <p>I have tried sending output to /dev/null, but Travis also fails if no output is seen for 10 minutes</p> <p>How can I workaround these constraints? </p>
26,082,445
3
1
null
2014-09-28 06:55:57.1 UTC
10
2019-10-23 11:15:42.62 UTC
null
null
null
null
1,033,422
null
1
21
travis-ci
4,375
<p>The following script sends some dummy output to keep the build alive but also records the build output to a file and displays a tail of the output if the build returns an error:</p> <pre><code>#!/bin/bash # Abort on Error set -e export PING_SLEEP=30s export WORKDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &amp;&amp; pwd )" export BUILD_OUTPUT=$WORKDIR/build.out touch $BUILD_OUTPUT dump_output() { echo Tailing the last 500 lines of output: tail -500 $BUILD_OUTPUT } error_handler() { echo ERROR: An error was encountered with the build. dump_output exit 1 } # If an error occurs, run our error handler to output a tail of the build trap 'error_handler' ERR # Set up a repeating loop to send some output to Travis. bash -c "while true; do echo \$(date) - building ...; sleep $PING_SLEEP; done" &amp; PING_LOOP_PID=$! # My build is using maven, but you could build anything with this, E.g. # your_build_command_1 &gt;&gt; $BUILD_OUTPUT 2&gt;&amp;1 # your_build_command_2 &gt;&gt; $BUILD_OUTPUT 2&gt;&amp;1 mvn clean install &gt;&gt; $BUILD_OUTPUT 2&gt;&amp;1 # The build finished without returning an error so dump a tail of the output dump_output # nicely terminate the ping output loop kill $PING_LOOP_PID </code></pre>
26,098,223
AngularJs code to navigate to another page in buttonclick
<p>AngularJs code to navigate to another page on a button click event. I have catch the button click event but cannot navigate to another page. The following is my code: HTML file:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="js/angular.min.js"&gt;&lt;/script&gt; &lt;script src="js/app/home.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-app="myapp"&gt; &lt;div ng-controller="TestCtrl"&gt; &lt;button ng-click="clicked()"&gt;Click me!&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And the javascript file is:</p> <pre><code>var VLogin = angular.module('myapp',[]); VLogin.controller('TestCtrl', ['$scope',function($scope) { $scope.clicked = function(){ $location.path('/test.html'); } }]); </code></pre>
26,104,602
3
1
null
2014-09-29 10:55:11.333 UTC
null
2014-09-29 16:30:25.283 UTC
2014-09-29 12:06:28.39 UTC
null
403,132
null
3,986,191
null
1
2
angularjs
56,027
<p>Try like as shown below...</p> <p>In html,</p> <pre><code> &lt;button ng-click="clicked()"&gt;Click&lt;/button&gt; </code></pre> <p>In JS,</p> <pre><code> $scope.clicked = function(){ window.location = "#/test.html"; } </code></pre> <p>I hope it helps you...</p>
7,394,748
What's the right way to decode a string that has special HTML entities in it?
<p>Say I get some JSON back from a service request that looks like this:</p> <pre><code>{ "message": "We&amp;#39;re unable to complete your request at this time." } </code></pre> <p>I'm not sure <em>why</em> that apostraphe is encoded like that (<code>&amp;#39;</code>); all I know is that I want to decode it.</p> <p>Here's one approach using jQuery that popped into my head:</p> <pre><code>function decodeHtml(html) { return $('&lt;div&gt;').html(html).text(); } </code></pre> <p>That seems (very) hacky, though. What's a better way? Is there a "right" way?</p>
7,394,787
7
1
null
2011-09-12 22:26:30.137 UTC
83
2022-08-25 16:13:52.083 UTC
null
null
null
null
105,570
null
1
266
javascript|jquery|html-entities
328,967
<p>This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.</p> <pre><code>function decodeHtml(html) { var txt = document.createElement("textarea"); txt.innerHTML = html; return txt.value; } </code></pre> <p>Example: <a href="http://jsfiddle.net/k65s3/">http://jsfiddle.net/k65s3/</a></p> <p>Input:</p> <pre><code>Entity:&amp;nbsp;Bad attempt at XSS:&lt;script&gt;alert('new\nline?')&lt;/script&gt;&lt;br&gt; </code></pre> <p>Output:</p> <pre><code>Entity: Bad attempt at XSS:&lt;script&gt;alert('new\nline?')&lt;/script&gt;&lt;br&gt; </code></pre>
14,279,977
How to Casting DataSource to List<T>?
<p>I have the following method that load products on a DataGridView</p> <pre><code>private void LoadProducts(List&lt;Product&gt; products) { Source.DataSource = products; // Source is BindingSource ProductsDataGrid.DataSource = Source; } </code></pre> <p>And now I'm trying to give me back to save them as shows below.</p> <pre><code>private void SaveAll() { Repository repository = Repository.Instance; List&lt;object&gt; products = (List&lt;object&gt;)Source.DataSource; Console.WriteLine("Este es el número {0}", products.Count); repository.SaveAll&lt;Product&gt;(products); notificacionLbl.Visible = false; } </code></pre> <p>But I get an <code>InvalidCastException</code> on this line:</p> <pre><code>List&lt;object&gt; products = (List&lt;object&gt;)Source.DataSource; </code></pre> <p>So how can I cast the DataSource to an List?</p>
14,280,037
4
1
null
2013-01-11 14:16:17.683 UTC
null
2018-10-11 15:50:34.39 UTC
2018-02-13 09:52:38.787 UTC
null
3,467,532
null
1,093,674
null
1
19
c#|winforms|datagridview|casting|datasource
41,424
<p>You can't cast covariantly directly to List;</p> <p>Either:</p> <pre><code>List&lt;Product&gt; products = (List&lt;Product&gt;)Source.DataSource; </code></pre> <p>or:</p> <pre><code>List&lt;Object&gt; products = ((List&lt;Product&gt;)Source.DataSource).Cast&lt;object&gt;().ToList(); </code></pre>
13,993,750
The async and await keywords don't cause additional threads to be created?
<p>I'm confused. How can one or many <code>Task</code> run in parallel on a single thread? My understanding of <em>parallelism</em> is obviously wrong.</p> <p>Bits of MSDN I can't wrap my head around:</p> <blockquote> <p>The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.</p> </blockquote> <p>.. and:</p> <blockquote> <p>Between starting a task and awaiting it, you can start other tasks. The additional tasks implicitly run in parallel, but no additional threads are created.</p> </blockquote>
13,993,802
1
0
null
2012-12-21 16:29:38.377 UTC
11
2014-02-19 18:31:01.727 UTC
2014-02-19 18:31:01.727 UTC
null
79,152
null
79,152
null
1
26
c#|multithreading|task-parallel-library|async-await|conceptual
3,495
<p>They don't run in parallel, they take turns. When progress is blocked for the running Task, it stores its state and yields control to a ready Task. It's cooperative multitasking, not true parallelism.</p> <p>Threads operate on the sample principle. However there are several key differences I'd like to highlight.</p> <p>First, simply because <code>async</code>/<code>await</code> aren't OS threads:</p> <ul> <li>Tasks won't see different Thread IDs</li> <li>Thread-local storage is not automatically context-switched when a Task yields.</li> </ul> <p>Secondly, differences in behavior:</p> <ul> <li><code>async</code>/<code>await</code> use cooperative multitasking, Win32 threads use pre-emption. So it's necessary that all blocking operations explicitly yield control using the <code>async</code>/<code>await</code> model. So you can end up blocking an entire thread and all its Tasks by making a blocking call to a function not written to yield.</li> <li>Tasks won't be executed in parallel on a multiprocessing system. Since re-entrancy is controlled, this makes keeping data structures consistent a whole lot easier.</li> </ul> <p>As Stephen points out in a comment, you <em>can</em> get simultaneous execution in multiple OS threads (along with all the complexity and potential race conditions) if you use a multithreaded synchronization context. But the MSDN quotes were about the single-threaded context case.</p> <p>Finally, other places this same design paradigm is used, you can learn a lot about good practices for <code>async</code>/<code>await</code> by studying these:</p> <ul> <li>Win32 <em>Fibers</em> (uses the same call style as threads, but cooperative)</li> <li>Win32 <em>Overlapped I/O</em> operations, Linux <em>aio</em></li> <li><em>Coroutines</em></li> </ul>
13,792,553
Write JavaScript in Chrome developer tools
<p>In Firebug, I can type my own JavaScript in the console tab and execute it. Is there a way to type JavaScript in Chrome Developer Tools and execute it?</p>
13,797,341
4
1
null
2012-12-09 22:31:21.523 UTC
26
2017-11-25 04:51:50.757 UTC
2012-12-14 17:51:21.637 UTC
null
896,886
null
896,886
null
1
28
google-chrome-devtools
45,719
<ol> <li>Go to <code>chrome://flags/</code>, enable the "Enable Developer Tools experiments" flag and restart Chrome (or start it with the <code>--enable-devtools-experiments</code> command-line flag.)</li> <li>Open DevTools, go to the <code>Settings</code> dialog, switch to the <code>Experiments</code> tab.</li> <li>Enable the "Snippets support" experiment, close and reopen DevTools.</li> <li>Go to the <code>Sources</code> panel. In the left-hand navigator sidebar, switch to the <code>Snippets</code> tab .</li> <li>Right-click in the [empty] tree in this tab, select the <code>New</code> context menu item.</li> <li>Give the new snippet any name you like and type the snippet body.</li> <li>Once done, click the <code>Run</code> (<code>&gt;</code>) button in the status bar to execute the snippet body. You can set breakpoints in snippets and debug them as ordinary scripts.</li> </ol>
13,960,514
How to adapt my plugin to Multisite?
<p>I have many plugins that I wrote for WordPress, and now I want to adapt them to MU.<br> What are the <em>considerations / best practices / workflow / functions / pitfalls</em> that I have to <em>follow / avoid / adapt</em> in order to 'upgrade' my plugins to support also Multisite installations? </p> <p>For example, but not limited to:</p> <ul> <li>Enqueue scripts/register</li> <li>Incuding files (php, images)</li> <li>Paths for custom files uploads</li> <li><code>$wpdb</code></li> <li>Activation, uninstall, deactivation</li> <li>Handling of admin specific pages</li> </ul> <p>In the Codex, there are <em>sometimes</em> remarks about Multisite in single function description, but I did not find any one-stop page that address this subject.</p>
15,940,351
1
0
null
2012-12-19 20:19:31.09 UTC
31
2014-09-18 22:22:14.38 UTC
2013-04-11 05:52:20.45 UTC
null
1,287,812
null
1,244,126
null
1
34
php|wordpress
22,269
<p>As for enqueuing and including, things go as normal. Plugin path and URL are the same.</p> <p>I never dealt with anything related to upload paths in Multisite and I guess normally WP takes care of this.</p> <hr> <h1><code>$wpdb</code></h1> <p>There is a commonly used snippet to iterate through all blogs:</p> <pre><code>global $wpdb; $blogs = $wpdb-&gt;get_results(" SELECT blog_id FROM {$wpdb-&gt;blogs} WHERE site_id = '{$wpdb-&gt;siteid}' AND spam = '0' AND deleted = '0' AND archived = '0' "); $original_blog_id = get_current_blog_id(); foreach ( $blogs as $blog_id ) { switch_to_blog( $blog_id-&gt;blog_id ); // do something in the blog, like: // update_option() } switch_to_blog( $original_blog_id ); </code></pre> <p>You may find examples where <code>restore_current_blog()</code> is used instead of <code>switch_to_blog( $original_blog_id )</code>. But here's why <code>switch</code> is more reliable: <a href="https://wordpress.stackexchange.com/q/89113/12615">restore_current_blog() vs switch_to_blog()</a>.</p> <hr> <h1><code>$blog_id</code></h1> <p>Execute some function or hook according to the blog ID:</p> <pre><code>global $blog_id; if( $blog_id != 3 ) add_image_size( 'category-thumb', 300, 9999 ); //300 pixels wide (and unlimited height) </code></pre> <p>Or maybe:</p> <pre><code>if( 'child.multisite.com' === $_SERVER['SERVER_NAME'] || 'domain-mapped-child.com' === $_SERVER['SERVER_NAME'] ) { // do_something(); } </code></pre> <hr> <h1>Install - Network Activation only</h1> <p>Using the plugin header <code>Network: true</code> <sup>(see: <strong>Sample Plugin</strong>)</sup> will only display the plugin in the page <code>/wp-admin/network/plugins.php</code>. With this header in place, we can use the following to block certain actions meant to happen if the plugin is Network only.</p> <pre><code>function my_plugin_block_something() { $plugin = plugin_basename( __FILE__ ); if( !is_network_only_plugin( $plugin ) ) wp_die( 'Sorry, this action is meant for Network only', 'Network only', array( 'response' =&gt; 500, 'back_link' =&gt; true ) ); } </code></pre> <hr> <h1>Uninstall</h1> <p>For (De)Activation, it depends on each plugin. But, for Uninstalling, this is the code I use in the file <a href="http://codex.wordpress.org/Function_Reference/register_uninstall_hook" rel="noreferrer"><code>uninstall.php</code></a>:</p> <pre><code>&lt;?php /** * Uninstall plugin - Single and Multisite * Source: https://wordpress.stackexchange.com/q/80350/12615 */ // Make sure that we are uninstalling if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) exit(); // Leave no trail $option_name = 'HardCodedOptionName'; if ( !is_multisite() ) { delete_option( $option_name ); } else { global $wpdb; $blog_ids = $wpdb-&gt;get_col( "SELECT blog_id FROM $wpdb-&gt;blogs" ); $original_blog_id = get_current_blog_id(); foreach ( $blog_ids as $blog_id ) { switch_to_blog( $blog_id ); delete_option( $option_name ); } switch_to_blog( $original_blog_id ); } </code></pre> <hr> <h1>Admin Pages</h1> <h3>1) Adding an admin page</h3> <p>To add an administration menu we check if <code>is_multisite()</code> and modify the hook accordingly:</p> <pre><code>$hook = is_multisite() ? 'network_' : ''; add_action( "{$hook}admin_menu", 'unique_prefix_function_callback' ); </code></pre> <h3>2) Check for Multisite dashboard and modify the admin URL:</h3> <pre><code>// Check for MS dashboard if( is_network_admin() ) $url = network_admin_url( 'plugins.php' ); else $url = admin_url( 'plugins.php' ); </code></pre> <h3>3) Workaround to show interface elements only in main site</h3> <p>Without creating a Network Admin Menu (action hook <code>network_admin_menu</code>), it is possible to show some part of the plugin <strong>only in the main site</strong>.</p> <p>I started to include some Multisite functionality in my <a href="http://wordpress.org/extend/plugins/many-tips-together/" rel="noreferrer">biggest plugin</a> and did the following to restrict one part of the plugin options to the main site. Meaning, if the plugin is activated in a sub site, the option <strong>won't show up</strong>.</p> <pre><code>$this-&gt;multisite = is_multisite() ? ( is_super_admin() &amp;&amp; is_main_site() ) // must meet this 2 conditions to be "our multisite" : false; </code></pre> <p><sup>Looking at this again, maybe it can be simply: <code>is_multisite() &amp;&amp; is_super_admin() &amp;&amp; is_main_site()</code>. Note that the last two return <code>true</code> in single sites.</sup></p> <p>And then:</p> <pre><code>if( $this-&gt;multisite ) echo "Something only for the main site, i.e.: Super Admin!"; </code></pre> <h3>4) Collection of useful hooks and functions.</h3> <p><strong>Hooks</strong>: <a href="https://wordpress.stackexchange.com/search?q=network_admin_menu"><code>network_admin_menu</code></a>, <a href="https://wordpress.stackexchange.com/q/70977/12615"><code>wpmu_new_blog</code></a>, <a href="https://wordpress.stackexchange.com/search?q=signup_blogform"><code>signup_blogform</code></a>, <a href="https://wordpress.stackexchange.com/search?q=wpmu_blogs_columns"><code>wpmu_blogs_columns</code></a>, <a href="https://wordpress.stackexchange.com/search?q=manage_sites_custom_column"><code>manage_sites_custom_column</code></a>, <code>manage_blogs_custom_column</code>, <a href="https://wordpress.stackexchange.com/questions/67876/12615"><code>wp_dashboard_setup</code></a>, <a href="https://wordpress.stackexchange.com/q/76145/12615"><code>network_admin_notices</code></a>, <a href="https://wordpress.stackexchange.com/q/3426/12615"><code>site_option_active_sitewide_plugins</code></a>, <code>{$hook}admin_menu</code></p> <p><strong>Functions</strong>: <a href="https://wordpress.stackexchange.com/search?q=is_multisite%20is:answer"><code>is_multisite</code></a>, <a href="https://wordpress.stackexchange.com/search?q=is_super_admin%20is:answer"><code>is_super_admin</code></a> <a href="https://wordpress.stackexchange.com/search?q=is_main_site"><code>is_main_site</code></a>, <a href="https://wordpress.stackexchange.com/q/91745/12615"><code>get_blogs_of_user</code></a>, <a href="https://wordpress.stackexchange.com/search?q=update_blog_option"><code>update_blog_option</code></a>, <code>is_network_admin</code>, <code>network_admin_url</code>, <code>is_network_only_plugin</code></p> <p><sup><em>PS: I rather link to WordPress Answers than to the Codex, as there'll be more examples of working code.</em></sup></p> <hr> <h1>Sample plugin</h1> <p>I've just rolled a Multisite plugin, <a href="https://github.com/brasofilo/Network-Deactivated-but-Active-Elsewhere" rel="noreferrer">Network Deactivated but Active Elsewhere</a>, and made a <strong>non-working</strong> resumed annotated version bellow (see GitHub for the finished full working version). The finished plugin is purely functional, there's no settings interface.</p> <p><sup>Note that the plugin header has <code>Network: true</code>. It prevents the plugin from <a href="https://wordpress.stackexchange.com/a/74649/12615">showing in child sites</a>.</sup></p> <pre><code>&lt;?php /** * Plugin Name: Network Deactivated but Active Elsewhere * Network: true */ /** * Start the plugin only if in Admin side and if site is Multisite */ if( is_admin() &amp;&amp; is_multisite() ) { add_action( 'plugins_loaded', array ( B5F_Blog_Active_Plugins_Multisite::get_instance(), 'plugin_setup' ) ); } /** * Based on Plugin Class Demo - https://gist.github.com/toscho/3804204 */ class B5F_Blog_Active_Plugins_Multisite { protected static $instance = NULL; public $blogs = array(); public $plugin_url = ''; public $plugin_path = ''; public static function get_instance() { NULL === self::$instance and self::$instance = new self; return self::$instance; } /** * Plugin URL and Path work as normal */ public function plugin_setup() { $this-&gt;plugin_url = plugins_url( '/', __FILE__ ); $this-&gt;plugin_path = plugin_dir_path( __FILE__ ); add_action( 'load-plugins.php', array( $this, 'load_blogs' ) ); } public function __construct() {} public function load_blogs() { /** * Using "is_network" property from $current_screen global variable. * Run only in /wp-admin/network/plugins.php */ global $current_screen; if( !$current_screen-&gt;is_network ) return; /** * A couple of Multisite-only filter hooks and a regular one. */ add_action( 'network_admin_plugin_action_links', array( $this, 'list_plugins' ), 10, 4 ); add_filter( 'views_plugins-network', // 'views_{$current_screen-&gt;id}' array( $this, 'inactive_views' ), 10, 1 ); add_action( 'admin_print_scripts', array( $this, 'enqueue') ); /** * This query is quite frequent to retrieve all blog IDs. */ global $wpdb; $this-&gt;blogs = $wpdb-&gt;get_results( " SELECT blog_id, domain FROM {$wpdb-&gt;blogs} WHERE site_id = '{$wpdb-&gt;siteid}' AND spam = '0' AND deleted = '0' AND archived = '0' " ); } /** * Enqueue script and style normally. */ public function enqueue() { wp_enqueue_script( 'ndbae-js', $this-&gt;plugin_url . '/ndbae.js', array(), false, true ); wp_enqueue_style( 'ndbae-css', $this-&gt;plugin_url . '/ndbae.css' ); } /** * Check if plugin is active in any blog * Using Multisite function get_blog_option */ private function get_network_plugins_active( $plug ) { $active_in_blogs = array(); foreach( $this-&gt;blogs as $blog ) { $the_plugs = get_blog_option( $blog['blog_id'], 'active_plugins' ); foreach( $the_plugs as $value ) { if( $value == $plug ) $active_in_blogs[] = $blog['domain']; } } return $active_in_blogs; } } </code></pre> <hr> <h1>Other resources - e-books</h1> <p>Not directly related to plugin development, but kind of essential to Multisite management.<br> The e-books are written by no less than two giants of Multisite: Mika Epstein (aka Ipstenu) and Andrea Rennick.</p> <ul> <li><a href="http://halfelf.org/ebooks/wordpress-multisite-101/" rel="noreferrer"><strong>WordPress Multisite 101</strong></a> </li> <li><a href="http://halfelf.org/ebooks/wordpress-multisite-110/" rel="noreferrer"><strong>WordPress Multisite 110</strong></a> </li> </ul>
13,996,302
Python - rolling functions for GroupBy object
<p>I have a time series object <code>grouped</code> of the type <code>&lt;pandas.core.groupby.SeriesGroupBy object at 0x03F1A9F0&gt;</code>. <code>grouped.sum()</code> gives the desired result but I cannot get rolling_sum to work with the <code>groupby</code> object. Is there any way to apply rolling functions to <code>groupby</code> objects? For example:</p> <pre><code>x = range(0, 6) id = ['a', 'a', 'a', 'b', 'b', 'b'] df = DataFrame(zip(id, x), columns = ['id', 'x']) df.groupby('id').sum() id x a 3 b 12 </code></pre> <p>However, I would like to have something like:</p> <pre><code> id x 0 a 0 1 a 1 2 a 3 3 b 3 4 b 7 5 b 12 </code></pre>
13,998,600
5
4
null
2012-12-21 19:49:00.067 UTC
25
2021-03-18 13:16:59.983 UTC
2019-06-29 03:26:37.933 UTC
user1642513
202,229
user1642513
null
null
1
78
python|pandas|pandas-groupby|rolling-computation|rolling-sum
121,364
<h3>cumulative sum</h3> <p>To answer the question directly, the cumsum method would produced the desired series:</p> <pre><code>In [17]: df Out[17]: id x 0 a 0 1 a 1 2 a 2 3 b 3 4 b 4 5 b 5 In [18]: df.groupby('id').x.cumsum() Out[18]: 0 0 1 1 2 3 3 3 4 7 5 12 Name: x, dtype: int64 </code></pre> <h3>pandas rolling functions per group</h3> <p>More generally, any rolling function can be applied to each group as follows (using the new .rolling method as commented by @kekert). Note that the return type is a multi-indexed series, which is different from previous (deprecated) pd.rolling_* methods.</p> <pre><code>In [10]: df.groupby('id')['x'].rolling(2, min_periods=1).sum() Out[10]: id a 0 0.00 1 1.00 2 3.00 b 3 3.00 4 7.00 5 9.00 Name: x, dtype: float64 </code></pre> <p>To apply the per-group rolling function and receive result in original dataframe order, transform should be used instead:</p> <pre><code>In [16]: df.groupby('id')['x'].transform(lambda s: s.rolling(2, min_periods=1).sum()) Out[16]: 0 0 1 1 2 3 3 3 4 7 5 9 Name: x, dtype: int64 </code></pre> <hr /> <h3>deprecated approach</h3> <p>For reference, here's how the now deprecated pandas.rolling_mean behaved:</p> <pre><code>In [16]: df.groupby('id')['x'].apply(pd.rolling_mean, 2, min_periods=1) Out[16]: 0 0.0 1 0.5 2 1.5 3 3.0 4 3.5 5 4.5 </code></pre>
28,937,392
JavaFX Alerts and their size
<p>Recently, JavaFX introduced Alerts (Java 8u40). </p> <p>Consider the code example below. How can I display a full message that is longer than just a few words? My messages (<code>contentText</code> property) get cut at the end with <code>...</code> and the Alert does not adjust its size properly in my opinion.</p> <p>On my Linux machine with Oracle JDK 8u40, I only see the text <code>This is a long text. Lorem ipsum dolor sit amet</code>, which is too short in some cases. </p> <p>Of course, the user can resize the Alert window manually and the text will be displayed accordingly, but that is not user-friendly at all. </p> <p>Edit: Screenshots for Windows 7 and Linux (JDK from Oracle): <img src="https://i.stack.imgur.com/zM0aR.png" alt="Windows Alert"> <img src="https://i.stack.imgur.com/Hf0JX.png" alt="Linux Alert"></p> <pre><code>import javafx.application.Application; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.stage.Stage; public class TestAlert extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Alert a = new Alert(AlertType.INFORMATION); a.setTitle("My Title"); a.setHeaderText("My Header Text"); a.setResizable(true); String version = System.getProperty("java.version"); String content = String.format("Java: %s.\nThis is a long text. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.", version); a.setContentText(content); a.showAndWait(); } } </code></pre>
36,938,061
5
3
null
2015-03-09 08:00:30.93 UTC
11
2020-10-02 20:20:57.503 UTC
2015-03-09 12:24:19.61 UTC
null
970,752
null
970,752
null
1
41
java|javafx|dialog|alert
38,214
<p>I have made the following workaround:</p> <pre><code>Alert alert = new Alert(AlertType.INFORMATION, "Content here", ButtonType.OK); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alert.show(); </code></pre> <p>So the window will resize automatically according to the content.</p>
28,999,906
'require': cannot load such file -- 'nokogiri\nokogiri' (LoadError) when running `rails server`
<p>I'm running a clean install of Ruby 2.2.1 on Windows 8.1 with DevKit. After the installation I run:</p> <pre><code>gem install rails rails new testapp cd testapp rails server </code></pre> <p>leaving everything else at default.</p> <p>The process fails at the last line when, instead of running the server, I get the error message </p> <pre><code>in 'require': cannot load such file -- 'nokogiri\nokogiri' (LoadError) </code></pre> <p>It happens every time and I've looked around and tried everything I found to fix it, but nothing so far has worked.</p> <p>What is the problem here and how do I get a simple test Rails app to work?</p>
29,007,731
4
3
null
2015-03-12 00:24:40.847 UTC
18
2021-10-08 03:44:05.7 UTC
2015-10-13 19:44:11.867 UTC
null
128,421
null
2,079,775
null
1
68
ruby-on-rails|ruby|nokogiri
73,943
<p>Nokogiri doesn't support Ruby 2.2 on Windows yet. The next release will. See <a href="https://github.com/sparklemotion/nokogiri/issues/1256" rel="noreferrer">https://github.com/sparklemotion/nokogiri/issues/1256</a></p> <p>Nokogiri doesn't support native builds (e.g. with devkit) on Windows. Instead it provides gems containing prebuilt DLLs.</p> <p>There's a discussion which you may want to join or watch on the topic of devkit build support here: <a href="https://github.com/sparklemotion/nokogiri/issues/1190" rel="noreferrer">https://github.com/sparklemotion/nokogiri/issues/1190</a></p>
43,330,915
Could not load file or assembly 'Microsoft.Build.Framework'(VS 2017)
<p>When I try running the command "update-database", I get this exception:</p> <blockquote> <p>Specify the '-Verbose' flag to view the SQL statements being applied to the target database. System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Build.Framework, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. File name: 'Microsoft.Build.Framework, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' </p> <p>WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].</p> <p>Could not load file or assembly 'Microsoft.Build.Framework, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.`</p> </blockquote>
43,498,190
23
2
null
2017-04-10 18:55:46.177 UTC
21
2022-09-16 01:35:52.8 UTC
2018-01-29 23:07:12.743 UTC
null
2,718,874
null
5,411,355
null
1
101
c#|msbuild|migration|visual-studio-2017
80,191
<p>I believe I had the same issue as you did. I didn't save the whole error message, but my error message was</p> <blockquote> <p>'<em>Could not load file or assembly 'Microsoft.Build.Framework, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.</em>'</p> </blockquote> <p>I am using Visual Studio 2017 and was trying to do <code>Update-Database</code> after <code>Add-Migration</code>.</p> <p>To resolve the issue I <strong>closed Visual Studio and re-opened it</strong>, then re-ran <code>Update-Database</code> again.</p> <p>This may or may not resolve your issue, but I thought I'd post just in case it would help.</p>
44,636,549
Why is there no support for concatenating std::string and std::string_view?
<p>Since C++17, we have <a href="http://en.cppreference.com/w/cpp/string/basic_string_view" rel="noreferrer"><code>std::string_view</code></a>, a light-weight view into a contiguous sequence of characters that avoids unnecessary copying of data. Instead of having a <code>const std::string&amp;</code> parameter, it is now often recommended to use <code>std::string_view</code>.</p> <p>However, one quickly finds out that switching from <code>const std::string&amp;</code> to <code>std::string_view</code> breaks code that uses string concatenation as there is no support for concatenating <code>std::string</code> and <code>std::string_view</code>:</p> <pre><code>std::string{&quot;abc&quot;} + std::string_view{&quot;def&quot;}; // ill-formed (fails to compile) std::string_view{&quot;abc&quot;} + std::string{&quot;def&quot;}; // ill-formed (fails to compile) </code></pre> <p>Why is there no support for concatenating <code>std::string</code> and <code>std::string_view</code> in the standard?</p>
47,735,624
2
6
null
2017-06-19 17:26:55.05 UTC
13
2022-06-02 13:41:51.877 UTC
2020-07-02 23:13:32.18 UTC
null
471,164
null
2,580,955
null
1
115
c++|string|c++17|string-view
18,904
<p>The reason for this is given in <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3512.html" rel="noreferrer">n3512 string_ref: a non-owning reference to a string, revision 2</a> by Jeffrey Yasskin:</p> <blockquote> <p>I also omitted operator+(basic_string, basic_string_ref) because LLVM returns a lightweight object from this overload and only performs the concatenation lazily. If we define this overload, we'll have a hard time introducing that lightweight concatenation later.</p> </blockquote> <p>It has been later suggested on the <a href="https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/1RcShRhrmRc" rel="noreferrer">std-proposals</a> mailing list to add these operator overloads to the standard.</p>
24,573,643
How to generate serial version UID in Intellij
<p>When I used <strong><em>Eclipse</em></strong> it had a nice feature to generate serial version UID.</p> <p>But what to do in IntelliJ? </p> <p><strong><em>How to choose or generate identical serial version UID in IntelliJ?</em></strong></p> <p>And what to do when you modify old class?</p> <p>If you haven't specify the <code>id</code>, it is generated at runtime...</p>
36,007,392
4
3
null
2014-07-04 11:50:55.73 UTC
35
2022-07-14 07:58:41.473 UTC
2017-11-02 12:13:37.62 UTC
null
5,180,989
null
1,498,427
null
1
207
java|serialization|intellij-idea
193,811
<p>Without any plugins:</p> <p>You just need to enable highlight: (Idea v.2016, 2017 and 2018, previous versions may have same or similar settings)</p> <blockquote> <p>File -&gt; Settings -&gt; Editor -&gt; Inspections -&gt; Java -&gt; Serialization issues -&gt; Serializable class without 'serialVersionUID' - set flag and click 'OK'. (For Macs, Settings is under IntelliJ IDEA -&gt; Preferences...)</p> </blockquote> <p>For Idea v. 2022.1 (Community and Ultimate) it's on:</p> <blockquote> <p>File -&gt; Settings -&gt; Editor -&gt; Inspections -&gt; JVM Languages -&gt; Serializable class without 'serialVersionUID' - set flag and click 'OK'</p> </blockquote> <p>Now, if your class implements <code>Serializable</code>, you will see highlight and alt+Enter on class name will ask you to generate <code>private static final long serialVersionUID</code>.</p> <p>UPD: a faster way to find this setting - you might use hotkey <code>Ctrl+Shift+A</code> (find action), type <code>Serializable class without 'serialVersionUID'</code> - the first is the one.</p>
788,786
how to write a complete server client communication using java nio
<p>I am new to java NIO. I have to write a simple server client communication program using Java NIO.</p> <p>Is there any sample programs or any link where can I go for this?</p>
788,879
5
0
null
2009-04-25 12:10:01 UTC
13
2014-10-08 23:01:52.703 UTC
2014-10-08 23:01:23.173 UTC
null
125,389
null
94,352
null
1
7
java|sockets|nio
16,234
<p>You might give a look at <a href="http://mina.apache.org/" rel="nofollow noreferrer">Apache Mina</a>. If you only want to learn java NIO it might me a little to hard to grasp.</p>
85,649
Safely remove a USB drive using the Win32 API?
<p>How do I remove a USB drive using the Win32 API? I do a lot of work on embedded systems and on one of these I have to copy my programs on a USB stick and insert it into the target hardware.</p> <p>Since I mostly work on the console I don't like to use the mouse and click on the small task-bar icon hundred times a day. </p> <p>I'd love to write a little program to do exactly that so I can put it into my makefiles, but I haven't found any API call that does the same thing.</p> <p>Any ideas?</p>
85,694
5
2
null
2008-09-17 17:33:07.5 UTC
16
2020-10-16 01:45:45.64 UTC
2014-12-01 12:33:05.777 UTC
monjardin
63,550
Nils
15,955
null
1
31
c|windows|winapi|usb
38,219
<p>You can use the CM_Request_Device_Eject() function as well as some other possibilities. Consult the following projects and articles:</p> <p>DevEject: Straightforward. <a href="http://www.withopf.com/tools/deveject/" rel="noreferrer">http://www.withopf.com/tools/deveject/</a></p> <p>A useful CodeProject article: <a href="http://www.codeproject.com/KB/system/RemoveDriveByLetter.aspx" rel="noreferrer">http://www.codeproject.com/KB/system/RemoveDriveByLetter.aspx</a></p>
122,853
How to get the file size from http headers
<p>I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?</p>
122,984
5
0
null
2008-09-23 18:31:42.917 UTC
26
2022-03-08 13:21:51.43 UTC
2017-03-23 18:40:45.57 UTC
null
1,664,443
Greg
null
null
1
70
c#|http|download|http-headers
61,368
<p>Yes, assuming the HTTP server you're talking to supports/allows this:</p> <pre><code>public long GetFileSize(string url) { long result = -1; System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.Method = "HEAD"; using (System.Net.WebResponse resp = req.GetResponse()) { if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength)) { result = ContentLength; } } return result; } </code></pre> <p>If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.</p>
1,298,636
How to set initial size for a dictionary in Python?
<p>I'm putting around 4 million different keys into a Python dictionary. Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast.</p> <p>I suspect that dictionary creation is so resource consuming because the dictionary is very often rehashed (as it grows enormously). Is is possible to create a dictionary in Python with some initial size or bucket number?</p> <p>My dictionary points from a number to an object.</p> <pre><code>class MyObject: def __init__(self): # some fields... d = {} d[i] = MyObject() # 4M times on different key... </code></pre>
1,298,905
6
4
null
2009-08-19 09:06:30.4 UTC
13
2021-05-20 04:32:32.627 UTC
2021-05-20 04:32:32.627 UTC
null
3,064,538
null
42,201
null
1
29
python|performance|dictionary
38,845
<p>With performance issues it's always best to measure. Here are some timings:</p> <pre><code> d = {} for i in xrange(4000000): d[i] = None # 722ms d = dict(itertools.izip(xrange(4000000), itertools.repeat(None))) # 634ms dict.fromkeys(xrange(4000000)) # 558ms s = set(xrange(4000000)) dict.fromkeys(s) # Not including set construction 353ms </code></pre> <p>The last option doesn't do any resizing, it just copies the hashes from the set and increments references. As you can see, the resizing isn't taking a lot of time. It's probably your object creation that is slow. </p>
1,082,311
Why should a .NET struct be less than 16 bytes?
<p>I've read in a few places now that the maximum instance size for a struct should be 16 bytes.</p> <p>But I cannot see where that number (16) comes from.</p> <p>Browsing around the net, I've found some who suggest that it's an approximate number for good performance but Microsoft talk like it is a hard upper limit. (e.g. <a href="http://msdn.microsoft.com/en-us/library/ms229017.aspx" rel="noreferrer">MSDN</a> )</p> <p>Does anyone have a definitive answer about why it is 16 bytes?</p>
1,082,340
6
0
null
2009-07-04 14:36:47.223 UTC
9
2021-04-12 01:40:00.83 UTC
2009-07-04 14:58:02.733 UTC
null
76,337
null
92,232
null
1
64
c#|.net
15,329
<p>It is just a performance rule of thumb.</p> <p>The point is that because value types are passed by value, the entire size of the struct has to be copied if it is passed to a function, whereas for a reference type, only the reference (4 bytes) has to be copied. A struct might save a bit of time though because you remove a layer of indirection, so even if it is larger than these 4 bytes, it might still be more efficient than passing a reference around. But at some point, it becomes so big that the cost of copying becomes noticeable. And a common rule of thumb is that this typically happens around 16 bytes. 16 is chosen because it's a nice round number, a power of two, and the alternatives are either 8 (which is too small, and would make structs almost useless), or 32 (at which point the cost of copying the struct is already problematic if you're using structs for performance reasons)</p> <p>But ultimately, this is performance advice. It answers the question of "which would be most efficient to use? A struct or a class?". But it doesn't answer the question of "which best maps to my problem domain".</p> <p>Structs and classes behave differently. If you need a struct's behavior, then I would say to make it a struct, no matter the size. At least until you run into performance problems, profile your code, and find that your struct is a problem.</p> <p>your link even says that it is just a matter of performance:</p> <blockquote> <p>If one or more of these conditions are not met, create a reference type instead of a structure. Failure to adhere to this guideline can negatively impact performance.</p> </blockquote>
453,372
Writing function definition in header files in C++
<p>I have a class which has many small functions. By small functions, I mean functions that doesn't do any processing but just return a literal value. Something like:</p> <pre><code>string Foo::method() const{ return "A"; } </code></pre> <p>I have created a header file "Foo.h" and source file "Foo.cpp". But since the function is very small, I am thinking about putting it in the header file itself. I have the following questions:</p> <ol> <li>Is there any performance or other issues if I put these function definition in header file? I will have many functions like this.</li> <li>My understanding is when the compilation is done, compiler will expand the header file and place it where it is included. Is that correct?</li> </ol>
453,387
6
0
null
2009-01-17 14:36:22.04 UTC
27
2018-11-01 11:57:11.1 UTC
2017-05-22 07:43:33.52 UTC
Ferruccio
2,291,710
Appu
50,419
null
1
65
c++|performance|header-files
105,357
<p>If the function is small (the chance you would change it often is low), and if the function can be put into the header without including myriads of other headers (because your function depends on them), it is perfectly valid to do so. If you declare them extern inline, then the compiler is required to give it the same address for every compilation unit:</p> <p><em>headera.h</em>:</p> <pre><code>inline string method() { return something; } </code></pre> <p>Member functions are implicit inline provided they are defined inside their class. The same stuff is true for them true: If they can be put into the header without hassle, you can indeed do so. </p> <p>Because the code of the function is put into the header and visible, the compiler is able to inline calls to them, that is, putting code of the function directly at the call site (not so much because you put inline before it, but more because the compiler decides that way, though. Putting inline only is a hint to the compiler regarding that). That can result in a performance improvement, because the compiler now sees where arguments match variables local to the function, and where argument doesn't alias each other - and last but not least, function frame allocation isn't needed anymore.</p> <blockquote> <p>My understanding is when the compilation is done, compiler will expand the header file and place it where it is included. Is that correct?</p> </blockquote> <p>Yes, that is correct. The function will be defined in every place where you include its header. The compiler will care about putting only one instance of it into the resulting program, by eliminating the others. </p>
978,052
How can I make my local repository available for git-pull?
<p>I have a working copy repository that I've been working in no problem; the origin for this repository is on GitHub. </p> <p>I'd like to make my working copy repository available as the origin for my build machine (a VM on another physical host), so that commits I make to my working copy can be built and tested on the build machine without having to go via GitHub first. I already have a build for the GitHub repository going, but I'd like this to be a "golden" repository/build; i.e., if something goes in there, the build against GitHub should be guaranteed to pass. </p> <p>I've looked at the documentation on Git URLs, and see that there's the option of using a URL in the form <code>git://host.xz[:port]/path/to/repo.git/</code> (see, e.g., <a href="http://git-scm.com/docs/git-clone" rel="noreferrer">git-clone documentation</a>). I want to do this in the simplest possible way, with the minimum of configuration: I don't want to have to set up an SSH daemon or web server just to publish this to my build machine. </p> <p>I'm running Windows 7 x64 RC, I have MSysGit and TortoiseGit installed, and I have opened Git's default port (9814) on the firewall. Please assume working copy repo is at <code>D:\Visual Studio Projects\MyGitRepo</code>, and the hostname is <code>devbox</code>. The build machine is Windows Server 2008 x64. I have been trying the following command on the build machine, with the associated output:</p> <pre><code>D:\Integration&gt;git clone "git://devbox/D:\Visual Studio Projects\MyGitRepo" Initialized empty Git repository in D:/Integration/MyGitRepo/.git/ devbox[0: 192.168.0.2]: errno=No error fatal: unable to connect a socket (No error) </code></pre> <p>Am I missing something?</p>
978,417
6
1
null
2009-06-10 20:45:41.883 UTC
33
2015-11-11 07:44:36.573 UTC
2015-11-11 07:28:48.507 UTC
null
248,296
null
5,296
null
1
91
git|pull|git-pull|working-copy
81,818
<p>Five possibilities exist to set up a repository for pull from:</p> <ul> <li><strong>local filesystem</strong>: <code>git clone /path/to/repo</code> or <code>git clone file://path/to/repo</code>. Least work if you have networked filesystem, but not very efficient use of network. <em>(This is almost exactly solution proposed by <a href="https://stackoverflow.com/users/109869/joakim-elofsson">Joakim Elofsson</a>)</em></li> <li><strong>HTTP protocols</strong>: <code>git clone http://example.com/repo</code>. You need <em>any</em> web server, and you also need to run (perhaps automatically, from a hook) <a href="http://www.kernel.org/pub/software/scm/git/docs/git-update-server-info.html" rel="noreferrer" title="git-update-server-info - Update auxiliary info file to help dumb servers">git-update-server-info</a> to generate information required for fetching/pulling via "dumb" protocols.</li> <li><strong>SSH</strong>: <code>git clone ssh://example.com/srv/git/repo</code> or <code>git clone example.com:/srv/git/repo</code>. You need to setup SSH server (SSH daemon), and have SSH installed on client (e.g. PuTTY on MS Windows).</li> <li><strong>git protocol</strong>: <code>git clone git://example.com/repo</code>. You need to run <a href="http://www.kernel.org/pub/software/scm/git/docs/git-daemon.html" rel="noreferrer" title="git-daemon - A really simple server for git repositories">git-daemon</a> on server; see documentation for details (you can run it as standalone process only for fetching, not necessary run as service). git-daemon is a part of git.</li> <li><strong>bundle</strong>: You generate bundle on server using <a href="http://www.kernel.org/pub/software/scm/git/docs/git-bundle.html" rel="noreferrer" title="git-bundle - Move objects and refs by archive">git-bundle</a> command, transfer it to a client machine in any way (even via USB), and clone using <code>git clone file.bndl</code> (if clone does not work, you can do "git init", "git remote add" and "git fetch").</li> </ul> <p>What you are missing in your example is probably running git-daemon on server. That, or misconfiguring git-daemon.</p> <p>Unfortunately I cannot help you with running git-daemon as service on MS Windows. There is nothing in announcement for last version of msysGit about git-daemon not working, though. </p>
609,826
Performance of ThreadLocal variable
<p>How much is read from <code>ThreadLocal</code> variable slower than from regular field?</p> <p>More concretely is simple object creation faster or slower than access to <code>ThreadLocal</code> variable?</p> <p>I assume that it is fast enough so that having <code>ThreadLocal&lt;MessageDigest&gt;</code> instance is much faster then creating instance of <code>MessageDigest</code> every time. But does that also apply for byte[10] or byte[1000] for example?</p> <p>Edit: Question is what is really going on when calling <code>ThreadLocal</code>'s get? If that is just a field, like any other, then answer would be "it's always fastest", right?</p>
610,249
6
2
null
2009-03-04 09:22:41.883 UTC
18
2020-12-24 10:49:36.953 UTC
2011-11-20 00:01:20.487 UTC
Sarmun
1,502,059
Sarmun
70,173
null
1
92
java|multithreading|performance|thread-local
32,216
<p>Running unpublished benchmarks, <code>ThreadLocal.get</code> takes around 35 cycle per iteration on my machine. Not a great deal. In Sun's implementation a custom linear probing hash map in <code>Thread</code> maps <code>ThreadLocal</code>s to values. Because it is only ever accessed by a single thread, it can be very fast.</p> <p>Allocation of small objects take a similar number of cycles, although because of cache exhaustion you may get somewhat lower figures in a tight loop.</p> <p>Construction of <code>MessageDigest</code> is likely to be relatively expensive. It has a fair amount of state and construction goes through the <code>Provider</code> SPI mechanism. You may be able to optimise by, for instance, cloning or providing the <code>Provider</code>.</p> <p>Just because it may be faster to cache in a <code>ThreadLocal</code> rather than create does not necessarily mean that the system performance will increase. You will have additional overheads related to GC which slows everything down.</p> <p>Unless your application very heavily uses <code>MessageDigest</code> you might want to consider using a conventional thread-safe cache instead.</p>
357,600
Is const_cast safe?
<p>I can't find much information on <code>const_cast</code>. The only info I could find (on Stack Overflow) is:</p> <blockquote> <p>The <code>const_cast&lt;&gt;()</code> is used to add/remove const(ness) (or volatile-ness) of a variable.</p> </blockquote> <p>This makes me nervous. Could using a <code>const_cast</code> cause unexpected behavior? If so, what?</p> <p>Alternatively, when is it okay to use <code>const_cast</code>?</p>
357,607
6
2
null
2008-12-10 21:01:13.417 UTC
40
2017-08-28 11:57:40.377 UTC
2017-08-28 11:57:40.377 UTC
Mag Roader
5,612,562
Mag Roader
10,606
null
1
96
c++|casting|const-cast
50,838
<p><code>const_cast</code> is safe only if you're casting a variable that was originally non-<code>const</code>. For example, if you have a function that takes a parameter of a <code>const char *</code>, and you pass in a modifiable <code>char *</code>, it's safe to <code>const_cast</code> that parameter back to a <code>char *</code> and modify it. However, if the original variable was in fact <code>const</code>, then using <code>const_cast</code> will result in undefined behavior.</p> <pre><code>void func(const char *param, size_t sz, bool modify) { if(modify) strncpy(const_cast&lt;char *&gt;(param), sz, "new string"); printf("param: %s\n", param); } ... char buffer[16]; const char *unmodifiable = "string constant"; func(buffer, sizeof(buffer), true); // OK func(unmodifiable, strlen(unmodifiable), false); // OK func(unmodifiable, strlen(unmodifiable), true); // UNDEFINED BEHAVIOR </code></pre>
37,725,934
ASP.NET Core MVC controllers in separate assembly
<p>I'm using ASP.NET MVC Core RC-2. I have a web project targeting the full .NET framework. I also have a separate class library in the solution, also targeting the full framework.</p> <p>In the class library, I have a controller, marked with a route attribute. I have referenced the class library from the web project. This assembly references the nuget package <code>Microsoft.AspNetCore.Mvc v. 1.0.0-rc2-final</code>.</p> <p>It was my understanding that this external controller would be discovered automatically, e.g. <a href="http://www.strathweb.com/2015/04/asp-net-mvc-6-discovers-controllers/" rel="noreferrer">http://www.strathweb.com/2015/04/asp-net-mvc-6-discovers-controllers/</a></p> <p>However this doesn't work for me- I browse to the URL of the route and I get a blank page and it doesn't hit my controller breakpoint.</p> <p>Any ideas how to get this working?</p> <p>Interestingly, it does seem to work for web projects targeting .NET Core Framework, referencing a class library also targeting .NET Core. But not for a web project targeting the full framework, referencing a standard .NET class library.</p> <p>Note: this is MVC Core which is supposed to support this kind of scenario without any <a href="https://stackoverflow.com/questions/7560005/how-to-register-a-controller-into-asp-net-mvc-when-the-controller-class-is-in-a">MVC&lt;=4 routing overrides</a>.</p>
37,735,487
2
2
null
2016-06-09 12:23:52.46 UTC
6
2018-10-16 15:50:41.223 UTC
2017-05-23 12:03:07.5 UTC
null
-1
null
619,759
null
1
43
asp.net-core-mvc|asp.net-core-1.0
28,919
<p>I believe you are hitting the following known issue in RC2. <a href="https://github.com/aspnet/Mvc/issues/4674" rel="noreferrer">https://github.com/aspnet/Mvc/issues/4674</a> (workaround is mentioned in the bug)</p> <p>This has been fixed since then but will only be available in next release (unless you are ok with using nightly builds)</p>
38,002,543
apt-get update' returned a non-zero code: 100
<p>I am trying to create a docker image from my docker file which has the following content:</p> <pre><code>FROM ubuntu:14.04.4 RUN echo 'deb http://private-repo-1.hortonworks.com/HDP/ubuntu14/2.x/updates/2.4.2.0 HDP main' &gt;&gt; /etc/apt/sources.list.d/HDP.list RUN echo 'deb http://private-repo-1.hortonworks.com/HDP-UTILS-1.1.0.20/repos/ubuntu14 HDP-UTILS main' &gt;&gt; /etc/apt/sources.list.d/HDP.list RUN echo 'deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/azurecore/ trusty main' &gt;&gt; /etc/apt/sources.list.d/azure-public-trusty.list RUN gpg --keyserver pgp.mit.edu --recv-keys B9733A7A07513CAD RUN gpg -a --export 07513CAD | apt-key add - RUN gpg --keyserver pgp.mit.edu --recv-keys B02C46DF417A0893 RUN gpg -a --export 417A0893 | apt-key add - RUN apt-get update </code></pre> <p>which fails with the following error:</p> <pre><code>root@sbd-docker:~/ubuntu# docker build -t hdinsight . Sending build context to Docker daemon 3.072 kB Step 1 : FROM ubuntu:14.04.4 ---&gt; 8f1bd21bd25c Step 2 : RUN echo 'deb http://private-repo-1.hortonworks.com/HDP/ubuntu14/2.x/updates/2.4.2.0 HDP main' &gt;&gt; /etc/apt/sources.list.d/HDP.list ---&gt; Using cache ---&gt; bc23070c0b18 Step 3 : RUN echo 'deb http://private-repo-1.hortonworks.com/HDP-UTILS-1.1.0.20/repos/ubuntu14 HDP-UTILS main' &gt;&gt; /etc/apt/sources.list.d/HDP.list ---&gt; Using cache ---&gt; e45c32975e28 Step 4 : RUN echo 'deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/azurecore/ trusty main' &gt;&gt; /etc/apt/sources.list.d/azure-public-trusty.list ---&gt; Using cache ---&gt; 1659cdcab06e Step 5 : RUN gpg --keyserver pgp.mit.edu --recv-keys B9733A7A07513CAD ---&gt; Using cache ---&gt; ca73b2bfcd21 Step 6 : RUN gpg -a --export 07513CAD | apt-key add - ---&gt; Using cache ---&gt; 95596ad10bc9 Step 7 : RUN gpg --keyserver pgp.mit.edu --recv-keys B02C46DF417A0893 ---&gt; Using cache ---&gt; f497deeef5b5 Step 8 : RUN gpg -a --export 417A0893 | apt-key add - ---&gt; Using cache ---&gt; d01dbe7fa02e Step 9 : RUN apt-get update ---&gt; Running in 89d75799982f E: The method driver /usr/lib/apt/methods/https could not be found. The command '/bin/sh -c apt-get update' returned a non-zero code: 100 root@sbd-docker:~/ubuntu# </code></pre> <p>I am running this on <code>Ubuntu 14.04.4</code>.</p> <p>I tried restarting docker, cleaning up all docker images, installing <code>apt-transport-https</code>, but nothing worked.</p> <p>I dont know whats wrong here.</p>
38,004,106
9
3
null
2016-06-23 21:55:45.007 UTC
13
2022-09-20 11:32:57.923 UTC
2021-01-22 22:54:47.127 UTC
null
11,154,841
null
3,579,198
null
1
89
ubuntu|docker|dockerfile
153,787
<p>Because you have an https sources. Install <code>apt-transport-https</code> before executing update.</p> <pre><code>FROM ubuntu:14.04.4 RUN apt-get update &amp;&amp; apt-get install -y apt-transport-https RUN echo 'deb http://private-repo-1.hortonworks.com/HDP/ubuntu14/2.x/updates/2.4.2.0 HDP main' &gt;&gt; /etc/apt/sources.list.d/HDP.list RUN echo 'deb http://private-repo-1.hortonworks.com/HDP-UTILS-1.1.0.20/repos/ubuntu14 HDP-UTILS main' &gt;&gt; /etc/apt/sources.list.d/HDP.list RUN echo 'deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/azurecore/ trusty main' &gt;&gt; /etc/apt/sources.list.d/azure-public-trusty.list .... Rest of your Dockerfile. </code></pre>
17,819,710
Is there any way to convert a Map to a JSON representation using Jackson without writing to a file?
<p>I'm trying to use Jackson to convert a HashMap to a JSON representation.</p> <p>However, all the ways I've seen involve writing to a file and then reading it back, which seems really inefficient. I was wondering if there was anyway to do it directly? </p> <p>Here's an example of an instance where I'd like to do it</p> <pre><code>public static Party readOneParty(String partyName) { Party localParty = new Party(); if(connection==null) { connection = new DBConnection(); } try { String query = "SELECT * FROM PureServlet WHERE PARTY_NAME=?"; ps = con.prepareStatement(query); ps.setString(1, partyName); resultSet = ps.executeQuery(); meta = resultSet.getMetaData(); String columnName, value; resultSet.next(); for(int j=1;j&lt;=meta.getColumnCount();j++) { // necessary to start at j=1 because of MySQL index starting at 1 columnName = meta.getColumnLabel(j); value = resultSet.getString(columnName); localParty.getPartyInfo().put(columnName, value); // this is the hashmap within the party that keeps track of the individual values. The column Name = label, value is the value } } } public class Party { HashMap &lt;String,String&gt; partyInfo = new HashMap&lt;String,String&gt;(); public HashMap&lt;String,String&gt; getPartyInfo() throws Exception { return partyInfo; } } </code></pre> <p>The output would look something like this</p> <pre><code>"partyInfo": { "PARTY_NAME": "VSN", "PARTY_ID": "92716518", "PARTY_NUMBER": "92716518" } </code></pre> <p>So far every example I've come across of using <code>ObjectMapper</code> involves writing to a file and then reading it back. </p> <p>Is there a Jackson version of Java's <code>HashMap</code> or <code>Map</code> that'll work in a similar way to what I have implemented?</p>
17,821,453
2
1
null
2013-07-23 19:49:06.51 UTC
2
2016-04-05 13:04:19.967 UTC
2015-07-31 07:25:18.573 UTC
null
1,082,449
user2494770
null
null
1
33
java|json|jackson
68,350
<p>Pass your Map to <code>ObjectMapper.writeValueAsString(Object value)</code></p> <p>It's more efficient than using <code>StringWriter</code>, <a href="http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#writeValueAsString%28java.lang.Object%29">according to the docs</a>:</p> <blockquote> <p>Method that can be used to serialize any Java value as a String. Functionally equivalent to calling writeValue(Writer,Object) with StringWriter and constructing String, but more efficient.</p> </blockquote> <p><strong>Example</strong></p> <pre><code>import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class Example { public static void main(String[] args) throws IOException { Map&lt;String,String&gt; map = new HashMap&lt;&gt;(); map.put("key1","value1"); map.put("key2","value2"); String mapAsJson = new ObjectMapper().writeValueAsString(map); System.out.println(mapAsJson); } } </code></pre>
1,389,431
How to check if JSON object is empty in PHP?
<p>I'm reading JSON data with PHP and that data contains empty objects (like <code>{}</code>). So the problem is, I have to handle the case when object is empty in different manner but I can't find good enough way to do the check. <code>empty(get_object_vars(object))</code> looks too scary and very inefficient. Is there good way to do the check?</p>
1,389,591
5
1
null
2009-09-07 13:28:10.917 UTC
6
2018-01-03 16:30:07.263 UTC
2018-01-03 16:30:07.263 UTC
null
3,995,261
null
6,258
null
1
24
php|json
65,725
<p>How many objects are you unserializing? Unless <code>empty(get_object_vars($object))</code> or casting to array proves to be a major slowdown/bottleneck, I wouldn't worry about it – Greg's solution is just fine.</p> <p>I'd suggest using the the <code>$associative</code> flag when decoding the JSON data, though: </p> <pre><code>json_decode($data, true) </code></pre> <p>This decodes JSON objects as plain old PHP arrays instead of as <code>stdClass</code> objects. Then you can check for empty objects using <code>empty()</code> and create objects of a user-defined class instead of using <code>stdClass</code>, which is probably a good idea in the long run.</p>
1,615,813
How to use C++ classes with ctypes?
<p>I'm just getting started with ctypes and would like to use a C++ class that I have exported in a dll file from within python using ctypes. So lets say my C++ code looks something like this:</p> <pre class="lang-c++ prettyprint-override"><code>class MyClass { public: int test(); ... </code></pre> <p>I would know create a .dll file that contains this class and then load the .dll file in python using ctypes. Now how would I create an Object of type MyClass and call its test function? Is that even possible with ctypes? Alternatively I would consider using SWIG or Boost.Python but ctypes seems like the easiest option for small projects.</p>
1,616,143
5
0
null
2009-10-23 20:51:00.747 UTC
28
2022-09-12 06:43:52.683 UTC
2015-01-23 18:57:30.083 UTC
null
3,204,551
null
89,987
null
1
65
c++|python|ctypes
60,400
<p>The short story is that there is no standard binary interface for C++ in the way that there is for C. Different compilers output different binaries for the same C++ dynamic libraries, due to name mangling and different ways to handle the stack between library function calls.</p> <p>So, unfortunately, there really isn't a portable way to access C++ libraries <em>in general</em>. But, for one compiler at a time, it's no problem. </p> <p><a href="http://blog.vrplumber.com/index.php?/archives/197-Ctypes-for-C++-is-going-to-be-a-pain-due-to-politics-Bothering-language-creators-is-fun....html" rel="noreferrer">This blog post</a> also has a short overview of why this currently won't work. Maybe after C++0x comes out, we'll have a standard ABI for C++? Until then, you're probably not going to have any way to access C++ classes through Python's <code>ctypes</code>.</p>
1,775,005
"super star" or find the word under the cursor equivalent in emacs
<p>I'm a vim user and have recently been trying out emacs for fun. I find that the feature I'm missing most so far from vim is the "<a href="http://vim.wikia.com/wiki/VimTip1" rel="noreferrer">super star</a>" (find the word under the cursor by typing *) feature, and I have yet to find the equivalent in emacs. If it's not built in, what would I need to add to my emacs file to get something similar?</p>
1,775,184
6
3
null
2009-11-21 09:16:34.087 UTC
13
2019-02-13 15:45:11.86 UTC
null
null
null
null
214,302
null
1
33
search|vim|emacs|editor
8,447
<p>As <a href="/questions/1775005/super-star-or-find-the-word-under-the-cursor-equivalent-in-emacs#comment54758673_1775184">pointed out</a> by <a href="/users/556072/paldepind">paldepind</a>, <code>isearch-forward-symbol-at-point</code> (<kbd>M-s</kbd><kbd>.</kbd>, by default) is a close equivalent to <kbd>*</kbd> in Vim. This function is available starting in GNU Emacs 24.4; if your Emacs is different or older, read on for alternatives.</p> <p>Usually I just do (<kbd>M-b</kbd> ...) <kbd>C-s</kbd> <kbd>C-w</kbd> ... <kbd>C-s</kbd>. That is: </p> <ol> <li><kbd>M-b</kbd> to move to beginning of word(s) of interest <ul> <li>zero or more of these</li> </ul></li> <li><kbd>C-s</kbd> to start an I-Search</li> <li><kbd>C-w</kbd> to yank the word(s) starting at point <ul> <li>one or more of these</li> </ul></li> <li><kbd>C-s</kbd> to find the next match</li> <li>more <kbd>C-s</kbd> to find later matches</li> <li><kbd>RET</kbd> to exit the I-search at the most recent match <ul> <li>or a bunch of <kbd>C-g</kbd> to abort back to the original starting location</li> </ul></li> </ol> <p>Here is a go at integrating it into I-Search (invoked via <kbd>C-s</kbd> and <kbd>C-r</kbd>; use <kbd>C-h k</kbd> <kbd>C-s</kbd> for info on <code>isearch</code>).</p> <pre><code>(require "thingatpt") (require "isearch") (define-key isearch-mode-map (kbd "C-*") (lambda () "Reset current isearch to a word-mode search of the word under point." (interactive) (setq isearch-word t isearch-string "" isearch-message "") (isearch-yank-string (word-at-point)))) </code></pre> <p>Integrating it into I-Search takes advantage of its word matching and case sensitivity settings (<kbd>C-s</kbd> <kbd>M-c</kbd> <kbd>C-*</kbd> would do a case-sensitive search on the word under point).</p>
2,261,480
In Joda-Time, set DateTime to start of month
<p>My API allows library client to pass Date:</p> <pre><code>method(java.util.Date date) </code></pre> <p>Working with <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a>, from this date I would like to extract the month and iterate over all days this month contains.</p> <p>Now, the passed date is usually <em>new Date()</em> - meaning current instant. My problem actually is setting the new <em>DateMidnight(jdkDate)</em> instance to be at the start of the month.</p> <p>Could someone please demonstrates this use case with <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a>?</p>
2,261,547
6
3
null
2010-02-14 14:56:10.023 UTC
6
2020-08-20 12:12:04.443 UTC
2013-11-25 23:34:14.477 UTC
null
642,706
null
48,062
null
1
34
java|date|jodatime
39,190
<p>Midnight at the start of the first day of the current month is given by:</p> <pre><code>// first midnight in this month DateMidnight first = new DateMidnight().withDayOfMonth(1); // last midnight in this month DateMidnight last = first.plusMonths(1).minusDays(1); </code></pre> <p>If starting from a java.util.Date, a different DateMidnight constructor is used: </p> <pre><code>// first midnight in java.util.Date's month DateMidnight first = new DateMidnight( date ).withDayOfMonth(1); </code></pre> <p>Joda Time java doc - <a href="https://www.joda.org/joda-time/apidocs/overview-summary.html" rel="nofollow noreferrer">https://www.joda.org/joda-time/apidocs/overview-summary.html</a></p>
1,525,605
Programmatically get parent pid of another process?
<p>I tried google, but found <code>getppid()</code> which gets the parent pid of the <em>current</em> process.</p> <p>I need something like <code>getppid(some_other_pid)</code>, is there such a thing? Basically takes the pid of some process and returns the parent process' pid.</p>
1,525,673
7
2
null
2009-10-06 13:30:10.663 UTC
9
2022-09-12 21:55:43.48 UTC
2022-09-12 18:33:13.613 UTC
null
224,132
null
35,364
null
1
33
linux|process|operating-system|pid
23,570
<p>I think the simplest thing would be to open &quot;/proc&quot; and parse the contents.</p> <p>You'll find the ppid as the 4th parameter of /proc/pid/stat</p> <p>In C, libproc has a <code>get_proc_stats</code> function for parsing that file: see <a href="https://stackoverflow.com/questions/35399271/given-a-child-pid-how-can-you-get-the-parent-pid">Given a child PID how can you get the parent PID</a> for an example.</p>
1,398,664
Enum.GetValues() Return Type
<p>I have read the documentation that states that &quot;given the type of the enum, the GetValues() method of System.Enum will return an array of the given enum's base type&quot; i.e. int, byte, etc.</p> <p>However, I have been using the GetValues() method and all I keep getting back is an array of type Enums. Am I missing something?</p> <pre class="lang-cs prettyprint-override"><code>public enum Response { Yes = 1, No = 2, Maybe = 3 } foreach (var value in Enum.GetValues(typeof(Response))) { var type = value.GetType(); // type is always of type Enum not of the enum base type } </code></pre>
1,398,668
7
2
null
2009-09-09 09:54:16.51 UTC
6
2022-08-26 01:11:42.37 UTC
2022-08-26 01:11:42.37 UTC
null
1,402,846
null
109,288
null
1
73
c#|enums
80,892
<p>You need to cast the result to the actual array type you want</p> <pre><code>(Response[])Enum.GetValues(typeof(Response)) </code></pre> <p>as GetValues isn't strongly typed</p> <p>EDIT: just re-read the answer. You need to explicitly cast each enum value to the underlying type, as GetValues returns an array of the actual enum type rather than the base type. Enum.GetUnderlyingType could help with this.</p>
1,666,052
Java HTTPS client certificate authentication
<p>I'm fairly new to <code>HTTPS/SSL/TLS</code> and I'm a bit confused over what exactly the clients are supposed to present when authenticating with certificates.</p> <p>I'm writing a Java client that needs to do a simple <code>POST</code> of data to a particular <code>URL</code>. That part works fine, the only problem is it's supposed to be done over <code>HTTPS</code>. The <code>HTTPS</code> part is fairly easy to handle (either with <code>HTTPclient</code> or using Java's built-in <code>HTTPS</code> support), but I'm stuck on authenticating with client certificates. I've noticed there's already a very similar question on here, which I haven't tried out with my code yet (will do so soon enough). My current issue is that - whatever I do - the Java client never sends along the certificate (I can check this with <code>PCAP</code> dumps).</p> <p>I would like to know what exactly the client is supposed to present to the server when authenticating with certificates (specifically for Java - if that matters at all)? Is this a <code>JKS</code> file, or <code>PKCS#12</code>? What's supposed to be in them; just the client certificate, or a key? If so, which key? There's quite a bit of confusion about all the different kinds of files, certificate types and such.</p> <p>As I've said before I'm new to <code>HTTPS/SSL/TLS</code> so I would appreciate some background information as well (doesn't have to be an essay; I'll settle for links to good articles).</p>
1,710,543
9
1
null
2009-11-03 08:51:39.66 UTC
195
2022-02-22 11:16:34.087 UTC
2019-02-25 22:28:45.24 UTC
null
9,851,598
null
201,202
null
1
262
java|ssl|https|client-certificates
448,159
<p>Finally managed to solve all the issues, so I'll answer my own question. These are the settings/files I've used to manage to get my particular problem(s) solved;</p> <p>The <strong>client's keystore</strong> is a <strong>PKCS#12 format</strong> file containing</p> <ol> <li>The client's <strong>public</strong> certificate (in this instance signed by a self-signed CA)</li> <li>The client's <strong>private</strong> key</li> </ol> <p>To generate it I used OpenSSL's <code>pkcs12</code> command, for example;</p> <pre><code>openssl pkcs12 -export -in client.crt -inkey client.key -out client.p12 -name "Whatever" </code></pre> <p><em>Tip:</em> make sure you get the latest OpenSSL, <strong>not</strong> version 0.9.8h because that seems to suffer from a bug which doesn't allow you to properly generate PKCS#12 files.</p> <p>This PKCS#12 file will be used by the Java client to present the client certificate to the server when the server has explicitly requested the client to authenticate. See the <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security#Client-authenticated_TLS_handshake" rel="noreferrer">Wikipedia article on TLS</a> for an overview of how the protocol for client certificate authentication actually works (also explains why we need the client's private key here).</p> <p>The <strong>client's truststore</strong> is a straight forward <strong>JKS format</strong> file containing the <strong>root</strong> or <strong>intermediate CA certificates</strong>. These CA certificates will determine which endpoints you will be allowed to communicate with, in this case it will allow your client to connect to whichever server presents a certificate which was signed by one of the truststore's CA's.</p> <p>To generate it you can use the standard Java keytool, for example;</p> <pre><code>keytool -genkey -dname "cn=CLIENT" -alias truststorekey -keyalg RSA -keystore ./client-truststore.jks -keypass whatever -storepass whatever keytool -import -keystore ./client-truststore.jks -file myca.crt -alias myca </code></pre> <p>Using this truststore, your client will try to do a complete SSL handshake with all servers who present a certificate signed by the CA identified by <code>myca.crt</code>.</p> <p>The files above are strictly for the client only. When you want to set-up a server as well, the server needs its own key- and truststore files. A great walk-through for setting up a fully working example for both a Java client and server (using Tomcat) can be found on <a href="http://emo.sourceforge.net/cert-login-howto.html" rel="noreferrer">this website</a>.</p> <p><strong>Issues/Remarks/Tips</strong></p> <ol> <li><strong>Client certificate authentication</strong> can only be enforced by the server.</li> <li>(<em>Important!</em>) When the server requests a client certificate (as part of the TLS handshake), it will also provide a list of trusted CA's as part of the certificate request. When the client certificate you wish to present for authentication is <strong>not</strong> signed by one of these CA's, it won't be presented at all (in my opinion, this is weird behaviour, but I'm sure there's a reason for it). This was the main cause of my issues, as the other party had not configured their server properly to accept my self-signed client certificate and we assumed that the problem was at my end for not properly providing the client certificate in the request.</li> <li>Get Wireshark. It has great SSL/HTTPS packet analysis and will be a tremendous help debugging and finding the problem. It's similar to <code>-Djavax.net.debug=ssl</code> but is more structured and (arguably) easier to interpret if you're uncomfortable with the Java SSL debug output.</li> <li><p>It's perfectly possible to use the Apache httpclient library. If you want to use httpclient, just replace the destination URL with the HTTPS equivalent and add the following JVM arguments (which are the same for any other client, regardless of the library you want to use to send/receive data over HTTP/HTTPS):</p> <pre><code>-Djavax.net.debug=ssl -Djavax.net.ssl.keyStoreType=pkcs12 -Djavax.net.ssl.keyStore=client.p12 -Djavax.net.ssl.keyStorePassword=whatever -Djavax.net.ssl.trustStoreType=jks -Djavax.net.ssl.trustStore=client-truststore.jks -Djavax.net.ssl.trustStorePassword=whatever</code></pre></li> </ol>
1,424,276
Ellipsize not working for textView inside custom listView
<p>I have a listView with custom objects defined by the xml-layout below. I want the textView with id "info" to be ellipsized on a single line, and I've tried using the attributes </p> <pre><code>android:singleLine="true" android:ellipsize="end" </code></pre> <p>without success.</p> <p>If I set the layout_width to a fixed width like e.g.</p> <pre><code>android:layout_width="100px" </code></pre> <p>the text is truncated fine. But for portability reasons this is not an acceptable solution.</p> <p>Can you spot the problem?</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="5px" &gt; &lt;TextView android:id="@+id/destination" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="22dp" android:paddingLeft="5px" /&gt; &lt;TextView android:id="@+id/date" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="15dp" android:paddingLeft="5px" /&gt; &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/info_table" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="5px" android:paddingTop="10px" &gt; &lt;TableRow&gt; &lt;TextView android:id="@+id/driver_label" android:gravity="right" android:paddingRight="5px" android:text="@string/driver_label" /&gt; &lt;TextView android:id="@+id/driver" /&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView android:id="@+id/passenger_label" android:gravity="right" android:paddingRight="5px" android:text="@string/passenger_label" /&gt; &lt;TextView android:id="@+id/passengers" /&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView android:id="@+id/info_label" android:gravity="right" android:paddingRight="5px" android:text="@string/info_label"/&gt; &lt;TextView android:id="@+id/info" android:layout_width="fill_parent" android:singleLine="true" android:ellipsize="end" /&gt; &lt;/TableRow&gt; &lt;/TableLayout&gt; </code></pre> <p></p>
1,424,686
9
0
null
2009-09-14 22:49:57.747 UTC
15
2017-03-09 06:59:01.437 UTC
null
null
null
null
91,098
null
1
28
xml|android|textview
35,856
<p>Ellipsize is broken (go <a href="http://code.google.com/p/android/issues/detail?id=882" rel="noreferrer">vote on the bug report</a>, especially since they claim it's not reproducible) so you have to use a minor hack. Use:</p> <pre><code>android:inputType="text" android:maxLines="1" </code></pre> <p>on anything you want to ellipsize. Also, don't use <code>singleLine</code>, it's been deprecated.</p> <p><strong>UPDATE:</strong></p> <p>On closer inspection, the problem you're having is that your table is extending off the right side of the screen. Changing your <code>TableLayout</code> definition to:</p> <pre><code>&lt;TableLayout android:id="@+id/info_table" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingLeft="5px" android:paddingTop="10px" android:shrinkColumns="1"&gt; </code></pre> <p>should fix that problem, then do what I said above to ellipsize your <code>TextView</code>.</p>
1,469,994
Using 'make' on OS X
<p>I have a MacBook Pro that I'm trying to do some development on.</p> <p>I have a program I want to build, and when I went to use <code>make</code> to build it, I got a "command not found" error. I did some googling and Stack&nbsp;Overflow searches and it doesn't look like this is a common problem. Why don't I have <code>make</code> installed and how do I get it?</p> <p>I'm extra confused, because I know I used it relatively recently (in the past month or so) when I was on this laptop.</p>
1,470,005
11
2
null
2009-09-24 06:07:25.123 UTC
18
2019-07-29 11:11:00.117 UTC
2019-07-29 11:11:00.117 UTC
null
63,550
null
63,791
null
1
73
macos|makefile|terminal
141,759
<p>Have you installed the Apple developer tools? What happens if you type gcc -v ?</p> <p>It look as if you do not have downloaded the development stuff. You can get it for free (after registration) from <a href="http://developer.apple.com/" rel="noreferrer">http://developer.apple.com/</a></p>
1,941,928
How to store data locally in .NET (C#)
<p>I'm writing an application that takes user data and stores it locally for use later. The application will be started and stopped fairly often, and I'd like to make it save/load the data on application start/end.</p> <p>It'd be fairly straightforward if I used flat files, as the data doesn't really need to be secured (it'll only be stored on this PC). The options I believe are thus:</p> <ul> <li>Flat files</li> <li>XML</li> <li>SQL DB</li> </ul> <p>Flat files require a bit more effort to maintain (no built in classes like with XML), however I haven't used XML before, and SQL seems like overkill for this relatively easy task.</p> <p>Are there any other avenues worth exploring? If not, which of these is the best solution?</p> <hr> <p>Edit: To add a little more data to the problem, basically the only thing I'd like to store is a Dictionary that looks like this</p> <pre><code>Dictionary&lt;string, List&lt;Account&gt;&gt; </code></pre> <p>where Account is another custom type.</p> <p>Would I serialize the dict as the xmlroot, and then the Account type as attributes?</p> <hr> <p>Update 2:</p> <p>So it's possible to serialize a dictionary. What makes it complicated is that the value for this dict is a generic itself, which is a list of complex data structures of type Account. Each Account is fairly simple, it's just a bunch of properties.</p> <p>It is my understanding that the goal here is to try and end up with this:</p> <pre><code>&lt;Username1&gt; &lt;Account1&gt; &lt;Data1&gt;data1&lt;/Data1&gt; &lt;Data2&gt;data2&lt;/Data2&gt; &lt;/Account1&gt; &lt;/Username1&gt; &lt;Username2&gt; &lt;Account1&gt; &lt;Data1&gt;data1&lt;/Data1&gt; &lt;Data2&gt;data2&lt;/Data2&gt; &lt;/Account1&gt; &lt;Account2&gt; &lt;Data1&gt;data1&lt;/Data1&gt; &lt;Data2&gt;data2&lt;/Data2&gt; &lt;/Account2&gt; &lt;/Username2&gt; </code></pre> <p>As you can see the heirachy is </p> <ul> <li>Username (string of dict) > </li> <li>Account (each account in the List) > </li> <li>Account data (ie class properties). </li> </ul> <p>Obtaining this layout from a <code>Dictionary&lt;Username, List&lt;Account&gt;&gt;</code> is the tricky bit, and the essence of this question.</p> <p>There are plenty of 'how to' responses here on serialisation, which is my fault since I didn't make it clearer early on, but now I'm looking for a definite solution.</p>
1,942,374
19
2
null
2009-12-21 19:00:40.91 UTC
46
2022-03-15 17:55:07.343 UTC
2022-03-15 17:55:07.343 UTC
null
169,713
null
169,713
null
1
79
c#|.net|xml|data-storage
186,090
<p>I'd store the file as <a href="http://www.json.org/" rel="noreferrer">JSON</a>. Since you're storing a dictionary which is just a name/value pair list then this is pretty much what json was designed for.<br> There a quite a few decent, free .NET json libraries - here's <a href="http://james.newtonking.com/projects/json-net.aspx" rel="noreferrer">one</a> but you can find a full list on the first link.</p>
8,642,012
Why should a Comparator implement Serializable?
<p>New to Java. Learning it while working on an Android app. I am implementing a Comparator to sort a list of files and the android docs <a href="http://developer.android.com/reference/java/util/Comparator.html" rel="noreferrer">say</a> that a Comparator should implement Serializable:</p> <blockquote> <p>It is recommended that a Comparator implements Serializable.</p> </blockquote> <p>This is the Serializable interface <a href="http://developer.android.com/reference/java/io/Serializable.html" rel="noreferrer">here</a>.</p> <p>I just want to sort a list of files. Why should I implement this or what even is the reason why it should be for any Comparator?</p>
8,642,040
5
2
null
2011-12-27 07:06:29.953 UTC
8
2016-05-09 15:22:02.797 UTC
2011-12-27 08:09:35.077 UTC
null
66,475
null
66,475
null
1
43
java|android|sorting|serialization|comparator
23,158
<p>This is not just an Android thing, the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html">Java SDK has the same recommendation</a>:</p> <blockquote> <p>Note: It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.</p> </blockquote> <p>So the idea is that because a TreeMap is serializable, and the TreeMap can contain a Comparator, it would be good if the Comparator is also serializable. The same applies for all elements in the collection.</p> <p>You can safely ignore this unless you use serialization in that way.</p>
6,678,756
Get all images from specific Facebook album with Graph API PHP SDK
<p>Hi I'm trying to grab all pictures from a specific album (always the same hardcoded id). I'm using the Graph API PHP SDK from Facebook. This is my code:</p> <pre><code>&lt;?php require 'phpfiles/facebook.php'; $facebook = new Facebook(array( 'appId' =&gt; 'aaaa', 'secret' =&gt; 'bbbb', 'cookie' =&gt; true )); $user_profile = $facebook-&gt;api('/1881235503185/photos?access_token=cccc'); var_dump($user_profile); </code></pre> <p>The var_dump output:</p> <pre><code>array(1) { ["data"]=&gt; array(0) { } } </code></pre> <ul> <li>1881235503185 is the id of MY album that is not restricted, it's open to everybody</li> <li>the access_token is the token I get from my application page for my fb id. I don't get oauth errors.</li> <li>I have the permissions (user_photos) and tryed to add a dozen of other permissions.</li> <li>When I try it with the Graph API Explorer it works to. </li> </ul> <p>When I use the Javascript SDK it works fine...</p> <pre><code>FB.api('/1881235503185/photos?access_token=cccc', function(response) { alert(response.data[0].name); }); </code></pre> <p>Output: Diep in de put</p> <p>Am I forgetting something?</p>
6,689,492
3
1
null
2011-07-13 12:22:02.837 UTC
5
2015-08-18 06:22:37.27 UTC
null
null
null
null
229,532
null
1
8
php|facebook|facebook-graph-api
39,177
<p>I got it! It should be: <strike></p> <pre><code>$user_profile = $facebook-&gt;api('/1881235503185/photos', array('access_token' =&gt; 'cccc')); </code></pre> <p></strike></p> <p>With the new Facebook PHP SDK it should be: </p> <pre><code>$albumjson = $facebook-&gt;api('/1881235503185?fields=photos'); </code></pre>
6,918,900
Impersonate tag in Web.Config
<p>I'm using <code>impersonate</code> tag in my web.config in Asp.net 4.0 website.</p> <p><strong>Below is my Web.Config code:</strong></p> <pre><code>&lt;system.web&gt; &lt;authentication mode="Windows"&gt; &lt;identity impersonate="true" userName="Administrator" password="LALLA$26526"/&gt; &lt;/authentication&gt; &lt;/system.web&gt; </code></pre> <p>When I run app in Visual Studio I get this error:</p> <pre><code>Parser Error Message: Unrecognized element 'identity'. </code></pre> <p>Source Error:</p> <pre><code>Line 50: &lt;system.web&gt; Line 51: &lt;authentication mode="Windows"&gt; Line 52: &lt;identity impersonate="true" Line 53: userName="Administrator" Line 54: password="LALLA$26526"/&gt; </code></pre> <p>Where am i going wrong?</p>
6,918,964
3
0
null
2011-08-02 21:30:41.79 UTC
11
2018-08-24 12:11:10.7 UTC
2018-08-24 12:11:10.7 UTC
null
107,625
user572844
null
null
1
30
asp.net|web-config|impersonation
148,930
<p>The <code>identity</code> section goes under the <code>system.web</code> section, not under <code>authentication</code>:</p> <pre><code>&lt;system.web&gt; &lt;authentication mode="Windows"/&gt; &lt;identity impersonate="true" userName="foo" password="bar"/&gt; &lt;/system.web&gt; </code></pre>
6,640,640
Check multiple items in ASP.NET CheckboxList
<p>I try to check multiple values in ASP.NET CheckboxList but I couldn't. <br> I Wrote : </p> <pre><code>chkApplications.SelectedValue = 2; chkApplications.SelectedValue = 6; </code></pre> <p>But it just selects item with value '6'<br> What's wrong ?</p>
6,640,677
4
0
null
2011-07-10 10:49:58.747 UTC
3
2016-02-12 15:56:29.67 UTC
null
null
null
null
369,161
null
1
9
c#|asp.net|checkboxlist
42,712
<p>The best technique that will work for you is the following: </p> <pre><code>chkApplications.Items.FindByValue("2").Selected = true; chkApplications.Items.FindByValue("6").Selected = true; </code></pre> <p>OR you can simply do it like...</p> <pre><code> foreach (ListItem item in chkApplications.Items) { if (item.Value == "2" || item.Value == "6") { item.Selected = true; } } </code></pre>
15,701,952
Change size of arrows using matplotlib quiver
<p>I am using quiver from matplotlib to plot a vectorial field. I would like to change the size of the thickness of each arrow depending on the number of data which produced a specific arrow of the vector field. Therefore what I am looking for is not a general scale transformation of the arrow size, but the way to customize the thickness of the arrow in quiver one-by-one. Is it possible? Can you help me?</p>
15,702,208
2
0
null
2013-03-29 11:02:20.67 UTC
3
2018-05-29 17:48:06.31 UTC
null
null
null
null
1,234,383
null
1
12
python|matplotlib
41,246
<p>The <code>linewidths</code> parameter to <code>plt.quiver</code> controls the thickness of the arrows. If you pass it a 1-dimensional array of values, each arrow gets a different thickness. </p> <p>For example,</p> <pre><code>widths = np.linspace(0, 2, X.size) plt.quiver(X, Y, cos(deg), sin(deg), linewidths=widths) </code></pre> <p>creates linewidths growing from 0 to 2.</p> <hr> <pre><code>import matplotlib.pyplot as plt import numpy as np sin = np.sin cos = np.cos # http://stackoverflow.com/questions/6370742/#6372413 xmax = 4.0 xmin = -xmax D = 20 ymax = 4.0 ymin = -ymax x = np.linspace(xmin, xmax, D) y = np.linspace(ymin, ymax, D) X, Y = np.meshgrid(x, y) # plots the vector field for Y'=Y**3-3*Y-X deg = np.arctan(Y ** 3 - 3 * Y - X) widths = np.linspace(0, 2, X.size) plt.quiver(X, Y, cos(deg), sin(deg), linewidths=widths) plt.show() </code></pre> <p>yields</p> <p><img src="https://i.stack.imgur.com/4YYiw.png" alt="enter image description here"></p>
40,257,968
Slow app compilation with new Sierra update
<p>When I updated my mac to macOS Sierra 10.12.1 time of running application on real device significantly increased. "Run custom script 'Embed Pods Frameworks'" and "Copy Swift standard libraries" take more then 30 minutes to build. </p> <p>Do someone face the same issue?</p>
40,298,722
4
5
null
2016-10-26 09:01:21.383 UTC
19
2017-07-26 14:35:17.427 UTC
2016-10-28 06:29:26.427 UTC
null
932,644
null
932,644
null
1
30
xcode|cocoapods|keychain|macos-sierra
5,467
<p>Check your keychain. After updating to Sierra to 10.12.1, I had over 500 copies one of my certificates, and a few others were duplicated a few hundred times. </p> <p>I removed all the duplicates and kept just one of each, and my code signing time went from 30 seconds per framework down to about 1 second per. </p> <p>I don't know how or why the certificates were duplicated, but the timing of the issue suggests it was due to updating Sierra.</p>
57,650,692
Where to store the refresh token on the Client?
<p>My SPA application uses the following architecture (<a href="https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/" rel="noreferrer">source</a>):</p> <p><a href="https://i.stack.imgur.com/BPJjA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BPJjA.png" alt="enter image description here"></a></p> <p>This assumes that my client application knows about the refresh token, because I need it to request a new access token if no user credentials (e.g. email/password) are present.</p> <p>My question: <strong>Where do I store the refresh token in my client-side application?</strong> There are lots of questions/answers about this topic on SO, but regarding the refresh token the answer are not clear.</p> <p>Access token and refresh token shouldn't be stored in the local/session storage, because they are not a place for any sensitive data. Hence I would store the <strong>access token</strong> in a <code>httpOnly</code> cookie (even though there is CSRF) and I need it for most of my requests to the Resource Server anyway.</p> <p><strong>But what about the refresh token?</strong> I cannot store it in a cookie, because (1) it would be send with every request to my Resource Server as well which makes it vulnerable to CSRF too and (2) it would send expose both access/refresh token with an identical attack vector.</p> <p>There are three solutions I could think of:</p> <hr> <p>1) Storing the refresh token in an in-memory JavaScript variable, which has two drawbacks: </p> <ul> <li>a) It's vulnerable to XSS (but may be not as obvious as local/session storage</li> <li>b) It looses the "session" if a user closes the browser tab</li> </ul> <p>Especially the latter drawback makes will turn out as a bad UX.</p> <hr> <p>2) Storing the access token in session storage and sending it via a <code>Bearer access_token</code> authorization header to my resource server. Then I can use <code>httpOnly</code> cookies for the refresh token. This has one drawback that I can think of:</p> <ul> <li>a) The refresh token is exposed to CSRF with every request made to the Resource Server. </li> </ul> <hr> <p>3) Keep both tokens in <code>httpOnly</code> cookies which has the mentioned drawback that both tokens are exposed to the same attack vector.</p> <hr> <p>Maybe there is another way or more than my mentioned drawbacks (please let me know), but in the end everything boils down to <strong>where do I keep my refresh token on the client-side</strong>? Is it <code>httpOnly</code> cookie or an in-memory JS variable? If it is the former, where do I put my access token then? </p> <p>Would be super happy to get any clues about how to do this the best way from people who are familiar with the topic.</p>
57,826,596
6
3
null
2019-08-26 00:34:31.23 UTC
41
2021-05-04 13:54:53.113 UTC
2019-09-02 01:28:45.373 UTC
null
1,189,762
null
1,189,762
null
1
94
authentication|cookies|oauth|oauth-2.0|token
83,136
<p>You can store encrypted tokens securely in <code>HttpOnly</code> cookies.</p> <p><a href="https://medium.com/@sadnub/simple-and-secure-api-authentication-for-spas-e46bcea592ad" rel="noreferrer">https://medium.com/@sadnub/simple-and-secure-api-authentication-for-spas-e46bcea592ad</a></p> <p>If you worry about long-living Refresh Token. You can skip storing it and not use it at all. Just keep Access Token in memory and do silent sign-in when Access Token expires.</p> <blockquote> <p>Don't use <code>Implicit</code> flow because it's <a href="https://developer.okta.com/blog/2019/05/01/is-the-oauth-implicit-flow-dead" rel="noreferrer">obsolete</a>.</p> </blockquote> <p>The most secure way of authentication for SPA is <a href="https://developer.okta.com/blog/2019/08/22/okta-authjs-pkce" rel="noreferrer">Authorization Code with PKCE</a>.</p> <p>In general, it's better to use existing libraries based on <a href="https://github.com/IdentityModel/oidc-client-js/" rel="noreferrer">oidc-client</a> than building something on your own.</p>
57,305,227
How to use map function for hooks useState properties
<p>I tried to use map function for looping my list data in react-hooks useState but I stuck with an error that "TypeError: Cannot read property 'map' of undefined"</p> <pre><code>//1.Initial declaration const App = props=&gt; { const [state, changeState]= useState ({ name:"", eventTitle:"", details:"", objdata:{}, list:[], toggleIndex:"", editName: "", editEventTitle: "", editDetails: "", editObj: {} }); //2.logic comes here //3.tried using map {(state.list.map((data,id)=&gt;{ console.log ('loop data',data) }))} </code></pre> <p><a href="https://i.stack.imgur.com/td100.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/td100.png" alt="enter image description here"></a></p>
57,310,256
2
7
null
2019-08-01 08:53:16.5 UTC
6
2019-08-01 13:54:42.48 UTC
2019-08-01 08:57:55.32 UTC
null
6,919,895
null
11,457,419
null
1
3
reactjs|react-hooks
48,688
<p>As we suspected you are not setting your state in the right way. I tried to explain in my comment, with hooks when you set your state it does not merge the updated properties with the current one. So, you should think about that. Right now you are setting your state like that:</p> <pre><code>const handleName = name =&gt; { changeState({ name: name.target.value }); }; </code></pre> <p>Here, you are setting the <code>name</code> property and lose other parts of your state. Hence, when you set your state, you lose <code>list</code> as well as other parts of your state. This is how you should do it:</p> <pre><code>const handleName = name =&gt; { const { target } = name; changeState(state =&gt; ({ ...state, name: target.value, })); }; </code></pre> <p>You take the old state, keep the other properties by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="noreferrer">spreading</a> it, then update the relevant part. I would use here <code>event</code> instead of <code>name</code>. It is not "name", it is "event" after all actually :)</p> <pre><code>const handleName = event =&gt; { const { target } = event; changeState(state =&gt; ({ ...state, name: target.value, })); }; </code></pre> <p>Also, you have a few other problems and unnecessary parts in your code. For example, you are struggling too much to handle the submit and add an object to your <code>list</code>. You don't need an extra <code>objdata</code> in your state to push it to the <code>list</code>. If you want to construct an extra object, you can do it in the function itself.</p> <p>Here is a very simple way to do it:</p> <pre><code>const submitHandle = () =&gt; { const { name, eventTitle, details } = state; const obj = { name, eventTitle, details }; changeState(state =&gt; ({ ...state, list: [ ...state.list, obj ], })) }; </code></pre> <p>Again, we are using spread operator to keep both the other parts of the state and while updating the <code>list</code>, to keep other objects. Do not set your state as you do in your <code>submitHandle</code> function. Try to think it simple :)</p> <p>Also, you don't need to bind your functions when it is not necessary. You can find a working copy of the code below. I just removed unnecessary parts and fix the issues.</p> <pre><code>import React, { useState } from "react"; import ReactDOM from "react-dom"; const App = props =&gt; { const [state, changeState] = useState({ name: "", eventTitle: "", details: "", list: [], toggleIndex: "", editName: "", editEventTitle: "", editDetails: "", editObj: {} }); const handleName = event =&gt; { const { target } = event; changeState(state =&gt; ({ ...state, name: target.value })); }; const handleEventTitle = event =&gt; { const { target } = event; changeState(state =&gt; ({ ...state, eventTitle: target.value })); }; const handleDetails = event =&gt; { const { target } = event; changeState(state =&gt; ({ ...state, details: target.value })); }; const submitHandle = () =&gt; { const { name, eventTitle, details } = state; const obj = { name, eventTitle, details }; changeState(state =&gt; ({ ...state, list: [...state.list, obj] })); }; const resetHandle = () =&gt; changeState(state =&gt; ({ ...state, name: "", eventTitle: "", details: "" })); return ( &lt;div&gt; &lt;div className="jumbotron jumbotron-fluid"&gt; &lt;div className="container"&gt; &lt;h1 className="display-5 text-center"&gt;Let's set your reminders&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className="bg-dark container-fluid"&gt; &lt;div className="row"&gt; &lt;div className="col-sm-12 col-md-4 col-lg-4 " /&gt; &lt;div className="col-sm-12 col-md-4 col-lg-4 "&gt; &lt;div className="card login-card "&gt; &lt;div className=" card-header "&gt; &lt;h3 className="text-center"&gt; TO-DO LIST FORM&lt;/h3&gt; &lt;/div&gt; &lt;div className="card-body"&gt; &lt;form className="form-elements"&gt; &lt;input value={state.name} className="form-control form-inputs form-elements" type="text" onChange={handleName} placeholder="user name" /&gt; &lt;input value={state.eventTitle} className="form-control form-inputs form-elements" type="text" onChange={handleEventTitle} placeholder="Event Title" /&gt; &lt;input value={state.details} className="form-control form-inputs form-elements" type="text" onChange={handleDetails} placeholder="Details " /&gt; &lt;/form&gt; &lt;/div&gt; &lt;div className="card-footer "&gt; &lt;button type="submit" onClick={submitHandle} className="btn-primary offset-lg-1 offset-md-0 btn-sm " &gt; Create &lt;/button&gt; &lt;button type="reset" onClick={resetHandle} className="btn-primary offset-lg-5 offset-md-0 btn-sm" &gt; cancel &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className="col-sm-12 col-md-4 col-lg-4 " /&gt; &lt;/div&gt; &lt;div className="container-fluid bg-dark"&gt; &lt;div className="row "&gt; {state.list.map(data =&gt; ( &lt;div style={{ border: "1px black solid" }}&gt; &lt;p&gt;{data.name}&lt;/p&gt; &lt;p&gt;{data.eventTitle}&lt;/p&gt; &lt;p&gt;{data.details}&lt;/p&gt; &lt;/div&gt; ))} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className="footer footer-copyright" style={{ background: "#e9ecef" }} &gt; &lt;div className="container"&gt; &lt;h6 className=" text-center"&gt;Just make it work ;)&lt;/h6&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); }; ReactDOM.render(&lt;App /&gt;, document.getElementById("root")); </code></pre>
27,646,107
How to check if the user gave permission to use the camera?
<p>Trying to write this:</p> <pre><code>if usergavepermissiontousercamera opencamera else showmycustompermissionview </code></pre> <p>Couldn't find a current way to do this simple task.<br> Note: Should also work iOS7 even if it requires a different method</p>
27,646,311
6
3
null
2014-12-25 09:52:00.563 UTC
25
2020-08-28 08:19:24.673 UTC
null
null
null
null
2,589,276
null
1
99
ios|swift
92,125
<p>You can use the following code for doing the same:</p> <pre><code>if AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) == AVAuthorizationStatus.Authorized { // Already Authorized } else { AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted: Bool) -&gt; Void in if granted == true { // User granted } else { // User rejected } }) } </code></pre> <p><strong>NOTE:</strong></p> <ol> <li>Make sure that you add the <code>AVFoundation</code> Framework in the Link Binary section of build phases</li> <li>You should write <code>import AVFoundation</code> on your class for importing <code>AVFoundation</code></li> </ol> <p><strong>SWIFT 3</strong></p> <pre><code>if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) == AVAuthorizationStatus.authorized { // Already Authorized } else { AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -&gt; Void in if granted == true { // User granted } else { // User Rejected } }) } </code></pre> <h3>Swift 4</h3> <pre><code>if AVCaptureDevice.authorizationStatus(for: .video) == .authorized { //already authorized } else { AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in if granted { //access allowed } else { //access denied } }) } </code></pre>
16,098,362
How to deep copy a Binary Tree?
<p>I would like using my own Node class to implement tree structure in Java. But I'm confused how to do a deep copy to copy a tree.</p> <p>My Node class would be like this:</p> <pre><code>public class Node{ private String value; private Node leftChild; private Node rightChild; .... </code></pre> <p>I'm new to recursion, so is there any code I can study? Thank you!</p>
16,098,659
7
2
null
2013-04-19 06:12:44.36 UTC
6
2021-12-28 22:59:26.88 UTC
2018-03-14 18:57:08.79 UTC
null
1,727,979
null
1,156,192
null
1
8
java|recursion|tree|treenode
39,172
<p>try</p> <pre><code>class Node { private String value; private Node left; private Node right; public Node(String value, Node left, Node right) { this.value = value; ... } Node copy() { Node left = null; Node right = null; if (this.left != null) { left = this.left.copy(); } if (this.right != null) { right = this.right.copy(); } return new Node(value, left, right); } } </code></pre>
16,262,194
file upload in cakephp 2.3
<p>I'm new in cakephp and i'm trying to create a simple file upload with cakephp 2.3 here is my controller</p> <pre><code>public function add() { if ($this-&gt;request-&gt;is('post')) { $this-&gt;Post-&gt;create(); $filename = WWW_ROOT. DS . 'documents'.DS.$this-&gt;data['posts']['doc_file']['name']; move_uploaded_file($this-&gt;data['posts']['doc_file']['tmp_name'],$filename); if ($this-&gt;Post-&gt;save($this-&gt;request-&gt;data)) { $this-&gt;Session-&gt;setFlash('Your post has been saved.'); $this-&gt;redirect(array('action' =&gt; 'index')); } else { $this-&gt;Session-&gt;setFlash('Unable to add your post.'); } } } </code></pre> <p>and my add.ctp</p> <pre><code>echo $this-&gt;Form-&gt;create('Post'); echo $this-&gt;Form-&gt;input('firstname'); echo $this-&gt;Form-&gt;input('lastname'); echo $this-&gt;Form-&gt;input('keywords'); echo $this-&gt;Form-&gt;create('Post', array( 'type' =&gt; 'file')); echo $this-&gt;Form-&gt;input('doc_file',array( 'type' =&gt; 'file')); echo $this-&gt;Form-&gt;end('Submit') </code></pre> <p>it saves firstname, lastname, keywords, and the name of the file in DB , but the file which i want to save in app/webroot/documents is not saving , can anyone help ? Thanks</p> <blockquote> <p><strong>Update</strong></p> <p>thaJeztah i did as u said but it gives some errors here is controller if i'm not wrong</p> </blockquote> <pre><code>public function add() { if ($this-&gt;request-&gt;is('post')) { $this-&gt;Post-&gt;create(); $filename = WWW_ROOT. DS . 'documents'.DS.$this-&gt;request-&gt;data['Post']['doc_file']['name']; move_uploaded_file($this-&gt;data['posts']['doc_file']['tmp_name'],$filename); if ($this-&gt;Post-&gt;save($this-&gt;request-&gt;data)) { $this-&gt;Session-&gt;setFlash('Your post has been saved.'); $this-&gt;redirect(array('action' =&gt; 'index')); } else { $this-&gt;Session-&gt;setFlash('Unable to add your post.'); } } } </code></pre> <blockquote> <p>and my add.ctp</p> </blockquote> <pre><code> echo $this-&gt;Form-&gt;create('Post', array( 'type' =&gt; 'file')); echo $this-&gt;Form-&gt;input('firstname'); echo $this-&gt;Form-&gt;input('lastname'); echo $this-&gt;Form-&gt;input('keywords'); echo $this-&gt;Form-&gt;input('doc_file',array( 'type' =&gt; 'file')); echo $this-&gt;Form-&gt;end('Submit') </code></pre> <blockquote> <p>and the errors are</p> <p>Notice (8): Array to string conversion [CORE\Cake\Model\Datasource\DboSource.php, line 1005]</p> <p>Database Error Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'field list'</p> <p>SQL Query: INSERT INTO first.posts (firstname, lastname, keywords, doc_file) VALUES ('dfg', 'cbhcfb', 'dfdbd', Array)</p> <p>and Victor i did your version too , it doesnt work too .</p> </blockquote>
16,277,245
4
0
null
2013-04-28 11:05:05.11 UTC
3
2016-05-05 07:33:56.223 UTC
2013-04-30 23:51:05.397 UTC
null
2,328,858
null
2,328,858
null
1
9
cakephp|file-upload|cakephp-2.3
49,701
<p>You seem to be using the wrong 'key' to access the posted data;</p> <pre><code>$this-&gt;data['posts'][.... </code></pre> <p>Should match the 'alias' of you Model; <em>singular</em> and a <em>captial</em> first letter</p> <pre><code>$this-&gt;data['Post'][.... </code></pre> <p>Also, <code>$this-&gt;data</code> is a wrapper for <code>$this-&gt;request-&gt;data</code> for backwards compatibility, so it's better to use this;</p> <pre><code>$this-&gt;request-&gt;data['Post'][... </code></pre> <p>To check the content of the posted data and understand how it's structured, you may debug it using this;</p> <pre><code>debug($this-&gt;request); </code></pre> <p>Just be sure to enable debugging, by setting <code>debug</code> to <code>1</code> or <code>2</code> inside <code>app/Config/core.php</code></p> <h3>Update; duplicate Form tags!</h3> <p>I just noticed you're also creating multiple (nested) forms in your code;</p> <pre><code>echo $this-&gt;Form-&gt;input('keywords'); // This creates ANOTHER form INSIDE the previous one! echo $this-&gt;Form-&gt;create('Post', array( 'type' =&gt; 'file')); echo $this-&gt;Form-&gt;input('doc_file',array( 'type' =&gt; 'file')); </code></pre> <p>Nesting forms will <em>never</em> work, remove that line and add the 'type =&gt; file' to the first <code>Form-&gt;create()</code></p> <h3>Using only the file <em>name</em> for the database</h3> <p>The <em>&quot;Array to string conversion&quot;</em> problem is cause by the fact that you're trying to directly use the data of 'doc_file' for your database. Because this is a file-upload field, 'doc_file' will contain an <em>Array</em> of data ('name', 'tmp_name' etc.).</p> <p>For your <em>database</em>, you only need the 'name' of that array so you need to modify the data before saving it to your database.</p> <p>For <em>example</em> this way;</p> <pre><code>// Initialize filename-variable $filename = null; if ( !empty($this-&gt;request-&gt;data['Post']['doc_file']['tmp_name']) &amp;&amp; is_uploaded_file($this-&gt;request-&gt;data['Post']['doc_file']['tmp_name']) ) { // Strip path information $filename = basename($this-&gt;request-&gt;data['Post']['doc_file']['name']); move_uploaded_file( $this-&gt;data['Post']['doc_file']['tmp_name'], WWW_ROOT . DS . 'documents' . DS . $filename ); } // Set the file-name only to save in the database $this-&gt;data['Post']['doc_file'] = $filename; </code></pre>
410,146
Vector graphics in Javascript?
<p>One of the advantages of Flash/Flex is that you can use vector graphics (SVG), which is nice. I did a bit of searching around and came across this <a href="http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm" rel="noreferrer">Javascript vector graphics library</a>. It's pretty simple stuff but it got me thinking: is there any possibility of using vector graphics files such as SVG with Javascript/HTML or it just can't be done or done reasonably?</p>
410,149
7
1
null
2009-01-04 00:20:40.587 UTC
10
2019-03-02 15:17:40.573 UTC
2009-01-04 00:41:24.82 UTC
cletus
18,393
cletus
18,393
null
1
17
javascript|html|vector-graphics
17,608
<p>I've used <a href="http://raphaeljs.com/" rel="noreferrer">Raphaël Javascript Library</a> and it worked quite well. Currently the library supports Firefox 3.0+, Safari 3.0+, Opera 9.5+ and Internet Explorer 6.0+. </p>
196,754
What does "select((select(s),$|=1)[0])" do in Perl?
<p>I've seen some horrific code written in Perl, but I can't make head nor tail of this one:</p> <pre><code>select((select(s),$|=1)[0]) </code></pre> <p>It's in some networking code that we use to communicate with a server and I assume it's something to do with buffering (since it sets <code>$|</code>).</p> <p>But I can't figure out why there's multiple <code>select</code> calls or the array reference. Can anyone help me out?</p>
196,768
7
1
null
2008-10-13 05:00:53.507 UTC
9
2016-10-30 01:21:17.83 UTC
2016-10-30 01:21:17.83 UTC
brian d foy
14,860
Pax Diablo
14,860
null
1
35
perl|select|buffering
11,633
<p>It's a nasty little idiom for setting autoflush on a filehandle other than STDOUT. </p> <p><code>select()</code> takes the supplied filehandle and (basically) replaces STDOUT with it, and it returns the old filehandle when it's done. </p> <p>So <code>(select($s),$|=1)</code> redirects the filehandle (remember <code>select</code> returns the old one), and sets autoflush (<code>$| = 1</code>). It does this in a list (<code>(...)[0]</code>) and returns the first value (which is the result of the <code>select</code> call - the original STDOUT), and then passes <em>that</em> back into another <code>select</code> to reinstate the original STDOUT filehandle. Phew.</p> <p>But now you understand it (well, maybe ;)), do this instead:</p> <pre><code>use IO::Handle; $fh-&gt;autoflush; </code></pre>
159,744
Converting MS Word Documents to PDF in ASP.NET
<p>Similar questions have been asked, but nothing exactly like mine, so here goes.</p> <p>We have a collection of Microsoft Word documents on an ASP.NET web server with merge fields whose values are filled in as a result of user form submissions. After the field merge, the server must convert the document to PDF and stream it down to the browser. Our first inclination was to use the Visual Studio Tools for Office API; however, we ran into <a href="http://support.microsoft.com/?id=257757" rel="noreferrer">this warning from Microsoft</a>:</p> <blockquote> <p>Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.</p> </blockquote> <p>It looks like the field manipulation can be done using the <a href="http://msdn.microsoft.com/en-us/library/aa982683.aspx" rel="noreferrer">Open XML SDK</a>, but what's the best way to convert Word 2007 documents to PDF without opening Word? The optimal solution would be low-cost, scalable, have a low memory footprint, be easy to deploy, and have a .NET API.</p>
204,306
8
1
null
2008-10-01 21:05:21.317 UTC
12
2012-03-24 11:51:41.657 UTC
null
null
null
glaxaco
2,144
null
1
20
asp.net|pdf|pdf-generation
52,052
<p>It's not exactly Open Source, but Aspose has a couple products which can do that,</p> <p><a href="http://www.aspose.com/categories/file-format-components/aspose.pdf.kit-for-.net-and-java/default.aspx" rel="noreferrer">Aspose.Pdf.Kit</a></p> <blockquote> <p>Aspose.Pdf.Kit is a non-graphical PDF® document manipulation component that enables both .NET and Java developers to manage existing PDF files as well as manage form fields embedded within PDF files. Aspose.Pdf is perfect for creating new PDF files; however, developers often need to edit already existing PDF documents. Aspose.Pdf.Kit allows them to do just that. Aspose.Pdf.Kit allows developers to create powerful applications for merging data directly into PDF documents as well as for updating and managing PDF documents. Aspose.Pdf.Kit is a wonderful product and works great with the rest of our PDF products.</p> </blockquote> <p>and <a href="http://www.aspose.com/categories/file-format-components/aspose.pdf-for-.net-and-java/default.aspx" rel="noreferrer">Aspose.pdf</a></p> <blockquote> <p>Aspose.Pdf is a non-graphical PDF® document reporting component that enables either .NET or Java applications to create PDF documents from scratch without utilizing Adobe Acrobat®. Aspose.Pdf is very affordably priced and offers a wealth of strong features including: compression, tables, graphs, images, hyperlinks, security and custom fonts. Aspose.Pdf supports the creation of PDF files through API, XML templates and XSL-FO files. Aspose.Pdf is very easy to use and is provided with 14 fully featured demos written in both C# and Visual Basic.</p> </blockquote> <p>Check out the <a href="http://www.aspose.com/documentation/file-format-components/aspose.pdf-for-.net-and-java/aspose.pdf-for-.net-api-reference.htm" rel="noreferrer">API</a> and <a href="http://www.aspose.com/demos/aspose.words/default.aspx" rel="noreferrer">demos</a>. You can download a DLL for free to try it out. I've used both before and they work out great.</p> <p>There's also <a href="http://itextsharp.sourceforge.net/" rel="noreferrer">iTextSharp</a> which is a C# port of iText, a Java PDF converter. I've heard some people try it with mixed results. </p>
61,233
The Best Way to shred XML data into SQL Server database columns
<p>What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so:</p> <pre><code>INSERT INTO some_table (column1, column2, column3) SELECT Rows.n.value('(@column1)[1]', 'varchar(20)'), Rows.n.value('(@column2)[1]', 'nvarchar(100)'), Rows.n.value('(@column3)[1]', 'int'), FROM @xml.nodes('//Rows') Rows(n) </code></pre> <p>However I find that this is getting very slow for even moderate size xml data.</p>
4,671,129
8
2
null
2008-09-14 09:39:29.613 UTC
33
2017-07-03 14:17:37.683 UTC
null
null
null
null
5,769
null
1
28
sql-server|xml
72,311
<p>Stumbled across this question whilst having a very similar problem, I'd been running a query processing a 7.5MB XML file (~approx 10,000 nodes) for around 3.5~4 hours before finally giving up.</p> <p>However, after a little more research I found that having typed the XML using a schema and created an XML Index (I'd bulk inserted into a table) the same query completed in ~ 0.04ms.</p> <p>How's that for a performance improvement!</p> <p>Code to create a schema:</p> <pre><code>IF EXISTS ( SELECT * FROM sys.xml_schema_collections where [name] = 'MyXmlSchema') DROP XML SCHEMA COLLECTION [MyXmlSchema] GO DECLARE @MySchema XML SET @MySchema = ( SELECT * FROM OPENROWSET ( BULK 'C:\Path\To\Schema\MySchema.xsd', SINGLE_CLOB ) AS xmlData ) CREATE XML SCHEMA COLLECTION [MyXmlSchema] AS @MySchema GO </code></pre> <p>Code to create the table with a typed XML column:</p> <pre><code>CREATE TABLE [dbo].[XmlFiles] ( [Id] [uniqueidentifier] NOT NULL, -- Data from CV element [Data] xml(CONTENT dbo.[MyXmlSchema]) NOT NULL, CONSTRAINT [PK_XmlFiles] PRIMARY KEY NONCLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] </code></pre> <p>Code to create Index</p> <pre><code>CREATE PRIMARY XML INDEX PXML_Data ON [dbo].[XmlFiles] (Data) </code></pre> <p>There are a few things to bear in mind though. SQL Server's implementation of Schema doesn't support xsd:include. This means that if you have a schema which references other schema, you'll have to copy all of these into a single schema and add that.</p> <p>Also I would get an error:</p> <pre><code>XQuery [dbo.XmlFiles.Data.value()]: Cannot implicitly atomize or apply 'fn:data()' to complex content elements, found type 'xs:anyType' within inferred type 'element({http://www.mynamespace.fake/schemas}:SequenceNumber,xs:anyType) ?'. </code></pre> <p>if I tried to navigate above the node I had selected with the nodes function. E.g.</p> <pre><code>SELECT ,C.value('CVElementId[1]', 'INT') AS [CVElementId] ,C.value('../SequenceNumber[1]', 'INT') AS [Level] FROM [dbo].[XmlFiles] CROSS APPLY [Data].nodes('/CVSet/Level/CVElement') AS T(C) </code></pre> <p>Found that the best way to handle this was to use the OUTER APPLY to in effect perform an "outer join" on the XML.</p> <pre><code>SELECT ,C.value('CVElementId[1]', 'INT') AS [CVElementId] ,B.value('SequenceNumber[1]', 'INT') AS [Level] FROM [dbo].[XmlFiles] CROSS APPLY [Data].nodes('/CVSet/Level') AS T(B) OUTER APPLY B.nodes ('CVElement') AS S(C) </code></pre> <p>Hope that that helps someone as that's pretty much been my day.</p>
590,007
Python or IronPython
<p>How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?</p> <p>Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?</p>
590,782
8
0
null
2009-02-26 10:41:16.173 UTC
5
2009-02-28 21:04:34.037 UTC
2009-02-28 21:04:34.037 UTC
null
5,302
lagerdalek
5,302
null
1
33
python|ironpython|cpython
14,911
<p>There are a number of important differences:</p> <ol> <li>Interoperability with other .NET languages. You can use other .NET libraries from an IronPython application, or use IronPython from a C# application, for example. This interoperability is increasing, with a movement toward greater support for dynamic types in .NET 4.0. For a lot of detail on this, see <a href="http://channel9.msdn.com/pdc2008/TL10/" rel="noreferrer">these</a> <a href="http://channel9.msdn.com/pdc2008/TL16/" rel="noreferrer">two</a> presentations at PDC 2008.</li> <li>Better concurrency/multi-core support, due to lack of a GIL. (Note that the GIL doesn't inhibit threading on a single-core machine---it only limits performance on multi-core machines.)</li> <li>Limited ability to consume Python C extensions. The <a href="http://code.google.com/p/ironclad/" rel="noreferrer">Ironclad</a> project is making significant strides toward improving this---they've nearly gotten <a href="http://numpy.scipy.org/" rel="noreferrer">Numpy</a> working!</li> <li>Less cross-platform support; basically, you've got the CLR and <a href="http://www.mono-project.com/Main_Page" rel="noreferrer">Mono</a>. Mono is impressive, though, and runs on many platforms---and they've got an implementation of Silverlight, called <a href="http://www.mono-project.com/Moonlight" rel="noreferrer">Moonlight</a>.</li> <li>Reports of improved performance, although I have not looked into this carefully.</li> <li>Feature lag: since CPython is the reference Python implementation, it has the "latest and greatest" Python features, whereas IronPython necessarily lags behind. Many people do not find this to be a problem.</li> </ol>
189,031
Set same icon for all my Forms
<p>Is there any way to set the same icon to all my forms without having to change one by one? Something like when you setup <code>GlobalAssemblyInfo</code> for all your projects inside your solution.</p>
189,050
8
1
null
2008-10-09 20:16:56.137 UTC
7
2020-03-03 12:51:18.3 UTC
2014-03-05 08:45:01.56 UTC
Matias
505,893
Matias
4,386
null
1
36
c#|.net|winforms|icons
31,725
<p>One option would be to inherit from a common base-Form that sets the Icon in the constructor (presumably from a resx). Another option might be <a href="http://www.postsharp.org/" rel="noreferrer">PostSharp</a> - it seems like it should be possible to do this (set .Icon) via AOP; not trivial, though. Finally, you could use a simple utility method (perhaps an extension method) to do the same.</p> <p>Best of all, with the first option, you could probably risk a <kbd>Ctrl</kbd>+<kbd>H</kbd> (replace all) from <code>: Form</code> or <code>: System.Windows.Forms.Form</code> to <code>: MyCustomForm</code>.</p>
60,160
How to escape text for regular expression in Java
<p>Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.</p>
60,161
8
0
null
2008-09-12 23:36:36.687 UTC
61
2018-11-28 21:30:48.15 UTC
null
null
null
Matt
2,338
null
1
350
java|regex|escaping
233,133
<p>Since <a href="http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)" rel="noreferrer">Java 1.5, yes</a>:</p> <pre><code>Pattern.quote("$5"); </code></pre>
224,026
Javascript style dot notation for dictionary keys unpythonic?
<p>I've started to use constructs like these:</p> <pre><code>class DictObj(object): def __init__(self): self.d = {} def __getattr__(self, m): return self.d.get(m, None) def __setattr__(self, m, v): super.__setattr__(self, m, v) </code></pre> <p>Update: based on this thread, I've revised the DictObj implementation to:</p> <pre><code>class dotdict(dict): def __getattr__(self, attr): return self.get(attr, None) __setattr__= dict.__setitem__ __delattr__= dict.__delitem__ class AutoEnum(object): def __init__(self): self.counter = 0 self.d = {} def __getattr__(self, c): if c not in self.d: self.d[c] = self.counter self.counter += 1 return self.d[c] </code></pre> <p>where DictObj is a dictionary that can be accessed via dot notation:</p> <pre><code>d = DictObj() d.something = 'one' </code></pre> <p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p> <p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p> <p>AutoEnum is an auto-incrementing Enum, used like this:</p> <pre><code>CMD = AutoEnum() cmds = { "peek": CMD.PEEK, "look": CMD.PEEK, "help": CMD.HELP, "poke": CMD.POKE, "modify": CMD.POKE, } </code></pre> <p>Both are working well for me, but I'm feeling unpythonic about them. </p> <p>Are these in fact bad constructs?</p>
224,722
12
2
null
2008-10-22 00:08:01.41 UTC
16
2019-10-23 02:14:23.973 UTC
2008-10-24 13:17:12.723 UTC
Parand
13,055
Parand
13,055
null
1
25
python|coding-style
9,411
<p>This is a simpler version of your DictObj class:</p> <pre><code>class DictObj(object): def __getattr__(self, attr): return self.__dict__.get(attr) &gt;&gt;&gt; d = DictObj() &gt;&gt;&gt; d.something = 'one' &gt;&gt;&gt; print d.something one &gt;&gt;&gt; print d.somethingelse None &gt;&gt;&gt; </code></pre>
441,412
Is there a link to the "latest" jQuery library on Google APIs?
<p>I use the following for a jQuery link in my <code>&lt;script&gt;</code> tags:</p> <pre><code>http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js </code></pre> <p>Is there a link to the "latest" version? Something like the following (which doesn't work):</p> <pre><code>http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js </code></pre> <p>(Obviously not necessarily a great plan to link your code to potentially changing libraries but useful in development.)</p>
441,429
12
14
null
2009-01-14 00:08:57.947 UTC
248
2019-07-23 16:13:57.2 UTC
2016-01-22 20:21:37.543 UTC
null
1,946,501
Nick Pierpoint
4,003
null
1
799
javascript|jquery|google-api
1,022,602
<p><strong>Up until jQuery 1.11.1</strong>, you could use the following URLs to get the latest version of jQuery:</p> <ul> <li><a href="https://code.jquery.com/jquery-latest.min.js" rel="noreferrer">https://code.jquery.com/jquery-latest.min.js</a> - jQuery hosted (minified)</li> <li><a href="https://code.jquery.com/jquery-latest.js" rel="noreferrer">https://code.jquery.com/jquery-latest.js</a> - jQuery hosted (uncompressed)</li> <li><a href="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" rel="noreferrer">https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js</a> - Google hosted (minified)</li> <li><a href="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js" rel="noreferrer">https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js</a> - Google hosted (uncompressed)</li> </ul> <p>For example:</p> <pre><code>&lt;script src="https://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt; </code></pre> <hr> <p>However, since jQuery 1.11.1, both jQuery and Google stopped updating these URL's; they will <em>forever</em> be fixed at 1.11.1. There is no supported alternative URL to use. For an explanation of why this is the case, see this blog post; <a href="http://blog.jquery.com/2014/07/03/dont-use-jquery-latest-js/" rel="noreferrer">Don't use jquery-latest.js</a>.</p> <p>Both hosts support <code>https</code> as well as <code>http</code>, so change the protocol as you see fit (or use a <a href="http://www.paulirish.com/2010/the-protocol-relative-url/" rel="noreferrer">protocol relative URI</a>)</p> <p>See also: <a href="https://developers.google.com/speed/libraries/devguide" rel="noreferrer">https://developers.google.com/speed/libraries/devguide</a></p>
971,249
How to find the cause of a malloc "double free" error?
<p>I'm programming an application in Objective-C and I'm getting this error:</p> <blockquote> <p>MyApp(2121,0xb0185000) malloc: &ast;** error for object 0x1068310: double free<br> *** set a breakpoint in malloc_error_break to debug</p> </blockquote> <p>It is happening when I release an NSAutoreleasePool and I can't figure out what object I'm releasing twice.</p> <p>How do I set his breakpoint?</p> <p>Is there a way to know what is this "object 0x1068310"?</p>
971,616
13
7
null
2009-06-09 16:49:50.4 UTC
43
2017-10-13 05:21:51.907 UTC
2017-10-13 05:21:51.907 UTC
null
1,033,581
null
104,291
null
1
82
iphone|objective-c|memory-management|malloc|autorelease
77,888
<p>You'll find out what the object is when you break in the debugger. Just look up the call stack and you will find where you free it. That will tell you which object it is.</p> <p>The easiest way to set the breakpoint is to:</p> <blockquote> <ol> <li>Go to Run -> Show -> Breakpoints (<kbd>ALT</kbd>-<kbd>Command</kbd>-<kbd>B</kbd>)</li> <li>Scroll to the bottom of the list and add the symbol <code>malloc_error_break</code></li> </ol> </blockquote>