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
7,685,458
Can I use the same keystore file to sign two different applications?
<p>I have to upload a new application, It's just the design that's a little different. Yesterday I generated the keystore file to sign application. Can I use the same?</p>
7,685,529
7
2
null
2011-10-07 09:36:28.85 UTC
17
2020-10-15 13:38:58.507 UTC
2016-12-09 13:48:21.883 UTC
null
4,540,701
null
806,972
null
1
101
android|android-keystore
51,221
<p>You can use that <code>keystore</code> for any number of applications.</p> <p>No need to generate a new keystore.</p>
7,143,788
Try-catch-finally in java
<p>In Java, will the finally block not get executed if we insert a return statement inside the try block of a try-catch-finally ?</p>
7,143,836
8
5
null
2011-08-22 06:20:19.473 UTC
8
2016-11-14 09:30:59.54 UTC
null
null
null
null
904,696
null
1
27
java|try-catch|try-catch-finally
53,587
<p>The only time a <code>finally</code> block will not be executed is when you call <code>exit()</code> before <code>finally</code> is reached. The <code>exit()</code> call will shutdown the JVM, so no subsequent line of code will be run.</p> <p>EDIT: This is not entirely correct. See the comments below for additional information.</p>
13,994,164
SOAPUI Certificate authentication
<p>I am trying to hit a remote web service and check if the service is working. To hit the service I am using SOAPUI client. The first time I tried, I got a 403/Forbidden response. The team developing the remote service provided me with a digital certificate to use to making the request. How should I use this certificate for making the request. I am a fairly new to the concept of using digital certificates in web service authentication as well as to soap ui.</p>
14,001,192
1
0
null
2012-12-21 16:56:16.02 UTC
1
2021-11-22 21:53:11.26 UTC
2017-12-13 07:28:34.597 UTC
null
1,033,581
null
1,639,616
null
1
17
web-services|authentication|encryption|certificate|soapui
123,754
<p>You need to configure soapui for client certificate authentication.</p> <p>There are a number of ways to do this.</p> <ol> <li>You can add an authentication option under the connection details for the project.</li> <li>You can configure the certificates for the request under the ws-auth tab</li> </ol> <p>Have a look at the link below. It gives some basic setup steps to assist with soapui <strike><a href="http://geekswithblogs.net/gvdmaaden/archive/2011/02/24/how-to-configure-soapui-with-client-certificate-authentication.aspx" rel="nofollow noreferrer">SoapUI Configure Client certificate authentication (soapui 3.6)</a></strike> <a href="https://www.soapui.org/docs/functional-testing/sending-https-requests/" rel="nofollow noreferrer">SoapUI Sending requests</a></p>
14,189,254
PGError: Error: column of relation does not exist
<p>I'm trying to change the value of a column "isGroup" to the value "public". </p> <p>I created a migration:</p> <pre><code>Post.connection.execute("update Posts set isgroup='public'") </code></pre> <p>However, I get the following error:</p> <pre class="lang-none prettyprint-override"><code>PGError: ERROR: column "isgroup" of relation "posts" does not exist </code></pre> <p>I had unfortunately ran the column creating migration at the same time as the connection.execute migration. However, the "isGroup" column does exist on Heroku, so it is weird that the column is not showing as appearing.</p> <p>Any advice?</p>
14,189,391
1
2
null
2013-01-07 02:58:45.473 UTC
2
2018-06-15 17:50:06.49 UTC
2018-06-15 17:50:06.49 UTC
null
2,747,593
null
749,798
null
1
28
ruby-on-rails-3|postgresql|heroku|migration
48,540
<p>If you are sure that column <code>isGroup</code> exists, then you should quote it like:</p> <pre><code>UPDATE posts SET "isGroup" = 'public' </code></pre> <p>Note that PostgreSQL by default folds all unquoted named to lowercase.</p> <p>To avoid this confusion and necessity to quote, you might want to rename <code>isGroup</code> to <code>isgroup</code> using <code>ALTER TABLE ... RENAME COLUMN ...</code>.</p>
14,260,126
How python-Levenshtein.ratio is computed
<p>According to the <code>python-Levenshtein.ratio</code> source:</p> <p><a href="https://github.com/miohtama/python-Levenshtein/blob/master/Levenshtein.c#L722" rel="noreferrer">https://github.com/miohtama/python-Levenshtein/blob/master/Levenshtein.c#L722</a></p> <p>it's computed as <code>(lensum - ldist) / lensum</code>. This works for </p> <pre><code># pip install python-Levenshtein import Levenshtein Levenshtein.distance('ab', 'a') # returns 1 Levenshtein.ratio('ab', 'a') # returns 0.666666 </code></pre> <p>However, it seems to break with</p> <pre><code>Levenshtein.distance('ab', 'ac') # returns 1 Levenshtein.ratio('ab', 'ac') # returns 0.5 </code></pre> <p>I feel I must be missing something very simple.. but why not <code>0.75</code>?</p>
14,296,743
4
1
null
2013-01-10 14:26:40.9 UTC
16
2020-02-27 01:10:58.94 UTC
2020-02-27 01:10:58.94 UTC
null
395,857
null
787,842
null
1
40
python|levenshtein-distance
29,114
<p>By looking more carefully at the C code, I found that this apparent contradiction is due to the fact that <code>ratio</code> treats the "replace" edit operation differently than the other operations (i.e. with a cost of 2), whereas <code>distance</code> treats them all the same with a cost of 1.</p> <p>This can be seen in the calls to the internal <code>levenshtein_common</code> function made within <code>ratio_py</code> function:</p> <hr> <p><a href="https://github.com/miohtama/python-Levenshtein/blob/master/Levenshtein.c#L727">https://github.com/miohtama/python-Levenshtein/blob/master/Levenshtein.c#L727</a> </p> <pre><code>static PyObject* ratio_py(PyObject *self, PyObject *args) { size_t lensum; long int ldist; if ((ldist = levenshtein_common(args, "ratio", 1, &amp;lensum)) &lt; 0) //Call return NULL; if (lensum == 0) return PyFloat_FromDouble(1.0); return PyFloat_FromDouble((double)(lensum - ldist)/(lensum)); } </code></pre> <hr> <p>and by <code>distance_py</code> function: </p> <p><a href="https://github.com/miohtama/python-Levenshtein/blob/master/Levenshtein.c#L715">https://github.com/miohtama/python-Levenshtein/blob/master/Levenshtein.c#L715</a> </p> <pre><code>static PyObject* distance_py(PyObject *self, PyObject *args) { size_t lensum; long int ldist; if ((ldist = levenshtein_common(args, "distance", 0, &amp;lensum)) &lt; 0) return NULL; return PyInt_FromLong((long)ldist); } </code></pre> <hr> <p>which ultimately results in different cost arguments being sent to another internal function, <code>lev_edit_distance</code>, which has the following doc snippet:</p> <pre><code>@xcost: If nonzero, the replace operation has weight 2, otherwise all edit operations have equal weights of 1. </code></pre> <p>Code of lev_edit_distance(): </p> <pre><code>/** * lev_edit_distance: * @len1: The length of @string1. * @string1: A sequence of bytes of length @len1, may contain NUL characters. * @len2: The length of @string2. * @string2: A sequence of bytes of length @len2, may contain NUL characters. * @xcost: If nonzero, the replace operation has weight 2, otherwise all * edit operations have equal weights of 1. * * Computes Levenshtein edit distance of two strings. * * Returns: The edit distance. **/ _LEV_STATIC_PY size_t lev_edit_distance(size_t len1, const lev_byte *string1, size_t len2, const lev_byte *string2, int xcost) { size_t i; </code></pre> <hr> <p><strong>[ANSWER]</strong> </p> <p>So in my example, </p> <p><code>ratio('ab', 'ac')</code> implies a replacement operation (cost of 2), over the total length of the strings (4), hence <code>2/4 = 0.5</code>.</p> <p>That explains the "how", I guess the only remaining aspect would be the "why", but for the moment I'm satisfied with this understanding.</p>
14,098,735
How to remove the default button highlighting in Safari when using jQuery
<p>I have noticed that under Safari on OS X my default jQuery buttons appear to have a blue glow highlight around them. Just checked and the same thing happens on the <a href="http://jqueryui.com/dialog/#modal-message" rel="noreferrer">jQuery UI Demo page</a>.</p> <p><img src="https://i.stack.imgur.com/PpncS.png" alt="Default button highlighting under Safari"></p> <p>Under Firefox on my same machine it looks like this</p> <p><img src="https://i.stack.imgur.com/QzaHe.png" alt="enter image description here"></p> <p>Can anyone tell me what I can do to remove this under Safari? I would still like the default behaviour.</p>
14,098,770
4
2
null
2012-12-31 07:22:46.18 UTC
4
2016-06-21 13:41:06.01 UTC
2012-12-31 07:30:55.967 UTC
null
205,997
null
525,138
null
1
60
css|jquery-ui
71,407
<p>To remove any highlight of inputs that any browser may apply as default action you can always use <code>outline:none</code> for their css. in your case it's a <code>button</code> element. so this should work:</p> <pre><code>button { outline: none; } </code></pre> <p><a href="http://a11yproject.com/posts/never-remove-css-outlines">Although it's not recommended to remove the CSS outline.</a> as it's is bad for accessibility. (Thanks Robin Clowers for mentioning this)</p>
13,988,145
How to unset max-height?
<p>How to I reset the <code>max-height</code> property to its default, if it has been previously set in some CSS rule? This doesn't work:</p> <pre><code>pre { max-height: 250px; } pre.doNotLimitHeight { max-height: auto; // Doesn't work at least in Chrome } </code></pre>
13,988,177
5
0
null
2012-12-21 10:12:21.41 UTC
13
2019-11-21 11:01:00.88 UTC
2019-11-21 11:01:00.88 UTC
null
8,343,610
null
521,257
null
1
201
css
121,267
<p>Reset it to <code>none</code>:</p> <pre><code>pre { max-height: 250px; } pre.doNotLimitHeight { max-height: none; } </code></pre> <p><strong><a href="https://developer.mozilla.org/en-US/docs/CSS/max-height">Reference</a></strong></p>
30,116,430
ReactJS giving error Uncaught TypeError: Super expression must either be null or a function, not undefined
<p>I am using ReactJS.</p> <p>When I run the code below the browser says:</p> <blockquote> <p><strong>Uncaught TypeError: Super expression must either be null or a function, not undefined</strong></p> </blockquote> <p>Any hints at all as to what is wrong would be appreciated.</p> <p>First the line used to compile the code:</p> <pre><code>browserify -t reactify -t babelify examples/temp.jsx -o examples/public/app.js </code></pre> <p>And the code:</p> <pre><code>var React = require('react'); class HelloMessage extends React.Component { render() { return &lt;div&gt;Hello &lt;/div&gt;; } } </code></pre> <p>UPDATE: After burning in hellfire for three days on this problem I found that I was not using the latest version of react.</p> <p><strong>Install globally:</strong></p> <pre><code>sudo npm install -g [email protected] </code></pre> <p><strong>install locally:</strong></p> <pre><code>npm install [email protected] </code></pre> <p><strong>make sure the browser is using the right version too:</strong></p> <pre><code>&lt;script type=&quot;text/javascript&quot; src=&quot;react-0.13.2.js&quot;&gt;&lt;/script&gt; </code></pre> <p>Hope this saves someone else three days of precious life.</p>
30,168,874
44
11
null
2015-05-08 05:29:27.2 UTC
40
2021-09-27 03:17:20.187 UTC
2021-08-26 09:11:26.773 UTC
null
6,904,888
null
627,492
null
1
292
reactjs|ecmascript-6
323,632
<p><strong>Class Names</strong></p> <p>Firstly, if you're certain that you're extending from the correctly named class, e.g. <strong>React.Component</strong>, not React.component or React.createComponent, you may need to upgrade your React version. See answers below for more information on the classes to extend from.</p> <p><strong>Upgrade React</strong></p> <p>React has only supported ES6-style classes since version 0.13.0 (see their official blog post on the support introduction <a href="https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html" rel="noreferrer" title="React v0.13.0 Beta 1 React Blog">here</a>.</p> <p>Before that, when using:</p> <pre><code>class HelloMessage extends React.Component </code></pre> <p>you were attempting to use ES6 keywords (<code>extends</code>) to subclass from a class which wasn't defined using ES6 <code>class</code>. This was likely why you were running into strange behaviour with <code>super</code> definitions etc.</p> <p>So, yes, <strong>TL;DR</strong> - update to React v0.13.x.</p> <p><strong>Circular Dependencies</strong></p> <p>This can also occur if you have circular import structure. One module importing another and the other way around. In this case you just need to refactor your code to avoid it. <a href="https://medium.com/content-uneditable/circular-dependencies-in-javascript-a-k-a-coding-is-not-a-rock-paper-scissors-game-9c2a9eccd4bc#.9nppw7oqv" rel="noreferrer">More info</a></p>
9,276,078
What's the right approach for calling functions after a flask app is run?
<p>I'm a little confused about how to do something that I thought would be quite simple. I have a simple app written using <code>Flask</code>. It looks something like this:</p> <pre><code>from flask import Flask app = Flask(__name__) def _run_on_start(a_string): print "doing something important with %s" % a_string @app.route('/') def root(): return 'hello world' if __name__ == "__main__": if len(sys.argv) &lt; 2: raise Exception("Must provide domain for application execution.") else: DOM = sys.argv[1] _run_on_start("%s" % DOM) app.run(debug=True) </code></pre> <p>What I'm finding is that my terminal is outputting the print statements in <code>_run_on_start</code> but non of the other usual Flask app debug code. If I remove the call before app.run, the output is normal. Further I'm finding the output of <code>_run_on_start</code> to be repeated twice on startup, though I don't know if it's some weird output or the function is actually being called twice.</p> <p>I'm assuming this is not the right way to add a function call before you call <code>app.run</code>. I looked in the Flask docs and found mentions of various decorators one can use, which allow you to execute a function before/after certain requests but I want to execute the call when the app server is run.</p> <p>Further, I realise that if I call this module from another module, i.e., not when <code>__name__ != "__main__"</code> my I won't get my call to <code>_run_on_start</code>. </p> <p>What's the right approach here? In both cases when I'm starting from the CL and from another module?</p>
9,314,134
3
1
null
2012-02-14 11:31:23.517 UTC
9
2019-02-17 16:54:32.427 UTC
null
null
null
null
646,300
null
1
33
python|web-frameworks|flask|werkzeug
25,309
<p>The duplicate output from your function can be explained by the reloader. The first thing it does is start the main function in a new thread so it can monitor the source files and restart the thread when they change. Disable this with the <code>use_reloader=False</code> option.</p> <p>If you want to be able to run your function when starting the server from a different module, wrap it in a function, and call that function from the other module:</p> <pre><code>def run_server(dom): _run_on_start("%s" % dom) app.run(debug=True, use_reloader=False) if __name__ == '__main__': if len(sys.argv) &lt; 2: raise Exception("Must provide domain for application execution.") else: DOM = sys.argv[1] run_server(DOM) </code></pre> <p>The "right approach" depends on what you're actually trying to accomplish here. The built-in server is meant for running your application in a local testing environment before deploying it to a production server, so the problem of starting it from a different module doesn't make much sense on its own.</p>
19,703,753
How to make the @Html.EditorFor Disabled
<p>I have the following inside my asp.net mvc web application :-</p> <pre><code>&lt;div&gt;&lt;span class="f"&gt;Data Center Name&lt;/span&gt; @Html.EditorFor(model =&gt; model.Switch.TMSRack.DataCenter.Name, new { disabled = "disabled" })&lt;/div&gt; </code></pre> <p>but the field will not be disabled ,, can anyone adivce please? THanks</p>
19,703,838
6
2
null
2013-10-31 10:17:50.243 UTC
5
2020-11-06 07:18:50.143 UTC
null
null
null
null
1,146,775
null
1
42
asp.net-mvc|html-helper
93,902
<p><code>@Html.EditorFor()</code> does not have an overload to support htmlAttributes. You could try <code>@Html.TextBoxFor()</code> </p> <pre><code>@Html.TextBoxFor(model =&gt; model.propertyName, new {disabled= "disabled" }) </code></pre> <p>If you are using system key words such as <code>class</code> in htmlAttributes please add <code>@</code> before the attribute name.</p> <p>Ex:</p> <pre><code>@Html.TextBoxFor(model =&gt; model.propertyName, new {@class = "disabledClass" }) </code></pre>
19,643,001
How to route EVERYTHING other than Web API to /index.html
<p>I've been working on an <strong>AngularJS</strong> project, inside of ASP.NET MVC using Web API. It works great except when you try to go directly to an angular routed URL or refresh the page. Rather than monkeying with server config, I thought this would be something I could handle with <strong>MVC's routing engine</strong>.</p> <p>Current WebAPIConfig: </p> <pre><code>public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: new { id = @"^[0-9]+$" } ); config.Routes.MapHttpRoute( name: "ApiWithActionAndName", routeTemplate: "api/{controller}/{action}/{name}", defaults: null, constraints: new { name = @"^[a-z]+$" } ); config.Routes.MapHttpRoute( name: "ApiWithAction", routeTemplate: "api/{controller}/{action}", defaults: new { action = "Get" } ); } } </code></pre> <p>Current RouteConfig:</p> <pre><code>public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute(""); //Allow index.html to load routes.IgnoreRoute("partials/*"); routes.IgnoreRoute("assets/*"); } } </code></pre> <p>Current Global.asax.cs:</p> <pre><code>public class WebApiApplication : HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); var formatters = GlobalConfiguration.Configuration.Formatters; formatters.Remove(formatters.XmlFormatter); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, PreserveReferencesHandling = PreserveReferencesHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, }; } } </code></pre> <p><strong>GOAL:</strong></p> <p>/api/* continues to go to WebAPI, /partials/<em>, and /assets/</em> all go to file system, absolutely anything else gets routed to /index.html, which is my Angular single page app.</p> <p><strong>--EDIT--</strong></p> <p>I seem to have gotten it working. Added this to the <strong>BOTTOM OF</strong> RouteConfig.cs:</p> <pre><code> routes.MapPageRoute("Default", "{*anything}", "~/index.html"); </code></pre> <p>And this change to the root web.config:</p> <pre><code>&lt;system.web&gt; ... &lt;compilation debug="true" targetFramework="4.5.1"&gt; &lt;buildProviders&gt; ... &lt;add extension=".html" type="System.Web.Compilation.PageBuildProvider" /&gt; &lt;!-- Allows for routing everything to ~/index.html --&gt; ... &lt;/buildProviders&gt; &lt;/compilation&gt; ... &lt;/system.web&gt; </code></pre> <p>However, it smells like a hack. Any better way to do this?</p>
19,643,149
6
3
null
2013-10-28 19:03:34.167 UTC
19
2020-06-21 18:11:01.42 UTC
2014-06-17 10:03:49.18 UTC
null
122,005
null
1,187,752
null
1
55
c#|asp.net|asp.net-mvc|asp.net-mvc-4|angularjs
35,972
<p>Use a wildcard segment:</p> <pre><code>routes.MapRoute( name: "Default", url: "{*anything}", defaults: new { controller = "Home", action = "Index" } ); </code></pre>
24,865,501
Chart.js: chart not displayed
<p>I'd like to use <strong><a href="http://www.chartjs.org/" rel="noreferrer">Chart.js</a></strong> to create stunning charts into a webpage.</p> <p>Following the documentation, I wrote the code as follows:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;Chart.js demo&lt;/title&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; var pieData = [ { value: 20, color:"#878BB6" }, { value : 40, color : "#4ACAB4" }, { value : 10, color : "#FF8153" }, { value : 30, color : "#FFEA88" } ]; // Get the context of the canvas element we want to select var countries= document.getElementById("countries").getContext("2d"); new Chart(countries).Pie(pieData); &lt;/script&gt; &lt;h1&gt;Chart.js Sample&lt;/h1&gt; &lt;canvas id="countries" width="600" height="400"&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Which is the reason why the chart doesn't appear?</p>
24,865,688
4
3
null
2014-07-21 12:48:14 UTC
3
2022-09-18 20:50:54.907 UTC
2014-07-21 12:54:27.733 UTC
null
2,274,686
null
2,274,686
null
1
22
javascript|html|html5-canvas
77,101
<p>First, you have to put your script after the canvas declaration. After that, delete the pie options (or define them).</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"/&gt; &lt;title&gt;Chart.js demo&lt;/title&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Chart.js Sample&lt;/h1&gt; &lt;canvas id="countries" width="600" height="400"&gt;&lt;/canvas&gt; &lt;script&gt; var pieData = [ { value: 20, color:"#878BB6" }, { value : 40, color : "#4ACAB4" }, { value : 10, color : "#FF8153" }, { value : 30, color : "#FFEA88" } ]; // Get the context of the canvas element we want to select var countries= document.getElementById("countries").getContext("2d"); new Chart(countries).Pie(pieData); &lt;/script&gt; &lt;/body&gt; </code></pre> <p></p>
45,046,728
Unit testing React click outside component
<p>Using the code from <a href="https://stackoverflow.com/a/42234988/766958">this answer</a> to solve clicking outside of a component:</p> <pre><code>componentDidMount() { document.addEventListener('mousedown', this.handleClickOutside); } componentWillUnmount() { document.removeEventListener('mousedown', this.handleClickOutside); } setWrapperRef(node) { this.wrapperRef = node; } handleClickOutside(event) { if (this.wrapperRef &amp;&amp; !this.wrapperRef.contains(event.target)) { this.props.actions.something() // Eg. closes modal } } </code></pre> <p>I can't figure out how to unit test the unhappy path so the alert isn't run, what i've got so far:</p> <pre><code>it('Handles click outside of component', () =&gt; { props = { actions: { something: jest.fn(), } } const wrapper = mount( &lt;Component {... props} /&gt;, ) expect(props.actions.something.mock.calls.length).toBe(0) // Happy path should trigger mock wrapper.instance().handleClick({ target: 'outside', }) expect(props.actions.something.mock.calls.length).toBe(1) //true // Unhappy path should not trigger mock here ??? expect(props.actions.something.mock.calls.length).toBe(1) }) </code></pre> <p>I've tried:</p> <ul> <li>sending through <code>wrapper.html()</code></li> <li><code>.find</code>ing a node and sending through (doesn't mock a <code>event.target</code>)</li> <li><code>.simulate</code>ing <code>click</code> on an element inside (doesn't trigger event listener)</li> </ul> <p>I'm sure i'm missing something small but I couldn't find an example of this anywhere.</p>
45,201,372
5
2
null
2017-07-12 01:12:15.2 UTC
5
2020-04-29 00:49:07.91 UTC
2017-07-12 01:25:02.617 UTC
null
766,958
null
766,958
null
1
30
javascript|unit-testing|reactjs|jestjs|enzyme
24,735
<pre><code>import { mount } from 'enzyme' import React from 'react' import ReactDOM from 'react-dom' it('Should not call action on click inside the component', () =&gt; { const map = {} document.addEventListener = jest.fn((event, cb) =&gt; { map[event] = cb }) const props = { actions: { something: jest.fn(), } } const wrapper = mount(&lt;Component {... props} /&gt;) map.mousedown({ target: ReactDOM.findDOMNode(wrapper.instance()), }) expect(props.actions.something).not.toHaveBeenCalled() }) </code></pre> <p>The solution from <a href="https://github.com/airbnb/enzyme/issues/426" rel="noreferrer">this</a> enzyme issue on github.</p>
1,040,479
Documenting C++/CLI library code for use from c# - best tools and practices?
<p>I'm working on a project where a c++/cli library is being used primarily from a c# application.</p> <p>Is there any way to make the code comments in c++/cli visible to c# intellisence within visual studio?</p> <p>Assuming there isn't, what would be the best way to document the c++/cli code to enable its easier use from c# (and within c++/cli of course)? What is you opinion on XML comments vs doxygen vs other tools (which)?</p>
1,071,967
5
0
null
2009-06-24 19:34:24.22 UTC
11
2019-03-24 17:27:04.08 UTC
2010-04-16 20:33:52.023 UTC
null
1,288
null
45,875
null
1
51
documentation|c++-cli|doxygen|documentation-generation
12,209
<p>I have gotten it to work as follows:</p> <ol> <li><p>Use XML style comments for your C++/CLI header entries. This means the full XML comment is required (triple-slash comments, <code>&lt;summary&gt;</code> tag at a minimum)</p></li> <li><p>Make sure that the C++ compiler option <a href="http://msdn.microsoft.com/en-us/library/ms177226.aspx" rel="noreferrer">Generate XML Documentation Files</a> is on. This should generate an XML file with documentation with the same name as your assembly (MyDll.xml).</p></li> <li><p>Make sure that the C# project references your assembly MyDll.dll where MyDll.xml is also present in the same folder. When you mouse over a reference from the assembly, MS Visual Studio will load the documentation. </p></li> </ol> <p>This worked for me in Visual Studio 2008 on an assembly built for .NET 3.5.</p>
1,228,701
Code for decoding/encoding a modified base64 URL (in ASP.NET Framework)
<p>I want to base64 encode data to put it in a URL and then decode it within my HttpHandler.</p> <p>I have found that <a href="http://en.wikipedia.org/wiki/Base64" rel="noreferrer">Base64 Encoding</a> allows for a '/' character which will mess up my UriTemplate matching. Then I found that there is a concept of a "modified Base64 for URL" from wikipedia:</p> <p>A modified Base64 for URL variant exists, where no padding '=' will be used, and the '+' and '/' characters of standard Base64 are respectively replaced by '-' and '_', so that using URL encoders/decoders is no longer necessary and has no impact on the length of the encoded value, leaving the same encoded form intact for use in relational databases, web forms, and object identifiers in general.</p> <p>Using .NET I want to modify my current code from doing basic base64 encoding and decoding to using the "modified base64 for URL" method. Has anyone done this?</p> <p>To decode, I know it starts out with something like:</p> <pre><code>string base64EncodedText = base64UrlEncodedText.Replace('-', '+').Replace('_', '/'); // Append '=' char(s) if necessary - how best to do this? // My normal base64 decoding now uses encodedText </code></pre> <p>But, I need to potentially add one or two '=' chars to the end which looks a little more complex.</p> <p>My encoding logic should be a little simpler:</p> <pre><code>// Perform normal base64 encoding byte[] encodedBytes = Encoding.UTF8.GetBytes(unencodedText); string base64EncodedText = Convert.ToBase64String(encodedBytes); // Apply URL variant string base64UrlEncodedText = base64EncodedText.Replace("=", String.Empty).Replace('+', '-').Replace('/', '_'); </code></pre> <p>I have seen the <a href="https://stackoverflow.com/questions/1032376/guid-to-base64-for-url">Guid to Base64 for URL</a> StackOverflow entry, but that has a known length and therefore they can hardcode the number of equal signs needed at the end.</p>
1,228,744
5
0
null
2009-08-04 16:58:54.083 UTC
43
2022-02-18 14:41:32.187 UTC
2022-02-18 14:41:32.187 UTC
null
67,593
null
74,276
null
1
121
c#|url|base64|encode|decode
102,310
<p>This ought to pad it out correctly:-</p> <pre><code> base64 = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '='); </code></pre>
233,455
Webcam usage in C#
<p>I am making a program in C# to connect to a webcam and do some image manipulation with it.</p> <p>I have a working application that uses win32 api (avicap32.dll) to connect to the webcam and send messages to it that sends it to the clipboard. The problem is that, while accessible from paint, reading it from the program results in null pointers.</p> <p>This is the code I use to connect the webcam:</p> <pre><code>mCapHwnd = capCreateCaptureWindowA(&quot;WebCap&quot;, 0, 0, 0, 320, 240, 1024, 0); SendMessage(mCapHwnd, WM_CAP_CONNECT, 0, 0); SendMessage(mCapHwnd, WM_CAP_SET_PREVIEW, 0, 0); </code></pre> <p>And this is what I use to copy the image to the clipboard:</p> <pre><code>SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0); SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0); tempObj = Clipboard.GetDataObject(); tempImg = (System.Drawing.Bitmap)tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap); </code></pre> <p>There's some error checking which I have removed from the code to make it shorter.</p>
234,423
6
0
null
2008-10-24 13:06:04.93 UTC
15
2022-06-03 03:28:16.47 UTC
2022-06-03 03:28:16.47 UTC
null
19,123,103
null
31,151
null
1
22
c#|clipboard|webcam
39,479
<p>I've recently started doing some hobby work in this area.</p> <p>We settled on using the <a href="http://sourceforge.net/projects/opencv/" rel="noreferrer">OpenCV</a> library with the <a href="http://code.google.com/p/opencvdotnet/" rel="noreferrer">opencvdotnet</a> wrapper. It supports capturing frames from a webcam:</p> <pre><code>using (var cv = new OpenCVDotNet.CVCapture(0)) { var image = cv.CreateCompatibleImage(); // ... cv.Release(); } </code></pre> <p>And if you're doing image manipulation, OpenCV's image processing algorithms have been wrapped within the OpenCVDotNet.Algs assembly.</p> <p>If you decide to go this route be sure to install OpenCV version 1.0 (and install it to "c:\program files\opencv" if you are on Vista 64-bit, or "mklink OpenCV 'c:\program files (x86)\OpenCV`" from the correct directory or else opencvdotnet will not install).</p>
544,791
Django + PostgreSQL: How to reset primary key?
<p>I have been working on an application in Django. To begin with, for simplicity, I had been using sqlite3 for the database.</p> <p>However, once I moved to PostgreSQL, I've run into a bit of a problem: the primary key does not reset once I clear out a table.</p> <p>This app is a game that is played over a long time period (weeks). As such, every time a new game starts, all of the data is cleared out of the database and then new, randomized data is added.</p> <p>I'd like to be able to "start over" with primary keys starting at <code>1</code> each time I clean/rebuild the game. </p> <p>The code still works as-is, but integers are a pretty natural way for describing the objects in my game. I'd like to have each new game start at 1 rather than wherever the last game left off.</p> <p>How can I reset the primary key counter in PostgreSQL? Keep in mind that I don't need to preserve the data in the table since I am wiping it out anyway.</p>
545,008
6
2
null
2009-02-13 05:00:33.74 UTC
13
2021-02-01 08:56:51.833 UTC
2016-09-16 19:02:17.627 UTC
null
4,370,109
TM
12,983
null
1
31
django|database|postgresql|primary-key
15,604
<p>In your app directory try this:</p> <pre><code>python manage.py help sqlsequencereset </code></pre> <p>Pipe it into psql like this to actually run the reset:</p> <pre><code>python manage.py sqlsequencereset myapp1 myapp2 | psql </code></pre> <p>Edit: here's an example of the output from this command on one of my tables:</p> <pre><code>BEGIN; SELECT setval('"project_row_id_seq"', coalesce(max("id"), 1), max("id") IS NOT null) FROM "project_row"; COMMIT; </code></pre>
568,929
What are the url parameters naming convention or standards to follow
<p>Are there any naming conventions or standards for Url parameters to be followed. I generally use camel casing like <code>userId</code> or <code>itemNumber</code>. As I am about to start off a new project, I was searching whether there is anything for this, and could not find anything. I am not looking at this from a perspective of language or framework but more as a general web standard.</p>
568,999
6
1
null
2009-02-20 09:43:42.12 UTC
10
2019-05-29 10:51:22.51 UTC
2019-05-29 10:51:22.51 UTC
null
4,922,375
Dinesh Manne
50,853
null
1
50
coding-style|web-standards
46,983
<p>I recommend reading <a href="http://www.w3.org/Provider/Style/URI" rel="noreferrer">Cool URI's Don't Change</a> by Tim Berners-Lee for an insight into this question. If you're using parameters in your URI, it might be better to rewrite them to reflect what the data actually means.</p> <p>So instead of having the following:</p> <pre><code>/index.jsp?isbn=1234567890 /author-details.jsp?isbn=1234567890 /related.jsp?isbn=1234567890 </code></pre> <p>You'd have</p> <pre><code>/isbn/1234567890/index /isbn/1234567890/author-details /isbn/1234567890/related </code></pre> <p>It creates a more obvious data structure, and means that if you change the platform architecture, your URI's don't change. Without the above structure, </p> <pre><code>/index.jsp?isbn=1234567890 </code></pre> <p>becomes</p> <pre><code>/index.aspx?isbn=1234567890 </code></pre> <p>which means all the links on your site are now broken.</p> <p>In general, you should only use query strings when the user could reasonably expect the data they're retrieving to be generated, e.g. with a search. If you're using a query string to retrieve an unchanging resource from a database, then use URL-rewriting.</p>
442,862
How can I protect MySQL username and password from decompiling?
<p>Java <code>.class</code> files can be decompiled fairly easily. How can I protect my database if I have to use the login data in the code?</p>
442,872
6
7
null
2009-01-14 13:04:39.907 UTC
42
2017-10-19 11:48:02.71 UTC
2012-06-29 20:50:46.133 UTC
William Brendel
834,176
Midday
54,988
null
1
89
java|mysql|security|reverse-engineering|decompiling
48,390
<p>Never hard-code passwords into your code. This was brought up recently in the <a href="http://blog.codinghorror.com/top-25-most-dangerous-programming-mistakes/" rel="noreferrer">Top 25 Most Dangerous Programming Mistakes</a>:</p> <blockquote> <p>Hard-coding a secret account and password into your software is extremely convenient -- for skilled reverse engineers. If the password is the same across all your software, then every customer becomes vulnerable when that password inevitably becomes known. And because it's hard-coded, it's a huge pain to fix.</p> </blockquote> <p>You should store configuration information, including passwords, in a separate file that the application reads when it starts. That is the only real way to prevent the password from leaking as a result of decompilation (never compile it into the binary to begin with).</p> <p>For more information about this common mistake, you can read the <a href="http://cwe.mitre.org/data/definitions/259.html" rel="noreferrer">CWE-259 article</a>. The article contains a more thorough definition, examples, and lots of other information about the problem.</p> <p>In Java, one of the easiest ways to do this is to use the Preferences class. It is designed to store all sorts of program settings, some of which could include a username and password.</p> <pre><code>import java.util.prefs.Preferences; public class DemoApplication { Preferences preferences = Preferences.userNodeForPackage(DemoApplication.class); public void setCredentials(String username, String password) { preferences.put("db_username", username); preferences.put("db_password", password); } public String getUsername() { return preferences.get("db_username", null); } public String getPassword() { return preferences.get("db_password", null); } // your code here } </code></pre> <p>In the above code, you could call the <code>setCredentials</code> method after showing a dialog askign for the username and password. When you need to connect to the database, you can just use the <code>getUsername</code> and <code>getPassword</code> methods to retrieve the stored values. The login credentials will not be hard-coded into your binaries, so decompilation will not pose a security risk.</p> <p><strong>Important Note:</strong> The preference files are just plain text XML files. Make sure you take appropriate steps to prevent unauthorized users from viewing the raw files (UNIX permissions, Windows permissions, et cetera). In Linux, at least, this isn't a problem, because calling <code>Preferences.userNodeForPackage</code> will create the XML file in the current user's home directory, which is non-readable by other users anyway. In Windows, the situation might be different.</p> <p><strong>More Important Notes:</strong> There has been a lot of discussion in the comments of this answer and others about what the correct architecture is for this situation. The original question doesn't really mention the context in which the application is being used, so I will talk about the two situations I can think of. The first is the case in which the person using the program already knows (and is authorized to know) the database credentials. The second is the case in which you, the developer, are trying to keep the database credentials secret from the person using the program.</p> <p><strong>First Case: User is authorized to know the database login credentials</strong></p> <p>In this case, the solution I mentioned above will work. The Java <code>Preference</code> class will stored the username and password in plain text, but the preferences file will only be readable by the authorized user. The user can simply open the preferences XML file and read the login credentials, but that is not a security risk because the user knew the credentials to begin with.</p> <p><strong>Second Case: Trying to hide login credentials from the user</strong></p> <p>This is the more complicated case: the user should not know the login credentials but still needs access to the database. In this case, the user running the application has direct access to the database, which means the program needs to know the login credentials ahead of time. The solution I mentioned above is not appropriate for this case. You can store the database login credentials in a preferences file, but he user will be able to read that file, since they will be the owner. In fact, there is really no good way to use this case in a secure way.</p> <p><strong>Correct Case: Using a multi-tier architecture</strong></p> <p>The correct way to do it is to have a middle layer, in between your database server and your client application, that authenticates individual users and allows a limited set of operations to be performed. Each user would have their own login credentials, but not for the database server. The credentials would allow access to the middle layer (the business logic tier) and would be different for each user.</p> <p>Every user would have their own username and password, which could be stored locally in a preferences file without any security risk. This is called a <a href="http://en.wikipedia.org/wiki/Three-tier_(computing)" rel="noreferrer">three-tier architecture</a> (the tiers being your database server, business logic server, and client application). It is more complex, but it really is the most secure way to do this sort of thing.</p> <p>The basic order of operations is:</p> <ol> <li>Client authenticates with business logic tier using the user's personal username/password. The username and password are known to the user and are not related to the database login credentials in any way.</li> <li>If authentication succeeds, the client makes a request to the business logic tier asking for some information from the database. For example, an inventory of products. Note that the client's request is not a SQL query; it is a remote procedure call such as <code>getInventoryList</code>.</li> <li>The business logic tier connects to the database and retrieves the requested information. The business logic tier is in charge of forming a secure SQL query based on the user's request. Any parameters to the SQL query should be sanitized to prevent SQL injection attacks.</li> <li>The business logic tier sends the inventory list back to the client application.</li> <li>The client displays the inventory list to the user.</li> </ol> <p>Note that in the entire process, <strong>the client application never connects directly to the database</strong>. The business logic tier receives a request from an authenticated user, processes the client's request for an inventory list, and only then executes a SQL query.</p>
32,163,436
Python Decorator for printing every line executed by a function
<p>I want to, for debugging purposes, print out something pertaining to each and every line executed in a python method. </p> <p>For example if there was some assignment in the line, i want to print what value was assigned for that variable, and if there was a function call, i want to print out the value returned by the function, etc.</p> <p>So, for example if i were to use a decorator, applied on function/method such as :</p> <pre><code>@some_decorator def testing() : a = 10 b = 20 c = a + b e = test_function() </code></pre> <p>the function testing when called, should print the following : </p> <pre><code>a = 10 b = 20 c = 30 e = some_value </code></pre> <p>Is there some way to achieve this? More fundamentally, i want to know whether i can write a code that can go through some other code line by line, check what type of an instruction it is, etc. Or maybe like we can get a dictionary for finding out all the variables in a class, can i get a dictionary like datastructure for getting every instruction in a function, which is as good a metaprogram can get.</p> <p>Hence, I am particularly looking a solution using decorators, as I am curious if one can have a decorator that can go through an entire function line by line, and decorate it line by line, but any and all solutions are welcome. </p> <p>Thanks in advance.</p>
32,261,446
1
8
null
2015-08-23 05:19:30.493 UTC
16
2015-09-03 21:14:52.833 UTC
2015-08-23 05:26:41.15 UTC
null
4,054,472
null
4,054,472
null
1
16
python|debugging|decorator|python-decorators
3,486
<p>How about something like this? Would this work for you?</p> <p>Debug Context:</p> <pre><code>import sys class debug_context(): """ Debug context to trace any function calls inside the context """ def __init__(self, name): self.name = name def __enter__(self): print('Entering Debug Decorated func') # Set the trace function to the trace_calls function # So all events are now traced sys.settrace(self.trace_calls) def __exit__(self, *args, **kwargs): # Stop tracing all events sys.settrace = None def trace_calls(self, frame, event, arg): # We want to only trace our call to the decorated function if event != 'call': return elif frame.f_code.co_name != self.name: return # return the trace function to use when you go into that # function call return self.trace_lines def trace_lines(self, frame, event, arg): # If you want to print local variables each line # keep the check for the event 'line' # If you want to print local variables only on return # check only for the 'return' event if event not in ['line', 'return']: return co = frame.f_code func_name = co.co_name line_no = frame.f_lineno filename = co.co_filename local_vars = frame.f_locals print (' {0} {1} {2} locals: {3}'.format(func_name, event, line_no, local_vars)) </code></pre> <p>Debug Decorator:</p> <pre><code>def debug_decorator(func): """ Debug decorator to call the function within the debug context """ def decorated_func(*args, **kwargs): with debug_context(func.__name__): return_value = func(*args, **kwargs) return return_value return decorated_func </code></pre> <p>Usage</p> <pre><code>@debug_decorator def testing() : a = 10 b = 20 c = a + b testing() </code></pre> <p>Output</p> <pre><code>########################################################### #output: # Entering Debug Decorated func # testing line 44 locals: {} # testing line 45 locals: {'a': 10} # testing line 46 locals: {'a': 10, 'b': 20} # testing return 46 locals: {'a': 10, 'b': 20, 'c': 30} ########################################################### </code></pre>
21,081,598
Import Google Play Services library in Android Studio
<p>I have an Android project that has been developed entirely within Android Studio (currently version 4.2, gradle version 1.9-all). I want to add functionality from Google Play Services.</p> <p>The project is unable to resolve <code>GooglePlayServicesUtil</code>, and when I enter the import manually (shown below), I get <code>Cannot resolve symbol 'common'</code>.</p> <pre><code>import com.google.android.gms.common.GooglePlayServicesUtil; </code></pre> <p>Any idea what I need to do to get <code>GooglePlayServicesUtil</code> to resolve?</p> <h2>What I've Tried</h2> <p>From the <a href="http://developer.android.com/google/play-services/setup.html" rel="noreferrer">Google Play Services Setup</a> it looks like I just have to add the <code>com.google.android.gms:play-services:4.+</code> dependency to my <code>build.gradle</code> file (and resync project files with gradle) to make the SDK available to my project. I do get an &quot;exploded bundle&quot; in <code>ProjectName/module/build/exploded-bundles</code>, but that doesn't seem like it does the trick.</p> <p>I have Google Play Services, Android Support Repository and Google Repository installed from the SDK Manager already. I've also deleted and reinstalled them multiple times :)</p> <p>Edit:</p> <p>Might I need to manually add google_play_services as a Project/Global Library? I've attempted with no success.</p> <p>I'm trying to verify that I'm developing against the Platform API with Google Services (if that's even possible), but I'm not sure that's the case. Nothing I change seems to do anything.</p> <p>The External Libraries of my project shows:</p> <ul> <li>&lt; Android API 19 Platform &gt;</li> <li>&lt; 1.7 &gt;</li> <li>joda-time-2.3</li> <li>support-v4-13.0.0</li> </ul> <h2>Source Code</h2> <p>This is my ProjectName/module/build.gradle file:</p> <pre><code>buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.7.+' } } apply plugin: 'android' repositories { mavenCentral() } android { compileSdkVersion 19 buildToolsVersion '19.0.1' defaultConfig { minSdkVersion 17 targetSdkVersion 19 versionCode 1 versionName &quot;1.0&quot; } buildTypes { release { runProguard true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } signingConfigs { } productFlavors { } } dependencies { compile 'com.google.android.gms:play-services:4.+' compile 'joda-time:joda-time:2.3@jar' } </code></pre> <p>The <code>com.google.android.gms.version</code> number resolves fine in my manifest. Here is my ProjectName/module/src/main/AndroidManifest.xml file:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;com.example.android&quot; &gt; &lt;uses-sdk android:minSdkVersion=&quot;17&quot; android:targetSdkVersion=&quot;19&quot;/&gt; &lt;application android:allowBackup=&quot;true&quot; android:icon=&quot;@drawable/ic_launcher&quot; android:label=&quot;@string/app_name&quot; android:theme=&quot;@style/AppTheme&quot; &gt; &lt;activity android:name=&quot;com.example.android.MainActivity&quot; android:label=&quot;@string/app_name&quot; &gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt; &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=&quot;.SecondActivity&quot;/&gt; &lt;meta-data android:name=&quot;com.google.android.gms.version&quot; android:value=&quot;@integer/google_play_services_version&quot; /&gt; &lt;provider android:name=&quot;.DataProvider&quot; android:authorities=&quot;com.example.android.provider&quot; &gt; &lt;/provider&gt; &lt;receiver android:name=&quot;.WidgetProvider&quot; &gt; &lt;intent-filter&gt; &lt;action android:name=&quot;android.appwidget.action.APPWIDGET_UPDATE&quot; /&gt; &lt;/intent-filter&gt; &lt;meta-data android:name=&quot;android.appwidget.provider&quot; android:resource=&quot;@xml/widget_info&quot; /&gt; &lt;/receiver&gt; &lt;service android:name=&quot;.DatabaseService&quot; /&gt; &lt;service android:name=&quot;.WidgetProvider$UpdateService&quot; /&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>Here is my MainActivity, where I'm trying to check whether GooglePlayServices is Available:</p> <pre><code>package com.example.android; import android.app.Activity; import android.os.Bundle; import android.util.Log; import com.google.android.gms.common.GooglePlayServicesUtil; public class MainActivity extends Activity { private static final String TAG = &quot;MainActivity&quot;; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onResume() { Log.i(TAG, &quot;onResume&quot;); GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); } } </code></pre>
21,086,904
7
4
null
2014-01-12 23:19:57.807 UTC
7
2017-05-18 09:28:15.317 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
697,231
null
1
51
java|android|gradle|android-studio|google-play-services
142,787
<p>Try this once and make sure you are not getting any error in project Structure saying that "ComGoogleAndroidGmsPlay not added"</p> <p>Open <code>File &gt; Project Structure</code> and check for below all. If error is shown click on Red bulb marked and click on "Add to dependency".</p> <p><img src="https://i.stack.imgur.com/xIZj1.jpg" alt="GMS dependency"></p> <p>This is a bug in Android Studio and fixed for the next release(0.4.3)</p>
54,605,286
What is destructuring assignment and its uses?
<p>I have been reading about <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">Destructuring assignment</a> introduced in ES6.</p> <p>What is the purpose of this syntax, why was it introduced, and what are some examples of how it might be used in practice?</p>
54,605,288
3
5
null
2019-02-09 10:20:40.697 UTC
15
2021-02-17 21:37:21.067 UTC
2020-01-23 09:36:05.29 UTC
null
5,648,954
null
9,624,435
null
1
16
javascript|ecmascript-6|destructuring|object-destructuring
4,946
<blockquote> <p><em><strong>What is destructuring assignment ?</strong></em></p> </blockquote> <p><em>The <strong>destructuring assignment</strong> syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.</em></p> <p>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">MDN</a></p> <blockquote> <p><em><strong>Advantages</strong></em></p> </blockquote> <p><strong>A.</strong> Makes code concise and more readable.</p> <p><strong>B.</strong> We can easily avoid repeated destructing expression.</p> <blockquote> <p><em><strong>Some use cases</strong></em></p> </blockquote> <p><em><strong>1. To get values in variable from Objects,array</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = { 'a': 1,'b': {'b1': '1.1'}} let {a,b,b:{b1}} = obj console.log('a--&gt; ' + a, '\nb--&gt; ', b, '\nb1---&gt; ', b1) let obj2 = { foo: 'foo' }; let { foo: newVarName } = obj2; console.log(newVarName); let arr = [1, 2, 3, 4, 5] let [first, second, ...rest] = arr console.log(first, '\n', second, '\n', rest) // Nested extraction is possible too: let obj3 = { foo: { bar: 'bar' } }; let { foo: { bar } } = obj3; console.log(bar);</code></pre> </div> </div> </p> <p><em><strong>2. To combine an array at any place with another array.</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = [2,3,4,5] let newArr = [0,1,...arr,6,7] console.log(newArr)</code></pre> </div> </div> </p> <p><em><strong>3. To change only desired property in an object</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}] let op = arr.map( ( {a,...rest}, index) =&gt; ({...rest,a:index+10})) console.log(op)</code></pre> </div> </div> </p> <p><em><strong>4. To create a shallow copy of objects</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {a:1,b:2,c:3} let newObj = {...obj} newObj.a = 'new Obj a' console.log('Original Object', obj) console.log('Shallow copied Object', newObj)</code></pre> </div> </div> </p> <p><em><strong>5. To extract values from parameters into standalone variables</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Object destructuring: const fn = ({ prop }) =&gt; { console.log(prop); }; fn({ prop: 'foo' }); console.log('------------------'); // Array destructuring: const fn2 = ([item1, item2]) =&gt; { console.log(item1); console.log(item2); }; fn2(['bar', 'baz']); console.log('------------------'); // Assigning default values to destructured properties: const fn3 = ({ foo="defaultFooVal", bar }) =&gt; { console.log(foo, bar); }; fn3({ bar: 'bar' });</code></pre> </div> </div> </p> <p><em><strong>6. To get dynamic keys value from object</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {a:1,b:2,c:3} let key = 'c' let {[key]:value} = obj console.log(value)</code></pre> </div> </div> </p> <p><em><strong>7. To build an object from other object with some default values</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let obj = {a:1,b:2,c:3} let newObj = (({d=4,...rest} = obj), {d,...rest}) console.log(newObj)</code></pre> </div> </div> </p> <p><em><strong>8. To swap values</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const b = [1, 2, 3, 4]; [b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2 console.log(b);</code></pre> </div> </div> </p> <p><em><strong>9. To get a subset of an object</strong></em></p> <ul> <li><p>9.1 <a href="https://stackoverflow.com/questions/17781472/how-to-get-a-subset-of-a-javascript-objects-properties/39333479">subset of an object</a>:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = {a:1, b:2, c:3}, subset = (({a, c}) =&gt; ({a, c}))(obj); // credit to Ivan N for this function console.log(subset);</code></pre> </div> </div> </p> </li> <li><p>9.2 To get a <a href="https://stackoverflow.com/a/54613019/9624435">subset of an object using comma operator and destructuring</a>:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const object = { a: 5, b: 6, c: 7 }; const picked = ({a,c}=object, {a,c}) console.log(picked); // { a: 5, c: 7 }</code></pre> </div> </div> </p> </li> </ul> <p><em><strong>10. To do array to object conversion:</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = ["2019", "09", "02"], date = (([year, day, month]) =&gt; ({year, month, day}))(arr); console.log(date);</code></pre> </div> </div> </p> <p><em><strong>11. <a href="https://stackoverflow.com/a/54616597/9624435">To set default values in function.</a> (Read this answer for more info )</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function someName(element, input,settings={i:"#1d252c", i2:"#fff",...input}){ console.log(settings.i) console.log(settings.i2) } someName('hello', {i:'#123'}) someName('hello', {i2:'#123'})</code></pre> </div> </div> </p> <p><em><strong>12. To get properties such as <code>length</code> from an array, function name, number of arguments etc.</strong></em></p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = [1,2,3,4,5]; let {length} = arr; console.log(length); let func = function dummyFunc(a,b,c) { return 'A B and C'; } let {name, length:funcLen} = func; console.log(name, funcLen);</code></pre> </div> </div> </p>
33,260,093
Node JS and Webpack Unexpected token <
<p>I've started studing <em>Node JS</em>.</p> <p>So here is my files.</p> <p><strong><em>index.html</em></strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="app"&gt; &lt;h1&gt;Hello&lt;h1&gt; &lt;/div&gt; &lt;script src='assets/bundle.js'&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong><em>app.js</em></strong></p> <pre><code>var http = require("http"), path = require('path') fs = require("fs"), colors = require('colors'), port = 3000; var Server = http.createServer(function(request, response) { var filename = path.join(__dirname, 'index.html'); fs.readFile(filename, function(err, file) { if(err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); return; } response.writeHead(200); response.write(file); response.end(); }); }); Server.listen(port, function() { console.log(('Server is running on http://localhost:'+ port + '...').cyan); </code></pre> <p><strong><em>webpack.config.js</em></strong></p> <pre><code>module.exports = { entry: './src/index.js', output: { path: __dirname + '/assets', filename: 'bundle.js' } } </code></pre> <p><strong><em>UPDATE</em></strong> <strong><em>bundle.js</em></strong></p> <pre><code>/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports) { alert('Hello'); /***/ } /******/ ]); </code></pre> <p>So, when i hit a <em>app.js</em> and visit the address (localhost:3000) i get the error in console.</p> <blockquote> <p>bundle.js:1 Uncaught SyntaxError: Unexpected token &lt;</p> </blockquote> <p>Also my JS file doesnt run. Could someone suggest something to fix it?</p> <p>Thanks in advance</p>
33,260,351
5
3
null
2015-10-21 13:02:56.857 UTC
12
2019-04-20 19:57:26.803 UTC
2015-10-21 13:12:39.157 UTC
user5471583
null
user5471583
null
null
1
27
javascript|node.js|webpack
31,837
<p>Your server:</p> <blockquote> <pre><code>var Server = http.createServer(function(request, response) { var filename = path.join(__dirname, 'index.html'); </code></pre> </blockquote> <p>… is configured to ignore everything in the request and always return the contents of <code>index.html</code>.</p> <p>So when the browser requests <code>/assets/bundle.js</code> it is given <code>index.html</code> (and errors because that isn't JavaScript).</p> <p>You need to pay attention to the path and serve up appropriate content, with the appropriate content type. </p> <p>This would probably be best done by finding a static file serving module (Google turns up <a href="https://github.com/cloudhead/node-static" rel="noreferrer">node-static</a>) for Node (or replacing Node with something like Lighttpd or Apache HTTPD). </p> <p>If you want to serve up dynamic content as well as static content, then <a href="http://expressjs.com/" rel="noreferrer">Express</a> is a popular choice (and has <a href="http://expressjs.com/starter/static-files.html" rel="noreferrer">support for static files</a>).</p>
33,119,748
Convert time.Time to string
<p>I'm trying to add some values from my database to a <code>[]string</code> in Go. Some of these are timestamps.</p> <p>I get the error:</p> <blockquote> <p>cannot use U.Created_date (type time.Time) as type string in array element</p> </blockquote> <p>Can I convert <code>time.Time</code> to <code>string</code>?</p> <pre><code>type UsersSession struct { Userid int Timestamp time.Time Created_date time.Time } type Users struct { Name string Email string Country string Created_date time.Time Id int Hash string IP string } </code></pre> <p>-</p> <pre><code>var usersArray = [][]string{} rows, err := db.Query("SELECT u.id, u.hash, u.name, u.email, u.country, u.IP, u.created_date, us.timestamp, us.created_date FROM usersSession AS us LEFT JOIN users AS u ON u.id = us.userid WHERE us.timestamp + interval 30 minute &gt;= now()") U := Users{} US := UsersSession{} for rows.Next() { err = rows.Scan(&amp;U.Id, &amp;U.Hash, &amp;U.Name, &amp;U.Email, &amp;U.Country, &amp;U.IP, &amp;U.Created_date, &amp;US.Timestamp, &amp;US.Created_date) checkErr(err) userid_string := strconv.Itoa(U.Id) user := []string{userid_string, U.Hash, U.Name, U.Email, U.Country, U.IP, U.Created_date, US.Timestamp, US.Created_date} // ------------- // ^ this is where the error occurs // cannot use U.Created_date (type time.Time) as type string in array element (for US.Created_date and US.Timestamp aswell) // ------------- usersArray = append(usersArray, user) log.Print("usersArray: ", usersArray) } </code></pre> <p><strong>EDIT</strong></p> <p>I added the following. It works now, thanks.</p> <pre><code>userCreatedDate := U.Created_date.Format("2006-01-02 15:04:05") userSessionCreatedDate := US.Created_date.Format("2006-01-02 15:04:05") userSessionTimestamp := US.Timestamp.Format("2006-01-02 15:04:05") </code></pre>
33,119,937
6
3
null
2015-10-14 07:57:18.757 UTC
25
2021-01-04 18:05:26.82 UTC
2018-09-04 14:49:53.94 UTC
null
13,860
null
4,273,851
null
1
156
string|time|go
309,924
<p>You can use the <a href="https://golang.org/pkg/time/#Time.String" rel="noreferrer"><code>Time.String()</code></a> method to convert a <a href="https://golang.org/pkg/time/#Time" rel="noreferrer"><code>time.Time</code></a> to a <code>string</code>. This uses the format string <code>&quot;2006-01-02 15:04:05.999999999 -0700 MST&quot;</code>.</p> <p>If you need other custom format, you can use <a href="https://golang.org/pkg/time/#Time.Format" rel="noreferrer"><code>Time.Format()</code></a>. For example to get the timestamp in the format of <code>yyyy-MM-dd HH:mm:ss</code> use the format string <code>&quot;2006-01-02 15:04:05&quot;</code>.</p> <p>Example:</p> <pre><code>t := time.Now() fmt.Println(t.String()) fmt.Println(t.Format(&quot;2006-01-02 15:04:05&quot;)) </code></pre> <p>Output (try it on the <a href="http://play.golang.org/p/VysF0Eu7v8" rel="noreferrer">Go Playground</a>):</p> <pre><code>2009-11-10 23:00:00 +0000 UTC 2009-11-10 23:00:00 </code></pre> <p>Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.</p> <p>Also note that using <code>Time.Format()</code>, as the layout <code>string</code> you always have to pass the same time –called the <em>reference</em> time– formatted in a way you want the result to be formatted. This is documented at <code>Time.Format()</code>:</p> <blockquote> <p>Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be</p> <pre><code>Mon Jan 2 15:04:05 -0700 MST 2006 </code></pre> <p>would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.</p> </blockquote>
33,259,763
UWP Enable local network loopback
<p>I wrote a UWP-App and after generating and installing the .appxbundle, every time I start the App I get a <code>net_http_client_execution_error</code>. The App is starting and running fine, when started in Visual Studio 2015. So there is no chance for me to get the problem, if I debug the app. <br/></p> <p><strong>Update:</strong> <br/> By default Windows restricts apps to reach the localhost (127.0.0.1). I have running a couch database there. This couch database should run there for our costumers as well. Is it possible to allow a App to reach the localhost (enable local network loopback)?</p>
33,263,253
1
5
null
2015-10-21 12:47:56.407 UTC
18
2021-05-11 15:29:03.157 UTC
2019-03-11 13:36:52.943 UTC
null
686,985
null
5,036,353
null
1
30
c#|uwp|win-universal-app
29,739
<p>For a line of business app use the checknetisolation.exe tool to grant the app a loopback exception.</p> <p>To enable loopback use this command:</p> <pre><code>c:\&gt;checknetisolation loopbackexempt -a -n=&lt;package family name&gt; </code></pre> <p>To disable loopback use this command:</p> <pre><code>c:\&gt;checknetisolation loopbackexempt -d -n=&lt;package family name&gt; </code></pre> <p>The package family name for a UWP app can be found in several places: Visual Studio shows it in Package.appxmanifest editor on the packaging tab, PowerShell's get-appxpackage cmdlet displays it, etc. It will look something like "MyPackage_edj12ye0wwgwa"</p> <p>In some cases loopback exemption will work for some time and then stop working. In this case you might need to run the following command to clean/remove all exemptions and then add them back one by one to get back in a good state. (from <a href="https://stackoverflow.com/questions/33259763/uwp-enable-local-network-loopback#comment68457334_33263253">Pawel Sledzikowski's comment</a>)</p> <pre><code>c:\&gt;checknetisolation loopbackexempt -c </code></pre> <p>There is a whitepaper with more details at <a href="https://msdn.microsoft.com/en-us/library/windows/apps/dn640582.aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/windows/apps/dn640582.aspx</a> </p>
1,913,685
How to copy views from one database to another database
<p>I have two databases with same structure in MS SQL server.</p> <p>I'd like to copy all views another database.</p> <p>I tried to use Export data functionality by DTS (that works with the table objects).</p> <p>But that executes the SQL &amp; creates the table object.</p> <p>I don't want to execute that just want to copy the view so that I can open them in design view.</p> <p>I tried to use create new view in destination database &amp; copy SQL query of the view of the source database &amp; save the view. That works works exactly same that I want, But I have number of views &amp; number of copies!</p>
1,913,707
5
0
null
2009-12-16 10:19:00.143 UTC
8
2018-11-27 09:38:09.27 UTC
null
null
null
null
415,865
null
1
25
sql-server|views
80,244
<p>Right click on your database and say Tasks->Generate scripts. SQL Server Management Studio is able to generate the CREATE scripts for you.</p> <p>Then you simple copy this script and execute it on the target server/database.</p>
1,387,354
How Would I Change ASP.NET MVC Views Based on Device Type?
<p>I'm working my way through some ASP.NET MVC reading and I have a web app at work that I'll be migrating from WebForms to MVC. One of the feature requests I expect to get in the process is to have a simplified view returned if the user is coming from a mobile device. </p> <p>I can't quite see where the best place is to implement that type of logic. I'm sure there's a better way than adding an if/else for Browser.IsMobileDevice in every action that returns a view. What kind of options would I have to do this?</p>
1,387,555
5
0
null
2009-09-07 02:40:36.793 UTC
21
2013-04-05 12:33:53.377 UTC
2009-09-07 02:46:21.027 UTC
null
19,626
null
19,626
null
1
27
asp.net-mvc|views|mobile-devices
11,956
<p><strong>Update</strong>: This solution has a subtle bug. The MVC framework will call into <code>FindView</code>/<code>FindPartialView</code> twice: once with <code>useCache=true</code>, and if that doesn't return a result, once with <code>useCache=false</code>. Since there's only one cache for all types of views, mobile users may end up seeing desktop views if a desktop browser was first to arrive.</p> <p>For those interested in using custom view engines to solve this problem, Scott Hanselman has updated his solution here: </p> <p><a href="http://www.hanselman.com/blog/ABetterASPNETMVCMobileDeviceCapabilitiesViewEngine.aspx" rel="noreferrer">http://www.hanselman.com/blog/ABetterASPNETMVCMobileDeviceCapabilitiesViewEngine.aspx</a></p> <p>(Apologies for the answer hijack, I just don't want anyone else to have to go through this!)</p> <p><strong>Edited by roufamatic (2010-11-17)</strong></p> <hr> <p>The first thing you want to do is introduce the <a href="http://mdbf.codeplex.com/" rel="noreferrer">Mobile Device Browser File</a> to your project. Using this file you can target what ever device you want to support without having to know the specifics of what those devices send in their headers. This file has already done the work for you. You then use the Request.Browser property to tailor which view you want to return.</p> <p>Next, come up with a strategy on how you want to organize your views under the Views folder. I prefer to leave the desktop version at the root and then have a Mobile folder. For instance the Home view folder would look like this:</p> <ul> <li>Home <ul> <li>Mobile <ul> <li>iPhone <ul> <li>Index.aspx </li> </ul></li> <li>BlackBerry <ul> <li>Index.aspx </li> </ul></li> </ul></li> <li>Index.aspx</li> </ul></li> </ul> <p>I have to disagree with @Mehrdad about using a custom view engine. The view engine serves more than one purpose and one of those purposes is finding views for the controller. You do this by overriding the FindView method. In this method, you can do your checks on where to find the view. After you know which device is using your site, you can use the strategy you came up with for organizing your views to return the view for that device.</p> <pre><code>public class CustomViewEngine : WebFormViewEngine { public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { // Logic for finding views in your project using your strategy for organizing your views under the Views folder. ViewEngineResult result = null; var request = controllerContext.HttpContext.Request; // iPhone Detection if (request.UserAgent.IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) &gt; 0) { result = base.FindView(controllerContext, "Mobile/iPhone/" + viewName, masterName, useCache); } // Blackberry Detection if (request.UserAgent.IndexOf("BlackBerry", StringComparison.OrdinalIgnoreCase) &gt; 0) { result = base.FindView(controllerContext, "Mobile/BlackBerry/" + viewName, masterName, useCache); } // Default Mobile if (request.Browser.IsMobileDevice) { result = base.FindView(controllerContext, "Mobile/" + viewName, masterName, useCache); } // Desktop if (result == null || result.View == null) { result = base.FindView(controllerContext, viewName, masterName, useCache); } return result; } } </code></pre> <p>The above code allows you set the view based on your strategy. The fall back is the desktop view, if no view was found for the device or if there isn't a default mobile view.</p> <p>If you decide to put the logic in your controller's instead of creating a view engine. The best approach would be to create a custom <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute.aspx" rel="noreferrer">ActionFilterAttribute</a> that you can decorate your controller's with. Then override the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute.onactionexecuted.aspx" rel="noreferrer">OnActionExecuted</a> method to determine which device is viewing your site. You can check this <a href="http://remark.wordpress.com/articles/mobile-asp-net-mvc/" rel="noreferrer">blog post</a> out on how to. The post also has some nice links to some Mix videos on this very subject.</p>
2,088,969
Generating confirmation code for an email confirmation
<p>Using PHP, what are some ways to generate a random confirmation code that can be stored in a DB and be used for email confirmation? I can't for the life of me think of a way to generate a unique number that can be generated from a user's profile. That way I can use a function to make the number small enough to be included in the URL (<a href="http://kevin.vanzonneveld.net/techblog/article/create_short_ids_with_php_like_youtube_or_tinyurl/" rel="noreferrer">see this link</a>). Remember, the user has to click on the link to "confirm/activate" his/her account. If I can't use numbers, I have no problems using both letters and numbers.</p> <p>With that said, I've tried hashing the username along with a "salt" to generate the random code. I know there has to be a better way, so let's hear it. </p>
2,088,983
5
0
null
2010-01-18 20:29:10.517 UTC
33
2019-06-04 10:05:10.337 UTC
2012-06-22 13:01:44.207 UTC
null
250,259
null
166,836
null
1
34
php|email-validation
51,293
<pre><code>$random_hash = md5(uniqid(rand(), true)); </code></pre> <p>That will be 32 alphanumeric characters long and unique. If you want it to be shorter just use substr():</p> <pre><code>$random_hash = substr(md5(uniqid(rand(), true)), 16, 16); // 16 characters long </code></pre> <p>Alternative methods to generate random data include:</p> <pre><code>$random_hash = md5(openssl_random_pseudo_bytes(32)); $random_hash = md5(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)); // New in PHP7 $random_hash = bin2hex(random_bytes(32)); </code></pre>
1,904,049
In F# what does the >> operator mean?
<p>I noticed in some code in this <a href="http://www.navision-blog.de/2009/12/12/christmas-tree-in-fsharp/" rel="noreferrer">sample</a> that contained the >> operator:</p> <pre><code>let printTree = tree &gt;&gt; Seq.iter (Seq.fold (+) "" &gt;&gt; printfn "%s") </code></pre> <p>What does the >> operator mean/do?</p> <p><strong>EDIT:</strong></p> <p>Thanks very much, now it is much clearer. Here's my example I generated to get the hang of it:</p> <pre><code>open System open System.IO let read_lines path = File.ReadAllLines(path) |&gt; Array.to_list let trim line = (string line).Trim() let to_upper line = (string line).ToUpper() let new_list = [ for line in read_lines "myText.txt" -&gt; line |&gt; (trim &gt;&gt; to_upper) ] printf "%A" new_list </code></pre>
1,904,063
5
6
null
2009-12-14 22:44:39.393 UTC
9
2019-08-06 11:19:07.427 UTC
2019-08-06 11:19:07.427 UTC
null
3,345,375
null
154,186
null
1
44
f#|operators
15,441
<p>It's the function composition operator.</p> <p>More info on <a href="http://blogs.msdn.com/chrsmith/archive/2008/06/14/function-composition.aspx" rel="noreferrer">Chris Smith's blogpost</a>.</p> <blockquote> <p>Introducing the Function Composition operator (>>):</p> <p><code>let inline (&gt;&gt;) f g x = g(f x)</code></p> <p>Which reads as: given two functions, f and g, and a value, x, compute the result of f of x and pass that result to g. The interesting thing here is that you can curry the (>>) function and only pass in parameters f and g, the result is a function which takes a single parameter and produces the result g ( f ( x ) ).</p> <p>Here's a quick example of composing a function out of smaller ones:</p> </blockquote> <pre><code>let negate x = x * -1 let square x = x * x let print x = printfn "The number is: %d" x let square_negate_then_print = square &gt;&gt; negate &gt;&gt; print asserdo square_negate_then_print 2 </code></pre> <blockquote> <p>When executed prints ‘-4’.</p> </blockquote>
2,295,119
When should I use attribute in C#?
<p>I saw some of the examples of utilize attribute, e.g. (as a map for dynamic factory) <a href="http://msdn.microsoft.com/en-us/magazine/cc164170.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/magazine/cc164170.aspx</a></p> <p>Just wondering what is the advantage of using attribute? I can find the reference on <a href="http://msdn.microsoft.com/en-gb/z0w1kczw(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-gb/z0w1kczw(VS.80).aspx</a> however, I am not sure when and why should I try to use it.</p>
2,295,161
5
1
null
2010-02-19 09:17:33.287 UTC
13
2020-06-04 19:08:39.533 UTC
2012-09-21 15:32:21.823 UTC
null
512,251
null
275,133
null
1
50
c#|attributes
25,191
<p>In the .NET Framework, attributes can be used for many reasons -- like</p> <ul> <li><p>Defining which classes are serializable </p></li> <li><p>Choosing which methods are exposed in a Web service</p></li> </ul> <p><code>Attributes</code> allow us to add <code>descriptions</code> to classes, properties, and methods at design time that can then be examined at runtime via reflection. </p> <p><strong>Consider this example:</strong></p> <p>Say you have a class which has a method from older version which is still in use for any reason and now you have come up with a new version of the class which makes fantastic use of Generic List and LINQ and has a new method for similar purpose. You would like developers to prefer the new one provided in the later version of your library. How will you do that ? One way is to write in the documentation. A better way is to use attribute as follow.</p> <pre><code>public class AccountsManager { [Obsolete("prefer GetAccountsList", true)] static Account[] GetAccounts( ) { } static List&lt;Account&gt; GetAccountsList( ) { } } </code></pre> <p>If an <code>obsolete</code> method is used when the program is compiled, the developer gets this info and decides accordingly.</p> <blockquote> <p>AccountManager.GetAccounts() is obsolete: prefer GetAccountsList</p> </blockquote> <p>We may also create and add <a href="http://msdn.microsoft.com/en-us/library/sw480ze8(VS.80).aspx" rel="noreferrer"><strong><code>Custom Attributes</code></strong></a> as per requirements.</p> <p>Reference : </p> <ul> <li><a href="http://www.codeguru.com/csharp/csharp/cs_syntax/attributes/article.php/c5831" rel="noreferrer"><strong>Using Attributes in C#</strong></a></li> </ul> <hr> <p>Hope this helps</p>
1,384,163
Looking for a web based diff component
<p>In a content management system, moderators have to approve changes to existing articles. Currently the system shows the old and the revised version of the text in plain text. It is a pain to find the actual differences.</p> <p>In GoogleDocs, there is a 'Compare revisions' feature which highlights the differences between two documents. </p> <p>If there a free component out there that does the same thing?</p> <p>If not, would you write such a component in JavaScript or on the server side?</p> <p>All the usual diff tools are desktop applications.</p>
1,384,190
6
1
null
2009-09-05 20:16:02.373 UTC
9
2017-02-16 01:52:57.02 UTC
null
null
null
null
66,169
null
1
17
diff|compare
9,583
<p>John Resig wrote one in JavaScript that looks interesting.</p> <p><a href="http://ejohn.org/projects/javascript-diff-algorithm/" rel="nofollow noreferrer">Here it is</a>.</p>
1,808,036
Is SqlCommand.Dispose() required if associated SqlConnection will be disposed?
<p>I usually use code like this:</p> <pre><code>using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString)) { var command = connection.CreateCommand(); command.CommandText = "..."; connection.Open(); command.ExecuteNonQuery(); } </code></pre> <p>Will my <code>command</code> automatically disposed? Or not and I have to wrap it into <code>using</code> block? Is it required to dispose <code>SqlCommand</code>?</p>
1,808,056
6
0
null
2009-11-27 10:47:21.713 UTC
7
2020-03-17 00:27:54.28 UTC
null
null
null
null
41,956
null
1
30
c#|ado.net|dispose|sqlconnection|sqlcommand
35,127
<p>Just do this:</p> <pre><code>using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString)) using(var command = connection.CreateCommand()) { command.CommandText = "..."; connection.Open(); command.ExecuteNonQuery(); } </code></pre> <p>Not calling dispose on the command won't do anything too bad. However, calling Dispose on it will <a href="http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx" rel="nofollow noreferrer">suppress the call to the finalizer</a>, making calling dispose a performance enhancement.</p>
1,618,280
Where can I set path to make.exe on Windows?
<p>When I try run <code>make</code> from cmd-console on Windows, it runs Turbo Delphi's <code>make.exe</code> but I need MSYS's <code>make.exe</code>. There is no mention about Turbo Delphi in <code>%path%</code> variable, maybe I can change it to MSYS in registry?</p>
1,618,297
6
1
null
2009-10-24 15:33:09.19 UTC
17
2021-06-17 17:54:34.17 UTC
2021-06-17 14:49:52.903 UTC
null
2,756,409
null
1,760,643
null
1
55
c++|registry|makefile|path|msys
232,156
<p>The path is in the registry but usually you edit through this interface:</p> <ol> <li>Go to <code>Control Panel</code> -> <code>System</code> -> <code>System settings</code> -> <code>Environment Variables</code>.</li> <li>Scroll down in system variables until you find <code>PATH</code>.</li> <li>Click edit and change accordingly.</li> <li>BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. <code>c:\path;c:\path2</code></li> <li>Launch a new console for the settings to take effect.</li> </ol>
2,200,566
Using keep-alive feature in .htaccess
<p>I want to use the <code>keep-alive</code> feature in Apache. How can I do this with my host (.htaccess file), and what are the best values for the parameters like <code>KeepAliveTimeout</code>?</p>
2,200,697
7
0
null
2010-02-04 14:54:42.347 UTC
9
2017-07-15 03:54:29.917 UTC
2017-03-31 14:06:33.907 UTC
null
1,183,764
null
129,099
null
1
28
apache|.htaccess
74,258
<p>You can't control keepalive behaviour in an <code>.htaccess</code>. Keepalives are a host-level feature, not one where different directories can behave differently depending on the per-directory htaccess info.</p> <p>If you are on the kind of basic shared hosting that only gives you <code>.htaccess</code> to configure your sites, you can't change the keepalive settings. Presumably the hosting company will have set them appropriately, or just left them on the default settings, which are usually fine.</p>
1,563,844
Best HashTag Regex
<p>I'm trying to find all the hash tags in a string. The hashtags are from a stream like twitter, they could be anywhere in the text like:</p> <blockquote> <p>this is a #awesome event, lets use the tag #fun</p> </blockquote> <p>I'm using the .NET framework (c#), I was thinking this would be a suitable regex pattern to use:</p> <p>#\w+</p> <p>Is this the best regex for this purpose?</p>
1,563,867
9
0
null
2009-10-14 01:40:51.183 UTC
15
2019-04-25 01:24:44.763 UTC
2012-12-10 18:38:20.887 UTC
user195488
null
user189528
null
null
1
12
.net|regex|twitter
34,170
<p>It depends on whether you want to match hashtags inside other strings ("Some#Word") or things that probably aren't hashtags ("We're #1"). The regex you gave <code>#\w+</code> will match in both these cases. If you slightly modify your regex to <code>\B#\w\w+</code>, you can eliminate these cases and only match hashtags of length greater than 1 on word boundaries.</p>
1,596,337
How to exclude designer.cs from Visual Studio file search
<p>Is there a way to exclude a particular type of .cs file when doing a search in Visual Studio 2005/8?</p> <p><strong>Example:</strong> In a refactoring scenario i might search to identify string literals in my code so that i can refactor them into constants or some such. However, *designer.cs files are full of string literals which i don't care to deal with but they show up in my search and pollute the result set.</p> <p>i usually search for *.cs...</p> <p>How do i ignore *.designer.cs?</p>
28,427,240
10
2
null
2009-10-20 18:04:32.03 UTC
10
2020-07-06 17:53:36.247 UTC
null
null
null
null
47,550
null
1
50
visual-studio|search
16,846
<p>I see it's pretty late, but looking at the number of votes and activity on this page, I'm posting my answer; maybe someone else finds it useful. Here's how you can do this in VS2010 and above:</p> <ol> <li>Open Package Manager Console (Tools > NuGet Package Manager > Package Manager Console). Let PowerShell initialize itself.</li> <li><p>Enter the following command at PowerShell Prompt:</p> <p><code>dir -Recurse | Select-String -pattern "Your Search Word Or Pattern" -exclude "*.designer.cs"</code></p></li> <li>This will list all the occurrences of the word or pattern you've specified, including file name, line number and the text line where it was found.</li> </ol> <p><strong>Additional Notes</strong></p> <ol> <li>If you want to specify multiple exclude patterns, replace <code>"*.designer.cs"</code> with <code>@("*.designer.cs", "*.designer.vb", "reference.cs")</code> or whatever other files you want to skip.</li> <li>Another good thing about it is that the search pattern supports regular expressions too.</li> <li><p>One downside of this solution is that it doesn't let you double-click a line in the result to open that file in Visual Studio. You can workaround this limitation through command-piping:</p> <p><code>dir -Recurse | Select-String -pattern "Your String Or Pattern" -exclude "*.designer.vb" | sort | Select -ExpandProperty "Path" | get-unique | ForEach-Object { $DTE.ExecuteCommand("File.OpenFile", """$_""") }</code></p></li> </ol> <p>This will open all the files where the string or pattern was found in Visual Studio. You can then use <strong>Find</strong> window in individual files to locate the exact instances.</p> <p>Another advantage of this solution is that it works in Express versions as well, since Package Manager is included in 2012 and 2013 Express versions; not sure about 2010 though.</p>
1,943,892
SQL Server PRINT SELECT (Print a select query result)?
<p>I am trying to print a selected value, is this possible?</p> <p>Example:</p> <pre><code>PRINT SELECT SUM(Amount) FROM Expense </code></pre>
1,943,913
10
2
null
2009-12-22 02:44:16.367 UTC
12
2020-10-16 11:45:41.04 UTC
2010-01-01 19:51:24.037 UTC
null
4,035
null
75,500
null
1
81
sql-server|tsql|select-query
354,072
<p>You know, there might be an easier way but the first thing that pops to mind is:</p> <pre><code>Declare @SumVal int; Select @SumVal=Sum(Amount) From Expense; Print @SumVal; </code></pre> <p>You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).</p>
33,646,049
How to Customise the angular material date-picker?
<p>I am using the material design date picker </p> <pre><code>&lt;md-content flex class="padding-top-0 padding-bottom-0" layout="row"&gt; &lt;md-datepicker ng-model="user.submissionDate" md-placeholder="Start date" flex ng-click="ctrl.openCalendarPane($event)"&gt;&lt;/md-datepicker&gt; &lt;md-datepicker ng-model="user.submissionDate" md-placeholder="Due date" flex&gt;&lt;/md-datepicker&gt; &lt;/md-content&gt; </code></pre> <p>and its shows the UI like this <a href="https://i.stack.imgur.com/HpKUJ.png"><img src="https://i.stack.imgur.com/HpKUJ.png" alt="enter image description here"></a></p> <p>I want to remove the calendar icon and include the ng-click functionality in the input box. </p> <p>How to bind the runtime event with the input box?</p> <p><strong>css</strong></p> <pre><code>&lt;style&gt; .inputdemoBasicUsage .md-datepicker-button { width: 36px; } .inputdemoBasicUsage .md-datepicker-input-container { margin-left: 2px; } .md-datepicker-input-container{ display:block; } .md-datepicker-input[placeholder]{ color=red; } .padding-top-0{ padding-top:0px;} .padding-bottom-0{ padding-bottom:0px; } &lt;/style&gt; </code></pre>
33,699,069
4
2
null
2015-11-11 07:36:39.633 UTC
8
2017-08-16 16:30:10.093 UTC
2015-11-11 08:37:01.837 UTC
null
1,391,499
null
1,391,499
null
1
13
javascript|html|css|angularjs|angular-material
38,652
<p>Use the function for manipulate event and hide image of calendar as:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var app = angular.module('StarterApp', ['ngMaterial']); app.controller('AppController', function($scope) { $scope.initDatepicker = function(){ angular.element(".md-datepicker-button").each(function(){ var el = this; var ip = angular.element(el).parent().find("input").bind('click', function(e){ angular.element(el).click(); }); angular.element(this).css('visibility', 'hidden'); }); }; });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.inputdemoBasicUsage .md-datepicker-button { width: 36px; } .inputdemoBasicUsage .md-datepicker-input-container { margin-left: 2px; } .md-datepicker-input-container { display: block; } .md-datepicker-input[placeholder] { color:red; } .padding-top-0 { padding-top: 0px; } .padding-bottom-0 { padding-bottom: 0px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Angular Material Dependencies --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-animate.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-aria.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angular_material/0.11.2/angular-material.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.11.2/angular-material.min.css"&gt; &lt;div ng-app="StarterApp" ng-controller="AppController" ng-init="initDatepicker();"&gt; &lt;md-content flex class="padding-top-0 padding-bottom-0" layout="row"&gt; &lt;md-datepicker ng-model="user.submissionDate1" md-placeholder="Start date" flex ng-click="ctrl.openCalendarPane($event)"&gt;&lt;/md-datepicker&gt; &lt;md-datepicker ng-model="user.submissionDate2" md-placeholder="Due date" flex&gt;&lt;/md-datepicker&gt; &lt;/md-content&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
18,111,739
Why do some Android phones cause our app to throw an java.lang.UnsatisfiedLinkError?
<p>We're experiencing a <code>java.lang.UnsatisfiedLinkError</code> on some of the Android phones that are using our app in the market.</p> <p><strong>Problem description:</strong></p> <pre><code>static { System.loadLibrary("stlport_shared"); // C++ STL System.loadLibrary("lib2"); System.loadLibrary("lib3"); } </code></pre> <p>Crashes the app in on of the <code>System.loadLibrary()</code> lines with a <code>java.lang.UnsatisfiedLinkError</code>. <code>java.lang.UnsatisfiedLinkError: Couldn't load stlport_shared from loader dalvik.system.PathClassLoader[dexPath=/data/app/app_id-2.apk,libraryPath=/data/app-lib/app_id-2]: findLibrary returned null</code></p> <p><strong>Solution approach</strong></p> <p>We started running some custom diagnostics on all our installs to check if every lib is unpacked in the <code>/data/data/app_id/lib</code> folder.</p> <pre><code>PackageManager m = context.getPackageManager(); String s = context.getPackageName(); PackageInfo p; p = m.getPackageInfo(s, 0); s = p.applicationInfo.dataDir; File appDir = new File(s); long freeSpace = appDir.getFreeSpace(); File[] appDirList = appDir.listFiles(); int numberOfLibFiles = 0; boolean subFilesLarger0 = true; for (int i = 0; i &lt; appDirList.length; i++) { if(appDirList[i].getName().startsWith("lib")) { File[] subFile = appDirList[i].listFiles(FileFilters.FilterDirs); numberOfLibFiles = subFile.length; for (int j = 0; j &lt; subFile.length; j++) { if(subFile[j].length() &lt;= 0) { subFilesLarger0 = false; break; } } } } </code></pre> <p>On every test phone that we have <code>numberOfLibFiles == 3</code> and <code>subFilesLarger0 == true</code>. We wanted to test if all libs are unpacked properly and are larger then 0 byte. In addition we're looking at <code>freeSpace</code> to see how much disk space is available. <code>freeSpace</code> matches the amount of memory that you can find in Settings --> Applications at the bottom of the screen. The thinking behind this approach was that when there is not enough space on the disk available that the installer might have problems unpacking the APK.</p> <p><strong>Real world scenario</strong></p> <p>Looking at the diagnostics, some of the devices out there do <strong>NOT</strong> have all 3 libs in the <code>/data/data/app_id/lib</code> folder but have plenty of free space. I'm wondering why the error message is looking for <code>/data/app-lib/app_id-2</code>. All our phones store their libs in <code>/data/data/app_id/lib</code>. Also the <code>System.loadLibrary()</code> should use a consistent path across installation and loading the libs? How can I know where the OS is looking for the libs?</p> <p><strong>Question</strong></p> <p>Anyone experiencing problems with installing native libs? What work arounds have been successful? Any experience with just downloading native libs over the internet when they are not existent and storing them manually? What could cause the problem in the first place? </p> <p><strong>EDIT</strong></p> <p>I now also have a user who runs into this problem after an application update. The previous version worked fine on his phone, an after an update the native libs seem missing. Copying the libs manually seem to cause trouble as well. He is on android 4.x with a non rooted phone without custom ROM.</p> <p><strong>EDIT 2 - Solution</strong></p> <p>After 2 years of spending time on this problem. We came up with a solution that works well for us now. We open sourced it: <a href="https://github.com/KeepSafe/ReLinker" rel="noreferrer">https://github.com/KeepSafe/ReLinker</a></p>
24,296,556
5
12
null
2013-08-07 19:06:27.457 UTC
21
2021-06-28 20:01:06.383 UTC
2016-02-25 00:39:19.81 UTC
null
366,967
null
366,967
null
1
42
android|android-ndk|java-native-interface|native|unsatisfiedlinkerror
16,129
<p>I have the same trouble, and the UnsatisfiedLinkErrors comes on all versions of Android - over the past 6 months, for an app that currently has over 90000 active installs, I had:</p> <pre><code>Android 4.2 36 57.1% Android 4.1 11 17.5% Android 4.3 8 12.7% Android 2.3.x 6 9.5% Android 4.4 1 1.6% Android 4.0.x 1 1.6% </code></pre> <p>and the users report that it usually happens just after the app update. This is for an app that gets around 200 - 500 new users per day. </p> <p><strong>I think I came up with a simpler work-around</strong>. I can find out where is the original apk of my app with this simple call:</p> <pre><code> String apkFileName = context.getApplicationInfo().sourceDir; </code></pre> <p>this returns something like "/data/app/com.example.pkgname-3.apk", the exact file name of my app's APK file. This file is a regular ZIP file and it is readable without root. Therefore, if I catch the java.lang.UnsatisfiedLinkError, I can extract and copy my native library, from the inside of .apk (zip) lib/armeabi-v7a folder (or whatever architecture I'm on), to any directory where I can read/write/execute, and load it with System.load(full_path).</p> <h2>Edit: It seems to work</h2> <p><strong>Update July 1, 2014</strong> since releasing a version of my product with the code similar to the listed below, on June 23, 2014, did not have any Unsatisfied Link Errors from my native library.</p> <p>Here is the code I used:</p> <pre><code>public static void initNativeLib(Context context) { try { // Try loading our native lib, see if it works... System.loadLibrary("MyNativeLibName"); } catch (UnsatisfiedLinkError er) { ApplicationInfo appInfo = context.getApplicationInfo(); String libName = "libMyNativeLibName.so"; String destPath = context.getFilesDir().toString(); try { String soName = destPath + File.separator + libName; new File(soName).delete(); UnzipUtil.extractFile(appInfo.sourceDir, "lib/" + Build.CPU_ABI + "/" + libName, destPath); System.load(soName); } catch (IOException e) { // extractFile to app files dir did not work. Not enough space? Try elsewhere... destPath = context.getExternalCacheDir().toString(); // Note: location on external memory is not secure, everyone can read/write it... // However we extract from a "secure" place (our apk) and instantly load it, // on each start of the app, this should make it safer. String soName = destPath + File.separator + libName; new File(soName).delete(); // this copy could be old, or altered by an attack try { UnzipUtil.extractFile(appInfo.sourceDir, "lib/" + Build.CPU_ABI + "/" + libName, destPath); System.load(soName); } catch (IOException e2) { Log.e(TAG "Exception in InstallInfo.init(): " + e); e.printStackTrace(); } } } } </code></pre> <p>Unfortunately, if a bad app update leaves an old version of the native library, or a copy somehow damaged, which we loaded with System.loadLibrary("MyNativeLibName"), there is no way to unload it. Upon finding out about such remnant defunct library lingering in the standard app native lib folder, e.g. by calling one of our native methods and finding out it's not there (UnsatisfiedLinkError again), we could store a preference to avoid calling the standard System.loadLibrary() altogether and relying on our own extraction and loading code upon next app startups.</p> <p>For completeness, here is UnzipUtil class, that I copied and modified from this <a href="http://www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java">CodeJava UnzipUtility article</a>:</p> <pre><code>import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class UnzipUtil { /** * Size of the buffer to read/write data */ private static final int BUFFER_SIZE = 4096; /** * Extracts a zip file specified by the zipFilePath to a directory specified by * destDirectory (will be created if does not exists) * @param zipFilePath * @param destDirectory * @throws java.io.IOException */ public static void unzip(String zipFilePath, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); // iterates over entries in the zip file while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { // if the entry is a file, extracts it extractFile(zipIn, filePath); } else { // if the entry is a directory, make the directory File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); } /** * Extracts a file from a zip to specified destination directory. * The path of the file inside the zip is discarded, the file is * copied directly to the destDirectory. * @param zipFilePath - path and file name of a zip file * @param inZipFilePath - path and file name inside the zip * @param destDirectory - directory to which the file from zip should be extracted, the path part is discarded. * @throws java.io.IOException */ public static void extractFile(String zipFilePath, String inZipFilePath, String destDirectory) throws IOException { ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); // iterates over entries in the zip file while (entry != null) { if (!entry.isDirectory() &amp;&amp; inZipFilePath.equals(entry.getName())) { String filePath = entry.getName(); int separatorIndex = filePath.lastIndexOf(File.separator); if (separatorIndex &gt; -1) filePath = filePath.substring(separatorIndex + 1, filePath.length()); filePath = destDirectory + File.separator + filePath; extractFile(zipIn, filePath); break; } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); } /** * Extracts a zip entry (file entry) * @param zipIn * @param filePath * @throws java.io.IOException */ private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = zipIn.read(bytesIn)) != -1) { bos.write(bytesIn, 0, read); } bos.close(); } } </code></pre> <p>Greg</p>
17,911,091
Append integer to beginning of list in Python
<p>How do I prepend an integer to the beginning of a list?</p> <pre><code>[1, 2, 3] ⟶ [42, 1, 2, 3] </code></pre>
17,911,209
10
1
null
2013-07-28 17:54:33.54 UTC
97
2022-07-28 09:04:27.55 UTC
2022-07-28 09:04:27.55 UTC
null
365,102
null
1,509,744
null
1
704
python|list|prepend
1,148,608
<pre><code>&gt;&gt;&gt; x = 42 &gt;&gt;&gt; xs = [1, 2, 3] &gt;&gt;&gt; xs.insert(0, x) &gt;&gt;&gt; xs [42, 1, 2, 3] </code></pre> <p>How it works:</p> <p><code>list.insert(index, value)</code></p> <p>Insert an item at a given position. The first argument is the index of the element before which to insert, so <code>xs.insert(0, x)</code> inserts at the front of the list, and <code>xs.insert(len(xs), x)</code> is equivalent to <code>xs.append(x)</code>. Negative values are treated as being relative to the end of the list.</p>
17,870,303
IDE "Cannot Resolve @style/Theme.Appcompat" when using v7 compatibility support theme
<p>This is not really a huge issue, as my project still builds and runs correctly (using gradle), but I'm having trouble getting Android Studio to recognize the application compatibility theme released in the API 18 SDK (for allowing actionbar support for android 2.1 and above).</p> <p>I have the support libraries loading successfully, because code completion is possible for the ActionBar classes in java files. The issue is that Android studio shows red text errors for assignments to the Theme.AppCompat.Light in the AndroidManifest.xml.</p> <p>Is there a way to enable code completion for theme resources declared in the manifest from external libraries in Android Studio?</p> <p><strong>Updated</strong> Here is my <code>&lt;activity&gt;</code> block from my AndroidManifest:</p> <pre><code>&lt;activity android:name="com.example.activities.MainActivity" android:label="@string/app_name" android:screenOrientation="portrait" android:theme="@style/Theme.AppCompat.Light" &gt; </code></pre> <p>I've also tried setting the theme in the application block:</p> <pre><code>&lt;application android:allowBackup="true" android:icon="@drawable/main_final_ic" android:label="@string/app_name" android:logo="@drawable/main_final_enzo" android:theme="@style/Theme.AppCompat.Light" &gt; </code></pre> <p>Again, these both work and compile OK, but appear as red text with errors in my IDE. I've also just confirmed that the same issues are occurring when running my project in eclipse.</p>
18,649,788
13
6
null
2013-07-25 23:09:54.813 UTC
7
2019-02-07 23:48:40.067 UTC
2013-08-04 07:52:35.243 UTC
null
1,197,775
null
342,745
null
1
41
android|eclipse|android-studio|android-support-library
55,662
<p>This problem was fixed in Android Studio v0.2.7.</p> <ul> <li><a href="https://code.google.com/p/android/issues/detail?id=56312" rel="nofollow">https://code.google.com/p/android/issues/detail?id=56312</a></li> <li><a href="https://android-review.googlesource.com/#/c/64533/" rel="nofollow">https://android-review.googlesource.com/#/c/64533/</a></li> </ul>
16,019,729
Deserializing JSON object into a C# list
<p>I'm trying to deserialize a given JSON file in C# using a <a href="http://www.billreiss.com/making-json-web-requests-easier-with-async-and-await/" rel="nofollow noreferrer">tutorial by Bill Reiss</a>. For XML data in a non-list this method works pretty well, though I would like to deserialize a JSON file with the following structure:</p> <pre><code>public class Data { public string Att1 { get; set; } public string Att2 { get; set; } public string Att3 { get; set; } public string Att4 { get; set; } } public class RootObject { public List&lt;Data&gt; Listname { get; set; } } </code></pre> <p>My problem is with using JSON.Net's ability to create / put data into lists, and then displaying the list on an XAML page. My idea so far (which is not working):</p> <pre><code>var resp = await client.DoRequestJsonAsync&lt;DATACLASS&gt;("URL"); string t = resp.ToString(); var _result = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;List&lt;DATACLASS&gt;&gt;(t); XAMLELEMENT.ItemsSource = _result; </code></pre>
16,020,050
1
3
null
2013-04-15 16:02:14.773 UTC
3
2016-12-15 15:52:16.193 UTC
2016-12-15 15:52:16.193 UTC
null
236,247
null
2,282,587
null
1
8
c#|json|list|json.net|deserialization
59,423
<p>So I think you're probably trying to deserialize to the wrong type. If you serialized it to RootObject and try to deserialize to List it's going to fail.</p> <p>See this example code</p> <pre><code>public void TestMethod1() { var items = new List&lt;Item&gt; { new Item { Att1 = "ABC", Att2 = "123" }, new Item { Att1 = "EFG", Att2 = "456" }, new Item { Att1 = "HIJ", Att2 = "789" } }; var root = new Root() { Items = items }; var itemsSerialized = JsonConvert.SerializeObject(items); var rootSerialized = JsonConvert.SerializeObject(root); //This works var deserializedItemsFromItems = JsonConvert.DeserializeObject&lt;List&lt;Item&gt;&gt;(itemsSerialized); //This works var deserializedRootFromRoot = JsonConvert.DeserializeObject&lt;Root&gt;(rootSerialized); //This will fail. YOu serialized it as root and tried to deserialize as List&lt;Item&gt; var deserializedItemsFromRoot = JsonConvert.DeserializeObject&lt;List&lt;Item&gt;&gt;(rootSerialized); //This will fail also for the same reason var deserializedRootFromItems = JsonConvert.DeserializeObject&lt;Root&gt;(itemsSerialized); } class Root { public IEnumerable&lt;Item&gt; Items { get; set; } } class Item { public string Att1 { get; set; } public string Att2 { get; set; } } </code></pre> <p>Edit: Added complete code.</p>
15,930,880
Unlist all list elements in a dataframe
<p>I have a data frame with the following classes of variables for each column:</p> <pre><code>"date" "numeric" "numeric" "list" "list" "numeric" </code></pre> <p>The data in each row looks like this:</p> <pre><code> 1978-01-01, 12.5, 6.3, c(0,0,0.25,0.45,0.3), c(0,0,0,0.1,0.9), 72 </code></pre> <p>I would like to transform it into a matrix or a data frame with one value per column, so the result should look like this:</p> <pre><code>1978-01-01, 12.5, 6.3, 0, 0, 0.25, 0.45, 0.3, 0, 0, 0, 0.1, 0.9, 72 </code></pre> <p>I have tried using:</p> <pre><code>j&lt;-unlist(input) output&lt;-matrix(j,nrow=nrow(input),ncol=length(j)/nrow(input)) </code></pre> <p>But it messes up the order of the rows in the output.</p> <p>Any idea?</p> <p><strong>Additional information:</strong></p> <p>The above example is slightly simplified and <code>dput(head(input))</code> returns the following sample:</p> <pre><code>structure(list(DATE = structure(c(2924, 2925, 2926, 2927, 2928, 2929), class = "Date"), TEMP_MEAN_M0 = c(-7.625, -7.375, -6, -5.5, -7.625, -9.625), SLP_MEAN_M0 = c(1012.125, 991.975, 989.825, 986.675, 988.95, 993.075), WIND_DIR_RF_M0 = structure(list(`2.counts` = c(0, 0.625, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.125, 0, 0, 0, 0.125), `3.counts` = c(0.75, 0.25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), `4.counts` = c(0.375, 0.125, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.125, 0.125, 0, 0, 0), `5.counts` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.125, 0, 0, 0.125, 0.375, 0.25, 0, 0, 0, 0, 0, 0, 0, 0, 0), `6.counts` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.125, 0, 0.25, 0.125, 0.25, 0.25, 0, 0, 0, 0, 0, 0, 0, 0, 0), `7.counts` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.125, 0.5, 0.375, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("2.counts", "3.counts", "4.counts", "5.counts", "6.counts", "7.counts")), CEIL_HGT_RF_M0 = structure(list(`2.counts` = c(0.625, 0, 0, 0, 0, 0, 0, 0, 0, 0.375), `3.counts` = c(0.75, 0.125, 0, 0.125, 0, 0, 0, 0, 0, 0), `4.counts` = c(0.25, 0.125, 0, 0.125, 0, 0, 0, 0, 0.25, 0.25), `5.counts` = c(0, 0, 0, 0, 0, 0, 0, 0, 0.125, 0.875), `6.counts` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 1), `7.counts` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 1)), .Names = c("2.counts", "3.counts", "4.counts", "5.counts", "6.counts", "7.counts")), WIND_SPD_MEAN_M0 = c(12.8125, 18.7375, 6.175, 8.175, 10.5375, 16.5375)), .Names = c("DATE", "TEMP_MEAN_M0", "SLP_MEAN_M0", "WIND_DIR_RF_M0", "CEIL_HGT_RF_M0", "WIND_SPD_MEAN_M0" ), row.names = c(NA, 6L), class = "data.frame") </code></pre>
15,932,091
1
1
null
2013-04-10 16:02:54.247 UTC
4
2016-03-08 17:36:25.453 UTC
2013-04-10 16:38:26.207 UTC
null
1,883,615
null
1,883,615
null
1
10
r|dataframe
40,302
<p>This is somewhat messy and probably pretty inefficient, but should help get you started:</p> <p>Here's some sample data:</p> <pre><code>mydf &lt;- data.frame(Date = as.Date(c("1978-01-01", "1978-01-02")), V1 = c(10, 10), V2 = c(11, 11)) mydf$V3 &lt;- list(c(1:10), c(11:20)) mydf$V4 &lt;- list(c(21:25), c(26:30)) mydf # Date V1 V2 V3 V4 # 1 1978-01-01 10 11 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 21, 22, 23, 24, 25 # 2 1978-01-02 10 11 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 26, 27, 28, 29, 30 </code></pre> <p>And, a little function that checks to see which columns are lists, and for those columns, <code>rbind</code>s them together, and ultimately <code>cbind</code>s them with the columns that are <em>not</em> lists.</p> <pre><code>myFun &lt;- function(data) { temp1 &lt;- sapply(data, is.list) temp2 &lt;- do.call( cbind, lapply(data[temp1], function(x) data.frame(do.call(rbind, x), check.names=FALSE))) cbind(data[!temp1], temp2) } myFun(mydf) # Date V1 V2 V3.1 V3.2 V3.3 V3.4 V3.5 V3.6 V3.7 V3.8 V3.9 V3.10 V4.1 # 1 1978-01-01 10 11 1 2 3 4 5 6 7 8 9 10 21 # 2 1978-01-02 10 11 11 12 13 14 15 16 17 18 19 20 26 # V4.2 V4.3 V4.4 V4.5 # 1 22 23 24 25 # 2 27 28 29 30 </code></pre> <p>This will only work if each "column" list contain vectors of the same length (otherwise base R's <code>rbind</code> will not work).</p> <hr> <h3>Update</h3> <p>Revisiting this question half a day later, I see that another user (<a href="https://stackoverflow.com/users/1981275/user1981275"><strong>@user1981275</strong></a>) posted a solution that is more straightforward, but then deleted their answer. Perhaps they deleted because their method converted the dates to integers since, as DWin pointed out, items in matrices must be all the same mode.</p> <p>Here was their solution:</p> <pre><code>t(apply(mydf, 1, unlist)) # Date V1 V2 V31 V32 V33 V34 V35 V36 V37 V38 V39 V310 V41 V42 V43 V44 V45 # [1,] 2922 10 11 1 2 3 4 5 6 7 8 9 10 21 22 23 24 25 # [2,] 2923 10 11 11 12 13 14 15 16 17 18 19 20 26 27 28 29 30 </code></pre> <p>Here's how it can easily be modified to get the desired output. This will definitely be faster than the earlier approach:</p> <pre><code>cbind(mydf[!sapply(mydf, is.list)], (t(apply(mydf[sapply(mydf, is.list)], 1, unlist)))) # Date V1 V2 V31 V32 V33 V34 V35 V36 V37 V38 V39 V310 V41 V42 V43 V44 V45 # 1 1978-01-01 10 11 1 2 3 4 5 6 7 8 9 10 21 22 23 24 25 # 2 1978-01-02 10 11 11 12 13 14 15 16 17 18 19 20 26 27 28 29 30 </code></pre> <p>Or, as a user function:</p> <pre><code>myFun &lt;- function(data) { ListCols &lt;- sapply(data, is.list) cbind(data[!ListCols], t(apply(data[ListCols], 1, unlist))) } myFun(mydf) </code></pre> <hr> <h3>Update 2</h3> <p>I've also written a more efficient function called <code>col_flatten</code> that's part of my "SOfun" package.</p> <p>Install the package using:</p> <pre><code>source("http://news.mrdwab.com/install_github.R") install_github("mrdwab/SOfun") </code></pre> <p>Then, you can do:</p> <pre><code>library(SOfun) col_flatten(mydf, names(which(sapply(mydf, is.list))), drop = TRUE) ## Date V1 V2 V3_1 V3_2 V3_3 V3_4 V3_5 V3_6 V3_7 V3_8 V3_9 V3_10 V4_1 V4_2 V4_3 V4_4 V4_5 ## 1: 1978-01-01 10 11 1 2 3 4 5 6 7 8 9 10 21 22 23 24 25 ## 2: 1978-01-02 10 11 11 12 13 14 15 16 17 18 19 20 26 27 28 29 30 </code></pre> <p>It's based on the <code>transpose</code> function in "data.table", so be sure you have "data.table" as well.</p>
15,539,617
String append with format in android
<p>Anybody help me please. I don't know how to append the String with format in android similar to this:</p> <pre><code>String key = ""; append("%d-%d-%d", 0, 1, 2)); </code></pre> <p>Please give me an example. Thank you in advance.</p>
15,539,701
3
0
null
2013-03-21 04:39:36.437 UTC
1
2013-03-21 05:09:58.633 UTC
null
null
null
null
1,597,700
null
1
11
android|string
42,237
<p>Use StringBuilder or StringBuffer but with adequate initial capacity to avoid re-allocation. The default capacity is 16, so once you exceed that, the data has to be copied into a new bigger place. Use append not +.</p> <pre><code>int integer = 5; StringBuilder s = new StringBuilder(100); s.append("something"); s.append(integer); s.append("more text"); </code></pre>
35,026,120
Is there a pure virtual function in the C++ Standard Library?
<p>In <a href="https://isocpp.org/blog/2016/01/functional-programming-in-cpp-nicola-gigante-meetingcpp-2015" rel="nofollow noreferrer">Nicola Gigante's lecture in 2015</a>, he mentions (at the beginning) that there are no pure virtual functions in the Standard Library (or he's not aware of any). I believe that Alex Stepanov was against this language feature but since the initial STL design, have any pure virtuals creeped into the Standard library?</p> <p>FWIW (and correct me if I'm wrong) the deleters in unique pointers ultimately use virtual dispatching in most implementations but these are not pure virtuals.</p>
35,026,367
2
14
null
2016-01-26 23:38:10.933 UTC
4
2019-10-26 05:53:10.603 UTC
2019-10-26 05:53:10.603 UTC
null
963,864
null
4,224,575
null
1
35
c++|language-lawyer|virtual-functions|c++-standard-library|pure-virtual
2,417
<p><strong>[syserr.errcat.overview]</strong> has <a href="http://en.cppreference.com/w/cpp/error/error_category" rel="noreferrer"><code>std::error_category</code></a></p> <pre><code>class error_category { virtual const char* name() const noexcept = 0; virtual string message(int ev) const = 0; }; </code></pre> <p>There are no others in C++14.</p>
5,372,872
MySQL trigger if condition exists
<p>I'm trying to write an update trigger that will only update a password when a new password is set in the update statement but I'm having a terrible time trying to nail down the syntax. This should be a no-brainer but I'm just not finding the solution.</p> <p>Here's my code:</p> <pre><code>CREATE TRIGGER upd_user BEFORE UPDATE ON `user` FOR EACH ROW BEGIN IF (NEW.password &lt;&gt; '') THEN SET NEW.password = PASSWORD(NEW.password); END IF; END; </code></pre> <p>I've tried:</p> <pre><code>IF (NEW.password &lt;&gt; NULL) THEN IF (NEW.password) THEN IF NEW.password &lt;&gt; NULL THEN IF (NEW.password &gt; 0) THEN IF (NEW.password != NULL) THEN </code></pre> <p>And I'm sure many other combinations but it's just not working. Does anyone have any insight?</p>
5,372,987
2
0
null
2011-03-21 01:10:24.447 UTC
5
2021-12-06 18:39:52.757 UTC
null
null
null
null
319,969
null
1
16
mysql|triggers
129,590
<p>I think you mean to update it back to the <code>OLD</code> password, when the NEW one is not supplied.</p> <pre><code>DROP TRIGGER IF EXISTS upd_user; DELIMITER $$ CREATE TRIGGER upd_user BEFORE UPDATE ON `user` FOR EACH ROW BEGIN IF (NEW.password IS NULL OR NEW.password = '') THEN SET NEW.password = OLD.password; ELSE SET NEW.password = Password(NEW.Password); END IF; END$$ DELIMITER ; </code></pre> <p>However, this means a user can never blank out a password.</p> <p><hr> If the password field (already encrypted) is being sent back in the update to mySQL, then it will not be null or blank, and MySQL will attempt to redo the Password() function on it. To detect this, use this code instead</p> <pre><code>DELIMITER $$ CREATE TRIGGER upd_user BEFORE UPDATE ON `user` FOR EACH ROW BEGIN IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN SET NEW.password = OLD.password; ELSE SET NEW.password = Password(NEW.Password); END IF; END$$ DELIMITER ; </code></pre>
875,033
Getters/setters in Java
<p>I'm new to Java, but have some OOP experience with ActionScript 3, so I'm trying to migrate relying on stuff I know.</p> <p>In ActionScript 3 you can create getters and setters using the get and set keywords, meaning you create a method in the class and access data through a property of an instance of that class. I might sound complicated, but it's not. Here's an example:</p> <pre><code>class Dummy{ private var _name:String; public function Dummy(name:String=null){ this._name = name; } //getter public function get name():String{ return _name; } //setter public function set name(value:String):void{ //do some validation if necessary _name = value; } } </code></pre> <p>And I would access <code>name</code> in an object as:</p> <pre><code>var dummy:Dummy = new Dummy("fred"); trace(dummy.name);//prints: fred dummy.name = "lolo";//setter trace(dummy.name);//getter </code></pre> <p>How would I do that in Java?</p> <p>Just having some public fields is out of the question. I've noticed that there is this convention of using get and set in front of methods, which I'm OK with.</p> <p>For example,</p> <pre><code>class Dummy{ String _name; public void Dummy(){} public void Dummy(String name){ _name = name; } public String getName(){ return _name; } public void setName(String name){ _name = name; } } </code></pre> <p>Is there an equivalent of ActionScript 3 getter/setters in Java, as in accessing a private field as a field from an instance of the class, but having a method for implementing that internally in the class?</p>
875,041
7
1
null
2009-05-17 17:24:54.54 UTC
2
2012-03-06 23:25:33.163 UTC
2010-09-18 11:20:26.823 UTC
null
63,550
null
89,766
null
1
23
java|actionscript-3|setter|getter|accessor
45,185
<p>Nope. AS3 getters and setters are an ECMAScript thing. In Java, you're stuck with the getVal() and setVal() style functions--there isn't any syntactic sugar to make things easy for you.</p> <p>I think Eclipse can help auto-generating those types of things though...</p>
749,622
How to get Return Value of a Stored Procedure
<p>Probably an easy-to-answer question. I have this procedure:</p> <pre><code>CREATE PROCEDURE [dbo].[AccountExists] @UserName nvarchar(16) AS IF EXISTS (SELECT Id FROM Account WHERE UserName=@UserName) SELECT 1 ELSE SELECT 0 </code></pre> <p>When I have ADO.NET code that calls this procedure and does this:</p> <pre><code>return Convert.ToBoolean(sproc.ExecuteScalar()); </code></pre> <p>Either true or false is returned.</p> <p>When I change the stored procedure to RETURN 1 or 0 instead of SELECT:</p> <pre><code>ALTER PROCEDURE [dbo].[AccountExists] @UserName nvarchar(16) AS IF EXISTS (SELECT Id FROM Account WHERE UserName=@UserName) RETURN 1 ELSE RETURN 0 </code></pre> <p>sproc.ExecuteScalar() returns null. If I try sproc.ExecuteNonQuery() instead, -1 is returned.</p> <p><strong>How do I get the result of a stored procedure with a RETURN in ADO.NET?</strong></p> <p>I need AccountExists to RETURN instead of SELECT so I can have another stored procedure call it:</p> <pre><code>--another procedure to insert or update account DECLARE @exists bit EXEC @exists = [dbo].[AccountExists] @UserName IF @exists=1 --update account ELSE --insert acocunt </code></pre>
749,633
7
2
null
2009-04-14 22:39:36.727 UTC
9
2017-10-05 10:13:52.837 UTC
2012-06-14 22:28:02.35 UTC
null
76,337
null
11,574
null
1
35
sql|tsql|stored-procedures|ado.net
63,459
<p>Add a parameter, using <code>ParameterDirection.ReturnValue</code>. The return value will be present in the paramter after the execution.</p>
240,244
vim -- How to read range of lines from a file into current buffer
<p>I want to read line n1->n2 from file foo.c into the current buffer.</p> <p>I tried: <code>147,227r /path/to/foo/foo.c</code></p> <p>But I get: "E16: Invalid range", though I am certain that foo.c contains more than 1000 lines.</p>
240,274
7
0
null
2008-10-27 15:12:27.97 UTC
25
2019-11-25 00:44:22.17 UTC
2012-08-14 04:16:47.29 UTC
null
128,421
Aman Jain
29,405
null
1
67
vim
34,678
<pre><code>:r! sed -n 147,227p /path/to/foo/foo.c </code></pre>
491,376
Why doesn't .NET/C# optimize for tail-call recursion?
<p>I found <a href="https://stackoverflow.com/questions/340762/which-languages-support-tail-recursion-optimization">this question</a> about which languages optimize tail recursion. Why C# doesn't optimize tail recursion, whenever possible?</p> <p>For a concrete case, why isn't this method optimized into a loop (<a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008" rel="noreferrer">Visual&nbsp;Studio&nbsp;2008</a> 32-bit, if that matters)?:</p> <pre><code>private static void Foo(int i) { if (i == 1000000) return; if (i % 100 == 0) Console.WriteLine(i); Foo(i+1); } </code></pre>
491,463
7
4
null
2009-01-29 12:20:21.227 UTC
33
2021-11-11 21:03:05.033 UTC
2017-05-23 12:17:52.443 UTC
null
-1
ripper234
11,236
null
1
122
c#|.net|optimization|tail-recursion
35,552
<p>JIT compilation is a tricky balancing act between not spending too much time doing the compilation phase (thus slowing down short lived applications considerably) vs. not doing enough analysis to keep the application competitive in the long term with a standard ahead-of-time compilation.</p> <p>Interestingly the <a href="https://en.wikipedia.org/wiki/Native_Image_Generator" rel="nofollow noreferrer">NGen</a> compilation steps are not targeted to being more aggressive in their optimizations. I suspect this is because they simply don't want to have bugs where the behaviour is dependent on whether the JIT or NGen was responsible for the machine code.</p> <p>The <a href="https://en.wikipedia.org/wiki/Common_Language_Runtime" rel="nofollow noreferrer">CLR</a> itself does support tail call optimization, but the language-specific compiler must know how to generate the relevant <a href="https://docs.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/56c08k0k(v=vs.95)?redirectedfrom=MSDN" rel="nofollow noreferrer">opcode</a> and the JIT must be willing to respect it. <a href="https://en.wikipedia.org/wiki/F_Sharp_(programming_language)" rel="nofollow noreferrer">F#'s</a> fsc will generate the relevant opcodes (though for a simple recursion it may just convert the whole thing into a <code>while</code> loop directly). C#'s csc does not.</p> <p>See <a href="https://docs.microsoft.com/en-us/archive/blogs/davbr/" rel="nofollow noreferrer">this blog post</a> for some details (quite possibly now out of date given recent JIT changes). Note that the CLR changes for 4.0 <a href="https://docs.microsoft.com/en-us/archive/blogs/clrcodegeneration/tail-call-improvements-in-net-framework-4" rel="nofollow noreferrer">the x86, x64 and ia64 will respect it</a>.</p>
330,737
jQuery datepicker- 2 inputs/textboxes and restricting range
<p>I am using the jQuery Datepicker widget with two input boxes, one for the <strong>"From"</strong> date and the second with the <strong>"To"</strong> date. I am using the <a href="http://jqueryui.com/datepicker/" rel="noreferrer">jQuery Datepicker functional demo</a> as a basis for getting the two input boxes to work with each other, but I need to be able to add these additional restrictions:</p> <ol> <li><p>Date range can be no earlier than 01 December 2008 </p></li> <li><p><strong>"To"</strong> date can be no later than today</p></li> <li><p>Once a <strong>"From"</strong> date is selected, the <strong>"To"</strong> date can only be within a range of 7 days after the <strong>"From"</strong> date</p></li> <li><p>If a <strong>"To"</strong> date is selected first, then the <strong>"From"</strong> date can only be within the range of 7 days before the <strong>"To"</strong> date (with the limit of 01 December being the first selectable date)</p></li> </ol> <p>I can't seem to get all of the above working together.</p> <p>In summary, I would like to be able to select a range of up to 7 days between 01 December and today (I realise I am posting this on 1st December so will only get today for the moment).</p> <p>My code so far</p> <pre><code>$(function () { $('#txtStartDate, #txtEndDate').datepicker( { showOn: "both", beforeShow: customRange, dateFormat: "dd M yy", firstDay: 1, changeFirstDay: false }); }); function customRange(input) { return { minDate: (input.id == "txtStartDate" ? new Date(2008, 12 - 1, 1) : null), minDate: (input.id == "txtEndDate" ? $("#txtStartDate").datepicker("getDate") : null), maxDate: (input.id == "txtStartDate" ? $("#txtEndDate").datepicker("getDate") : null) }; } </code></pre> <p>I'm missing the 7 day range restriction and also preventing a <strong>"To"</strong> date selection before 01 December 2008 or after today. Any help would be much appreciated, Thanks.</p>
333,585
8
1
null
2008-12-01 12:49:37.677 UTC
33
2014-03-21 21:50:05.707 UTC
2014-03-21 21:50:05.707 UTC
Russ Cam
814,702
Russ Cam
1,831
null
1
53
jquery|jquery-plugins|datepicker|jquery-ui-datepicker
95,649
<p>Many thanks for your help Ben, I have built upon your posts and have come up with this. It is now complete and works brilliantly!</p> <p>Here's a <strong><a href="http://jsbin.com/evudo" rel="noreferrer">Working Demo</a></strong>. Add <strong>/edit</strong> to the URL to see the code</p> <p>Complete Code below-</p> <pre><code>$(function () { $('#txtStartDate, #txtEndDate').datepicker({ showOn: "both", beforeShow: customRange, dateFormat: "dd M yy", firstDay: 1, changeFirstDay: false }); }); function customRange(input) { var min = new Date(2008, 11 - 1, 1), //Set this to your absolute minimum date dateMin = min, dateMax = null, dayRange = 6; // Set this to the range of days you want to restrict to if (input.id === "txtStartDate") { if ($("#txtEndDate").datepicker("getDate") != null) { dateMax = $("#txtEndDate").datepicker("getDate"); dateMin = $("#txtEndDate").datepicker("getDate"); dateMin.setDate(dateMin.getDate() - dayRange); if (dateMin &lt; min) { dateMin = min; } } else { dateMax = new Date; //Set this to your absolute maximum date } } else if (input.id === "txtEndDate") { dateMax = new Date; //Set this to your absolute maximum date if ($("#txtStartDate").datepicker("getDate") != null) { dateMin = $("#txtStartDate").datepicker("getDate"); var rangeMax = new Date(dateMin.getFullYear(), dateMin.getMonth(),dateMin.getDate() + dayRange); if(rangeMax &lt; dateMax) { dateMax = rangeMax; } } } return { minDate: dateMin, maxDate: dateMax }; } </code></pre>
1,296,501
Find path to currently running file
<p>How can I find the full path to the currently running Python script? That is to say, what do I have to do to achieve this:</p> <pre><code>$ pwd /tmp $ python baz.py running from /tmp file is baz.py </code></pre>
1,297,407
8
1
null
2009-08-18 21:02:54.523 UTC
18
2019-08-01 06:45:03.24 UTC
2019-08-01 06:45:03.24 UTC
null
6,862,601
null
422
null
1
53
python
97,431
<p><strong><code>__file__</code> is NOT what you are looking for.</strong> Don't use accidental side-effects</p> <p><code>sys.argv[0]</code> is <strong>always</strong> the path to the script (if in fact a script has been invoked) -- see <a href="http://docs.python.org/library/sys.html#sys.argv" rel="noreferrer">http://docs.python.org/library/sys.html#sys.argv</a></p> <p><code>__file__</code> is the path of the <em>currently executing</em> file (script or module). This is <strong>accidentally</strong> the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use <code>sys.argv[0]</code>.</p> <p>Example:</p> <pre><code>C:\junk\so&gt;type \junk\so\scriptpath\script1.py import sys, os print "script: sys.argv[0] is", repr(sys.argv[0]) print "script: __file__ is", repr(__file__) print "script: cwd is", repr(os.getcwd()) import whereutils whereutils.show_where() C:\junk\so&gt;type \python26\lib\site-packages\whereutils.py import sys, os def show_where(): print "show_where: sys.argv[0] is", repr(sys.argv[0]) print "show_where: __file__ is", repr(__file__) print "show_where: cwd is", repr(os.getcwd()) C:\junk\so&gt;\python26\python scriptpath\script1.py script: sys.argv[0] is 'scriptpath\\script1.py' script: __file__ is 'scriptpath\\script1.py' script: cwd is 'C:\\junk\\so' show_where: sys.argv[0] is 'scriptpath\\script1.py' show_where: __file__ is 'C:\\python26\\lib\\site-packages\\whereutils.pyc' show_where: cwd is 'C:\\junk\\so' </code></pre>
502,002
How do I move a file to the Recycle Bin using PowerShell?
<p>When using the <code>rm</code> command to delete files in Powershell, they are permanently deleted.</p> <p>Instead of this, I would like to have the deleted item go to the recycle bin, like what happens when files are deleted through the UI.</p> <p>How can you do this in PowerShell?</p>
503,768
8
1
null
2009-02-02 01:47:04.373 UTC
18
2022-07-01 05:48:44.907 UTC
2022-07-01 05:48:44.907 UTC
null
13,710,015
null
1,496
null
1
54
powershell|recycle-bin
29,863
<p>Here is a shorter version that reduces a bit of work</p> <pre><code>$path = "&lt;path to file&gt;" $shell = new-object -comobject "Shell.Application" $item = $shell.Namespace(0).ParseName("$path") $item.InvokeVerb("delete") </code></pre>
426,609
How to assign Profile values?
<p>I don't know what I am missing, but I added Profile properties in the Web.config file but cannot access Profile.<em>Item</em> in the code or create a new profile.</p>
1,111,714
10
0
null
2009-01-09 00:16:58.267 UTC
71
2015-11-27 16:56:58.293 UTC
2010-05-22 12:50:31.777 UTC
null
6,068
zsharp
49,632
null
1
110
asp.net|asp.net-mvc|asp.net-membership|profile
60,379
<p>I had the same problem today, and learned a lot.</p> <p>There are two kinds of project in Visual Studio -- "Web Site Projects" and "Web Application Projects." For reasons which are a complete mystery to me, Web Application Projects cannot use <strong>Profile.</strong> directly... the strongly-typed class is not magically generated for you from the Web.config file, so you have to roll your own.</p> <p>The sample code in MSDN assumes you are using a Web Site Project, and they tell you just to add a <code>&lt;profile&gt;</code> section to your <code>Web.config</code> and party on with <code>Profile.</code><em>property</em>, but that doesn't work in Web Application Projects.</p> <p>You have two choices to roll your own:</p> <p>(1) Use the <a href="http://code.msdn.microsoft.com/WebProfileBuilder" rel="noreferrer">Web Profile Builder</a>. This is a custom tool you add to Visual Studio which automatically generates the Profile object you need from your definition in Web.config.</p> <p>I chose not to do this, because I didn't want my code to depend on this extra tool to compile, which could have caused problems for someone else down the line when they tried to build my code without realizing that they needed this tool.</p> <p>(2) Make your own class that derives from <code>ProfileBase</code> to represent your custom profile. This is easier than it seems. Here's a very very simple example that adds a "FullName" string profile field:</p> <p><em>In your web.config:</em></p> <pre><code>&lt;profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile"&gt; &lt;providers&gt; &lt;clear /&gt; &lt;add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="sqlServerMembership" /&gt; &lt;/providers&gt; &lt;/profile&gt; </code></pre> <p><em>In a file called AccountProfile.cs:</em></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Profile; using System.Web.Security; namespace YourNamespace { public class AccountProfile : ProfileBase { static public AccountProfile CurrentUser { get { return (AccountProfile) (ProfileBase.Create(Membership.GetUser().UserName)); } } public string FullName { get { return ((string)(base["FullName"])); } set { base["FullName"] = value; Save(); } } // add additional properties here } } </code></pre> <p><em>To set a profile value:</em></p> <pre><code>AccountProfile.CurrentUser.FullName = "Snoopy"; </code></pre> <p><em>To get a profile value</em></p> <pre><code>string x = AccountProfile.CurrentUser.FullName; </code></pre>
1,222,935
Why don't structs support inheritance?
<p>I know that structs in .NET do not support inheritance, but its not exactly clear <em>why</em> they are limited in this way.</p> <p>What technical reason prevents structs from inheriting from other structs?</p>
1,223,227
10
6
null
2009-08-03 15:19:50.493 UTC
41
2015-10-09 11:53:04.31 UTC
2009-08-03 22:26:48.237 UTC
null
82,118
null
40,516
null
1
139
.net|inheritance|struct
37,634
<p>The reason value types can't support inheritance is because of arrays.</p> <p>The problem is that, for performance and GC reasons, arrays of value types are stored "inline". For example, given <code>new FooType[10] {...}</code>, if <code>FooType</code> is a reference type, 11 objects will be created on the managed heap (one for the array, and 10 for each type instance). If <code>FooType</code> is instead a value type, only one instance will be created on the managed heap -- for the array itself (as each array value will be stored "inline" with the array).</p> <p>Now, suppose we had inheritance with value types. When combined with the above "inline storage" behavior of arrays, Bad Things happen, as can be seen <a href="https://isocpp.org/wiki/faq/proper-inheritance#array-derived-vs-base" rel="noreferrer">in C++</a>.</p> <p>Consider this pseudo-C# code:</p> <pre><code>struct Base { public int A; } struct Derived : Base { public int B; } void Square(Base[] values) { for (int i = 0; i &lt; values.Length; ++i) values [i].A *= 2; } Derived[] v = new Derived[2]; Square (v); </code></pre> <p>By normal conversion rules, a <code>Derived[]</code> is convertible to a <code>Base[]</code> (for better or worse), so if you s/struct/class/g for the above example, it'll compile and run as expected, with no problems. But if <code>Base</code> and <code>Derived</code> are value types, and arrays store values inline, then we have a problem.</p> <p>We have a problem because <code>Square()</code> doesn't know anything about <code>Derived</code>, it'll use only pointer arithmetic to access each element of the array, incrementing by a constant amount (<code>sizeof(A)</code>). The assembly would be vaguely like:</p> <pre><code>for (int i = 0; i &lt; values.Length; ++i) { A* value = (A*) (((char*) values) + i * sizeof(A)); value-&gt;A *= 2; } </code></pre> <p>(Yes, that's abominable assembly, but the point is that we'll increment through the array at known compile-time constants, without any knowledge that a derived type is being used.)</p> <p>So, if this actually happened, we'd have memory corruption issues. Specifically, within <code>Square()</code>, <code>values[1].A*=2</code> would <i>actually</i> be modifying <code>values[0].B</code>!</p> <p>Try to debug <em>THAT</em>!</p>
462,477
sql primary key and index
<p>Say I have an ID row (int) in a database set as the primary key. If I query off the ID often do I also need to index it? Or does it being a primary key mean it's already indexed?</p> <p>Reason I ask is because in MS SQL Server I can create an index on this ID, which as I stated is my primary key.</p> <p>Edit: an additional question - will it do any harm to additionally index the primary key?</p>
462,578
11
0
null
2009-01-20 18:28:00.21 UTC
18
2021-08-07 14:50:59.83 UTC
2020-09-17 12:29:05.953 UTC
danifo
1,080,354
danifo
56,302
null
1
112
sql|sql-server|tsql|indexing|primary-key
114,989
<p>You are right, it's confusing that SQL Server allows you to create duplicate indexes on the same field(s). But the fact that you can create another doesn't indicate that the PK index doesn't also already exist.</p> <p>The additional index does no good, but the only harm (very small) is the additional file size and row-creation overhead.</p>
326,062
In STL maps, is it better to use map::insert than []?
<p>A while ago, I had a discussion with a colleague about how to insert values in STL <a href="http://www.sgi.com/tech/stl/Map.html" rel="noreferrer">maps</a>. I preferred <code>map[key] = value;</code> because it feels natural and is clear to read whereas he preferred <code>map.insert(std::make_pair(key, value))</code>.</p> <p>I just asked him and neither of us can remember the reason why insert is better, but I am sure it was not just a style preference rather there was a technical reason such as efficiency. The <a href="http://www.sgi.com/tech/stl/Map.html" rel="noreferrer">SGI STL reference</a> simply says: &quot;Strictly speaking, this member function is unnecessary: it exists only for convenience.&quot;</p> <p>Can anybody tell me that reason, or am I just dreaming that there is one?</p>
327,289
13
6
null
2008-11-28 15:42:52.337 UTC
93
2020-08-10 12:33:10.85 UTC
2020-08-10 12:33:10.85 UTC
danio
2,675,154
danio
12,663
null
1
209
c++|dictionary|stl|insert|stdmap
164,481
<p>When you write</p> <pre><code>map[key] = value; </code></pre> <p>there's no way to tell if you <strong>replaced</strong> the <code>value</code> for <code>key</code>, or if you <strong>created</strong> a new <code>key</code> with <code>value</code>.</p> <p><a href="http://en.cppreference.com/w/cpp/container/map/insert" rel="noreferrer"><code>map::insert()</code></a> will only create:</p> <pre><code>using std::cout; using std::endl; typedef std::map&lt;int, std::string&gt; MyMap; MyMap map; // ... std::pair&lt;MyMap::iterator, bool&gt; res = map.insert(MyMap::value_type(key,value)); if ( ! res.second ) { cout &lt;&lt; "key " &lt;&lt; key &lt;&lt; " already exists " &lt;&lt; " with value " &lt;&lt; (res.first)-&gt;second &lt;&lt; endl; } else { cout &lt;&lt; "created key " &lt;&lt; key &lt;&lt; " with value " &lt;&lt; value &lt;&lt; endl; } </code></pre> <p>For most of my apps, I usually don't care if I'm creating or replacing, so I use the easier to read <code>map[key] = value</code>.</p>
171,326
How can I increase the key repeat rate beyond the OS's limit?
<p>I have a bad habit of using the cursor keys of my keyboard to navigate source code. It's something I've done for 15 years and this of course means that my navigating speed is limited by the speed of the keyboard. On both Vista and OS X (I dual boot a MacBook), I have my key repeat rate turned all the way up. But in Visual Studio, and other apps, the rate is still much slower than I would prefer.</p> <p>How can I make the key repeat rate faster in Visual Studio and other text editors?</p>
429,465
15
0
null
2008-10-05 01:33:28.903 UTC
33
2021-06-26 10:25:22.06 UTC
2016-10-06 11:49:10.01 UTC
ΤΖΩΤΖΙΟΥ
19,405
Frank Krueger
338
null
1
60
windows|visual-studio|macos|keyboard
44,605
<p>On Mac OS X, open the Global Preferences plist</p> <pre><code>open ~/Library/Preferences/.GlobalPreferences.plist </code></pre> <p>Then change the KeyRepeat field. Smaller numbers will speed up your cursor rate. The settings dialog will only set it to a minimum of 2, so if you go to 0 or 1, you'll get a faster cursor.</p> <p>I had to reboot for this to take effect.</p>
203,174
Is there a Java API that can create rich Word documents?
<p>I have a new app I'll be working on where I have to generate a Word document that contains tables, graphs, a table of contents and text. What's a good API to use for this? How sure are you that it supports graphs, ToCs, and tables? What are some hidden gotcha's in using them?</p> <p>Some clarifications:</p> <ul> <li>I can't output a PDF, they want a Word doc.</li> <li>They're using MS Word 2003 (or 2007), not OpenOffice</li> <li>Application is running on *nix app-server</li> </ul> <p>It'd be nice if I could start with a template doc and just fill in some spaces with tables, graphs, etc.</p> <p>Edit: Several good answers below, each with their own faults as far as my current situation. Hard to pick a "final answer" from them. Think I'll leave it open, and hope for better solutions to be created.</p> <p>Edit: The OpenOffice UNO project does seem to be closest to what I asked for. While POI is certainly more mainstream, it's too immature for what I want.</p>
257,001
16
4
null
2008-10-14 23:09:59.847 UTC
63
2018-09-21 02:16:19.643 UTC
2018-09-20 17:39:16.307 UTC
Bill James
4,815,184
Bill James
13,824
null
1
112
java|ms-word|docx|doc
155,294
<p>In 2007 my project successfully used OpenOffice.org's <a href="https://www.openoffice.org/udk/common/man/uno.html" rel="noreferrer">Universal Network Objects</a> (UNO) interface to programmatically generate MS-Word compatible documents (*.doc), as well as corresponding PDF documents, from a Java Web application (a Struts/JSP framework). </p> <p>OpenOffice UNO also lets you build MS-Office-compatible charts, spreadsheets, presentations, etc. We were able to dynamically build sophisticated Word documents, including charts and tables. </p> <p>We simplified the process by using template MS-Word documents with bookmark inserts into which the software inserted content, however, you can build documents completely from scratch. The goal was to have the software generate report documents that could be shared and further tweaked by end-users before converting them to PDF for final delivery and archival. </p> <p>You can optionally produce documents in OpenOffice formats if you want users to use OpenOffice instead of MS-Office. In our case the users want to use MS-Office tools. </p> <p>UNO is included within the OpenOffice suite. We simply linked our Java app to UNO-related libraries within the suite. An <a href="http://www.openoffice.org/download/sdk/" rel="noreferrer">OpenOffice Software Development Kit</a> (SDK) is available containing example applications and the UNO Developer's Guide.</p> <p>I have not investigated whether the latest OpenOffice UNO can generate MS-Office 2007 Open XML document formats.</p> <p>The important things about OpenOffice UNO are: </p> <ol> <li>It is freeware</li> <li>It supports multiple languages (e.g. Visual Basic, Java, C++, and others).</li> <li>It is platform-independent (Windows, Linux, Unix, etc.). </li> </ol> <p>Here are some useful web sites: </p> <ul> <li><a href="http://www.openoffice.org" rel="noreferrer">Open Office home</a></li> <li><a href="http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide" rel="noreferrer">Open Office UNO Developer's Guide</a></li> <li><a href="http://www.staroffice.org/developers.html" rel="noreferrer">OpenOffice Developer's Forum</a> (especially the "Macros and API" and "Code Snippets" forums).</li> </ul>
562,904
Clustering Algorithm for Paper Boys
<p>I need help selecting or creating a clustering algorithm according to certain criteria.</p> <p>Imagine you are managing newspaper delivery persons.</p> <ul> <li>You have a set of street addresses, each of which is geocoded.</li> <li>You want to cluster the addresses so that each cluster is assigned to a delivery person.</li> <li>The number of delivery persons, or clusters, is not fixed. If needed, I can always hire more delivery persons, or lay them off.</li> <li>Each cluster should have about the same number of addresses. However, a cluster may have less addresses if a cluster's addresses are more spread out. (Worded another way: minimum number of clusters where each cluster contains a maximum number of addresses, and any address within cluster must be separated by a maximum distance.)</li> <li>For bonus points, when the data set is altered (address added or removed), and the algorithm is re-run, it would be nice if the clusters remained as unchanged as possible (ie. this rules out simple k-means clustering which is random in nature). Otherwise the delivery persons will go crazy.</li> </ul> <p>So... ideas?</p> <p><strong>UPDATE</strong></p> <p>The street network graph, as described in Arachnid's answer, is not available.</p>
563,091
17
7
null
2009-02-18 21:25:06.177 UTC
24
2021-03-03 02:19:38.29 UTC
2009-03-05 15:34:09.983 UTC
carrier
20,498
carrier
20,498
null
1
34
algorithm|language-agnostic|cluster-analysis
5,532
<p>I think you want a <a href="http://en.wikipedia.org/wiki/Hierarchical_clustering#Hierarchical_clustering" rel="noreferrer">hierarchical agglomeration</a> technique rather than k-means. If you get your algorithm right you can stop it when you have the right number of clusters. As someone else mentioned you can seed subsequent clusterings with previous solutions which may give you a siginificant performance improvement.</p> <p>You may want to look closely at the distance function you use, especially if your problem has high dimension. Euclidean distance is the easiest to understand but may not be the best, look at alternatives such as Mahalanobis. </p> <p>I'm presuming that your real problem has nothing to do with delivering newspapers...</p>
1,334,143
DateTime2 vs DateTime in SQL Server
<p>Which one: </p> <ul> <li><a href="https://msdn.microsoft.com/en-us/library/ms187819.aspx" rel="noreferrer"><code>datetime</code></a></li> <li><a href="https://msdn.microsoft.com/en-us/library/bb677335.aspx" rel="noreferrer"><code>datetime2</code></a></li> </ul> <p>is <em>the</em> recommended way to store date and time in SQL Server 2008+?</p> <p>I'm aware of differences in precision (and storage space probably), but ignoring those for now, is there a best practice document on when to use what, or maybe we should just use <code>datetime2</code> only?</p>
1,884,088
17
0
null
2009-08-26 11:45:10.697 UTC
139
2022-09-11 11:22:47.607 UTC
2017-03-20 19:25:50.977 UTC
null
41,956
null
158,801
null
1
853
sql|sql-server|tsql|datetime|datetime2
602,718
<p>The MSDN documentation for <a href="http://technet.microsoft.com/en-us/library/ms187819.aspx" rel="noreferrer">datetime</a> recommends using <a href="http://technet.microsoft.com/en-us/library/bb677335.aspx" rel="noreferrer">datetime2</a>. Here is their recommendation:</p> <blockquote> <p>Use the <code>time</code>, <code>date</code>, <code>datetime2</code> and <code>datetimeoffset</code> data types for new work. These types align with the SQL Standard. They are more portable. <code>time</code>, <code>datetime2</code> and <code>datetimeoffset</code> provide more seconds precision. <code>datetimeoffset</code> provides time zone support for globally deployed applications.</p> </blockquote> <p>datetime2 has larger date range, a larger default fractional precision, and optional user-specified precision. Also depending on the user-specified precision it may use less storage. </p>
64,649
How do I get the find command to print out the file size with the file name?
<p>If I issue the <a href="https://en.wikipedia.org/wiki/Find_(Unix)" rel="noreferrer">find</a> command as follows:</p> <pre><code>find . -name *.ear </code></pre> <p>It prints out:</p> <pre><code>./dir1/dir2/earFile1.ear ./dir1/dir2/earFile2.ear ./dir1/dir3/earFile1.ear </code></pre> <p>I want to 'print' the name and the size to the command line:</p> <pre><code>./dir1/dir2/earFile1.ear 5000 KB ./dir1/dir2/earFile2.ear 5400 KB ./dir1/dir3/earFile1.ear 5400 KB </code></pre>
64,699
17
0
2009-05-06 04:08:09.053 UTC
2008-09-15 16:53:13.353 UTC
36
2022-01-18 17:28:20.773 UTC
2022-01-18 17:21:01.917 UTC
null
63,550
Brian
700
null
1
150
unix|command-line|find|solaris
192,304
<pre><code>find . -name '*.ear' -exec ls -lh {} \; </code></pre> <p>just the h extra from jer.drab.org's reply. saves time converting to MB mentally ;)</p>
1,262,737
IntelliJ IDEA way of editing multiple lines
<p>I've seen this done in TextMate and I was wondering if there's a way to do it in IDEA.</p> <p>Say I have the following code:</p> <pre><code> leaseLabel = "Lease"; leaseLabelPlural = "Leases"; portfolioLabel = "Portfolio"; portfolioLabelPlural = "Portfolios"; buildingLabel = "Building"; </code></pre> <p>What is the best way to append '+ "foo"' to every line? Column mode won't work since the lines are not correctly aligned on the right side... unless there is an easy way to right justify the text :P</p>
22,526,528
21
4
null
2009-08-11 20:29:55.74 UTC
41
2021-11-19 12:27:33.977 UTC
2020-01-28 19:07:20.137 UTC
null
974,045
null
125,491
null
1
186
java|android-studio|intellij-idea|ide|text-editor
149,794
<p>Since Idea IntelliJ IDEA 13.1 there is a possibility to edit multiple lines.</p> <h2>Windows</h2> <p><kbd>Alt</kbd> + <kbd>Shift</kbd> + Mouse click</p> <h2>macOS</h2> <p><kbd>Option</kbd> + <kbd>Shift</kbd> + Mouse click</p> <p>for selection. More about this new improvement in the IntelliJ blog post <a href="http://blog.jetbrains.com/idea/2014/03/intellij-idea-13-1-rc-introduces-sublime-text-style-multiple-selections/" rel="noreferrer">here</a>. Very useful feature.</p>
468,119
What's the best way to calculate the size of a directory in .NET?
<p>I've written the following routine to manually traverse through a directory and calculate its size in C#/.NET:</p> <pre> <code> protected static float CalculateFolderSize(string folder) { float folderSize = 0.0f; try { //Checks if the path is valid or not if (!Directory.Exists(folder)) return folderSize; else { try { foreach (string file in Directory.GetFiles(folder)) { if (File.Exists(file)) { FileInfo finfo = new FileInfo(file); folderSize += finfo.Length; } } foreach (string dir in Directory.GetDirectories(folder)) folderSize += CalculateFolderSize(dir); } catch (NotSupportedException e) { Console.WriteLine("Unable to calculate folder size: {0}", e.Message); } } } catch (UnauthorizedAccessException e) { Console.WriteLine("Unable to calculate folder size: {0}", e.Message); } return folderSize; } </code> </pre> <p>I have an application which is running this routine repeatedly for a large number of folders. I'm wondering if there's a more efficient way to calculate the size of a folder with .NET? I didn't see anything specific in the framework. Should I be using P/Invoke and a Win32 API? What's the most efficient way of calculating the size of a folder in .NET?</p>
468,143
23
0
null
2009-01-22 05:21:16.647 UTC
22
2022-07-07 11:12:49.033 UTC
null
null
null
Steve W
3,429
null
1
86
c#|.net|windows
121,547
<p>I do not believe there is a Win32 API to calculate the space consumed by a directory, although I stand to be corrected on this. If there were then I would assume Explorer would use it. If you get the Properties of a large directory in Explorer, the time it takes to give you the folder size is proportional to the number of files/sub-directories it contains.</p> <p>Your routine seems fairly neat &amp; simple. Bear in mind that you are calculating the sum of the file lengths, not the actual space consumed on the disk. Space consumed by wasted space at the end of clusters, file streams etc, are being ignored.</p>
6,979,747
Read stdin stream in a batch file
<p>Is it possible to use a piped stdin stream inside a batch file?</p> <p>I want to be able to redirect the output of one command into my batch file <code>process.bat</code> list so:</p> <pre><code>C:\&gt;someOtherProgram.exe | process.bat </code></pre> <p>My first attempt looked like:</p> <pre><code>echo OFF setlocal :again set /p inputLine="" echo.%inputLine% if not (%inputLine%)==() goto again endlocal :End </code></pre> <p>When I test it with <code>type testFile.txt | process.bat</code> it prints out the first line repeatedly.</p> <p>Is there another way?</p>
6,980,605
4
1
null
2011-08-08 08:57:47.633 UTC
12
2022-03-09 06:41:04.44 UTC
2013-06-05 10:16:08.23 UTC
null
611,007
null
305,264
null
1
38
windows|batch-file|stdout|stdin
34,903
<p><code>set /p</code> doesn't work with pipes, it takes one (randomly) line from the input.<br /> But you can use <code>more</code> inside of an for-loop.</p> <pre><code>@echo off setlocal for /F &quot;tokens=*&quot; %%a in ('more') do ( echo #%%a ) </code></pre> <p>But this fails with lines beginning with a semicolon (as the FOR-LOOP-standard of eol is <code>;</code>).<br /> And it can't read empty lines.<br /> But with findstr you can solve this too, it prefix each line with the linenumber, so you never get empty lines.<br /> And then the prefix is removed to the first colon.</p> <pre><code>@echo off setlocal DisableDelayedExpansion for /F &quot;tokens=*&quot; %%a in ('findstr /n &quot;^&quot;') do ( set &quot;line=%%a&quot; setlocal EnableDelayedExpansion set &quot;line=!line:*:=!&quot; echo(!line! endlocal ) </code></pre> <p>Alternatively, on some environments (like WinRE) that don't include <code>findstr</code>, an alternative with <code>find.exe</code> might suffice. <code>find</code> will accept a null search string <code>&quot;&quot;</code>, and allows search inversion. This would allow something like this:</p> <pre><code>@echo off setlocal DisableDelayedExpansion for /F &quot;tokens=*&quot; %%a in ('find /v &quot;&quot;') do ( ... </code></pre>
6,895,098
PDO/MySQL memory consumption with large result set
<p>I'm having a strange time dealing with selecting from a table with about 30,000 rows.</p> <p>It seems my script is using an outrageous amount of memory for what is a simple, forward only walk over a query result.</p> <p>Please note that this example is a somewhat contrived, absolute bare minimum example which bears very little resemblance to the real code and it cannot be replaced with a simple database aggregation. It is intended to illustrate the point that each row does not need to be retained on each iteration.</p> <pre><code>&lt;?php $pdo = new PDO('mysql:host=127.0.0.1', 'foo', 'bar', array( PDO::ATTR_ERRMODE=&gt;PDO::ERRMODE_EXCEPTION, )); $stmt = $pdo-&gt;prepare('SELECT * FROM round'); $stmt-&gt;execute(); function do_stuff($row) {} $c = 0; while ($row = $stmt-&gt;fetch()) { // do something with the object that doesn't involve keeping // it around and can't be done in SQL do_stuff($row); $row = null; ++$c; } var_dump($c); var_dump(memory_get_usage()); var_dump(memory_get_peak_usage()); </code></pre> <p>This outputs:</p> <pre><code>int(39508) int(43005064) int(43018120) </code></pre> <p>I don't understand why 40 meg of memory is used when hardly any data needs to be held at any one time. I have already worked out I can reduce the memory by a factor of about 6 by replacing "SELECT *" with "SELECT home, away", however I consider even this usage to be insanely high and the table is only going to get bigger.</p> <p>Is there a setting I'm missing, or is there some limitation in PDO that I should be aware of? I'm happy to get rid of PDO in favour of mysqli if it can not support this, so if that's my only option, how would I perform this using mysqli instead?</p>
6,935,271
5
1
null
2011-08-01 06:59:39.8 UTC
12
2013-05-12 21:15:25.11 UTC
2011-08-04 01:54:28.75 UTC
null
15,004
null
15,004
null
1
25
php|mysql|pdo
25,584
<p>After creating the connection, you need to set <a href="http://www.php.net/manual/en/ref.pdo-mysql.php" rel="noreferrer"><code>PDO::MYSQL_ATTR_USE_BUFFERED_QUERY</code></a> to false:</p> <pre><code>&lt;?php $pdo = new PDO('mysql:host=127.0.0.1', 'foo', 'bar', array( PDO::ATTR_ERRMODE=&gt;PDO::ERRMODE_EXCEPTION, )); $pdo-&gt;setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); // snip var_dump(memory_get_usage()); var_dump(memory_get_peak_usage()); </code></pre> <p>This outputs:</p> <pre><code>int(39508) int(653920) int(668136) </code></pre> <p>Regardless of the result size, the memory usage remains pretty much static.</p>
6,329,468
How to create a HTTP server in Android?
<p>I would like to create a simple HTTP server in Android for serving some content to a client.</p> <p>Any advice on how to build the server or use any existing library? </p>
6,329,508
6
1
null
2011-06-13 10:52:36.263 UTC
70
2020-09-09 10:09:12.66 UTC
2016-05-21 14:48:54.26 UTC
null
4,717,992
null
217,527
null
1
127
android|http
151,313
<p>Consider this one: <a href="https://github.com/NanoHttpd/nanohttpd" rel="noreferrer">https://github.com/NanoHttpd/nanohttpd</a>. Very small, written in Java. I used it without any problem.</p>
6,390,138
Combining multiple conditional expressions in C#
<p>In C#, instead of doing <code>if(index == 7 || index == 8)</code>, is there a way to combine them? I'm thinking of something like <code>if(index == (7, 8))</code>.</p>
6,390,220
9
4
null
2011-06-17 18:28:17.61 UTC
16
2014-10-22 00:18:32.543 UTC
null
null
null
null
759,705
null
1
23
c#|conditional-statements
3,899
<p>You can accomplish this with an extension method.</p> <pre><code>public static bool In&lt;T&gt;(this T obj, params T[] collection) { return collection.Contains(obj); } </code></pre> <p>Then...</p> <pre><code>if(index.In(7,8)) { ... } </code></pre>
6,751,920
Tomcat 7 - Servlet 3.0: Invalid byte tag in constant pool
<ul> <li>tomcat 7.0.16 </li> <li>Java 1.6.0_22 </li> <li>CentOS 5.6</li> </ul> <p>I just switched the web.xml to servlet 3.0 (from a app running 2.4 previously) and now I'm seeing the following error (turned on fine logging for org.apache.tomcat.util):</p> <pre><code>mtyson FINE: Scanning JAR [file:/usr/java/jdk1.6.0_22/jre/lib/ext/jcharset.jar] from classpath mtyson Jul 19, 2011 10:04:40 AM org.apache.catalina.startup.HostConfig deployDirectory mtyson SEVERE: Error deploying web application directory ROOT mtyson org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 60 </code></pre> <p><em>UPDATE:</em> Just Tried tomcat 7.0.19 - same results</p>
6,765,398
11
1
null
2011-07-19 18:07:46.55 UTC
14
2022-06-23 09:53:31.747 UTC
2011-07-20 00:39:49.653 UTC
null
467,240
null
467,240
null
1
33
tomcat7|servlet-3.0
104,478
<p>It may not be your issue, but mine was the <a href="http://maven.40175.n5.nabble.com/Problem-when-mvn-site-site-Generating-quot-Dependencies-quot-report-td113470.html" rel="nofollow noreferrer">same as this one</a> -- an old version of <code>com.ibm.icu:icu4j</code>. I solved the problem by changing my build configuration to exclude the older transitive dependencies and explicitly depending upon the latest version (4.8).</p>
15,700,148
Getting value from html radio button - in aspx-c#
<p>I have the following HTML source</p> <pre><code>&lt;form name="Register1" action="Register.aspx" id="registerform" method="post" runat="server" style="margin-top: 15px;"&gt; &lt;input type="radio" name="Gender" value="male" /&gt;male &lt;input type="radio" name="Gender" value="female" /&gt;female &lt;/form&gt; </code></pre> <p>My question is how can I get the selected value to variable in the c# page?</p> <p>I tried this : </p> <pre><code>Gender = Request.Form["Gender"].ToString(); </code></pre> <p>But it didn't work...</p>
15,700,330
4
4
null
2013-03-29 08:56:37.337 UTC
9
2018-10-22 10:33:48.86 UTC
2013-03-29 09:31:01.21 UTC
null
184,842
null
1,873,436
null
1
13
c#|asp.net|html|radio-button|radiobuttonlist
76,943
<p>place your code like this:</p> <pre><code> if (Request.Form["Gender"] != null) { string selectedGender = Request.Form["Gender"].ToString(); } </code></pre> <p>Note that <code>Request.Form["Gender"]</code> will be null if none of the RadioButtons are selected.</p> <p>see the markup below</p> <pre><code>&lt;form id="form1" runat="server" method="post"&gt; &lt;input type="radio" name="Gender" value="male" id="test" checked="checked" /&gt; male &lt;input type="radio" name="Gender" value="female" /&gt;female &lt;input type="submit" value="test" /&gt; &lt;asp:Button ID="btn" runat="server" Text="value" /&gt; &lt;/form&gt; </code></pre> <p>for both the buttons i.e <code>input type="submit"</code> and usual <code>asp:button</code>, <code>Request.Form["Gender"]</code> is going to have some value upon <code>PostBack</code>, provided, either of the RadioButtons is selected.</p> <p>And yes, upon <code>PostBack</code> only, i.e. when you hit either of the buttons and not on first load.</p>
15,726,795
Offsetting Anchor Links with Fixed Header
<p>There've been a few similar posts (<a href="https://stackoverflow.com/questions/10732690/offsetting-an-html-anchor-to-adjust-for-fixed-header">offsetting an html anchor to adjust for fixed header</a>, for example), but those solution doesn't work for my particular case.</p> <p>I am using jQuery to populate a Table of Contents, specifically the method described here: <a href="http://css-tricks.com/automatic-table-of-contents/" rel="noreferrer">http://css-tricks.com/automatic-table-of-contents/</a>. It searches for the h2 tags within the article, and then creates anchors links.</p> <p>The problem is I'm using a fixed header. When I click on one of these anchor links, the target h2 is <em>underneath</em> the header. One temporary solution I'm using is:</p> <pre><code>h2:target{ padding-top:[header-height]; } </code></pre> <p>This works until you scroll back up, and there's a huge gap in the middle of the content. Do y'all have any ideas on how I can offset these anchor links to account for the header? I'd like to keep the HTML as semantic as possible. Any help would be appreciated.</p> <p><strong>Here's a jsFiddle of what exactly I'm talking about: <a href="http://jsfiddle.net/aweber9/GbNFv/" rel="noreferrer">http://jsfiddle.net/aweber9/GbNFv/</a></strong></p> <p>Thanks.</p>
15,726,864
5
0
null
2013-03-31 05:55:36.1 UTC
10
2020-11-26 05:45:56.56 UTC
2017-05-23 12:34:10.563 UTC
null
-1
null
1,562,018
null
1
16
jquery|html|css|header
28,652
<p>You could include <code>padding-top</code> and then use negative <code>margin-top</code> to balance it out.</p> <p><a href="http://jsfiddle.net/Tyriar/pp9dg/">jsFiddle</a></p> <pre><code>h2 { padding-top: 70px; margin-top: -70px; } </code></pre>
15,532,667
ASP.NET+Azure 400 Bad Request doesn't return JSON data
<p>There is an action in my ASP.NET MVC controller that returns JSON data with a 400 Bad Request when invalid parameters are passed to the action.</p> <pre><code>[HttpDelete] public ActionResult RemoveObject(string id) { if(!Validate(id)) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { message = "Failed", description = "More details of failure" }); } } </code></pre> <p>This works perfectly running under IIS or with the development test server launched from Visual Studio. After the project has been deployed to Azure the 400 Bad Request comes back without the JSON data. The content type has changed to 'text/html' and 'Bad Request' for the message.</p> <p>Why is the behavior different under Azure?</p>
15,532,685
1
0
null
2013-03-20 19:14:10.003 UTC
14
2013-03-20 19:15:03.013 UTC
null
null
null
null
1,698,415
null
1
30
asp.net-mvc|azure
7,445
<p>Add the following entry to your 'web.config'.</p> <pre><code>&lt;system.webServer&gt; &lt;httpErrors existingResponse="PassThrough"/&gt; &lt;/system.webServer&gt; </code></pre> <p>This will allow HTTP errors to pass through un-molested.</p>
35,988,315
Convert Java List to Scala Seq
<p>I need to implement a method that returns a Scala <code>Seq</code>, in Java.</p> <p>But I encounter this error:</p> <pre><code>java.util.ArrayList cannot be cast to scala.collection.Seq </code></pre> <p>Here is my code so far:</p> <pre><code>@Override public Seq&lt;String&gt; columnNames() { List&lt;String&gt; a = new ArrayList&lt;String&gt;(); a.add("john"); a.add("mary"); Seq&lt;String&gt; b = (scala.collection.Seq&lt;String&gt;) a; return b; } </code></pre> <p>But <code>scala.collection.JavaConverters</code> doesn't seem to offer the possibility to convert as a <code>Seq</code>.</p>
35,988,913
7
5
null
2016-03-14 13:02:04.783 UTC
6
2022-01-03 10:30:04.063 UTC
2020-02-03 16:11:12.483 UTC
null
4,708,077
null
4,708,077
null
1
43
java|scala|seq|scala-java-interop
68,350
<p>JavaConverters is what I needed to solve this.</p> <pre><code>import scala.collection.JavaConverters; public Seq&lt;String&gt; convertListToSeq(List&lt;String&gt; inputList) { return JavaConverters.asScalaIteratorConverter(inputList.iterator()).asScala().toSeq(); } </code></pre>
10,434,736
Difference between BufferedReader and BufferedInputStream
<p>What are the differences between <code>BufferedReader</code> , <code>BufferedInputStream</code> and <code>Scanner</code> in java? <code>BufferedReader</code> reads the text and <code>BufferedInputStream</code> reads <code>byte</code>. Is there any difference other than this?</p>
10,434,770
2
3
null
2012-05-03 15:39:54.533 UTC
7
2017-03-24 12:12:37.563 UTC
2017-03-24 12:12:37.563 UTC
null
3,151,210
null
1,357,722
null
1
31
java|io|java.util.scanner|bufferedreader
22,523
<p>I guess, the difference is the same as between reader and inputstream: one is character-based, another is byte-based. For example, reader normally supports encoding...</p> <p><strong>Edit:</strong> Check this question: <a href="https://stackoverflow.com/questions/5764065/inputstream-and-reader-in-java-io">The difference between InputStream and InputStreamReader when reading multi-byte characters</a></p>
37,827,073
Does this 'for' loop stop, and why/why not? for (var i=0; 1/i > 0; i++) { }
<p>Does this <code>for</code> loop ever stop?</p> <pre><code>for (var i=0; 1/i &gt; 0; i++) { } </code></pre> <p>If so, when and why? I was told that it stops, but I was given no reason for that.</p> <h3>Upddate</h3> <p>As part of the investigation I've written quite lengthy and detailed article that explains everything what's going on under the hood - <a href="https://medium.com/the-node-js-collection/javascripts-number-type-8d59199db1b6" rel="nofollow noreferrer">Here is what you need to know about JavaScript’s Number type</a></p>
37,830,614
3
12
null
2016-06-15 05:48:26.003 UTC
30
2017-08-08 09:59:25.627 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,545,680
null
1
103
javascript
7,628
<p><em>(I'm not a fan of meta-content, but: <a href="https://stackoverflow.com/a/37827271/157247">gotnull's</a> and <a href="https://stackoverflow.com/a/37827313/157247">le_m's</a> answers are both correct and useful. They were originally, and are <strong>even more so</strong> with the edits made after this Community Wiki was posted. The original motivation for this CW is largely gone as a result of those edits, but it remains useful, so... Also: While there are only a couple of authors listed, many other community members have helped greatly with comments which have been folded in and cleaned up. This isn't just a CW in name.)</em></p> <hr> <p>The loop won't stop in a correctly-implemented JavaScript engine. <em>(The engine's host environment might eventually terminate it because it's endless, but that's another thing.)</em></p> <p>Here's why:</p> <ol> <li><p>Initially, when <code>i</code> is <code>0</code>, the condition <code>1/i &gt; 0</code> is true because in JavaScript, <code>1/0</code> is <code>Infinity</code>, and <code>Infinity &gt; 0</code> is true.</p></li> <li><p>After that, <code>i</code> will be incremented and continue to grow as a positive integer value for a long time (a further 9,007,199,254,740,991 iterations). In all of those cases, <code>1/i</code> will remain <code>&gt; 0</code> (although the values for <code>1/i</code> get <strong>really</strong> small toward the end!) and so the loop continues up to and including the loop where <code>i</code> reaches the value <code>Number.MAX_SAFE_INTEGER</code>.</p></li> <li><p>Numbers in JavaScript are IEEE-754 double-precision binary floating point, a fairly compact format (64 bits) which provides for fast calculations and a vast range. It does this by storing the number as a sign bit, an 11-bit exponent, and a 52-bit significand (although through cleverness it actually gets 53 bits of precision). It's <em>binary</em> (base 2) floating point: The significand (plus some cleverness) gives us the value, and the exponent gives us the magnitude of the number.</p> <p>Naturally, with just so many significant bits, not every number can be stored. Here is the number 1, and the next highest number after 1 that the format can store, 1 + 2<sup>-52</sup> ≈ 1.00000000000000022, and the next highest after that 1 + 2 × 2<sup>-52</sup> ≈ 1.00000000000000044:</p> <pre> &nbsp;&nbsp;&nbsp;+--------------------------------------------------------------- sign bit &nbsp;&nbsp;/ +-------+------------------------------------------------------ exponent &nbsp;/ / | +-------------------------------------------------+- significand / / | / | 0 01111111111 0000000000000000000000000000000000000000000000000000 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= 1 0 01111111111 0000000000000000000000000000000000000000000000000001 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;≈ 1.00000000000000022 0 01111111111 0000000000000000000000000000000000000000000000000010 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;≈ 1.00000000000000044 </pre> <p>Note the jump from 1.00000000000000022 to 1.00000000000000044; there's no way to store 1.0000000000000003. That can happen with integers, too: <code>Number.MAX_SAFE_INTEGER</code> (9,007,199,254,740,991) is the highest positive integer value that the format can hold where <code>i</code> and <code>i + 1</code> are both exactly representable (<a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-number.max_safe_integer" rel="nofollow noreferrer">spec</a>). Both 9,007,199,254,740,991 and 9,007,199,254,740,992 can be represented, but the <em>next</em> integer, 9,007,199,254,740,993, cannot; the next integer we can represent after 9,007,199,254,740,992 is 9,007,199,254,740,994. Here are the bit patterns, note the rightmost (least significant) bit:</p> <pre> &nbsp;&nbsp;&nbsp;+--------------------------------------------------------------- sign bit &nbsp;&nbsp;/ +-------+------------------------------------------------------ exponent &nbsp;/ / | +-------------------------------------------------+- significand / / | / | 0 10000110011 1111111111111111111111111111111111111111111111111111 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= 9007199254740991 (Number.MAX_SAFE_INTEGER) 0 10000110100 0000000000000000000000000000000000000000000000000000 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= 9007199254740992 (Number.MAX_SAFE_INTEGER + 1) x xxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;9007199254740993 (Number.MAX_SAFE_INTEGER + 2) can't be stored 0 10000110100 0000000000000000000000000000000000000000000000000001 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;= 9007199254740994 (Number.MAX_SAFE_INTEGER + 3) </pre> <p>Remember, the format is base 2, and with that exponent the least significant bit is no longer fractional; it has a value of 2. It can be off (9,007,199,254,740,992) or on (9,007,199,254,740,994); so at this point, we've started to lose precision even at the whole number (integer) scale. Which has implications for our loop!</p></li> <li><p>After completing the <code>i = 9,007,199,254,740,992</code> loop, <code>i++</code> gives us ... <code>i = 9,007,199,254,740,992</code> again; there's no change in <code>i</code>, because the next integer can't be stored and the calculation ends up rounding down. <code>i</code> would change if we did <code>i += 2</code>, but <code>i++</code> can't change it. So we've reached steady-state: <code>i</code> never changes, and the loop never terminates.</p></li> </ol> <p>Here are the various relevant calculations:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>if (!Number.MAX_SAFE_INTEGER) { // Browser doesn't have the Number.MAX_SAFE_INTEGER // property; shim it. Should use Object.defineProperty // but hey, maybe it's so old it doesn't have that either Number.MAX_SAFE_INTEGER = 9007199254740991; } var i = 0; console.log(i, 1/i, 1/i &gt; 0); // 0, Infinity, true i++; console.log(i, 1/i, 1/i &gt; 0); // 1, 1, true // ...eventually i is incremented all the way to Number.MAX_SAFE_INTEGER i = Number.MAX_SAFE_INTEGER; console.log(i, 1/i, 1/i &gt; 0); // 9007199254740991 1.1102230246251568e-16, true i++; console.log(i, 1/i, 1/i &gt; 0); // 9007199254740992 1.1102230246251565e-16, true i++; console.log(i, 1/i, 1/i &gt; 0); // 9007199254740992 1.1102230246251565e-16, true (no change) console.log(i == i + 1); // true</code></pre> </div> </div> </p>
41,135,875
Unable to simulate keypress event in Angular 2 unit test (Jasmine)
<p>I am using a directive to get the data from input used as a filter text.</p> <p>here is my hostlistener in the directive:</p> <pre><code>@HostListener('input', ['$event.target.value']) public onChangeFilter(event: any): void { console.log('input event fired, value: ' + event); this.columnFiltering.filterString = event; this.filterChanged.emit({filtering: this.columnFiltering}); } </code></pre> <p>this code is working perfectly, I am unable to unit test the same.</p> <p>I have subscribed to the filterChanged EventEmitter, in my unit test to check the value. </p> <p>I tried simulating keypress event to change value and also tried settings value attribute. None of these is working for me.</p> <p>here is my spec file:</p> <pre><code>describe('Table View', () =&gt; { let fixture: ComponentFixture&lt;any&gt;; let context: TableComponent; beforeEach(() =&gt; { TestBed.configureTestingModule({ providers: [ TableComponent, ], imports: [TableModule], }); fixture = TestBed.createComponent(TableComponent); context = fixture.componentInstance; }); it('should allow filter', () =&gt; { const element = fixture.nativeElement; context.config = config; fixture.detectChanges(); let tableChangeCount = 0; let tableEvent: any; context.tableChanged.subscribe((event: any) =&gt; { tableChangeCount++; tableEvent = event; }); // Check if table exists let inputElement = element.querySelectorAll('tr')[1].querySelector('input'); let e = new KeyboardEvent("keypress", { key: "a", bubbles: true, cancelable: true, }); inputElement.dispatchEvent(e); }); }); </code></pre> <p>I tried setting value:</p> <pre><code>let attrs = inputElement.attributes; inputElement.setAttribute('value', 'abc'); for (let i = attrs.length - 1; i &gt;= 0; i--) { // Attribute value is set correctly if (attrs[i].name === 'value') { console.log(attrs[i].name + "-&gt;" + attrs[i].value); } } </code></pre> <p>Can anyone please help me, how can I unit test the same?</p>
42,156,063
3
8
null
2016-12-14 06:05:28.037 UTC
4
2021-02-16 12:46:17.093 UTC
2016-12-14 06:13:12.4 UTC
null
1,124,913
null
1,124,913
null
1
35
unit-testing|angular|input|jasmine|keypress
51,148
<p>I've had some trouble simulating a keypress in a unit test also. But came across an answer by Seyed Jalal Hosseini. It might be what you're after.</p> <p>If you're attempting to simulate a keypress you can trigger an event by calling <code>dispatchEvent(new Event('keypress'));</code> on the element.</p> <p>Here is the answer I'm referring to which gives more detail : <a href="https://stackoverflow.com/a/37956877/4081730">https://stackoverflow.com/a/37956877/4081730</a> </p> <p>If you want to set the key that was pressed, this can be done also.</p> <pre><code>const event = new KeyboardEvent("keypress",{ "key": "Enter" }); el.dispatchEvent(event); </code></pre> <p>Further information I've just come across: <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events</a></p>
13,296,461
(Im)perfect forwarding with variadic templates
<h1>Synopsis</h1> <p>Given a type with a variadic template constructor that forwards the arguments to an implementation class, is it possible to restrict the types being forwarded with SFINAE?</p> <h1>Details</h1> <p>First, consider the non-variadic case with a constructor taking a universal reference. Here one can disable forwarding of a non-const lvalue reference via SFINAE to use the copy constructor instead.</p> <pre><code>struct foo { foo() = default; foo(foo const&amp;) { std::cout &lt;&lt; &quot;copy&quot; &lt;&lt; std::endl; } template &lt; typename T, typename Dummy = typename std::enable_if&lt; !std::is_same&lt; T, typename std::add_lvalue_reference&lt;foo&gt;::type &gt;::value &gt;::type &gt; foo(T&amp;&amp; x) : impl(std::forward&lt;T&gt;(x)) { std::cout &lt;&lt; &quot;uref&quot; &lt;&lt; std::endl; } foo_impl impl; }; </code></pre> <p>This restriction of the universal reference is useful because otherwise the implementation class would receive a non-const lvalue reference of type <code>foo</code>, which it does not know about. Full example <a href="https://web.archive.org/web/20160304221013/http://liveworkspace.org/code/32662d3222396202a9bdb6e9703bc8d1" rel="nofollow noreferrer">at LWS</a>.</p> <h1>Question</h1> <p>But how does this work with variadic templates? Is it possible at all? If so, how? The naive extension does not work:</p> <pre><code>template &lt; typename... Args, typename Dummy = typename std::enable_if&lt; !std::is_same&lt; Args..., typename std::add_lvalue_reference&lt;foo&gt;::type &gt;::value &gt;::type &gt; foo(Args&amp;&amp;... args) : impl(std::forward&lt;Args&gt;(args)...) { std::cout &lt;&lt; &quot;uref&quot; &lt;&lt; std::endl; } </code></pre> <p>(Also <a href="https://web.archive.org/web/20160305062022/http://liveworkspace.org/code/98da783837eb749ff561b45792a9f3fe" rel="nofollow noreferrer">at LWS</a>.)</p> <p><em>EDIT:</em> I found that R. Martinho Fernandez blogged about a variation of this issue in 2012: <a href="https://web.archive.org/web/20141205121901/http://flamingdangerzone.com:80/cxx11/2012/06/05/is_related.html" rel="nofollow noreferrer">Link</a></p>
13,328,507
2
1
null
2012-11-08 19:38:30.29 UTC
8
2022-06-15 20:02:19.547 UTC
2022-06-15 20:02:19.547 UTC
null
4,751,173
null
1,170,277
null
1
14
c++|c++11|variadic-templates|sfinae|variadic-functions
2,566
<p>Here are the different ways to write a properly constrained constructor template, in increasing order of complexity and corresponding increasing order of feature-richness and decreasing order of number of gotchas.</p> <p><a href="https://rmf.io/cxx11/almost-static-if/" rel="nofollow">This particular form of EnableIf</a> will be used but this is an implementation detail that doesn't change the essence of the techniques that are outlined here. It's also assumed that there are <code>And</code> and <code>Not</code> aliases to combine different metacomputations. E.g. <code>And&lt;std::is_integral&lt;T&gt;, Not&lt;is_const&lt;T&gt;&gt;&gt;</code> is more convenient than <code>std::integral_constant&lt;bool, std::is_integral&lt;T&gt;::value &amp;&amp; !is_const&lt;T&gt;::value&gt;</code>.</p> <p>I don't recommend any particular strategy, because <em>any</em> constraint is much, much better than no constraint at all when it comes to constructor templates. If possible, avoid the first two techniques which have very obvious drawbacks -- the rest are elaborations on the same theme.</p> <h2>Constrain on self</h2> <pre><code>template&lt;typename T&gt; using Unqualified = typename std::remove_cv&lt; typename std::remove_reference&lt;T&gt;::type &gt;::type; struct foo { template&lt; typename... Args , EnableIf&lt; Not&lt;std::is_same&lt;foo, Unqualified&lt;Args&gt;&gt;...&gt; &gt;... &gt; foo(Args&amp;&amp;... args); }; </code></pre> <p><strong>Benefit:</strong> avoids the constructor from participating in overload resolution in the following scenario:</p> <pre><code>foo f; foo g = f; // typical copy constructor taking foo const&amp; is not preferred! </code></pre> <p><strong>Drawback</strong>: participates in <em>every</em> other kind of overload resolution</p> <h2>Constrain on construction expression</h2> <p>Since the constructor has the moral effects of constructing a <code>foo_impl</code> from <code>Args</code>, it seems natural to express the constraints on those exact terms:</p> <pre><code> template&lt; typename... Args , EnableIf&lt; std::is_constructible&lt;foo_impl, Args...&gt; &gt;... &gt; foo(Args&amp;&amp;... args); </code></pre> <p><strong>Benefit:</strong> This is now officially a constrained template, since it only participates in overload resolution if some semantic condition is met.</p> <p><strong>Drawback:</strong> Is the following valid?</p> <pre><code>// function declaration void fun(foo f); fun(42); </code></pre> <p>If, for instance, <code>foo_impl</code> is <code>std::vector&lt;double&gt;</code>, then yes, the code is valid. Because <code>std::vector&lt;double&gt; v(42);</code> is a valid way to <em>construct</em> a vector of such type, then it is valid to <em>convert</em> from <code>int</code> to <code>foo</code>. In other words, <code>std::is_convertible&lt;T, foo&gt;::value == std::is_constructible&lt;foo_impl, T&gt;::value</code>, putting aside the matter of other constructors for <code>foo</code> (mind the swapped order of parameters -- it is unfortunate).</p> <h3>Constrain on construction expression, explicitly</h3> <p>Naturally, the following comes immediately to mind:</p> <pre><code> template&lt; typename... Args , EnableIf&lt; std::is_constructible&lt;foo_impl, Args...&gt; &gt;... &gt; explicit foo(Args&amp;&amp;... args); </code></pre> <p>A second attempt that marks the constructor <code>explicit</code>.</p> <p><strong>Benefit:</strong> Avoids the above drawback! And it doesn't take much either -- as long as you don't forget that <code>explicit</code>.</p> <p><strong>Drawbacks:</strong> If <code>foo_impl</code> is <code>std::string</code>, then the following may be inconvenient:</p> <pre><code>void fun(foo f); // No: // fun("hello"); fun(foo { "hello" }); </code></pre> <p>It depends on whether <code>foo</code> is for instance meant to be a thin wrapper around <code>foo_impl</code>. Here is what I think is a more annoying drawback, assuming <code>foo_impl</code> is <code>std::pair&lt;int, double*&gt;</code>.</p> <pre><code>foo make_foo() { // No: // return { 42, nullptr }; return foo { 42, nullptr }; } </code></pre> <p>I don't feel like <code>explicit</code> actually saves me from anything here: there are two arguments in the braces so it's obviously not a conversion, and the type <code>foo</code> already appears in the signature, so I'd like to spare with it when I feel it is redundant. <code>std::tuple</code> suffers from that problem (although factories like <code>std::make_tuple</code> do ease that pain a bit).</p> <h2>Separately constrain conversion from construction</h2> <p>Let's separately express <em>construction</em> and <em>conversion</em> constraints:</p> <pre><code>// New trait that describes e.g. // []() -&gt; T { return { std::declval&lt;Args&gt;()... }; } template&lt;typename T, typename... Args&gt; struct is_perfectly_convertible_from: std::is_constructible&lt;T, Args...&gt; {}; template&lt;typename T, typename U&gt; struct is_perfectly_convertible_from: std::is_convertible&lt;U, T&gt; {}; // New constructible trait that will take care that as a constraint it // doesn't overlap with the trait above for the purposes of SFINAE template&lt;typename T, typename U&gt; struct is_perfectly_constructible : And&lt; std::is_constructible&lt;T, U&gt; , Not&lt;std::is_convertible&lt;U, T&gt;&gt; &gt; {}; </code></pre> <p>Usage:</p> <pre><code>struct foo { // General constructor template&lt; typename... Args , EnableIf&lt; is_perfectly_convertible_from&lt;foo_impl, Args...&gt; &gt;... &gt; foo(Args&amp;&amp;... args); // Special unary, non-convertible case template&lt; typename Arg , EnableIf&lt; is_perfectly_constructible&lt;foo_impl, Arg&gt; &gt;... &gt; explicit foo(Arg&amp;&amp; arg); }; </code></pre> <p><strong>Benefit:</strong> Construction and conversion of <code>foo_impl</code> are now necessary and sufficient conditions for construction and conversion of <code>foo</code>. That is to say, <code>std::is_convertible&lt;T, foo&gt;::value == std::is_convertible&lt;T, foo_impl&gt;::value</code> and <code>std::is_constructible&lt;foo, Ts...&gt;::value == std::is_constructible&lt;foo_impl, T&gt;::value</code> both hold (almost).</p> <p><strong>Drawback?</strong> <code>foo f { 0, 1, 2, 3, 4 };</code> doesn't work if <code>foo_impl</code> is e.g. <code>std::vector&lt;int&gt;</code>, because the constraint is in terms of a construction of the style <code>std::vector&lt;int&gt; v(0, 1, 2, 3, 4);</code>. It is possible to add a further overload taking <code>std::initializer_list&lt;T&gt;</code> that is constrained on <code>std::is_convertible&lt;std::initializer_list&lt;T&gt;, foo_impl&gt;</code> (left as an exercise to the reader), or even an overload taking <code>std::initializer_list&lt;T&gt;, Ts&amp;&amp;...</code> (constraint also left as an exercise to the reader -- but remember that 'conversion' from more than one argument is not a construction!). Note that we don't need to modify <code>is_perfectly_convertible_from</code> to avoid overlap.</p> <p>The more obsequious amongst us will also make sure to discriminate <em>narrow</em> conversions against the other kind of conversions.</p>
13,630,641
Backup AWS Dynamodb to S3
<p>It has been suggested on <a href="http://aws.amazon.com/dynamodb/" rel="noreferrer">Amazon docs</a> <a href="http://aws.amazon.com/dynamodb/" rel="noreferrer">http://aws.amazon.com/dynamodb/</a> among other places, that you can backup your dynamodb tables using Elastic Map Reduce,<br> I have a general understanding of how this could work but I couldn't find any guides or tutorials on this, </p> <p>So my question is how can I automate dynamodb backups (using EMR)? </p> <p>So far, I think I need to create a "streaming" job with a map function that reads the data from dynamodb and a reduce that writes it to S3 and I believe these could be written in Python (or java or a few other languages). </p> <p>Any comments, clarifications, code samples, corrections are appreciated.</p>
14,689,749
9
2
null
2012-11-29 16:49:27.813 UTC
16
2021-04-11 18:44:05.95 UTC
null
null
null
null
487,855
null
1
36
amazon-s3|backup|amazon-dynamodb|elastic-map-reduce
44,647
<p>With introduction of AWS Data Pipeline, with a ready made template for dynamodb to S3 backup, the easiest way is to schedule a back up in the Data Pipeline <a href="http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-importexport-ddb-part2.html" rel="noreferrer">[link]</a>, </p> <p>In case you have special needs (data transformation, very fine grain control ...) consider the answer by @greg </p>
13,501,217
ggplot2 for grayscale printouts
<p>ggplot2 produces fancy graphs for screen/color prints, but the gray background and the colors interfere when printing them to grayscale. For better readablility, I'd prefer to disable the gray background and use color generators that produce either different shades of gray or different kinds of filling strokes to distinguish the groups.</p>
13,507,514
3
0
null
2012-11-21 20:07:11.04 UTC
11
2016-01-29 11:52:09.06 UTC
2012-11-22 07:14:30.243 UTC
null
419,994
null
411,944
null
1
37
r|ggplot2
63,685
<p>** EDIT ** Updated code: <code>geom_bar</code> requires a <code>stat</code>.</p> <p><code>theme_bw</code> could be what you're after. If you are plotting a geom that has a fill such as bars, the <code>scale_fill_grey</code> function will give you control over the shades of grey. If you are plotting a geom that has a colour (such as a line or points), the <code>scale_colour_grey</code> function will give you the control. As far as I know, ggplot does not plot patterned fills. Assuming you're plotting bars, the following will plot coloured bars on a grey background.</p> <pre><code>library(ggplot2) data &lt;- read.table(text = "type Year Value A 2000 3 B 2000 10 C 2000 11 A 2001 4 B 2001 5 C 2001 12", sep = "", header = TRUE) (p = ggplot(data = data, aes(x = factor(Year), y = Value)) + geom_bar(aes(fill = type), stat="identity", position = "dodge")) </code></pre> <p>The following changes the coloured bars to shades of grey. Note that one of the bars gets lost in the background.</p> <pre><code>(p = p + scale_fill_grey(start = 0, end = .9)) </code></pre> <p>The following removes the grey background.</p> <pre><code>(p = p + theme_bw()) </code></pre> <p><img src="https://i.stack.imgur.com/Pdx4h.png" alt="enter image description here"></p> <p>A point has a colour, not a fill. So to use shades of grey on points, you would need something like this.</p> <pre><code>(p = ggplot(data = data, aes(x = factor(Year), y = Value)) + geom_point(aes(colour = type), size = 5) + scale_colour_grey(start = 0, end = .9) + theme_bw()) </code></pre> <p><img src="https://i.stack.imgur.com/pYNrW.png" alt="enter image description here"></p>
13,700,798
Basic communication between two fragments
<p>I have one activity - <code>MainActivity</code>. Within this activity I have two fragments, both of which I created declaratively within the xml. </p> <p>I am trying to pass the <code>String</code> of text input by the user into <code>Fragment A</code> to the text view in <code>Fragment B</code>. However, this is proving to be very difficult. Does anyone know how I might achieve this?</p> <p>I am aware that a fragment can get a reference to it's activity using <code>getActivity()</code>. So I'm guessing I would start there?</p>
13,701,071
14
0
null
2012-12-04 10:26:46.04 UTC
37
2022-02-02 12:29:57.863 UTC
2019-10-20 20:19:37.28 UTC
null
4,607,733
null
1,732,515
null
1
75
android|android-fragments
125,199
<p>Have a look at the Android developers page: <a href="http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface" rel="noreferrer">http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface</a></p> <p>Basically, you define an interface in your Fragment A, and let your Activity implement that Interface. Now you can call the interface method in your Fragment, and your Activity will receive the event. Now in your activity, you can call your second Fragment to update the textview with the received value</p> <p>Your Activity implements your interface (See FragmentA below)</p> <pre><code>public class YourActivity implements FragmentA.TextClicked{ @Override public void sendText(String text){ // Get Fragment B FraB frag = (FragB) getSupportFragmentManager().findFragmentById(R.id.fragment_b); frag.updateText(text); } } </code></pre> <p>Fragment A defines an Interface, and calls the method when needed</p> <pre><code>public class FragA extends Fragment{ TextClicked mCallback; public interface TextClicked{ public void sendText(String text); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // This makes sure that the container activity has implemented // the callback interface. If not, it throws an exception try { mCallback = (TextClicked) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement TextClicked"); } } public void someMethod(){ mCallback.sendText("YOUR TEXT"); } @Override public void onDetach() { mCallback = null; // =&gt; avoid leaking, thanks @Deepscorn super.onDetach(); } } </code></pre> <p>Fragment B has a public method to do something with the text</p> <pre><code>public class FragB extends Fragment{ public void updateText(String text){ // Here you have it } } </code></pre>
13,681,213
What is the difference between Amazon SNS and Amazon SQS?
<p>When would I use SNS versus SQS, and why are they always coupled together?</p>
13,692,720
8
5
null
2012-12-03 10:22:12.477 UTC
169
2021-12-22 09:36:12.183 UTC
2021-02-02 10:42:01.687 UTC
null
63,550
null
972,789
null
1
674
amazon-web-services|amazon-sqs|amazon-sns
282,380
<p><strong>SNS</strong> is a distributed <strong>publish-subscribe</strong> system. Messages are <strong>pushed</strong> to subscribers as and when they are sent by publishers to SNS.</p> <p><strong>SQS</strong> is distributed <strong>queuing</strong> system. Messages are <em>not</em> pushed to receivers. Receivers have to <strong>poll or pull</strong> messages from <strong>SQS</strong>. Messages can't be received by multiple receivers at the same time. Any one receiver can receive a message, process and delete it. Other receivers do not receive the same message later. Polling inherently introduces some latency in message delivery in SQS unlike SNS where messages are immediately pushed to subscribers. SNS supports several end points such as email, SMS, HTTP end point and SQS. If you want unknown number and type of subscribers to receive messages, you need SNS.</p> <p>You don't have to couple SNS and SQS always. You can have SNS send messages to email, SMS or HTTP end point apart from SQS. There are advantages to coupling SNS with SQS. You may not want an external service to make connections to your hosts (a firewall may block all incoming connections to your host from outside).</p> <p>Your end point may just die because of heavy volume of messages. Email and SMS maybe not your choice of processing messages quickly. By coupling SNS with SQS, you can receive messages at your pace. It allows clients to be offline, tolerant to network and host failures. You also achieve guaranteed delivery. If you configure SNS to send messages to an HTTP end point or email or SMS, several failures to send message may result in messages being dropped.</p> <p>SQS is mainly used to decouple applications or integrate applications. Messages can be stored in SQS for a short duration of time (maximum 14 days). SNS distributes several copies of messages to several subscribers. For example, let’s say you want to replicate data generated by an application to several storage systems. You could use SNS and send this data to multiple subscribers, each replicating the messages it receives to different storage systems (<a href="https://en.wikipedia.org/wiki/Amazon_S3" rel="noreferrer">S3</a>, hard disk on your host, database, etc.).</p>
51,996,175
How to break out of nested loops in Go?
<p>I have an outer and inner loop, each iterating over a range. I want to exit the outer loop when a condition is satisfied inside the inner loop.</p> <p>I have a solution which works using two 'break's, one inside the inner loop and one inside the outerloop, just outside the inner loop (a very simplified case for demonstration):</p> <pre><code>package main import ( "fmt" ) func main() { word := "" for _, i := range("ABCDE") { for _,j := range("ABCDE") { word = string(i) + string(j) fmt.Println(word) if word == "DC" { break } } if word == "DC" { break } } // More logic here that needs to be executed } </code></pre> <p><a href="https://play.golang.org/p/URY29ukzp9A" rel="noreferrer">Go Playground</a></p> <p>There is no problem with this solution, but it just looks patched and ugly to me. Is there a better way to do this?</p> <p>I can try and have another for conditional loop outside the outer loop in the previous solution and have a label and use continue with the label. But as you can see, this approach isn't any more elegant than the solution with break.</p> <pre><code>package main import ( "fmt" ) func main() { word := "" Exit: for word != "DC" { for _, i := range "ABCDE" { for _, j := range "ABCDE" { word = string(i) + string(j) fmt.Println(word) if word == "DC" { continue Exit } } } } // More logic here that needs to be executed } </code></pre> <p><a href="https://play.golang.org/p/cWrqtDV34L4" rel="noreferrer">Go Playground</a></p> <p>I have seen similar questions here pertaining to other languages (C, C#, Python etc). But what I am really interested to see is whether there is any trick with Go constructs such as 'for select'.</p>
51,996,305
6
5
null
2018-08-24 01:07:22.783 UTC
11
2019-12-05 10:15:04.773 UTC
2019-08-26 10:56:33.51 UTC
null
55,504
null
1,479,093
null
1
62
loops|go
56,302
<p>use function</p> <pre><code>package main import ( "fmt" ) func getWord() string { word := "" for word != "DC" { for _, i := range "ABCDE" { for _, j := range "ABCDE" { word = string(i) + string(j) fmt.Println(word) if word == "DC" { return word } } } } return word } func main(){ word := getWord() } </code></pre> <p>Edit: thanks to @peterSO who points on some mistakes in the details and provides this playground <a href="https://play.golang.org/p/udcJptBW9pQ" rel="noreferrer">https://play.golang.org/p/udcJptBW9pQ</a></p>
3,943,801
Objective C - How do I use initWithCoder method?
<p>I have the following method for my class which intends to load a nib file and instantiate the object:</p> <pre><code>- (id)initWithCoder:(NSCoder*)aDecoder { if(self = [super initWithCoder:aDecoder]) { // Do something } return self; } </code></pre> <p>How does one instantiate an object of this class? What is this <code>NSCoder</code>? How can I create it?</p> <pre><code> MyClass *class = [[MyClass alloc] initWithCoder:aCoder]; </code></pre>
3,943,938
2
0
null
2010-10-15 15:41:54.887 UTC
11
2014-01-17 20:28:16.75 UTC
2014-01-17 20:28:16.75 UTC
null
1,038,379
null
242,769
null
1
49
objective-c|cocoa-touch|nscoder
66,900
<p>You also need to define the following method as follows:</p> <pre><code>- (void)encodeWithCoder:(NSCoder *)enCoder { [super encodeWithCoder:enCoder]; [enCoder encodeObject:instanceVariable forKey:INSTANCEVARIABLE_KEY]; // Similarly for the other instance variables. .... } </code></pre> <p>And in the initWithCoder method initialize as follows:</p> <pre><code>- (id)initWithCoder:(NSCoder *)aDecoder { if(self = [super initWithCoder:aDecoder]) { self.instanceVariable = [aDecoder decodeObjectForKey:INSTANCEVARIABLE_KEY]; // similarly for other instance variables .... } return self; } </code></pre> <p>You can initialize the object standard way i.e </p> <pre><code>CustomObject *customObject = [[CustomObject alloc] init]; </code></pre>
16,448,002
Android: FileObserver monitors only top directory
<p>According to the documentation, </p> <pre><code>"Each FileObserver instance monitors a single file or directory. If a directory is monitored, events will be triggered for all files and subdirectories inside the monitored directory." </code></pre> <p>My code goes like,</p> <pre><code> FileObserver fobsv = new FileObserver("/mnt/sdcard/") { @Override public void onEvent(int event, String path) { System.out.println(event+" "+path); } }; fobsv.startWatching(); </code></pre> <p>However, the <code>onEvent()</code> is triggering only when a file is changed in the <strong>/mnt/sdcard/</strong>. If I create a file in <strong>/mnt/sdcard/downloads/</strong>, the method is not getting fired.</p> <p>Is there any problem with the code?</p>
16,449,501
2
0
null
2013-05-08 18:47:26.763 UTC
10
2014-03-12 14:22:46.833 UTC
2014-01-10 15:05:12.567 UTC
null
2,360,535
null
1,176,304
null
1
13
android|android-sdcard|fileobserver
12,061
<blockquote> <p>According to the documentation</p> </blockquote> <p>The documentation is incorrect, as is noted in <a href="https://code.google.com/p/android/issues/detail?id=33659" rel="noreferrer">this issue</a>.</p> <blockquote> <p>Is there any problem with the code?</p> </blockquote> <p>No, but <code>FileObserver</code> is not recursive, despite the documentation to the contrary.</p>
16,552,801
How do I conditionally add a class with Add-Type -TypeDefinition if it isn't added already?
<p>Consider the following PowerShell snippet:</p> <pre><code>$csharpString = @" using System; public sealed class MyClass { public MyClass() { } public override string ToString() { return "This is my class. There are many others " + "like it, but this one is mine."; } } "@ Add-Type -TypeDefinition $csharpString; $myObject = New-Object MyClass Write-Host $myObject.ToString(); </code></pre> <p>If I run it more than once in the same AppDomain (e.g. run the script twice in powershell.exe or powershell_ise.exe) I get the following error:</p> <pre><code>Add-Type : Cannot add type. The type name 'MyClass' already exists. At line:13 char:1 + Add-Type -TypeDefinition $csharpString; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (MyClass:String) [Add-Type], Exception + FullyQualifiedErrorId : TYPE_ALREADY_EXISTS,Microsoft.PowerShell.Commands.AddTypeCommand </code></pre> <p>How do I wrap the call to <a href="http://ss64.com/ps/add-type.html">Add-Type</a> -TypeDefinition so that its only called once? </p>
22,156,833
5
1
null
2013-05-14 21:02:04.543 UTC
3
2018-04-10 20:02:45.273 UTC
2013-05-14 21:07:47.357 UTC
null
6,920
null
95,195
null
1
51
powershell|add-type
18,037
<p>This technique works well for me:</p> <pre><code>if (-not ([System.Management.Automation.PSTypeName]'MyClass').Type) { Add-Type -TypeDefinition 'public class MyClass { }' } </code></pre> <ul> <li>The type name can be enclosed in quotes 'MyClass', square brackets [MyClass], or both '[MyClass]' (v3+ only).</li> <li>The type name lookup is not case-sensitive.</li> <li>You must use the full name of the type, unless it is part of the System namespace (e.g. [System.DateTime] can be looked up via 'DateTime', but [System.Reflection.Assembly] cannot be looked up via 'Assembly').</li> <li>I've only tested this in Win8.1; PowerShell v2, v3, v4.</li> </ul> <p>Internally, the PSTypeName class calls the LanguagePrimitives.ConvertStringToType() method which handles the heavy lifting. It caches the lookup string when successful, so additional lookups are faster.</p> <p>I have not confirmed whether or not any exceptions are thrown internally as mentioned by x0n and Justin D.</p>
16,423,774
string representation of a numpy array with commas separating its elements
<p>I have a numpy array, for example: </p> <pre><code>points = np.array([[-468.927, -11.299, 76.271, -536.723], [-429.379, -694.915, -214.689, 745.763], [ 0., 0., 0., 0. ]]) </code></pre> <p>if I print it or turn it into a string with str() I get:</p> <pre><code>print w_points [[-468.927 -11.299 76.271 -536.723] [-429.379 -694.915 -214.689 745.763] [ 0. 0. 0. 0. ]] </code></pre> <p>I need to turn it into a string that prints with separating commas while keeping the 2D array structure, that is:</p> <pre><code>[[-468.927, -11.299, 76.271, -536.723], [-429.379, -694.915, -214.689, 745.763], [ 0., 0., 0., 0. ]] </code></pre> <p>Does anybody know an easy way of turning a numpy array to that form of string?</p> <p>I know that .tolist() adds the commas but the result loses the 2D structure.</p>
16,423,805
4
1
null
2013-05-07 16:11:46.97 UTC
6
2021-04-15 16:57:12.343 UTC
null
null
null
null
874,829
null
1
61
python|numpy
50,710
<p>Try using <code>repr</code></p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; points = np.array([[-468.927, -11.299, 76.271, -536.723], ... [-429.379, -694.915, -214.689, 745.763], ... [ 0., 0., 0., 0. ]]) &gt;&gt;&gt; print(repr(points)) array([[-468.927, -11.299, 76.271, -536.723], [-429.379, -694.915, -214.689, 745.763], [ 0. , 0. , 0. , 0. ]]) </code></pre> <p>If you plan on using large numpy arrays, set <code>np.set_printoptions(threshold=np.nan)</code> first. Without it, the array representation will be truncated after about 1000 entries (by default).</p> <pre><code>&gt;&gt;&gt; arr = np.arange(1001) &gt;&gt;&gt; print(repr(arr)) array([ 0, 1, 2, ..., 998, 999, 1000]) </code></pre> <p>Of course, if you have arrays that large, this starts to become less useful and you should probably analyze the data some way other than just looking at it and there are <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html" rel="noreferrer">better ways</a> of persisting a numpy array than saving it's <code>repr</code> to a file...</p>
15,090,185
AngularJS + Bootstrap Dropdown : can't do ng-click in ng-repeat
<p>I'm trying to create a picker with Bootstrap Dropdown and AngularJS.</p> <p><a href="http://jsfiddle.net/qbjfQ/" rel="noreferrer">http://jsfiddle.net/qbjfQ/</a></p> <pre><code>&lt;li ng-repeat="item in list"&gt;&lt;a ng-click="current = item"&gt;Dynamic set {{item}}&lt;/a&gt;&lt;/li&gt; </code></pre> <p>When I use ng-click statically in the list, it works fine (example 4 and 5) But when I use ng-click in ng-repeat, it won't update the value (example 1 to 3)</p> <p>What can I do ?</p>
15,090,254
3
0
null
2013-02-26 13:21:22.557 UTC
1
2013-12-29 14:11:48.267 UTC
2013-02-26 18:22:25.143 UTC
null
422,353
null
2,111,343
null
1
9
drop-down-menu|twitter-bootstrap|angularjs|ng-repeat
41,339
<p>It is a known problem with scoping in directives. You can read the article <a href="https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance" rel="nofollow noreferrer">The Nuances of Scope Prototypal Inheritance</a> to learn more about the scoping in angular js.</p> <p>You need to change the <code>ng-repeat</code> to</p> <pre><code>&lt;li ng-repeat="item in list"&gt; &lt;a ng-click="$parent.current = item"&gt; Dynamic set {{item}} &lt;/a&gt; &lt;/li&gt; </code></pre> <p>Demo: <a href="http://jsfiddle.net/arunpjohny/qbjfQ/1/" rel="nofollow noreferrer">Fiddle</a></p> <p>For explanation of the problem, you can read <a href="https://stackoverflow.com/questions/15037743/why-does-assignment-not-always-work-in-angular-expressions/15037878#15037878">my answer</a> to <a href="https://stackoverflow.com/questions/15037743/why-does-assignment-not-always-work-in-angular-expressions">this question</a></p>
17,541,739
How to add the bubbles to textview android?
<p>In my application, I want to set bubbles to a text view, in the text view I add the <code>setBackgroundResource()</code> as you can see in the code.</p> <p>With this code i'm getting an image like this:</p> <p><img src="https://i.stack.imgur.com/IlcYQ.png" alt="enter image description here"> </p> <p>I want a bubble shape image like this:</p> <p><img src="https://i.stack.imgur.com/0eJZr.png" alt="enter image description here"></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" &gt; &lt;solid android:color="#EDF5E4" /&gt; &lt;corners android:bottomLeftRadius="@dimen/corner_radius" android:bottomRightRadius="@dimen/corner_radius" android:topLeftRadius="@dimen/corner_radius" id:topRightRadius="@dimen/corner_radius" /&gt; </code></pre> <p></p> <p>Please tell me how to make this in my <code>setBackgroundResource()</code> XML.</p>
17,542,066
2
1
null
2013-07-09 06:47:35.957 UTC
11
2018-09-15 09:45:09.137 UTC
2017-10-26 21:24:02.493 UTC
null
5,706,778
null
2,353,676
null
1
18
android|android-intent|android-custom-view|nine-patch
28,425
<p>What you need to use is essentially a 9-patch image (<em>As already pointed out by <strong>Ken Wolf</strong> in this comment</em>).</p> <p>To get you started, I am including a set of 9-patch images from one of my apps along with a brief piece of code on how to use it when creating a layout XMl. ;-)</p> <p><strong>The 9-patch Image Set:</strong></p> <p><img src="https://i.stack.imgur.com/RRG1e.png" alt="mdpi"> <img src="https://i.stack.imgur.com/SZ4IV.png" alt="hdpi"> <img src="https://i.stack.imgur.com/ItrMd.png" alt="xhdpi"></p> <p>(These are named: <code>bubble_white_normal_mdpi.9</code>, <code>bubble_white_normal_hdpi.9</code> and <code>bubble_white_normal_xhdpi.9</code> respectively. <strong>Remove</strong> the <strong>_mdpi</strong>, <strong>_hdpi</strong> and <strong>_xhdpi</strong> from the file names after placing them in their respective <code>drawable</code> folders.</p> <p><strong>The XML:</strong></p> <pre><code>&lt;LinearLayout android:id="@+id/linlaUserOther" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:baselineAligned="false" android:orientation="horizontal" android:padding="2dp" &gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="fill_parent" android:gravity="top|center" &gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" &gt; &lt;ImageView android:id="@+id/imgvwProfileOther" android:layout_width="42dp" android:layout_height="42dp" android:adjustViewBounds="true" android:contentDescription="@string/content_desc_user_profile" android:scaleType="centerCrop" android:src="@drawable/ic_contact_picture" &gt; &lt;/ImageView&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="1" android:background="@drawable/bubble_white_normal" android:gravity="top|center" android:orientation="vertical" &gt; .... // OTHER STUFF HERE THAT IS NOT NECESSARY IN THIS CODE SNIPPET ON SO &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p><strong>NOTE 1:</strong></p> <p>Although, I am including a working set of Images (<em>almost spoon feeding, if you will</em>), I would strongly urge you to create your own set of images that fit in your scheme of things. Plus, this will also equip you to build your own resources in the future. The only reason I am going the <em>extra mile</em> is because I personally lost 3 days getting the speech bubble looking and working right. :-(</p> <p><strong>NOTE 2:</strong></p> <p>I am setting the image as a background to a <code>LinearLayout</code>. You, however, will need to set it to the <code>TextView</code> you need looking like a Speech Bubble.</p> <p><strong>Additional Sites (Tutorials):</strong></p> <ol> <li><a href="http://blog.booleanbites.com/2012/12/android-listview-with-speech-bubble.html" rel="nofollow noreferrer">http://blog.booleanbites.com/2012/12/android-listview-with-speech-bubble.html</a></li> <li><a href="https://github.com/AdilSoomro/Android-Speech-Bubble" rel="nofollow noreferrer">https://github.com/AdilSoomro/Android-Speech-Bubble</a></li> <li><a href="http://developer.android.com/reference/android/graphics/NinePatch.html" rel="nofollow noreferrer">http://developer.android.com/reference/android/graphics/NinePatch.html</a></li> <li><a href="http://developer.android.com/tools/help/draw9patch.html" rel="nofollow noreferrer">http://developer.android.com/tools/help/draw9patch.html</a></li> </ol>
27,390,989
Swift enum with custom initializer loses rawValue initializer
<p>I have tried to boil this issue down to its simplest form with the following.</p> <h2>Setup</h2> <p>Xcode Version 6.1.1 (6A2008a)</p> <p>An enum defined in <code>MyEnum.swift</code>:</p> <pre><code>internal enum MyEnum: Int { case Zero = 0, One, Two } extension MyEnum { init?(string: String) { switch string.lowercaseString { case "zero": self = .Zero case "one": self = .One case "two": self = .Two default: return nil } } } </code></pre> <p>and code that initializes the enum in another file, <code>MyClass.swift</code>:</p> <pre><code>internal class MyClass { let foo = MyEnum(rawValue: 0) // Error let fooStr = MyEnum(string: "zero") func testFunc() { let bar = MyEnum(rawValue: 1) // Error let barStr = MyEnum(string: "one") } } </code></pre> <h2>Error</h2> <p>Xcode gives me the following error when attempting to initialize <code>MyEnum</code> with its raw-value initializer:</p> <pre><code>Cannot convert the expression's type '(rawValue: IntegerLiteralConvertible)' to type 'MyEnum?' </code></pre> <h2>Notes</h2> <ol> <li><p>Per <a href="https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html#//apple_ref/doc/uid/TP40014097-CH12-XID_226" rel="noreferrer">the Swift Language Guide</a>:</p> <blockquote> <p>If you define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value’s type (as a parameter called <code>rawValue</code>) and returns either an enumeration member or <code>nil</code>.</p> </blockquote></li> <li><p>The custom initializer for <code>MyEnum</code> was defined in an extension to test whether the enum's raw-value initializer was being removed because of the following case from <a href="https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html#//apple_ref/doc/uid/TP40014097-CH18-XID_321" rel="noreferrer">the Language Guide</a>. However, it achieves the same error result.</p> <blockquote> <p>Note that if you define a custom initializer for a value type, you will no longer have access to the default initializer (or the memberwise initializer, if it is a structure) for that type. [...]<br> If you want your custom value type to be initializable with the default initializer and memberwise initializer, and also with your own custom initializers, write your custom initializers in an extension rather than as part of the value type’s original implementation.</p> </blockquote></li> <li><p>Moving the enum definition to <code>MyClass.swift</code> resolves the error for <code>bar</code> but not for <code>foo</code>.</p></li> <li><p>Removing the custom initializer resolves both errors.</p></li> <li><p>One workaround is to include the following function in the enum definition and use it in place of the provided raw-value initializer. So it seems as if adding a custom initializer has a similar effect to marking the raw-value initializer <code>private</code>.</p> <pre><code>init?(raw: Int) { self.init(rawValue: raw) } </code></pre></li> <li><p>Explicitly declaring protocol conformance to <code>RawRepresentable</code> in <code>MyClass.swift</code> resolves the inline error for <code>bar</code>, but results in a linker error about duplicate symbols (because raw-value type enums implicitly conform to <code>RawRepresentable</code>).</p> <pre><code>extension MyEnum: RawRepresentable {} </code></pre></li> </ol> <p>Can anyone provide a little more insight into what's going on here? Why isn't the raw-value initializer accessible?</p>
31,711,091
6
5
null
2014-12-09 23:46:16.297 UTC
15
2018-03-17 09:35:31.82 UTC
null
null
null
null
2,712,445
null
1
104
swift|enums
65,791
<p>This bug is solved in Xcode 7 and Swift 2 </p>
21,694,302
What are the mechanics of short string optimization in libc++?
<p><a href="https://stackoverflow.com/a/10319672/1805388">This answer</a> gives a nice high-level overview of short string optimization (SSO). However, I would like to know in more detail how it works in practice, specifically in the libc++ implementation:</p> <ul> <li><p>How short does the string have to be in order to qualify for SSO? Does this depend on the target architecture?</p></li> <li><p>How does the implementation distinguish between short and long strings when accessing the string data? Is it as simple as <code>m_size &lt;= 16</code> or is it a flag that is part of some other member variable? (I imagine that <code>m_size</code> or part of it might also be used to store string data).</p></li> </ul> <p>I asked this question specifically for libc++ because I know that it uses SSO, this is even mentioned on the <a href="http://libcxx.llvm.org/" rel="noreferrer">libc++ home page</a>.</p> <p>Here are some observations after looking at <a href="http://llvm.org/svn/llvm-project/libcxx/trunk/include/string" rel="noreferrer">the source</a>:</p> <p>libc++ can be compiled with two slightly different memory layouts for the string class, this is governed by the <code>_LIBCPP_ALTERNATE_STRING_LAYOUT</code> flag. Both of the layouts also distinguish between little-endian and big-endian machines which leaves us with a total of 4 different variants. I will assume the "normal" layout and little-endian in what follows.</p> <p>Assuming further that <code>size_type</code> is 4 bytes and that <code>value_type</code> is 1 byte, this is what the first 4 bytes of a string would look like in memory:</p> <pre><code>// short string: (s)ize and 3 bytes of char (d)ata sssssss0;dddddddd;dddddddd;dddddddd ^- is_long = 0 // long string: (c)apacity ccccccc1;cccccccc;cccccccc;cccccccc ^- is_long = 1 </code></pre> <p>Since the size of the short string is in the upper 7 bits, it needs to be shifted when accessing it:</p> <pre><code>size_type __get_short_size() const { return __r_.first().__s.__size_ &gt;&gt; 1; } </code></pre> <p>Similarly, the getter and setter for the capacity of a long string uses <code>__long_mask</code> to work around the <code>is_long</code> bit.</p> <p>I am still looking for an answer to my first question, i.e. what value would <code>__min_cap</code>, the capacity of short strings, take for different architectures?</p> <p><strong>Other standard library implementations</strong></p> <p><a href="https://stackoverflow.com/a/28003328/1805388">This answer</a> gives a nice overview of <code>std::string</code> memory layouts in other standard library implementations.</p>
21,710,033
2
4
null
2014-02-11 06:01:50.807 UTC
57
2019-02-08 06:56:21.15 UTC
2019-02-08 06:56:21.15 UTC
null
1,805,388
null
1,805,388
null
1
121
c++|string|optimization|c++-standard-library|libc++
49,155
<p>The libc++ <code>basic_string</code> is designed to have a <code>sizeof</code> 3 words on all architectures, where <code>sizeof(word) == sizeof(void*)</code>. You have correctly dissected the long/short flag, and the size field in the short form.</p> <blockquote> <p>what value would __min_cap, the capacity of short strings, take for different architectures?</p> </blockquote> <p>In the short form, there are 3 words to work with:</p> <ul> <li>1 bit goes to the long/short flag.</li> <li>7 bits goes to the size.</li> <li>Assuming <code>char</code>, 1 byte goes to the trailing null (libc++ will always store a trailing null behind the data).</li> </ul> <p>This leaves 3 words minus 2 bytes to store a short string (i.e. largest <code>capacity()</code> without an allocation).</p> <p>On a 32 bit machine, 10 chars will fit in the short string. sizeof(string) is 12.</p> <p>On a 64 bit machine, 22 chars will fit in the short string. sizeof(string) is 24.</p> <p>A major design goal was to minimize <code>sizeof(string)</code>, while making the internal buffer as large as possible. The rationale is to speed move construction and move assignment. The larger the <code>sizeof</code>, the more words you have to move during a move construction or move assignment.</p> <p>The long form needs a minimum of 3 words to store the data pointer, size and capacity. Therefore I restricted the short form to those same 3 words. It has been suggested that a 4 word sizeof might have better performance. I have not tested that design choice.</p> <p><strong>_LIBCPP_ABI_ALTERNATE_STRING_LAYOUT</strong></p> <p>There is a configuration flag called <code>_LIBCPP_ABI_ALTERNATE_STRING_LAYOUT</code> which rearranges the data members such that the "long layout" changes from:</p> <pre><code>struct __long { size_type __cap_; size_type __size_; pointer __data_; }; </code></pre> <p>to:</p> <pre><code>struct __long { pointer __data_; size_type __size_; size_type __cap_; }; </code></pre> <p>The motivation for this change is the belief that putting <code>__data_</code> first will have some performance advantages due to better alignment. An attempt was made to measure the performance advantages, and it was difficult to measure. It won't make the performance worse, and it may make it slightly better.</p> <p>The flag should be used with care. It is a different ABI, and if accidentally mixed with a libc++ <code>std::string</code> compiled with a different setting of <code>_LIBCPP_ABI_ALTERNATE_STRING_LAYOUT</code> will create run time errors.</p> <p>I recommend this flag only be changed by a vendor of libc++.</p>
39,805,018
How do I resolve peer dependency error: The package [email protected] does not satisfy its siblings' peerDependencies requirements
<p>I am getting this error when I run npm install. This seems because I am unable to satisfy some peer dependency but I am unsure which peer dependency I need to fix. </p> <pre><code>λ npm install npm ERR! Windows_NT 10.0.14393 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" npm ERR! node v4.6.0 npm ERR! npm v2.15.9 npm ERR! code EPEERINVALID npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements! npm ERR! peerinvalid Peer [email protected] wants react@&gt;=0.14.0 || ^15.0.0-rc npm ERR! peerinvalid Peer [email protected] wants react@^15.0.0 npm ERR! peerinvalid Peer [email protected] wants react@^15.0.0 npm ERR! peerinvalid Peer [email protected] wants react@&gt;=0.12.0 npm ERR! peerinvalid Peer [email protected] wants [email protected] || 0.14.x || ^15.0.1 npm ERR! peerinvalid Peer [email protected] wants react@^0.14.0 npm ERR! peerinvalid Peer [email protected] wants react@~0.14 || ~15.3.0 npm ERR! peerinvalid Peer [email protected] wants react@^15.3.2 npm ERR! peerinvalid Peer [email protected] wants react@^15.3.2 npm ERR! Please include the following file with any support request: npm ERR! C:\Users\Daljeet\Documents\hive\client\npm-debug.log </code></pre> <p>I have also attached a copy of the package.json </p> <pre><code>dependencies: "dependencies": { "belle": "^2.0.7", "body-parser": "^1.6.5", "bootstrap": "^3.3.0", "compression": "^1.0.11", "config": "^1.21.0", "config-js": "^1.1.9", "connect-ensure-login": "^0.1.1", "cors": "^2.4.1", "dateformat": "^1.0.12", "dotenv": "^0.4.0", "errorhandler": "^1.1.1", "express": "^4.8.5", "express-jwt": "^0.3.1", "flux": "^2.0.1", "i": "^0.3.5", "immutability-helper": "^2.0.0", "jsonwebtoken": "^5.0.1", "jwt-decode": "^1.1.0", "keymirror": "^0.1.1", "lodash": "4.0.0", "log4js": "^0.6.38", "material-ui": "~0.15.4", "mongoose": "^4.3.4", "morgan": "^1.2.3", "normalize.css": "^4.2.0", "pg": "^4.5.5", "react": "15.3.2", "react-infinite": "^0.9.2", "react-input-field": "^1.2.4", "react-mixin": "^1.1.0", "react-router": "^0.13.2", "react-star-rating": "^1.4.2", "react-tap-event-plugin": "~0.2.2", "react-toolbox": "^1.2.1", "react-virtual-list": "^1.8.0", "reqwest": "2.0.5", "when": "^3.7.2" }, "devDependencies": { "babelify": "^6.1.0", "browser-sync": "^2.1.6", "browserify": "^8.0.3", "clean-css": "^3.1.9", "eslint": "^0.14.1", "nodemon": "^1.5.0", "rework": "^1.0.1", "rework-npm": "^1.0.0", "rework-npm-cli": "^0.1.1", "serve": "^1.4.0", "uglify-js": "^2.4.15", "watchify": "^2.1.1" } } </code></pre>
39,819,731
4
6
null
2016-10-01 09:30:24.957 UTC
4
2022-09-07 05:14:08.133 UTC
2016-10-01 17:45:32.76 UTC
null
2,816,509
null
2,816,509
null
1
16
node.js|reactjs|npm|package.json
59,511
<p>it worked when I:</p> <hr> <ol> <li>updated npm <code>"npm install npm -g"</code> </li> <li>downgraded react to; <code>"react": "15.3.0"</code></li> <li>cleared cache: <code>npm cache clear</code></li> <li>removed node_modules, <code>rm -rf node_modules</code>, </li> <li>reinstalled node_modules, <code>npm install</code>.</li> </ol>
19,395,200
Does all asynchronous I/O ultimately implemented in polling?
<p>I have been though asynchronous I/O is always has a callback form. But recently I discovered some low level implementations are using polling style API.</p> <ol> <li><a href="http://julipedia.meroh.net/2004/10/example-of-kqueue.html" rel="nofollow noreferrer">kqueue</a></li> <li><a href="https://stackoverflow.com/questions/19335408/why-does-libpq-use-polling-rather-than-notification-for-data-fetch">libpq</a></li> </ol> <p>And this leads me to think that maybe all (or most) asynchronous I/O (any of file, socket, mach-port, etc.) is implemented in a kind of polling manner at last. Maybe the callback form is just an abstraction only for higher-level API.</p> <p>This could be a silly question, but I don't know how actually most of asynchronous I/O implemented at low level. I just used the <em>system level notifications</em>, and when I see <code>kqueue</code> - which is the system notification, it's a polling style!</p> <p>How should I understand asynchronous I/O at low-level? <strong>How the high-level <em>asynchronous notification</em> is being made from low-level polling system?</strong> (if it actually does)</p>
19,395,425
1
3
null
2013-10-16 04:22:13.94 UTC
9
2013-10-16 04:51:17.337 UTC
2017-05-23 11:53:46.983 UTC
null
-1
null
246,776
null
1
12
asynchronous|io
980
<p>At the lowest (or at least, lowest worth looking at) hardware level, asynchronous operations truly <em>are</em> asynchronous in modern operating systems.</p> <p>For example, when you read a file from the disk, the operating system translates your call to <code>read</code> to a series of disk operations (seek to location, read blocks X through Y, etc.). On most modern OSes, these commands get written either to special registers, or special locations in main memory, and the disk controller is informed that there are operations pending. The operating system then goes on about its business, and when the disk controller has completed all of the operations assigned to it, it triggers an <a href="http://en.wikipedia.org/wiki/Interrupt">interrupt</a>, causing the thread that requested the read to pickup where it left off.</p> <p>Regardless of what type of low-level asynchronous operation you're looking at (disk I/O, network I/O, mouse and keyboard input, etc.), ultimately, there is some stage at which a command is dispatched to hardware, and the "callback" as it were is not executed until the hardware reaches out and informs the OS that it's done, usually in the form of an interrupt.</p> <p><strong>That's not to say</strong> that there aren't some asynchronous operations implemented using polling. One trivial (but naive and costly) way to implement any blocking operation asynchronously is just to spawn a thread that waits for the operation to complete (perhaps polling in a tight loop), and then call the callback when it's finished. Generally speaking, though, common asynchronous operations at the OS level are truly asynchronous.</p> <p>It's also worth mentioning that just because an API is blocking doesn't mean it's polling: you can put a blocking API on an asynchronous operation, and a non-blocking API on a synchronous operation. With things like <code>select</code> and kqueues, for example, the thread actually just goes to sleep until something interesting happens. That "something interesting" comes in in the form of an interrupt (usually), and that's taken as an indication that the operating system should wake up the relevant threads to continue work. It doesn't just sit there in a tight loop waiting for something to happen.</p> <p>There really is no way to tell whether a system uses polling or "real" callbacks (like interrupts) just from its API, but yes, there are asynchronous APIs that are truly backed by asynchronous operations.</p>
19,664,993
Is it possible to implement Common Lisp's macro system in scheme?
<p>Hopefully this is not a redundant question. </p> <p>As a newcomer to scheme I am aware that <code>syntax-case</code> macros are more powerful than the <code>syntax-rules</code> alternative, at the cost of unwanted complexity. </p> <p>Is it possible, however, to implement Common Lisp's macro system in scheme, which is more powerful than <code>syntax-rules</code>, using <code>syntax-case</code>? </p>
19,670,813
3
6
null
2013-10-29 17:18:52.457 UTC
15
2013-10-30 01:38:47.137 UTC
null
null
null
null
1,693,831
null
1
23
compiler-construction|macros|scheme|common-lisp
5,448
<p>I'll try to be brief -- which is hard since this is generally a very deep issue, more than the average SO level of Q&amp;A... so this is still going to be pretty long. I'll also try to be unbiased; even though I come from a Racket perspective, I have been using Common Lisp in the past, and I always liked to use macros in both worlds (and in others, actually). It won't look like a direct answer to your question (at an extreme end, that would be just "yes"), but it is comparing the two systems and hopefully this will help in clarifying the issue for people -- especially people outside of lisp (all flavors) who would wonder why is this such a big deal. I'll also describe how <code>defmacro</code> can be implemented in "syntax-case" systems, but only generally to keep things clear (and since you can just find such implementations, some given in the comments and in other answers).</p> <p>First, your question is very much not redundant -- it is very justified, and (as I implied), one of the things that Lisp newcomers to Scheme and Scheme newcomers to Lisp encounter.</p> <p>Second, the very shallow, very short answer is what people have told you: yes, it's possible to implement CL's <code>defmacro</code> in a Scheme that supports <code>syntax-case</code>, and as expected you've got multiple pointers to such implementations. Going the other way and implementing <code>syntax-case</code> using simple <code>defmacro</code> is a trickier subject that I won't talk about too much; I'll just say it <a href="http://www.p-cos.net/documents/hygiene.pdf" rel="noreferrer">has been done</a>, only at a very high cost of re-implementing <code>lambda</code> and other binding constructs, which means that it's basically a re-implementation of a new language which you should commit to if you want to use that implementation.</p> <p>And another clarification: people, especially CLers, very often collapse two things related to Scheme macros: hygiene, and <code>syntax-rules</code>. The thing is that in R5RS all you have is <code>syntax-rules</code>, which is a very limited pattern-based rewrite system. As with other rewrite systems, you can use it naively, or get all the way up to using rewrites to define a small language which you can then use to write macros in. See <a href="http://www.phyast.pitt.edu/~micheles/syntax-rules.pdf" rel="noreferrer">this text</a> for a known explanation on how this is done. While it's possible to do that, the bottom line is that it's hard, you're using some weird small language thing that is not directly related to your actual language, and this makes it very far from Scheme programming -- probably in an even worse way that using the hygienic macro implementation in CL is not really using plain CL. In short, it's possible to use only <code>syntax-rules</code>, but this is mostly in a theoretical sense, not something that you'll want to use in "real" code. The main point here is that hygiene does not imply being limited to <code>syntax-rules</code>.</p> <p>However, <code>syntax-rules</code> was not intended as "the" Scheme macro system -- the idea was always that you have some "low-level" macro implementation which is used to implement <code>syntax-rules</code> but can also implement hygiene-breaking macros -- it's just that there was no agreement on the particular low-level implementation. R6RS fixes that by standardizing the "syntax-case" macro system (note that I'm using "syntax-case" as the name of the system, different from <code>syntax-case</code> which is the form that is it's main highlight). As if to make a point that the discussion is still alive, R7RS took a step back and excluded it, reverting back to having <code>syntax-rules</code> with no commitment on a low-level system, at least as far as the "small language" goes.</p> <p>Now, to actually understand the difference between the two systems, the best thing to clarify is the difference between the <em>types</em> that they're dealing with. With <code>defmacro</code>, a transformer is basically a function that takes in an S-expression(s) and returns an S-expression. An S-expression here is a type that is made of a bunch of literal types (numbers, strings, booleans), symbols, and list-nested structures of these. (The actual types used are a little more than that, but that's enough to make the point.) The thing is that this is a very simple world: you're getting in something that is very concrete -- you can actually print the input/output values and that's all you have. Note that this system uses <em>symbols</em> to denote identifiers -- and a symbol is something very concrete in just that sense: an <code>x</code> is a piece of code that has just that name, <code>x</code>.</p> <p>However, this simplicity comes at a cost: you cannot use it for hygienic macros since you have no way to distinguish two <em>different</em> identifiers that are both called <code>x</code>. The usual CL-based <code>defmacro</code> does have some addtional bits that compensate for some of this. One such bit is <code>gensym</code> -- a tool to create "fresh" symbols that are uninterned and therefore are guaranteed to be different from any other symbol, including ones that have the same name. Another such bit is the <code>&amp;environment</code> argument to <code>defmacro</code> transformers, which holds some representation of the lexical environment of the location where the macro is used.</p> <p>It's obvious that these things complicate the <code>defmacro</code> world since it's no longer dealing with plain printable values, and since you need to be aware of some representation of an environment -- which makes it even more clear that a macro is actually a piece of code that is a compiler hook (since this environment is essentially some datatype that the compiler usually deals with, and one that is more complicated than just S-expressions). But as it turns out, they're not enough to implement hygiene. Using <code>gensym</code> you can get one easy aspect of hygiene knocked off (avoiding macro-side captures of user code), but the other aspect (avoiding user code capturing macro code) is still left open. Some people settle for this with arguing that the kind of capture that you can avoid is sufficient -- but when you're dealing with a modular system where a macro's environment often has different bindings than the ones used in its implementation, the other side becomes much more important.</p> <p>Switch over to syntax-case macro systems (and happily skipping over <code>syntax-rules</code>, which is trivially implemented using <code>syntax-case</code>). In this system, the idea is that if plain symbolic S-expressions are not expressive enough to represent the complete lexical knowledge (ie, the difference between two different bindings, both called <code>x</code>), then we're going to "enrich" them and use a datatype that does. (Note that there are other low-level macro systems that take different approaches to providing the extra information, like explicit renaming and syntactic closures.)</p> <p>The way that this is done is by making macro transformers be functions that consume and return "syntax objects", which are exactly that kind of a representation. More precisely, these syntax objects are usually built on top of the plain symbolic representation, only wrapped in structures that have additional information that represent the lexical scope. In some systems (notably in Racket), everything gets wrapped in syntax objects -- symbols as well as other literals and lists. Given this, it's not surprising that it's easy to get S-expressions out of syntax objects: you just pull out the symbolic contents, and if it's a list, then continue doing that recursively. In syntax-case systems, this is done by <code>syntax-e</code> which implements the accessor for the symbolic content of a syntax object, and <code>syntax-&gt;datum</code> that implements the versions that goes down the result recursively to produce a full S-expression. As a side-note, this is a rough explanation why in Scheme people don't talk about bindings being represented as <em>symbols</em>, but as <em>identifiers</em>.</p> <p>On the other side, the question is how do you start from a given symbolic name and construct such a syntax object. The way that this is done is with the <code>datum-&gt;syntax</code> function -- but instead of making the api specify how is the lexical scope information represented, the function takes in a syntax object as a first argument and a symbolic S-expression as the second argument, and it creates a syntax object by properly wrapping the S-expression with the lexical scope information taken from the first. This means that to break hygiene what you usually do is start with a user-supplied syntax object (eg, a body form of a macro), and use its lexical information to create some new identifier like <code>this</code> that is visible in the same scope.</p> <p>This quick description is enough to see how the macros that you were shown work. The macro that @ChrisJester-Young showed simply takes in the syntax object(s), strips it to a raw S-expression with <code>syntax-&gt;datum</code>, sends that to the <code>defmacro</code> transformer and gets back an S-expression, then it uses <code>syntax-&gt;datum</code> to convert the result back to a syntax object using the user code's lexical context. Racket's <code>defmacro</code> implementation is a bit fancier: during the stripping stage it keeps a hash table that maps the resulting S-expressions to their original syntax objects, and during the reconstruction step it consults this table to get the same context as the bits of code originally had. This makes it a more robust implementation for some more complex macros, but it's also more useful in Racket since syntax objects have much more information in them, like source location, properties, etc, and this careful reconstruction will usually result in output values (syntax objects) that keep the information they had on their way into the macro.</p> <p>For a slightly more technical introduction for <code>defmacro</code> programmers to the syntax-case system, see my <a href="http://blog.racket-lang.org/2011/04/writing-syntax-case-macros.html" rel="noreferrer">writing <code>syntax-case</code> macros</a> blog post. If you're coming from the Scheme side it won't be as useful, but it will still be useful in clarifying the whole issue.</p> <p>To get this closer to a conclusion, I should note that dealing with unhygienic macros can still be tricky. More specifically, there are various ways to achieve such bindings, but they are different in various subtle ways, and can usually come back and bite you leaving slightly different teeth marks in each case. In a "true" <code>defmacro</code> system like CL, you learn to live with a specific set of teeth marks, ones that are relatively well known, and therefore there are things that you just don't do. Most notably here is the kind of modular composition of languages with different bindings for the same names that Racket uses so frequently. In syntax-case systems a better approach is <code>fluid-let-syntax</code> that is used to "adjust" the meaning of a lexically scoped name -- and more recently, that has evolved into "syntax parameters". There is a good <a href="http://www.schemeworkshop.org/2011/papers/Barzilay2011.pdf" rel="noreferrer">overview of the problems of hygiene-breaking macros</a>, which includes a description of how you can attempt to solve it with just hygienic <code>syntax-rules</code>, with basic syntax-case, with CL-style <code>defmacro</code>, and finally with syntax parameters. This text gets a bit more technical, but its relatively easy to read the first few pages, and if you understand this, then you will have a very good picture of the whole debate. (There is also an <a href="http://blog.racket-lang.org/2008/02/dirty-looking-hygiene.html" rel="noreferrer">older blog post</a> that is covered better in the paper.)</p> <p>I should also mention that this is far from being the only "hot" issue around macros. The debate within Scheme circles about which low-level macro system is better can get pretty hot at times. And there are other issues around macros like the question of how to make them work in a module system where a library can provide macros as well as values and functions, or whether to separate macro-expansion time and runtime into separate phases, and more.</p> <p>Hopefully this presents a more complete picture of the issue, to the point of being aware of the tradeoffs and being able to decide for yourself what works best for you. I also hope that this clarifies some of the sources for the usual flames: hygienic macros are certainly not useless, but since the new type is more than just simple S-expressions, there is more functionality around them -- and all too often shallow-reading bypassers jump to a conclusion that "it's too complex". Even worse are flames in the spirit of "in the Scheme world people know close to nothing about metaprogramming": being very painfully aware of the added cost and also of the desired benefits, people in the Scheme world has spent orders of magnitude more collective efforts on the subject. It's a fine choice to stick with <code>defmacro</code> if the extra wrappers around S-expressions are too complicated for your taste, but you should be aware of the cost involved in learning that vs what you pay by dumping hygiene (and vs what you get by embracing it).</p> <p>Unfortunately, macros of any flavor are overall a pretty hard subject for newbies (perhaps excluding the extremely limited <code>syntax-rules</code>), so people tend to find themselves in the middle of such flames without having enough experience to know your left from your right. Ultimately, nothing beats having good experience in both worlds to clarify the tradeoffs. (And that's from very concrete personal experience: had PLT Scheme not switch to syntax case N years ago, I would have probably never bother with it... Once they did switch, it took me a long while to convert my code -- and only then did I realize just how great it is to have a robust system where no names get "confused" by mistake (which would result in weird bugs, and obfuscated <code>%%__names__</code>).)</p> <p>(Still, it's very likely that comment flames will happen...)</p>
17,647,872
PDFsharp edit a pdf file
<p>Environment - PDFsharp Library, Visual Studio 2012 and C# as the language.</p> <p>I am trying to:</p> <ol> <li>read Test1.pdf (Width = 17 inches, Height – 11 inches) with 1 page</li> <li>add some text to it</li> <li>save it as another file (Test2.pdf)</li> </ol> <p>I am able to do all the following. But when I open the file Test2.pdf the size of the page is getting reduced to Width = 11 inches, Height – 11 inches. These PDF files that I am using are Product Specification Sheets that I have downloaded from the internet. I believe this is happening on only certain types of file and I am not sure how to differentiate these files.</p> <p>Code given below:</p> <pre><code>//File dimentions - Width = 17 inches, Height - 11 inches (Tabloid Format) PdfDocument pdfDocument = PdfReader.Open(@"D:\Test1.pdf", PdfDocumentOpenMode.Modify); PdfPage page = pdfDocument.Pages[0]; XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic); gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center); //When the file is saved dimentions change to - Width = 11 inches, Height - 11 inches pdfDocument.Save(@"D:\Test2.pdf"); </code></pre> <p>I have uploaded the file here <a href="https://www.dropbox.com/s/o2kbpmd37egk6lh/Test1.pdf" rel="noreferrer">Test1.pdf</a></p> <p>==================================================================================</p> <p>As suggested by the PDFsharp Team the code should be as follows:</p> <pre><code>PdfDocument PDFDoc = PdfReader.Open(@"D:\Test1.pdf", PdfDocumentOpenMode.Import); PdfDocument PDFNewDoc = new PdfDocument(); for (int Pg = 0; Pg &lt; PDFDoc.Pages.Count; Pg++) { PdfPage pp = PDFNewDoc.AddPage(PDFDoc.Pages[Pg]); XGraphics gfx = XGraphics.FromPdfPage(pp); XFont font = new XFont("Arial", 10, XFontStyle.Regular); gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, pp.Width, pp.Height), XStringFormats.BottomCenter); } PDFNewDoc.Save(@"D:\Test2.pdf"); </code></pre>
17,649,357
1
2
null
2013-07-15 06:20:21.01 UTC
8
2013-07-15 09:33:36.863 UTC
2013-07-15 09:33:36.863 UTC
null
1,571,189
null
1,571,189
null
1
24
c#-4.0|pdf|pdfsharp
43,338
<p>Instead of modifying the document, please create a new document and copy the pages from the old document to the new document.</p> <p>Sample code can be found in this post on the PDFsharp forum:<br> <a href="http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637" rel="noreferrer">http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637</a></p>
17,555,699
Internal Server Error with Django and uWSGI
<p>I am trying to follow the steps in this guide: <a href="http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html">http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html</a></p> <p>Before I even get to the nginx part I am trying to make sure that uWSGI works correctly</p> <p>my folder structure is srv/www/domain/projectdatabank/</p> <p>the project databank folder contains my manage.py file</p> <p>my wsgi.py file looks like this:</p> <pre><code>import os import sys from django.core.wsgi import get_wsgi_application application = get_wsgi_application() </code></pre> <p>do you need to see my settings.py?</p> <p>i get the following error when i point myself to the browser:</p> <p><code>-- no python application found, check your startup logs for errors --- [pid: 10165|app: -1|req: -1/1] 66.56.35.151 () {38 vars in 681 bytes} [Tue Jul 9 18:19:46 2013] GET /admin/ =&gt; generated 21 bytes in 0 msecs (HTTP/1.1 500) 1 headers in 57 bytes (0 switches on core 0) --- no python application found, check your startup logs for errors --- [pid: 10165|app: -1|req: -1/2] 66.56.35.151 () {36 vars in 638 bytes} [Tue Jul 9 18:19:49 2013] GET / =&gt; generated 21 bytes in 0 msecs (HTTP/1.1 500) 1 headers in 57 bytes (0 switches on core 0)</code></p> <p>Now when I check my uWGI log it is just the same as above.</p>
17,555,858
6
0
null
2013-07-09 18:37:14.463 UTC
13
2021-11-03 21:20:50.857 UTC
null
null
null
null
1,555,963
null
1
47
django|uwsgi
94,189
<p>I have solved this</p> <p>in my original command line did not include full path to the wsgi.py file to run uWSGI</p> <pre><code>uwsgi --http :8000 --chdir /srv/www/databankinfo.com/projectdatabank/ --wsgi-file wsgi.py </code></pre> <p>to this</p> <pre><code>uwsgi --http :8000 --chdir /srv/www/databankinfo.com/projectdatabank/ --wsgi-file full/path/wsgi.py </code></pre> <p>and it worked</p>
17,556,250
How to ignore Icon? in git
<p>While trying to setup a dropbox folder with git, I saw a "Icon\r" file which is not created by me. I try to ignore it in the ~/.gitignore file. But adding <code>Icon\r</code> <code>Icon\r\r</code> <code>Icon?</code> won't work at all. </p>
30,755,378
10
4
null
2013-07-09 19:07:39.903 UTC
22
2022-07-02 06:58:09.333 UTC
null
null
null
null
768,823
null
1
62
macos|git
15,744
<p>(This improves on the original answer, following a suggestion by <strong>robotspacer</strong>, according to <strong>hidn</strong>'s <a href="https://stackoverflow.com/a/33974028/192740">explanation</a>.)</p> <p>The <code>Icon?</code> is the file of OS X folder icon. The &quot;<code>?</code>&quot; is a special character for double carriage return (<code>\r\r</code>).</p> <p>To tell <code>git</code> to ignore it, open a terminal and navigate to your repository folder. Then type:</p> <pre><code>printf &quot;Icon\r\r&quot; &gt;&gt; .gitignore </code></pre> <p>If the file does not exist, it will be created and <code>Icon\r\r</code> will be its one line. If the file does exist, the line <code>Icon\r\r</code> will be appended to it.</p>
17,663,186
Initializing a two dimensional std::vector
<p>So, I have the following:</p> <pre><code>std::vector&lt; std::vector &lt;int&gt; &gt; fog; </code></pre> <p>and I am initializing it very naively like:</p> <pre><code> for(int i=0; i&lt;A_NUMBER; i++) { std::vector &lt;int&gt; fogRow; for(int j=0; j&lt;OTHER_NUMBER; j++) { fogRow.push_back( 0 ); } fog.push_back(fogRow); } </code></pre> <p>And it feels very wrong... Is there another way of initializing a vector like this?</p>
17,663,236
13
2
null
2013-07-15 20:21:47.863 UTC
84
2022-08-19 08:22:11.853 UTC
2013-07-15 20:28:24.78 UTC
null
186,193
null
186,193
null
1
170
c++|vector
359,160
<p>Use the <a href="http://en.cppreference.com/w/cpp/container/vector/vector" rel="noreferrer"><code>std::vector::vector(count, value)</code></a> constructor that accepts an initial size and a default value:</p> <pre><code>std::vector&lt;std::vector&lt;int&gt; &gt; fog( ROW_COUNT, std::vector&lt;int&gt;(COLUMN_COUNT)); // Defaults to zero initial value </code></pre> <p>If a value other than zero, say <code>4</code> for example, was required to be the default then:</p> <pre><code>std::vector&lt;std::vector&lt;int&gt; &gt; fog( ROW_COUNT, std::vector&lt;int&gt;(COLUMN_COUNT, 4)); </code></pre> <p>I should also mention uniform initialization was introduced in C++11, which permits the initialization of <code>vector</code>, and other containers, using <code>{}</code>:</p> <pre><code>std::vector&lt;std::vector&lt;int&gt; &gt; fog { { 1, 1, 1 }, { 2, 2, 2 } }; </code></pre>
37,083,445
Reset SQLite database in Django
<p>I am trying to refactor a Django project. I renamed a couple apps and added a new one, as well as shuffled some models around. I want to clear my database and migrations and start fresh, but I am not sure how to accomplish this. Here's what I did:</p> <pre><code>rm -r myapp/migrations // I ran this for all my apps python manage.py flush python manage.py makemigrations myapp // I ran this for all my apps python manage.py migrate // This errors </code></pre> <p>I get an error:</p> <pre><code>django.db.utils.OperationalError: table "myapp_mymodel" already exists </code></pre> <p>Can anyone tell me what I might be doing wrong?</p> <p>EDIT: <a href="https://stackoverflow.com/questions/10605940/what-is-the-django-command-to-delete-all-tables">What is the django command to delete all tables?</a> did not work.</p>
37,083,740
5
4
null
2016-05-07 01:10:35.44 UTC
10
2021-09-26 18:12:11.703 UTC
2017-05-23 11:47:24.667 UTC
null
-1
null
3,593,889
null
1
18
python|django|sqlite
37,382
<p>Delete database and delete migration files (<code>.py</code> and <code>.pyc</code>) in <code>migrations</code> directory of your app (don't delete <code>__init__.py</code> file). Then run <code>python manage.py makemigrations app</code> and <code>python manage.py migrate</code>.</p>
18,269,338
Keep animated View at final Animation Position
<p>So I'm animating a view using animation:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator" &gt; &lt;translate android:duration="1000" android:fromYDelta="0%" android:toYDelta="-75%" /&gt; &lt;/set&gt; </code></pre> <p>It does visually what I want but I also I want to freeze result of this animation. Like I need somehow to get resulting layout parameters (or something else?) after animation and set it to layout. Assume layout Y-coord is changing from 0 to 100 but I don't really know what was starting coords and what are resulting coords. I need to get resulting coords and set it to the layout cuz if wouldn't do so layout returns back to its initial position after animation but I need to make it stay in new position instead of returning back. Also I need 2.3.x compatible solution.<br> <strong>UPDATE 1</strong><br> I also tried NineOldAndroids:</p> <pre><code>ObjectAnimator.ofFloat(rootWrapper, "translationY", -rootWrapper.getHeight()*75/100).start(); </code></pre> <p>this animates the view and view stays at animated position - thats exactly what I want to achieve.<br> However all controls stays at their positions virtually. Even thou layout is only visible by 25% of its bottom part and 75% of rest screen looks empty if I tap that empty screen area then button's (which was there b4 animation) onClick triggered. The same happens with xml-animtaions if set</p> <pre><code>animation.setFillAfter(true); </code></pre> <p>How to fix that issue? All controls has to move with the view.<br> <strong>UPDATE 2</strong><br> The code:</p> <pre><code> public void showAbout(){ final Animation animShow = AnimationUtils.loadAnimation(this, R.anim.about_in_from_bottom); animShow.setFillAfter(true); //ObjectAnimator.ofFloat(rootWrapper, "translationY", -rootWrapper.getHeight()*75/100).start(); animShow.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { LinearLayout.LayoutParams rootlp = (LinearLayout.LayoutParams) rootWrapper.getLayoutParams(); Log.i(this,"rootlp: h: "+rootlp.topMargin+ " / w: "+rootlp.bottomMargin); rootlp.topMargin = -rootlp.height*75/100; rootWrapper.setLayoutParams(rootlp); } }); rootWrapper.startAnimation(animShow); } </code></pre> <p>I got the problem - <code>rootlp.height</code> returns 0 cuz its like MATCH_PARENT or like. It wont return the REAL pixels but some value representing some constant! So it looks like I have 2 play with <code>.getViewTreeObserver().addOnGlobalLayoutListener</code>.<br> Ok, I got the real height of rootWrapper via getViewTreeObserver(). And now using the formula <code>rootlp.topMargin = -rootlp.height*75/100;</code> I'm getting even more issues.<br> 1) After animation View moves up additionally (due to setting LP).<br> 2) Controls that animated View contains (buttons which has to move up with the parent View) stays at their positions virtually (they are invisible but clickable)! Visually those controls are moved up with the animated View and I can't reach it (it goes off the screen). But if I tap area where they was before animation corresponding onClick() triggers! What a fun!<br> <strong>UPDATE 3</strong><br> Finally I had achieved my goal! The problem was with moving View's child containers. I was thinking that if I move some View then all of its child views are also moving. But thats not the case and I was had to move child views manually after animation completes to fix ghost buttons.</p>
18,269,477
3
3
null
2013-08-16 08:47:55.163 UTC
8
2015-07-06 15:40:03.673 UTC
2013-08-16 12:28:53.897 UTC
null
1,811,719
null
1,811,719
null
1
24
android|animation
37,035
<p>Please consider <strong>setFillAfter(boolean);</strong> setting it to true will make the view stay at the animated position.</p> <pre><code>Animation anim = new TranslateAnimation(0, 0, 0, 100); // or like this Animation anim = AnimationUtils.loadAnimation(this, R.anim.animation_name); anim.setFillAfter(true); anim.setDuration(1000); </code></pre> <p>This can be done even easier using the <strong>ViewPropertyAnimator</strong>, available from API 14 and onwards:</p> <pre><code>int animationpos = 500; View.animate().y(animationpos).setDuration(1000); // this will also keep the view at the animated position </code></pre> <p>Or consider an <strong>AnimationListener</strong> to get the LayoutParams exactly after the animation:</p> <pre><code>anim.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { // get layoutparams here and set it in this example your views // parent is a relative layout, please change that to your desires RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) View.getLayoutParams(); lp.topMargin = yournewtopmargin // use topmargin for the y-property, left margin for the x-property of your view View.setLayoutParams(lp); } }); View.startAnimation(anim); </code></pre> <p><strong>UPDATE:</strong></p> <blockquote> <p>How to know how many pixels the view moved, depending on the percentage values of the animation?</p> </blockquote> <p><strong>The percentage value in your .xml animation is relative to the animated View's dimensions (such as width and height).</strong> Therefore, you just need to use <strong>your View's width and height properties</strong> (depending on weather u use x or y animation to get the actual animation distance in pixels).</p> <p>For example:</p> <p>Your View has a width of 400 pixels. Your animation animates the x-property from 0% to 75%, meaning that your view will move 300 pixels (400 * 0.75) to the right side. So onAnimationEnd(), set the LayoutParams.leftMargin to 300 and your View will have the desired position.</p>
18,437,594
Angularjs: call other scope which in iframe
<p>In my test, given 2 document, A and B. In A document, there is an iframe, the iframe source is B document. My question is how to modify B document certain scope of variable?</p> <p>Here is my code: A document</p> <p></p> <pre><code>&lt;html lang="en" ng-app=""&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Google Phone Gallery&lt;/title&gt; &lt;script type='text/javascript' src="js/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;script type='text/javascript' src="js/angular1.0.2.min.js"&gt;&lt;/script&gt; &lt;script&gt; var g ; function test($scope,$http,$compile) { $scope.tryget = function(){ var iframeContentWindow = $("#iframe")[0].contentWindow; var iframeDOM = $("#iframe")[0].contentWindow.document; var target = $(iframeDOM).find("#test2"); var iframeAngular = iframeContentWindow.angular; var iframeScope = iframeAngular.element("#test2").scope(); iframeScope.parentcall(); iframeContentWindow.angular.element("#test2").scope().tempvalue = 66 ; iframeScope.tempvalue = 66; iframeContentWindow.tt = 22; iframeScope.parentcall(); console.log(iframeScope.tempvalue); console.log(angular.element("#cont").scope()); } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div ng-controller="test"&gt; &lt;div id="cont" &gt; &lt;button ng-click="tryget()"&gt;try&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;iframe src="test2.html" id="iframe"&gt;&lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My B document:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en" ng-app=""&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Google Phone Gallery&lt;/title&gt; &lt;script type='text/javascript' src="js/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;script type='text/javascript' src="js/angular1.0.2.min.js"&gt;&lt;/script&gt; &lt;script&gt; var tt =11; function test2($scope,$http,$compile) { console.log("test2 controller initialize"); $scope.tempvalue=0; $scope.parentcall = function() { $scope.tempvalue = 99 ; console.log($scope.tempvalue); console.log(tt); } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div ng-controller="test2" id="test2"&gt; &lt;div id="cont" &gt; &lt;button ng-click="parentcall()"&gt;get script&lt;/button&gt; &lt;/div&gt; {{tempvalue}} &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Note: Actually there is some way to do it, which i feel it like a hack instead of proper way to get it done: that is create a button in b Document, and then bind with angularjs ng-click. After that A document jquery "trigger" click on button.</p>
21,733,164
4
2
null
2013-08-26 06:03:41.343 UTC
19
2018-10-19 09:51:38.657 UTC
null
null
null
null
1,528,153
null
1
25
javascript|angularjs|angularjs-scope
41,067
<p>To access and communicate in two directions (parent to iFrame, iFrame to parent), in case they are both in the same domain, with access to the angular scope, try following those steps: </p> <p>*You don’t need the parent to have reference to angularJS library…</p> <p><strong>Calling to child iFrame from parent</strong></p> <p>1.Get child iFrame element from the parent (<a href="https://stackoverflow.com/questions/251420/invoking-javascript-code-in-an-iframe-from-the-parent-page">link to answer</a>): </p> <blockquote> <p>document.getElementById("myIframe").contentWindow</p> </blockquote> <p>2.Access the scope of the element: </p> <blockquote> <p>document.getElementById("myIframe").contentWindow.angular.element("#someDiv").scope()</p> </blockquote> <p>3.Call the scope’s function or property: </p> <blockquote> <p>document.getElementById("myIframe").contentWindow.angular.element("#someDiv").scope().someAngularFunction(data);</p> </blockquote> <p>4.Call $scope.$apply after running the logic of the function/updating the property (<a href="https://stackoverflow.com/questions/10490570/call-angular-js-from-legacy-code/10508731#10508731">link to Mishko’s answer</a>): </p> <blockquote> <p>$scope.$apply(function () { });</p> </blockquote> <ul> <li>Another solution is to share the scope between the iFrames, but then you need angular in both sides: (<a href="https://stackoverflow.com/questions/19125910/is-it-possible-to-update-angularjs-expressions-inside-of-an-iframe/19126316#19126316">link to answer and example</a>)</li> </ul> <p><strong>Calling parent from child iFrame</strong></p> <ol> <li>Calling the parent function: </li> </ol> <blockquote> <p>parent.someChildsFunction();</p> </blockquote> <p>Will update also on how to do it cross domain if it is necessary..</p>