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
18,789,973
Sortable table columns with AngularJs
<p>I'm trying to sort a table of data which is populated from a JSON source. The code I have is as follows:</p> <p>HTML:</p> <pre><code>&lt;div ng-app="myApp"&gt; &lt;div ng-controller="PurchasesCtrl"&gt; &lt;table cellspacing="0"&gt; &lt;tr class="first"&gt; &lt;th class="first" ng:click="changeSorting(purchases.date)"&gt;Date&lt;/th&gt; &lt;th ng:click="changeSorting(purchases.text)"&gt;Description&lt;/th&gt; &lt;th ng:click="changeSorting(purchases.price)"&gt;Amount&lt;/th&gt; &lt;th ng:click="changeSorting(purchases.availability)"&gt;Status&lt;/th&gt; &lt;/tr&gt; &lt;tr ng-repeat="purchase in purchases.data"&gt; &lt;td class="first"&gt;{{purchase.date}}&lt;/td&gt; &lt;td&gt;{{purchase.text}}&lt;/td&gt; &lt;td&gt;{{purchase.price}}&lt;/td&gt; &lt;td&gt;{{purchase.availability}}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code>var myApp = angular.module("myApp",[]); myApp.factory("Purchases", function(){ var Purchases = {}; Purchases.data = [ { date: "10/05/2012", text: "1 Lorem ipsum dolor sit amet ipsum dolor", price: "£123.45", availability: "1 Available until 10th Dec 2013" }, { date: "24/05/2012", text: "2 Lorem ipsum dolor sit amet ipsum dolor", price: "£234.56", availability: "2 Available until 10th Dec 2013" }, { date: "20/05/2012", text: "3 Lorem ipsum dolor sit amet ipsum dolor", price: "£345.67", availability: "3 Available until 10th Dec 2013" } ]; return Purchases; }); function PurchasesCtrl($scope, Purchases){ $scope.purchases = Purchases; $scope.changeSorting = function(column) { var sort = $scope.sort; if (sort.column == column) { sort.descending = !sort.descending; } else { sort.column = column; sort.descending = false; } }; } </code></pre> <p>Fiddle: <a href="http://jsfiddle.net/7czsM/1/">http://jsfiddle.net/7czsM/1/</a></p> <p>As you can see I've tried to add a click function to the table headers to call a function that sorts the data, but it's not working. </p> <p>I've seen an example of this kind of thing which does work, here: <a href="http://jsfiddle.net/vojtajina/js64b/14/">http://jsfiddle.net/vojtajina/js64b/14/</a>, but when I try to apply the same kind of thing to my scenario it breaks very quickly; for example, I tried adding the table headers programatically in JSON by adding the following:</p> <pre><code>var Purchases = {}; Purchases.head = [ { date: "Date", text: "Text column", price: "Price column", availability: "Availability column" } Purchases.data = [ { date: "10/05/2012", text: "1 Lorem ipsum dolor sit amet ipsum dolor", price: "£123.45", availability: "1 Available until 10th Dec 2013" }, </code></pre> <p>This just prevents anything from working, but I thought it would be possible to add multiple sets of data to an Angular variable?</p> <p>I'm a total new-comer to Angular so I'm really stuck with this. Any pointers would be much appreciated, thanks.</p>
18,790,499
5
2
null
2013-09-13 15:26:06.56 UTC
6
2019-10-08 16:23:23.28 UTC
null
null
null
null
405,781
null
1
11
angularjs|angularjs-ng-repeat
40,165
<p>Updated jsfiddle: <a href="http://jsfiddle.net/gweur/">http://jsfiddle.net/gweur/</a></p> <p>sza is right, you did forget the $scope.sort object, but you are also missing the orderBy filter in your ng-repeat</p> <pre><code>|orderBy:sort.column:sort.descending </code></pre> <p>Additionally, you'll need to explicitly pass the column name to the changeSorting() function, like </p> <pre><code>ng-click="changeSorting('text')" </code></pre> <p>not sure if there is a different way you can handle this. </p> <p>Finally, ng-click is the correct syntax for the version of AngularJS you are using. </p>
19,205,547
Implementing Simple SeekBar in android
<p><strong>Filters.java</strong></p> <pre><code>public class Filters extends Activity implements OnSeekBarChangeListener{ private SeekBar PRICEbar,DISTANCEbar, RATINGbar; // declare seekbar object variable // declare text label objects private TextView PRICEtextProgress,DISTANCEtextProgress, RATINGtextProgress; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // load the layout setContentView(R.layout.filters); PRICEbar = (SeekBar)findViewById(R.id.PRICEseekBarID); // make seekbar object PRICEbar.setOnSeekBarChangeListener(this); PRICEbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub PRICEtextProgress = (TextView)findViewById(R.id.PRICEtextViewProgressID); PRICEtextProgress.setText(&quot;Price:: Rs &quot;+progress); } }); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (seekBar == PRICEbar) PRICEtextProgress.setText(&quot;Price:: Rs &quot;+progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } } </code></pre> <p><strong>filters.xml</strong></p> <pre><code>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:orientation=&quot;vertical&quot; &gt; &lt;RelativeLayout android:id=&quot;@+id/relativeLayoutforPRICE&quot; android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot; &gt; &lt;TextView android:id=&quot;@+id/PRICEtextViewProgressID&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_alignParentLeft=&quot;true&quot; android:layout_alignParentTop=&quot;true&quot; android:text=&quot;Price&quot; android:textAppearance=&quot;?android:attr/textAppearanceLarge&quot; &gt; &lt;/TextView&gt; &lt;SeekBar android:id=&quot;@+id/PRICEseekBarID&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:layout_alignParentLeft=&quot;true&quot; android:layout_below=&quot;@+id/textView1&quot; android:layout_marginTop=&quot;26dp&quot; android:max=&quot;100&quot; &gt; &lt;/SeekBar&gt; &lt;/RelativeLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>I have an output like this::</p> <p><img src="https://i.stack.imgur.com/jr6r0.png" alt="image of obnoxious slider for selecting amount" /></p> <p>How to modify my code to get initial and final values in the seek bar as in figure below?</p> <p><img src="https://i.stack.imgur.com/cDhew.png" alt="obnoxious slider with min 0 and max 100, but these values should be configurable from other inputs" /></p>
19,205,579
5
2
null
2013-10-06 04:50:23.433 UTC
3
2021-03-25 05:12:07.34 UTC
2021-03-25 05:10:50.347 UTC
null
874,188
null
1,083,093
null
1
14
android|xml|seekbar
54,770
<p>You have already defined max value of seekbar </p> <pre><code>android:max="100" </code></pre> <p>Now you need to add <strong>two textviews on left and right of seekbar</strong>. Use <strong>Relative layout</strong> and align both <strong>textviews Left and Right</strong> to the parent.</p>
27,711,184
Why is PIP raising an AssertionError on pip freeze?
<p>My console:</p> <pre><code>desarrollador@desarrollador-HP-14-Notebook-PC1:~$ pip freeze Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 126, in main self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/freeze.py", line 68, in run req = pip.FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags) File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 156, in from_dist assert len(specs) == 1 and specs[0][0] == '==' AssertionError </code></pre> <p>I installed the tornado package and this happened since. How can I fix it?</p>
27,948,576
7
4
null
2014-12-30 19:15:29.453 UTC
6
2019-12-02 05:09:08.793 UTC
2019-12-02 05:09:08.793 UTC
null
498,256
null
1,105,249
null
1
39
pip
14,924
<p>Reason: The python-pip package in Ubuntu 12.04 is seriously outdated and has some bugs with certain package names (as I can see) and cannot parse them correctly.</p> <p>Solution: install a newer version of pip, via easy_install.</p>
1,104,599
Convert byte array to short array in C#
<p>I'm currently reading a file and wanted to be able to convert the array of bytes obtained from the file into a short array.</p> <p>How would I go about doing this?</p>
1,104,615
7
1
null
2009-07-09 15:23:28.097 UTC
4
2016-11-15 09:59:24.383 UTC
null
null
null
null
47,013
null
1
15
c#|bytearray
40,587
<p>One possibility is using <a href="http://msdn.microsoft.com/en-us/library/bb548891.aspx" rel="noreferrer"><code>Enumerable.Select</code></a>:</p> <pre><code>byte[] bytes; var shorts = bytes.Select(b =&gt; (short)b).ToArray(); </code></pre> <p>Another is to use <a href="http://msdn.microsoft.com/en-us/library/exc45z53.aspx" rel="noreferrer"><code>Array.ConvertAll</code></a>:</p> <pre><code>byte[] bytes; var shorts = Array.ConvertAll(bytes, b =&gt; (short)b); </code></pre>
748,965
What is a multibyte character set?
<p>Does the term multibyte refer to a charset whose characters can - but don't have to be - wider than 1 byte, (e.g. UTF-8) or does it refer to character sets which are in any case wider than 1 byte (e.g. UTF-16) ? In other words: What is meant if anybody talks about multibyte character sets?</p>
749,028
9
0
null
2009-04-14 19:17:46.103 UTC
8
2021-09-09 07:48:57.857 UTC
null
null
null
null
49,628
null
1
45
utf-8|terminology|multibyte
92,935
<p>The term is ambiguous, but in my internationalization work, we typically avoided the term "multibyte character sets" to refer to Unicode-based encodings. Generally, we used the term only for legacy encoding schemes that had one or more bytes to define each character (excluding encodings that require only one byte per character).</p> <p>Shift-jis, jis, euc-jp, euc-kr, along with Chinese encodings are typically included.</p> <p>Most of the legacy encodings, with some exceptions, require a sort of state machine model (or, more simply, a page swapping model) to process, and moving backwards in a text stream is complicated and error-prone. UTF-8 and UTF-16 do not suffer from this problem, as UTF-8 can be tested with a bitmask and UTF-16 can be tested against a range of surrogate pairs, so moving backward and forward in a non-pathological document can be done safely without major complexity.</p> <p>A few legacy encodings, for languages like Thai and Vietnamese, have some of the complexity of multibyte character sets but are really just built on combining characters, and aren't generally lumped in with the broad term "multibyte."</p>
455,061
how do I check that two folders are the same in linux
<p>I have moved a web site from one server to another and I copied the files using SCP </p> <p>I now wish to check that all the files have been copied OK.</p> <p>How do I compare the sites?</p> <p>Count files for a folder?</p> <p>Get the total files size for folder tree?</p> <p>or is there a better way to compare the sites?</p> <p>Paul</p>
455,085
10
1
null
2009-01-18 12:36:32.797 UTC
12
2016-03-14 10:05:07.88 UTC
2009-01-18 13:27:52.577 UTC
Rob Wells
2,974
null
3,582
null
1
30
linux|web
26,828
<p>If you were using scp, you could probably have used <a href="http://samba.anu.edu.au/rsync/" rel="noreferrer">rsync</a>. </p> <p>rsync won't transfer files that are already up to date, so you can use it to verify a copy is current by simply running rsync again.</p> <p>If you were doing something like this on the old host:</p> <pre><code>scp -r from/my/dir newhost:/to/new/dir </code></pre> <p>Then you could do something like</p> <pre><code>rsync -a --progress from/my/dir newhost:/to/new/dir </code></pre> <p>The '-a' is short for 'archive' which does a recursive copy and preserves permissions, ownerships etc. Check the <a href="http://samba.anu.edu.au/ftp/rsync/rsync.html" rel="noreferrer">man page</a> for more info, as it can do a lot of clever things.</p>
124,143
Why are Exceptions not Checked in .NET?
<p>I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions.<br/> <strong>What is the main reason of the difference between Java and C# in throwing exceptions?</strong><br/> In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.</p>
124,175
10
0
null
2008-09-23 21:52:24.603 UTC
17
2016-03-11 21:47:50.383 UTC
2008-09-26 20:06:31.53 UTC
Dima
13,313
Scuffia
68,336
null
1
42
java|.net|exception
9,997
<p>Because the response to checked exceptions is almost always:</p> <pre><code>try { // exception throwing code } catch(Exception e) { // either log.error("Error fooing bar",e); // OR throw new RuntimeException(e); } </code></pre> <p>If you actually know that there is something you can do if a particular exception is thrown, then you can catch it and then handle it, but otherwise it's just incantations to appease the compiler.</p>
248,760
VB6 Editor changing case of variable names
<p>I'm not much of a Visual Basic person, but I am tasked with maintaining an old VB6 app. Whenever I check out a file, the editor will replace a bunch of the uppercase variable names with lowercase automatically. How can I make this stop!? I don't want to have to change them all back, and it's a pain to have these changes show up in SourceSafe "Differences" when I'm trying to locate the REAL differences.</p> <p>It is changing it automatically in the definition, too: <code>Dim C as Control</code> becomes <code>Dim c as Control</code>. <code>Dim X&amp;</code> becomes <code>Dim x&amp;</code>. But it doesn't do it all the time; for example, three lines down from <code>Dim x&amp;</code>, there's a <code>Dim Y&amp;</code>, uppercase, which it did not change. Why's it do this to me?</p>
248,853
10
1
null
2008-10-29 23:11:37.143 UTC
11
2021-03-17 20:36:16.273 UTC
2019-12-17 09:16:22.187 UTC
Mike Spross
12,258,312
Laure
32,613
null
1
42
ide|vb6
19,057
<p>Continuing from <a href="https://stackoverflow.com/questions/248760/vb6-editor-changing-case-of-variable-names#248773">DJ's answer</a>...</p> <p>And it won't only change the case of variables in the same scope either.</p> <p>It will change the case of all variables with the same name in your entire project. So even if they're declared in uppercase in one place, another module might have different variables using the same variable names in lowercase, causing all variables in your project to change to lowercase, depending on which of the declarations was loaded (?) or edited last.</p> <p>So the reason your C and X variables are changing case, while the Y isn't, is probably because C and X are declared somewhere else in your project too, but in lowercase, while Y isn't.</p> <p>There's another mention of it <a href="http://www.programmingtalk.com/showthread.php?t=47839" rel="nofollow noreferrer">here</a>, where they mostly seem concerned with such variable names conflicting when case is being used to differentiate local from global variables. They end up going for prefixes instead.</p> <p>The only alternative I can think of is to use some other editor with VB6-highlighting capabilities to do your editing...</p>
270,138
How do I draw lines using XNA?
<p>I've read a bunch of tutorials involving XNA (and it's various versions) and I still am a little confused on drawing primitives. Everything seems to be really convoluted.</p> <p>Can someone show me, using code, the simplest XNA implementation of drawing one or two lines on to the screen? Perhaps with a brief explanation (including the boilerplate)?</p> <p>I'm not a games programmer and I have little XNA experience. My ultimate goal is to draw some lines onto the screen which I will eventually transform with rotations, etc (by hand). However, for this first step.. I need to simply draw the lines! I remember back in my ancient OpenGL days it was fairly straightforward when drawing a line with a few method calls. Should I simply revert to using unmanaged directx calls?</p>
270,179
10
0
null
2008-11-06 20:32:02.497 UTC
10
2020-04-25 18:34:42.12 UTC
2008-11-06 20:37:38.6 UTC
Simucal
2,635
Simucal
2,635
null
1
46
drawing|xna|lines|primitive|shapes
63,927
<p>When working with XNA, everything (even 2d primitives) have to be expressed in a way that a 3d card can understand, which means that a line is just a set of vertices.</p> <p>MSDN has a pretty good walkthrough here:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb196414.aspx#ID2EEF" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb196414.aspx#ID2EEF</a></p> <p>You'll find that it takes more code to render a primitive line than it would take to just setup a textured quad and rotate that, since in essence, your doing the same thing when rendering a line.</p>
322,470
Can I invoke an instance method on a Ruby module without including it?
<h3>Background:</h3> <p>I have a module which declares a number of instance methods</p> <pre><code>module UsefulThings def get_file; ... def delete_file; ... def format_text(x); ... end </code></pre> <p>And I want to call some of these methods from within a class. How you normally do this in ruby is like this:</p> <pre><code>class UsefulWorker include UsefulThings def do_work format_text("abc") ... end end </code></pre> <h3>Problem</h3> <p><code>include UsefulThings</code> brings in <em>all</em> of the methods from <code>UsefulThings</code>. In this case I only want <code>format_text</code> and explicitly do not want <code>get_file</code> and <code>delete_file</code>.</p> <p>I can see several possible solutions to this: </p> <ol> <li>Somehow invoke the method directly on the module without including it anywhere <ul> <li>I don't know how/if this can be done. (Hence this question)</li> </ul></li> <li>Somehow include <code>Usefulthings</code> and only bring in some of it's methods <ul> <li>I also don't know how/if this can be done</li> </ul></li> <li>Create a proxy class, include <code>UsefulThings</code> in that, then delegate <code>format_text</code> to that proxy instance <ul> <li>This would work, but anonymous proxy classes are a hack. Yuck.</li> </ul></li> <li>Split up the module into 2 or more smaller modules <ul> <li>This would also work, and is probably the best solution I can think of, but I'd prefer to avoid it as I'd end up with a proliferation of dozens and dozens of modules - managing this would be burdensome</li> </ul></li> </ol> <p>Why are there lots of unrelated functions in a single module? It's <code>ApplicationHelper</code> from a rails app, which our team has de-facto decided on as the dumping ground for anything not specific enough to belong anywhere else. Mostly standalone utility methods that get used everywhere. I could break it up into seperate helpers, but there'd be 30 of them, all with 1 method each... this seems unproductive</p>
322,526
10
2
null
2008-11-26 23:03:37.793 UTC
52
2019-10-01 23:48:14.28 UTC
2014-09-11 16:06:09.63 UTC
Orion Edwards
322,020
Orion Edwards
234
null
1
206
ruby|module|methods
155,639
<p>If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as</p> <pre><code>module Mods def self.foo puts "Mods.foo(self)" end end </code></pre> <p>The module_function approach below will avoid breaking any classes which include all of Mods.</p> <pre><code>module Mods def foo puts "Mods.foo" end end class Includer include Mods end Includer.new.foo Mods.module_eval do module_function(:foo) public :foo end Includer.new.foo # this would break without public :foo above class Thing def bar Mods.foo end end Thing.new.bar </code></pre> <p>However, I'm curious why a set of unrelated functions are all contained within the same module in the first place? </p> <p><em>Edited</em> to show that includes still work if <code>public :foo</code> is called after <code>module_function :foo</code></p>
708,352
How do I reinitialize or reset the properties of a class?
<p>I've created a class with properties that have default values. At some point in the object's lifetime, I'd like to "reset" the object's properties back to what they were when the object was instantiated. For example, let's say this was the class:</p> <pre><code>public class Truck { public string Name = "Super Truck"; public int Tires = 4; public Truck() { } public void ResetTruck() { // Do something here to "reset" the object } } </code></pre> <p>Then at some point, after the <code>Name</code> and <code>Tires</code> properties have been changed, the <code>ResetTruck()</code> method could be called and the properties would be reset back to "Super Truck" and 4, respectively.</p> <p>What's the best way to reset the properties back to their initial hard-coded defaults?</p>
708,363
11
0
null
2009-04-02 04:56:26.79 UTC
1
2022-05-18 20:32:38.503 UTC
null
null
null
Dylan
551
null
1
15
c#|class|properties|instantiation
59,586
<p>You can have the initialization in a method instead of inlining with the declaration. Then have the constructor and reset method call the initialization method:</p> <pre><code>public class Truck { public string Name; public int Tires; public Truck() { Init(); } public void ResetTruck() { Init(); } private void Init() { Name = "Super Truck"; Tires = 4; } } </code></pre> <p>Another way is not to have a reset method at all. Just create a new instance.</p>
1,341,847
Apostrophe (') in XPath query
<p>I use the following <code>XPATH Query</code> to list the object under a site. <code>ListObject[@Title='SomeValue']</code>. SomeValue is dynamic. This query works as long as SomeValue does not have an apostrophe ('). Tried using escape sequence also. Didn't work. </p> <p>What am I doing wrong?</p>
1,352,556
11
2
null
2009-08-27 15:31:12.493 UTC
12
2022-06-09 05:31:17.26 UTC
2021-10-10 13:42:44.827 UTC
null
290,085
null
141,282
null
1
42
c#|java|xml|xpath
44,283
<p>This is surprisingly difficult to do.</p> <p>Take a look at the <a href="http://www.w3.org/TR/xpath" rel="noreferrer">XPath Recommendation</a>, and you'll see that it defines a literal as:</p> <pre><code>Literal ::= '"' [^"]* '"' | "'" [^']* "'" </code></pre> <p>Which is to say, string literals in XPath expressions can contain apostrophes or double quotes but not both.</p> <p>You can't use escaping to get around this. A literal like this:</p> <pre><code>'Some&amp;apos;Value' </code></pre> <p>will match this XML text:</p> <pre><code>Some&amp;amp;apos;Value </code></pre> <p>This does mean that it's possible for there to be a piece of XML text that you can't generate an XPath literal to match, e.g.:</p> <pre><code>&lt;elm att="&amp;quot;&amp;apos"/&gt; </code></pre> <p>But that doesn't mean it's impossible to match that text with XPath, it's just tricky. In any case where the value you're trying to match contains both single and double quotes, you can construct an expression that uses <code>concat</code> to produce the text that it's going to match:</p> <pre><code>elm[@att=concat('"', "'")] </code></pre> <p>So that leads us to this, which is a lot more complicated than I'd like it to be:</p> <pre><code>/// &lt;summary&gt; /// Produce an XPath literal equal to the value if possible; if not, produce /// an XPath expression that will match the value. /// /// Note that this function will produce very long XPath expressions if a value /// contains a long run of double quotes. /// &lt;/summary&gt; /// &lt;param name="value"&gt;The value to match.&lt;/param&gt; /// &lt;returns&gt;If the value contains only single or double quotes, an XPath /// literal equal to the value. If it contains both, an XPath expression, /// using concat(), that evaluates to the value.&lt;/returns&gt; static string XPathLiteral(string value) { // if the value contains only single or double quotes, construct // an XPath literal if (!value.Contains("\"")) { return "\"" + value + "\""; } if (!value.Contains("'")) { return "'" + value + "'"; } // if the value contains both single and double quotes, construct an // expression that concatenates all non-double-quote substrings with // the quotes, e.g.: // // concat("foo", '"', "bar") StringBuilder sb = new StringBuilder(); sb.Append("concat("); string[] substrings = value.Split('\"'); for (int i = 0; i &lt; substrings.Length; i++ ) { bool needComma = (i&gt;0); if (substrings[i] != "") { if (i &gt; 0) { sb.Append(", "); } sb.Append("\""); sb.Append(substrings[i]); sb.Append("\""); needComma = true; } if (i &lt; substrings.Length - 1) { if (needComma) { sb.Append(", "); } sb.Append("'\"'"); } } sb.Append(")"); return sb.ToString(); } </code></pre> <p>And yes, I tested it with all the edge cases. That's why the logic is so stupidly complex:</p> <pre><code> foreach (string s in new[] { "foo", // no quotes "\"foo", // double quotes only "'foo", // single quotes only "'foo\"bar", // both; double quotes in mid-string "'foo\"bar\"baz", // multiple double quotes in mid-string "'foo\"", // string ends with double quotes "'foo\"\"", // string ends with run of double quotes "\"'foo", // string begins with double quotes "\"\"'foo", // string begins with run of double quotes "'foo\"\"bar" // run of double quotes in mid-string }) { Console.Write(s); Console.Write(" = "); Console.WriteLine(XPathLiteral(s)); XmlElement elm = d.CreateElement("test"); d.DocumentElement.AppendChild(elm); elm.SetAttribute("value", s); string xpath = "/root/test[@value = " + XPathLiteral(s) + "]"; if (d.SelectSingleNode(xpath) == elm) { Console.WriteLine("OK"); } else { Console.WriteLine("Should have found a match for {0}, and didn't.", s); } } Console.ReadKey(); } </code></pre>
447,456
What the typical viewport size on a 1024x768 screen?
<p>I am designing a web application, and I wish to know the largest size (x and y) that I can design for.</p> <p><a href="http://www.w3schools.com/browsers/browsers_display.asp" rel="nofollow noreferrer">As of January 2008</a>, about half of users are using 1024x278 screens, and probably less than 10% are using smaller screens. (Phone and palmtop users are an exception here.) So we are designing for minimum screen size of 1024x768.</p> <p><em>However</em>, that's the screen size, and when we are laying out our content we need to know the <em>viewport</em> size. <a href="http://www.baekdal.com/articles/Usability/actual-browser-size-preliminary/" rel="nofollow noreferrer">There is evidence</a> that most users have the browser maximized, but one still must subtract out space for OS decorations and browser chrome. People customize their chrome, so there is no single "right" answer; I am going for a reasonable bound that will accommodate the majority of users.</p> <p>I see <a href="https://stackoverflow.com/questions/202557/what-is-the-best-absolute-width-for-a-webpage">plenty of designers</a> who say that they use a width of 960 pixels because it has many factors and can be divided up evenly -- but before deciding on this I want to know the <em>maximum</em> size that I can get away with, then I might choose to use somewhat less. I have seen max widths of 960, 974 or even 990 quoted... my own experiments seem to show a width of 1000 works OK.</p> <p>Heights are even more difficult to come by: I find I can fit a vertical viewport height of 595 pixels works on the browsers that I've tried, with typical default OS and chrome settings. But I haven't tried very many, and I would rather see a more authoritative source. Surely someone else has done this research and done it better than me.</p> <p>So my real question is this: What is the largest viewport size I can design for and expect it to fit without scrollbars for 80-90% of all users?</p>
1,921,958
13
0
null
2009-01-15 16:28:01.26 UTC
8
2015-04-15 22:56:04.003 UTC
2017-05-23 12:17:05.463 UTC
null
-1
mcherm
14,570
null
1
25
html|browser|cross-browser
69,763
<p>Today I just came across a site which is HIGHLY relevant to this old question of mine. Apparently Google is willing to share their knowledge about browser window sizes. Their new service is at <a href="http://browsersize.googlelabs.com/" rel="nofollow noreferrer">http://browsersize.googlelabs.com/</a> and it basically just shows you their data on typical browser portal sizes.</p> <p><strong>Note</strong>: The Google Labs browsersize is now very out of date (the image is titled <code>2009-11-18-day_google_com_100_donate_example.png</code>) and <a href="http://analytics.blogspot.ca/2012/06/new-feature-conduct-browser-size.html" rel="nofollow noreferrer">will be shut down soon</a>. Google suggests that Google Analytics can be used to determine browser size distribution for your own site: <a href="http://analytics.blogspot.ca/2012/06/new-feature-conduct-browser-size.html" rel="nofollow noreferrer">http://analytics.blogspot.ca/2012/06/new-feature-conduct-browser-size.html</a></p>
226,689
Unique element ID, even if element doesn't have one
<p>I'm writing a GreaseMonkey script where I'm iterating through a bunch of elements. For each element, I need a string ID that I can use to reference that element later. The element itself doesn't have an <code>id</code> attribute, and I can't modify the original document to give it one (although I can make DOM changes in my script). I can't store the references in my script because when I need them, the GreaseMonkey script itself will have gone out of scope. Is there some way to get at an "internal" ID that the browser uses, for example? A Firefox-only solution is fine; a cross-browser solution that could be applied in other scenarios would be awesome.</p> <p>Edit:</p> <ul> <li><p><strong>If the GreaseMonkey script is out of scope, how are you referencing the elements later?</strong> They GreaseMonkey script is adding events to DOM objects. I can't store the references in an array or some other similar mechanism because when the event fires, the array will be gone because the GreaseMonkey script will have gone out of scope. So the event needs some way to know about the element reference that the script had when the event was attached. And the element in question is not the one to which it is attached.</p></li> <li><p><strong>Can't you just use a custom property on the element?</strong> Yes, but the problem is on the lookup. I'd have to resort to iterating through all the elements looking for the one that has that custom property set to the desired id. That would work, sure, but in large documents it could be very time consuming. I'm looking for something where the browser can do the lookup grunt work.</p></li> <li><p><strong>Wait, can you or can you not modify the document?</strong> I can't modify the source document, but I can make DOM changes in the script. I'll clarify in the question.</p></li> <li><p><strong>Can you not use closures?</strong> Closuses did turn out to work, although I initially thought they wouldn't. See my later post.</p></li> </ul> <p>It sounds like the answer to the question: "Is there some internal browser ID I could use?" is "No."</p>
230,114
13
4
null
2008-10-22 16:58:56.097 UTC
8
2017-07-07 07:36:52.02 UTC
2008-10-23 15:04:27.76 UTC
Robert J. Walker
4,287
Robert J. Walker
4,287
null
1
42
javascript|firefox|dom|greasemonkey
43,020
<p><strong>UPDATE:</strong> Closures are indeed the answer. So after fiddling with it some more, I figured out why closures were initially problematic and how to fix it. The tricky thing with a closure is you have to be careful when iterating through the elements not to end up with all of your closures referencing the same element. For example, this doesn't work:</p> <pre><code>for (var i = 0; i &lt; elements.length; i++) { var element = elements[i]; var button = document.createElement("button"); button.addEventListener("click", function(ev) { // do something with element here }, false) } </code></pre> <p>But this does:</p> <pre><code>var buildListener = function(element) { return function(ev) { // do something with event here }; }; for (var i = 0; i &lt; elements.length; i++) { var element = elements[i]; var button = document.createElement("button"); button.addEventListener("click", buildListener(element), false) } </code></pre> <p>Anyway, I decided not to select one answer because the question had two answers: 1) No, there are no internal IDs you can use; 2) you should use closures for this. So I simply upvoted the first people to say whether there were internal IDs or who recommended generating IDs, plus anyone who mentioned closures. Thanks for the help!</p>
334,708
GET parameters in the URL with CodeIgniter
<p>I know that codeIgniter turns off GET parameters by default. </p> <p>But by having everything done in POST, don't you get annoyed by the re-send data requests if ever you press back after a form submission?</p> <p>It annoys me, but I'm not sure if I want to allow GET purely for this reason.</p> <p>Is it such a big security issue to allow GET parameters too?</p>
334,787
17
1
null
2008-12-02 17:05:36.66 UTC
22
2021-02-02 23:40:45.673 UTC
2011-11-09 11:40:40.303 UTC
null
42,106
null
42,106
null
1
49
html|codeigniter|post|get
205,596
<p>When I first started working with CodeIgniter, not using GET really threw me off as well. But then I realized that you can simulate GET parameters by manipulating the URI using the built-in <a href="http://codeigniter.com/user_guide/libraries/uri.html" rel="noreferrer">URI Class</a>. It's fantastic and it makes your URLs look better.</p> <p>Or if you really need GETs working you can put this into your controller:</p> <pre><code>parse_str($_SERVER['QUERY_STRING'], $_GET); </code></pre> <p>Which will put the variables back into the GET array. </p>
6,935,006
Making curl send errors to stderr and everything else to stdout
<p>Is there a way to tell curl to output errors to stderr, and everything else to stdout?</p> <p>The reason is that I am using curl from the command line (actually a cronjob) to upload a file to an FTP site every evening. Unfortunately because curl outputs status information on stderr, I receive an e-mail about an error when nothing actually went wrong. (I'm redirecting stdout to a log file, but leaving stderr unchanged so that cron will e-mail it to me if there is any output.)</p> <p>There are options to make curl silent, or output everything to stdout, however both these alternatives prevent errors from appearing on stderr - meaning I won't get an e-mail when there is actually an error I want to know about.</p> <p>So is there a way to make curl only output errors on stderr, but leave normal output intact on stdout?</p>
6,935,338
4
0
null
2011-08-04 00:49:35.463 UTC
3
2022-03-08 09:54:15.87 UTC
2016-12-22 08:16:57.887 UTC
null
308,237
null
308,237
null
1
43
curl|stdout|stderr
46,103
<p>After some more experimentation I have come up with the following workaround, but I'm still open to better alternatives.</p> <p>It works by temporarily storing all output (stdout and stderr) in a temporary file, and then sending the contents of that file to stderr or stdout depending on curl's exit code. If curl failed the entire output will go to stderr (and be e-mailed to me thanks to cron), but if curl succeeded the output will go to stdout instead (which is redirected to a log file in the cron command, resulting in no e-mail.)</p> <pre> # Get a temporary filename CURL_LOG=`tempfile` ( # Run curl, and stick all output in the temp file /usr/bin/curl --verbose ... > "$CURL_LOG" 2>&1 ) || ( # If curl exited with a non-zero error code, send its output to stderr so that # cron will e-mail it. cat "$CURL_LOG" > /dev/stderr rm "$CURL_LOG" exit 1 ) # Otherwise curl completed successfully, so send the output to stdout (which # is redirected to a log file in crontab) cat "$CURL_LOG" rm "$CURL_LOG" </pre>
6,374,874
How to change the default time zone in R?
<p>How can I change the default timezone in R? I'm working with time series. All my time series are defined in UTC time zone, but if I print a date it is always done in CET/CEST time zone. </p>
6,408,072
4
2
null
2011-06-16 15:55:52.107 UTC
21
2018-05-25 09:25:54.893 UTC
2018-05-25 09:25:54.893 UTC
null
202,229
Paul PUGET
802,890
null
1
69
r|timezone|date-arithmetic
59,375
<p>Another way to do it, without changing the whole computer time is using the setenv command like this : <code>Sys.setenv(TZ='GMT')</code></p>
6,873,973
How to find Control in TemplateField of GridView?
<p>How does <code>FindControl</code> method works if I need to find any <code>Control</code> which is inside <code>GridView</code> <code>Template</code>, more specifically <code>ItemTemplate</code>?</p> <p>I have a <code>hyperlink</code> but it is not able to find the same.</p> <p><strong>Question updated with code</strong></p> <p><code>GridView</code> Code is below:</p> <pre><code>&lt;asp:GridView ID="grvYourOpportunities" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ID#,B,H" PageSize="20" CellPadding="4" ForeColor="#333333" GridLines="Both" OnRowDataBound="grvYourOpt_RowDataBound"&gt; &lt;HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /&gt; &lt;RowStyle BackColor="#F7F6F3" ForeColor="#333333" /&gt; &lt;Columns&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; i &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("i") %&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; H &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%--&lt;a href="javascript:ShowChildGrid('div&lt;%# Eval("ID#") %&gt;');"&gt; &lt;img id="imgdiv&lt;%# Eval("ID#") %&gt;" alt="Click" border="0" src="plus.gif" runat="server" /&gt; &lt;/a&gt; --%&gt; &lt;asp:HyperLink runat="server" ID="hlPlus" ImageUrl="~/plus.gif"&gt;&lt;/asp:HyperLink&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; B &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%--&lt;%# Eval("B") %&gt;--%&gt; &lt;a href="javascript:ShowChildGridForBCol('div1&lt;%# Eval("ID#") %&gt;');"&gt; &lt;img id="imgdiv1&lt;%# Eval("ID#") %&gt;" alt="Click here" border="0" src="tempY.png" /&gt; &lt;/a&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; ID.Nr. &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("ID#")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Entry Date &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Entry Date") %&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderStyle-Width="20px" ItemStyle-Width="20px"&gt; &lt;HeaderTemplate&gt; BU &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("BU")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; BE &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("BE")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Product Family &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Product Family")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Project Name &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Project Name")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; SOP &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("SOP")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Award Date &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Award Date")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Milestone Next Date &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Milestone Next Date")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Contract Status &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Contract Status")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Prob.Of Success &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("ProbSuccess")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Key Account &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Key Account")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Sales SubRegion &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Sales SubRegion")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Growth &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Growth")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Sales p.a.OE mio$ &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("SalesOE")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Sales p.a.AM mio$ &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("SalesAM")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;%--GridView 2, 3--%&gt; &lt;asp:TemplateField&gt; &lt;ItemTemplate&gt; &lt;tr&gt; &lt;td align="left" style="margin-left: 10px;" colspan="5"&gt; &lt;div id="div&lt;%# Eval("ID#") %&gt;" style="display: none; position: relative; left: 110px;"&gt; &lt;asp:GridView ID="GridView2" runat="server" Width="40%" AutoGenerateColumns="false" DataKeyNames="Entry Date" EmptyDataText="No orders for this customer." CellPadding="0" ForeColor="#333333" GridLines="Both"&gt; &lt;HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /&gt; &lt;RowStyle BackColor="#F7F6F3" ForeColor="#333333" /&gt; &lt;HeaderStyle CssClass="header" /&gt; &lt;RowStyle CssClass="row" /&gt; &lt;Columns&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("ID#")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Entry Date") %&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("ID#")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField ItemStyle-Wrap="false"&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Other Text") %&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align="left" colspan="19"&gt; &lt;div id="div1&lt;%# Eval("ID#") %&gt;" style="display: none; position:relative; left: 110px;"&gt; &lt;asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="false" DataKeyNames="Entry Date" EmptyDataText="No orders for this customer." CellPadding="0" ForeColor="#333333" GridLines="Both" Width="100%"&gt; &lt;HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /&gt; &lt;RowStyle BackColor="#F7F6F3" ForeColor="#333333" /&gt; &lt;%--&lt;HeaderStyle CssClass="header" /&gt; &lt;RowStyle CssClass="row" /&gt;--%&gt; &lt;Columns&gt; &lt;%--&lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt;--%&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("ID#")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;%-- &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Entry Date") %&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderStyle-Width="20px" ItemStyle-Width="20px"&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("BU")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("BE")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Product Family")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Project Name")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("SOP")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Award Date")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Milestone Next Date")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Contract Status")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("ProbSuccess")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Key Account")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Sales SubRegion")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("Growth")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("SalesOE")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%# Eval("SalesAM")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt;--%&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>The <code>RowDataBound</code> event of the parent <code>GridView</code> is as below;</p> <pre><code>Protected void grvYourOpt_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { string colId = grvYourOpportunities.DataKeys[e.Row.RowIndex].Values[0].ToString(); string colB = grvYourOpportunities.DataKeys[e.Row.RowIndex].Values[1].ToString(); string colH = grvYourOpportunities.DataKeys[e.Row.RowIndex].Values[2].ToString(); #region "Commented Code for Col.B" //if (colB == "Y") //{ // e.Row.Cells[2].Text = "&lt;img src='tempY.png'&gt;"; //} //else //{ // e.Row.Cells[2].Text = "&lt;img src='tempN.png'&gt;"; //} #endregion #region "Commented code for Col.H" if (colH == "1") { e.Row.Cells[1].Text = string.Empty; //e.Row.Cells[1].Text = "&lt;a href=''&gt; &lt;img id='13' alt='Click' border='0' src='plus.gif'/&gt; &lt;/a&gt;"; string js = string.Format("javascript:ShowChildGrid('div{0}');", colId); HyperLink lnk = (HyperLink)e.Row.FindControl("hlPlus"); if (lnk!=null) { lnk.NavigateUrl = js; lnk.ImageUrl = "plus.gif"; lnk.Visible = true; } //Page.ClientScript.RegisterStartupScript(this.GetType(), "HCol", "ShowChildGrid("+ colId + ");", true); } else { e.Row.Cells[1].Text = string.Empty; e.Row.Cells[1].Text = ""; } #endregion DataTable dt1 = new DataTable(); DataTable dt2 = new DataTable(); DataRow dr1 = null; DataRow dr2 = null; DataRow dr3 = null; DataRow dr4 = null; DataRow dr5 = null; DataRow dr7 = null; DataRow r = dt1.NewRow(); DataSet ds1 = new DataSet(); DataSet ds2 = new DataSet(); dt1.TableName = "Opportunity1"; dt1.Columns.Add(new System.Data.DataColumn("ID#", typeof(System.String))); dt1.Columns.Add(new System.Data.DataColumn("Entry Date", typeof(System.String))); dt1.Columns.Add(new System.Data.DataColumn("Other Text", typeof(System.String))); ds1.Tables.Add(dt1); dt2.Columns.Add(new System.Data.DataColumn("ID#", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("Entry Date", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("BU", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("BE", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("Product Family", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("Project Name", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("SOP", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("Award Date", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("Milestone Next Date", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("Contract Status", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("ProbSuccess", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("Key Account", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("Sales SubRegion", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("Growth", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("SalesOE", typeof(System.String))); dt2.Columns.Add(new System.Data.DataColumn("SalesAM", typeof(System.String))); ds2.Tables.Add(dt2); dr2 = dt1.NewRow(); dr3 = dt1.NewRow(); dr4 = dt1.NewRow(); dr5 = dt1.NewRow(); dr1["ID#"] = ""; dr2["ID#"] = ""; dr3["ID#"] = ""; dr4["ID#"] = ""; dr5["ID#"] = ""; dr1["Entry Date"] = "18/01/2010"; dr2["Entry Date"] = "19/01/2010"; dr3["Entry Date"] = "20/01/2010"; dr4["Entry Date"] = "21/01/2010"; dr5["Entry Date"] = "14/01/2010"; dr1["Other Text"] = "17:25CET changed by"; // - product family: ABS, Milestone Date: 23.02.1022, Contract Status: Signed, Probability of success: 100%"; dr2["Other Text"] = "18:44CET changed by"; //- product family: ABS, Milestone Date: 23.02.1022, Contract Status: Signed, Probability of success: 100%"; dr3["Other Text"] = "19:25CET changed by"; //- product family: ABS, Milestone Date: 23.02.1022, Contract Status: Signed, Probability of success: 100%"; dr4["Other Text"] = "14:25CET changed by"; //- product family: ABS, Milestone Date: 23.02.1022, Contract Status: Signed, Probability of success: 100%"; dr5["Other Text"] = "11:25CET changed by"; //- product family: ABS, Milestone Date: 23.02.1022, Contract Status: Signed, Probability of success: 100%"; dt1.Rows.Add(dr1); dt1.Rows.Add(dr2); dt1.Rows.Add(dr3); dt1.Rows.Add(dr4); dt1.Rows.Add(dr5); GridView gv12 = (GridView)e.Row.FindControl("GridView2"); gv12.DataSource = ds1.Tables[0]; gv12.DataBind(); for (int i = 0; i &lt; gv12.Rows.Count; i++) { gv12.RowStyle.BackColor = System.Drawing.Color.Gray; } dr7 = dt2.NewRow(); dr7["ID#"] = "11-0101"; dr7["Entry Date"] = "19/01/2010"; dr7["BU"] = "VDC"; dr7["BE"] = "ASES"; dr7["Product Family"] = "Car Air Systems"; dr7["Project Name"] = "Example"; dr7["SOP"] = "09/08/2011"; dr7["Award Date"] = "10/2011"; dr7["Milestone Next Date"] = System.DateTime.Today.ToString("dd.MM.yyyy"); dr7["Contract Status"] = "won"; dr7["ProbSuccess"] = "70%"; dr7["Key Account"] = "E-Paccar"; dr7["Sales SubRegion"] = "North America"; dr7["Growth"] = "10%"; dr7["SalesOE"] = "150"; dr7["SalesAM"] = "18"; dt2.Rows.Add(dr7); GridView gv13 = (GridView)e.Row.FindControl("GridView3"); gv13.DataSource = ds2.Tables[0]; gv13.DataBind(); } } </code></pre> <p>The <code>hyperlink</code> <code>hlPlus</code> is a <code>hyperlink</code> field inside <code>GridView</code>'s Template Field(Item Template).</p>
6,874,083
7
0
null
2011-07-29 13:34:57.077 UTC
5
2019-02-18 13:00:34.183 UTC
2017-07-01 11:39:14.99 UTC
null
1,305,969
null
224,636
null
1
29
c#|asp.net|gridview|findcontrol|templatefield
212,320
<p>Try this:</p> <pre><code>foreach(GridViewRow row in GridView1.Rows) { if(row.RowType == DataControlRowType.DataRow) { HyperLink myHyperLink = row.FindControl("myHyperLinkID") as HyperLink; } } </code></pre> <p>If you are handling RowDataBound event, it's like this:</p> <pre><code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if(e.Row.RowType == DataControlRowType.DataRow) { HyperLink myHyperLink = e.Row.FindControl("myHyperLinkID") as HyperLink; } } </code></pre>
6,549,149
Extending the defaults of a Model superclass in Backbone.js
<p>I would like to pose this as a question to <a href="https://stackoverflow.com/questions/6505873/in-backbone-js-how-can-i-get-model-superclass-defaults-to-act-as-defaults-for-sub/6508530#6508530">this</a> answer but I can't seem to do so, I apologize.</p> <p>Extending the defaults for the subclass are reflected in the superclass. This seems to defeat the purpose and I'm more apt to explicitly list the superclass' defaults in the subclass to get the structure I'm looking for.</p> <pre><code>var Inventory = Backbone.Model.extend({ defaults: { cat: 3, dog: 5 } }); var ExtendedInventory = Inventory.extend({ }); _.extend(ExtendedInventory.prototype.defaults, {rabbit: 25}); var i = new Inventory(); var ei = new ExtendedInventory(); console.log(i.attributes); console.log(ei.attributes); </code></pre> <p>This outputs:</p> <pre><code>{cat: 3, dog: 5, rabbit: 25} {cat: 3, dog: 5, rabbit: 25} </code></pre> <p>Not what I (nor, I assume, the <a href="https://stackoverflow.com/questions/6505873/in-backbone-js-how-can-i-get-model-superclass-defaults-to-act-as-defaults-for-sub">op</a>) want:</p> <pre><code>{cat: 3, dog: 5} {cat: 3, dog: 5, rabbit: 25} </code></pre>
6,550,191
7
0
null
2011-07-01 14:15:48.157 UTC
8
2015-10-25 23:33:15.307 UTC
2017-05-23 12:16:50.12 UTC
null
-1
null
307,827
null
1
37
javascript|backbone.js|prototypal-inheritance
17,867
<p>The problem is that <code>Inventory.prototype.defaults</code> and <code>Extended.prototype.defaults</code> has the same reference, because you have not override the reference.</p> <p>So you can do this in 2 ways, maybe more but i only found this 2:</p> <p><strong>Edit:</strong> The first example is incorrect (see comments); please refer to the second.</p> <pre><code>var ExtendedInventory = Inventory.extend({ defaults: { rabit:25 } }); _.extend(ExtendedInventory.prototype.defaults, Inventory.prototype.defaults); </code></pre> <p>or</p> <pre><code>var ExtendedInventory = Inventory.extend({ defaults: _.extend({},Inventory.prototype.defaults, {rabit:25} ) }); </code></pre> <p>I think the first looks cleaner.</p>
6,340,664
Delete a particular local notification
<p>I am developing an iPhone alarm app based on local notifications.</p> <p>On deleting an alarm, the related local notification should get cancelled. But how can I determine exactly which object from the array of local notifications is to be cancelled?</p> <p>I am aware of <code>[[UIApplication sharedApplication] cancelLocalNotification:notification]</code> method but how can I get this 'notification' to cancel it?</p>
6,341,476
13
0
null
2011-06-14 07:57:36.77 UTC
47
2019-08-29 21:58:54.603 UTC
2017-11-06 04:58:21.453 UTC
null
2,303,865
null
770,817
null
1
92
objective-c|iphone|uilocalnotification|usernotifications
71,817
<p>You can save a unique value for key in your local notification's userinfo. Get all local notification, loop through the array and delete the particular notification.</p> <p>Code as follows,</p> <p><strong>OBJ-C:</strong></p> <pre><code>UIApplication *app = [UIApplication sharedApplication]; NSArray *eventArray = [app scheduledLocalNotifications]; for (int i=0; i&lt;[eventArray count]; i++) { UILocalNotification* oneEvent = [eventArray objectAtIndex:i]; NSDictionary *userInfoCurrent = oneEvent.userInfo; NSString *uid=[NSString stringWithFormat:@"%@",[userInfoCurrent valueForKey:@"uid"]]; if ([uid isEqualToString:uidtodelete]) { //Cancelling local notification [app cancelLocalNotification:oneEvent]; break; } } </code></pre> <p><strong>SWIFT:</strong></p> <pre><code>var app:UIApplication = UIApplication.sharedApplication() for oneEvent in app.scheduledLocalNotifications { var notification = oneEvent as UILocalNotification let userInfoCurrent = notification.userInfo! as [String:AnyObject] let uid = userInfoCurrent["uid"]! as String if uid == uidtodelete { //Cancelling local notification app.cancelLocalNotification(notification) break; } } </code></pre> <p><strong>UserNotification:</strong></p> <p>If you use <a href="https://developer.apple.com/reference/usernotifications">UserNotification</a> (iOS 10+), just follow this steps:</p> <ol> <li><p>When creating the UserNotification content, add an unique <a href="https://developer.apple.com/reference/usernotifications/unnotificationrequest/1649634-identifier" title="identifier">identifier</a></p></li> <li><p>Remove specific pending notification using <a href="https://developer.apple.com/reference/usernotifications/unusernotificationcenter/1649517-removependingnotificationrequest" title="removePendingNotificationRequests&#40;withIdentifiers:&#41;">removePendingNotificationRequests(withIdentifiers:)</a></p></li> <li><p>Remove specific delivered notification using <a href="https://developer.apple.com/reference/usernotifications/unusernotificationcenter/1649500-removedeliverednotifications">removeDeliveredNotifications(withIdentifiers:)</a></p></li> </ol> <p>For more info, <a href="https://developer.apple.com/reference/usernotifications/unusernotificationcenter#symbols">UNUserNotificationCenter</a></p>
45,500,836
Close multiple goroutine if an error occurs in one in go
<p>consider this function :</p> <pre><code>func doAllWork() error { var wg sync.WaitGroup for i := 0; i &lt; 2; i++ { wg.add(1) go func() { defer wg.Done() for j := 0; j &lt; 10; j++ { result, err := work(j) if err != nil { // can't use `return err` here // what sould I put instead ? os.Exit(0) } } }() } wg.Wait() return nil } </code></pre> <p>In each goroutine, the function <code>work()</code> is called 10 times. If one call to <code>work()</code> returns an error in any of the running goroutines, I want all the goroutines to stop immediately, and the program to exit. Is it ok to use <code>os.Exit()</code> here ? How should I handle this ?</p> <hr /> <p><strong>Edit</strong>: this question is different from <a href="https://stackoverflow.com/questions/6807590/how-to-stop-a-goroutine">how to stop a goroutine</a> as here I need to close all goroutines if an error occurs in one</p>
45,502,591
3
4
null
2017-08-04 07:37:37.303 UTC
9
2020-09-30 17:01:11.623 UTC
2020-07-02 22:52:28.45 UTC
null
6,858,274
null
6,858,274
null
1
22
go|error-handling|synchronization|exit|goroutine
16,536
<p>You may use the <a href="https://golang.org/pkg/context/" rel="noreferrer"><code>context</code></a> package which was created for things like this (<em>"carries deadlines, cancelation signals..."</em>).</p> <p>You create a context capable of publishing cancelation signals with <a href="https://golang.org/pkg/context/#WithCancel" rel="noreferrer"><code>context.WithCancel()</code></a> (parent context may be the one returned by <a href="https://golang.org/pkg/context/#Background" rel="noreferrer"><code>context.Background()</code></a>). This will return you a <code>cancel()</code> function which may be used to cancel (or more precisely <em>signal</em> the cancel intent) to the worker goroutines.<br> And in the worker goroutines you have to check if such intent has been initiated, by checking if the channel returned by <code>Context.Done()</code> is closed, easiest done by attempting to receive from it (which proceeds immediately if it is closed). And to do a non-blocking check (so you can continue if it is not closed), use the <code>select</code> statement with a <code>default</code> branch.</p> <p>I will use the following <code>work()</code> implementation, which simulates a 10% failure chance, and simulates 1 second of work:</p> <pre><code>func work(i int) (int, error) { if rand.Intn(100) &lt; 10 { // 10% of failure return 0, errors.New("random error") } time.Sleep(time.Second) return 100 + i, nil } </code></pre> <p>And the <code>doAllWork()</code> may look like this:</p> <pre><code>func doAllWork() error { var wg sync.WaitGroup ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Make sure it's called to release resources even if no errors for i := 0; i &lt; 2; i++ { wg.Add(1) go func(i int) { defer wg.Done() for j := 0; j &lt; 10; j++ { // Check if any error occurred in any other gorouties: select { case &lt;-ctx.Done(): return // Error somewhere, terminate default: // Default is must to avoid blocking } result, err := work(j) if err != nil { fmt.Printf("Worker #%d during %d, error: %v\n", i, j, err) cancel() return } fmt.Printf("Worker #%d finished %d, result: %d.\n", i, j, result) } }(i) } wg.Wait() return ctx.Err() } </code></pre> <p>This is how it can be tested:</p> <pre><code>func main() { rand.Seed(time.Now().UnixNano() + 1) // +1 'cause Playground's time is fixed fmt.Printf("doAllWork: %v\n", doAllWork()) } </code></pre> <p>Output (try it on the <a href="https://play.golang.org/p/od8ShySgMM" rel="noreferrer">Go Playground</a>):</p> <pre><code>Worker #0 finished 0, result: 100. Worker #1 finished 0, result: 100. Worker #1 finished 1, result: 101. Worker #0 finished 1, result: 101. Worker #0 finished 2, result: 102. Worker #1 finished 2, result: 102. Worker #1 finished 3, result: 103. Worker #1 during 4, error: random error Worker #0 finished 3, result: 103. doAllWork: context canceled </code></pre> <p>If there would be no errors, e.g. when using the following <code>work()</code> function:</p> <pre><code>func work(i int) (int, error) { time.Sleep(time.Second) return 100 + i, nil } </code></pre> <p>The output would be like (try it on the <a href="https://play.golang.org/p/gZKXSAa4F-" rel="noreferrer">Go Playground</a>):</p> <pre><code>Worker #0 finished 0, result: 100. Worker #1 finished 0, result: 100. Worker #1 finished 1, result: 101. Worker #0 finished 1, result: 101. Worker #0 finished 2, result: 102. Worker #1 finished 2, result: 102. Worker #1 finished 3, result: 103. Worker #0 finished 3, result: 103. Worker #0 finished 4, result: 104. Worker #1 finished 4, result: 104. Worker #1 finished 5, result: 105. Worker #0 finished 5, result: 105. Worker #0 finished 6, result: 106. Worker #1 finished 6, result: 106. Worker #1 finished 7, result: 107. Worker #0 finished 7, result: 107. Worker #0 finished 8, result: 108. Worker #1 finished 8, result: 108. Worker #1 finished 9, result: 109. Worker #0 finished 9, result: 109. doAllWork: &lt;nil&gt; </code></pre> <p><strong>Notes:</strong></p> <p>Basically we just used the <code>Done()</code> channel of the context, so it seems we could just as easily (if not even easier) use a <code>done</code> channel instead of the <code>Context</code>, closing the channel to do what <code>cancel()</code> does in the above solution.</p> <p>This is not true. <strong>This can only be used if only one goroutine may close the channel, but in our case any of the workers may do so.</strong> And attempting to close an already closed channel panics (see details here: <a href="https://stackoverflow.com/questions/39015602/how-does-a-non-initialized-channel-behave/39016004#39016004">How does a non initialized channel behave?</a>). So you would have to ensure some kind of synchronization / exclusion around the <code>close(done)</code>, which will make it less readable and even more complex. Actually this is exactly what the <code>cancel()</code> function does under the hood, hidden / abstracted away from your eyes, so <code>cancel()</code> may be called multiple times to make your code / use of it simpler.</p> <h3>How to get and return the error(s) from the workers?</h3> <p>For this you may use an error channel:</p> <pre><code>errs := make(chan error, 2) // Buffer for 2 errors </code></pre> <p>And inside the workers when an error is encountered, send it on the channel instead of printing it:</p> <pre><code>result, err := work(j) if err != nil { errs &lt;- fmt.Errorf("Worker #%d during %d, error: %v\n", i, j, err) cancel() return } </code></pre> <p>And after the loop, if there was an error, return that (and <code>nil</code> otherwise):</p> <pre><code>// Return (first) error, if any: if ctx.Err() != nil { return &lt;-errs } return nil </code></pre> <p>Output this time (try this on the <a href="https://play.golang.org/p/J2wMOuxiTm" rel="noreferrer">Go Playground</a>):</p> <pre><code>Worker #0 finished 0, result: 100. Worker #1 finished 0, result: 100. Worker #1 finished 1, result: 101. Worker #0 finished 1, result: 101. Worker #0 finished 2, result: 102. Worker #1 finished 2, result: 102. Worker #1 finished 3, result: 103. Worker #0 finished 3, result: 103. doAllWork: Worker #1 during 4, error: random error </code></pre> <p>Note that I used a buffered channel with a buffer size equal to the number of workers, which ensures sending on it is always non-blocking. This also gives you the possibility to receive and process all errors, not just one (e.g. the first). Another option could be to use a buffered channel to hold only 1, and do a non-blocking send on it, which could look like this:</p> <pre><code>errs := make(chan error, 1) // Buffered only for the first error // ...and inside the worker: result, err := work(j) if err != nil { // Non-blocking send: select { case errs &lt;- fmt.Errorf("Worker #%d during %d, error: %v\n", i, j, err): default: } cancel() return } </code></pre>
41,495,658
Use custom build output folder when using create-react-app
<p>Facebook provides a <code>create-react-app</code> <a href="https://github.com/facebookincubator/create-react-app" rel="noreferrer">command</a> to build react apps. When we run <code>npm run build</code>, we see output in <code>/build</code> folder. </p> <blockquote> <p>npm run build</p> <p>Builds the app for production to the build folder. It correctly bundles React in production mode and optimizes the build for the best performance.</p> <p>The build is minified and the filenames include the hashes. Your app is ready to be deployed!</p> </blockquote> <p>How can we use custom folder instead of <code>/build</code> for the output? Thanks.</p>
41,495,859
17
2
null
2017-01-05 22:13:16.807 UTC
35
2022-01-10 23:07:52.497 UTC
null
null
null
null
4,130,867
null
1
142
reactjs|create-react-app
222,039
<p>Edit: Support for a configurable <code>BUILD_PATH</code> just landed into v4.0.2. See <a href="https://stackoverflow.com/a/66036117/1333836">t_dom93's answer</a>.</p> <p>You can't change the build output folder name with the current configuration options.</p> <p>Moreover, you shouldn't. This is a part of <a href="https://github.com/facebookincubator/create-react-app#philosophy" rel="noreferrer">the philosophy behind <code>create-react-app</code></a>: they say <strong>Convention over Configuration</strong>.</p> <p>If you really need to rename your folder, I see two options:</p> <ol> <li><p>Right after the build process finishes, <strong>write a command that copies the build folder content to another folder you want</strong>. For example you can <a href="https://www.npmjs.com/package/copyfiles" rel="noreferrer">try the <code>copyfiles</code> npm package</a>, or anything similar.</p> </li> <li><p>You could try to <a href="https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-eject" rel="noreferrer">eject create-react-app</a> and tweak the configuration.</p> </li> </ol> <blockquote> <p>If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.</p> </blockquote> <blockquote> <p>Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.</p> </blockquote> <p>However, it is important to note that <strong>this is a one-way operation. Once you eject, you can’t go back</strong>! You loose all future updates.</p> <p>Therefore, <strong>I'd recommend you to not use a custom folder naming, if possible</strong>. Try to stick with the default naming. If not an option, try #1. If it still doesn't work for your specific use-case and you're really out of options - explore #2. Good luck!</p>
15,751,723
How to train a neural network to supervised data set using pybrain black-box optimization?
<p>I have played around a bit with pybrain and understand how to generate neural networks with custom architectures and train them to supervised data sets using backpropagation algorithm. </p> <p>However I am confused by the optimization algorithms and the concepts of tasks, learning agents and environments. </p> <p>For example: How would I implement a neural network such as (1) to classify the XOR dataset using pybrain genetic algorithm (2)?</p> <p>(1) <code>pybrain.tools.shortcuts.buildNetwork(2, 3, 1)</code></p> <p>(2) <code>pybrain.optimization.GA()</code></p>
15,868,489
1
1
null
2013-04-01 20:55:20.637 UTC
12
2015-08-05 00:39:35.81 UTC
2013-04-13 13:19:47.567 UTC
null
1,376,627
null
1,376,627
null
1
20
python|artificial-intelligence|neural-network|pybrain
10,815
<p>I finally worked it out!! Its always easy once you know how! </p> <p>Essentially the first arg to the GA is the fitness function (called evaluator in docs) which must take the second argument (an individual, called evaluable in docs) as its only arg. </p> <p>In this example will train to XOR</p> <pre><code>from pybrain.datasets.classification import ClassificationDataSet # below line can be replaced with the algorithm of choice e.g. # from pybrain.optimization.hillclimber import HillClimber from pybrain.optimization.populationbased.ga import GA from pybrain.tools.shortcuts import buildNetwork # create XOR dataset d = ClassificationDataSet(2) d.addSample([0., 0.], [0.]) d.addSample([0., 1.], [1.]) d.addSample([1., 0.], [1.]) d.addSample([1., 1.], [0.]) d.setField('class', [ [0.],[1.],[1.],[0.]]) nn = buildNetwork(2, 3, 1) # d.evaluateModuleMSE takes nn as its first and only argument ga = GA(d.evaluateModuleMSE, nn, minimize=True) for i in range(100): nn = ga.learn(0)[0] </code></pre> <p>Test results after the above script:</p> <pre><code>In [68]: nn.activate([0,0]) Out[68]: array([-0.07944574]) In [69]: nn.activate([1,0]) Out[69]: array([ 0.97635635]) In [70]: nn.activate([0,1]) Out[70]: array([ 1.0216745]) In [71]: nn.activate([1,1]) Out[71]: array([ 0.03604205]) </code></pre>
15,814,346
Is it possible to use css to make a background image "fade" or gradient the bottom portion to transparent so that a background color shows?
<p>I know that this can easily be done in any image editing program, I was just curious if there was a way just using css.</p> <p>Example:</p> <pre><code>body {background-color: #837960; background-image: url("Images/background.jpg") background-repeat: no-repeat;} </code></pre> <p>Could you use css to fade the background image into the background color so a visible line does not exist or should I keep adding a gradient to transparency in Photoshop?</p>
15,814,561
3
7
null
2013-04-04 14:39:28.387 UTC
3
2019-02-23 14:27:05.74 UTC
null
null
null
null
1,839,715
null
1
23
css
67,623
<p>It is possible - in CSS3 you can set multiple values for background</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: #837960 url("https://i.stack.imgur.com/MUsp6.jpg") 0 0 no-repeat; background: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(130,91,0,1) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,0)), color-stop(100%,rgba(130,91,0,1))); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%,rgba(130,91,0,1) 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, rgba(255,255,255,0) 0%,rgba(130,91,0,1) 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, rgba(255,255,255,0) 0%,rgba(130,91,0,1) 100%); /* IE10+ */ background: linear-gradient(to bottom, rgba(255,255,255,0) 0%,rgba(130,91,0,1) 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00ffffff', endColorstr='#825b00',GradientType=0 ); /* IE6-9 */ }</code></pre> </div> </div> </p> <p>However, it will work only in modern browser that supports CSS3</p> <p>(code generated via <a href="http://www.colorzilla.com/gradient-editor/" rel="nofollow noreferrer">http://www.colorzilla.com/gradient-editor/</a>)</p>
15,641,898
Python: timezone.localize() not working
<p>I am having some issues getting <code>timezone.localize()</code> to work correctly. My goal is to grab today's date and convert it from CST to EST. Then finally format the datetime before spitting it out. I am able to format the date correctly, but the datetime is not changing from CST to EST. Additionally when I format the date I don't see the text representation of the timezone included.</p> <p>Below I have listed out a simple program I created to test this out:</p> <pre><code>#! /usr/bin/python #Test script import threading import datetime import pexpect import pxssh import threading from pytz import timezone import pytz est = timezone('US/Eastern') curtime = est.localize(datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Z %Y")) #test time change #curtime = datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Z %Y") class ThreadClass(threading.Thread): def run(self): #now = (datetime.datetime.now() + datetime.timedelta(0, 3600)) now = (datetime.datetime.now()) print "%s says Hello World at time: %s" % (self.getName(), curtime) for i in range(3): t = ThreadClass() t.start() </code></pre>
15,642,065
2
2
null
2013-03-26 16:09:21.183 UTC
2
2013-03-26 16:29:54.82 UTC
2013-03-26 16:29:54.82 UTC
null
1,086,571
null
1,086,571
null
1
27
python|datetime|timezone
41,632
<p><code>.localize()</code> takes a naive datetime object and interprets it <em>as if</em> it is in that timezone. It does <em>not</em> move the time to another timezone. A naive datetime object has <em>no</em> timezone information to be able to make that move possible.</p> <p>You want to interpret <code>now()</code> in your <em>local</em> timezone instead, then use <code>.astimezone()</code> to interpret the datetime in another timezone:</p> <pre><code>est = timezone('US/Eastern') cst = timezone('US/Central') curtime = cst.localize(datetime.datetime.now()) est_curtime = curtime.astimezone(est).strftime("%a %b %d %H:%M:%S %Z %Y")) def run(self): print "%s says Hello World at time: %s" % (self.getName(), est_curtime) </code></pre>
15,576,009
How to make HashMap work with Arrays as key?
<p>I am using boolean arrays as keys for a HashMap. But the problem is HashMap fails to get the keys when a different array is passed as key, although the elements are same. (As they are different objects). </p> <p>How can I make it work with arrays as keys ? Here is the code :</p> <pre><code>public class main { public static HashMap&lt;boolean[], Integer&gt; h; public static void main(String[] args){ boolean[] a = {false, false}; h = new HashMap&lt;boolean[], Integer&gt;(); h.put(a, 1); if(h.containsKey(a)) System.out.println("Found a"); boolean[] t = {false, false}; if(h.containsKey(t)) System.out.println("Found t"); else System.out.println("Couldn't find t"); } } </code></pre> <p>Both the arrays <code>a</code> and <code>t</code> contain the same elements, but HashMap doesn't return anything for <code>t</code>. </p> <p>How do I make it work ?</p>
15,576,112
9
2
null
2013-03-22 17:02:20.137 UTC
11
2020-02-21 19:28:35.923 UTC
null
null
null
null
564,503
null
1
35
java|arrays|hashmap
44,088
<p>You cannot do it this way. Both <code>t</code> and <code>a</code> will have different <code>hashCode()</code> values because the the <code>java.lang.Array.hashCode()</code> method is inherited from <code>Object</code>, which uses the reference to compute the hash-code (default implementation). Hence the hash code for arrays is reference-dependent, which means that you will get a different hash-code value for <code>t</code> and <code>a</code>. Furthermore, <code>equals</code> will not work for the two arrays because that is also based on the reference.</p> <p>The only way you can do this is to create a custom class that keeps the <code>boolean</code> array as an internal member. Then you need to override <code>equals</code> and <code>hashCode</code> in such a way that ensures that instances that contain arrays with identical values are equal and also have the same hash-code.</p> <p>An easier option might be to use <code>List&lt;Boolean&gt;</code> as the key. Per the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html#hashCode()" rel="noreferrer">documentation</a> the <code>hashCode()</code> implementation for <code>List</code> is defined as:</p> <pre><code>int hashCode = 1; Iterator&lt;E&gt; i = list.iterator(); while (i.hasNext()) { E obj = i.next(); hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode()); } </code></pre> <p>As you can see, it depends on the values inside your list and not the reference, and so this should work for you.</p>
15,872,254
Android NDK: WARNING: APP_PLATFORM android-9 is larger than android:minSdkVersion 8
<p>I am getting the following warning when compiling my cocos2d-x project with cygwin.</p> <pre><code>`/cygdrive/e/project/MyGame/proj.android ` /cygdrive/e/android-ndk-r8e/build/core/add-application.mk:128: Android NDK: WARNING:APP_PLATFORM android-9 is larger than android:minSdkVersion 8 in ./AndroidManifest.xml </code></pre> <p>I am using NDK version r8e. My minimum SDK version is 8 in my AndroidManifest.xml but i do not specify APP_PLATFORM as android-9 anywhere. How can i change this to 8.</p> <p>Can anyone tell me how to solve this warning as I think this may cause issues. </p>
15,887,984
3
3
null
2013-04-08 06:01:19.777 UTC
7
2016-12-10 20:28:01.723 UTC
null
null
null
null
1,495,342
null
1
42
android|android-ndk|cygwin|cocos2d-x
36,002
<p>It seems that you are using Android-9 as runtime. You can put <code>APP_PLATFORM := android-8</code> in your <code>Application.mk</code> file and the warning will disappear.</p>
15,750,535
Using mysqldump to format one insert per line?
<p>This has been asked a few times but I cannot find a resolution to my problem. Basically when using mysqldump, which is the built in tool for the MySQL Workbench administration tool, when I dump a database using extended inserts, I get massive long lines of data. I understand why it does this, as it speeds inserts by inserting the data as one command (especially on InnoDB), but the formatting makes it REALLY difficult to actually look at the data in a dump file, or compare two files with a diff tool if you are storing them in version control etc. In my case I am storing them in version control as we use the dump files to keep track of our integration test database.</p> <p>Now I know I can turn off extended inserts, so I will get one insert per line, which works, but any time you do a restore with the dump file it will be slower.</p> <p>My core problem is that in the OLD tool we used to use (MySQL Administrator) when I dump a file, it does basically the same thing but it FORMATS that INSERT statement to put one insert per line, while still doing bulk inserts. So instead of this:</p> <pre><code>INSERT INTO `coupon_gv_customer` (`customer_id`,`amount`) VALUES (887,'0.0000'),191607,'1.0300'); </code></pre> <p>you get this:</p> <pre><code>INSERT INTO `coupon_gv_customer` (`customer_id`,`amount`) VALUES (887,'0.0000'), (191607,'1.0300'); </code></pre> <p>No matter what options I try, there does not seem to be any way of being able to get a dump like this, which is really the best of both worlds. Yes, it take a little more space, but in situations where you need a human to read the files, it makes it MUCH more useful.</p> <p>Am I missing something and there is a way to do this with MySQLDump, or have we all gone backwards and this feature in the old (now deprecated) MySQL Administrator tool is no longer available?</p>
19,961,480
9
2
null
2013-04-01 19:43:09.16 UTC
11
2020-05-22 09:19:04.483 UTC
null
null
null
null
443,943
null
1
61
mysql|mysqldump|mysql-workbench|mysqladministrator
27,512
<p>With the default mysqldump format, each record dumped will generate an individual INSERT command in the dump file (i.e., the sql file), each on its own line. This is perfect for source control (e.g., svn, git, etc.) as it makes the diff and delta resolution much finer, and ultimately results in a more efficient source control process. However, for significantly sized tables, executing all those INSERT queries can potentially make restoration from the sql file prohibitively slow.</p> <p>Using the --extended-insert option fixes the multiple INSERT problem by wrapping all the records into a single INSERT command on a single line in the dumped sql file. However, the source control process becomes very inefficient. The entire table contents is represented on a single line in the sql file, and if a single character changes anywhere in that table, source control will flag the entire line (i.e., the entire table) as the delta between versions. And, for large tables, this negates many of the benefits of using a formal source control system.</p> <p>So ideally, for efficient database restoration, in the sql file, we want each table to be represented by a single INSERT. For an efficient source control process, in the sql file, we want each record in that INSERT command to reside on its own line.</p> <p>My solution to this is the following back-up script:</p> <pre><code>#!/bin/bash cd my_git_directory/ ARGS="--host=myhostname --user=myusername --password=mypassword --opt --skip-dump-date" /usr/bin/mysqldump $ARGS --database mydatabase | sed 's$VALUES ($VALUES\n($g' | sed 's$),($),\n($g' &gt; mydatabase.sql git fetch origin master git merge origin/master git add mydatabase.sql git commit -m "Daily backup." git push origin master </code></pre> <p>The result is a sql file INSERT command format that looks like:</p> <pre><code>INSERT INTO `mytable` VALUES (r1c1value, r1c2value, r1c3value), (r2c1value, r2c2value, r2c3value), (r3c1value, r3c2value, r3c3value); </code></pre> <p>Some notes:</p> <ul> <li>password on the command line ... I know, not secure, different discussion.</li> <li>--opt: Among other things, turns on the --extended-insert option (i.e., one INSERT per table).</li> <li>--skip-dump-date: mysqldump normally puts a date/time stamp in the sql file when created. This can become annoying in source control when the only delta between versions is that date/time stamp. The OS and source control system will date/time stamp the file and version. Its not really needed in the sql file.</li> <li>The git commands are not central to the fundamental question (formatting the sql file), but shows how I get my sql file back into source control, something similar can be done with svn. When combining this sql file format with your source control of choice, you will find that when your users update their working copies, they only need to move the deltas (i.e., changed records) across the internet, and they can take advantage of diff utilities to easily see what records in the database have changed.</li> <li>If you're dumping a database that resides on a remote server, if possible, run this script on that server to avoid pushing the entire contents of the database across the network with each dump.</li> <li>If possible, establish a working source control repository for your sql files on the same server you are running this script from; check them into the repository from there. This will also help prevent having to push the entire database across the network with every dump. </li> </ul>
15,734,031
Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?
<p>I am writing a JavaScript client to be included on 3rd party sites (think Facebook Like button). It needs to retrieve information from an API that requires basic HTTP authentication. The simplified setup looks like this:</p> <p>A 3rd party site includes this snippet on their page:</p> <pre><code>&lt;script async="true" id="web-dev-widget" data-public-key="pUbl1c_ap1k3y" src="http://web.dev/widget.js"&gt; &lt;/script&gt; </code></pre> <p><strong>widget.js</strong> calls the API:</p> <pre><code>var el = document.getElementById('web-dev-widget'), user = 'token', pass = el.getAttribute('data-public-key'), url = 'https://api.dev/', httpRequest = new XMLHttpRequest(), handler = function() { if (httpRequest.readyState === 4) { if (httpRequest.status === 200) { console.log(httpRequest.responseText); } else { console.log('There was a problem with the request.', httpRequest); } } }; httpRequest.open('GET', url, true, user, pass); httpRequest.onreadystatechange = handler; httpRequest.withCredentials = true; httpRequest.send(); </code></pre> <p>The API has been configured to respond with appropriate headers:</p> <pre><code>Header set Access-Control-Allow-Credentials: true Header set Access-Control-Allow-Methods: "GET, OPTIONS" Header set Access-Control-Allow-Headers: "origin, authorization, accept" SetEnvIf Origin "http(s)?://(.+?\.[a-z]{3})$" AccessControlAllowOrigin=$0 Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin </code></pre> <p>Note that the <code>Access-Control-Allow-Origin</code> is set to the <code>Origin</code> instead of using a wildcard because I am sending a credentialed request (<code>withCredentials</code>).</p> <p>Everything is now in place to make an asynchronous cross-domain authenticated request, and it works great in Chrome 25 on OS X 10.8.2. In Dev Tools, I can see the network request for the <code>OPTIONS</code> request before the <code>GET</code> request, and the response comes back as expected.</p> <p>When testing in Firefox 19, no network requests appear in Firebug to the API, and this error is logged in the console: <code>NS_ERROR_DOM_BAD_URI: Access to restricted URI denied</code></p> <p>After much digging, I found that <a href="https://stackoverflow.com/questions/11255173/firefox-wont-send-cross-origin-resource-sharing-pre-flight">Gecko doesn't allow the username and password to be directly in a cross-site URI</a> according to the comments. I assumed this was from using the optional user and password params to <code>open()</code> so I tried the other method of making authenticated requests which is to Base64 encode the credentials and send in an Authorization header:</p> <pre><code>// Base64 from http://www.webtoolkit.info/javascript-base64.html auth = "Basic " + Base64.encode(user + ":" + pass); ... // after open() and before send() httpRequest.setRequestHeader('Authorization', auth); </code></pre> <p>This results in a <code>401 Unauthorized</code> response to the <code>OPTIONS</code> request which lead to Google searches like, "Why does this work in Chrome and not Firefox!?" That's when I knew I was in trouble.</p> <p>Why <em>does</em> it work in Chrome and not Firefox? How can I get the <code>OPTIONS</code> request to send and respond consistently?</p>
15,734,032
3
1
null
2013-03-31 20:14:42.697 UTC
19
2020-06-26 12:54:29.03 UTC
2017-05-23 12:18:11.943 UTC
null
-1
null
613,588
null
1
70
javascript|ajax|cors
114,088
<p><strong>Why <em>does</em> it work in Chrome and not Firefox?</strong></p> <p>The <a href="https://fetch.spec.whatwg.org/#cors-protocol-and-credentials" rel="noreferrer">W3 spec for CORS preflight requests</a> clearly states that user credentials should be excluded. There is a bug in <a href="https://code.google.com/p/chromium/issues/detail?id=139566" rel="noreferrer">Chrome</a> and <a href="https://bugs.webkit.org/show_bug.cgi?id=92755" rel="noreferrer">WebKit</a> where <code>OPTIONS</code> requests returning a status of 401 still send the subsequent request.</p> <p><a href="https://bugzilla.mozilla.org/show_bug.cgi?id=778548" rel="noreferrer">Firefox</a> has a related bug filed that ends with a link to the <a href="http://lists.w3.org/Archives/Public/public-webapps/2012JulSep/0252.html" rel="noreferrer">W3 public webapps mailing list</a> asking for the CORS spec to be changed to allow authentication headers to be sent on the <code>OPTIONS</code> request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.</p> <p><strong>How can I get the <code>OPTIONS</code> request to send and respond consistently?</strong></p> <p>Simply have the server (API in this example) respond to <code>OPTIONS</code> requests without requiring authentication.</p> <p><a href="http://www.kinvey.com/blog/60/kinvey-adds-cross-origin-resource-sharing-cors" rel="noreferrer">Kinvey</a> did a good job expanding on this while also linking to <a href="https://code.google.com/p/twitter-api/issues/detail?id=2273" rel="noreferrer">an issue of the Twitter API</a> outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.</p>
15,821,532
Get current AUTO_INCREMENT value for any table
<p>How do I get the current AUTO_INCREMENT value for a table in MySQL?</p>
15,821,543
9
1
null
2013-04-04 20:55:27.94 UTC
81
2021-12-25 03:09:55.113 UTC
2014-05-05 18:47:56.21 UTC
null
19,405
null
2,246,727
null
1
357
mysql|auto-increment
375,131
<p>You can get all of the table data by using this query:</p> <pre><code>SHOW TABLE STATUS FROM `DatabaseName` WHERE `name` LIKE 'TableName' ; </code></pre> <p>You can get exactly this information by using this query:</p> <pre><code>SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'DatabaseName' AND TABLE_NAME = 'TableName'; </code></pre>
10,415,653
Run Batch file as administrator - Windows 7 - Command "Run As" from network file system
<p>I need to set up the delivery of a program installer.</p> <p>This program has a program_installer.exe and a folder that i cannot include in the installer at the time in which i create the installer.</p> <p>therefore, when a user needs to install the program i send him a BATCH file via MAIL</p> <pre><code>@echo off if DEFINED PROGRAMFILES(X86) ( SET TOOL_INSTALL_DIR="%PROGRAMFILES(X86)%\myfolder" ) else ( SET TOOL_INSTALL_DIR="%PROGRAMFILES%\myfolder" ) MKDIR %TOOL_INSTALL_DIR% copy /y \\rk0012352\Public\lkh5iwwh.m4s %TOOL_INSTALL_DIR% START %PROGRAMFILES%\program_installer.exe </code></pre> <p>The issue is that, when the user execute the BATCH and run COPY command, on windows 7 the command will fail because he has no ADMIN rights.</p> <p>How can i make that copy command run as administrator on both XP and 7 ?</p> <p>You might say: when the user gets the EMAIl with INSTALL.BAT, CAN'T he click RUN AS ADMINISTRATOR?</p> <p>The answer unfortunately is that most of them will not do that and just complain that it doesn't work. Moreover many email client such as Outlook will prompt "open" "save" choice panel and most of the users will click Open directly(generating the no rights error)</p> <p>the "run as" commands requires to specify the administrator name for the machine and i cannot know how the admin user is called on every computer.</p> <p>Any suggestion?</p>
10,415,764
3
4
null
2012-05-02 14:19:56.487 UTC
1
2014-09-17 09:53:48.773 UTC
2012-05-02 14:31:17.433 UTC
null
1,207,195
null
958,744
null
1
7
shell|batch-file|cmd|dos|administration
50,014
<p>It's a little bit tricky but it can be done.</p> <p>First you have to know (from the batch file) if the user is an administrator. If it is then you can simply go on with installation. If it's not you can run another cmd.exe instance to run the batch file as administrator (using the <code>runas</code> command).</p> <p>To detect if the user is an administrator take a look to this post: <a href="http://www.tomshardware.co.uk/forum/169421-36-determine-batch-file-user-administrator">http://www.tomshardware.co.uk/forum/169421-36-determine-batch-file-user-administrator</a> (there is the full code to elevate the batch itself too).</p>
10,717,249
Get current domain
<p>I have my site on the server <code>http://www.myserver.uk.com</code>.</p> <p>On this server I have two domains:</p> <pre class="lang-none prettyprint-override"><code>one.com and two.com </code></pre> <p>I would like to get the current domain using PHP, but if I use <code>$_SERVER['HTTP_HOST']</code> then it is showing me</p> <pre class="lang-none prettyprint-override"><code>myserver.uk.com </code></pre> <p>instead of:</p> <pre class="lang-none prettyprint-override"><code>one.com or two.com </code></pre> <p>How can I get the domain, and not the server name?</p>
10,717,309
8
7
null
2012-05-23 09:36:29.727 UTC
37
2021-08-21 18:11:11.337 UTC
2021-08-21 17:50:25.993 UTC
null
63,550
null
1,381,903
null
1
182
php|url|php-5.2
443,353
<p>Try using this:</p> <pre><code>$_SERVER['SERVER_NAME'] </code></pre> <p>Or parse:</p> <pre><code>$_SERVER['REQUEST_URI'] </code></pre> <p>Reference: <em><a href="http://php.net/manual/en/function.apache-request-headers.php" rel="noreferrer">apache_request_headers()</a></em></p>
67,798,798
Unhandled Exception: Null check operator used on a null value shared preference
<p>so I tried Shared preference to make user still logged in until they log out but when i tried to restart the app this appears</p> <pre><code>[VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value #0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86) #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36) #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12) #3 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:358:49) #4 MethodChannelSharedPreferencesStore.getAll (package:shared_preferences_platform_interface/method_channel_shared_preferences.dart:44:25) #5 SharedPreferences._getSharedPreferencesMap (package:shared_preferences/shared_preferences.dart:180:57) #6 SharedPreferences.getInstance (package:shared_preferences/shared_preferences.dart:56:19) #7 read_loggedIn (package:indonesia_bisa_2/API/LocalService.dart:11:41) #8 main (package:indonesia_bisa_2/Main/main.dart:16:14) #9 _runMainZoned.&lt;anonymous closure&gt;.&lt;…&gt; </code></pre> <p>heres the checker code</p> <pre><code>import 'package:shared_preferences/shared_preferences.dart'; Future&lt;void&gt; save_loggedIn() async { final prefs = await SharedPreferences.getInstance(); prefs.setString(&quot;loggedIn&quot;, &quot;true&quot;); } //this is for checking the saved variable to check if the user is already logged in or not Future&lt;String&gt; read_loggedIn() async { final prefs = await SharedPreferences.getInstance(); var value = prefs.getString(&quot;loggedIn&quot;); return value; } </code></pre> <p>and here is when the code used</p> <pre><code>Future&lt;void&gt; main() async { runApp(new MaterialApp( debugShowCheckedModeBanner: false, home: (read_loggedIn() == &quot;true&quot;) ? new SPAL (): new MyApp())); } </code></pre>
68,178,721
4
9
null
2021-06-02 04:08:59.21 UTC
3
2021-06-29 12:30:42.837 UTC
null
null
null
null
15,957,792
null
1
29
flutter|dart
9,333
<p>Make sure to call <code>WidgetsFlutterBinding.ensureInitialized();</code> before <code>await SharedPreferences.getInstance();</code></p> <p>For example in your main.dart:</p> <pre><code>void main() async { await runZonedGuarded( () async { WidgetsFlutterBinding.ensureInitialized(); final prefs = await SharedPreferences.getInstance(); runApp(MyApp(prefs)); }, (error, st) =&gt; print(error), ); } </code></pre> <p></p>
25,081,757
What's NSLocalizedString equivalent in Swift?
<p>Is there an Swift equivalent of <code>NSLocalizedString(...)</code>? In <code>Objective-C</code>, we usually use:</p> <pre><code>NSString *string = NSLocalizedString(@"key", @"comment"); </code></pre> <p>How can I achieve the same in Swift? I found a function:</p> <pre><code>func NSLocalizedString( key: String, tableName: String? = default, bundle: NSBundle = default, value: String = default, #comment: String) -&gt; String </code></pre> <p>However, it is very long and not convenient at all.</p>
25,081,758
16
4
null
2014-08-01 13:48:47.663 UTC
63
2021-04-14 13:30:38.18 UTC
2016-01-18 20:12:12.293 UTC
null
1,634,890
null
348,796
null
1
239
ios|swift|localization|nslocalizedstring
124,119
<p>The <code>NSLocalizedString</code> exists also in the Swift's world.</p> <pre><code>func NSLocalizedString( key: String, tableName: String? = default, bundle: NSBundle = default, value: String = default, #comment: String) -&gt; String </code></pre> <p>The <code>tableName</code>, <code>bundle</code>, and <code>value</code> parameters are marked with a <strong><code>default</code></strong> keyword which means we can omit these parameters while calling the function. In this case, their default values will be used.</p> <p>This leads to a conclusion that the method call can be simplified to:</p> <pre><code>NSLocalizedString("key", comment: "comment") </code></pre> <p><strong>Swift 5</strong> - no change, still works like that.</p>
31,978,324
What exactly is std::atomic?
<p>I understand that <code>std::atomic&lt;&gt;</code> is an atomic object. But atomic to what extent? To my understanding an operation can be atomic. What exactly is meant by making an object atomic? For example if there are two threads concurrently executing the following code:</p> <pre><code>a = a + 12; </code></pre> <p>Then is the entire operation (say <code>add_twelve_to(int)</code>) atomic? Or are changes made to the variable atomic (so <code>operator=()</code>)? </p>
31,978,762
3
4
null
2015-08-13 02:00:06.16 UTC
137
2021-05-24 11:48:00.55 UTC
2019-06-02 04:01:21.827 UTC
user4386938
963,864
user4386938
null
null
1
246
c++|multithreading|c++11|atomic
212,735
<p>Each instantiation and full specialization of <a href="http://en.cppreference.com/w/cpp/atomic/atomic" rel="noreferrer">std::atomic&lt;></a> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:</p> <blockquote> <p>Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.</p> <p>In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by <code>std::memory_order</code>.</p> </blockquote> <p><code>std::atomic&lt;&gt;</code> wraps operations that, in pre-C++ 11 times, had to be performed using (for example) <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms686360%28v=vs.85%29.aspx#interlocked_functions" rel="noreferrer">interlocked functions</a> with MSVC or <a href="https://gcc.gnu.org/onlinedocs/gcc-4.4.3/gcc/Atomic-Builtins.html" rel="noreferrer">atomic bultins</a> in case of GCC.</p> <p>Also, <code>std::atomic&lt;&gt;</code> gives you more control by allowing various <a href="http://en.cppreference.com/w/cpp/atomic/memory_order" rel="noreferrer">memory orders</a> that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:</p> <ul> <li><a href="http://bartoszmilewski.com/2008/12/01/c-atomics-and-memory-ordering/" rel="noreferrer">C++ atomics and memory ordering </a></li> <li><a href="https://www.arangodb.com/2015/02/comparing-atomic-mutex-rwlocks/" rel="noreferrer">Comparison: Lockless programming with atomics in C++ 11 vs. mutex and RW-locks</a></li> <li><a href="https://stackoverflow.com/questions/6319146/c11-introduced-a-standardized-memory-model-what-does-it-mean-and-how-is-it-g">C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?</a></li> <li><a href="https://www.classes.cs.uchicago.edu/archive/2013/spring/12300-1/labs/lab6/" rel="noreferrer">Concurrency in C++11</a></li> </ul> <p>Note that, for typical use cases, you would probably use <a href="http://en.cppreference.com/w/cpp/atomic/atomic/operator_arith" rel="noreferrer">overloaded arithmetic operators</a> or <a href="http://en.cppreference.com/w/cpp/atomic/atomic/operator_arith2" rel="noreferrer">another set of them</a>:</p> <pre><code>std::atomic&lt;long&gt; value(0); value++; //This is an atomic op value += 5; //And so is this </code></pre> <p>Because operator syntax does not allow you to specify the memory order, these operations will be performed with <a href="http://en.cppreference.com/w/cpp/atomic/memory_order" rel="noreferrer"><code>std::memory_order_seq_cst</code></a>, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.</p> <p>In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:</p> <pre><code>std::atomic&lt;long&gt; value {0}; value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation </code></pre> <p>Now, your example:</p> <pre><code>a = a + 12; </code></pre> <p>will not evaluate to a single atomic op: it will result in <code>a.load()</code> (which is atomic itself), then addition between this value and <code>12</code> and <code>a.store()</code> (also atomic) of final result. As I noted earlier, <code>std::memory_order_seq_cst</code> will be used here.</p> <p>However, if you write <code>a += 12</code>, it will be an atomic operation (as I noted before) and is roughly equivalent to <code>a.fetch_add(12, std::memory_order_seq_cst)</code>.</p> <p>As for your comment:</p> <blockquote> <p>A regular <code>int</code> has atomic loads and stores. Whats the point of wrapping it with <code>atomic&lt;&gt;</code>?</p> </blockquote> <p>Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic <code>std::atomic&lt;&gt;</code> is something that is guaranteed to be atomic on <em>every</em> platform, without additional requirements. Moreover, it allows you to write code like this:</p> <pre><code>void* sharedData = nullptr; std::atomic&lt;int&gt; ready_flag = 0; // Thread 1 void produce() { sharedData = generateData(); ready_flag.store(1, std::memory_order_release); } // Thread 2 void consume() { while (ready_flag.load(std::memory_order_acquire) == 0) { std::this_thread::yield(); } assert(sharedData != nullptr); // will never trigger processData(sharedData); } </code></pre> <p>Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after <code>while</code> loop exits. That is because:</p> <ul> <li><code>store()</code> to the flag is performed after <code>sharedData</code> is set (we assume that <code>generateData()</code> always returns something useful, in particular, never returns <code>NULL</code>) and uses <code>std::memory_order_release</code> order:</li> </ul> <blockquote> <p><code>memory_order_release</code></p> <p>A store operation with this memory order performs the <strong>release</strong> operation: no reads or writes in the current thread can be reordered <strong>after</strong> this store. <strong>All writes in the current thread are visible in other threads that acquire the same atomic variable</strong></p> </blockquote> <ul> <li><code>sharedData</code> is used after <code>while</code> loop exits, and thus after <code>load()</code> from flag will return a non-zero value. <code>load()</code> uses <code>std::memory_order_acquire</code> order:</li> </ul> <blockquote> <p><code>std::memory_order_acquire</code></p> <p>A load operation with this memory order performs the <strong>acquire</strong> operation on the affected memory location: no reads or writes in the current thread can be reordered <strong>before</strong> this load. <strong>All writes in other threads that release the same atomic variable are visible in the current thread</strong>.</p> </blockquote> <p>This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the <a href="http://en.cppreference.com/w/cpp/atomic/memory_order#Release-Consume_ordering" rel="noreferrer">release-consume ordering</a>.</p>
10,408,740
Why does in_array() wrongly return true with these (large numeric) strings?
<p>I am not getting what is wrong with this code. It's returning "Found", which it should not.</p> <pre><code>$lead = "418176000000069007"; $diff = array("418176000000069003","418176000000057001"); if (in_array($lead,$diff)) echo "Found"; else echo "Not found"; </code></pre>
10,408,802
9
10
null
2012-05-02 06:27:13.65 UTC
13
2020-05-18 11:46:31.857 UTC
2012-05-31 13:15:17.807 UTC
null
367,456
null
929,265
null
1
43
php|arrays
8,189
<p><strong>Note: <em>This was a bug in PHP old versions and is corrected in <code>PHP 5.4</code> and newer versions.</em></strong> </p> <p>It is because of the limitations of the number storage in <code>PHP</code></p> <p>The real problem here is because of the <code>PHP_INT_MAX</code> - the value exceeded in our case.</p> <p>Try to <code>echo</code>/<code>print_r</code> <code>$lead</code> and <code>$diff</code> without using the quotes. It will result</p> <pre><code>$lead ---&gt; 418176000000070000 $diff ---&gt; Array ( [0] =&gt; 418176000000070000 [1] =&gt; 418176000000060000 ) </code></pre> <p>so, in this case, the <code>in_array</code> result is true!</p> <p>so use <code>strict</code> comparison in <code>in_array()</code> by setting third argument in <code>in_array()</code> as <code>true</code> <pre><code> if(in_array($lead,$diff,true)) //use type too echo "Found"; else echo "Not found"; ?&gt; </code></pre> <p>Try this. It will work.</p>
41,102,299
Pip Error : 'module' object has no attribute 'Cryptography_HAS_SSL_ST'
<p>I tried to install from pip and keep on getting similar type of errors.</p> <pre><code>$ pip install quandl Traceback (most recent call last): File "/usr/bin/pip", line 9, in &lt;module&gt; load_entry_point('pip==1.5.6', 'console_scripts', 'pip')() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 558, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2682, in load_entry_point return ep.load() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2355, in load return self.resolve() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2361, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 74, in &lt;module&gt; from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/usr/lib/python2.7/dist-packages/pip/vcs/mercurial.py", line 9, in &lt;module&gt; from pip.download import path_to_url File "/usr/lib/python2.7/dist-packages/pip/download.py", line 22, in &lt;module&gt; import requests, six File "/usr/lib/python2.7/dist-packages/requests/__init__.py", line 53, in &lt;module&gt; from .packages.urllib3.contrib import pyopenssl File "/usr/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 53, in &lt;module&gt; import OpenSSL.SSL File "/home/ubuntu/.local/lib/python2.7/site-packages/OpenSSL/__init__.py", line 8, in &lt;module&gt; from OpenSSL import rand, crypto, SSL File "/home/ubuntu/.local/lib/python2.7/site-packages/OpenSSL/SSL.py", line 112, in &lt;module&gt; if _lib.Cryptography_HAS_SSL_ST: AttributeError: 'module' object has no attribute 'Cryptography_HAS_SSL_ST' </code></pre> <p>Now even though i tried to install different pip modules iam getting same error.Is there any solution for this ? This was caused due to the unexpected killing of the process while a pip module is being downloaded.</p> <p>Please help me with the necessary steps to rectify this error.</p> <p>I tried to install this </p> <pre><code>$ pip install -U cryptography Traceback (most recent call last): File "/usr/bin/pip", line 9, in &lt;module&gt; load_entry_point('pip==1.5.6', 'console_scripts', 'pip')() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 558, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2682, in load_entry_point return ep.load() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2355, in load return self.resolve() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2361, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 74, in &lt;module&gt; from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/usr/lib/python2.7/dist-packages/pip/vcs/mercurial.py", line 9, in &lt;module&gt; from pip.download import path_to_url File "/usr/lib/python2.7/dist-packages/pip/download.py", line 22, in &lt;module&gt; import requests, six File "/usr/lib/python2.7/dist-packages/requests/__init__.py", line 53, in &lt;module&gt; from .packages.urllib3.contrib import pyopenssl File "/usr/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 53, in &lt;module&gt; import OpenSSL.SSL File "/home/ubuntu/.local/lib/python2.7/site-packages/OpenSSL/__init__.py", line 8, in &lt;module&gt; from OpenSSL import rand, crypto, SSL File "/home/ubuntu/.local/lib/python2.7/site-packages/OpenSSL/SSL.py", line 112, in &lt;module&gt; if _lib.Cryptography_HAS_SSL_ST: AttributeError: 'module' object has no attribute 'Cryptography_HAS_SSL_ST' </code></pre>
45,853,179
9
7
null
2016-12-12 13:45:05.68 UTC
8
2019-01-20 20:58:30.053 UTC
2018-06-16 20:20:16.207 UTC
null
5,908,241
null
5,908,241
null
1
17
python|linux|ubuntu|openssl|pip
29,262
<p>Ubuntu 16.04.3 here:</p> <p>I think I have fixed this by removing the python-openssl package (and it's dependencies) with:</p> <pre><code>apt-get --auto-remove remove python-openssl </code></pre> <p>Then installing the latest version with pip:</p> <pre><code>pip install pyOpenSSL </code></pre> <p>Of course, if you install another apt package that depends on it, it'll pull it back in. I hope if you use pip for everything you can from now on instead of apt, it should be fine.</p> <p>Edit: as of January 2019 this issue doesn't seem to exist any more.</p>
51,911,368
What restriction is perf_event_paranoid == 1 actually putting on x86 perf?
<p>Newer Linux kernels have a sysfs tunable <code>/proc/sys/kernel/perf_event_paranoid</code> which allows the user to adjust the available functionality of <code>perf_events</code> for non-root users, with higher numbers being more secure (offering correspondingly less functionality):</p> <p>From the <a href="https://www.kernel.org/doc/Documentation/sysctl/kernel.txt" rel="noreferrer">kernel documenation</a> we have the following behavior for the various values:</p> <blockquote> <p>perf_event_paranoid:</p> <p>Controls use of the performance events system by unprivileged users (without CAP_SYS_ADMIN). The default value is 2.</p> <p>-1: Allow use of (almost) all events by all users Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK</p> <p>>=0: Disallow ftrace function tracepoint by users without CAP_SYS_ADMIN Disallow raw tracepoint access by users without CAP_SYS_ADMIN</p> <p>>=1: Disallow CPU event access by users without CAP_SYS_ADMIN</p> <p>>=2: Disallow kernel profiling by users without CAP_SYS_ADMIN</p> </blockquote> <p>I have <code>1</code> in my <code>perf_event_paranoid</code> file which should "Disallow CPU event access" - but what does that mean exactly?</p> <p>A plain reading would imply no access to CPU performance counter events (such as Intel PMU events), but it seems I can access those just fine. For example:</p> <pre><code>$ perf stat sleep 1 Performance counter stats for 'sleep 1': 0.408734 task-clock (msec) # 0.000 CPUs utilized 1 context-switches # 0.002 M/sec 0 cpu-migrations # 0.000 K/sec 57 page-faults # 0.139 M/sec 1,050,362 cycles # 2.570 GHz 769,135 instructions # 0.73 insn per cycle 152,661 branches # 373.497 M/sec 6,942 branch-misses # 4.55% of all branches 1.000830821 seconds time elapsed </code></pre> <p>Here, many of the events are CPU PMU events (<code>cycles</code>, <code>instructions</code>, <code>branches</code>, <code>branch-misses</code>, <code>cache-misses</code>).</p> <p>If these aren't the CPU events being referred to, what are they?</p>
51,919,744
1
5
null
2018-08-18 18:08:54.447 UTC
9
2018-08-19 16:36:25.46 UTC
null
null
null
null
149,138
null
1
27
linux-kernel|x86|profiling|perf|intel-pmu
23,689
<p>In this case <em>CPU event</em> refers to monitoring events per CPU rather than per task. For <code>perf</code> tools this restricts the usage of</p> <pre><code>-C, --cpu= Count only on the list of CPUs provided. Multiple CPUs can be provided as a comma-separated list with no space: 0,1. Ranges of CPUs are specified with -: 0-2. In per-thread mode, this option is ignored. The -a option is still necessary to activate system-wide monitoring. Default is to count on all CPUs. -a, --all-cpus system-wide collection from all CPUs (default if no target is specified) </code></pre> <p>For <code>perf_event_open</code> this considers the following case:</p> <pre><code>pid == -1 and cpu &gt;= 0 This measures all processes/threads on the specified CPU. This requires CAP_SYS_ADMIN capability or a /proc/sys/ker‐ nel/perf_event_paranoid value of less than 1. </code></pre> <p>This may be version specific, the cited documentation is from 4.17. This is <a href="https://unix.stackexchange.com/q/14227/45546">another related question</a>.</p>
51,891,415
NullPointerException on Meizu devices in Editor.updateCursorPositionMz
<p>Lately, there have been crashes on my Android app, on Meizu devices <strong>only</strong> (M5c, M5s, M5 Note). Android version: 6.0.</p> <p>Here is the full stack trace:</p> <pre><code>Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.text.Layout.getLineForOffset(int)' on a null object reference at android.widget.Editor.updateCursorPositionMz(Editor.java:6964) at android.widget.Editor.updateCursorsPositions(Editor.java:1760) at android.widget.TextView.getUpdatedHighlightPath(TextView.java:5689) at android.widget.TextView.onDraw(TextView.java:5882) at android.view.View.draw(View.java:16539) at android.view.View.updateDisplayListIfDirty(View.java:15492) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3719) at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3699) at android.view.View.updateDisplayListIfDirty(View.java:15443) at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:286) at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:292) at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:327) at android.view.ViewRootImpl.draw(ViewRootImpl.java:3051) at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2855) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2464) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1337) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6819) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894) at android.view.Choreographer.doCallbacks(Choreographer.java:696) at android.view.Choreographer.doFrame(Choreographer.java:631) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880) at android.os.Handler.handleCallback(Handler.java:815) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:207) at android.app.ActivityThread.main(ActivityThread.java:5969) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:830) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:720) </code></pre> <p>There is no direct relation to my code (even in other threads' stracktraces). I only know that it happens <strong>everytime</strong> in a Fragment in which there are TextViews. It might be happening when a TextView is gaining focus but I have no way of being sure. Of course I cannot reproduce the bug, unless I buy a Meizu.</p> <p>Also, since the top method is called <code>updateCursorPositionMz</code>, it looks to me like this may be an internal issue in Meizu's FlymeOS ("Mz" = "Meizu"?).</p> <p>Has anyone already had this issue, knows the cause and how to fix it?</p> <p>Thanks.</p>
52,001,305
9
6
null
2018-08-17 08:34:49.783 UTC
16
2019-08-06 12:47:08.957 UTC
null
null
null
null
4,561,039
null
1
73
android|textview|meizu
10,715
<h2>Update (Aug. 8, 2019)</h2> <p>As @andreas-wenger, @waseefakhtar and @vadim-kotov mentioned, the fix is now included from <a href="https://github.com/material-components/material-components-android/releases" rel="noreferrer">com.google.android.material:material:1.1.0-alpha08</a> onwards.</p> <h2>Old answer</h2> <p>Finally I had the chance to put my hands on a Meizu. As I thought, the crash occurs every time the user clicks on a field to get the focus.</p> <p>In my case, I had some <code>android.support.design.widget.TextInputEditText</code> inside <code>TextInputLayout</code>s. Simply replacing these <code>TextInputEditText</code>s with <code>AppCompatEditText</code>s fixed the problem, like so:</p> <pre><code>&lt;android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="..."&gt; &lt;android.support.v7.widget.AppCompatEditText android:layout_width="match_parent" android:layout_height="wrap_content"/&gt; &lt;/android.support.design.widget.TextInputLayout&gt; </code></pre> <p>The behavior remains the same (since <code>TextInputEditText</code> extends <code>AppCompatEditText</code>). I still haven't found the root cause of the problem though.</p>
28,795,975
iOS App Rejection due to 2.23 - iOS Data Storage Guidelines
<p>Here's message from Apple about rejection : </p> <blockquote> <p>2.23 - Apps must follow the iOS Data Storage Guidelines or they will be rejected 2.23 Details</p> <p>On launch and content download, your app stores 6.5 MB, which does not comply with the iOS Data Storage Guidelines.</p> <p>Next Steps</p> <p>Please verify that only the content that the user creates using your app, e.g., documents, new files, edits, etc. is backed up by iCloud as required by the iOS Data Storage Guidelines. Also, check that any temporary files used by your app are only stored in the /tmp directory; please remember to remove or delete the files stored in this location when it is determined they are no longer needed.</p> <p>Data that can be recreated but must persist for proper functioning of your app - or because users expect it to be available for offline use - should be marked with the "do not back up" attribute. For NSURL objects, add the NSURLIsExcludedFromBackupKey attribute to prevent the corresponding file from being backed up. For CFURLRef objects, use the corresponding kCRUFLIsExcludedFromBackupKey attribute.</p> </blockquote> <p>I checked out the data files of my application both for device and simulator. I found that if app has used for a while, it's total app data could store 5-6 MB, on launch. But I uninstalled and re-installed app and checked again, I see ~3MB data store on launch of app.</p> <p>I'm not storing any Core Data databases or any other database files. But I've realized that <strong>Google Analytics and Google Tag Manager</strong> stores some sqlite data on this path : "AppData/Library". I mean it does NOT store on this path : "AppData/Library/Caches". Does it make any difference for iOS Data Storage Guidelines?</p> <p>By the way, <strong>iCloud</strong> is disabled for application.</p> <p>Also I'm using <strong>SDWebImage</strong> for downloading images and it stores almost 3 MB images on the launch and it stores image data on this path : "AppData/Library/Caches"</p> <p>Do you have any idea that what should I do to handle this issue?</p>
29,182,488
3
11
null
2015-03-01 16:28:19.877 UTC
10
2016-07-15 03:17:59.737 UTC
2015-03-02 20:54:42.04 UTC
null
1,011,777
null
1,011,777
null
1
20
ios|objective-c|app-store|appstore-approval
7,006
<p>I just got the same rejection message yesterday.</p> <p>I use the following code in <code>application:didFinishLaunchingWithOptions:</code> to see what my application has inside the documents folder and what is the permission of each item about iCloud backup:</p> <pre><code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *basePath = ([paths count] &gt; 0) ? [paths objectAtIndex:0] : nil; NSArray *documents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:basePath error:nil]; NSURL *URL; NSString *completeFilePath; for (NSString *file in documents) { completeFilePath = [NSString stringWithFormat:@"%@/%@", basePath, file]; URL = [NSURL fileURLWithPath:completeFilePath]; NSLog(@"File %@ is excluded from backup %@", file, [URL resourceValuesForKeys:[NSArray arrayWithObject:NSURLIsExcludedFromBackupKey] error:nil]); } </code></pre> <p>I had some files inside that folder that were synchronising with iCloud. So instead of saving those files in another place I set the resource value for the <code>NSURLIsExcludedFromBackupKey</code> key set to <code>YES</code> to exclude those files from being backed up by iCloud, like this:</p> <pre><code>NSURL *URL = [NSURL fileURLWithPath:photoPath]; [URL setResourceValue:@(YES) forKey:NSURLIsExcludedFromBackupKey error:nil]; </code></pre> <p>I'm sending my app again today to see if works.</p> <p>Hope this help.</p>
28,521,583
UIPopoverPresentationController on iPhone doesn't produce popover
<p>I'm trying to implement the new <code>UIPopoverPresentationController</code> in my iPhone app (using Objective C). What I want is a simple popover with a tableview that emanates from the initiating button.</p> <p><strong>--Edit--</strong></p> <p>Here's my <strong>REVISED</strong> code, adapted from research in the docs, SO, and from input in comments below:</p> <pre><code>- (IBAction)selectCategoryBtn:(UIButton *)sender { [self performSegueWithIdentifier:@"CatSelectSegue" sender:self.selCatButton]; } -(void) prepareForSegue:(UIStoryboardSegue *) segue Sender:(id) sender { if (sender == self.selCatButton) { if ([segue.identifier isEqualToString:@"CatSelectSegue"]) { UIPopoverPresentationController *controller = segue.destinationViewController; controller.delegate = self; controller.sourceView = self.selCatButton; controller.sourceRect = self.selCatButton.frame; } } } -(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller { return UIModalPresentationNone; </code></pre> <p>Here's my storyboard hookup:</p> <p><img src="https://i.stack.imgur.com/Hhz6g.png" alt="enter image description here"></p> <p>However this simply presents a tableview in a modal fashion, rising up from the bottom and consuming the entire screen.</p> <p>I've googled, and looked all over SO, but it appears that I'm not the only one confused by what I'd hoped would resolve a nettlesome issue for the iPhone.</p> <p>Can anyone see a glitch in my code or direct me to a clear tutorial? I've looked, but maybe the API is just so new nobody's got a handle on it yet.</p> <p>Thanks!</p> <p><strong>2nd edit:</strong></p> <p>Here's what gets presented as a result of the code above. I reduced the size of the tableview in the View Controller I expected to be presented as a popover. I colored the background gray, just to clarify what's showing up instead of the popover.</p> <p><img src="https://i.stack.imgur.com/VyzFD.png" alt="enter image description here"></p>
28,521,768
5
13
null
2015-02-14 23:50:18.46 UTC
17
2022-05-25 12:22:21.257 UTC
2015-02-15 04:36:59.87 UTC
null
2,671,035
null
2,671,035
null
1
33
ios|objective-c|iphone|popover
37,356
<p>Steps:</p> <p>A) Link your <code>UIButton</code> to the popover's view controller using the <code>Present As Popover</code> segue type. I actually had to create a new project to get this to appear but it's probably something to do with the base SDK.</p> <p>B) Make the View Controller containing the <code>UIButton</code> conform to the <code>&lt;UIPopoverPresentationControllerDelegate&gt;</code>. E.g. In your <code>MyViewController.m</code> file add:</p> <pre><code>@interface MyViewController () &lt;UIPopoverPresentationControllerDelegate&gt; </code></pre> <p>C) Add the method below to the View Controller containing the <code>UIButton</code>:</p> <pre><code>- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller { return UIModalPresentationNone; } </code></pre> <p>D) Add the following into your <code>prepareForSegue:sender:</code> replacing your <code>segue.identifier</code> check:</p> <pre><code>if ([segue.identifier isEqualToString:@"CatSelectSegue"]) { UIViewController *dvc = segue.destinationViewController; UIPopoverPresentationController *controller = dvc.popoverPresentationController; if (controller) { controller.delegate = self; } } </code></pre> <p>Code tested and proof it works:</p> <p><img src="https://i.stack.imgur.com/MWGUp.png" alt="Popover on iPhone without 3rd Party Controls"></p> <p>Edit: My test app TPOPViewController.m file where the magic happens:</p> <pre><code>#import "TPOPViewController.h" @interface TPOPViewController () &lt;UIPopoverPresentationControllerDelegate&gt;//, UIAdaptivePresentationControllerDelegate&gt; @end @implementation TPOPViewController - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { NSString *identifier = segue.identifier; if ([identifier isEqualToString:@"popover"]) { UIViewController *dvc = segue.destinationViewController; UIPopoverPresentationController *ppc = dvc.popoverPresentationController; if (ppc) { if ([sender isKindOfClass:[UIButton class]]) { // Assumes the popover is being triggered by a UIButton ppc.sourceView = (UIButton *)sender; ppc.sourceRect = [(UIButton *)sender bounds]; } ppc.delegate = self; } } } - (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller { return UIModalPresentationNone; } @end </code></pre> <p>My test storyboard as well:</p> <p><img src="https://i.stack.imgur.com/G77HZ.png" alt="Popover on iPhone test storyboard"></p>
9,440,380
Using an instance of an object as a key in hashmap, and then access it with exactly new object?
<p>I have a hasmap with a key object, </p> <pre><code>HashMap&lt;Key, Object&gt; test; </code></pre> <p>and make new Key("the same") as key..</p> <p>so its like..:</p> <pre><code>test.put(new Key("the same"), someObject); </code></pre> <p>(without storing that key in a variable)</p> <p>so.. after a while... i want to access the hashmap, because i do not have the object, i've tried to make new Key("the same") and make it as a key. But it didnt work.</p> <p>How to make it work? (without saving the first object "key" in a variable)</p> <p>So meanwhile, for now, im using String object as a key.</p> <pre><code>HashMap&lt;String, Object&gt; </code></pre>
9,440,411
3
2
null
2012-02-25 01:44:37.703 UTC
18
2015-12-16 14:56:58.923 UTC
null
null
null
null
448,451
null
1
51
java|hashmap
138,678
<p>You need to implement <code>hashCode</code> and <code>equals</code> on <code>Key</code>. The <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals%28java.lang.Object%29">default implementation</a> of these methods simply checks for <em>instance</em> equality (in other words, two <code>Object</code>s will only be equal if they are in fact the same object).</p> <h2>Further reading</h2> <p><a href="http://fpl.cs.depaul.edu/jriely/ds2/extras/Chapter3.pdf">Effective Java - Methods common to all objects</a></p>
16,062,893
Why does @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) fix Hibernate Lazy Loading Exceptions?
<p>I switched an app I am working on from using AspectJ load time weaving to using Spring CGlib proxies and right after I did that there were many parts of the code where I started to get hibernate lazy loading exceptions where in the past there were no exceptions being thrown.</p> <p>I have been able to resolve these lazy loading exceptions by adding <code>@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)</code> to bunch of previously public methods that did not have any transactional attributes on them but called spring repositories to read data from the database.</p> <p>Anyone know why adding <code>@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)</code> eliminates the hibernate lazy loading exceptions and why these annotations were not required with AspectJ load time weaving but are are required with out?</p> <p><strong>Update 2</strong> <strong>I believe that removing AspectJ was NOT the issue</strong>, but the issue was was that I did not really understand the actual behavior of the SUPPORTS propagation. In particular how SUPPORTS interacted with the JPA EntityManager and so I removed a bunch a SUPPORTS propagation which caused the lazy loading exceptions. After reading through the source code for the Spring Transaction Manager It all became clear as to what to do. The key idea that the spring documentation does not really point out very well is that @Transactional annotations are used as synchronization points that tie life cycle of an EntityManager to the start and end of a transactional method. Also highly recommend this series of articles at <a href="http://www.ibm.com/developerworks/java/library/j-ts1/" rel="noreferrer">http://www.ibm.com/developerworks/java/library/j-ts1/</a> and this blog post <a href="http://doanduyhai.wordpress.com/2011/11/21/spring-persistencecontext-explained/" rel="noreferrer">http://doanduyhai.wordpress.com/2011/11/21/spring-persistencecontext-explained/</a></p> <p><strong>Update 1</strong> </p> <p>This is not a case of calls to private @Transactional methods not going through the AOP proxy. These issues are happening with public methods that are being called from other services. </p> <p>Here is an example of the code structure, where I see the problem occurring. </p> <pre><code>@Service public class FooService { @Autowired private BarService barService; public void someMethodThatOnlyReads() { SomeResult result = this.barService.anotherMethodThatOnlyReads() // the following line blows up with a HibernateLazyLoadingEcxeption // unless there is a @Transactional supports annotation on this method result.getEntity().followSomeRelationship(); } } @Service public class BarService { @Autowired private BarRepository barRepo; public SomeResult anotherMethodThatOnlyReads() { SomeEntity entity = this.barRepo.findSomeEntity(1123); SomeResult result = new SomeResult(); result.setEntity(entity); return result; } } @Repository public class BarRepository { @PersistenceContext private EntityManager em; public SomeEntity findSomeEntity(id Integer) { em.find(SomeEntity.class,id); } } </code></pre>
16,555,359
2
0
null
2013-04-17 14:33:03.803 UTC
9
2013-05-21 15:07:39.477 UTC
2013-05-21 15:07:39.477 UTC
null
438,319
null
438,319
null
1
18
java|spring|hibernate
9,392
<p>I assume your code is not using <code>OpenSessionInViewFilter</code> or anything similar.</p> <p>Without the <code>@Transactional</code> annotation, the Hibernate session is closed after leaving the <code>BarRepository.findSomeEntity()</code> method.</p> <p>When a <code>@Transactional</code> method is called and the <code>TransactionalInterceptor</code> is properly bound to the method (through the cglib proxy or whatever other AOP configuration you have in the Spring context), then the Session is held open by Spring for the entirety of the annotated method, thus preventing any lazy loading exceptions.</p> <p>If you turn up the logging to <code>DEBUG</code> on the <code>org.springframework.transaction</code> and <code>org.springframework.orm.hibernate3</code> (or <code>hibernate4</code> if you are on Hibernate 4) loggers, particularly the <code>HibernateTransactionManager</code> class and <code>org.springframework.transaction.support.AbstractPlatformTransactionManager</code>, you should see exactly at which points in the code flow Spring is deciding it needs to open and close the Hibernate Session. The logs should also show why a session or transaction is opened/closed at each point.</p>
16,455,777
Python Count Elements in a List of Objects with Matching Attributes
<p>I am trying to find a simple and fast way of counting the number of Objects in a list that match a criteria. e.g.</p> <pre><code>class Person: def __init__(self, Name, Age, Gender): self.Name = Name self.Age = Age self.Gender = Gender # List of People PeopleList = [Person("Joan", 15, "F"), Person("Henry", 18, "M"), Person("Marg", 21, "F")] </code></pre> <p>Now what's the simplest function for counting the number of objects in this list that match an argument based on their attributes? E.g., returning 2 for Person.Gender == "F" or Person.Age &lt; 20.</p>
16,455,812
5
0
null
2013-05-09 06:30:01.227 UTC
8
2016-11-24 15:24:22.57 UTC
null
null
null
null
1,148,991
null
1
60
python|list|object|attributes|count
72,620
<pre><code>class Person: def __init__(self, Name, Age, Gender): self.Name = Name self.Age = Age self.Gender = Gender &gt;&gt;&gt; PeopleList = [Person("Joan", 15, "F"), Person("Henry", 18, "M"), Person("Marg", 21, "F")] &gt;&gt;&gt; sum(p.Gender == "F" for p in PeopleList) 2 &gt;&gt;&gt; sum(p.Age &lt; 20 for p in PeopleList) 2 </code></pre>
16,132,759
Is there auto type inferring in Java?
<p>Is there an <code>auto</code> variable type in Java like you have in C++?</p> <p>An example:</p> <pre><code>for ( auto var : object_array) std::cout &lt;&lt; var &lt;&lt; std::endl; for( auto var : object_array) var.do_something_that_only_this_particular_obj_can_do(); </code></pre> <p>I know that there is an enhanced for loop in Java, but is there an auto? If not, is there a hack to doing this? I am referring to the new feature in C++11</p>
16,132,818
6
5
null
2013-04-21 15:23:15.607 UTC
17
2020-11-29 13:11:27.103 UTC
2017-06-18 16:17:30.07 UTC
null
1,033,581
null
1,624,921
null
1
155
java|c++|auto
115,105
<p>Java 10 introduced a <code>var</code> identifier which is like C++ <code>auto</code>; see <a href="https://stackoverflow.com/a/47037550/">sorrymissjackson's answer</a>.</p> <p>Prior to Java 10, there was no equivalent to the <code>auto</code> keyword. The same loop can be achieved as:</p> <pre><code>for ( Object var : object_array) System.out.println(var); </code></pre> <p>Java has local variables, whose scope is within the block where they have been defined. <em>Similar to C and C++, but there is no auto or register keyword. However, the Java compiler will not allow the usage of a not-explicitly-initialized local variable and will give a compilation error (unlike C and C++ where the compiler will usually only give a warning).</em> Courtesy: <a href="http://en.wikipedia.org/wiki/Automatic_variable" rel="noreferrer">Wikipedia</a>.</p> <p>There wasn't any mainstream type-inference in Java like C++ . There was an <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4459053" rel="noreferrer">RFE</a> but this was closed as &quot;Will not fix&quot;. The given was:</p> <blockquote> <p>Humans benefit from the redundancy of the type declaration in two ways. First, the redundant type serves as valuable documentation - readers do not have to search for the declaration of getMap() to find out what type it returns. Second, the redundancy allows the programmer to declare the intended type, and thereby benefit from a cross check performed by the compiler.</p> </blockquote>
12,844,687
Code 128 Barcode generation in vb.net
<p>I am attempting to take a string and convert it into a code 128 barcode in vb.net. I am a novice programmer and was wondering what some people thought would be the best design practices for accomplishing this. </p> <p>A simple google search has yielded a few seemingly free solutions to this. <a href="http://www.onbarcode.com/vb_net/code-128-generator.html" rel="nofollow">http://www.onbarcode.com/vb_net/code-128-generator.html</a> for example </p> <p>I could also attempt to do this myself, but I'm not sure the exact method of converting strings into barcodes. I am going to keep looking into this but if someone knew this off the top of their head already it could save me some time. </p> <p>Thanks in advance</p>
13,234,682
5
1
null
2012-10-11 16:54:21.927 UTC
null
2019-03-26 18:32:46.053 UTC
null
null
null
null
1,665,657
null
1
3
vb.net|visual-studio-2010|barcode|code128
44,989
<p>If you don't want to write any code for string conversion in barcode and don't want to buy an external component, you can use the ItextSharp library ( <a href="http://sourceforge.net/projects/itextsharp/" rel="nofollow">http://sourceforge.net/projects/itextsharp/</a> ) which is in my opinion the simplest way to achieve your goal. You can find several resources online and on stackoverflow too for itextsharp, mostly in c# but also vb.net.</p> <p>for barcode generation vb.net code you can have a look here: <a href="http://professionalaspnet.com/archive/2008/11/09/A-Quick-and-Dirty-Bar-Code-Image-httpHandler.aspx" rel="nofollow">http://professionalaspnet.com/archive/2008/11/09/A-Quick-and-Dirty-Bar-Code-Image-httpHandler.aspx</a></p>
37,578,362
How to add "colSpan" attribute in ReactJS
<p>I'm getting the error "<strong>Type string is not assignable to type number</strong>" when I try to add a <strong>colSpan="2"</strong> attribute to the below ReactJS TypeScript code. How can I fix this?</p> <pre><code>class ProductCategoryRow extends React.Component&lt;MyProps, MyState&gt; { constructor(props: MyProps) { super(props); } render() { return (&lt;div&gt; &lt;tr&gt;&lt;th colSpan="2"&gt;{ this.props.category }&lt;/th&gt;&lt;/tr&gt; &lt;/div&gt;); } //end render. } //end class. </code></pre>
37,579,218
1
4
null
2016-06-01 20:39:05.067 UTC
3
2017-11-10 08:01:40.46 UTC
2017-09-09 06:48:55.73 UTC
null
28,324
null
2,304,788
null
1
46
reactjs|typescript
36,613
<p>Have you tried <code>&lt;th colSpan={2}&gt;{ this.props.category}&lt;/th&gt;</code>?</p>
24,665,649
Why does C# not allow me to call a void method as part of the return statement?
<p>I am curious if there is a legitimate reason as to why C# does not support calling a void method as part of the return statement when the calling method's return type is also void.</p> <pre><code>public void MethodA() { return; } public void MethodB() { return MethodA(); } </code></pre> <p>So we would normally see this:</p> <pre><code>public void MethodMeh() { if (expression) { MethodA(); return; } // Do more stuff } </code></pre> <p>... when we could be using this instead:</p> <pre><code>public void MethodAwesome() { if (expression) return MethodA(); // Do more stuff } </code></pre> <p>Is this a language limitation due to how C# handles void?</p>
24,665,814
9
18
null
2014-07-10 00:15:54.937 UTC
4
2014-07-24 16:24:29.03 UTC
2014-07-11 18:38:56.1 UTC
null
302,939
null
302,939
null
1
38
c#|void
13,647
<p>Because it's simply the way <a href="http://msdn.microsoft.com/en-us/library/ms228593.aspx">the language is defined</a>.</p> <blockquote> <p>A method can use <code>return</code> statements to return control to its caller. <strong>In a method returning <code>void</code>, <code>return</code> statements cannot specify an expression.</strong> In a method returning non-<code>void</code>, <code>return</code> statements must include an expression that computes the return value.</p> </blockquote> <p>It's an arbitrary decision (presumably made for compatibility with ANSI C and its other descendants), and other languages do things differently.</p> <p>For example, in Python, all functions return a value. If you execute a <code>return</code> statement without a value, or let control reach the end of the function, then it's just like you had written <code>return None</code>.</p> <p>In contrast, Pascal limits the terminology of <code>function</code> to subprograms that have a return value; if you don't want to return anything, you use a <code>procedure</code> instead.</p>
21,512,678
Check at compile-time is a template type a vector
<p>I can imagine the following code:</p> <pre><code>template &lt;typename T&gt; class X { public: T container; void foo() { if(is_vector(T)) container.push_back(Z); else container.insert(Z); } } // somewhere else... X&lt;std::vector&lt;sth&gt;&gt; abc; abc.foo(); </code></pre> <p>How to write it, to successfully compile? I know type traits, but when I'm defining:</p> <pre><code>template&lt;typename T&gt; struct is_vector : public std::false_type {}; template&lt;typename T, typename A&gt; struct is_vector&lt;std::vector&lt;T, A&gt;&gt; : public std::true_type {}; </code></pre> <p>It doesn't compile:</p> <pre><code>error: no matching function for call to 'std::vector&lt;sth&gt;::insert(Z)' </code></pre> <p>static_assert also isn't that what I'm looking for. Any advices?</p> <p>Here's a short example of what I want to achieve (SSC<del>C</del>E): <a href="http://ideone.com/D3vBph">http://ideone.com/D3vBph</a></p>
21,512,908
6
5
null
2014-02-02 15:59:41.03 UTC
11
2022-01-31 07:57:09.853 UTC
2014-02-02 16:14:32.13 UTC
null
515,203
null
3,127,595
null
1
19
c++|templates
6,496
<p>It is named tag dispatching :</p> <pre><code>#include &lt;vector&gt; #include &lt;set&gt; #include &lt;type_traits&gt; template&lt;typename T&gt; struct is_vector : public std::false_type {}; template&lt;typename T, typename A&gt; struct is_vector&lt;std::vector&lt;T, A&gt;&gt; : public std::true_type {}; template &lt;typename T&gt; class X { T container; void foo( std::true_type ) { container.push_back(0); } void foo( std::false_type ) { container.insert(0); } public: void foo() { foo( is_vector&lt;T&gt;{} ); } }; // somewhere else... int main() { X&lt;std::vector&lt;int&gt;&gt; abc; abc.foo(); X&lt;std::set&lt;int&gt;&gt; def; def.foo(); } </code></pre>
19,691,920
Collision resolution in Java HashMap
<p>Java <code>HashMap</code> uses <code>put</code> method to insert the K/V pair in <code>HashMap</code>. Lets say I have used <code>put</code> method and now <code>HashMap&lt;Integer, Integer&gt;</code> has one entry with <code>key</code> as 10 and <code>value</code> as 17.</p> <p>If I insert 10,20 in this <code>HashMap</code> it simply replaces the the previous entry with this entry due to collision because of same key 10. </p> <p>If the key collides <code>HashMap</code> replaces the old K/V pair with the new K/V pair. </p> <p>So my question is when does the <code>HashMap</code> use Chaining collision resolution technique? </p> <p>Why it did not form a <code>linkedlist</code> with key as 10 and value as 17,20?</p>
19,691,998
9
4
null
2013-10-30 19:17:25.21 UTC
34
2021-12-22 14:58:45.577 UTC
2018-05-01 21:00:25.69 UTC
null
2,938,723
null
2,938,723
null
1
89
java|hashmap
150,050
<p>When you insert the pair <code>(10, 17)</code> and then <code>(10, 20)</code>, there is technically no collision involved. You are just replacing the old value with the new value for a given key <code>10</code> (since in both cases, 10 is equal to 10 and also the hash code for 10 is always 10).</p> <p>Collision happens when multiple keys hash to the same bucket. In that case, you need to make sure that you can distinguish between those keys. Chaining collision resolution is one of those techniques which is used for this.</p> <p>As an example, let's suppose that two strings <code>"abra ka dabra"</code> and <code>"wave my wand"</code> yield hash codes <code>100</code> and <code>200</code> respectively. Assuming the total array size is 10, both of them end up in the same bucket (<code>100 % 10</code> and <code>200 % 10</code>). Chaining ensures that whenever you do <code>map.get( "abra ka dabra" );</code>, you end up with the correct value associated with the key. In the case of hash map in Java, this is done by using the <code>equals</code> method.</p>
19,794,739
What is the difference between iteration and recursion?
<p>What is the difference between <code>iteration</code> and <code>recursion</code> and why/when is one better:</p> <pre><code>while (true) { // Iterating } </code></pre> <p>And</p> <pre><code>private void recursion() { if (true) recursion(); // Recursing return; } </code></pre> <p>I see a lot of <code>recursive</code> implementation while it could be easily done in a simple loop.</p>
19,794,926
8
4
null
2013-11-05 17:10:04.88 UTC
16
2016-02-19 17:19:59.993 UTC
2014-03-12 12:40:01.48 UTC
user2742371
null
user2742371
null
null
1
24
c++|recursion|iteration
40,327
<p>There are two main differences between Recursion and an Iterative Version of the same algorithm. </p> <p>First of all, some times it is almost better to understand a recursive algorithm than an iterative one (At least if you are experienced programmer) So it does increase expressivity and in some cases readability (It might also lead to the exact opposite in other cases)</p> <p>Expresivity is a huge deal on programming languages and be able to write the same code in 5 lines instead of 20 is a huge deal.</p> <p>On the downside, it decreases the performance of your code. Recursive functions have to keep the function records in memory and jump from one memory address to another to be invoked to pass parameters and return values. That makes them very bad performance wise. </p> <p><strong>Sum Up:</strong></p> <p>Iterative Algorithms = Fast Performance but hard to write (sometimes hard to read too)</p> <p>Recursive Algorithms = Fast to write but Bad performance wise (Sometimes easier to understand too)</p> <p>Take this example: </p> <pre><code>public static long fib(long n) { if (n &lt;= 1) return n; else return fib(n-1) + fib(n-2); } </code></pre> <p>vs</p> <pre><code> if ((n == 1) || (n == 2)) { return 1; } else { long prev = 1, current = 1, next = 0; for (long i = 3; i &lt;= n; i++) { next = prev + current; prev = current; current = next; } return next; } </code></pre> <p>Source: </p> <p><a href="http://www.csd.uwo.ca/Courses/CS1027a/code/FibonacciDemo.java">http://www.csd.uwo.ca/Courses/CS1027a/code/FibonacciDemo.java</a></p>
21,716,527
In Windows: How do you programatically launch a process in administrator mode under another user context?
<p><strong>Scenario</strong></p> <p>I have a remote computer that I want to run installers (arbitrary executables) on programatically. These installers require two things:</p> <ul> <li>They must run in Administrator mode.</li> <li>They must run under a specific user context (Specifically, a local user who is a member of the Administrators group).</li> </ul> <p>This has proven to be very challenging.</p> <p>It appears as though there are a few external tools that exist that do this, but I am looking for a solution that comes with Windows.</p> <p><strong>What a valid solution to this problem would look like</strong></p> <p>From an elevated context (e.g. an elevated batch file or executable program) a valid solution should be able to programatically launch a process in Administrator mode under another user context. Assume that the other user's id and password are available, and that the other user is a member of the Administrators group. Additional restrictions:</p> <ul> <li>A valid solution cannot rely on an external tool. Since newer versions of Windows come with .NET and PowerShell by default, these are valid tools to use.</li> <li>A valid solution cannot require user interactions. This means that if a UAC window pops up, or if any user confirmation is required, the solution is invalid.</li> </ul> <p><strong><em>Please test your solution before posting it to make sure it works! If you are going to provide a link to another solution, please verify that the linked solution works before posting. Many people who claim to have working solutions to this problem in fact do not.</em></strong></p> <p><strong>What I have tried</strong></p> <p>I have tried using Batch Scripts, PowerShell, and C#. As far as I can tell, none of these technologies will accomplish the task. They all suffer from the same fundamental problem - running a task as another user and in Administrator mode are mutually exclusive processes. Let me be more specific:</p> <p><strong>Why Not Batch</strong></p> <p>The command that one would use to run under a different user context is Runas, which does not launch the process elevated. There are several external tools that claim to get around this, but as stated earlier these are not permitted.</p> <p><strong>Why Not PowerShell</strong></p> <p>The command to start a new process, Start-Process, can elevate a new process and run it as a different user, but not at the same time. I have an open question <a href="https://stackoverflow.com/questions/21641100/from-powershell-how-do-you-launch-an-executable-in-administrator-mode-under-a-d">here</a> referring to this issue. Unfortunately no one has provided a solution, which leads me to believe that it is impossible.</p> <p><strong>Why Not C#</strong></p> <p>This also appears to be impossible, as the Process class does not appear to support launching a process in Administrator mode and under a different user's credentials.</p> <p><strong>Why not an external tool?</strong></p> <p>This forces me to rely on someone else's code to do the right thing, and I would rather code it up myself than do that. In fact I have a <a href="http://www.davidaiken.com/2011/01/19/running-azure-startup-tasks-as-a-real-user/" rel="nofollow noreferrer">solution</a> that is one step better than relying on someone else, but is <strong><em>rather hackish</em></strong>:</p> <ul> <li>Create a task using the Task Scheduler to launch the executable in administrator mode on the specified account at some time in the very distant future.</li> <li>Force the Task to run immediately.</li> <li>Wait to see if the task has finished. <a href="https://stackoverflow.com/questions/20261639/how-do-you-wait-on-a-task-scheduler-task-to-finish-in-a-batch-file-or-c">Answered here</a>.</li> </ul> <p>Thanks in advance to anyone who tries to help! It is greatly appreciated and I hope that if nothing else, other people are able to find this for the Task Scheduler work around.</p>
21,718,198
1
12
null
2014-02-12 00:58:09.337 UTC
9
2017-03-29 01:35:50.09 UTC
2017-05-23 12:10:18.85 UTC
null
-1
null
3,044,940
null
1
2
windows|batch-file
5,335
<p>OK, so it turns out that <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms682431%28v=vs.85%29.aspx" rel="noreferrer"><code>CreateProcessWithLogonW</code></a> function filters the user token, and so does <a href="http://msdn.microsoft.com/en-us/library/aa378184%28v=vs.85%29.aspx" rel="noreferrer"><code>LogonUser</code></a>. This would seem to leave us stuck, since we don't have the right privileges to correct the problem (see footnote) but it turns out that <code>LogonUser</code> does <em>not</em> filter the token if you use <code>LOGON32_LOGON_BATCH</code> rather than <code>LOGON32_LOGON_INTERACTIVE</code>.</p> <p>Here's some code that actually works. We use the <a href="http://msdn.microsoft.com/en-us/library/ms682434%28v=vs.85%29.aspx" rel="noreferrer"><code>CreateProcessAsTokenW</code></a> function to launch the process, because this particular variant requires only <code>SE_IMPERSONATE_NAME</code> privilege, which is granted to administrator accounts by default.</p> <p>This sample program launches a subprocess which creates a directory in <code>c:\windows\system32</code>, which would not be possible if the subprocess was not elevated.</p> <pre><code>#define _WIN32_WINNT 0x0501 #include &lt;Windows.h&gt; #include &lt;Sddl.h&gt; #include &lt;conio.h&gt; #include &lt;stdio.h&gt; wchar_t command[] = L"c:\\windows\\system32\\cmd.exe /c md c:\\windows\\system32\\proof-that-i-am-an-admin"; int main(int argc, char **argv) { HANDLE usertoken; STARTUPINFO sinfo; PROCESS_INFORMATION pinfo; ZeroMemory(&amp;sinfo, sizeof(sinfo)); sinfo.cb = sizeof(sinfo); if (!LogonUser(L"username", L"domain", L"password", LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, &amp;usertoken)) { printf("LogonUser: %u\n", GetLastError()); return 1; } if (!CreateProcessWithTokenW(usertoken, LOGON_WITH_PROFILE, L"c:\\windows\\system32\\cmd.exe", command, 0, NULL, NULL, &amp;sinfo, &amp;pinfo)) { printf("CreateProcess: %u\n", GetLastError()); return 1; } return 0; } </code></pre> <p>However, if the target process is a GUI process (including a process with a visible console) it won't display properly. Apparently <code>CreateProcessWithTokenW</code> only assigns the minimum desktop and window station permissions necessary for a process to run, which is not enough to actually display a GUI.</p> <p>Even if you don't actually need to see the output, there's a risk that the broken GUI will cause functional problems with the program.</p> <p>So, unless the target process runs in the background, we should probably assign permissions appropriately. In general, it is best to create a new window station and a new desktop, to isolate the target process; in this case, though, the target process is going to be running as admin anyway, so there's no point - we can make life easier by just changing the permissions on the existing window station and desktop.</p> <p><em>Edit 24 November 2014: corrected access rights in window station ACE so they will work for non-administrative users. Note that doing this may allow the non-admin user in question to compromise processes in the target session.</em></p> <pre><code>#define _WIN32_WINNT 0x0501 #include &lt;Windows.h&gt; #include &lt;AccCtrl.h&gt; #include &lt;Aclapi.h&gt; #include &lt;stdio.h&gt; wchar_t command[] = L"c:\\windows\\system32\\notepad.exe"; int main(int argc, char **argv) { HANDLE usertoken; STARTUPINFO sinfo; PROCESS_INFORMATION pinfo; HDESK desktop; EXPLICIT_ACCESS explicit_access; BYTE buffer_token_user[SECURITY_MAX_SID_SIZE]; PTOKEN_USER token_user = (PTOKEN_USER)buffer_token_user; PSECURITY_DESCRIPTOR existing_sd; SECURITY_DESCRIPTOR new_sd; PACL existing_dacl, new_dacl; BOOL dacl_present, dacl_defaulted; SECURITY_INFORMATION sec_info_dacl = DACL_SECURITY_INFORMATION; DWORD dw, size; HWINSTA window_station; if (!LogonUser(L"username", L"domain", L"password", LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, &amp;usertoken)) { printf("LogonUser: %u\n", GetLastError()); return 1; } if (!GetTokenInformation(usertoken, TokenUser, buffer_token_user, sizeof(buffer_token_user), &amp;dw)) { printf("GetTokenInformation(TokenUser): %u\n", GetLastError()); return 1; } window_station = GetProcessWindowStation(); if (window_station == NULL) { printf("GetProcessWindowStation: %u\n", GetLastError()); return 1; } if (!GetUserObjectSecurity(window_station, &amp;sec_info_dacl, &amp;dw, sizeof(dw), &amp;size) &amp;&amp; GetLastError() != ERROR_INSUFFICIENT_BUFFER) { printf("GetUserObjectSecurity(window_station) call 1: %u\n", GetLastError()); return 1; } existing_sd = malloc(size); if (existing_sd == NULL) { printf("malloc failed\n"); return 1; } if (!GetUserObjectSecurity(window_station, &amp;sec_info_dacl, existing_sd, size, &amp;dw)) { printf("GetUserObjectSecurity(window_station) call 2: %u\n", GetLastError()); return 1; } if (!GetSecurityDescriptorDacl(existing_sd, &amp;dacl_present, &amp;existing_dacl, &amp;dacl_defaulted)) { printf("GetSecurityDescriptorDacl(window_station): %u\n", GetLastError()); return 1; } if (!dacl_present) { printf("no DACL present on window station\n"); return 1; } explicit_access.grfAccessMode = SET_ACCESS; explicit_access.grfAccessPermissions = WINSTA_ALL_ACCESS | READ_CONTROL; explicit_access.grfInheritance = NO_INHERITANCE; explicit_access.Trustee.pMultipleTrustee = NULL; explicit_access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; explicit_access.Trustee.TrusteeForm = TRUSTEE_IS_SID; explicit_access.Trustee.TrusteeType = TRUSTEE_IS_USER; explicit_access.Trustee.ptstrName = (LPTSTR)token_user-&gt;User.Sid; dw = SetEntriesInAcl(1, &amp;explicit_access, existing_dacl, &amp;new_dacl); if (dw != ERROR_SUCCESS) { printf("SetEntriesInAcl(window_station): %u\n", dw); return 1; } if (!InitializeSecurityDescriptor(&amp;new_sd, SECURITY_DESCRIPTOR_REVISION)) { printf("InitializeSecurityDescriptor(window_station): %u\n", GetLastError()); return 1; } if (!SetSecurityDescriptorDacl(&amp;new_sd, TRUE, new_dacl, FALSE)) { printf("SetSecurityDescriptorDacl(window_station): %u\n", GetLastError()); return 1; } if (!SetUserObjectSecurity(window_station, &amp;sec_info_dacl, &amp;new_sd)) { printf("SetUserObjectSecurity(window_station): %u\n", GetLastError()); return 1; } free(existing_sd); LocalFree(new_dacl); desktop = GetThreadDesktop(GetCurrentThreadId()); if (desktop == NULL) { printf("GetThreadDesktop: %u\n", GetLastError()); return 1; } if (!GetUserObjectSecurity(desktop, &amp;sec_info_dacl, &amp;dw, sizeof(dw), &amp;size) &amp;&amp; GetLastError() != ERROR_INSUFFICIENT_BUFFER) { printf("GetUserObjectSecurity(desktop) call 1: %u\n", GetLastError()); return 1; } existing_sd = malloc(size); if (existing_sd == NULL) { printf("malloc failed\n"); return 1; } if (!GetUserObjectSecurity(desktop, &amp;sec_info_dacl, existing_sd, size, &amp;dw)) { printf("GetUserObjectSecurity(desktop) call 2: %u\n", GetLastError()); return 1; } if (!GetUserObjectSecurity(desktop, &amp;sec_info_dacl, existing_sd, 4096, &amp;dw)) { printf("GetUserObjectSecurity: %u\n", GetLastError()); return 1; } if (!GetSecurityDescriptorDacl(existing_sd, &amp;dacl_present, &amp;existing_dacl, &amp;dacl_defaulted)) { printf("GetSecurityDescriptorDacl: %u\n", GetLastError()); return 1; } if (!dacl_present) { printf("no DACL present\n"); return 1; } explicit_access.grfAccessMode = SET_ACCESS; explicit_access.grfAccessPermissions = GENERIC_ALL; explicit_access.grfInheritance = NO_INHERITANCE; explicit_access.Trustee.pMultipleTrustee = NULL; explicit_access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; explicit_access.Trustee.TrusteeForm = TRUSTEE_IS_SID; explicit_access.Trustee.TrusteeType = TRUSTEE_IS_USER; explicit_access.Trustee.ptstrName = (LPTSTR)token_user-&gt;User.Sid; dw = SetEntriesInAcl(1, &amp;explicit_access, existing_dacl, &amp;new_dacl); if (dw != ERROR_SUCCESS) { printf("SetEntriesInAcl: %u\n", dw); return 1; } if (!InitializeSecurityDescriptor(&amp;new_sd, SECURITY_DESCRIPTOR_REVISION)) { printf("InitializeSecurityDescriptor: %u\n", GetLastError()); return 1; } if (!SetSecurityDescriptorDacl(&amp;new_sd, TRUE, new_dacl, FALSE)) { printf("SetSecurityDescriptorDacl: %u\n", GetLastError()); return 1; } if (!SetUserObjectSecurity(desktop, &amp;sec_info_dacl, &amp;new_sd)) { printf("SetUserObjectSecurity(window_station): %u\n", GetLastError()); return 1; } free(existing_sd); LocalFree(new_dacl); ZeroMemory(&amp;sinfo, sizeof(sinfo)); sinfo.cb = sizeof(sinfo); if (!CreateProcessWithTokenW(usertoken, LOGON_WITH_PROFILE, L"c:\\windows\\system32\\notepad.exe", command, 0, NULL, NULL, &amp;sinfo, &amp;pinfo)) { printf("CreateProcess: %u\n", GetLastError()); return 1; } return 0; } </code></pre> <p>Note the use of LOGON_WITH_PROFILE. This is not necessary to display a GUI, and it slows down launching the process considerably, so remove it if you don't need it - but if you are an administrator, the most likely reason that you are launching a process as a different administrator is that you need something in that administrator's user profile. (Another scenario might be that you need to use a specific domain account in order to access resources on another machine.)</p> <hr> <p><em>Footnote:</em> </p> <p>Specifically, you need <code>SeTcbPrivilege</code> in order to use <code>GetTokenInformation</code> and <code>TokenLinkedToken</code> to obtain a usable handle to the elevated token that <code>LogonUser</code> generates. Unfortunately, this privilege is usually only available if you are running as local system.</p> <p>If you do not have <code>SeTcbPrivilege</code> you can still obtain a copy of the linked token, but in this case it is an impersonation token at <code>SecurityIdentification</code> level so is of no use when creating a new process. Thanks to RbMm for helping me clarify this.</p>
44,830,663
Docker Container Networking with Docker-in-Docker
<p>I would like to network with a child docker container from a parent docker container, with a docker-in-docker setup.</p> <p>Let's say I'm trying to connect to a simple Apache httpd server. When I run the httpd container on my host machine, everything works fine:</p> <pre><code>asnyder:~$ docker run -d -p 8080:80 httpd:alpine asnyder:~$ curl localhost:8080 &lt;html&gt;&lt;body&gt;&lt;h1&gt;It works!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> <p>But when I do the same from a docker-in-docker setup, I get a <code>Connection refused</code> error:</p> <pre><code>asnyder:~$ docker run -d --name mydind --privileged docker:dind asnyder:~$ docker run -it --link mydind:docker docker:latest sh / # docker run -d -p 8080:80 httpd:alpine / # curl localhost:8080 curl: (7) Failed to connect to localhost port 8080: Connection refused </code></pre> <p>I have tried a couple alterations without luck. Specifying the <code>0.0.0.0</code> interface:</p> <pre><code>asnyder:~$ docker run -d --name mydind --privileged docker:dind asnyder:~$ docker run -it --link mydind:docker docker:latest sh / # docker run -d -p 0.0.0.0:8080:80 httpd:alpine / # curl 0.0.0.0:8080 curl: (7) Failed to connect to 0.0.0.0 port 8080: Connection refused </code></pre> <p>Using the host network:</p> <pre><code>asnyder:~$ docker run -d --name mydind --privileged docker:dind asnyder:~$ docker run -it --link mydind:docker docker:latest sh / # docker run -d --network host httpd:alpine / # curl localhost:80 curl: (7) Failed to connect to localhost port 80: Connection refused </code></pre> <p>Surprisingly, I was unable to find any existing articles on this. Does anyone here have some insight?</p> <p>Thanks!</p>
44,996,703
3
4
null
2017-06-29 16:34:57.97 UTC
8
2019-08-26 12:39:11.7 UTC
2017-08-06 03:12:02.41 UTC
null
5,091,191
null
5,091,191
null
1
31
networking|docker|docker-in-docker
8,884
<p>There are pros and cons for both DinD and bind mounting the Docker socket and there are certainly use cases for both. As an example, check out <a href="https://applatix.com/case-docker-docker-kubernetes-part/" rel="noreferrer">this set of blog posts</a>, which does a good job of explaining one of the use cases. </p> <p>Given your example docker-in-docker setup above, you can access Apache httpd server in one of two ways:</p> <p>1) From inside the <code>docker:dind</code> container, it will be available on <code>localhost:8080</code>.</p> <p>2) From inside the <code>docker:latest</code> container, where you were trying to access it originally, it will be available on whatever hostname is set for the <code>docker:dind</code> container. In this case, you used <code>--name mydind</code>, therefore <code>curl mydind:8080</code> would give you the standard Apache <code>&lt;html&gt;&lt;body&gt;&lt;h1&gt;It works!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;</code>.</p> <p>Hope it makes sense! </p>
45,028,246
Android Studio 3.0 : canary 6 : android.content.res.Resources$NotFoundException inside Launching activity
<p>I update android-studio 3.0 from canary 5 to canary 6 and suddenly My app gives crash on KitKat(API 19) with below stacktrace.</p> <p>The Main2Activity.java:10 line is the first line in my activity onCreate() method. </p> <pre><code>07-11 13:00:39.523 8913-8913/dcpl.com.myapplication E/AndroidRuntime: FATAL EXCEPTION: main Process: dcpl.com.myapplication, PID: 8913 java.lang.RuntimeException: Unable to start activity ComponentInfo{dcpl.com.myapplication/dcpl.com.myapplication.Main2Activity}: android.content.res.Resources$NotFoundException: Resource ID #0x7f070058 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) at dalvik.system.NativeStart.main(Native Method) Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f070058 at android.content.res.Resources.getValue(Resources.java:1173) at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:332) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:197) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:190) at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:711) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:195) at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:81) at android.support.v7.app.AppCompatDelegateImplBase.&lt;init&gt;(AppCompatDelegateImplBase.java:131) at android.support.v7.app.AppCompatDelegateImplV9.&lt;init&gt;(AppCompatDelegateImplV9.java:155) at android.support.v7.app.AppCompatDelegateImplV11.&lt;init&gt;(AppCompatDelegateImplV11.java:31) at android.support.v7.app.AppCompatDelegateImplV14.&lt;init&gt;(AppCompatDelegateImplV14.java:55) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:205) at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185) at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519) at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) at dcpl.com.myapplication.Main2Activity.onCreate(Main2Activity.java:10) at android.app.Activity.performCreate(Activity.java:5411) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)  at android.app.ActivityThread.access$800(ActivityThread.java:139)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:149)  at android.app.ActivityThread.main(ActivityThread.java:5257)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:515)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633)  at dalvik.system.NativeStart.main(Native Method)  </code></pre> <p>How can I solve it?</p>
45,031,035
4
5
null
2017-07-11 07:37:36.113 UTC
7
2017-07-20 09:08:46.38 UTC
2017-07-17 02:48:14.133 UTC
null
1,402,846
null
5,144,038
null
1
29
android|android-4.4-kitkat|android-studio-3.0
3,757
<p>Seems like the issue is related to Aapt 2.</p> <p>Put </p> <p><code>android.enableAapt2=false </code></p> <p>In your <code>gradle.properties</code> file and it fixes the issue for me.</p>
17,193,825
Loading PictureBox Image from resource file with path (Part 3)
<p>I understand that this question has been asked (and answered) before. However, none of the solutions are working for me.</p> <p>Below is a screen capture of all the relevant pieces of the puzzle:</p> <p><a href="http://dinosaur-island.com/PlantPictureBoxScreenCap.jpg" rel="noreferrer">Screen capture http://dinosaur-island.com/PlantPictureBoxScreenCap.jpg</a></p> <p>As you can see there are numerous bitmaps of plants loaded as resources into the Images folder. There is a form with a picturebox named "PlantPicture". There is string, which I know has a good path (because I've checked it in the debugger):</p> <pre><code> PicPath = PicPath+".bmp"; </code></pre> <p><a href="http://dinosaur-island.com/PlantDebugger.jpg" rel="noreferrer">Screen capture http://dinosaur-island.com/PlantDebugger.jpg</a></p> <p>I've tried numerous ways of loading, casting, etc., etc.</p>
17,194,695
5
0
null
2013-06-19 14:23:41.483 UTC
5
2020-03-13 05:30:29.217 UTC
2019-09-09 19:59:31.817 UTC
null
472,495
null
918,489
null
1
28
c#|picturebox
217,053
<p>The path should be something like: <code>"Images\a.bmp"</code>. (Note the lack of a leading slash, and the slashes being <strong>back</strong> slashes.)</p> <p>And then:</p> <pre><code>pictureBox1.Image = Image.FromFile(@"Images\a.bmp"); </code></pre> <p>I just tried it to make sure, and it works. This is besides the other answer that you got - to "copy always".</p>
17,225,088
$http get parameters does not work
<p>Does anyone know why this does not work?</p> <pre><code>$http .get('accept.php', { source: link, category_id: category }) .success(function (data, status) { $scope.info_show = data }); </code></pre> <p>and this does work:</p> <pre><code>$http .get('accept.php?source=' + link + '&amp;category_id=' + category) .success(function (data, status) { $scope.info_show = data }); </code></pre>
17,225,186
2
0
null
2013-06-20 22:45:17.753 UTC
18
2017-05-23 09:58:57.147 UTC
2017-04-24 12:45:00.85 UTC
null
4,927,984
null
1,835,545
null
1
93
javascript|angularjs|http|angular-http
114,018
<p>The 2nd parameter in the <code>get</code> call is a config object. You want something like this:</p> <pre><code>$http .get('accept.php', { params: { source: link, category_id: category } }) .success(function (data,status) { $scope.info_show = data }); </code></pre> <p>See the <strong>Arguments</strong> section of <a href="http://docs.angularjs.org/api/ng.$http" rel="noreferrer">http://docs.angularjs.org/api/ng.$http</a> for more detail</p>
17,202,548
Wavy shape with css
<p>I'm trying to recreate this image with CSS:</p> <p><img src="https://i.stack.imgur.com/Jq0kf.png" alt="wayvy shape"></p> <p>I would not need it to repeat. This is what I started but it just has a straight line:</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-css lang-css prettyprint-override"><code>#wave { position: absolute; height: 70px; width: 600px; background: #e0efe3; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="wave"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
17,202,736
7
6
null
2013-06-19 22:38:16.367 UTC
51
2022-09-02 06:23:58 UTC
2018-07-29 20:12:55.68 UTC
null
8,620,333
null
1,411,004
null
1
107
css|css-shapes
282,790
<p>I'm not sure it's your shape but it's close - you can play with the values:</p> <p><a href="https://jsfiddle.net/7fjSc/9/" rel="noreferrer">https://jsfiddle.net/7fjSc/9/</a></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-css lang-css prettyprint-override"><code>#wave { position: relative; height: 70px; width: 600px; background: #e0efe3; } #wave:before { content: ""; display: block; position: absolute; border-radius: 100% 50%; width: 340px; height: 80px; background-color: white; right: -5px; top: 40px; } #wave:after { content: ""; display: block; position: absolute; border-radius: 100% 50%; width: 300px; height: 70px; background-color: #e0efe3; left: 0; top: 27px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="wave"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
17,385,916
IntelliJ how to zoom in / out
<p>The IntelliJ keymap says:</p> <pre><code>Zoom in: Keypad + = Zoom out Keypad - - </code></pre> <p>But they have no effect. Anyone have this working?</p> <p>New info: Now I have added more key-bindings:</p> <pre><code>Zoom in: Alt-Shift-= Zoom out: Alt-Shift-minus </code></pre> <p>But these still have no effect. Does zoom in/zoom out even work at all in IntelliJ?</p>
65,592,795
12
7
null
2013-06-30 00:20:02.053 UTC
24
2022-08-09 21:05:29.487 UTC
2020-12-22 15:40:31.033 UTC
null
1,056,563
null
1,056,563
null
1
138
intellij-idea|zooming
181,653
<p>Double click <code>Shift</code> to open the quick actions. Then search for &quot;Decrease Font Size&quot; or &quot;Increase Font Size&quot; and hit <code>Enter</code>. To repeat the action you can doubleclick <code>Shift</code> and <code>Enter</code></p> <p>I prefer that way because it works even when you're using not your own Computer without opening settings. Also works without leaving fullscreen, which is useful if you are live coding.</p>
17,139,501
Using $_POST to get select option value from HTML
<p>I use <code>select</code> as below:</p> <pre><code>&lt;select name="taskOption"&gt; &lt;option&gt;First&lt;/option&gt; &lt;option&gt;Second&lt;/option&gt; &lt;option&gt;Third&lt;/option&gt; &lt;/select&gt; </code></pre> <p>How do I get the value from the <code>select</code> option and store it into a variable for future use, in PHP?</p>
17,139,538
8
0
null
2013-06-17 02:04:11.707 UTC
31
2022-09-20 13:17:06.927 UTC
2016-09-24 21:39:13.413 UTC
null
462,627
null
2,473,385
null
1
148
php|html|arrays
827,090
<p>Use this way:</p> <pre><code>$selectOption = $_POST['taskOption']; </code></pre> <p>But it is always better to give values to your <code>&lt;option&gt;</code> tags.</p> <pre><code>&lt;select name="taskOption"&gt; &lt;option value="1"&gt;First&lt;/option&gt; &lt;option value="2"&gt;Second&lt;/option&gt; &lt;option value="3"&gt;Third&lt;/option&gt; &lt;/select&gt; </code></pre>
17,162,308
Node.js Error: Cannot find module express
<p>I wrote my first node.js app, but it can't find express library:</p> <pre><code>C:\ChatServer\Server&gt;node server.js module.js:340 throw err; ^ Error: Cannot find module 'express' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) at require (module.js:380:17) at Object.&lt;anonymous&gt; (C:\ChatServer\Server\server.js:6:9) at Object.&lt;anonymous&gt; (C:\ChatServer\Server\server.js:25:4) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) </code></pre> <p>But express is intalled (with <code>-g</code> key):</p> <pre><code>C:\ChatServer\Server&gt;npm install -g express npm http GET https://registry.npmjs.org/express npm http 304 https://registry.npmjs.org/express npm http GET https://registry.npmjs.org/connect/2.7.11 npm http GET https://registry.npmjs.org/commander/0.6.1 npm http GET https://registry.npmjs.org/range-parser/0.0.4 npm http GET https://registry.npmjs.org/mkdirp/0.3.4 npm http GET https://registry.npmjs.org/cookie/0.1.0 npm http GET https://registry.npmjs.org/buffer-crc32/0.2.1 npm http GET https://registry.npmjs.org/fresh/0.1.0 npm http GET https://registry.npmjs.org/methods/0.0.1 npm http GET https://registry.npmjs.org/send/0.1.0 npm http GET https://registry.npmjs.org/cookie-signature/1.0.1 npm http GET https://registry.npmjs.org/debug npm http 304 https://registry.npmjs.org/mkdirp/0.3.4 npm http 304 https://registry.npmjs.org/range-parser/0.0.4 npm http 304 https://registry.npmjs.org/cookie/0.1.0 npm http 304 https://registry.npmjs.org/connect/2.7.11 npm http 304 https://registry.npmjs.org/commander/0.6.1 npm WARN package.json range-parser@0.0.4 No repository field. npm http 304 https://registry.npmjs.org/buffer-crc32/0.2.1 npm http 304 https://registry.npmjs.org/fresh/0.1.0 npm http 304 https://registry.npmjs.org/methods/0.0.1 npm http 304 https://registry.npmjs.org/send/0.1.0 npm http 304 https://registry.npmjs.org/cookie-signature/1.0.1 npm WARN package.json methods@0.0.1 No repository field. npm WARN package.json methods@0.0.1 No readme data. npm WARN package.json fresh@0.1.0 No repository field. npm WARN package.json send@0.1.0 No repository field. npm WARN package.json cookie-signature@1.0.1 No repository field. npm http 304 https://registry.npmjs.org/debug npm http GET https://registry.npmjs.org/mime/1.2.6 npm http GET https://registry.npmjs.org/qs/0.6.5 npm http GET https://registry.npmjs.org/send/0.1.1 npm http GET https://registry.npmjs.org/formidable/1.0.14 npm http GET https://registry.npmjs.org/cookie/0.0.5 npm http GET https://registry.npmjs.org/bytes/0.2.0 npm http GET https://registry.npmjs.org/pause/0.0.1 npm http 304 https://registry.npmjs.org/mime/1.2.6 npm http 304 https://registry.npmjs.org/bytes/0.2.0 npm WARN package.json bytes@0.2.0 No repository field. npm http 304 https://registry.npmjs.org/pause/0.0.1 npm WARN package.json pause@0.0.1 No repository field. npm http 304 https://registry.npmjs.org/formidable/1.0.14 npm http 304 https://registry.npmjs.org/qs/0.6.5 npm http 304 https://registry.npmjs.org/send/0.1.1 npm http 304 https://registry.npmjs.org/cookie/0.0.5 npm http GET https://registry.npmjs.org/mime npm http 304 https://registry.npmjs.org/mime C:\Users\Dmitry\AppData\Roaming\npm\express -&gt; C:\Users\Dmitry\AppData\Roaming\npm\node_modules\express\bin\express npm WARN package.json policyfile@0.0.4 'repositories' (plural) Not supported. npm WARN package.json Please pick one as the 'repository' field npm WARN package.json assert-plus@0.1.2 No repository field. npm WARN package.json ctype@0.5.2 No repository field. express@3.2.6 C:\Users\Dmitry\AppData\Roaming\npm\node_modules\express ├── methods@0.0.1 ├── fresh@0.1.0 ├── range-parser@0.0.4 ├── cookie-signature@1.0.1 ├── buffer-crc32@0.2.1 ├── cookie@0.1.0 ├── debug@0.7.2 ├── commander@0.6.1 ├── mkdirp@0.3.4 ├── send@0.1.0 (mime@1.2.6) └── connect@2.7.11 (pause@0.0.1, qs@0.6.5, bytes@0.2.0, cookie@0.0.5, formidable@1.0.14, send@0.1.1) </code></pre> <p>Some information:</p> <pre><code>C:\ChatServer\Server&gt;npm --version 1.2.24 C:\ChatServer\Server&gt;node --version v0.10.9 C:\ChatServer\Server&gt;npm --version 1.2.24 C:\ChatServer\Server&gt;npm ls -g installed express npm WARN package.json cookie-signature@1.0.1 No repository field. npm WARN package.json fresh@0.1.0 No repository field. npm WARN package.json methods@0.0.1 No repository field. npm WARN package.json range-parser@0.0.4 No repository field. npm WARN package.json send@0.1.0 No repository field. npm WARN package.json policyfile@0.0.4 'repositories' (plural) Not supported. npm WARN package.json Please pick one as the 'repository' field npm WARN package.json bytes@0.2.0 No repository field. npm WARN package.json pause@0.0.1 No repository field. npm WARN package.json assert-plus@0.1.2 No repository field. npm WARN package.json ctype@0.5.2 No repository field. C:\Users\Dmitry\AppData\Roaming\npm └── express@3.2.6 C:\ChatServer\Server&gt;npm ls installed express C:\ChatServer\Server └── (empty) </code></pre> <p>How can I solve this problem? (<strong>MUST</strong> I install it without <code>-g</code>?)</p>
17,162,384
15
3
null
2013-06-18 06:52:23.453 UTC
33
2021-01-29 01:37:14.483 UTC
null
null
null
null
966,972
null
1
168
node.js|express|npm
393,647
<p>You need to install Express locally into the context of your application (<code>node_modules</code> folder):</p> <pre><code>$ npm install express </code></pre> <p>The reason for this is that applications always look in their local context for any dependencies. The global installation is only for setting up system-wide available binaries, such as unit test runners or bootstrappers or things like that.</p> <p>With Express, when you install it globally, you get an <code>express</code> binary that can bootstrap an application for you. For more information, type</p> <pre><code>$ express --help </code></pre> <p>So, to answer your final question: <em>YES</em>, you need to install it without <code>-g</code>.</p>
31,868,639
How to ping an IP Address in golang
<p>How can you ping an IP address from a golang application? The ultimate goal is to check if a server is online.</p> <p>Does go have a way in the standard library to implement a network ping?</p>
35,194,144
6
9
null
2015-08-07 02:09:18.937 UTC
3
2020-06-14 06:04:50.603 UTC
2017-12-16 07:07:35.703 UTC
null
1,033,581
null
4,798,893
null
1
25
go
43,121
<p>As @desaipath mentions, there is no way to do this in the standard library. However, you do not need to write the code for yourself - it has already been done:</p> <blockquote> <p><a href="https://github.com/tatsushid/go-fastping" rel="noreferrer">https://github.com/tatsushid/go-fastping</a></p> </blockquote> <p><em>Note, sending ICMP packets requires root privileges</em> </p>
5,256,516
MATLAB: print a figure to pdf as the figure shown in the MATLAB
<p>I am trying to export (save as, print) a figure into .pdf format. However, no matter how I configure the setting, there are large margins around the figure.</p> <p>When I export the figure into .eps format, there is no such problem --- i.e. the figure just looks like it is displayed in the MATLAB.</p> <p>How could I export the figure into .pdf format, which looks the same as it is shown in the MATLAB?</p>
5,256,555
3
2
null
2011-03-10 07:05:43.47 UTC
4
2019-06-05 08:48:36.957 UTC
null
null
null
null
468,841
null
1
7
matlab|figure|export-to-pdf
40,535
<p>You can try the following:</p> <p>1) After you plot the figure in <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a>, go to 'File->Export Setup', and input the size of the output you want. For example, Width: 6 inches, Height: 5 inches. Then click 'Apply to Figure' button.</p> <p>2) Don't close the 'Export Setup' window. Go to 'File->Print Preview->Paper', input the same size in the Width and Height options.</p> <p>3) Don't close the 'Print Preview' window. Go back to the 'Export Setup' window, and click 'Export', then select pdf format and save it.</p> <p>4) Check the output PDF file, you'll see it is perfect.</p> <p>I found the solution in blog post <em><a href="http://jinghaoxu.blogspot.com/2007/04/export-figure-to-pdf-in-matlab.html" rel="nofollow">Export figure to PDF in MATLAB</a></em>.</p>
5,282,099
Signal handling in pthreads
<p>I have created a pthread, and installed a signal handler inside that, same way as we do in <code>main( )</code> function. The thread's signal handler is a separate function. Surprisingly, it is not working, that is the thread's signal handler is not able to catch signals.</p> <p>Here is the code:</p> <pre><code>#include &lt;pthread.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;stdio.h&gt; #include &lt;signal.h&gt; #include &lt;string.h&gt; typedef struct data { char name[10]; int age; }data; void sig_func(int sig) { printf(&quot;Caught signal: %d\n&quot;,sig); signal(SIGSEGV,sig_func); } void func(data *p) { printf(&quot;This is from thread function\n&quot;); signal(SIGSEGV,sig_func); // Register signal handler inside thread strcpy(p-&gt;name,&quot;Mr. Linux&quot;); p-&gt;age=30; sleep(2); // Sleep to catch the signal } int main() { pthread_t tid; pthread_attr_t attr; data *ptr; pthread_attr_init(&amp;attr); pthread_create(&amp;tid,&amp;attr,(void*)func,ptr); pthread_kill(tid,SIGSEGV); pthread_join(tid,NULL); printf(&quot;Name:%s\n&quot;,ptr-&gt;name); printf(&quot;Age:%d\n&quot;,ptr-&gt;age); } </code></pre> <p>Output:</p> <blockquote> <p>Segmentation fault (which means the signal is not caught by handler)</p> </blockquote>
5,282,181
3
3
null
2011-03-12 11:03:21.48 UTC
16
2021-12-07 11:07:07.743 UTC
2021-12-07 11:06:12.537 UTC
null
6,594,576
null
575,281
null
1
28
c|pthreads|signals
94,217
<p>There are several problems with your code:</p> <ul> <li><code>ptr</code> is not initialised, so all the <code>ptr-&gt;</code> parts will crash the program</li> <li>you are calling <code>pthread_kill()</code> immediately, very likely before the signal handler has been installed, and in a thread (which has unspecified behaviour)</li> <li>you call <code>printf()</code> from a signal handler, which is not guaranteed to work (see <code>man 7 signal</code> for a list of safe functions)</li> </ul> <p>This will work a lot better, though you'd still need proper thread synchronisation, and as stated elsewhere, you should use <code>sigaction()</code>:</p> <pre><code>#include &lt;pthread.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;stdio.h&gt; #include &lt;signal.h&gt; #include &lt;string.h&gt; typedef struct data { char name[10]; int age; }data; void sig_func(int sig) { write(1, &quot;Caught signal 11\n&quot;, 17); signal(SIGSEGV,sig_func); } void func(data *p) { fprintf(stderr, &quot;This is from thread function\n&quot;); strcpy(p-&gt;name,&quot;Mr. Linux&quot;); p-&gt;age=30; sleep(2); // Sleep to catch the signal } int main() { pthread_t tid; pthread_attr_t attr; data d; data *ptr = &amp;d; signal(SIGSEGV,sig_func); // Register signal handler before going multithread pthread_attr_init(&amp;attr); pthread_create(&amp;tid,&amp;attr,(void*)func,ptr); sleep(1); // Leave time for initialisation pthread_kill(tid,SIGSEGV); pthread_join(tid,NULL); fprintf(stderr, &quot;Name:%s\n&quot;,ptr-&gt;name); fprintf(stderr, &quot;Age:%d\n&quot;,ptr-&gt;age); } </code></pre> <p><strong>Edit</strong>: install sighandler in main thread</p>
5,042,379
In VB6 what is the difference between Property Set and Property Let?
<p>I have just created several <code>Property Set</code> methods, and they didn't compile. When I changed them to <code>Property Let</code>, everything was fine.</p> <p>I have since studied the documentation to find the difference between <code>Property Set</code> and <code>Property Let</code>, but must admit to being none the wiser. Is there any difference, and if so could someone offer a pointer to a proper explanation of it?</p>
5,042,718
3
1
null
2011-02-18 14:21:10.373 UTC
7
2016-10-24 14:36:01.977 UTC
2015-11-11 19:11:47.483 UTC
null
4,865,599
null
326,900
null
1
40
oop|properties|vb6|setter|letter
54,646
<p><code>Property Set</code> is for objects (e.g., class instances) </p> <p><code>Property Let</code> is for "normal" datatypes (e.g., string, boolean, long, etc.)</p>
5,201,965
Objective-C (cocoa) equivalent to python's endswith/beginswith
<p>Python has <code>string.startswith()</code> and <code>string.endswith()</code> functions which are pretty useful. What NSString methods can I use to have the same function?</p>
5,202,006
3
0
null
2011-03-05 05:44:01.957 UTC
null
2011-12-05 19:04:42.473 UTC
2011-03-05 06:33:21.637 UTC
null
308,903
null
260,127
null
1
46
python|objective-c|cocoa
7,820
<p>Use <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/hasPrefix%3a"><code>-hasPrefix:</code></a> and <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/hasSuffix%3a"><code>-hasSuffix:</code></a>:</p> <pre><code>NSString *s = @"foobar"; NSLog(@"%d %d\n", [s hasPrefix:@"foo"], [s hasSuffix:@"bar"]); // Output: "1 1" </code></pre>
5,027,808
How to avoid DIVIDE BY ZERO error in an SQL query
<pre><code>SELECT YEAR, period, round((1- sum(rej_qty) / sum(recd_qty))*100, 0) FROM TAB_A WHERE sid = '200' AND sdid IN ('4750') AND ( ( YEAR ='2011' AND period IN('01_JAN') ) OR ( YEAR = '2010' AND period IN('02_FEB','03_MAR','04_APR','05_MAY','06_JUN','07_JUL','08_AUG','09_SEP','10_OCT','11_NOV','12_DEC') ) ) group by year, period </code></pre> <p>For a particular month, recd_qty is ZERO because of which I am getting DIVIDE BY ZERO error.</p> <p>Is there any way to avoid DIVIDE BY ZERO error?</p> <p>I there any way where in that particular month is ignored?</p>
5,027,850
4
0
null
2011-02-17 10:38:55.767 UTC
7
2019-10-17 14:37:26.7 UTC
2012-10-01 08:16:21.307 UTC
null
309,086
null
157,705
null
1
10
sql|oracle9i|divide-by-zero
64,075
<p>If you want to ignore such records you can use a subquery</p> <pre><code>SELECT YEAR, period, round((1- rej_sum / recd_sum)*100, 0) FROM ( SELECT YEAR, sum(rej_qty) rej_sum, sum(recd_qty) recd_sum FROM TAB_A WHERE sid = '200' AND sdid IN ('4750') AND ( ( YEAR ='2011' AND period IN('01_JAN') ) OR ( YEAR = '2010' AND period IN ('02_FEB','03_MAR','04_APR','05_MAY','06_JUN','07_JUL','08_AUG','09_SEP','10_OCT','11_NOV','12_DEC') ) ) group by year, period ) WHERE recd_sum &lt;&gt; 0; </code></pre> <p>If you want to keep them and handle the division by zero issue, you can use decode or case</p> <pre><code>SELECT YEAR, period, DECODE(recd_qty, 0, NULL, round((1- sum(rej_qty) / sum(recd_qty))*100, 0)) </code></pre>
25,741,027
Default username and password for Oracle database
<p>I forgot to feed sys, system and hr password while Oracle DB installation and hit OK but now for SQ*Plus it needs those credentials for login in command prompt.How to get default user name and password?</p>
25,743,716
2
2
null
2014-09-09 09:24:12.897 UTC
3
2020-05-01 18:46:35.507 UTC
null
null
null
null
2,596,551
null
1
6
database|oracle
64,104
<p>You can simply login as :</p> <pre><code>sqlplus / as sysdba </code></pre> <p>Then give password to the respective users :</p> <pre><code>ALTER USER &lt;username&gt; IDENTIFIED BY &lt;password&gt;; </code></pre> <p>You can do that for all the three users.</p> <p>I hope you are not on 12c. Else, you need to mention which CONTAINER are you working with. For example, if you are working on pluggable database, let's say PDBORCL, you need to do following steps :</p> <ol> <li><code>connect / as sysdba;</code></li> <li><p>alter session to set the container of which the respective users are a part of.</p> <p><code>alter session set container=PDBORCL;</code></p></li> <li><p>Then follow the same steps to change the passwords for the users.</p></li> </ol>
25,616,382
how to set cornerRadius for only bottom-left,bottom-right and top-left corner of a UIView?
<p>Is there a way to set cornerRadius for only bottom-left,bottom-right and top-left corner of a UIView?</p> <p>I tried the following, but it ended up making the view disappear. Is there anything wrong with the code below?</p> <pre><code> UIBezierPath *maskPath; maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20.0, 20.0)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.path = maskPath.CGPath; view.layer.mask = maskLayer; </code></pre>
25,616,833
10
3
null
2014-09-02 05:22:43.66 UTC
35
2018-05-29 08:43:55.113 UTC
2014-09-02 06:31:27.087 UTC
null
3,830,876
null
1,595,141
null
1
37
ios|objective-c|iphone|xcode|ipad
47,242
<p>You can do it like this:</p> <pre><code>UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.viewOutlet.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(10.0, 10.0)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.frame = self.view.bounds; maskLayer.path = maskPath.CGPath; self.viewOutlet.layer.mask = maskLayer; </code></pre> <p><img src="https://i.stack.imgur.com/jWpd7.png" alt="enter image description here"></p> <p><strong>Update:</strong><br/> If You need border just create another <code>CAShapeLayer</code> and add it to view's layer as sublayer. Like this (place this code below upper code):</p> <pre><code>CAShapeLayer *borderLayer = [[CAShapeLayer alloc] init]; borderLayer.frame = self.view.bounds; borderLayer.path = maskPath.CGPath; borderLayer.lineWidth = 4.0f; borderLayer.strokeColor = [UIColor blackColor].CGColor; borderLayer.fillColor = [UIColor clearColor].CGColor; [self.viewOutlet.layer addSublayer:borderLayer]; </code></pre> <p><img src="https://i.stack.imgur.com/hbsf0.png" alt="enter image description here"></p> <p>In swift 3.0 like this:</p> <pre><code>let maskPath = UIBezierPath.init(roundedRect: self.viewOutlet.bounds, byRoundingCorners:[.topLeft, .bottomLeft], cornerRadii: CGSize.init(width: 10.0, height: 10.0)) let maskLayer = CAShapeLayer() maskLayer.frame = self.viewOutlet.bounds maskLayer.path = maskPath.cgPath self.viewOutlet.layer.mask = maskLayer </code></pre>
9,410,401
Adding Custom header to the excel file
<p>Is it possible to add a custom header to the Excel while exporting a <code>DataSet</code> to Excel in ASP.NET? I have one requirement like this. I can export the <code>DataSet</code> to the Excel successfully. But I can't add the custom header. Please help me if anybody have the solution. Thanks in advance.</p>
9,653,194
3
4
null
2012-02-23 09:38:19.19 UTC
2
2012-09-13 05:07:03.963 UTC
2012-02-23 09:43:02.317 UTC
null
26,396
null
124,875
null
1
6
c#|asp.net|header|export-to-excel
51,554
<p>IF you are using <code>Response.Write</code> to Export the Excel. You can use the following code with minimal effort and the <code>Header</code> can be customized as you want, just like HTML headers.</p> <pre><code>Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;"); StringWriter stringWrite = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); dgrExport.DataSource = dtExport; dgrExport.DataBind(); dgrExport.RenderControl(htmlWrite); string headerTable = @"&lt;Table&gt;&lt;tr&gt;&lt;td&gt;Report Header&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;img src=""D:\\Folder\\Report Header.jpg"" \&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/Table&gt;"; Response.Write(headerTable); Response.Write(stringWrite.ToString()); Response.End(); </code></pre> <p>Mac, Are you looking for the same?</p>
9,522,631
How to put a line comment for a multi-line command
<p>I know how to write a multi-line command in a Bash script, but how can I add a comment for each line in a multiline command?</p> <pre><code>CommandName InputFiles \ # This is the comment for the 1st line --option1 arg1 \ # This is the comment for the 2nd line --option2 arg2 # This is the comment for the 3nd line </code></pre> <p>But unfortunately, the comment after continuation character <code>\</code> will break the command.</p>
9,525,753
4
4
null
2012-03-01 19:27:09.25 UTC
97
2021-02-17 17:11:58.897 UTC
2018-04-01 17:14:21.547 UTC
null
42,223
null
301,336
null
1
440
bash|shell|comments
88,099
<p>I'm afraid that, in general, you can't do what you're asking for. The best you can do is a comment on the lines before the command, or one single comment at the end of the command line, or a comment after the command.</p> <p>You can't manage to intersperse comments inside a command this way. The <code>\</code>s express an intent to merge lines, so for all intents and purposes you're trying to intersperse comments in a single line, which doesn't work anyway because a <code>\</code> has to be at the end of the line to have that effect.</p>
18,330,917
How to alert inline of button
<p>I know already how to alert by use javascript or Jquery. But just onclick button I apply javascript external or internal. What I need is we alert inline of button Example: </p> <pre><code>&lt;button name="my_btn" id="my_btn" onClick="alert('Hello I am alert')"&gt;Alert&lt;/button&gt; </code></pre> <p>If it is possible please tell me. I am waiting for all of you </p>
18,330,969
4
1
null
2013-08-20 08:57:33.02 UTC
0
2018-02-12 18:10:58.643 UTC
2013-08-20 09:04:46.343 UTC
null
2,572,353
null
2,605,515
null
1
7
javascript
40,624
<p>I never really understand why someone wants to do it this way, but here is an inline alert on a button.</p> <pre><code>&lt;button type="button" onclick="alert('Hello World')"&gt;Show Alert&lt;/button&gt; </code></pre> <p><a href="http://jsfiddle.net/pfQPT/" rel="noreferrer">Here is the fiddle</a></p> <p><a href="https://stackoverflow.com/questions/10607847/how-does-inline-javascript-in-html-work">By the way, I believe this question has been answered</a></p> <p>Did I answer your question?</p>
18,413,014
Run a JAR file from the command line and specify classpath
<p>I've compiled a <a href="http://en.wikipedia.org/wiki/JAR_%28file_format%29" rel="noreferrer">JAR</a> file and specified the Main-Class in the manifest (I used the Eclipse <em>Export</em> function). My dependencies are all in a directory labeled <code>lib</code>. I can't seem to get a straight answer on how to execute my JAR file while specifying it should use the <code>lib/*</code> as the classpath.</p> <p>I've tried:</p> <pre><code>]$ java -jar -cp .:lib/* MyJar.jar ]$ java -cp .:lib/* -jar MyJar.jar ]$ java -cp .:lib/* com.somepackage.subpackage.Main </code></pre> <p>etc...</p> <p>Each gives an error saying:</p> <blockquote> <p><code>Error: Could not find or load main class ....</code></p> </blockquote> <p>or gives the <code>NoClassDefFoundError</code> indicating the libraries are not being found.</p> <p>I even tried remaking the JAR file and included the <code>lib</code> directory and contents, but still no dice...</p> <p>How can I execute a JAR file from the command line and specify the classpath to use?</p>
18,413,058
5
1
null
2013-08-23 22:50:19.597 UTC
32
2019-12-17 21:20:55.363 UTC
2016-04-04 18:11:49.383 UTC
null
63,550
null
2,161,954
null
1
143
java|shell|command-line|classpath
274,827
<p>When you specify <code>-jar</code> then the <code>-cp</code> parameter will be ignored. </p> <p>From <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/java.html#jar">the documentation</a>:</p> <blockquote> <p><i>When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored. </i></p> </blockquote> <p>You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)</p> <p>You have two options:</p> <ol> <li>include all jar files from the <code>lib</code> directory into the manifest (you can use relative paths there)</li> <li>Specify everything (<em>including</em> your jar) on the commandline using <code>-cp</code>: <br/> <code>java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main</code></li> </ol>
20,257,266
How to access localhost from a Genymotion android emulator?
<p>I can not figure out how to access localhost from a Genymotion android emulator. By the way, Im using MAMP.</p>
20,257,547
10
2
null
2013-11-28 03:36:27.763 UTC
20
2022-08-17 12:57:42.323 UTC
null
null
null
null
2,940,948
null
1
73
android|emulation|mamp|genymotion
83,191
<p><Strong>Update</strong></p> <p>After genymotion update to 2.2 you can use <code>10.0.3.2</code>, <a href="https://stackoverflow.com/a/18940022/1729802">ref</a></p> <p><Strong>Another approach</Strong></p> <p>To access your localhost through Genymotion is using your PC IP address. to get your IP address go to:</p> <pre><code>start -&gt; cmd -&gt; ipconfig </code></pre> <p>then search for IPv4, copy the IP and paste it in your URL. It should looks like the following:</p> <pre><code>String YourURL = "http://192.168.0.106:8888/your_script_location.php"; </code></pre> <p>Hope this works too for you, give me a feedback.</p> <p><Strong>P.S: if it didn't work, turn off the firewall and any anti-virus application you have in your PC.</strong></p>
15,204,470
Pyqt how to get a widget's dimensions
<p>I am currently developing an application in which i cannot use modal windows (due to some application constraints). However, in some cases i would like to simulate a popup window. To do so i dynamically create a widget that has the centralwidget as parent and i use the move() method to place it where i want. I would like to know if there is a way to get a widget's dimensions at a given time (considering the mainWindow can be resized at any time) so that i will be able to center the placeholder popup (a simple widget) at the middle of the centralwidget.</p> <p>Thank you</p>
15,205,853
3
1
null
2013-03-04 14:59:45.73 UTC
3
2018-10-04 12:07:30.337 UTC
null
null
null
null
1,504,016
null
1
15
python|widget|size|pyqt
54,747
<p>You can use <a href="http://qt-project.org/doc/qt-4.8/qwidget.html#frameGeometry-prop" rel="nofollow"><code>frameGeometry</code></a> or <a href="http://qt-project.org/doc/qt-4.8/qwidget.html#geometry-prop" rel="nofollow"><code>geometry</code></a> depending on <a href="http://qt-project.org/doc/qt-4.8/application-windows.html#window-geometry" rel="nofollow">your needs</a>.</p>
15,214,179
How to read the classifier confusion matrix in WEKA
<p>Sorry, I am new to WEKA and just learning.</p> <p>In my decision tree (J48) classifier output, there is a confusion Matrix:</p> <pre><code>a b &lt;----- classified as 130 8 a = functional 15 150 b = non-functional </code></pre> <ul> <li>How do I read this matrix? What's the difference between a &amp; b?</li> <li>Also, can anyone explain to me what domain values are?</li> </ul>
26,616,662
2
1
null
2013-03-05 01:21:40.093 UTC
7
2019-01-18 19:57:06.547 UTC
2013-12-12 17:01:59 UTC
null
1,693,859
null
1,267,180
null
1
17
classification|weka|decision-tree
46,151
<p>I'd put it this way:</p> <p>The confusion matrix is Weka reporting on how good this J48 model is in terms of what it gets right, and what it gets wrong.</p> <p>In your data, the target variable was either "functional" or "non-functional;" the right side of the matrix tells you that column "a" is functional, and "b" is non-functional.</p> <p>The columns tell you how your model classified your samples - it's what the model predicted:</p> <ul> <li>The first column contains all the samples which your model thinks are "a" - 145 of them, total</li> <li>The second column contains all the samples which your model thinks are "b" - 158 of them</li> </ul> <p>The rows, on the other hand, represent reality:</p> <ul> <li>The first row contains all the samples which really are "a" - 138 of them, total</li> <li>The second row contains all the samples which really are "b" - 165 of them</li> </ul> <p>Knowing the columns and rows, you can dig into the details:</p> <ul> <li>Top left, 130, are things your model thinks are "a" which really are "a" &lt;- these were correct </li> <li>Bottom left, 15, are things your model thinks are "a" but which are really "b" &lt;- one kind of error </li> <li>Top right, 8, are things your model thinks are "b" but which really are "a" &lt;- another kind of error </li> <li>Bottom right, 150 are things your model thinks are "b" which really are "b"</li> </ul> <p>So top-left and bottom-right of the matrix are showing things your model gets right.</p> <p>Bottom-left and top-right of the matrix are are showing where your model is confused.</p>
15,024,383
Why are dates in match aggregate query being ignored?
<p>I'm trying to run an aggregation statement in my mongo db. I have a document whose structure is (at least) as follows:</p> <pre><code>{ "_id": ObjectId, "date": ISODate, "keywordGroupId": NumberLong, "ranking": NumberLong, } </code></pre> <p>I would like to run an aggregation statement that aggregates the 'ranking' field for a given 'keywordGroupId' and a given 'date' interval.</p> <p>I have been trying with the following aggregate command:</p> <pre><code>{ aggregate : "KeywordHistory", pipeline : [ { $match: { keywordGroupId: 75 , "$date": {$gte: ISODate("2013-01-01T00:00:00.0Z"), $lt: ISODate("2013-02-01T00:00:00.0Z")}} }, { $group: { _id: { null }, count: { $sum: "$ranking" } } } ] } </code></pre> <p>This command executes without errors and returns a result. If I try to change the value for the 'keywordGroupId' field, the command returns a different value, so I assume that the $match statement works for that field (NumberLong). Though, if I change the 'date' range and I specify a time interval for which I don't have any data in the database, it still returns a result (I would actually expect an empty result set). So I have to assume that the $match statement is ignoring the date interval specified. </p> <p>Can anyone help me with this point?</p>
15,025,828
3
0
null
2013-02-22 12:35:54.44 UTC
4
2022-08-19 09:25:10.893 UTC
2022-08-19 09:25:10.893 UTC
null
542,251
null
2,099,122
null
1
24
mongodb|aggregation-framework
86,063
<p>Remove the <code>$</code> prefix on the <code>$date</code> field of your <code>$match</code>:</p> <pre><code>{ $match: { keywordGroupId: 75, date: {$gte: ISODate("2013-01-01T00:00:00.0Z"), $lt: ISODate("2013-02-01T00:00:00.0Z")} }}, </code></pre> <p>You only use the <code>$</code> prefix when the field name is used in a value, not as a key.</p>
43,811,434
Error: <path> attribute d: Expected number, "MNaN,NaNLNaN,NaN"
<p>I'm tring to create a multi-line chart using D3.js v4. I'm using this example: <a href="https://bl.ocks.org/mbostock/3884955" rel="noreferrer">https://bl.ocks.org/mbostock/3884955</a>.</p> <p>Sample csv Data:</p> <pre><code>storageSystem,poolId,availableVolumeCapacity,date system01,0,18031398,20170413 system01,1,15626268,20170413 system01,2,61256286,20170413 system01,3,119514990,20170413 system02,0,15046668,20170413 system02,1,12486558,20170413 system02,2,12303396,20170413 system03,0,35171335,20170413 system03,1,17263722,20170413 system01,0,18031387,20170414 system01,1,15626257,20170414 system01,2,61256275,20170414 system01,3,119514989,20170414 system02,0,15046657,20170414 system02,1,12486547,20170414 system02,2,12303385,20170414 system03,0,35171324,20170414 system03,1,17263711,20170414 </code></pre> <p>Data Object:</p> <pre><code>0: Object color: "#8c564b" key: "system03" values: Array(2) 0: Object key: "0" values: Array(23) 0: Object availableVolumeCapacity: 35171335 date: Thu Apr 13 2017 00:00:00 GMT+0000 (Coordinated Universal Time) poolId: "0" storageSystem: "system03" 1: Object key: "1" values: Array(23) 0: Object availableVolumeCapacity: 17263722 date: Thu Apr 13 2017 00:00:00 GMT+0000 (Coordinated Universal Time) poolId:"1" storageSystem: "system03" </code></pre> <p>D3.js Code:</p> <pre><code>var svg = d3.select("svg") m = {top: 20, right: 20, bottom: 50, left: 20}, w = svg.attr("width") - m.left - m.right, h = svg.attr("height") - m.top - m.bottom, g = svg.append("g").attr("transform", "translate(" + m.left + "," + m.top + ")"); var parseTime = d3.timeParse("%Y%m%d"); var x = d3.scaleTime().range([0, w]), y = d3.scaleLinear().range([h, 0]), z = d3.scaleOrdinal(d3.schemeCategory10); var line = d3.line() .curve(d3.curveBasis) .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.availableVolumeCapacity); }); d3.csv("ssystem.csv", function(error, data) { if (error) throw error; data.forEach(function(d) { d.date = parseTime(d.date); d.availableVolumeCapacity = +d.availableVolumeCapacity; }); x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.availableVolumeCapacity; })]); var dataNest = d3.nest() .key(function(d) {return d.storageSystem; }) .key(function(d) {return d.poolId; }) .entries(data); console.log(dataNest) legendSpace = w/dataNest.length; dataNest.forEach(function(d,i) { svg.append("path") .attr("class", "line") .style("stroke", function() { return d.color = z(d.key); }) .attr("id", 'tag'+d.key.replace(/\s+/g, '')) .attr("d", line(d.values)); svg.append("text") .attr("x", (legendSpace/2)+i*legendSpace) .attr("y", h + (m.bottom/2)+ 5) .attr("class", "legend") .style("fill", function() { return d.color = z(d.key); }) .on("click", function(){ // Determine if current line is visible var active = d.active ? false : true, newOpacity = active ? 0 : 1; // Hide or show the elements based on the ID d3.select("#tag"+d.key.replace(/\s+/g, '')) .transition().duration(100) .style("opacity", newOpacity); // Update whether or not the elements are active d.active = active; }) .text(d.key); }); svg.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + h + ")") .call(d3.axisBottom(x)); svg.append("g") .attr("class", "axis axis--y") .call(d3.axisLeft(y)) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("fill", "#000") .text("Capacity (MB)"); }); </code></pre> <p>I'm seeing the following error 4 times from the console:</p> <pre><code>Error: &lt;path&gt; attribute d: Expected number, "MNaN,NaNLNaN,NaN". (anonymous) @ d3.v4.min.js:205 ul @ d3.v4.min.js:3768 al @ d3.v4.min.js:3775 (anonymous) @ multi-line.js:51 (anonymous) @ multi-line.js:45 (anonymous) @ d3.v4.min.js:5857 call @ d3.v4.min.js:3622 e @ d3.v4.min.js:5840 </code></pre> <p>Any help is much appreciated.</p>
43,814,401
2
4
null
2017-05-05 18:17:07.623 UTC
1
2017-05-05 22:06:34.803 UTC
2017-05-05 18:46:44.74 UTC
null
7,259,469
null
7,259,469
null
1
18
javascript|d3.js
47,852
<p>The root of your problem is that the value <code>d</code> in your anonymous function passed to <code>dataNest.forEach</code> still contains one level of nesting but you are using it as if it doesn't have any nesting. Your code fails because it is looking for <code>date</code> and <code>availableVolumeCapacity</code> properties on an object that only has <code>key</code> and <code>values</code> properties.</p> <p>There are ultimately two approaches to fix this:</p> <ol> <li><p>Use a single key function which combines both the storage system and pool ID. This reduces the nesting to only one level:</p> <pre><code>var dataNest = d3.nest() .key(function(d) { return d.storageSystem + " " + d.poolId; }) .entries(data); </code></pre></li> <li><p>Use two nested calls to <code>forEach</code>:</p> <pre><code>dataNest.forEach(function(d2,i2) { d2.forEach(function (d,i) { svg.append("path") // .... rest of inner function omitted }); }); </code></pre> <p>You will need to go through all uses of <code>d</code> (in particular <code>d.key</code>) and <code>i</code> within the inner function (whose body I omitted for brevity) to see whether you need to incorporate <code>d2</code> and <code>i2</code>. For example, perhaps you want to use <code>d2.key + " " + d.key</code> instead of <code>d.key</code>.</p></li> </ol>
7,890,685
Referencing "this" inside setInterval/setTimeout within object prototype methods
<p>Normally I'd assign an alternative "self" reference when referring to "this" within setInterval. Is it possible to accomplish something similar within the context of a prototype method? The following code errors.</p> <pre><code>function Foo() {} Foo.prototype = { bar: function () { this.baz(); }, baz: function () { this.draw(); requestAnimFrame(this.baz); } }; </code></pre>
7,890,978
2
1
null
2011-10-25 14:15:40.96 UTC
19
2017-12-01 15:39:57.76 UTC
null
null
null
null
477,610
null
1
45
javascript|scope|lexical-scope
35,232
<p>Unlike in a language like Python, a Javascript method forgets it is a method after you extract it and pass it somewhere else. You can either</p> <h2>Wrap the method call inside an anonymous function</h2> <p>This way, accessing the <code>baz</code> property and calling it happen at the same time, which is necessary for the <code>this</code> to be set correctly inside the method call.</p> <p>You will need to save the <code>this</code> from the outer function in a helper variable, since the inner function will refer to a different <code>this</code> object.</p> <pre><code>var that = this; setInterval(function(){ return that.baz(); }, 1000); </code></pre> <h2>Wrap the method call inside a fat arrow function</h2> <p>In Javascript implementations that implement the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">arrow functions</a> feature, it is possible to write the above solution in a more concise manner by using the fat arrow syntax:</p> <pre><code>setInterval( () =&gt; this.baz(), 1000 ); </code></pre> <p>Fat arrow anonymous functions preserve the <code>this</code> from the surrounding function so there is no need to use the <code>var that = this</code> trick. To see if you can use this feature, consult a compatibility table like <a href="https://kangax.github.io/compat-table/es6/#test-arrow_functions" rel="noreferrer">this one</a>.</p> <h2>Use a binding function</h2> <p>A final alternative is to use a function such as Function.prototype.bind or an equivalent from your favorite Javascript library.</p> <pre><code>setInterval( this.baz.bind(this), 1000 ); //dojo toolkit example: setInterval( dojo.hitch(this, 'baz'), 100); </code></pre>
23,531,608
How do I save streaming tweets in json via tweepy?
<p>I've been learning Python for a couple of months through online courses and would like to further my learning through a real world mini project. </p> <p>For this project, I would like to collect tweets from the twitter streaming API and store them in json format (though you can choose to just save the key information like status.text, status.id, I've been advised that the best way to do this is to save all the data and do the processing after). However, with the addition of the on_data() the code ceases to work. Would someone be able to to assist please? I'm also open to suggestions on the best way to store/process tweets! My end goal is to be able to track tweets based on demographic variables (e.g., country, user profile age, etc) and the sentiment of particular brands (e.g., Apple, HTC, Samsung). </p> <p>In addition, I would also like to try filtering tweets by location AND keywords. I've adapted the code from <a href="https://stackoverflow.com/questions/22889122/how-to-add-a-location-filter-to-tweepy-module?rq=1">How to add a location filter to tweepy module</a> separately. However, while it works when there are a few keywords, it stops when the number of keywords grows. I presume my code is inefficient. Is there a better way of doing it?</p> <pre><code>### code to save tweets in json### import sys import tweepy import json consumer_key=" " consumer_secret=" " access_key = " " access_secret = " " auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) file = open('today.txt', 'a') class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): print status.text def on_data(self, data): json_data = json.loads(data) file.write(str(json_data)) def on_error(self, status_code): print &gt;&gt; sys.stderr, 'Encountered error with status code:', status_code return True # Don't kill the stream def on_timeout(self): print &gt;&gt; sys.stderr, 'Timeout...' return True # Don't kill the stream sapi = tweepy.streaming.Stream(auth, CustomStreamListener()) sapi.filter(track=['twitter']) </code></pre>
23,547,623
3
6
null
2014-05-08 02:15:37.49 UTC
11
2014-10-31 12:12:40.21 UTC
2017-05-23 11:45:28.967 UTC
null
-1
null
3,611,239
null
1
7
python|json|tweepy
21,187
<p>In rereading your original question, I realize that you ask a <em>lot</em> of smaller questions. I'll try to answer most of them here but some may merit actually asking a separate question on SO.</p> <ul> <li><strong>Why does it break with the addition of</strong> <code>on_data</code> <strong>?</strong></li> </ul> <p>Without seeing the actual error, it's hard to say. It actually didn't work for me until I regenerated my consumer/acess keys, I'd try that.</p> <p>There are a few things I might do differently than your answer.</p> <p><code>tweets</code> is a global list. This means that if you have multiple <code>StreamListeners</code> (i.e. in multiple threads), <em>every</em> tweet collected by <em>any</em> stream listener will be added to this list. This is because lists in Python refer to locations in memory--if that's confusing, here's a basic example of what I mean:</p> <pre><code>&gt;&gt;&gt; bar = [] &gt;&gt;&gt; foo = bar &gt;&gt;&gt; foo.append(7) &gt;&gt;&gt; print bar [7] </code></pre> <p>Notice that even though you thought appended 7 to <code>foo</code>, <code>foo</code> and <code>bar</code> actually refer to the same thing (and therefore changing one changes both).</p> <p>If you meant to do this, it's a pretty great solution. However, if your intention was to segregate tweets from different listeners, it could be a huge headache. I personally would construct my class like this:</p> <pre><code>class CustomStreamListener(tweepy.StreamListener): def __init__(self, api): self.api = api super(tweepy.StreamListener, self).__init__() self.list_of_tweets = [] </code></pre> <p>This changes the tweets list to be only in the scope of your class. Also, I think it's appropriate to change the property name from <code>self.save_file</code> to <code>self.list_of_tweets</code> because you also name the <em>file</em> that you're appending the tweets to <code>save_file</code>. Although this will not strictly cause an error, it's confusing to human me that <code>self.save_file</code> is a list and <code>save_file</code> is a file. It helps future you and anyone else that reads your code figure out what the heck everything does/is. <a href="https://stackoverflow.com/questions/203618/how-to-name-variables">More on variable naming.</a></p> <p>In my comment, I mentioned that you shouldn't use <code>file</code> as a variable name. <code>file</code> is a Python builtin function that constructs a new object of type <code>file</code>. You can technically overwrite it, but it is a very bad idea to do so. For more builtins, see the <a href="https://docs.python.org/2/library/functions.html#file" rel="nofollow noreferrer">Python documentation</a>.</p> <ul> <li><strong>How do I filter results on multiple keywords?</strong></li> </ul> <p>All keywords are <code>OR</code>'d together in this type of search, <a href="https://stackoverflow.com/questions/14083968/tweepy-tracking-terms-and-following-users">source</a>:</p> <pre><code>sapi.filter(track=['twitter', 'python', 'tweepy']) </code></pre> <p>This means that this will get tweets containing 'twitter', 'python' or 'tweepy'. If you want the union (<code>AND</code>) all of the terms, you have to post-process by checking a tweet against the list of all terms you want to search for.</p> <ul> <li><strong>How do I filter results based on location AND keyword?</strong></li> </ul> <p>I actually just realized that you did <a href="https://stackoverflow.com/questions/23531835/how-do-i-filter-tweets-using-location-and-keyword?noredirect=1#comment36100514_23531835">ask this as its own question</a> as I was about to suggest. A regex post-processing solution is a good way to accomplish this. You could also try filtering by both location <em>and</em> keyword like so:</p> <pre><code>sapi.filter(locations=[103.60998,1.25752,104.03295,1.44973], track=['twitter']) </code></pre> <ul> <li><strong>What is the best way to store/process tweets?</strong></li> </ul> <p>That depends on how many you'll be collecting. I'm a fan of databases, especially if you're planning to do a sentiment analysis on a lot of tweets. When you collect data, you should <strong>only</strong> collect things you will need. This means, when you save results to your database/wherever in your <code>on_data</code> method, you should extract the important parts from the JSON and not save anything else. If for example you want to look at brand, country and time, only take those three things; don't save the entire JSON dump of the tweet because it'll just take up unnecessary space.</p>
8,945,879
How to get body of a POST in php?
<p>I submit as POST to a php page the following: </p> <pre><code>{a:1} </code></pre> <p>This is the body of the request (a POST request).<br> In php, what do I have to do to extract that value? </p> <pre><code>var_dump($_POST); </code></pre> <p>is not the solution, not working.</p>
8,945,912
9
3
null
2012-01-20 18:05:41.747 UTC
84
2021-05-01 01:03:42.687 UTC
2012-10-24 21:09:52.77 UTC
null
895,378
null
67,153
null
1
369
php|rest|post
396,532
<p>To access the entity body of a POST or PUT request (or any other HTTP method):</p> <pre><code>$entityBody = file_get_contents('php://input'); </code></pre> <p>Also, the <code>STDIN</code> constant is an already-open stream to <code>php://input</code>, so you can alternatively do:</p> <pre><code>$entityBody = stream_get_contents(STDIN); </code></pre> <p>From the <a href="http://php.net/manual/en/wrappers.php.php" rel="noreferrer">PHP manual entry on I/O streams<sup><em>docs</em></sup></a>:</p> <blockquote> <p><em>php://input</em> is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use <em>php://input</em> instead of <code>$HTTP_RAW_POST_DATA</code> as it does not depend on special php.ini directives. Moreover, for those cases where <code>$HTTP_RAW_POST_DATA</code> is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. <em>php://input</em> is not available with enctype="multipart/form-data".</p> </blockquote> <p>Specifically you'll want to note that the <code>php://input</code> stream, regardless of how you access it in a web SAPI, <em>is not seekable</em>. This means that it can only be read once. If you're working in an environment where large HTTP entity bodies are routinely uploaded you may wish to maintain the input in its stream form (rather than buffering it like the first example above).</p> <p>To maintain the stream resource something like this can be helpful:</p> <pre><code>&lt;?php function detectRequestBody() { $rawInput = fopen('php://input', 'r'); $tempStream = fopen('php://temp', 'r+'); stream_copy_to_stream($rawInput, $tempStream); rewind($tempStream); return $tempStream; } </code></pre> <p><code>php://temp</code> allows you to manage memory consumption because it will transparently switch to filesystem storage after a certain amount of data is stored (2M by default). This size can be manipulated in the php.ini file or by appending <code>/maxmemory:NN</code>, where <code>NN</code> is the maximum amount of data to keep in memory before using a temporary file, in bytes.</p> <p>Of course, unless you have a really good reason for seeking on the input stream, you shouldn't need this functionality in a web application. Reading the HTTP request entity body once is usually enough -- don't keep clients waiting all day while your app figures out what to do.</p> <p>Note that php://input is not available for requests specifying a <code>Content-Type: multipart/form-data</code> header (<code>enctype="multipart/form-data"</code> in HTML forms). This results from PHP already having parsed the form data into the <code>$_POST</code> superglobal.</p>
8,672,401
Get random post in Wordpress
<p>How do I get a random post in Wordpress?</p> <p>I would like to display a button on a page that, when pressed, goes to a random post from the blog. I don't want a random post to be displayed on the page, I just want a link that leads to that post. I tried searching for a code on Google and here at stackoverflow but no success.</p> <p>Thanks...</p> <p><strong>UPDATE:</strong></p> <p>Here is my template code:</p> <pre><code>&lt;?php /*Template Name: Random*/ ?&gt; &lt;?php get_header(); ?&gt; &lt;nav&gt;&lt;?php wp_nav_menu(array('menu' =&gt; 'Main Nav Menu')); ?&gt;&lt;/nav&gt; &lt;div id="main-content-archive"&gt; &lt;div class="grey-text"&gt;Random post&lt;/div&gt; &lt;?php $query = new WP_Query( array ( 'orderby' =&gt; 'rand', 'posts_per_page' =&gt; '1' ) );?&gt; &lt;?php if (have_posts()) : while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); echo '&lt;li&gt;'; the_title(); echo '&lt;/li&gt;'; ?&gt; &lt;?php endwhile; ?&gt; &lt;?php else : ?&gt; &lt;h2&gt;Not Found&lt;/h2&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre>
8,683,664
5
4
null
2011-12-29 19:20:20.227 UTC
2
2017-03-14 13:53:02.693 UTC
2011-12-30 20:03:10.37 UTC
null
1,038,471
null
1,038,471
null
1
16
wordpress|random
42,287
<p>I found <a href="http://www.wpbeginner.com/wp-tutorials/how-to-redirect-users-to-a-random-post-in-wordpress/" rel="noreferrer">this</a> post which gave me desired results...</p> <p>Here's a solution copy/pasted from the wpbeginner blog post. No copyright infringement intended.</p> <p>Just add the following code to the <code>functions.php</code> file:</p> <pre><code>add_action('init','random_add_rewrite'); function random_add_rewrite() { global $wp; $wp-&gt;add_query_var('random'); add_rewrite_rule('random/?$', 'index.php?random=1', 'top'); } add_action('template_redirect','random_template'); function random_template() { if (get_query_var('random') == 1) { $posts = get_posts('post_type=post&amp;orderby=rand&amp;numberposts=1'); foreach($posts as $post) { $link = get_permalink($post); } wp_redirect($link,307); exit; } } </code></pre> <p>Use <code>mydomain.com/random/</code> as your <code>href</code> for your button that leads to the random post.</p> <p>Thanks everyone who contributed for your help...</p> <p>Cheers!</p>
5,172,630
How do I display protected Amazon S3 images on my secure site using PHP?
<p>I am trying to move images for my site from my host to Amazon S3 cloud hosting. These images are of client work sites and cannot be publicly available. I would like them to be displayed on my site preferably by using the PHP SDK available from Amazon.</p> <p>So far I have been able to script for the conversion so that I look up records in my database, grab the file path, name it appropriately, and send it to Amazon.</p> <pre><code> //upload to s3 $s3-&gt;create_object($bucket, $folder.$file_name_new, array( 'fileUpload' =&gt; $file_temp, 'acl' =&gt; AmazonS3::ACL_PRIVATE, //access denied, grantee only own //'acl' =&gt; AmazonS3::ACL_PUBLIC, //image displayed //'acl' =&gt; AmazonS3::ACL_OPEN, //image displayed, grantee everyone has open permission //'acl' =&gt; AmazonS3::ACL_AUTH_READ, //image not displayed, grantee auth users has open permissions //'acl' =&gt; AmazonS3::ACL_OWNER_READ, //image not displayed, grantee only ryan //'acl' =&gt; AmazonS3::ACL_OWNER_FULL_CONTROL, //image not displayed, grantee only ryan 'storage' =&gt; AmazonS3::STORAGE_REDUCED ) ); </code></pre> <p>Before I copy everything over, I have created a simple form to do test upload and display of the image. If I upload an image using ACL_PRIVATE, I can either grab the public url and I will not have access, or I can grab the public url with a temporary key and can display the image.</p> <pre><code>&lt;?php //display the image link $temp_link = $s3-&gt;get_object_url($bucket, $folder.$file_name_new, '1 minute'); ?&gt; &lt;a href='&lt;?php echo $temp_link; ?&gt;'&gt;&lt;?php echo $temp_link; ?&gt;&lt;/a&gt;&lt;br /&gt; &lt;img src='&lt;?php echo $temp_link; ?&gt;' alt='finding image' /&gt;&lt;br /&gt; </code></pre> <p>Using this method, how will my caching work? I'm guessing every time I refresh the page, or modify one of my records, I will be pulling that image again, increasing my get requests.</p> <p>I have also considered using bucket policies to only allow image retrieval from certain referrers. Do I understand correctly that Amazon is supposed to only fetch requests from pages or domains I specify?</p> <p>I referenced: <a href="https://forums.aws.amazon.com/thread.jspa?messageID=188183&amp;#188183" rel="noreferrer">https://forums.aws.amazon.com/thread.jspa?messageID=188183&amp;#188183</a> to set that up, but then am confused as to which security I need on my objects. It seemed like if I made them Private they still would not display, unless I used the temp link like mentioned previously. If I made them public, I could navigate to them directly, regardless of referrer.</p> <p>Am I way off what I'm trying to do here? Is this not really supported by S3, or am I missing something simple? I have gone through the SDK documentation and lots of searching and feel like this should be a little more clearly documented so hopefully any input here can help others in this situation. I've read others who name the file with a unique ID, creating security through obscurity, but that won't cut it in my situation, and probably not best practice for anyone trying to be secure.</p>
5,181,773
4
0
null
2011-03-02 19:54:31.773 UTC
14
2015-01-20 22:10:15.61 UTC
null
null
null
null
599,105
null
1
27
php|image|amazon-s3|amazon-web-services|intranet
26,839
<p>The best way to serve your images is to generate a url using the PHP SDK. That way the downloads go directly from S3 to your users. </p> <p>You don't need to download via your servers as @mfonda suggested - you can set any caching headers you like on S3 objects - and if you did you would be losing some major benefits of using S3.</p> <p>However, as you pointed out in your question, the url will always be changing (actually the querystring) so browsers won't cache the file. The easy work around is simply to always use the same expiry date so that the same querystring is always generated. Or better still 'cache' the url yourself (eg in the database) and reuse it every time. </p> <p>You'll obviously have to set the expiry time somewhere far into the future, but you can regenerate these urls every so often if you prefer. eg in your database you would store the generated url and the expiry date(you could parse that from the url too). Then either you just use the existing url or, if the expiry date has passed, generate a new one. etc...</p>
5,252,465
Android: enum vs static final ints?
<p>What are the advantages (or disadvantages) of having an <code>enum</code> versus having a set of <code>static final int</code>s in Java Android applications? Are there efficiency or performance optimizations that occur that favor the use of one or the other?</p> <p>I ask this in context of say intent requestCodes and such - which tend to be ints in the Android sample code, as opposed to values from an enum, which I was used to in C.</p>
5,252,563
4
3
null
2011-03-09 21:36:08.163 UTC
8
2015-06-09 15:37:10.003 UTC
null
null
null
null
649,066
null
1
31
java|android|enums
24,223
<p>Enum advantages from <a href="https://stackoverflow.com/questions/4822877/why-doesnt-android-use-more-enums">this question</a>:</p> <blockquote> <ul> <li>They are much more type-safe than integers, strings, or sets of boolean flags.</li> <li>They lead to more readable code.</li> <li>It's more difficult to set an enum to an invalid value than an int or string.</li> <li>They make it easy to discover the allowed values for a variable or parameter.</li> <li>Everything I've read indicates that they perform just as well as integers in C# and most JVMs.</li> </ul> </blockquote> <p>I would add:</p> <ul> <li>Enums can have member and instance variables, whereas an <code>int</code> can't.</li> </ul> <p>Like most abstractions, they are generally unequivocally advantageous once their <a href="https://stackoverflow.com/questions/5143256/why-was-avoid-enums-where-you-only-need-ints-removed-from-androids-performance">performance catches up</a>. Especially in your application code (as opposed to framework code) I would choose enums over other methods that simulate them.</p>
5,447,278
Bash scripts with tmux to launch a 4-paned window
<p>Can anyone help explain what's going on with <code>tmux</code>, <code>bash</code>, and <code>exec</code>? I'm trying to set up a tmux session with a 4-pane window. Ideally, I want to run a command in 3 of the panes: e.g. a Ruby Thin server and a couple of Ruby daemons. This is what I have so far:</p> <p><code>~/.bin/tmux-foo</code>:</p> <pre><code>#!/bin/sh tmux new-session -d -s foo 'exec pfoo "bundle exec thin start"' tmux rename-window 'Foo' tmux select-window -t foo:0 tmux split-window -h 'exec pfoo "bundle exec compass watch"' tmux split-window -v -t 0 'exec pfoo "rake ts:start"' tmux split-window -v -t 1 'exec pfoo' tmux -2 attach-session -t foo </code></pre> <p><code>~/.bin/pfoo</code>:</p> <pre><code>#!/bin/bash cd ~/projects/foo rvm use ree # here I want to execute command1 2 3 or 4... exec $SHELL </code></pre> <p>It all works... but when I <code>ctlr-c</code> in the first pane that is running the thin server, it stops the thin server and returns to the shell. However, the command is not in the history; i.e. if I hit the up key I don't get the <code>bundle exec thin start</code> command... I get some other command from my bash history. I'm wondering if there's any way to arrange these scripts so that I get the commands in the bash history.</p> <p>Also... I've tried many combinations of <code>exec</code>, <code>exec $SHELL -s ...</code>, and <code>exec $SHELL -s ... -I</code> and I'm not quite sure what is going on...</p> <p>Can anyone help explain the general idea of what is going on with <code>tmux</code> and <code>bash</code> and <code>exec</code> here?</p>
7,720,881
4
1
null
2011-03-27 04:42:30.07 UTC
27
2020-10-31 23:05:09.533 UTC
null
null
null
null
59,639
null
1
76
bash|exec|tmux
80,135
<p>As others have mentioned, your commands are being run by the shell script <em>before</em> launching your <code>$SHELL</code>; there is no general way the instance of <code>$SHELL</code> can know what its parent ran before starting it.</p> <p>To get the “initial command” into the shell history, you need to feed the command keystrokes directly to the instance of <code>$SHELL</code> itself (after it has been started, of course). In other contexts I might suggest using a small Expect program to spawn an instance of <code>$SHELL</code>, feed it the keystrokes, then use <code>interact</code> to tie the tty to the <em>expect</em>-spawned <code>$SHELL</code>.</p> <p>But in the context of <em>tmux</em>, we can just use <code>send-keys</code>: </p> <pre><code>#!/bin/sh tmux new-session -d -s foo 'exec pfoo' tmux send-keys 'bundle exec thin start' 'C-m' tmux rename-window 'Foo' tmux select-window -t foo:0 tmux split-window -h 'exec pfoo' tmux send-keys 'bundle exec compass watch' 'C-m' tmux split-window -v -t 0 'exec pfoo' tmux send-keys 'rake ts:start' 'C-m' tmux split-window -v -t 1 'exec pfoo' tmux -2 attach-session -t foo </code></pre>
5,407,814
C++ - interval tree implementation
<p><em>Does someone know any good <code>interval tree</code> implementation in C++?</em></p> <p>Obviously, something template-driven, better in <code>boost</code>-like style.</p> <p>And another question - if somebody tested, does a basic <code>std::vector</code>-based interval tree implementation with sorting can beat the generic interval tree <em>(with O(lg) operations)</em> in practice?</p>
5,408,008
5
0
null
2011-03-23 15:41:47.313 UTC
11
2020-12-18 20:29:42.933 UTC
null
null
null
null
346,332
null
1
35
c++|data-structures|interval-tree
21,718
<p>Boost-like ? <a href="http://www.boost.org/doc/libs/1_46_1/libs/icl/doc/html/index.html" rel="noreferrer">Boost ICL</a>!</p> <p><em>The Boost Interval Container Library</em></p>
5,013,717
Are inner classes in C++ automatically friends?
<p>If I define an inner class in C++, is it automatically a friend of the class that contains it? For example, is this legal:</p> <pre><code>class Outer { public: class Inner { public: void mutateOuter(Outer&amp; o); }; private: int value; }; void Outer::Inner::mutateOuter(Outer&amp; o) { o.value ++; // Legal? Or not? } </code></pre> <p>I ask because on some compilers I've tried (VS2003) this code won't work, but I've heard at least anecdotally that it does work on some compilers. I can't find a relevant section in the C++ spec about this, and if anyone can cite something specific that would say that it is or is not legal that would be great.</p>
14,759,603
5
8
null
2011-02-16 07:37:05.057 UTC
15
2017-06-29 08:50:12.157 UTC
2015-08-07 14:37:53.77 UTC
null
5,640
null
501,557
null
1
81
c++|friend|nested-class
24,938
<p>After having asked more or less the same question <a href="https://stackoverflow.com/q/14758881/1984137">here</a> myself, I wanted to share the (apparently) updated answer for C++11: </p> <p>Quoted from <a href="https://stackoverflow.com/a/14759027/1984137">https://stackoverflow.com/a/14759027/1984137</a>:</p> <blockquote> <p>standard $11.7.1</p> <p>"A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed"</p> <p>and the usual access rules specify that:</p> <p>"A member of a class can also access all the names to which the class has access..."</p> <p>specific examples has been given in the standard:</p> </blockquote> <pre><code>class E { int x; class B { }; class I { B b; // OK: E::I can access E::B int y; void f(E* p, int i) { p-&gt;x = i; // OK: E::I can access E::x } }; } </code></pre>
5,171,502
.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx
<blockquote> <p><strong>Possible Duplicates:</strong><br /> <a href="https://stackoverflow.com/questions/152555/h-or-hpp-for-your-class-definitions">*.h or *.hpp for your class definitions</a><br /> <a href="https://stackoverflow.com/questions/1545080/correct-c-code-file-extension-cc-vs-cpp">Correct C++ code file extension? .cc vs .cpp</a></p> </blockquote> <p>I used to think that it used to be that:</p> <ul> <li><code>.h</code> files are header files for C and C++, and usually only contain declarations.</li> <li><code>.c</code> files are C source code.</li> <li><code>.cpp</code> files are C++ source code (which can also be C source code).</li> </ul> <p>then files like <code>.hpp</code>, <code>.cc</code>, and <code>.cxx</code> came along, and I got totally confused... what's the difference(s) between those? When do you use the &quot;new&quot; ones?</p>
5,171,821
6
3
null
2011-03-02 18:04:59.567 UTC
82
2020-08-23 17:19:18.427 UTC
2020-08-23 17:19:18.427 UTC
null
5,740,428
null
541,686
null
1
296
c++|c|filenames|header-files|naming
230,968
<p>Historically, the first extensions used for C++ were <code>.c</code> and <code>.h</code>, exactly like for C. This caused practical problems, especially the <code>.c</code> which didn't allow build systems to easily differentiate C++ and C files.</p> <p>Unix, on which C++ has been developed, has case sensitive file systems. So some used <code>.C</code> for C++ files. Other used <code>.c++</code>, <code>.cc</code> and <code>.cxx</code>. <code>.C</code> and <code>.c++</code> have the problem that they aren't available on other file systems and their use quickly dropped. DOS and Windows C++ compilers tended to use <code>.cpp</code>, and some of them make the choice difficult, if not impossible, to configure. Portability consideration made that choice the most common, even outside MS-Windows.</p> <p>Headers have used the corresponding <code>.H</code>, <code>.h++</code>, <code>.hh</code>, <code>.hxx</code> and <code>.hpp</code>. But unlike the main files, <code>.h</code> remains to this day a popular choice for C++ even with the disadvantage that it doesn't allow to know if the header can be included in C context or not. Standard headers now have no extension at all.</p> <p>Additionally, some are using <code>.ii</code>, <code>.ixx</code>, <code>.ipp</code>, <code>.inl</code> for headers providing inline definitions and <code>.txx</code>, <code>.tpp</code> and <code>.tpl</code> for template definitions. Those are either included in the headers providing the definition, or manually in the contexts where they are needed.</p> <p>Compilers and tools usually don't care about what extensions are used, but using an extension that they associate with C++ prevents the need to track out how to configure them so they correctly recognize the language used.</p> <p>2017 edit: the experimental module support of Visual Studio recognize <code>.ixx</code> as a default extension for module interfaces, clang++ is recognizing <code>.c++m</code>, <code>.cppm</code> and <code>.cxxm</code> for the same purpose.</p>
5,089,042
jarsigner: unable to sign jar: java.util.zip.ZipException: invalid entry compressed size (expected 463 but got 465 bytes)
<p>when I am signing the apk, I get "jarsigner: unable to sign jar: java.util.zip.ZipException: invalid entry compressed size (expected 463 but got 465 bytes)" this error message. The apk size is almost 1MB. When I reduce the size to 500KB, signing success. Why this so?..Any Idea?</p>
5,089,188
6
2
null
2011-02-23 09:29:06.157 UTC
31
2021-07-01 12:01:11.6 UTC
null
null
null
null
536,091
null
1
93
android
83,700
<p>You are trying to sign an already signed <code>.apk</code>. You need to export an unsigned <code>.apk</code> file and then sign it with <code>jarsigner</code>.</p>
5,484,809
Full url for an image-path in Rails 3
<p>I have an Image, which contains carrierwave uploads: </p> <pre><code>Image.find(:first).image.url #=&gt; "/uploads/image/4d90/display_foo.jpg" </code></pre> <p>In my view, I want to find the absolute url for this. Appending the <a href="https://stackoverflow.com/questions/1939942/generate-full-url-to-javascript-in-rails-similar-to-javascript-path-but-url">root_url</a> results in a double <code>/</code>.</p> <pre><code>root_url + image.url #=&gt; http://localhost:3000//uploads/image/4d90/display_foo.jpg </code></pre> <p>I cannot use <a href="https://stackoverflow.com/questions/3489838/full-url-with-url-for-in-rails">url_for</a> (that I know of), because that <em>either</em> allows passing a path, <em>or</em> a list of options to identify the resource and the <code>:only_path</code> option. Since I do't have a resource that can be identified trough "controller"+"action" I cannot use the <code>:only_path</code> option. </p> <pre><code>url_for(image.url, :only_path =&gt; true) #=&gt; wrong amount of parameters, 2 for 1 </code></pre> <p>What would be the cleanest and best way to create a path into a full url in Rails3?</p>
5,484,829
9
0
null
2011-03-30 10:00:28.767 UTC
11
2017-11-21 19:20:56.69 UTC
2017-05-23 12:03:02.317 UTC
null
-1
null
73,673
null
1
37
ruby-on-rails|ruby|ruby-on-rails-3|url|path
43,109
<p>try <code>path</code> method</p> <pre><code>Image.find(:first).image.path </code></pre> <p><strong>UPD</strong></p> <pre><code>request.host + Image.find(:first).image.url </code></pre> <p>and you can wrap it as a helper to DRY it forever</p> <pre><code>request.protocol + request.host_with_port + Image.find(:first).image.url </code></pre>
5,074,893
How to remove the last character from a bash grep output
<pre><code>COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2` </code></pre> <p>outputs something like this</p> <pre><code>"Abc Inc"; </code></pre> <p>What I want to do is I want to remove the trailing ";" as well. How can i do that? I am a beginner to bash. Any thoughts or suggestions would be helpful.</p>
5,074,995
14
2
null
2011-02-22 06:38:48.3 UTC
10
2018-03-27 20:24:08.4 UTC
2011-02-22 06:50:57.963 UTC
null
90,848
null
316,082
null
1
64
bash|grep
176,823
<p>I'd use <code>sed 's/;$//'</code>. eg:</p> <pre><code>COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2 | sed 's/;$//'` </code></pre>
12,132,060
confirm() on window.onbeforeunload
<p>I want to show a confirmation dialog if the user wants to leave the page with unsaved form data. What I have is:</p> <pre><code>window.onbeforeunload = function() { if (not_saved) if (confirm('Changes will not be saved')) return true; return false; } </code></pre> <p>But no matter what the user clicks, the result is the same - the stupid hardcoded dialog box that asks them whether they want to leave the page or stay on page. What I want to ask them is whether they want to stay or leave, and if they want to stay nothing happens, if they want to leave, they leave. Is this even possible? I can see how browsers want to limit what websites can do about keeping the users on the page, but I think I've seen some websites (Google Docs I think) having nice civilized dialog boxes.</p>
12,132,076
3
0
null
2012-08-26 16:57:55.667 UTC
2
2018-08-21 13:23:01.273 UTC
null
null
null
null
993,110
null
1
11
javascript
42,972
<pre><code>window.onbeforeunload = function(e) { return 'Dialog text here.'; }; </code></pre> <p>Docs: </p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload" rel="noreferrer">https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload</a></li> <li><a href="http://dev.w3.org/html5/spec-LC/history.html#unloading-documents" rel="noreferrer">http://dev.w3.org/html5/spec-LC/history.html#unloading-documents</a></li> </ul> <blockquote> <p><strong>Note that in Firefox 4 and later the returned string is not displayed to the user.</strong></p> <p>If the returnValue attribute of the event object is not the empty string, or if the event was canceled, then the user agent should ask the user to confirm that they wish to unload the document. The prompt shown by the user agent may include the string of the returnValue attribute, or some leading subset thereof. (A user agent may want to truncate the string to 1024 characters for display, for instance.)</p> </blockquote>
12,480,497
Why am I getting error for apple-touch-icon-precomposed.png
<p>I have created a new rails3 project but I am seeing following logs many times in my server logs. Why I am getting these request and how can I avoid these?</p> <blockquote> <p>Started GET "/apple-touch-icon-precomposed.png" for 192.168.6.2 at 2012-09-18 20:03:53 +0530</p> <p>ActionController::RoutingError (No route matches [GET] "/apple-touch-icon-precomposed.png"):</p> </blockquote> <p>I haven't given this link anywhere and don't want to render this image anywhere. I am clueless why this resource is being tried to be loaded.</p>
12,683,605
11
1
null
2012-09-18 15:46:38.53 UTC
51
2018-08-25 13:03:33.27 UTC
2013-03-13 15:23:12.39 UTC
null
425,313
null
624,657
null
1
269
apple-touch-icon
184,017
<p>I guess apple devices make those requests if the device owner adds the site to it. This is the equivalent of the favicon. To resolve, add 2 100×100 png files, save it as apple-touch-icon-precomposed.png and apple-touch-icon.png and upload it to the root directory of the server. After that, the error should be gone.</p> <blockquote> <p>I noticed lots of requests for apple-touch-icon-precomposed.png and apple-touch-icon.png in the logs that tried to load the images from the root directory of the site. I first thought it was a misconfiguration of the mobile theme and plugin, but found out later that Apple devices make those requests if the device owner adds the site to it.</p> </blockquote> <p>Source: <a href="http://www.ghacks.net/2012/03/16/why-webmasters-should-analyze-their-404-error-log/" rel="noreferrer"><em>Why Webmasters Should Analyze Their 404 Error Log</em> (Mar 2012; by Martin Brinkmann)</a></p>
19,022,210
preferredStatusBarStyle isn't called
<p>I followed <a href="https://stackoverflow.com/questions/17678881/how-to-change-status-bar-text-color-in-ios-7">this thread</a> to override <code>-preferredStatusBarStyle</code>, but it isn't called. Are there any options that I can change to enable it? (I'm using XIBs in my project.)</p>
19,032,879
25
7
null
2013-09-26 07:42:14.107 UTC
118
2022-05-06 16:22:07.557 UTC
2017-05-23 12:26:38.723 UTC
null
-1
null
902,136
null
1
278
ios|ios7|uikit|uistatusbar
141,000
<h2>Possible root cause</h2> <p>I had the same problem, and figured out it was happening because I wasn't setting the root view controller in my application window. </p> <p>The <code>UIViewController</code> in which I had implemented the <code>preferredStatusBarStyle</code> was used in a <code>UITabBarController</code>, which controlled the appearance of the views on the screen.</p> <p>When I set the root view controller to point to this <code>UITabBarController</code>, the status bar changes started to work correctly, as expected (and the <code>preferredStatusBarStyle</code> method was getting called).</p> <pre><code>(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... // other view controller loading/setup code self.window.rootViewController = rootTabBarController; [self.window makeKeyAndVisible]; return YES; } </code></pre> <h2>Alternative method (Deprecated in iOS 9)</h2> <p>Alternatively, you can call one of the following methods, as appropriate, in each of your view controllers, depending on its background color, instead of having to use <code>setNeedsStatusBarAppearanceUpdate</code>:</p> <pre><code>[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; </code></pre> <p>or</p> <pre><code>[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault]; </code></pre> <p>Note that you'll also need to set <code>UIViewControllerBasedStatusBarAppearance</code> to <code>NO</code> in the plist file if you use this method.</p>
43,343,231
Enhanced REP MOVSB for memcpy
<p>I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom <code>memcpy</code>. </p> <p>ERMSB was introduced with the Ivy Bridge microarchitecture. See the section "Enhanced REP MOVSB and STOSB operation (ERMSB)" in the <a href="https://www-ssl.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-optimization-manual.html" rel="noreferrer">Intel optimization manual</a> if you don't know what ERMSB is.</p> <p>The only way I know to do this directly is with inline assembly. I got the following function from <a href="https://groups.google.com/forum/#!topic/gnu.gcc.help/-Bmlm_EG_fE" rel="noreferrer">https://groups.google.com/forum/#!topic/gnu.gcc.help/-Bmlm_EG_fE</a></p> <pre><code>static inline void *__movsb(void *d, const void *s, size_t n) { asm volatile ("rep movsb" : "=D" (d), "=S" (s), "=c" (n) : "0" (d), "1" (s), "2" (n) : "memory"); return d; } </code></pre> <p>When I use this however, the bandwidth is much less than with <code>memcpy</code>. <code>__movsb</code> gets 15 GB/s and <code>memcpy</code> get 26 GB/s with my i7-6700HQ (Skylake) system, Ubuntu 16.10, DDR4@2400 MHz dual channel 32 GB, GCC 6.2.</p> <p><strong>Why is the bandwidth so much lower with <code>REP MOVSB</code>? What can I do to improve it?</strong></p> <p>Here is the code I used to test this. </p> <pre><code>//gcc -O3 -march=native -fopenmp foo.c #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;stddef.h&gt; #include &lt;omp.h&gt; #include &lt;x86intrin.h&gt; static inline void *__movsb(void *d, const void *s, size_t n) { asm volatile ("rep movsb" : "=D" (d), "=S" (s), "=c" (n) : "0" (d), "1" (s), "2" (n) : "memory"); return d; } int main(void) { int n = 1&lt;&lt;30; //char *a = malloc(n), *b = malloc(n); char *a = _mm_malloc(n,4096), *b = _mm_malloc(n,4096); memset(a,2,n), memset(b,1,n); __movsb(b,a,n); printf("%d\n", memcmp(b,a,n)); double dtime; dtime = -omp_get_wtime(); for(int i=0; i&lt;10; i++) __movsb(b,a,n); dtime += omp_get_wtime(); printf("dtime %f, %.2f GB/s\n", dtime, 2.0*10*1E-9*n/dtime); dtime = -omp_get_wtime(); for(int i=0; i&lt;10; i++) memcpy(b,a,n); dtime += omp_get_wtime(); printf("dtime %f, %.2f GB/s\n", dtime, 2.0*10*1E-9*n/dtime); } </code></pre> <hr> <p>The reason I am interested in <code>rep movsb</code> is based off these comments</p> <blockquote> <p>Note that on Ivybridge and Haswell, with buffers to large to fit in MLC you can beat movntdqa using rep movsb; movntdqa incurs a RFO into LLC, rep movsb does not... rep movsb is significantly faster than movntdqa when streaming to memory on Ivybridge and Haswell (but be aware that pre-Ivybridge it is slow!)</p> </blockquote> <p><a href="https://stackoverflow.com/questions/26246040/whats-missing-sub-optimal-in-this-memcpy-implementation/26256216#comment41203823_26256216">What&#39;s missing/sub-optimal in this memcpy implementation?</a></p> <hr> <p>Here are my results on the same system from <a href="https://github.com/ssvb/tinymembench" rel="noreferrer">tinymembnech</a>.</p> <pre><code> C copy backwards : 7910.6 MB/s (1.4%) C copy backwards (32 byte blocks) : 7696.6 MB/s (0.9%) C copy backwards (64 byte blocks) : 7679.5 MB/s (0.7%) C copy : 8811.0 MB/s (1.2%) C copy prefetched (32 bytes step) : 9328.4 MB/s (0.5%) C copy prefetched (64 bytes step) : 9355.1 MB/s (0.6%) C 2-pass copy : 6474.3 MB/s (1.3%) C 2-pass copy prefetched (32 bytes step) : 7072.9 MB/s (1.2%) C 2-pass copy prefetched (64 bytes step) : 7065.2 MB/s (0.8%) C fill : 14426.0 MB/s (1.5%) C fill (shuffle within 16 byte blocks) : 14198.0 MB/s (1.1%) C fill (shuffle within 32 byte blocks) : 14422.0 MB/s (1.7%) C fill (shuffle within 64 byte blocks) : 14178.3 MB/s (1.0%) --- standard memcpy : 12784.4 MB/s (1.9%) standard memset : 30630.3 MB/s (1.1%) --- MOVSB copy : 8712.0 MB/s (2.0%) MOVSD copy : 8712.7 MB/s (1.9%) SSE2 copy : 8952.2 MB/s (0.7%) SSE2 nontemporal copy : 12538.2 MB/s (0.8%) SSE2 copy prefetched (32 bytes step) : 9553.6 MB/s (0.8%) SSE2 copy prefetched (64 bytes step) : 9458.5 MB/s (0.5%) SSE2 nontemporal copy prefetched (32 bytes step) : 13103.2 MB/s (0.7%) SSE2 nontemporal copy prefetched (64 bytes step) : 13179.1 MB/s (0.9%) SSE2 2-pass copy : 7250.6 MB/s (0.7%) SSE2 2-pass copy prefetched (32 bytes step) : 7437.8 MB/s (0.6%) SSE2 2-pass copy prefetched (64 bytes step) : 7498.2 MB/s (0.9%) SSE2 2-pass nontemporal copy : 3776.6 MB/s (1.4%) SSE2 fill : 14701.3 MB/s (1.6%) SSE2 nontemporal fill : 34188.3 MB/s (0.8%) </code></pre> <p>Note that on my system <code>SSE2 copy prefetched</code> is also faster than <code>MOVSB copy</code>.</p> <hr> <p>In my original tests I did not disable turbo. I disabled turbo and tested again and it does not appear to make much of a difference. However, changing the power management does make a big difference.</p> <p>When I do </p> <pre><code>sudo cpufreq-set -r -g performance </code></pre> <p>I sometimes see over 20 GB/s with <code>rep movsb</code>.</p> <p>with </p> <pre><code>sudo cpufreq-set -r -g powersave </code></pre> <p>the best I see is about 17 GB/s. But <code>memcpy</code> does not seem to be sensitive to the power management. </p> <hr> <p>I checked the frequency (using <code>turbostat</code>) <a href="https://askubuntu.com/a/620114/259597">with and without SpeedStep enabled</a>, with <code>performance</code> and with <code>powersave</code> for idle, a 1 core load and a 4 core load. I ran Intel's MKL dense matrix multiplication to create a load and set the number of threads using <code>OMP_SET_NUM_THREADS</code>. Here is a table of the results (numbers in GHz).</p> <pre><code> SpeedStep idle 1 core 4 core powersave OFF 0.8 2.6 2.6 performance OFF 2.6 2.6 2.6 powersave ON 0.8 3.5 3.1 performance ON 3.5 3.5 3.1 </code></pre> <p>This shows that with <code>powersave</code> even with SpeedStep disabled the CPU still clocks down to the idle frequency of <code>0.8 GHz</code>. It's only with <code>performance</code> without SpeedStep that the CPU runs at a constant frequency.</p> <p>I used e.g <code>sudo cpufreq-set -r performance</code> (because <code>cpufreq-set</code> was giving strange results) to change the power settings. This turns turbo back on so I had to disable turbo after. </p>
43,574,756
6
51
null
2017-04-11 10:22:09.467 UTC
57
2022-07-05 03:27:38.697 UTC
2021-03-11 12:25:59.953 UTC
null
224,132
null
2,542,702
null
1
87
performance|assembly|x86|cpu-architecture|memcpy
25,031
<p>This is a topic pretty near to my heart and recent investigations, so I'll look at it from a few angles: history, some technical notes (mostly academic), test results on my box, and finally an attempt to answer your actual question of when and where <code>rep movsb</code> might make sense. </p> <p>Partly, this is a <strong>call to share results</strong> - if you can run <a href="https://github.com/ssvb/tinymembench" rel="noreferrer">Tinymembench</a> and share the results along with details of your CPU and RAM configuration it would be great. Especially if you have a 4-channel setup, an Ivy Bridge box, a server box, etc. </p> <h1>History and Official Advice</h1> <p>The performance history of the fast string copy instructions has been a bit of a stair-step affair - i.e., periods of stagnant performance alternating with big upgrades that brought them into line or even faster than competing approaches. For example, there was a jump in performance in Nehalem (mostly targeting startup overheads) and again in Ivy Bridge (most targeting total throughput for large copies). You can find decade-old insight on the difficulties of implementing the <code>rep movs</code> instructions from an Intel engineer <a href="https://software.intel.com/en-us/forums/intel-visual-fortran-compiler-for-windows/topic/275765#comment-1551057" rel="noreferrer">in this thread</a>.</p> <p>For example, in guides preceding the introduction of Ivy Bridge, the typical <a href="https://stackoverflow.com/a/8429084/149138">advice</a> is to avoid them or use them very carefully<sup>1</sup>.</p> <p>The current (well, June 2016) guide has a variety of confusing and somewhat inconsistent advice, such as<sup>2</sup>:</p> <blockquote> <p>The specific variant of the implementation is chosen at execution time based on data layout, alignment and the counter (ECX) value. For example, MOVSB/STOSB with the REP prefix should be used with counter value less than or equal to three for best performance.</p> </blockquote> <p>So for copies of 3 or less bytes? You don't need a <code>rep</code> prefix for that in the first place, since with a claimed startup latency of ~9 cycles you are almost certainly better off with a simple DWORD or QWORD <code>mov</code> with a bit of bit-twiddling to mask off the unused bytes (or perhaps with 2 explicit byte, word <code>mov</code>s if you know the size is exactly three).</p> <p>They go on to say:</p> <blockquote> <p>String MOVE/STORE instructions have multiple data granularities. For efficient data movement, larger data granularities are preferable. This means better efficiency can be achieved by decomposing an arbitrary counter value into a number of double words plus single byte moves with a count value less than or equal to 3.</p> </blockquote> <p>This certainly seems wrong on current hardware with ERMSB where <code>rep movsb</code> is at least as fast, or faster, than the <code>movd</code> or <code>movq</code> variants for large copies.</p> <p>In general, that section (3.7.5) of the current guide contains a mix of reasonable and badly obsolete advice. This is common throughput the Intel manuals, since they are updated in an incremental fashion for each architecture (and purport to cover nearly two decades worth of architectures even in the current manual), and old sections are often not updated to replace or make conditional advice that doesn't apply to the current architecture.</p> <p>They then go on to cover ERMSB explicitly in section 3.7.6.</p> <p>I won't go over the remaining advice exhaustively, but I'll summarize the good parts in the "why use it" below.</p> <p>Other important claims from the guide are that on Haswell, <code>rep movsb</code> has been enhanced to use 256-bit operations internally.</p> <h1>Technical Considerations</h1> <p>This is just a quick summary of the underlying advantages and disadvantages that the <code>rep</code> instructions have from an <em>implementation standpoint</em>.</p> <h2>Advantages for <code>rep movs</code></h2> <ol> <li><p>When a <code>rep</code> movs instruction is issued, the CPU <em>knows</em> that an entire block of a known size is to be transferred. This can help it optimize the operation in a way that it cannot with discrete instructions, for example:</p> <ul> <li>Avoiding the RFO request when it knows the entire cache line will be overwritten.</li> <li>Issuing prefetch requests immediately and exactly. Hardware prefetching does a good job at detecting <code>memcpy</code>-like patterns, but it still takes a couple of reads to kick in and will "over-prefetch" many cache lines beyond the end of the copied region. <code>rep movsb</code> knows exactly the region size and can prefetch exactly.</li> </ul></li> <li><p>Apparently, there is no guarantee of ordering among the stores within<sup>3</sup> a single <code>rep movs</code> which can help simplify coherency traffic and simply other aspects of the block move, versus simple <code>mov</code> instructions which have to obey rather strict memory ordering<sup>4</sup>. </p></li> <li><p>In principle, the <code>rep movs</code> instruction could take advantage of various architectural tricks that aren't exposed in the ISA. For example, architectures may have wider internal data paths that the ISA exposes<sup>5</sup> and <code>rep movs</code> could use that internally.</p></li> </ol> <h2>Disadvantages</h2> <ol> <li><p><code>rep movsb</code> must implement a specific semantic which may be stronger than the underlying software requirement. In particular, <code>memcpy</code> forbids overlapping regions, and so may ignore that possibility, but <code>rep movsb</code> allows them and must produce the expected result. On current implementations mostly affects to startup overhead, but probably not to large-block throughput. Similarly, <code>rep movsb</code> must support byte-granular copies even if you are actually using it to copy large blocks which are a multiple of some large power of 2.</p></li> <li><p>The software may have information about alignment, copy size and possible aliasing that cannot be communicated to the hardware if using <code>rep movsb</code>. Compilers can often determine the alignment of memory blocks<sup>6</sup> and so can avoid much of the startup work that <code>rep movs</code> must do on <em>every</em> invocation.</p></li> </ol> <h3>Test Results</h3> <p>Here are test results for many different copy methods from <a href="https://github.com/ssvb/tinymembench" rel="noreferrer"><code>tinymembench</code></a> on my i7-6700HQ at 2.6 GHz (too bad I have the identical CPU so we aren't getting a new data point...):</p> <pre><code> C copy backwards : 8284.8 MB/s (0.3%) C copy backwards (32 byte blocks) : 8273.9 MB/s (0.4%) C copy backwards (64 byte blocks) : 8321.9 MB/s (0.8%) C copy : 8863.1 MB/s (0.3%) C copy prefetched (32 bytes step) : 8900.8 MB/s (0.3%) C copy prefetched (64 bytes step) : 8817.5 MB/s (0.5%) C 2-pass copy : 6492.3 MB/s (0.3%) C 2-pass copy prefetched (32 bytes step) : 6516.0 MB/s (2.4%) C 2-pass copy prefetched (64 bytes step) : 6520.5 MB/s (1.2%) --- standard memcpy : 12169.8 MB/s (3.4%) standard memset : 23479.9 MB/s (4.2%) --- MOVSB copy : 10197.7 MB/s (1.6%) MOVSD copy : 10177.6 MB/s (1.6%) SSE2 copy : 8973.3 MB/s (2.5%) SSE2 nontemporal copy : 12924.0 MB/s (1.7%) SSE2 copy prefetched (32 bytes step) : 9014.2 MB/s (2.7%) SSE2 copy prefetched (64 bytes step) : 8964.5 MB/s (2.3%) SSE2 nontemporal copy prefetched (32 bytes step) : 11777.2 MB/s (5.6%) SSE2 nontemporal copy prefetched (64 bytes step) : 11826.8 MB/s (3.2%) SSE2 2-pass copy : 7529.5 MB/s (1.8%) SSE2 2-pass copy prefetched (32 bytes step) : 7122.5 MB/s (1.0%) SSE2 2-pass copy prefetched (64 bytes step) : 7214.9 MB/s (1.4%) SSE2 2-pass nontemporal copy : 4987.0 MB/s </code></pre> <p>Some key takeaways:</p> <ul> <li>The <code>rep movs</code> methods are faster than all the other methods which aren't "non-temporal"<sup>7</sup>, and considerably faster than the "C" approaches which copy 8 bytes at a time.</li> <li>The "non-temporal" methods are faster, by up to about 26% than the <code>rep movs</code> ones - but that's a much smaller delta than the one you reported (26 GB/s vs 15 GB/s = ~73%).</li> <li>If you are not using non-temporal stores, using 8-byte copies from C is pretty much just as good as 128-bit wide SSE load/stores. That's because a good copy loop can generate enough memory pressure to saturate the bandwidth (e.g., 2.6 GHz * 1 store/cycle * 8 bytes = 26 GB/s for stores).</li> <li>There are no explicit 256-bit algorithms in tinymembench (except probably the "standard" <code>memcpy</code>) but it probably doesn't matter due to the above note.</li> <li>The increased throughput of the non-temporal store approaches over the temporal ones is about 1.45x, which is very close to the 1.5x you would expect if NT eliminates 1 out of 3 transfers (i.e., 1 read, 1 write for NT vs 2 reads, 1 write). The <code>rep movs</code> approaches lie in the middle.</li> <li>The combination of fairly low memory latency and modest 2-channel bandwidth means this particular chip happens to be able to saturate its memory bandwidth from a single-thread, which changes the behavior dramatically.</li> <li><code>rep movsd</code> seems to use the same magic as <code>rep movsb</code> on this chip. That's interesting because ERMSB only explicitly targets <code>movsb</code> and earlier tests on earlier archs with ERMSB show <code>movsb</code> performing much faster than <code>movsd</code>. This is mostly academic since <code>movsb</code> is more general than <code>movsd</code> anyway.</li> </ul> <h3>Haswell</h3> <p>Looking at the <a href="https://pastebin.com/HCsXH44w" rel="noreferrer">Haswell results</a> kindly provided by iwillnotexist in the comments, we see the same general trends (most relevant results extracted):</p> <pre><code> C copy : 6777.8 MB/s (0.4%) standard memcpy : 10487.3 MB/s (0.5%) MOVSB copy : 9393.9 MB/s (0.2%) MOVSD copy : 9155.0 MB/s (1.6%) SSE2 copy : 6780.5 MB/s (0.4%) SSE2 nontemporal copy : 10688.2 MB/s (0.3%) </code></pre> <p>The <code>rep movsb</code> approach is still slower than the non-temporal <code>memcpy</code>, but only by about 14% here (compared to ~26% in the Skylake test). The advantage of the NT techniques above their temporal cousins is now ~57%, even a bit more than the theoretical benefit of the bandwidth reduction.</p> <h1>When should you use <code>rep movs</code>?</h1> <p>Finally a stab at your actual question: when or why should you use it? It draw on the above and introduces a few new ideas. Unfortunately there is no simple answer: you'll have to trade off various factors, including some which you probably can't even know exactly, such as future developments.</p> <p>A note that the alternative to <code>rep movsb</code> may be the optimized libc <code>memcpy</code> (including copies inlined by the compiler), or it may be a hand-rolled <code>memcpy</code> version. Some of the benefits below apply only in comparison to one or the other of these alternatives (e.g., "simplicity" helps against a hand-rolled version, but not against built-in <code>memcpy</code>), but some apply to both.</p> <h2>Restrictions on available instructions</h2> <p>In some environments there is a restriction on certain instructions or using certain registers. For example, in the Linux kernel, use of SSE/AVX or FP registers is generally disallowed. Therefore most of the optimized <code>memcpy</code> variants cannot be used as they rely on SSE or AVX registers, and a plain 64-bit <code>mov</code>-based copy is used on x86. For these platforms, using <code>rep movsb</code> allows most of the performance of an optimized <code>memcpy</code> without breaking the restriction on SIMD code.</p> <p>A more general example might be code that has to target many generations of hardware, and which doesn't use hardware-specific dispatching (e.g., using <code>cpuid</code>). Here you might be forced to use only older instruction sets, which rules out any AVX, etc. <code>rep movsb</code> might be a good approach here since it allows "hidden" access to wider loads and stores without using new instructions. If you target pre-ERMSB hardware you'd have to see if <code>rep movsb</code> performance is acceptable there, though...</p> <h2>Future Proofing</h2> <p>A nice aspect of <code>rep movsb</code> is that it can, <em>in theory</em> take advantage of architectural improvement on future architectures, without source changes, that explicit moves cannot. For example, when 256-bit data paths were introduced, <code>rep movsb</code> was able to take advantage of them (as claimed by Intel) without any changes needed to the software. Software using 128-bit moves (which was optimal prior to Haswell) would have to be modified and recompiled.</p> <p>So it is both a software maintenance benefit (no need to change source) and a benefit for existing binaries (no need to deploy new binaries to take advantage of the improvement).</p> <p>How important this is depends on your maintenance model (e.g., how often new binaries are deployed in practice) and a very difficult to make judgement of how fast these instructions are likely to be in the future. At least Intel is kind of guiding uses in this direction though, by committing to at least <em>reasonable</em> performance in the future (<strong>15.3.3.6</strong>):</p> <blockquote> <p>REP MOVSB and REP STOSB will continue to perform reasonably well on future processors.</p> </blockquote> <h2>Overlapping with subsequent work</h2> <p>This benefit won't show up in a plain <code>memcpy</code> benchmark of course, which by definition doesn't have subsequent work to overlap, so the magnitude of the benefit would have to be carefully measured in a real-world scenario. Taking maximum advantage might require re-organization of the code surrounding the <code>memcpy</code>.</p> <p>This benefit is pointed out by Intel in their optimization manual (section 11.16.3.4) and in their words:</p> <blockquote> <p>When the count is known to be at least a thousand byte or more, using enhanced REP MOVSB/STOSB can provide another advantage to amortize the cost of the non-consuming code. The heuristic can be understood using a value of Cnt = 4096 and memset() as example:</p> <p>• A 256-bit SIMD implementation of memset() will need to issue/execute retire 128 instances of 32- byte store operation with VMOVDQA, before the non-consuming instruction sequences can make their way to retirement.</p> <p>• An instance of enhanced REP STOSB with ECX= 4096 is decoded as a long micro-op flow provided by hardware, but retires as one instruction. There are many store_data operation that must complete before the result of memset() can be consumed. Because the completion of store data operation is de-coupled from program-order retirement, a substantial part of the non-consuming code stream can process through the issue/execute and retirement, essentially cost-free if the non-consuming sequence does not compete for store buffer resources.</p> </blockquote> <p>So Intel is saying that after all some uops the code after <code>rep movsb</code> has issued, but while lots of stores are still in flight and the <code>rep movsb</code> as a whole hasn't retired yet, uops from following instructions can make more progress through the out-of-order machinery than they could if that code came after a copy loop.</p> <p>The uops from an explicit load and store loop all have to actually retire separately in program order. That has to happen to make room in the ROB for following uops.</p> <p>There doesn't seem to be much detailed information about how very long microcoded instruction like <code>rep movsb</code> work, exactly. We don't know exactly how micro-code branches request a different stream of uops from the microcode sequencer, or how the uops retire. If the individual uops don't have to retire separately, perhaps the whole instruction only takes up one slot in the ROB?</p> <p>When the front-end that feeds the OoO machinery sees a <code>rep movsb</code> instruction in the uop cache, it activates the Microcode Sequencer ROM (MS-ROM) to send microcode uops into the queue that feeds the issue/rename stage. It's probably not possible for any other uops to mix in with that and issue/execute<sup>8</sup> while <code>rep movsb</code> is still issuing, but subsequent instructions can be fetched/decoded and issue right after the last <code>rep movsb</code> uop does, while some of the copy hasn't executed yet. This is only useful if at least some of your subsequent code doesn't depend on the result of the <code>memcpy</code> (which isn't unusual). </p> <p>Now, the size of this benefit is limited: at most you can execute N instructions (uops actually) beyond the slow <code>rep movsb</code> instruction, at which point you'll stall, where N is the <a href="https://en.wikipedia.org/wiki/Re-order_buffer" rel="noreferrer">ROB size</a>. With current ROB sizes of ~200 (192 on Haswell, 224 on Skylake), that's a maximum benefit of ~200 cycles of free work for subsequent code with an IPC of 1. In 200 cycles you can copy somewhere around 800 bytes at 10 GB/s, so for copies of that size you may get free work close to the cost of the copy (in a way making the copy free). </p> <p>As copy sizes get much larger, however, the relative importance of this diminishes rapidly (e.g., if you are copying 80 KB instead, the free work is only 1% of the copy cost). Still, it is quite interesting for modest-sized copies.</p> <p>Copy loops don't totally block subsequent instructions from executing, either. Intel does not go into detail on the size of the benefit, or on what kind of copies or surrounding code there is most benefit. (Hot or cold destination or source, high ILP or low ILP high-latency code after).</p> <h2>Code Size</h2> <p>The executed code size (a few bytes) is microscopic compared to a typical optimized <code>memcpy</code> routine. If performance is at all limited by i-cache (including uop cache) misses, the reduced code size might be of benefit.</p> <p>Again, we can bound the magnitude of this benefit based on the size of the copy. I won't actually work it out numerically, but the intuition is that reducing the dynamic code size by B bytes can save at most <code>C * B</code> cache-misses, for some constant C. Every <em>call</em> to <code>memcpy</code> incurs the cache miss cost (or benefit) once, but the advantage of higher throughput scales with the number of bytes copied. So for large transfers, higher throughput will dominate the cache effects.</p> <p>Again, this is not something that will show up in a plain benchmark, where the entire loop will no doubt fit in the uop cache. You'll need a real-world, in-place test to evaluate this effect.</p> <h2>Architecture Specific Optimization</h2> <p>You reported that on your hardware, <code>rep movsb</code> was considerably slower than the platform <code>memcpy</code>. However, even here there are reports of the opposite result on earlier hardware (like Ivy Bridge).</p> <p>That's entirely plausible, since it seems that the string move operations get love periodically - but not every generation, so it may well be faster or at least tied (at which point it may win based on other advantages) on the architectures where it has been brought up to date, only to fall behind in subsequent hardware.</p> <p><a href="https://stackoverflow.com/questions/8858778/why-are-complicated-memcpy-memset-superior/9177369#comment55051490_9177369">Quoting</a> Andy Glew, who should know a thing or two about this after implementing these on the P6:</p> <blockquote> <p>the big weakness of doing fast strings in microcode was [...] the microcode fell out of tune with every generation, getting slower and slower until somebody got around to fixing it. Just like a library men copy falls out of tune. I suppose that it is possible that one of the missed opportunities was to use 128-bit loads and stores when they became available, and so on.</p> </blockquote> <p>In that case, it can be seen as just another "platform specific" optimization to apply in the typical every-trick-in-the-book <code>memcpy</code> routines you find in standard libraries and JIT compilers: but only for use on architectures where it is better. For JIT or AOT-compiled stuff this is easy, but for statically compiled binaries this does require platform specific dispatch, but that often already exists (sometimes implemented at link time), or the <code>mtune</code> argument can be used to make a static decision. </p> <h2>Simplicity</h2> <p>Even on Skylake, where it seems like it has fallen behind the absolute fastest non-temporal techniques, it is still faster than most approaches and is <em>very simple</em>. This means less time in validation, fewer mystery bugs, less time tuning and updating a monster <code>memcpy</code> implementation (or, conversely, less dependency on the whims of the standard library implementors if you rely on that).</p> <h2>Latency Bound Platforms</h2> <p>Memory throughput bound algorithms<sup>9</sup> can actually be operating in two main overall regimes: DRAM bandwidth bound or concurrency/latency bound.</p> <p>The first mode is the one that you are probably familiar with: the DRAM subsystem has a certain theoretic bandwidth that you can calculate pretty easily based on the number of channels, data rate/width and frequency. For example, my DDR4-2133 system with 2 channels has a max bandwidth of 2.133 * 8 * 2 = 34.1 GB/s, same as <a href="http://ark.intel.com/products/88967/Intel-Core-i7-6700HQ-Processor-6M-Cache-up-to-3_50-GHz" rel="noreferrer">reported on ARK</a>.</p> <p>You won't sustain more than that rate from DRAM (and usually somewhat less due to various inefficiencies) added across all cores on the socket (i.e., it is a global limit for single-socket systems).</p> <p>The other limit is imposed by how many concurrent requests a core can actually issue to the memory subsystem. Imagine if a core could only have 1 request in progress at once, for a 64-byte cache line - when the request completed, you could issue another. Assume also very fast 50ns memory latency. Then despite the large 34.1 GB/s DRAM bandwidth, you'd actually only get 64 bytes / 50 ns = 1.28 GB/s, or less than 4% of the max bandwidth.</p> <p>In practice, cores can issue more than one request at a time, but not an unlimited number. It is usually understood that there are only 10 <em>line fill buffers</em> per core between the L1 and the rest of the memory hierarchy, and perhaps 16 or so fill buffers between L2 and DRAM. Prefetching competes for the same resources, but at least helps reduce the effective latency. For more details look at any of the great posts <a href="https://software.intel.com/en-us/forums/software-tuning-performance-optimization-platform-monitoring/topic/480004" rel="noreferrer">Dr. Bandwidth has written on the topic</a>, mostly on the Intel forums.</p> <p>Still, <em>most</em> recent CPUs are limited by <em>this</em> factor, not the RAM bandwidth. Typically they achieve 12 - 20 GB/s per core, while the RAM bandwidth may be 50+ GB/s (on a 4 channel system). Only some recent gen 2-channel "client" cores, which seem to have a better uncore, perhaps more line buffers can hit the DRAM limit on a single core, and our Skylake chips seem to be one of them.</p> <p>Now of course, there is a reason Intel designs systems with 50 GB/s DRAM bandwidth, while only being to sustain &lt; 20 GB/s per core due to concurrency limits: the former limit is socket-wide and the latter is per core. So each core on an 8 core system can push 20 GB/s worth of requests, at which point they will be DRAM limited again.</p> <p>Why I am going on and on about this? Because the best <code>memcpy</code> implementation often depends on which regime you are operating in. Once you are DRAM BW limited (as our chips apparently are, but most aren't on a single core), using non-temporal writes becomes very important since it saves the read-for-ownership that normally wastes 1/3 of your bandwidth. You see that exactly in the test results above: the memcpy implementations that <em>don't</em> use NT stores lose 1/3 of their bandwidth.</p> <p>If you are concurrency limited, however, the situation equalizes and sometimes reverses, however. You have DRAM bandwidth to spare, so NT stores don't help and they can even hurt since they may increase the latency since the handoff time for the line buffer may be longer than a scenario where prefetch brings the RFO line into LLC (or even L2) and then the store completes in LLC for an effective lower latency. Finally, <em>server</em> uncores tend to have much slower NT stores than client ones (and high bandwidth), which accentuates this effect.</p> <p>So on other platforms you might find that NT stores are less useful (at least when you care about single-threaded performance) and perhaps <code>rep movsb</code> wins where (if it gets the best of both worlds).</p> <p>Really, this last item is a call for most testing. I know that NT stores lose their apparent advantage for single-threaded tests on most archs (including current server archs), but I don't know how <code>rep movsb</code> will perform relatively...</p> <h1>References</h1> <p>Other good sources of info not integrated in the above. </p> <p><a href="https://groups.google.com/forum/#!topic/comp.arch/ULvFgEM_ZSY" rel="noreferrer">comp.arch investigation</a> of <code>rep movsb</code> versus alternatives. Lots of good notes about branch prediction, and an implementation of the approach I've often suggested for small blocks: using overlapping first and/or last read/writes rather than trying to write only exactly the required number of bytes (for example, implementing all copies from 9 to 16 bytes as two 8-byte copies which might overlap in up to 7 bytes).</p> <hr> <p><sup>1</sup> Presumably the intention is to restrict it to cases where, for example, code-size is very important. </p> <p><sup>2</sup> See <strong>Section 3.7.5:</strong> REP Prefix and Data Movement.</p> <p><sup>3</sup> It is key to note this applies only for the various stores within the single instruction itself: once complete, the block of stores still appear ordered with respect to prior and subsequent stores. So code can see stores from the <code>rep movs</code> out of order <em>with respect to each other</em> but not with respect to prior or subsequent stores (and it's the latter guarantee you usually need). It will only be a problem if you use the end of the copy destination as a synchronization flag, instead of a separate store.</p> <p><sup>4</sup> Note that non-temporal discrete stores also avoid most of the ordering requirements, although in practice <code>rep movs</code> has even more freedom since there are still some ordering constraints on WC/NT stores.</p> <p><sup>5</sup> This is was common in the latter part of the 32-bit era, where many chips had 64-bit data paths (e.g, to support FPUs which had support for the 64-bit <code>double</code> type). Today, "neutered" chips such as the Pentium or Celeron brands have AVX disabled, but presumably <code>rep movs</code> microcode can still use 256b loads/stores.</p> <p><sup>6</sup> E.g., due to language alignment rules, alignment attributes or operators, aliasing rules or other information determined at compile time. In the case of alignment, even if the exact alignment can't be determined, they may at least be able to hoist alignment checks out of loops or otherwise eliminate redundant checks.</p> <p><sup>7</sup> I'm making the assumption that "standard" <code>memcpy</code> is choosing a non-temporal approach, which is highly likely for this size of buffer.</p> <p><sup>8</sup> That isn't necessarily obvious, since it could be the case that the uop stream that is generated by the <code>rep movsb</code> simply monopolizes dispatch and then it would look very much like the explicit <code>mov</code> case. It seems that it doesn't work like that however - uops from subsequent instructions can mingle with uops from the microcoded <code>rep movsb</code>.</p> <p><sup>9</sup> I.e., those which can issue a large number of independent memory requests and hence saturate the available DRAM-to-core bandwidth, of which <code>memcpy</code> would be a poster child (and as apposed to purely latency bound loads such as pointer chasing).</p>
3,362,885
How to get Users Email Id in Facebook application using PHP?
<p>I have created a simple Facebook application in PHP, that greets user by there user name, I also want there Email id, to be displayed. But i am not able to do that. the code that i am using is,</p> <pre><code>require_once('facebook.php'); require_once('config.php'); $facebook = new Facebook(APIKEY, SECRETKEY); $user=$facebook-&gt;require_login(); echo $user; // displaying the ID &lt;div style="padding: 10px;" id="greeting"&gt; &lt;fb:if-is-app-user uid="loggedinuser"&gt; &lt;h2&gt;Hi &lt;fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/&gt;! welcome to facebook&lt;/h2&gt; &lt;fb:else&gt; &lt;h2&gt;Hi &lt;fb:name firstnameonly="true" uid="loggedinuser" useyou="false"/&gt;! welcome to facebook&lt;/h2&gt; &lt;/fb:else&gt; &lt;/fb:if-user-has-added-app&gt; &lt;/div&gt; </code></pre> <p>the Output that i am getting is,</p> <pre><code>1000002020202020 Hi User! welcome to facebook </code></pre> <p>I want the Email address to be displayed along with the user name, i searched many code but did not get any solution. and if you any good facebook tutorial site please post the links too..</p>
3,413,156
3
2
null
2010-07-29 13:20:52.5 UTC
7
2012-04-22 13:30:29.557 UTC
null
null
null
null
212,595
null
1
7
php|facebook
45,444
<p>You can get the Email Address, directly without using the FQL.</p> <pre><code>// initialize facebook $facebook = new Facebook(array( 'appId' =&gt; APP_ID, 'secret' =&gt; APP_SECRET)); $session = $facebook-&gt;getSession(); if ($session) { try { $fbme = $facebook-&gt;api('/me'); } catch (FacebookApiException $e) { error_log($e); } } else { echo "You are NOT Logged in"; } //getting the login page if not signned in if (!$fbme) { $loginUrl = $facebook-&gt;getLoginUrl(array('canvas' =&gt; 1, 'fbconnect' =&gt; 0, 'req_perms' =&gt; 'email,user_birthday,publish_stream', 'next' =&gt; CANVAS_PAGE, 'cancel_url' =&gt; CANVAS_PAGE )); echo '&lt;fb:redirect url="' . $loginUrl . '" /&gt;'; } else { // $fbme is valid i.e. user can access our app echo "You can use this App"; } // getting the profile data $user_id = $fbme[id]; $name=$fbme['name']; $first_name=$fbme['first_name']; $last_name=$fbme['last_name']; $facebook_url=$fbme['link']; $location=$fbme['location']['name']; $bio_info=$fbme['bio']; $work_array=$fbme['work']; $education_array=$fbme["education"]; $email=$fbme['email']; $date_of_birth=$fbme['birthday']; </code></pre> <p>This code worked for me..and i go all the information needed with the Email ID.</p> <pre><code>NOTE: User has to allow us to get their Information during the Approval of Application. </code></pre>
3,730,358
How to add multiple headers throughout a single ListView with addHeaderView()?
<p>Can Android's addHeaderView() be used to add multiple headers throughout a single ListView? Can someone give an example of how to do this?</p> <p>I was able to accomplish what I wanted by manipulating the IconicAdapter Class... is there any reason why I should not do it this way? I feel this could be modified for more advanced implementations. In my case, I know that I will have two sections, with a header + 2 rows in each section.</p> <pre><code>class IconicAdapter extends ArrayAdapter&lt;String&gt; { IconicAdapter() { super(ContactTabProfileResource.this, R.layout.row_iconic, mArrayList); } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); View row = null; if(position == 1 || position == 5) { // phone row = inflater.inflate(R.layout.row_iconic, parent, false); TextView label =(TextView)row.findViewById(R.id.label); label.setText(mArrayList.get(position)); ImageView icon = (ImageView)row.findViewById(R.id.rowicon); icon.setImageResource(R.drawable.icon_phone); } else if (position == 2 || position == 6) { // email row = inflater.inflate(R.layout.row_iconic, parent, false); TextView label =(TextView)row.findViewById(R.id.label); label.setText(mArrayList.get(position)); ImageView icon = (ImageView)row.findViewById(R.id.rowicon); icon.setImageResource(R.drawable.icon_email); } else if (position == 0 || position == 4) { // section header row = inflater.inflate(R.layout.row_header, parent, false); TextView label =(TextView)row.findViewById(R.id.label); label.setText(mArrayList.get(position)); label.setBackgroundColor(Color.GRAY); } else if (position == 3) { // section divider row = inflater.inflate(R.layout.row_header, parent, false); TextView label =(TextView)row.findViewById(R.id.label); label.setText(" "); } return(row); } } </code></pre> <p>Then I created two different XML layouts. row_header.xml is for the header rows and row_iconic.xml is for the non-header rows, which contain an icon. </p> <p>row_header.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="right" &gt; &lt;TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="20sp" android:paddingTop="10dp" android:paddingBottom="10dp" android:paddingRight="10dp" android:paddingLeft="10px" android:gravity="left" android:textStyle="bold" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>row_iconic.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="right" &gt; &lt;TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="16sp" android:paddingTop="10dp" android:paddingBottom="10dp" android:paddingRight="10dp" android:paddingLeft="44px" /&gt; &lt;ImageView android:id="@+id/rowicon" android:layout_width="40dp" android:paddingRight="10dp" android:paddingTop="10dp" android:layout_height="30dp" android:src="@drawable/icon" /&gt; &lt;/LinearLayout&gt; </code></pre>
3,761,414
4
0
null
2010-09-16 20:04:23.013 UTC
9
2014-12-27 06:48:58.243 UTC
2014-12-27 06:48:58.243 UTC
null
474,189
null
300,129
null
1
13
android|listview|header
23,950
<p>What you want Android developers might call a list separator or subheading ("headers" and "footers" live only at the top or bottom of the list). The gist of how you can do this is by using a ListAdapter that wraps other ListAdapters and is smart enough to return a header view type for certain rows and keep track of the offsets, or wraps those separator views in their own mini adapters.</p> <p>Take a look at Mark Murphy's <a href="http://github.com/commonsguy/cw-advandroid/tree/master/ListView/Sections" rel="nofollow noreferrer">SectionedListAdapter</a>, GPL, which takes the first approach (based on code by Jeff Sharkey), or his <a href="http://github.com/commonsguy/cwac-merge" rel="nofollow noreferrer">MergeAdapter</a>, and see <a href="https://stackoverflow.com/questions/1606320/android-custom-separator-or-even-item-in-listview-depening-on-content-of-item">this SO question</a>.</p> <p>It's a far cry from the graceful handling of smart list subheadings on the iPhone, but it is fairly straightforward to use MergeAdapter and very flexible once you wrap your head around exactly what's going on inside the adapters.</p>
36,987,636
Cannot create an instance of OLE DB provider Microsoft.Jet.OLEDB.4.0 for linked server null
<p>I am trying to export from my <code>Table</code> data into <code>Excel</code> through <code>T-SQL</code> query. After little research I came up with this </p> <pre><code>INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=G:\Test.xls;', 'SELECT * FROM [Sheet1$]') SELECT * FROM dbo.products </code></pre> <p>When I execute the above query am getting this error </p> <blockquote> <p>Msg 7302, Level 16, State 1, Line 7 Cannot create an instance of OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)".</p> </blockquote> <p>So went through internet for solution, got the below link </p> <p><a href="https://blogs.msdn.microsoft.com/spike/2008/07/23/ole-db-provider-microsoft-jet-oledb-4-0-for-linked-server-null-returned-message-unspecified-error/" rel="noreferrer">https://blogs.msdn.microsoft.com/spike/2008/07/23/ole-db-provider-microsoft-jet-oledb-4-0-for-linked-server-null-returned-message-unspecified-error/</a></p> <p>In the above link they were saying like we need to be administrator to create folder in <strong>C drive</strong> <code>TEMP</code> folder since <code>OPENROWSET</code> creates some files or folder inside <code>TEMP</code> folder </p> <p>I am doing this in My Home PC and I am the administrator. Still am getting the same error.</p> <p><strong>SQL SERVER</strong> details </p> <blockquote> <p>Microsoft SQL Server 2016 (RC1) - 13.0.1200.242 (X64) Mar 10 2016 16:49:45 Copyright (c) Microsoft Corporation Enterprise Evaluation Edition (64-bit) on Windows 10 Pro 6.3 (Build 10586: )</p> </blockquote> <p>Any pointers to fix the problem will be highly appreciated </p> <p><strong>Update :</strong> Already I have configured the <code>Ad Hoc Distributed Queries</code> and</p> <p>Executed the below queries </p> <pre><code>EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.Jet.OLEDB.4.0', N'AllowInProcess', 1 GO EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.Jet.OLEDB.4.0', N'DynamicParameters', 1 GO </code></pre> <p>now am getting this error </p> <blockquote> <p>Msg 7438, Level 16, State 1, Line 7 The 32-bit OLE DB provider "Microsoft.Jet.OLEDB.4.0" cannot be loaded in-process on a 64-bit SQL Server.</p> </blockquote>
37,197,221
4
14
null
2016-05-02 16:55:52.233 UTC
17
2021-02-16 15:43:54.637 UTC
2016-05-12 17:08:20.117 UTC
null
3,349,551
null
3,349,551
null
1
33
sql|sql-server|export-to-excel|openrowset
114,931
<p>I have MS Sql server 2012, and Office 2013. This seems to be very finicky, so you may have to adjust to your particular versions.</p> <ol> <li>Download the Microsoft.ACE.OLEDB.12.0 for Windows, 64 bit version found here: <a href="https://www.microsoft.com/en-us/download/details.aspx?id=13255" rel="noreferrer">https://www.microsoft.com/en-us/download/details.aspx?id=13255</a></li> <li>Install it on your server.</li> <li>Check the user running SQL Server and make sure that user has access to the temp directory C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp if it's a local service account or C:\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp if it's a network service account.</li> <li>Configure 'Ad Hoc Distributed Queries' and enable the <code>Microsoft.ACE.OLEDB</code> files like this:</li> </ol> <p>Here's the SP_CONFIGURE commands: </p> <pre><code>SP_CONFIGURE 'show advanced options', 1; GO RECONFIGURE; SP_CONFIGURE 'Ad Hoc Distributed Queries', 1; GO RECONFIGURE; EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1 EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParam', 1 </code></pre> <p>On newer <strong>SQL Server 2014</strong> You had use <code>'DynamicParameters'</code> instead of <code>'DynamicParam'</code></p> <pre><code>EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1 </code></pre> <p>Make sure you register msexcl40.dll like this: </p> <pre><code>regsvr32 C:\Windows\SysWOW64\msexcl40.dll </code></pre>
38,255,655
Trying to pull files from my Github repository: "refusing to merge unrelated histories"
<p>I'm learning git, and I'm following the Git community book. </p> <p>Previously (long time ago) I made a public repository on Github, with some files. Now I set up a local Git repository on my current computer, and committed some files. Then I added a remote pointing to my Github page:</p> <pre><code>[root@osboxes c]# git remote add learnc https://github.com/michaelklachko/Learning-C </code></pre> <p>That seemed to be successful: </p> <pre><code>[root@osboxes c]# git remote show learnc * remote learnc Fetch URL: https://github.com/michaelklachko/Learning-C Push URL: https://github.com/michaelklachko/Learning-C HEAD branch: master Remote branch: master tracked Local ref configured for 'git push': master pushes to master (local out of date) </code></pre> <p>Now I want to download the files from my Github repo to my computer. I did this:</p> <pre><code>[root@osboxes c]# git fetch learnc [root@osboxes c]# git merge learnc/master warning: refname 'learnc/master' is ambiguous. Already up-to-date. </code></pre> <p>However, I don't see any new files in my local directory. How can I get them? </p> <p>I also tried to do this:</p> <pre><code>[root@osboxes c]# git pull learnc master From https://github.com/michaelklachko/Learning-C * branch master -&gt; FETCH_HEAD fatal: refusing to merge unrelated histories </code></pre> <p>BTW, locally I'm on master branch (there are no other branches):</p> <pre><code>[root@osboxes c]# git status On branch master nothing to commit, working directory clean </code></pre>
38,680,153
8
7
null
2016-07-07 21:33:49.263 UTC
45
2021-11-09 14:15:49.92 UTC
null
null
null
null
2,722,504
null
1
155
git|github|git-pull|git-fetch
185,381
<p>Try <code>--allow-unrelated-histories</code></p> <p>Like max630 commented, or as explained here <a href="https://stackoverflow.com/questions/37937984/git-refusing-to-merge-unrelated-histories">Git refusing to merge unrelated histories</a></p>
8,430,777
Programmatically get path to Application Support folder
<p>I'm trying to get an NSString for the user's Application Support folder.</p> <p>I know I can do <code>NSString *path = @"~/Library/Application Support";</code> but this doesn't seem very elegant. I've played around with using <code>NSSearchPathForDirectoriesInDomains</code> but it seems to be quite long-winded and creates several unnecessary objects (at least, my implementation of it does).</p> <p>Is there a simple way to do this?</p>
8,430,843
7
6
null
2011-12-08 12:05:39.277 UTC
11
2020-05-13 14:44:17.137 UTC
2017-04-04 12:15:00.967 UTC
null
1,033,581
null
262,455
null
1
64
ios|objective-c|swift|cocoa
40,695
<p>This is outdated, for current best practice use <code>FileManager.default.urls(for:in:)</code> as in the comment by <a href="https://stackoverflow.com/users/151471/andyvn22">@andyvn22</a> below.</p> <p>the Best practice is to use <code>NSSearchPathForDirectoriesInDomains</code> with <code>NSApplicationSupportDirectory</code> as "long winded" as it may be.</p> <p>Example:</p> <pre><code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); NSString *applicationSupportDirectory = [paths firstObject]; NSLog(@"applicationSupportDirectory: '%@'", applicationSupportDirectory); </code></pre> <p>NSLog output:</p> <pre><code>applicationSupportDirectory: '/Volumes/User/me/Library/Application Support' </code></pre>
22,155,832
Spring Java Config: how do you create a prototype-scoped @Bean with runtime arguments?
<p>Using Spring's Java Config, I need to acquire/instantiate a prototype-scoped bean with constructor arguments that are only obtainable at runtime. Consider the following code example (simplified for brevity):</p> <pre><code>@Autowired private ApplicationContext appCtx; public void onRequest(Request request) { //request is already validated String name = request.getParameter("name"); Thing thing = appCtx.getBean(Thing.class, name); //System.out.println(thing.getName()); //prints name } </code></pre> <p>where the Thing class is defined as follows:</p> <pre><code>public class Thing { private final String name; @Autowired private SomeComponent someComponent; @Autowired private AnotherComponent anotherComponent; public Thing(String name) { this.name = name; } public String getName() { return this.name; } } </code></pre> <p>Notice <code>name</code> is <code>final</code>: it can only be supplied via a constructor, and guarantees immutability. The other dependencies are implementation-specific dependencies of the <code>Thing</code> class, and shouldn't be known to (tightly coupled to) the request handler implementation.</p> <p>This code works perfectly well with Spring XML config, for example:</p> <pre><code>&lt;bean id="thing", class="com.whatever.Thing" scope="prototype"&gt; &lt;!-- other post-instantiation properties omitted --&gt; &lt;/bean&gt; </code></pre> <p>How do I achieve the same thing with Java config? The following does not work using Spring 3.x:</p> <pre><code>@Bean @Scope("prototype") public Thing thing(String name) { return new Thing(name); } </code></pre> <p>Now, I <em>could</em> create a Factory, e.g.:</p> <pre><code>public interface ThingFactory { public Thing createThing(String name); } </code></pre> <p>But that <em>defeats the entire point of using Spring to replace the ServiceLocator and Factory design pattern</em>, which would be ideal for this use case.</p> <p>If Spring Java Config could do this, I would be able to avoid:</p> <ul> <li>defining a Factory interface</li> <li>defining a Factory implementation</li> <li>writing tests for the Factory implementation</li> </ul> <p>That's a ton of work (relatively speaking) for something so trivial that Spring already supports via XML config.</p>
22,184,027
9
6
null
2014-03-03 19:43:43.6 UTC
72
2022-07-20 06:54:25.213 UTC
2018-12-14 19:21:58.367 UTC
null
407,170
null
407,170
null
1
170
java|spring|scope|prototype|spring-java-config
115,113
<p>In a <code>@Configuration</code> class, a <code>@Bean</code> method like so</p> <pre><code>@Bean @Scope(&quot;prototype&quot;) public Thing thing(String name) { return new Thing(name); } </code></pre> <p>is used to register a <strong>bean definition and provide the factory for creating the bean</strong>. The bean that it defines is only instantiated upon request using arguments that are determined either directly or through scanning that <code>ApplicationContext</code>.</p> <p>In the case of a <code>prototype</code> bean, a new object is created every time and therefore the corresponding <code>@Bean</code> method is also executed.</p> <p>You can retrieve a bean from the <code>ApplicationContext</code> through its <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean-java.lang.String-java.lang.Object...-" rel="noreferrer"><code>BeanFactory#getBean(String name, Object... args)</code></a> method which states</p> <blockquote> <p>Allows for specifying explicit constructor arguments / factory method arguments, overriding the specified default arguments (if any) in the bean definition.</p> <p>Parameters:</p> <p><strong>args</strong> arguments to use if creating a prototype using explicit arguments to a static factory method. It is invalid to use a non-null args value in any other case.</p> </blockquote> <p>In other words, for this <code>prototype</code> scoped bean, you are providing the arguments that will be used, not in the constructor of the bean class, but in the <code>@Bean</code> method invocation. (This method has very weak type guarantees since it uses a name lookup for the bean.)</p> <p>Alternatively, you can use the typed <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html#getBean-java.lang.Class-java.lang.Object...-" rel="noreferrer"><code>BeanFactory#getBean(Class requiredType, Object... args)</code></a> method which looks up the bean by type.</p> <p>This is at least true for Spring versions 4+.</p> <p>Note that, if you don't want to start with the <code>ApplicationContext</code> or <code>BeanFactory</code> for your bean retrieval, you can inject an <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/ObjectProvider.html" rel="noreferrer"><code>ObjectProvider</code></a> (since Spring 4.3).</p> <blockquote> <p>A variant of <code>ObjectFactory</code> designed specifically for injection points, allowing for programmatic optionality and lenient not-unique handling.</p> </blockquote> <p>and use its <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/ObjectProvider.html#getObject-java.lang.Object...-" rel="noreferrer"><code>getObject(Object... args)</code></a> method</p> <blockquote> <p>Return an instance (possibly shared or independent) of the object managed by this factory.</p> <p>Allows for specifying explicit construction arguments, along the lines of <code>BeanFactory.getBean(String, Object)</code>.</p> </blockquote> <p>For example,</p> <pre><code>@Autowired private ObjectProvider&lt;Thing&gt; things; [...] Thing newThing = things.getObject(name); [...] </code></pre>