id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
7,379,915
Java: How To Call Non Static Method From Main Method?
<p>I'm learning java and now i've the following problem: I have the main method declared as</p> <pre><code>public static void main(String[] args) { ..... } </code></pre> <p>Inside my main method, because it is <strong>static</strong> I can call ONLY other static method!!! Why ?</p> <p>For example: I have another class</p> <pre><code> public class ReportHandler { private Connection conn; private PreparedStatement prep; public void executeBatchInsert() { .... } } </code></pre> <p>So in my main class I declare a <code>private ReportHandler rh = new ReportHandler();</code></p> <p>But I can't call any method if they aren't static.</p> <p>Where does this go wrong?</p> <p>EDIT: sorry, my question is: how to 'design' the app to allow me to call other class from my 'starting point' (the <code>static void main</code>).</p>
7,379,939
9
0
null
2011-09-11 17:16:09.063 UTC
15
2021-01-25 11:57:29.737 UTC
2021-01-25 11:57:29.737 UTC
null
2,051,142
null
141,579
null
1
52
java
188,448
<p>You simply need to create an instance of ReportHandler:</p> <pre><code>ReportHandler rh = new ReportHandler(/* constructor args here */); rh.executeBatchInsert(); // Having fixed name to follow conventions </code></pre> <p>The important point of instance methods is that they're meant to be specific to a particular instance of the class... so you'll need to <em>create</em> an instance first. That way the instance will have access to the right connection and prepared statement in your case. Just calling <code>ReportHandler.executeBatchInsert</code>, there isn't enough <em>context</em>.</p> <p>It's really important that you understand that:</p> <ul> <li>Instance methods (and fields etc) relate to a particular instance</li> <li>Static methods and fields relate to the type itself, <em>not</em> a particular instance</li> </ul> <p>Once you understand that fundamental difference, it makes sense that you can't call an instance method without creating an instance... For example, it makes sense to ask, "What is the height of <em>that</em> person?" (for a specific person) but it doesn't make sense to ask, "What is the height of Person?" (without specifying a person).</p> <p>Assuming you're leaning Java from a book or tutorial, you should read up on more examples of static and non-static methods etc - it's a <em>vital</em> distinction to understand, and you'll have all kinds of problems until you've understood it.</p>
14,217,997
java: how to use bufferedreader to read specific line
<p>Lets say I have a text file called: data.txt (contains 2000 lines)</p> <p>How do I read given specific line from: 500-1500 and then 1500-2000 and display the output of specific line?</p> <p>this code will read whole files (2000 line)</p> <pre><code>public static String getContents(File aFile) { StringBuffer contents = new StringBuffer(); try { BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } </code></pre> <p>How do I modify above code to read specific line?</p>
14,218,138
3
7
null
2013-01-08 15:09:38.393 UTC
4
2018-12-10 10:14:56.31 UTC
2013-01-08 15:21:57.52 UTC
null
1,833,653
null
1,424,079
null
1
8
java|bufferedreader|file-handling|file-read
47,292
<p>I suggest java.io.LineNumberReader. It extends BufferedReader and you can use its <code>LineNumberReader.getLineNumber();</code> to get the current line number</p> <p>You can also use Java 7 <code>java.nio.file.Files.readAllLines</code> which returns a <code>List&lt;String&gt;</code> if it suits you better</p> <p>Note: </p> <p>1) favour StringBuilder over StringBuffer, StringBuffer is just a legacy class</p> <p>2) <code>contents.append(System.getProperty("line.separator"))</code> does not look nice use <code>contents.append(File.separator)</code> instead</p> <p>3) Catching exception seems irrelevant, I would also suggest to change your code as </p> <pre><code>public static String getContents(File aFile) throws IOException { BufferedReader rdr = new BufferedReader(new FileReader("aFile")); try { StringBuilder sb = new StringBuilder(); // read your lines return sb.toString(); } finally { rdr.close(); } } </code></pre> <p>now code looks cleaner in my view. And if you are in Java 7 use try-with-resources</p> <pre><code> try (BufferedReader rdr = new BufferedReader(new FileReader("aFile"))) { StringBuilder sb = new StringBuilder(); // read your lines return sb.toString(); } </code></pre> <p>so finally your code could look like </p> <pre><code>public static String[] getContents(File aFile) throws IOException { try (LineNumberReader rdr = new LineNumberReader(new FileReader(aFile))) { StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for (String line = null; (line = rdr.readLine()) != null;) { if (rdr.getLineNumber() &gt;= 1500) { sb2.append(line).append(File.pathSeparatorChar); } else if (rdr.getLineNumber() &gt; 500) { sb1.append(line).append(File.pathSeparatorChar); } } return new String[] { sb1.toString(), sb2.toString() }; } } </code></pre> <p>Note that it returns 2 strings 500-1499 and 1500-2000</p>
14,184,182
Why won't Fragment retain state when screen is rotated?
<p>I've been having some trouble getting some custom DialogPreference subclasses inside a PreferenceFragment to remain visible when the screen is rotated. I don't experience this problem when using a PreferenceActivity, so I don't know whether it's an Android bug or a problem with my code, but I'd like someone to confirm whether they are having the same experience.</p> <p>To test this, first create a preference screen containing at least one DialogPreference (it doesn't matter which subclass). Then display it in a PreferenceActivity. When you run your app, press on the DialogPreference so that it's dialog shows. Then rotate the screen so the orientation changes. Does the dialog remain visible?</p> <p>Then try the same, but with a PreferenceFragment to display your preferences instead of a PreferenceActivity. Again, does the dialog remain visible when you rotate the screen?</p> <p>So far, I've found that the dialog will remain visible if using a PreferenceActivity, but not if using a PreferenceFragment. Looking at the <a href="https://github.com/android/platform_frameworks_base/blob/master/core/java/android/preference/DialogPreference.java">source code for DialogPreference</a>, it seems that the correct behaviour is for the dialog to remain visible, because <code>isDialogShowing</code> is the state information that gets saved when <code>onSaveInstanceState()</code> is called on screen re-orientation. Therefore, I think a bug may be preventing the PreferenceFragment (and everything inside it) from restoring that state information.</p> <p>If it is an Android bug, then it has far-reaching implications, because anyone using PreferenceFragment cannot save and restore state information.</p> <p>Can someone please confirm? If it's not a bug, then what is going on?</p>
14,304,020
2
0
null
2013-01-06 16:32:13.613 UTC
19
2021-03-08 22:07:01.2 UTC
2013-01-15 17:32:09.19 UTC
null
963,396
null
963,396
null
1
29
android|android-fragments|android-preferences|preferenceactivity|dialog-preference
17,470
<p>Finally figured out a solution to this problem. Turns out it's not a bug, but a problem/oversight in the Android developer documentation.</p> <p>You see, I was following the PreferenceFragment tutorial <a href="http://developer.android.com/guide/topics/ui/settings.html#Fragment" rel="noreferrer">here</a>. That article tells you to do the following in order to instantiate your PreferenceFragment within an Activity:</p> <pre><code>public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Display the fragment as the main content. getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } } </code></pre> <p>The problem with this is that when you change the screen orientation (or any other action that destroys and re-creates the Activity), your PreferenceFragment will get created <strong>twice</strong>, which is what causes it to lose its state. </p> <p>The <strong>first</strong> creation will occur via the Activity's call to <code>super.onCreate()</code> (shown above), which will call the <code>onActivityCreated()</code> method for your PreferenceFragment () and the <code>onRestoreInstanceState()</code> method for each Preference it contains. These will successfully restore the state of everything.</p> <p>But then once that call to <code>super.onCreate()</code> returns, you can see that the <code>onCreate()</code> method will then go on to create the PreferenceFragment a <strong>second</strong> time. Because it is pointlessly created again (and this time, without state information!), all of the state that was just successfully restored will be completely discarded/lost. This explains why a DialogPreference that may be showing at the time that the Activity is destroyed will no longer be visible once the Activity is re-created.</p> <p>So what's the solution? Well, just add a small check to determine whether the PreferenceFragment has already been created, like so:</p> <pre><code>public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Fragment existingFragment = getFragmentManager().findFragmentById(android.R.id.content); if (existingFragment == null || !existingFragment.getClass().equals(SettingsFragment.class)) { // Display the fragment as the main content. getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } } } </code></pre> <p>Or another way is to simply check if <code>onCreate()</code> is meant to restore state or not, like so:</p> <pre><code>public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { // Display the fragment as the main content. getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } } } </code></pre> <p>So I guess the lesson learnt here is that <code>onCreate()</code> has a dual role - it can set up an Activity for the first time, or it can restore from an earlier state.</p> <p>The answer <a href="https://stackoverflow.com/a/14295474/963396">here</a> led me to realizing this solution.</p>
14,054,122
Associate an object with Marker (google map v2)
<p>In my app I have some objects that have their location displayed on the map using markers. The problem is that the only way I've found to handle marker clicks is</p> <pre><code>googleMap.setOnMarkerClickListener(new ... { @Override public void onMarkerClick(Marker marker) { // how to get the object associated to marker??? } }) </code></pre> <p>In other words I get the Marker object while the only interface that I have allows me to set just MarkerOptions.</p> <p>Any way to associate Marker with an object?</p>
39,122,553
3
0
null
2012-12-27 11:43:21.943 UTC
9
2016-08-24 11:51:21.8 UTC
null
null
null
null
504,663
null
1
31
android|android-maps|google-maps-android-api-2
20,201
<p>You can associate arbitrary object by using <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/model/Marker" rel="noreferrer">Marker</a>'s <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/model/Marker.html#setTag(java.lang.Object)" rel="noreferrer">setTag()</a> method </p> <pre><code>Marker amarker = mMap.addMarker(new MarkerOptions().position(lat, lng).title("Hello World")); amarker.setTag(new SomeData()); </code></pre> <p>To retrieve data associated with marker, you simply read it using its <a href="https://developers.google.com/android/reference/com/google/android/gms/maps/model/Marker.html#getTag()" rel="noreferrer">getTag()</a> and then cast it to its original type.</p> <pre><code>SomeData adata = (SomeData) amarker.getTag(); </code></pre> <p><a href="https://developers.google.com/maps/documentation/android-api/marker#display_additional_information_about_a_marker" rel="noreferrer">More information</a></p>
14,003,332
Access-Control-Allow-Origin wildcard subdomains, ports and protocols
<p>I'm trying to enable CORS for all subdomains, ports and protocol.</p> <p>For example, I want to be able to run an XHR request from <code>http://sub.mywebsite.example:8080/</code> to <code>https://www.mywebsite.example/</code>*</p> <p>Typically, I'd like to enable request from origins matching (and limited to):</p> <p><code>//*.mywebsite.example:*/*</code></p>
27,990,162
13
0
null
2012-12-22 13:44:26.957 UTC
94
2022-09-02 05:47:37.3 UTC
2022-06-23 19:45:18.507 UTC
null
1,145,388
null
246,077
null
1
420
cors
510,189
<p>Based on DaveRandom's <a href="https://stackoverflow.com/a/18958914/357774">answer</a>, I was also playing around and found a slightly simpler Apache solution that produces the same result (<code>Access-Control-Allow-Origin</code> is set to the current specific protocol + domain + port dynamically) without using any rewrite rules:</p> <pre><code>SetEnvIf Origin ^(https?://.+\.mywebsite\.example(?::\d{1,5})?)$ CORS_ALLOW_ORIGIN=$1 Header append Access-Control-Allow-Origin %{CORS_ALLOW_ORIGIN}e env=CORS_ALLOW_ORIGIN Header merge Vary &quot;Origin&quot; </code></pre> <p>And that's it.</p> <p>Those who want to enable CORS on the parent domain (e.g. <code>mywebsite.example</code>) in addition to all its subdomains can simply replace the regular expression in the first line with this one:</p> <p><code>^(https?://(?:.+\.)?mywebsite\.example(?::\d{1,5})?)$</code>.</p> <p><em>Note: For <a href="http://www.w3.org/TR/cors/#resource-implementation" rel="noreferrer">spec compliance</a> and correct caching behavior, ALWAYS add the <code>Vary: Origin</code> response header for CORS-enabled resources, even for non-CORS requests and those from a disallowed origin (see <a href="http://crbug.com/409090" rel="noreferrer">example why</a>).</em></p>
29,859,413
Bundle install: ERROR: Failed to build gem native extension. nio4r gem
<p>I'm currently working on a project using:</p> <ul> <li>rvm 1.26.11</li> <li>ruby 2.2.1p85</li> </ul> <p>I tried to run <code>bundle install</code> but keep getting the following error:</p> <pre><code>Gem::Ext::BuildError: ERROR: Failed to build gem native extension. </code></pre> <p>and, following:</p> <pre><code>An error occurred while installing nio4r (1.0.0), and Bundler cannot continue. Make sure that `gem install nio4r -v '1.0.0'` succeeds before bundling. </code></pre> <p>When I try running <code>gem install nio4r -v '1.0.0'</code>:</p> <pre><code>Building native extensions. This could take a while... ERROR: Error installing nio4r: ERROR: Failed to build gem native extension. </code></pre> <p>When I try running <code>bundle update</code>:</p> <pre><code>Please make sure you have the correct access rights and the repository exists. Retrying git clone '[email protected]:kshmir/requirejs-rails.git' ....* Git error: command `git clone '[email protected]:kshmir/requirejs-rails.git'.... has failed </code></pre> <p>When I try running <code>bundle update nio4r</code>:</p> <pre><code>Gem::Ext::BuildError: ERROR: Failed to build gem native extension.... An error occurred while installing eventmachine (1.0.3), and Bundler cannot continue. Make sure that `gem install eventmachine -v '1.0.3'` succeeds before bundling. </code></pre> <p>I tried that command too, to no result.</p> <p>I also tried changing Ruby version:</p> <p><code>rvm use 2.2.1</code> <code>2.2.0</code> <code>2.0.0</code> and running the commands above, but it doesn't change anything</p> <p><strong>Edit:</strong></p> <p>The output from running <code>bundle install log</code>:</p> <pre><code>Fetching gem metadata from rubygems....... Fetching version metadata from rubygems... Fetching dependency metadata from rubygems.. Using rake 10.2.2 Using i18n 0.7.0 Using multi_json 1.11.0 Using activesupport 3.2.17 Using builder 3.0.4 Using activemodel 3.2.17 Using erubis 2.7.0 Using journey 1.0.4 Using rack 1.4.5 Using rack-cache 1.2 Using rack-test 0.6.2 Using hike 1.2.3 Using tilt 1.4.1 Using sprockets 2.2.2 Using actionpack 3.2.17 Using mime-types 1.25.1 Using polyglot 0.3.4 Using treetop 1.4.15 Using mail 2.5.4 Using actionmailer 3.2.17 Using arbre 1.0.1 Using sass 3.2.19 Using thor 0.19.1 Using bourbon 3.1.8 Using bcrypt 3.1.7 Using bcrypt-ruby 3.1.5 Using orm_adapter 0.5.0 Using rack-ssl 1.3.4 Using json 1.8.1 Using rdoc 3.12.2 Using railties 3.2.17 Using atomic 1.1.15 Using thread_safe 0.2.0 Using warden 1.2.3 Using devise 3.2.3 Using formtastic 2.2.1 Using has_scope 0.6.0.rc Using responders 1.0.0 Using inherited_resources 1.4.1 Using jquery-rails 2.3.0 Using kaminari 0.15.1 Using arel 3.0.3 Using tzinfo 0.3.39 Using activerecord 3.2.17 Using polyamorous 0.5.0 Using meta_search 1.1.3 Using activeresource 3.2.17 Using bundler 1.8.4 Using rails 3.2.17 Using activeadmin 0.6.2 Using rgeo 0.3.20 Using rgeo-activerecord 0.5.0 Using activerecord-postgis-adapter 0.6.5 Using addressable 2.3.5 Using airbrake 3.1.16 Using descendants_tracker 0.0.3 Using ice_nine 0.11.0 Using axiom-types 0.0.5 Using coderay 1.1.0 Using better_errors 1.1.0 Using debug_inspector 0.0.2 Using binding_of_caller 0.7.2 Using bootstrap-datepicker-rails 1.1.1.8 Using bootstrap-sass 3.1.1.0 Using browser 0.8.0 Using columnize 0.3.6 Using debugger-linecache 1.2.0 Using byebug 2.7.0 Using cancan 1.6.10 Using highline 1.6.21 Using net-ssh 2.8.0 Using net-scp 1.1.2 Using net-sftp 2.1.2 Using net-ssh-gateway 1.2.0 Using capistrano 2.15.5 Using mini_portile 0.5.2 Using nokogiri 1.6.1 Using ffi 1.9.3 Using childprocess 0.5.1 Using rubyzip 1.1.0 Using websocket 1.0.7 Using selenium-webdriver 2.40.0 Using xpath 1.0.0 Using capybara 2.0.2 Using carrierwave 0.10.0 Using carrierwave_backgrounder 0.3.0 Using hitimes 1.2.2 Using timers 4.0.1 Using celluloid 0.16.0 Gem::Ext::BuildError: ERROR: Failed to build gem native extension. /home/adrian/.rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20150424-28432-11y95op.rb extconf.rb checking for rb_thread_blocking_region()... no checking for sys/select.h... yes checking for poll.h... yes checking for sys/epoll.h... yes checking for sys/event.h... no checking for port.h... no checking for sys/resource.h... yes creating Makefile make "DESTDIR=" clean make "DESTDIR=" compiling selector.c In file included from nio4r.h:10:0, from selector.c:6: /home/adrian/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/backward/rubyio.h:2:2: warning: #warning use "ruby/io.h" instead of "rubyio.h" [-Wcpp] #warning use "ruby/io.h" instead of "rubyio.h" ^ In file included from selector.c:7:0: /home/adrian/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/backward/rubysig.h:14:2: warning: #warning rubysig.h is obsolete [-Wcpp] #warning rubysig.h is obsolete ^ selector.c: In function ‘NIO_Selector_allocate’: selector.c:94:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] ev_init(&amp;selector-&gt;timer, NIO_Selector_timeout_callback); ^ selector.c:94:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:94:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:99:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] ev_io_init(&amp;selector-&gt;wakeup, NIO_Selector_wakeup_callback, selector-&gt;wakeup_reader, EV_READ); ^ selector.c:99:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:99:5: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c: In function ‘NIO_Selector_synchronize’: selector.c:159:11: warning: variable ‘current_thread’ set but not used [-Wunused-but-set-variable] VALUE current_thread, lock_holder, lock; ^ selector.c: In function ‘NIO_Selector_deregister_synchronized’: selector.c:241:11: warning: unused variable ‘monitor_args’ [-Wunused-variable] VALUE monitor_args[3]; ^ selector.c:240:21: warning: unused variable ‘interests’ [-Wunused-variable] VALUE self, io, interests, selectables, monitor; ^ selector.c: In function ‘NIO_Selector_select’: selector.c:268:20: warning: unused variable ‘array’ [-Wunused-variable] VALUE timeout, array; ^ selector.c: In function ‘NIO_Selector_select_synchronized’: selector.c:286:9: warning: unused variable ‘i’ [-Wunused-variable] int i, ready; ^ selector.c: In function ‘NIO_Selector_run’: selector.c:326:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement] ev_tstamp started_at = ev_now(selector-&gt;ev_loop); ^ selector.c:341:9: error: ‘TRAP_BEG’ undeclared (first use in this function) TRAP_BEG; ^ selector.c:341:9: note: each undeclared identifier is reported only once for each function it appears in selector.c:343:9: error: ‘TRAP_END’ undeclared (first use in this function) TRAP_END; ^ selector.c:347:9: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] ev_timer_init(&amp;selector-&gt;timer, NIO_Selector_timeout_callback, BUSYWAIT_INTERVAL, BUSYWAIT_INTERVAL); ^ selector.c:347:9: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:347:9: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c:347:9: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] selector.c: In function ‘NIO_Selector_close’: selector.c:391:5: warning: passing argument 2 of ‘NIO_Selector_synchronize’ from incompatible pointer type [enabled by default] return NIO_Selector_synchronize(self, NIO_Selector_close_synchronized, self); ^ selector.c:157:14: note: expected ‘VALUE (*)(VALUE *)’ but argument is of type ‘VALUE (*)(VALUE)’ static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE *args) ^ selector.c:391:5: warning: passing argument 3 of ‘NIO_Selector_synchronize’ makes pointer from integer without a cast [enabled by default] return NIO_Selector_synchronize(self, NIO_Selector_close_synchronized, self); ^ selector.c:157:14: note: expected ‘VALUE *’ but argument is of type ‘VALUE’ static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE *args) ^ selector.c: In function ‘NIO_Selector_closed’: selector.c:407:5: warning: passing argument 2 of ‘NIO_Selector_synchronize’ from incompatible pointer type [enabled by default] return NIO_Selector_synchronize(self, NIO_Selector_closed_synchronized, self); ^ selector.c:157:14: note: expected ‘VALUE (*)(VALUE *)’ but argument is of type ‘VALUE (*)(VALUE)’ static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE *args) ^ selector.c:407:5: warning: passing argument 3 of ‘NIO_Selector_synchronize’ makes pointer from integer without a cast [enabled by default] return NIO_Selector_synchronize(self, NIO_Selector_closed_synchronized, self); ^ selector.c:157:14: note: expected ‘VALUE *’ but argument is of type ‘VALUE’ static VALUE NIO_Selector_synchronize(VALUE self, VALUE (*func)(VALUE *args), VALUE *args) ^ selector.c: In function ‘NIO_Selector_wakeup’: selector.c:384:10: warning: ignoring return value of ‘write’, declared with attribute warn_unused_result [-Wunused-result] write(selector-&gt;wakeup_writer, "\0", 1); ^ make: *** [selector.o] Error 1 make failed, exit code 2 Gem files will remain installed in /home/adrian/.rvm/gems/ruby-2.2.1/gems/nio4r-1.0.0 for inspection. Results logged to /home/adrian/.rvm/gems/ruby-2.2.1/extensions/x86_64-linux/2.2.0/nio4r-1.0.0/gem_make.out An error occurred while installing nio4r (1.0.0), and Bundler cannot continue. Make sure that `gem install nio4r -v '1.0.0'` succeeds before bundling. </code></pre>
29,866,716
7
5
null
2015-04-25 00:00:59.77 UTC
8
2019-10-03 04:44:58.39 UTC
2015-04-26 15:22:30.853 UTC
null
4,830,557
null
4,830,557
null
1
16
ruby-on-rails|ruby|gem|rvm|bundler
28,517
<p>I solved it with:</p> <pre><code>sudo apt-get install libmysqlclient-dev sudo apt-get install libpq-dev sudo apt-get install libsqlite3-dev sudo apt-get install libev-dev rvm use 2.0.0 Reboot pc </code></pre> <p>If I run <code>rails -v</code> shows me:</p> <ul> <li>Rails 3.2.17</li> </ul> <p>And now I can make <code>Bundle install</code></p> <p>I think the rails version was in conflict. I don't know why, maybe anyone can explain me.</p>
30,103,356
Distributions and internal state
<p>On Stackoverflow there are many questions about generating uniformly distributed integers from a-priory unknown ranges. E.g.</p> <ul> <li><a href="https://stackoverflow.com/questions/25222167/c11-generating-random-numbers-from-frequently-changing-range">C++11 Generating random numbers from frequently changing range</a></li> <li><a href="https://stackoverflow.com/questions/19036141/vary-range-of-uniform-int-distribution">Vary range of uniform_int_distribution</a></li> </ul> <p>The typical solution is something like:</p> <pre><code>inline std::mt19937 &amp;engine() { thread_local std::mt19937 eng; return eng; } int get_int_from_range(int from, int to) { std::uniform_int_distribution&lt;int&gt; dist(from, to); return dist(engine()); } </code></pre> <p>Given that a distribution should be a lightweight object and there aren't performance concerns recreating it multiple times, it seems that even simple distribution may very well and usually will have <a href="https://stackoverflow.com/questions/16017494/what-is-a-c11-random-distribution-made-of">some internal state</a>.</p> <p>So I was wondering if interfering with how the distribution works by constantly resetting it (i.e. recreating the distribution at every call of <code>get_int_from_range</code>) I get properly distributed results.</p> <p>There's a <a href="https://stackoverflow.com/a/14858040/3235496">long discussion</a> between Pete Becker and Steve Jessop but without a final word. In another question (<a href="https://stackoverflow.com/questions/8433421/should-i-keep-the-random-distribution-object-instance-or-can-i-always-recreate-i">Should I keep the random distribution object instance or can I always recreate it?</a>) the "problem" of the internal state doesn't seem very important.</p> <p>Does the C++ standard make any guarantee regarding this topic?</p> <p>Is the following implementation (from <a href="http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2014/n4316.html" rel="noreferrer">N4316 - std::rand replacement</a>) somewhat more reliable?</p> <pre><code>int get_int_from_range(int from, int to) { using distribution_type = std::uniform_int_distribution&lt;int&gt;; using param_type = typename distribution_type::param_type; thread_local std::uniform_int_distribution&lt;int&gt; dist; return dist(engine(), param_type(from, to)); } </code></pre> <p>EDIT</p> <p>This reuses a possible internal state of a distribution but it's complex and I'm not sure it does worth the trouble:</p> <pre><code>int get_int_from_range(int from, int to) { using range_t = std::pair&lt;int, int&gt;; using map_t = std::map&lt;range_t, std::uniform_int_distribution&lt;int&gt;&gt;; thread_local map_t range_map; auto i = range_map.find(range_t(from, to)); if (i == std::end(range_map)) i = range_map.emplace( std::make_pair(from, to), std::uniform_int_distribution&lt;int&gt;{from, to}).first; return i-&gt;second(engine()); } </code></pre> <p><sup>(from <a href="https://stackoverflow.com/a/30097323/3235496">https://stackoverflow.com/a/30097323/3235496</a>)</sup></p>
30,355,300
1
6
null
2015-05-07 14:00:15.203 UTC
8
2015-05-20 18:13:59.693 UTC
2017-05-23 11:52:17.12 UTC
null
-1
null
3,235,496
null
1
21
c++|c++11|random|distribution|prng
893
<p>Interesting question.</p> <blockquote> <p>So I was wondering if interfering with how the distribution works by constantly resetting it (i.e. recreating the distribution at every call of get_int_from_range) I get properly distributed results.</p> </blockquote> <p>I've written code to test this with <code>uniform_int_distribution</code> and <code>poisson_distribution</code>. It's easy enough to extend this to test another distribution if you wish. The answer seems to be <strong>yes</strong>.</p> <p>Boiler-plate code:</p> <pre><code>#include &lt;random&gt; #include &lt;memory&gt; #include &lt;chrono&gt; #include &lt;utility&gt; typedef std::mt19937_64 engine_type; inline size_t get_seed() { return std::chrono::system_clock::now().time_since_epoch().count(); } engine_type&amp; engine_singleton() { static std::unique_ptr&lt;engine_type&gt; ptr; if ( !ptr ) ptr.reset( new engine_type(get_seed()) ); return *ptr; } // ------------------------------------------------------------------------ #include &lt;cmath&gt; #include &lt;cstdio&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;algorithm&gt; void plot_distribution( const std::vector&lt;double&gt;&amp; D, size_t mass = 200 ) { const size_t n = D.size(); for ( size_t i = 0; i &lt; n; ++i ) { printf("%02ld: %s\n", i, std::string(static_cast&lt;size_t&gt;(D[i]*mass),'*').c_str() ); } } double maximum_difference( const std::vector&lt;double&gt;&amp; x, const std::vector&lt;double&gt;&amp; y ) { const size_t n = x.size(); double m = 0.0; for ( size_t i = 0; i &lt; n; ++i ) m = std::max( m, std::abs(x[i]-y[i]) ); return m; } </code></pre> <p>Code for the actual tests:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;cstdio&gt; #include &lt;random&gt; #include &lt;string&gt; #include &lt;cmath&gt; void compare_uniform_distributions( int lo, int hi ) { const size_t sample_size = 1e5; // Initialize histograms std::vector&lt;double&gt; H1( hi-lo+1, 0.0 ), H2( hi-lo+1, 0.0 ); // Initialize distribution auto U = std::uniform_int_distribution&lt;int&gt;(lo,hi); // Count! for ( size_t i = 0; i &lt; sample_size; ++i ) { engine_type E(get_seed()); H1[ U(engine_singleton())-lo ] += 1.0; H2[ U(E)-lo ] += 1.0; } // Normalize histograms to obtain "densities" for ( size_t i = 0; i &lt; H1.size(); ++i ) { H1[i] /= sample_size; H2[i] /= sample_size; } printf("Engine singleton:\n"); plot_distribution(H1); printf("Engine creation :\n"); plot_distribution(H2); printf("Maximum difference: %.3f\n", maximum_difference(H1,H2) ); std::cout&lt;&lt; std::string(50,'-') &lt;&lt; std::endl &lt;&lt; std::endl; } void compare_poisson_distributions( double mean ) { const size_t sample_size = 1e5; const size_t nbins = static_cast&lt;size_t&gt;(std::ceil(2*mean)); // Initialize histograms std::vector&lt;double&gt; H1( nbins, 0.0 ), H2( nbins, 0.0 ); // Initialize distribution auto U = std::poisson_distribution&lt;int&gt;(mean); // Count! for ( size_t i = 0; i &lt; sample_size; ++i ) { engine_type E(get_seed()); int u1 = U(engine_singleton()); int u2 = U(E); if (u1 &lt; nbins) H1[u1] += 1.0; if (u2 &lt; nbins) H2[u2] += 1.0; } // Normalize histograms to obtain "densities" for ( size_t i = 0; i &lt; H1.size(); ++i ) { H1[i] /= sample_size; H2[i] /= sample_size; } printf("Engine singleton:\n"); plot_distribution(H1); printf("Engine creation :\n"); plot_distribution(H2); printf("Maximum difference: %.3f\n", maximum_difference(H1,H2) ); std::cout&lt;&lt; std::string(50,'-') &lt;&lt; std::endl &lt;&lt; std::endl; } // ------------------------------------------------------------------------ int main() { compare_uniform_distributions( 0, 25 ); compare_poisson_distributions( 12 ); } </code></pre> <p>Run it <a href="http://cpp.sh/4b35t" rel="nofollow">here</a>.</p> <hr> <blockquote> <p>Does the C++ standard make any guarantee regarding this topic?</p> </blockquote> <p>Not that I know of. However, I would say that the standard makes an implicit recommendation not to re-create the engine every time; for any distribution <code>Distrib</code>, the prototype of <code>Distrib::operator()</code> takes a reference <code>URNG&amp;</code> and not a const reference. This is understandably required because the engine might need to update its internal state, but it also implies that code looking like this</p> <pre><code>auto U = std::uniform_int_distribution(0,10); for ( &lt;something here&gt; ) U(engine_type()); </code></pre> <p>does not compile, which to me is a clear incentive not to write code like this.</p> <hr> <p>I'm sure there are plenty of advice out there on how to properly use the random library. It does get complicated if you have to handle the possibility of using <code>random_device</code>s and allowing deterministic seeding for testing purposes, but I thought it might be useful to throw my own recommendation out there too:</p> <pre><code>#include &lt;random&gt; #include &lt;chrono&gt; #include &lt;utility&gt; #include &lt;functional&gt; inline size_t get_seed() { return std::chrono::system_clock::now().time_since_epoch().count(); } template &lt;class Distrib&gt; using generator_type = std::function&lt; typename Distrib::result_type () &gt;; template &lt;class Distrib, class Engine = std::mt19937_64, class... Args&gt; inline generator_type&lt;Distrib&gt; get_generator( Args&amp;&amp;... args ) { return std::bind( Distrib( std::forward&lt;Args&gt;(args)... ), Engine(get_seed()) ); } // ------------------------------------------------------------------------ #include &lt;iostream&gt; int main() { auto U = get_generator&lt;std::uniform_int_distribution&lt;int&gt;&gt;(0,10); std::cout&lt;&lt; U() &lt;&lt; std::endl; } </code></pre> <p>Run it <a href="http://cpp.sh/7p25t" rel="nofollow">here</a>. Hope this helps!</p> <p><strong>EDIT</strong> My first recommendation was a mistake, and I apologise for that; we can't use a singleton engine like in the tests above, because this would mean that two uniform int distributions would produce the same random sequence. Instead I rely on the fact that <code>std::bind</code> copies the newly-created engine locally in <code>std::function</code> with its own seed, and this yields the expected behaviour; different generators with the same distribution produce different random sequences.</p>
9,156,417
Valid JSON giving JSONDecodeError: Expecting , delimiter
<p>I'm trying to parse a json response data from youtube api but i keep getting an error.</p> <p>Here is the snippet where it choking:</p> <pre><code>data = json.loads("""{ "entry":{ "etag":"W/\"A0UGRK47eCp7I9B9WiRrYU0.\"" } }""") </code></pre> <p>..and this happens:</p> <pre><code>JSONDecodeError: Expecting , delimiter: line 1 column 23 (char 23) </code></pre> <p>I've confirmed that it's valid json and I have no control over the formatting of it so how can I get past this error?</p>
9,156,466
2
1
null
2012-02-06 06:34:04.08 UTC
20
2020-08-27 09:20:34 UTC
2020-01-03 15:34:02.097 UTC
null
202,229
null
1,045,235
null
1
60
python|json|escaping|rawstring
136,007
<p>You'll need a <code>r</code> before """, or replace all <code>\</code> with <code>\\</code>. This is not something you should care about when read the json from somewhere else, but something in the string itself.</p> <p><code>data = json.loads(r"""{ "entry":{ "etag":"W/\"A0UGRK47eCp7I9B9WiRrYU0.\"" } }""")</code></p> <p>see <a href="http://docs.python.org/reference/lexical_analysis.html">here</a> for more information</p>
19,373,061
What happens to global and static variables in a shared library when it is dynamically linked?
<p>I'm trying to understand what happens when modules with globals and static variables are dynamically linked to an application. By modules, I mean each project in a solution (I work a lot with visual studio!). These modules are either built into *.lib or *.dll or the *.exe itself.</p> <p>I understand that the binary of an application contains global and static data of all the individual translation units (object files) in the data segment (and read only data segment if const).</p> <ul> <li><p>What happens when this application uses a module A with load-time dynamic linking? I assume the DLL has a section for its globals and statics. Does the operating system load them? If so, where do they get loaded to?</p></li> <li><p>And what happens when the application uses a module B with run-time dynamic linking?</p></li> <li><p>If I have two modules in my application that both use A and B, are copies of A and B's globals created as mentioned below (if they are different processes)?</p></li> <li><p>Do DLLs A and B get access to the applications globals?</p></li> </ul> <p>(Please state your reasons as well)</p> <p>Quoting from <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms682594%28v=vs.85%29.aspx">MSDN</a>:</p> <blockquote> <p>Variables that are declared as global in a DLL source code file are treated as global variables by the compiler and linker, but each process that loads a given DLL gets its own copy of that DLL's global variables. The scope of static variables is limited to the block in which the static variables are declared. As a result, each process has its own instance of the DLL global and static variables by default.</p> </blockquote> <p>and from <a href="http://c2.com/cgi/wiki?GlobalVariablesAreBad">here</a>:</p> <blockquote> <p>When dynamically linking modules, it can be unclear whether different libraries have their own instances of globals or whether the globals are shared.</p> </blockquote> <p>Thanks.</p>
19,374,253
3
3
null
2013-10-15 03:58:04.957 UTC
108
2022-01-15 07:16:28.433 UTC
2016-08-30 17:24:15.957 UTC
null
5,012,298
null
481,059
null
1
168
c++|linker|global-variables|global|dynamic-linking
116,035
<p>This is a pretty famous difference between Windows and Unix-like systems.</p> <p>No matter what:</p> <ul> <li>Each <em>process</em> has its own address space, meaning that there is never any memory being shared between processes (unless you use some inter-process communication library or extensions).</li> <li>The <em>One Definition Rule</em> (ODR) still applies, meaning that you can only have one definition of the global variable visible at link-time (static or dynamic linking).</li> </ul> <p>So, the key issue here is really <em>visibility</em>.</p> <p>In all cases, <code>static</code> global variables (or functions) are never visible from outside a module (dll/so or executable). The C++ standard requires that these have internal linkage, meaning that they are not visible outside the translation unit (which becomes an object file) in which they are defined. So, that settles that issue.</p> <p>Where it gets complicated is when you have <code>extern</code> global variables. Here, Windows and Unix-like systems are completely different.</p> <p>In the case of Windows (.exe and .dll), the <code>extern</code> global variables are not part of the exported symbols. In other words, different modules are in no way aware of global variables defined in other modules. This means that you will get linker errors if you try, for example, to create an executable that is supposed to use an <code>extern</code> variable defined in a DLL, because this is not allowed. You would need to provide an object file (or static library) with a definition of that extern variable and link it statically with <em>both</em> the executable and the DLL, resulting in two distinct global variables (one belonging to the executable and one belonging to the DLL).</p> <p>To actually export a global variable in Windows, you have to use a syntax similar to the function export/import syntax, i.e.:</p> <pre><code>#ifdef COMPILING_THE_DLL #define MY_DLL_EXPORT extern "C" __declspec(dllexport) #else #define MY_DLL_EXPORT extern "C" __declspec(dllimport) #endif MY_DLL_EXPORT int my_global; </code></pre> <p>When you do that, the global variable is added to the list of exported symbols and can be linked like all the other functions.</p> <p>In the case of Unix-like environments (like Linux), the dynamic libraries, called "shared objects" with extension <code>.so</code> export all <code>extern</code> global variables (or functions). In this case, if you do <em>load-time</em> linking from anywhere to a shared object file, then the global variables are shared, i.e., linked together as one. Basically, Unix-like systems are designed to make it so that there is virtually no difference between linking with a static or a dynamic library. Again, ODR applies across the board: an <code>extern</code> global variable will be shared across modules, meaning that it should have only one definition across all the modules loaded.</p> <p>Finally, in both cases, for Windows or Unix-like systems, you can do <em>run-time</em> linking of the dynamic library, i.e., using either <code>LoadLibrary()</code> / <code>GetProcAddress()</code> / <code>FreeLibrary()</code> or <code>dlopen()</code> / <code>dlsym()</code> / <code>dlclose()</code>. In that case, you have to manually get a pointer to each of the symbols you wish to use, and that includes the global variables you wish to use. For global variables, you can use <code>GetProcAddress()</code> or <code>dlsym()</code> just the same as you do for functions, provided that the global variables are part of the exported symbol list (by the rules of the previous paragraphs).</p> <p>And of course, as a necessary final note: <strong>global variables should be avoided</strong>. And I believe that the text you quoted (about things being "unclear") is referring exactly to the platform-specific differences that I just explained (dynamic libraries are not really defined by the C++ standard, this is platform-specific territory, meaning it is much less reliable / portable).</p>
52,363,518
How to push into an array of object using the spread operator to a specific element
<p>I have an array as such</p> <pre><code>const arr = [a={} , b={}] </code></pre> <p>Now I know the spread operator is not for mutation or pushing but it is very easy to do so with.</p> <p>I want this button to add elements to <code>a</code> when it's pressed </p> <pre><code> &lt;Button title= {this.props.title} onPress={ this.roomNumberPressed } /&gt; </code></pre> <p>so the end results be something like :</p> <pre><code>arr = [a={1,2,3} , b={3,4,5}] </code></pre>
52,363,566
1
3
null
2018-09-17 08:21:16.873 UTC
3
2018-09-17 08:24:43.483 UTC
null
null
null
null
3,621,842
null
1
8
javascript|arrays|reactjs
39,003
<blockquote> <p>I want this button to add elements to <code>a</code> when it's pressed</p> </blockquote> <p>As you said in your question, spread notation isn't for adding to existing objects. Your options are:</p> <ol> <li><p>Use spread to create a <strong>new</strong> object and assign that new object to <code>a</code>:</p> <pre><code>a = {...a, ...theNewPropertiesToAdd}; </code></pre></li> <li><p>Use <code>Object.assign</code> to add new properties to the <strong>existing</strong> <code>a</code>:</p> <pre><code>Object.assign(a, theNewPropertiesToAdd); </code></pre></li> </ol> <p>Note I've just used <code>a</code> above because your <code>const arr = [a={}, b={}]</code> is a syntax error, and I can't tell whether you mean <code>const arr = [{}, {}]</code> (in which case <code>a</code> above is <code>arr[0]</code>), or <code>const arr = {a: {}, b: {}}</code> (in which case <code>a</code> above is <code>arr.a</code> [and <code>arr</code> isn't an array]).</p>
24,936,689
Import Cordova project in Android Studio
<p>I am trying to create a Cordova project. After creating the project <code>cordova create myProject</code> I would like to open it in Android Studio. The problem is ... it doesn't work. </p> <p>The CordovaLib will not build with various errors <code>package android.* does not exist</code>.</p> <p>Does anyone know how to import a cordova project in Android Studio?</p>
33,270,847
4
3
null
2014-07-24 14:36:20.987 UTC
6
2018-03-19 12:53:04.943 UTC
null
null
null
null
1,990,021
null
1
29
android|cordova|android-studio
57,827
<p>Unfortunately the accepted answer is a bit out of date. Using Cordova v5.3.3 (it probably works on all versions > 5) it is much the same process a building and then entering XCode for an iOS application now - the build system has moved to gradle.</p> <p>Before opening in Android Studio</p> <pre><code>cordova build android </code></pre> <p>Then just open up the project using File > Open and pointing to the <strong>(yourProjectDir)/Platforms/Android</strong> directory.</p> <p>If you are using an older version of the cordova android platform you might need to run</p> <pre><code>cordova platform android update </code></pre> <p>To get moved to the gradle build system which is compatible with the current version of Android Studio</p>
196,173
How I do I make controls/elements move with inertia?
<p>Modern UI's are starting to give their UI elments nice inertia when moving. Tabs slide in, page transitions, even some listboxes and scroll elments have nice inertia to them (the iphone for example). What is the best algorythm for this? It is more than just gravity as they speed up, and then slow down as they fall into place. I have tried various formulae's for speeding up to a maximum (terminal) velocity and then slowing down but nothing I have tried "feels" right. It always feels a little bit off. Is there a standard for this, or is it just a matter of playing with various numbers until it looks/feels right?</p>
196,209
5
0
null
2008-10-12 21:52:49.113 UTC
11
2010-04-25 05:06:05.237 UTC
2010-04-25 05:06:05.237 UTC
null
164,901
Kris Erickson
3,798
null
1
9
user-interface|look-and-feel
5,168
<p>You're talking about two different things here.</p> <p>One is momentum - giving things residual motion when you release them from a drag. This is simply about remembering the velocity of a thing when the user releases it, then applying that velocity to the object every frame and also reducing the velocity every frame by some amount. How you reduce velocity every frame is what you experiment with to get the feel right.</p> <p>The other thing is ease-in and ease-out animation. This is about smoothly accelerating/decelerating objects when you move them between two positions, instead of just linearly interpolating. You do this by simply feeding your 'time' value through a sigmoid function before you use it to interpolate an object between two positions. One such function is</p> <pre><code>smoothstep(t) = 3*t*t - 2*t*t*t [0 &lt;= t &lt;= 1] </code></pre> <p>This gives you both ease-in and ease-out behaviour. However, you'll more commonly see only ease-out used in GUIs. That is, objects start moving snappily, then slow to a halt at their final position. To achieve that you just use the right half of the curve, ie.</p> <pre><code>smoothstep_eo(t) = 2*smoothstep((t+1)/2) - 1 </code></pre>
93,541
Baseline snaplines in custom Winforms controls
<p>I have a custom user control with a textbox on it and I'd like to expose the baseline (of the text in the textbox) snapline outside of the custom control. I know that you create a designer (inherited from ControlDesigner) and override SnapLines to get access to the snaplines, but I'm wondering how to get the text baseline of a control that I have exposed by my custom user control.</p>
402,419
5
0
null
2008-09-18 15:23:35.837 UTC
10
2013-10-29 16:40:04.623 UTC
2010-06-22 14:46:03.08 UTC
null
274,402
Mike
2,848
null
1
35
.net|winforms|user-controls|design-time|windows-forms-designer
6,703
<p>I just had a similar need, and I solved it like this:</p> <pre><code> public override IList SnapLines { get { IList snapLines = base.SnapLines; MyControl control = Control as MyControl; if (control == null) { return snapLines; } IDesigner designer = TypeDescriptor.CreateDesigner( control.textBoxValue, typeof(IDesigner)); if (designer == null) { return snapLines; } designer.Initialize(control.textBoxValue); using (designer) { ControlDesigner boxDesigner = designer as ControlDesigner; if (boxDesigner == null) { return snapLines; } foreach (SnapLine line in boxDesigner.SnapLines) { if (line.SnapLineType == SnapLineType.Baseline) { snapLines.Add(new SnapLine(SnapLineType.Baseline, line.Offset + control.textBoxValue.Top, line.Filter, line.Priority)); break; } } } return snapLines; } } </code></pre> <p>This way it's actually creating a temporary sub-designer for the subcontrol in order to find out where the "real" baseline snapline is.</p> <p>This seemed reasonably performant in testing, but if perf becomes a concern (and if the internal textbox doesn't move) then most of this code can be extracted to the Initialize method.</p> <p>This also assumes that the textbox is a direct child of the UserControl. If there are other layout-affecting controls in the way then the offset calculation becomes a bit more complicated.</p>
723,152
Difference between SSH and SSL, especially in terms of "SFTP" vs. "FTP over SSL"
<p>Apart from enhanced authentication options offered by SSH, is there any difference between basic working of SSH and SSL protocols ?</p> <p>I am asking since we can use <a href="https://en.wikipedia.org/wiki/File_Transfer_Protocol#Secure_FTP" rel="noreferrer">SFTP</a> or FTP over SSL, both would require authentication.</p>
729,903
5
0
null
2009-04-06 20:47:05.747 UTC
27
2019-11-19 21:49:41.333 UTC
2014-06-05 14:58:28.227 UTC
null
611,007
null
64,668
null
1
46
networking
69,903
<p>SSH and SSL are similar protocols that both use most of the same cryptographic primitives under the hood, so they are both as secure as each other. One advantage of SSH is that using key-pair authentication is actually quite easy to do, and built right into the protocol.</p> <p>With SSL it's a bit of a mess involving CA certificates and other things. After you have the PKI in place you also need to configure your services to use the PKI for authentication instead of its internal password database; this is a nightmare on some services and a piece of cake on others. It also means you need to go to the hassle of signing all of your user's keys so they can log in with them.</p> <p>Most competent users can grok SSH keys in no time but it takes a bit longer to get their heads around SSL keys (the extra CA certs and key certs confused me when I first discovered it).</p> <p>Pick what's supportable. SSH+SFTP is great for Unix people, but FTP over SSL is probably easier to do if your users are Windows-based and are pretty clueless about anything other than Internet Exploiter (and you don't mind risking that your users will choose insecure passwords).</p>
790,195
rm fails to delete files by wildcard from a script, but works from a shell prompt
<p>I've run into a really silly problem with a Linux shell script. I want to delete all files with the extension ".bz2" in a directory. In the script I call</p> <pre><code>rm "$archivedir/*.bz2" </code></pre> <p>where $archivedir is a directory path. Should be pretty simple, shouldn't it? Somehow, it manages to fail with this error:</p> <pre><code>rm: cannot remove `/var/archives/monthly/April/*.bz2': No such file or directory </code></pre> <p>But there <em>is</em> a file in that directory called test.bz2 and if I change my script to</p> <pre><code>echo rm "$archivedir/*.bz2" </code></pre> <p>and copy/paste the output of that line into a terminal window the file is removed successfully. What am I doing wrong?</p>
790,245
6
1
null
2009-04-26 03:41:45.537 UTC
15
2017-12-26 11:13:07.43 UTC
2009-04-26 14:05:34.38 UTC
null
15,168
null
20,336
null
1
68
linux|bash|shell
56,602
<p><strong>TL;DR</strong></p> <p>Quote only the variable, not the whole expected path with the wildcard</p> <pre><code>rm "$archivedir"/*.bz2 </code></pre> <p><strong>Explanation</strong></p> <ul> <li><p>In Unix, programs generally do not interpret wildcards themselves. The shell interprets unquoted wildcards, and replaces each wildcard argument with a list of matching file names. if $archivedir might contain spaces, then <code>rm $archivedir/*.bz2</code> might not do what you </p></li> <li><p>You can disable this process by quoting the wildcard character, using double or single quotes, or a backslash before it. However, that's not what you want here - you do want the wildcard expanded to the list of files that it matches.</p></li> <li><p>Be careful about writing <code>rm $archivedir/*.bz2</code> (without quotes). The word splitting (i.e., breaking the command line up into arguments) happens <em>after</em> $archivedir is substituted. So if $archivedir contains spaces, then you'll get extra arguments that you weren't intending. Say archivedir is <code>/var/archives/monthly/April to June</code>. Then you'll get the equivalent of writing <code>rm /var/archives/monthly/April to June/*.bz2</code>, which tries to delete the files "/var/archives/monthly/April", "to", and all files matching "June/*.bz2", which isn't what you want.</p></li> </ul> <p>The correct solution is to write:</p> <pre>rm "$archivedir"/*.bz2</pre>
186,857
Splitting a semicolon-separated string to a dictionary, in Python
<p>I have a string that looks like this:</p> <pre><code>"Name1=Value1;Name2=Value2;Name3=Value3" </code></pre> <p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p> <pre><code>dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } </code></pre> <p>I have looked through the modules available but can't seem to find anything that matches.</p> <hr> <p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p> <p>I'll do it myself then.</p>
186,873
6
2
null
2008-10-09 11:38:22.347 UTC
30
2020-08-23 08:07:34.587 UTC
2008-10-09 11:48:01.89 UTC
lassevk
267
lassevk
267
null
1
87
python|string|dictionary|split
105,573
<p>There's no builtin, but you can accomplish this fairly simply with a generator comprehension:</p> <pre><code>s= "Name1=Value1;Name2=Value2;Name3=Value3" dict(item.split("=") for item in s.split(";")) </code></pre> <p><strong>[Edit]</strong> From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):</p> <pre><code>&gt;&gt;&gt; s = "Name1='Value=2';Name2=Value2;Name3=Value3" &gt;&gt;&gt; dict(csv.reader([item], delimiter='=', quotechar="'").next() for item in csv.reader([s], delimiter=';', quotechar="'").next()) {'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'} </code></pre> <p>Depending on the exact structure of your format, you may need to write your own simple parser however.</p>
32,506,643
C++ compilation bug?
<p>I have the following code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;complex&gt; using namespace std; int main() { complex&lt;int&gt; delta; complex&lt;int&gt; mc[4] = {0}; for(int di = 0; di &lt; 4; di++, delta = mc[di]) { cout &lt;&lt; di &lt;&lt; endl; } return 0; } </code></pre> <p>I expect it to output "0, 1, 2, 3" and stop, but it outputs an endless series of "0, 1, 2, 3, 4, 5, ....."</p> <p>It looks like the comparison <code>di&lt;4</code> doesn't work well and always returns true.</p> <p>If I just comment out <code>,delta=mc[di]</code>, I get "0, 1, 2, 3" as normal. What's the problem with the innocent assignment?</p> <p>I am using <a href="http://ideone.com/" rel="noreferrer">Ideone.com</a> g++ C++14 with -O2 option.</p>
32,507,135
4
10
null
2015-09-10 16:00:23.603 UTC
13
2018-08-05 16:04:52.583 UTC
2015-09-11 11:58:59.637 UTC
null
1,708,801
null
3,423,503
null
1
74
c++|gcc|undefined-behavior
5,946
<p>This is due to undefined behavior, you are accessing the array <code>mc</code> out of bounds on the last iteration of your loop. Some compilers may perform aggressive loop optimization around the assumptions of no undefined behavior. The logic would be similar to the following:</p> <ul> <li>Accessing <code>mc</code> out of bounds is undefined behavior</li> <li>Assume no undefined behavior</li> <li>Therefore <code>di &lt; 4</code> is always true since otherwise <code>mc[di]</code> would invoke undefined behavior</li> </ul> <p>gcc with optimization turned on and using the <code>-fno-aggressive-loop-optimizations</code> flag causes the infinite loop behavior to disappear(<em><a href="http://melpon.org/wandbox/permlink/508I8VRM8AQsYMhC" rel="noreferrer">see it live</a></em>). While a <a href="http://melpon.org/wandbox/permlink/llQpnhdWRiNSLL44" rel="noreferrer">live example with optimization but without -fno-aggressive-loop-optimizations</a> exhibits the infinite loop behavior you observe.</p> <p>A <a href="https://gcc.godbolt.org/#%7B%22version%22%3A3%2C%22filterAsm%22%3A%7B%22labels%22%3Atrue%2C%22directives%22%3Atrue%2C%22commentOnly%22%3Atrue%2C%22colouriseAsm%22%3Atrue%7D%2C%22compilers%22%3A%5B%7B%22sourcez%22%3A%22MQSwdgxgNgrgJgUwAQB4QHsDOAXATggQwFsA%2BAKFElkVQhzg3MunmRQnSIAcoEAPcmTLhsSIgXAAKAJRIA3mSRKk9AFyqO3XnzRhsJJIijYCAbkXK1Gzj3679YiAG0ALAF0AvHIAMAX3PKSABm6LiSIoYgHt6mSBaBSgwoLgEJiSAA1BkANEYmHkTODG7S8fJxaVYcMKIoKJGo9VYIYHBQqUq%2BZfjYMLhgSDFkvkAAA%3D%22%2C%22compiler%22%3A%22g520%22%2C%22options%22%3A%22-std%3Dc%2B%2B11%20-O3%22%7D%5D%7D" rel="noreferrer">godbolt live example of the code</a> shows the <code>di &lt; 4</code> check is removed and replaced with and unconditional jmp:</p> <pre><code>jmp .L6 </code></pre> <p>This is almost identical to the case outlined in <a href="http://blog.regehr.org/archives/918" rel="noreferrer">GCC pre-4.8 Breaks Broken SPEC 2006 Benchmarks</a>. The comments to this article are excellent and well worth the read. It notes that clang caught the case in the article using <code>-fsanitize=undefined</code> which I can not reproduce for this case but gcc using <code>-fsanitize=undefined</code> does (<em><a href="http://melpon.org/wandbox/permlink/BPetd3bysBlJQEy4" rel="noreferrer">see it live</a></em>). Probably the most infamous bug around an optimizer making an inference around undefined behavior is the <a href="http://blog.regehr.org/archives/970" rel="noreferrer">Linux kernel null pointer check removal</a>.</p> <p>Although this is an aggressive optimizations, it is important to note that as the C++ standard says undefined behavior is:</p> <blockquote> <p>behavior for which this International Standard imposes no requirements</p> </blockquote> <p>Which essentially means anything is possible and it notes (<em>emphasis mine</em>):</p> <blockquote> <p>[...]Permissible undefined behavior ranges from ignoring the situation completely <strong>with unpredictable results</strong>, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).[...]</p> </blockquote> <p>In order to get a warning from gcc we need to move the <code>cout</code> outside the loop and then we see the following warning (<em><a href="http://melpon.org/wandbox/permlink/pH497fr2MQ2astNY" rel="noreferrer">see it live</a></em>):</p> <pre><code>warning: iteration 3u invokes undefined behavior [-Waggressive-loop-optimizations] for(di=0; di&lt;4;di++,delta=mc[di]){ } ^ </code></pre> <p>which would have likely been sufficient to provide the OP with enough information to figure out what was going on. Inconsistency like this are typical of the types of behavior we can see with undefined behavior. To get a better understanding of why such waring can be inconsitent in the face of undefined behavior <a href="http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html" rel="noreferrer">Why can't you warn when optimizing based on undefined behavior?</a> is a good read.</p> <p>Note, <code>-fno-aggressive-loop-optimizations</code> is documented in the <a href="https://gcc.gnu.org/gcc-4.8/changes.html" rel="noreferrer">gcc 4.8 release notes</a>.</p>
43,927,955
Should GetEnvironmentVariable work in xUnit tests?
<p>If I set environment variables for a .Net Core web project in Visual Studio 2017 using the project properties page, I can read the value of the variable using <code>Environment.GetEnvironmentVariable</code>; however, when I set the environment variable for my xUnit testing project and then debug the test, <code>Environment.GetEnvironmentVariable</code> always returns null. Is there something about the fact that it is a testing project that should prevent the variable from being used the same as with the web project? If so, is there a way that I can set the environment variables for a test project? Thank you.</p>
43,951,218
2
2
null
2017-05-12 01:31:08.25 UTC
10
2022-07-18 13:21:24.66 UTC
2022-07-18 13:21:00.447 UTC
null
70,345
null
4,194,514
null
1
55
visual-studio|.net-core|visual-studio-2017|xunit.net
33,400
<p>The <code>GetEnvironmentVariable</code> works fine in xUnit tests. The <strong>problem</strong> is to properly set a variable. If you set the variable at <code>Properties -&gt; Debug</code> page, then the variable is written to <code>Properties\launchSettings.json</code> and Visual Studio makes all work to launch an application with the selected profile. As you could see, <code>launchSettings.json</code> even isn't copied to output folder by default. It's impossible to pass this file as argument to <code>dotnet run</code> or <code>dotnet test</code>, that leads to obvious problem if tests are run automatically on a CI server. So it is not surprising that <code>launchSettings.json</code> isn't considered by a test runner.</p> <p><strong>Solution</strong>: there are a lot of ways to setup a test environment in xUnit:</p> <ul> <li>Constructor</li> <li>Base class</li> <li><a href="https://xunit.net/docs/shared-context#collection-fixture" rel="nofollow noreferrer">Fixture</a></li> </ul> <p>For example, this collection fixture sets up all environment variables from <code>launchSettings.json</code>:</p> <pre class="lang-cs prettyprint-override"><code>public class LaunchSettingsFixture : IDisposable { public LaunchSettingsFixture() { using (var file = File.OpenText(&quot;Properties\\launchSettings.json&quot;)) { var reader = new JsonTextReader(file); var jObject = JObject.Load(reader); var variables = jObject .GetValue(&quot;profiles&quot;) //select a proper profile here .SelectMany(profiles =&gt; profiles.Children()) .SelectMany(profile =&gt; profile.Children&lt;JProperty&gt;()) .Where(prop =&gt; prop.Name == &quot;environmentVariables&quot;) .SelectMany(prop =&gt; prop.Value.Children&lt;JProperty&gt;()) .ToList(); foreach (var variable in variables) { Environment.SetEnvironmentVariable(variable.Name, variable.Value.ToString()); } } } public void Dispose() { // ... clean up } } </code></pre> <p>Set <code>Copy to output directory: Always</code> for <code>launchSettings.json</code> to make the file accessible from tests.</p>
59,621,784
How to detect prefers-color-scheme change in javascript?
<p>I can use <code>window.matchMedia</code> to detect whether user is in dark mode, but how to listen dark mode change event?</p> <p>Is there any API like:</p> <pre class="lang-js prettyprint-override"><code>window.addEventListener('perfers-color-scheme-change', () =&gt; { // do something }) </code></pre>
59,621,903
3
1
null
2020-01-07 03:23:56.77 UTC
6
2022-09-15 18:20:38.007 UTC
null
null
null
null
7,957,792
null
1
28
javascript|css|browser
8,079
<p>You can add a <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryListListener" rel="noreferrer">MediaQueryListListener</a> by calling <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener" rel="noreferrer"><code>addListener()</code></a> on the <code>MediaQueryList</code> returned by <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia" rel="noreferrer">Window.matchMedia()</a>:</p> <pre class="lang-js prettyprint-override"><code>function activateDarkMode() { // set style to dark } window.matchMedia(&quot;(prefers-color-scheme: dark)&quot;).addListener( e =&gt; e.matches &amp;&amp; activateDarkMode() // listener ); </code></pre> <p>See this How-To article on <a href="https://medium.com/@jonas_duri/enable-dark-mode-with-css-variables-and-javascript-today-66cedd3d7845" rel="noreferrer">Use “prefers-color-scheme” to detect macOS dark mode with CSS and Javascript</a></p> <h3>Newer version to register the listener</h3> <p>Above method <code>addListener(listener)</code> has become deprecated but still works as an alias for newer <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener" rel="noreferrer"><code>addEventListener(&quot;change&quot;, listener))</code></a>. (Thanks to <a href="https://stackoverflow.com/users/2908501/lukaszpolowczyk">lukaszpolowczyk</a> for pointing out!)</p>
17,809,237
What does GLEW do and why do I need it?
<p>Okay, so I already know why I need GLEW, but only up to a point.</p> <p>If I am using modern OpenGL stuff, probably from version 3.0 onwards, and/or am using the Core Profile, then GLEW is required as without it compilation produced error such as <code>glGenVertexArrays</code> was not declared.</p> <p>So GLEW does a bit of background work including the modern OpenGL functions we would like to use, probably.</p> <p>Apart from that, does it do anything else? Also, how does it work.</p> <p>As an example, does it improve cross-platform compilation? (Require less modifications to code if moving from Linux to Windows or OS X for example?</p> <p>Does it also improved the "cross-platform-ness" of graphics hardware? For example, say we had two identical computers, including the OS. A program is compiled using OpenGL 4.3 commands on one system. If the other system has a graphics card or driver which only supports OpenGL 3.3, does GLEW help with that? (Compiling shaders for an older version of OpenGL, perhaps?)</p> <p>So you can probably see I don't actually know what GLEW does or how it does it.</p> <p>One last point; does anyone know how to use GLEW with GLFW? I might post that as a separate question actually.</p>
17,809,606
2
0
null
2013-07-23 11:42:58.633 UTC
5
2015-02-21 20:15:58.847 UTC
2013-07-23 13:14:38.017 UTC
null
44,729
null
893,254
null
1
29
opengl|opengl-3|glew|opengl-4
14,809
<p>GLEW isn't 'required', as you put it. You could use glcorearb.h header, or anything like that. However, if you link with some function - it must exist on target platform, or your program wouldn't launch. GLEW and others are exactly to handle that - you're not linking with GL functions directly, but instead getting function pointers after initialization phase. It allows you to check at runtime which extensions are present and which functions may be used.</p> <p>The only thing it helps with portability is getting function pointers - it may be wglGetProcAddress/glxGetProcAddress and it's analog for apple OSes. So no, it's not a case. However, the variety of available GL extensions is.</p> <p>GLEW requires no touch points with your preferred GL initialization library - just call glewInit after creating GL context.</p>
68,109,043
How to downgrade React version 17 to 16?
<p>How can I downgrade my React version from 17 to 16 as many of the React packages are not supported by React 17?</p>
68,109,161
3
1
null
2021-06-24 02:50:25.9 UTC
4
2022-07-24 21:38:57.587 UTC
2021-11-09 07:35:30.35 UTC
null
12,892,553
null
16,093,000
null
1
11
reactjs
51,831
<p>Assuming you're using npm/yarn or another node package manager, dependency versions are listed in <code>package.json</code>.</p> <p>Search for the <code>react</code> and <code>react-dom</code> packages under <code>dependencies</code> (or <code>devDependencies</code>) and replace their versions with <code>16.13.0</code>. Then run <code>npm install</code> or <code>yarn</code> or whatever package manager you're using. This should be enough to downgrade to React 16.</p> <p>If you have packages not compatible with React 16, you might have to downgrade them, too.</p>
33,313,393
Getting "Cannot verify client. (3000)" when trying to upload archive from Xcode to itunesConnect
<p>Just updated to Xcode 7.1 and getting this error. Was able to upload fine using 7.0.1</p>
33,313,520
20
4
null
2015-10-24 00:51:05.74 UTC
9
2016-01-27 13:17:04.543 UTC
null
null
null
null
36,510
null
1
114
xcode|app-store-connect
26,270
<p>Hmmm, well a restart of Xcode, a fresh clean, build and archive seems to have fixed it.</p>
23,099,915
Outlook calendar disappear from inbox after accept the request
<p>Outlook 2010 and 2010+ versions seem to remove meeting request emails from your inbox once you accept or decline the invite.</p> <p>How do I prevent these from being removed and keep them in my inbox? </p> <p>Usually the meeting invite also contains useful information or things that need to be followed up later.</p>
23,099,955
3
2
null
2014-04-16 04:20:05.387 UTC
7
2020-06-04 20:42:23.413 UTC
2016-05-23 14:12:30.11 UTC
null
1,898,563
null
1,423,280
null
1
24
outlook|outlook-2010|outlook-2013|outlook-2016
49,826
<p>In Outlook, this is found under the <strong>File</strong> tab. Click <strong>Options</strong>, then <strong>Mail</strong>, and scroll down to the <strong>Send messages</strong> section. Uncheck the box next to <strong>Delete meeting requests and notifications from Inbox after responding</strong></p>
2,312,852
How can I take screenshots of webpages with Perl?
<p>Is it possible to write a script in Perl that opens different URLs and saves a screenshot of each of them?</p>
2,313,035
5
4
null
2010-02-22 17:45:23.407 UTC
12
2018-06-29 21:51:31.19 UTC
2015-05-28 12:26:08.12 UTC
null
63,550
null
170,005
null
1
17
perl
7,764
<p>You could use <a href="http://search.cpan.org/perldoc?WWW::Mechanize::Firefox" rel="nofollow noreferrer">WWW::Mechanize::Firefox</a> to control a Firefox instance and dump the rendered page with <code>$mech-&gt;content_as_png</code>.</p> <p>Be aware that setting it up can pose quite a challenge, though.</p> <p>If all works as expected, you can simply use a script like this to dump images of the desired websites, but you should start Firefox and resize it to the desired width manually (height doesn't matter, WWW::Mechanize::Firefox always dumps the whole page).</p> <pre><code>use WWW::Mechanize::Firefox; use Path::Class qw/file/; my $mech = WWW::Mechanize::Firefox-&gt;new( bufsize =&gt; 10_000_000, # PNGs might become huge ); $mech-&gt;get('http://www.stackoverflow.com/'); my $fh = file( 'test.png' )-&gt;open( '&gt; :raw' ); print $fh $mech-&gt;content_as_png(); </code></pre>
1,760,542
Asp.net forms authentication cookie not honoring timeout with IIS7
<p>Authentication cookies seem to timeout after a short period of time (a day or so). I am using Forms Authentication and have the timeout="10080" with slidingExpiration="false" in the web.config. With that setting, the cookie should expire roughly 7 days after the user is successfully authenticated.</p> <p>This worked as advertised with IIS6, but when I moved the site to IIS7, the cookie expires much quicker. I've confirmed this behavior on multiple machines with IE and Firefox, leading me to believe it's an IIS7 setting.</p> <p>Is there a hidden setting that is IIS7 specific related to authentication? All other authentication types are disabled for the website, except for anonymous user tracking.</p>
2,191,001
5
5
null
2009-11-19 02:35:18.937 UTC
17
2015-07-12 16:50:01.717 UTC
null
null
null
null
3,085
null
1
26
asp.net|authentication|iis-7|cookies|forms-authentication
13,080
<p>The authentication cookie is encrypted using the <code>machineKey</code> value from the local <code>web.config</code> or the global <code>machine.config</code>. If no such key is <em>explicitly</em> set, a key will be automatically generated, but it is not persisted to disk – hence, it will change whenever the application is restarted or "recycled" due to inactivity, and a new key will be created on the next hit.</p> <p>Resolving the problem is as easy as adding a <code>&lt;machineKey&gt;</code> configuration section to <code>web.config</code>, or possibly (preferably?) to the <code>machine.config</code> on the server (untested):</p> <pre><code>&lt;system.web&gt; ... &lt;machineKey validationKey="..." decryptionKey="..." validation="SHA1" decryption="AES"/&gt; ... &lt;/system.web&gt; </code></pre> <p><a href="http://www.google.com/search?q=generate%20random%20machinekey" rel="noreferrer">Google <em>generate random machinekey</em></a> for sites that can generate this section for you. If your application deals with confidential information, you might want to create the keys yourself, though.</p>
2,113,936
Cuke4Nuke or SpecFlow?
<p>I am trying to decide if I should use Cuke4Nuke or SpecFlow. What are the pro/cons of each? Opinions on which is better and why.</p> <p>Thanks! </p>
2,116,572
6
0
null
2010-01-21 23:55:45.67 UTC
13
2011-12-08 21:53:55.227 UTC
2011-12-08 21:53:55.227 UTC
null
75,707
null
92,961
null
1
39
rspec|tdd|cucumber|bdd|specflow
7,693
<p>(I might be biased because I am involved with SpecFlow, but here my thoughts...)</p> <p>Cuke4Nuke is very close to Cucumber. This promises a lot of advantages:</p> <ul> <li>Compatibility</li> <li>Getting new features from Cucumber when Cucumber evolves (at least in theory, but language support is an example for this)</li> <li>Being a real part of the Cucumber community and the Cucumber ecosystem</li> </ul> <p>However this comes also with some potential disadvantages:</p> <ul> <li>Ruby is a necessity</li> <li>Since more infrastructure (Ruby, Wire-Protocol, command-line integration...) is involved, the complexity of the whole solution rises, and chances that something in the chain is failing rise</li> <li>Debugging is possible but a bit of a <a href="http://www.richardlawrence.info/2010/01/12/debugging-cuke4nuke-step-definitions/" rel="noreferrer">hassle</a></li> <li>Running scenarios on the dos-commandline is just plain ugly, and I still have problems with some characters (German Umlaute). The <a href="http://wiki.github.com/aslakhellesoy/cucumber/troubleshooting" rel="noreferrer">solutions</a> from Cucumber did not work for cuke4nuke in my case.</li> <li>Integration with your continuous build is something you have to work out for yourself</li> </ul> <p>SpecFlow is a separate project from Cucumber. It tries to be as close to Cucumber as possible, but there are and will be gaps. There are plans to use the same parser as Cucumber, to improve compatibility on the language level.</p> <p>SpecFlow tries to offer the following advantages:</p> <ul> <li>A pure .NET solution (so no installation of Ruby is necessary and Ruby is not involved at runtime)</li> <li>There is a basic integration with VisualStudio (and there are plans to evolve this)</li> <li>Scenarios are basically UnitTests and can be run with your existing infrastructure (NUnit.Runners, ReSharper, VisualStudio MSTest Integration ...)</li> <li>Scenarios and steps are easily debuggable out of VisualStudio (just set a breakpoint)</li> <li>Integration in your continuous build should be a breeze, since the infrastructure to run unit-tests is most certainly there already</li> </ul> <p>As disadvantages of SpecFlow I see currently:</p> <ul> <li>It does not support as many languages as Cucumber</li> <li>Currently there is a "code generation" step involved. This is transparent when using VisualStudio, and there is a commandline to do this without VisualStudio, but a lot of people do not like code-generation.</li> <li>Currently there is no explicit commandline runner for SpecFlow. However you can use your unit-test commandline runner.</li> <li>SpecFlow depends on a Unit-Test framework, and currently only NUnit and MSTest is supported</li> <li>Reporting in SpecFlow is not very sophisticated yet. Cucumber does offer more options, however I don't know if they are all available in cuke4nuke...</li> </ul>
2,259,228
How are booleans formatted in Strings in Python?
<p>I see I can't do:</p> <pre><code>"%b %b" % (True, False) </code></pre> <p>in Python. I guessed <code>%b</code> for b(oolean). Is there something like this?</p>
2,259,250
6
3
null
2010-02-13 22:02:11.637 UTC
18
2022-03-18 16:22:08.153 UTC
2014-06-08 01:16:51.623 UTC
null
562,769
null
157,519
null
1
190
python|boolean|string-formatting
199,429
<pre><code>&gt;&gt;&gt; print "%r, %r" % (True, False) True, False </code></pre> <p>This is not specific to boolean values - <code>%r</code> calls the <code>__repr__</code> method on the argument. <code>%s</code> (for <code>str</code>) should also work.</p>
2,145,026
Why is so complicated to remap Esc to CAPS LOCK in Vim?
<p>I saw the vim wiki tips and it says that in order to remap Esc to CAPS LOCK you have to edit the following windows code:</p> <pre><code>REGEDIT4 [HKEY_CURRENT_USER\Keyboard Layout] "Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,01,00,3a,00,00,00,00,00 </code></pre> <p>Is it possible to remap Esc to CAPS LOCK by only adding or modifying lines in the _vimrc?</p>
2,145,086
7
10
null
2010-01-27 06:41:39.367 UTC
10
2020-05-19 14:24:40.067 UTC
2018-03-29 07:11:51.003 UTC
null
2,729,109
null
122,536
null
1
27
windows|vim|capslock|remap
16,982
<p>I recommend that you use AutoHotkey for this.</p> <p>You can do a per-application hotkey change:</p> <pre><code>SetTitleMatchMode,2 #IfWinActive,VIM CAPSLOCK::ESC return #IfWinActive CAPSLOCK::CTRL return </code></pre> <p>This script, for example sets caps to escape in vim, and control everywhere else.</p>
1,957,637
Java: convert int to InetAddress
<p>I have an <code>int</code> which contains an IP address in network byte order, which I would like to convert to an <code>InetAddress</code> object. I see that there is an <code>InetAddress</code> constructor that takes a <code>byte[]</code>, is it necessary to convert the <code>int</code> to a <code>byte[]</code> first, or is there another way?</p>
1,957,670
10
3
null
2009-12-24 09:59:17.807 UTC
8
2020-09-04 13:13:56.573 UTC
null
null
null
null
99,876
null
1
30
java|inetaddress
37,758
<p>This should work:</p> <pre><code>int ipAddress = .... byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray(); InetAddress address = InetAddress.getByAddress(bytes); </code></pre> <p>You might have to swap the order of the byte array, I can't figure out if the array will be generated in the correct order.</p>
1,615,792
Does CodeIgniter automatically prevent SQL injection?
<p>I just inherited a project because the last developer left. The project is built off of Code Igniter. I've never worked with Code Igniter before.</p> <p>I took a quick look at the code and I see database calls in the controller like this:</p> <pre><code>$dbResult = $this-&gt;db-&gt;query("SELECT * FROM users WHERE username = '".$_POST['user_name']."'"); </code></pre> <p>or calls like this:</p> <pre><code>$dbResult = $this-&gt;db-&gt;query("SELECT * FROM users WHERE username = '".$this-&gt;input-&gt;post('username')."'"); </code></pre> <p>Does code igniter automatically sanitize these queries to prevent sql injection?</p>
1,615,868
12
2
null
2009-10-23 20:47:19.413 UTC
23
2020-05-14 10:26:09.813 UTC
2015-07-13 05:15:05.04 UTC
null
4,595,675
null
27,305
null
1
63
codeigniter|sql-injection
89,865
<p>CodeIgniter DOES ESCAPE the variables you pass by when using the <code>$this-&gt;db-&gt;query</code> method. But ONLY when you pass the variables as binds, here's an example:</p> <pre><code>$dbResult = $this-&gt;db-&gt;query("SELECT * FROM users WHERE username = ?", array($this-&gt;input-&gt;post('username'))); </code></pre> <p>Also remember that <code>$_POST</code> shouldn't be preferred over <code>$this-&gt;input-&gt;post</code> since what it does is check if the variables exists to prevent errors.</p>
1,508,490
Erase the current printed console line
<p>How can I erase the current printed console line in C? I am working on a Linux system. For example - </p> <pre><code>printf("hello"); printf("bye"); </code></pre> <p>I want to print bye on the same line in place of hello.</p>
1,508,589
13
1
null
2009-10-02 09:11:42.033 UTC
46
2022-05-02 05:43:06.52 UTC
2017-02-27 23:44:44.86 UTC
null
7,659,995
Peter
null
null
1
90
c|linux|console|erase
190,344
<p>You can use <a href="http://www.climagic.org/mirrors/VT100_Escape_Codes.html" rel="noreferrer">VT100 escape codes</a>. Most terminals, including xterm, are VT100 aware. For erasing a line, this is <code>^[[2K</code>. In C this gives:</p> <pre><code>printf(&quot;\33[2K\r&quot;); </code></pre>
2,264,083
Rounded UIView using CALayers - only some corners - How?
<p>In my application - there are four buttons named as follows:</p> <ul> <li>Top - left</li> <li>Bottom - left</li> <li>Top - right</li> <li>Bottom - right</li> </ul> <p>Above the buttons there is an image view (or a UIView).</p> <p>Now, suppose a user taps on - top - left button. Above image / view should be rounded at that particular corner.</p> <p>I am having some difficulty in applying rounded corners to the UIView.</p> <p>Right now I am using the following code to apply the rounded corners to each view:</p> <pre><code> // imgVUserImg is a image view on IB. imgVUserImg.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"any Url Here"]; CALayer *l = [imgVUserImg layer]; [l setMasksToBounds:YES]; [l setCornerRadius:5.0]; [l setBorderWidth:2.0]; [l setBorderColor:[[UIColor darkGrayColor] CGColor]]; </code></pre> <p>Above code is applying the roundness to each of corners of supplied View. Instead I just wanted to apply roundness to selected corners like - top / top+left / bottom+right etc.</p> <p>Is it possible? How?</p>
2,319,074
14
0
null
2010-02-15 04:55:54.64 UTC
124
2019-10-16 11:28:49.1 UTC
2015-10-03 05:08:01.977 UTC
null
3,830,876
null
140,765
null
1
125
iphone|objective-c|xcode|uiview|calayer
66,837
<p>I used the answer over at <a href="https://stackoverflow.com/questions/510382/how-do-i-create-a-round-cornered-uilabel-on-the-iphone/512402">How do I create a round cornered UILabel on the iPhone?</a> and the code from <a href="https://stackoverflow.com/questions/1031930/how-is-a-rounded-rect-view-with-transparency-done-on-iphone/1031936#1031936">How is a rounded rect view with transparency done on iphone?</a> to make this code. </p> <p>Then I realized I'd answered the wrong question (gave a rounded UILabel instead of UIImage) so I used this code to change it:</p> <p><a href="http://discussions.apple.com/thread.jspa?threadID=1683876" rel="nofollow noreferrer">http://discussions.apple.com/thread.jspa?threadID=1683876</a></p> <p>Make an iPhone project with the View template. In the view controller, add this:</p> <pre><code>- (void)viewDidLoad { CGRect rect = CGRectMake(10, 10, 200, 100); MyView *myView = [[MyView alloc] initWithFrame:rect]; [self.view addSubview:myView]; [super viewDidLoad]; } </code></pre> <p><code>MyView</code> is just a <code>UIImageView</code> subclass:</p> <pre><code>@interface MyView : UIImageView { } </code></pre> <p>I'd never used graphics contexts before, but I managed to hobble together this code. It's missing the code for two of the corners. If you read the code, you can see how I implemented this (by deleting some of the <code>CGContextAddArc</code> calls, and deleting some of the radius values in the code. The code for all corners is there, so use that as a starting point and delete the parts that create corners you don't need. Note that you can make rectangles with 2 or 3 rounded corners too if you want.</p> <p>The code's not perfect, but I'm sure you can tidy it up a little bit. </p> <pre><code>static void addRoundedRectToPath(CGContextRef context, CGRect rect, float radius, int roundedCornerPosition) { // all corners rounded // CGContextMoveToPoint(context, rect.origin.x, rect.origin.y + radius); // CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height - radius); // CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + rect.size.height - radius, // radius, M_PI / 4, M_PI / 2, 1); // CGContextAddLineToPoint(context, rect.origin.x + rect.size.width - radius, // rect.origin.y + rect.size.height); // CGContextAddArc(context, rect.origin.x + rect.size.width - radius, // rect.origin.y + rect.size.height - radius, radius, M_PI / 2, 0.0f, 1); // CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y + radius); // CGContextAddArc(context, rect.origin.x + rect.size.width - radius, rect.origin.y + radius, // radius, 0.0f, -M_PI / 2, 1); // CGContextAddLineToPoint(context, rect.origin.x + radius, rect.origin.y); // CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + radius, radius, // -M_PI / 2, M_PI, 1); // top left if (roundedCornerPosition == 1) { CGContextMoveToPoint(context, rect.origin.x, rect.origin.y + radius); CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height - radius); CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + rect.size.height - radius, radius, M_PI / 4, M_PI / 2, 1); CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y); CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y); } // bottom left if (roundedCornerPosition == 2) { CGContextMoveToPoint(context, rect.origin.x, rect.origin.y); CGContextAddLineToPoint(context, rect.origin.x, rect.origin.y + rect.size.height); CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); CGContextAddLineToPoint(context, rect.origin.x + rect.size.width, rect.origin.y); CGContextAddLineToPoint(context, rect.origin.x + radius, rect.origin.y); CGContextAddArc(context, rect.origin.x + radius, rect.origin.y + radius, radius, -M_PI / 2, M_PI, 1); } // add the other corners here CGContextClosePath(context); CGContextRestoreGState(context); } -(UIImage *)setImage { UIImage *img = [UIImage imageNamed:@"my_image.png"]; int w = img.size.width; int h = img.size.height; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst); CGContextBeginPath(context); CGRect rect = CGRectMake(0, 0, w, h); addRoundedRectToPath(context, rect, 50, 1); CGContextClosePath(context); CGContextClip(context); CGContextDrawImage(context, rect, img.CGImage); CGImageRef imageMasked = CGBitmapContextCreateImage(context); CGContextRelease(context); CGColorSpaceRelease(colorSpace); [img release]; return [UIImage imageWithCGImage:imageMasked]; } </code></pre> <p><a href="http://nevan.net/skitch/skitched-20100224-092237.png" rel="nofollow noreferrer">alt text http://nevan.net/skitch/skitched-20100224-092237.png</a></p> <p>Don't forget that you'll need to get the QuartzCore framework in there for this to work.</p>
8,750,602
Detect when a form has been closed c#
<p>I have a WinForm that I create that shows a prompt with a button. This is a custom WinForm view, as a message box dialog was not sufficient.</p> <p>I have a background worker started and running. I also want to exit the while(<code>aBackgroundWorker.IsBusy</code>) loop if the button on myForm was clicked. </p> <pre><code>//MyProgram.cs using(CustomForm myForm = new CustomForm()) { myForm.Show(theFormOwner); myForm.Refresh(); while(aBackgroundWorker.IsBusy) { Thread.Sleep(1); Application.DoEvents(); } } </code></pre> <p>Right now, in the <code>CustomForm</code> the <code>Button_clicked</code> event, I have </p> <pre><code>//CustomForm.cs private void theButton_Click(object sender, EventArgs e) { this.Close(); } </code></pre> <p>Do I need to add more code to the CustomForm class, or the location where I declare and initialize the form in order to be able to detect a closure?</p>
8,750,673
7
2
null
2012-01-05 22:13:05.637 UTC
2
2017-04-10 20:28:00.553 UTC
2013-12-14 03:45:01.413 UTC
null
321,731
null
834,201
null
1
14
c#|winforms|events|event-handling
58,052
<p>To detect when the form is actually closed, you need to hook the FormClosed event:</p> <pre><code> this.FormClosed += new FormClosedEventHandler(Form1_FormClosed); void Form1_FormClosed(object sender, FormClosedEventArgs e) { // Do something } </code></pre> <p>Alternatively:</p> <pre><code>using(CustomForm myForm = new CustomForm()) { myForm.FormClosed += new FormClosedEventHandler(MyForm_FormClosed); ... } void MyForm_FormClosed(object sender, FormClosedEventArgs e) { // Do something } </code></pre>
8,667,798
Compile failed; see the compiler error output for details
<p>When I tried to compile build.xml file, below error is hitting:</p> <p><strong>BUILD FAILED</strong></p> <pre><code>C:\Users\workspace\testrepo\src\build.xml:36: Compile failed; see the compiler error output for details. at org.apache.tools.ant.taskdefs.Javac.compile(Javac.java:1150) at org.apache.tools.ant.taskdefs.Javac.execute(Javac.java:912) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) at org.apache.tools.ant.Task.perform(Task.java:348) at org.apache.tools.ant.Target.execute(Target.java:390) at org.apache.tools.ant.Target.performTasks(Target.java:411) at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399) at org.apache.tools.ant.Project.executeTarget(Project.java:1368) at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41) at org.eclipse.ant.internal.launching.remote.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:32) at org.apache.tools.ant.Project.executeTargets(Project.java:1251) at org.eclipse.ant.internal.launching.remote.InternalAntRunner.run(InternalAntRunner.java:424) at org.eclipse.ant.internal.launching.remote.InternalAntRunner.main(InternalAntRunner.java:138) </code></pre> <p>Can someone help me ?</p>
8,667,807
5
2
null
2011-12-29 12:18:23.543 UTC
2
2022-05-03 18:03:53.77 UTC
2012-01-03 15:50:04.877 UTC
null
644,073
null
1,121,120
null
1
16
java|ant
110,358
<p>There is a compile error that occurred earlier during the build. Look for that error in the same output log file and try to fix it. </p>
8,392,413
ASP.NET Returning JSON with ASHX
<p>I am creating autocomplete functionality for my website. So far, the javascript part is over. Also, I can get the MembershipUser object of the user that matches.</p> <p>I need to return JSON in the following format:</p> <pre><code>{ query:'Li', suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'], data:['LR','LY','LI','LT'] } </code></pre> <p>and this is the code in ashx:</p> <pre><code>public void ProcessRequest (HttpContext context) { System.Web.Script.Serialization.JavaScriptSerializer JsonSerializer; string query = context.Request.QueryString["query"]; System.Web.Security.MembershipUserCollection Users = System.Web.Security.Membership.GetAllUsers(); context.Response.ContentType = "application/json"; foreach (System.Web.Security.MembershipUser User in Users) { if (User.UserName.StartsWith(query.ToLower())) { context.Response.Write(query + Environment.NewLine); context.Response.Write(User.Email); } } } </code></pre> <p>How can I return the json in the desired format? Thanks.</p>
8,392,963
4
2
null
2011-12-05 21:53:58.79 UTC
7
2014-05-27 12:35:25.093 UTC
null
null
null
null
1,027,620
null
1
30
c#|jquery|asp.net|ajax|json
71,208
<pre><code>context.Response.Write( jsonSerializer.Serialize( new { query = "Li", suggestions = new[] { "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania" }, data = new[] { "LR", "LY", "LI", "LT" } } ) ); </code></pre>
8,537,037
CAST DECIMAL to INT
<p>I'm trying to do this:</p> <pre><code>SELECT CAST(columnName AS INT), moreColumns, etc FROM myTable WHERE ... </code></pre> <p>I've looked at the help FAQs here: <a href="http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html</a> , it says I can do it like <code>CAST(val AS TYPE)</code>, but it's not working.</p> <p>Trying to convert a decimal to int, real value is 223.00 and I want 223</p>
8,537,086
10
2
null
2011-12-16 16:21:20.587 UTC
14
2021-11-26 08:28:51.66 UTC
null
null
null
null
820,750
null
1
91
mysql
219,512
<p>You could try the <a href="http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_floor">FLOOR</a> function like this:</p> <pre><code>SELECT FLOOR(columnName), moreColumns, etc FROM myTable WHERE ... </code></pre> <p>You could also try the <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_format">FORMAT</a> function, provided you know the decimal places can be omitted:</p> <pre><code>SELECT FORMAT(columnName,0), moreColumns, etc FROM myTable WHERE ... </code></pre> <p>You could combine the two functions</p> <pre><code>SELECT FORMAT(FLOOR(columnName),0), moreColumns, etc FROM myTable WHERE ... </code></pre>
46,351,951
ValueError: Cannot run multiple SparkContexts at once in spark with pyspark
<p>i am new in using spark , i try to run this code on pyspark </p> <pre><code>from pyspark import SparkConf, SparkContext import collections conf = SparkConf().setMaster("local").setAppName("RatingsHistogram") sc = SparkContext(conf = conf) </code></pre> <p>but he till me this erore message </p> <pre><code>Using Python version 3.5.2 (default, Jul 5 2016 11:41:13) SparkSession available as 'spark'. &gt;&gt;&gt; from pyspark import SparkConf, SparkContext &gt;&gt;&gt; import collections &gt;&gt;&gt; conf = SparkConf().setMaster("local").setAppName("RatingsHistogram") &gt;&gt;&gt; sc = SparkContext(conf = conf) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\spark\python\pyspark\context.py", line 115, in __init__ SparkContext._ensure_initialized(self, gateway=gateway, conf=conf) File "C:\spark\python\pyspark\context.py", line 275, in _ensure_initialized callsite.function, callsite.file, callsite.linenum)) ValueError: Cannot run multiple SparkContexts at once; existing SparkContext(app=PySparkShell, master=local[*]) created by getOrCreate at C:\spark\bin\..\python\pyspark\shell.py:43 &gt;&gt;&gt; </code></pre> <p>i have version spark 2.1.1 and python 3.5.2 , i search and found it is problem in sc ,he could not read it but no when till why , any one have help here </p>
47,731,444
4
3
null
2017-09-21 19:37:22.167 UTC
5
2022-09-22 12:05:21.143 UTC
null
null
null
null
8,583,033
null
1
31
python-3.x|apache-spark|pyspark
37,282
<p>You can try out this </p> <p><code>sc = SparkContext.getOrCreate();</code></p>
17,782,142
Why doesn't requests.get() return? What is the default timeout that requests.get() uses?
<p>In my script, <code>requests.get</code> never returns:</p> <pre><code>import requests print (&quot;requesting..&quot;) # This call never returns! r = requests.get( &quot;http://www.some-site.example&quot;, proxies = {'http': '222.255.169.74:8080'}, ) print(r.ok) </code></pre> <p>What could be the possible reason(s)? Any remedy? What is the default timeout that <code>get</code> uses?</p>
17,782,541
6
4
null
2013-07-22 07:31:57.747 UTC
22
2022-06-23 10:17:57.253 UTC
2022-06-23 10:17:23.857 UTC
null
1,145,388
null
415,784
null
1
124
python|get|python-requests
138,412
<blockquote> <p>What is the default timeout that get uses?</p> </blockquote> <p>The default timeout is <code>None</code>, which means it'll wait (hang) until the connection is closed.</p> <p>Just <a href="https://requests.readthedocs.io/en/latest/user/advanced/#timeouts" rel="noreferrer">specify a timeout value</a>, like this:</p> <pre><code>r = requests.get( 'http://www.example.com', proxies={'http': '222.255.169.74:8080'}, timeout=5 ) </code></pre>
18,103,715
Navigation bar appear over the views with new iOS7 SDK
<pre><code>CGRect cgRect1 = [[UIScreen mainScreen] applicationFrame]; UISearchBar *mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, cgRect.size.width, 40)]; mySearchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight ; UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, cgRect.size.width, cgRect.size.height-40)]; myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; [self.view addSubview:mySearchBar]; [self.view addSubview:myTableView]; </code></pre> <p>In the earlier versions it is working correctly. The search bar is appearing below the <code>statusbar</code> and navigation bar. The <code>tableview</code> is appearing below the search bar</p> <p>But when I run this on <code>Xcode 5 sdk iOS 7</code>, the search bar is not visible (I think its placed under the status bar and navigation bar) , and also the navigation bar is appearing over the table view.</p> <p>Will it be fixed with <code>iOS 7</code> stable release ?</p> <p>Or is it the problem of my coding ?</p> <p>Or should we handle it by adding the y <code>(y = statubar height + nav bar height)</code> value for <code>iOS 7</code> ?</p> <p>I recently downloaded Xcode 5 DP to test my apps in iOS 7. The first thing I noticed and confirmed is that my view's bounds is not always resized to account for the status bar and navigation bar.</p> <p>In viewDidLayoutSubviews, I print the view's bounds:</p> <pre><code>{{0, 0}, {320, 568}} </code></pre> <p>This results in my content appearing below the navigation bar and status bar.</p> <p>I know I could account for the height myself by getting the main screen's height, subtracting the status bar's height and navigation bar's height, but that seems like unnecessary extra work.</p> <p>Has anyone else experienced this issue?</p> <p><strong>UPDATE:</strong></p> <p>I've found a solution for this specific problem. Set the navigation bar's translucent property to NO:</p> <pre><code>self.navigationController.navigationBar.translucent = NO; </code></pre> <p>This will fix the view from being framed underneath the navigation bar and status bar.</p> <p>However, I have not found a fix for the case when you want the navigation bar to be translucent. For instance, viewing a photo full screen, I wish to have the navigation bar translucent, and the view to be framed underneath it. That works, but when I toggle showing/hiding the navigation bar, I've experienced even stranger results. The first subview (a <code>UIScrollView</code>) gets its bounds y origin changed every time.</p>
18,103,727
9
1
null
2013-08-07 12:43:36.187 UTC
38
2015-01-19 16:47:07.54 UTC
2013-09-30 12:11:22.407 UTC
user2110287
null
user2110287
null
null
1
114
iphone|ios|objective-c|ipad|ios7
73,748
<p>That’s not entirely true. There has been a new property introduced in iOS 7 that lets you adjust the layout behavior as in previous versions of iOS. Place this piece of code in your view controller, and you should be good to go! The space your navigation bar takes up should be accounted for automatically </p> <pre><code> if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) self.edgesForExtendedLayout = UIRectEdgeNone; </code></pre> <p>You need add the above in your <code>-(void)viewDidLoad</code> method.</p> <p>Note: You should be using the latest GM release of iOS 7 and Xcode 5 now since the API has changed from beta versions.</p>
17,781,472
How to get a subset of a javascript object's properties
<p>Say I have an object:</p> <pre><code>elmo = { color: 'red', annoying: true, height: 'unknown', meta: { one: '1', two: '2'} }; </code></pre> <p>I want to make a new object with a subset of its properties.</p> <pre><code> // pseudo code subset = elmo.slice('color', 'height') //=&gt; { color: 'red', height: 'unknown' } </code></pre> <p>How may I achieve this?</p>
39,333,479
35
6
null
2013-07-22 06:47:20.59 UTC
202
2022-07-20 16:34:05.533 UTC
2021-04-14 09:49:40.38 UTC
null
9,205,413
null
80,559
null
1
702
javascript|object
437,782
<p>Using Object Destructuring and Property Shorthand</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const object = { a: 5, b: 6, c: 7 }; const picked = (({ a, c }) =&gt; ({ a, c }))(object); console.log(picked); // { a: 5, c: 7 }</code></pre> </div> </div> </p> <hr> <p>From Philipp Kewisch:</p> <blockquote> <p>This is really just an anonymous function being called instantly. All of this can be found on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noreferrer">Destructuring Assignment</a> page on MDN. Here is an expanded form</p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let unwrap = ({a, c}) =&gt; ({a, c}); let unwrap2 = function({a, c}) { return { a, c }; }; let picked = unwrap({ a: 5, b: 6, c: 7 }); let picked2 = unwrap2({a: 5, b: 6, c: 7}) console.log(picked) console.log(picked2)</code></pre> </div> </div> </p>
42,123,382
Import module from root path in TypeScript
<p>Let's suppose I've a project, and its main source directory is:</p> <pre><code>C:\product\src </code></pre> <p>Based on this directory, every import path would be relative to it. I.e., suppose:</p> <pre><code>// Current script: C:\product\src\com\name\product\blah.ts import { thing } from '/com/name/product/thing'; </code></pre> <p>same as:</p> <pre><code>// Current script: C:\product\src\com\name\product\blah.ts import { thing } from '../../../com/name/product/thing'; </code></pre> <p>My entry compilation file would be at:</p> <pre><code>C:\product\src </code></pre> <p>for instance. So, is there a way to specify this such entry path (<code>C:\product\src</code>, for example) at the compiler options? I need to specify this in the <code>tsconfig.json</code> file, because I'll use webpack.</p> <p>I've tried my above example, but TypeScript says the requested module cannot be found:</p> <pre><code>// Current script: A.ts import { B } from '/com/B'; // Current script: B.ts export const B = 0; </code></pre> <p>My tsconfig.json file (inside another project, but both similiar):</p> <pre><code>{ "compilerOptions": { "module": "commonjs", "noImplicitReturns": true, "noImplicitThis": true, "noUnusedLocals": true, "preserveConstEnums": true, "removeComments": true, "sourceMap": true, "strictNullChecks": true, "target": "ES6" }, "include": [ "./src/**/*.ts", "./src/**/*.d.ts" ] } </code></pre>
42,195,257
5
4
null
2017-02-08 20:53:31.913 UTC
3
2021-02-27 22:53:26.187 UTC
2017-02-13 09:55:37.933 UTC
user5066707
null
user7536774
null
null
1
31
typescript|typescript2.0|typescript1.8|typescript2.1|typescript2.2
58,430
<p>(Re-posting my answer to avoid puppy-socket.)</p> <p>Using the <a href="https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url" rel="noreferrer"><code>compilerOptions.baseUrl</code></a> property I was able to do the below import. This allowed me to have a complete root-to-expected-path, which helps my code maintainance, and works in any file, independently of the current folder. The below examples will have the src folder of my project as the modules root.</p> <p>Important advice: this baseUrl property doesn't affect the entry webpack file (at least for me?), so separate a main file inside the src folder with this example, and run it from the entry (i.e., <code>import { Main } from './src/Main'; new Main;</code>), only once.</p> <pre><code>// browser: directory inside src; // * net: A TS file. import { URLRequest } from 'browser/net'; </code></pre> <p><strong>tsconfig.json</strong> example:</p> <pre><code>{ "compilerOptions": { "baseUrl": "./src", "module": "commonjs", "noImplicitReturns": true, "noImplicitThis": true, "noUnusedLocals": true, "preserveConstEnums": true, "removeComments": true, "sourceMap": true, "strictNullChecks": true, "target": "ES6" }, "include": [ "./src/**/*.ts", "./src/**/*.d.ts" ] } </code></pre> <p>However, it won't directly work with webpack. The same thing must be done at the webpack options. This is how it worked in webpack 2:</p> <pre><code>module.exports = { ... , resolve: { ... , modules: [ path.join(__dirname, './src') ] } } </code></pre>
6,830,904
Java: tutorials/explanations of jsr166y Phaser
<p><a href="https://stackoverflow.com/questions/1148125/resources-on-the-upcoming-fork-join-framework">This question</a> was asked two years ago, but the resources it mentions are either not very helpful (IMHO) or links are no longer valid.</p> <p>There must be some good tutorials out there to understand <a href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/Phaser.html" rel="nofollow noreferrer"><code>Phaser</code></a>. I've read the javadoc, but my eyes glaze over, since in order to really understand the javadoc you kind of have to know how these classes are supposed to be used.</p> <p>Anyone have any suggestions?</p>
6,831,171
3
1
null
2011-07-26 13:41:46.957 UTC
11
2015-05-08 20:32:38.96 UTC
2017-05-23 12:17:55.067 UTC
null
-1
null
44,330
null
1
16
java|concurrency|phaser
5,889
<p>For Phaser I have answered a few questions. Seeing them may help in understanding their applications. They are linked at the bottom. But to understand what the Phaser does and why its useful its important to know what it solves. </p> <p>Here are attributes of a CountdownLatch and CyclicBarrier</p> <p>Note: </p> <ul> <li>Number of parties is another way of saying # of different threads</li> <li>Not Reusable means you will have to create a new instance of the barrier before reusing</li> <li>A barrier is advanceable if a thread can arrive and continue doing work without waiting for others or can wait for all threads to complete</li> </ul> <p><strong><em>CountdownLatch</em></strong></p> <ul> <li>Fixed number of parties</li> <li>Not resuable </li> <li>Advanceable (look at <code>latch.countDown();</code> <strong>advanceable</strong> <code>latch.await();</code> <strong>must wait</strong> )</li> </ul> <p><strong><em>CyclicBarrier</em></strong></p> <ul> <li>Fixed number of parties</li> <li>Reusable</li> <li>Not advanceable</li> </ul> <p>So the CountdownLatch is not reusable, you must create a new instance each time, but is avanceable. CylicBarrier can be re used but all threads must wait for each party to arrive at the barrier.</p> <p><strong><em>Phaser</em></strong></p> <ul> <li>Dynamic number of parties</li> <li>Reusable</li> <li>Advanceable</li> </ul> <p>When a thread wants to be known to the Phaser they invoke <code>phaser.register()</code> when the thread arrives at the barrier they invoke <code>phaser.arrive()</code> <strong>and here is where it is advanceable</strong>. If the thread wants to await for all registered tasks to complete <code>phaser.arriveAndAwaitAdvance()</code></p> <p>There is also the concept of a phase in which threads can wait on a completion of a other operations that may have not completed. Once all threads arrive at the phaser's barrier a new phase is created (an increment of one). </p> <p>You can take a look at my other answers, maybe it will help:</p> <p><a href="https://stackoverflow.com/questions/4958330/java-executorservice-awaittermination-of-all-recursively-created-tasks/4958476#4958476">Java ExecutorService: awaitTermination of all recursively created tasks</a></p> <p><a href="https://stackoverflow.com/questions/1636194/flexible-countdownlatch/1637030#1637030">Flexible CountDownLatch?</a></p>
35,970,727
Use of variables like %{buildDir} in QtCreator kit settings in Qt5
<p>In <a href="http://doc.qt.io/qtcreator/creator-run-settings.html" rel="noreferrer">this documentation</a> (under section "Specifying a Custom Executable to Run") I noticed that there is mention of what looks like a variable <code>%{buildDir}</code> in the field "Working directory".</p> <p><a href="https://i.stack.imgur.com/dShAh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dShAh.png" alt="enter image description here"></a></p> <p>I have struggled for a while now to find documentation for this feature. I would like to know first of all <strong>is there documentation for this somewhere?</strong>.</p> <p>Secondary questions: </p> <ul> <li>What other variables are available?</li> <li>In which fields can they be used?</li> <li>Can I access variables that I created in my project's <code>.pro</code> file?</li> <li>Are there any other eval features or is this mechanism limited to variables?</li> </ul> <p>Thanks!</p>
35,982,389
2
5
null
2016-03-13 13:20:30.813 UTC
8
2021-02-12 15:31:11.29 UTC
null
null
null
null
1,035,897
null
1
22
qt|variables|qt5|qt-creator|eval
9,584
<p>As mentioned in the comments there is a "variables" button... supposedly for use all over the qt environment. However I have only found it available in obscure places that are not very useful!</p> <p>However, you can at least get the list of vars from these places and use them where you actually need them. To find this, navigate to:</p> <ul> <li>Tools (menu) --> Options --> Environment (tab) --> External Tools</li> <li>Click "Update Translations..."</li> <li>Click inside "Working Directory.." and you should see a "AB->" icon in colour to the right.</li> <li>Click the icon for your list of vars.</li> </ul> <p>You will notice that the style is a little different then <code>%{BuildDir}</code> but I believe the equivalent is <code>%{CurrentProject:BuildPath}</code> - You can see on the second screen shot I have right clicked and it asks you what you want to insert (the variable, or the value of the variable).</p> <p>Annoyingly I could not figure out how to copy / paste the whole list as it is single line click only... maybe someone more clever can figure that out and we can stick that list in some Qt wiki :o</p> <p>Here are the screen shots... Notice in screen shot 1 the little icon at the right side of "Working Directory" text-edit box.</p> <p><a href="https://i.stack.imgur.com/QsaEG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QsaEG.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/AbaEQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AbaEQ.png" alt="enter image description here"></a></p>
23,523,869
Is there any way to define flags for cabal dependencies?
<p>I recently ran into a Cabal issue that I only managed to solve by manually installing <a href="http://hackage.haskell.org/package/transformers-compat" rel="noreferrer"><code>transformers-compat</code></a> with the <code>-f transformers3</code> flag in my cabal sandbox before running <code>cabal install</code> for my project.</p> <p>Is there any way to indicate in my application's <code>.cabal</code> file that I depend on a library so that it is built with the specific build flag?</p>
35,123,917
6
2
null
2014-05-07 16:58:07.877 UTC
5
2021-12-06 11:16:52.6 UTC
2019-02-17 04:42:32.097 UTC
null
402,884
null
572,606
null
1
34
haskell|cabal
4,506
<p>You <strong>cannot</strong> do this with Cabal.</p> <p>One way to do this is to use <a href="http://docs.haskellstack.org/en/stable/README.html" rel="nofollow noreferrer">Stack</a>. Edit your <code>stack.yaml</code> to include</p> <pre><code>flags: transformers-compat: transformers3: true </code></pre> <p>See also the section on <a href="http://docs.haskellstack.org/en/stable/yaml_configuration.html#flags" rel="nofollow noreferrer">flags</a>.</p>
15,506,402
How to copy files from server to Dropbox using PHP?
<p>I think I may have found a PHP program to upload files from a specific folder onto my Dropbox account. The full solution can be found <a href="http://www.ryandiver.com/wordpress/2013/03/08/website-backup-to-dropbox/" rel="nofollow">here</a>.</p> <p>The code seems to work because files and folders a like are being uploaded. However, I don't want the files on my server to be compressed beforehand: I want to copy all files with the files and folders within.</p> <p>How can the code be modified please? All I want is to copy a specific directory called uploads from my server to dropbox. After modifying the code I managed to arrive at this code:</p> <pre><code> &lt;?php // Set the timezone so filenames are correct date_default_timezone_set('Europe/London'); // Dropbox username/password $dropbox_email='[email protected]'; $dropbox_pass='password'; // Filenames for backup files $backup_files = "files_" . date("Y.m.d-h.i.s_l") . '.zip'; // File to backup $siteroot = "/site/home/public_html/website/parent/child/uploads/"; // Backup all files in public_html apart from the gz system("zip -r $backup_files $siteroot"); include("DropboxUploader.php"); $uploader = new DropboxUploader($dropbox_email, $dropbox_pass); $uploader-&gt;upload($backup_files,'Backup/Files/'); system("rm $backup_files"); ?&gt; </code></pre> <p><strong>Actual Solution</strong> Special thanks to Alireza Noori, halfer and everyone else.</p> <pre><code>&lt;?php // Set the timezone so filenames are correct date_default_timezone_set('Europe/London'); // Backup all files in public_html apart from the gz $siteroot = "/path/to/backup"; $dropbox_email='dropbox@email'; //Dropbox username $dropbox_pass='pass'; // Dropbox password include("DropboxUploader.php"); $uploader = new DropboxUploader($dropbox_email, $dropbox_pass); function FolderToDropbox($dir, $dropbox_link){ $dropbox_folder = 'FolderInDropboxRoot/'; $files = scandir($dir); foreach($files as $item){ if($item != '.' &amp;&amp; $item != '..'){ if(is_dir($dir.'/'.$item)) FolderToDropbox($dir.'/'.$item,$dropbox_link); else if(is_file($dir.'/'.$item)) { $clean_dir = str_replace("/path/to/backup", "", $dir); $dropbox_link-&gt;upload($dir.'/'.$item,$dropbox_folder.$clean_dir.'/'); } } } } FolderToDropbox($siteroot,$uploader); ?&gt; </code></pre>
15,512,868
3
5
null
2013-03-19 17:27:23.24 UTC
9
2013-03-21 21:52:57.837 UTC
2013-03-21 21:52:57.837 UTC
null
2,159,719
null
2,159,719
null
1
6
php|dropbox-php
7,197
<p>What @halfer is suggesting is this (I just modified your potential solution based on his idea) so he should take credit:</p> <pre><code>&lt;?php function uploadx($dirtocopy, $dropboxdir, $uploader){ if ($handle = opendir($dirtocopy)) { while (false !== ($entry = readdir($handle))) { if ($entry != "." &amp;&amp; $entry != "..") { if(is_dir($entry)){ uploadx($dirtocopy.$entry.'/', $dropboxdir.$entry.'/', $uploader); } else { $uploader-&gt;upload($dirtocopy.$entry, $dropboxdir.$entry); } } } closedir($handle); } } // Dropbox username/password $dropbox_email='[email protected]'; $dropbox_pass='password'; // File to backup $siteroot = "./"; include("DropboxUploader.php"); $uploader = new DropboxUploader($dropbox_email, $dropbox_pass); uploadx($siteroot, 'Backup/Files/', $uploader); ?&gt; </code></pre> <p>BTW, the function above is from here: <a href="https://stackoverflow.com/questions/15356766/how-to-backup-files-from-a-specific-directory-to-dropbox-using-php-only">How to backup files from a specific directory to Dropbox using PHP only?</a></p>
5,484,125
Passing value to a HREF in a Razor view in ASP.Net MVC3
<pre><code> &lt;a href="@(Html.MyActionHref(controllerName: "MyController", actionName: "MyAction"))"&gt; </code></pre> <p>The above line generates a hyperlink for Razor view. The html helper method MyActionHref() creates the link. On clicking the link it calls an action method from controller. Now suppose the action controller method which this link calls is parameterized i.e.<br> <code>public ActionResult MyAction(string myParams){}</code><br> (The html helper method MyActionHref() is even overloaded to accept three parameters accordingly.)</p> <p><strong>How this additional parameter can be passed to the controller action method from the model?</strong><br> Say,</p> <pre><code>&lt;a href="@(Html.MyActionHref(controllerName: "MyController", actionName: "MyAction",params: new {....} }))"&gt; </code></pre> <p>Any suggestions?</p>
5,484,167
2
0
null
2011-03-30 08:53:56.303 UTC
2
2011-03-30 08:58:57.37 UTC
null
null
null
null
106,245
null
1
4
asp.net-mvc|asp.net-mvc-3|razor
43,586
<p>Why are you using such helper when you can simply:</p> <pre><code>@Html.ActionLink( "some text", "MyAction", "MyController", new { myParams = "Hello" }, null ) </code></pre> <p>which will generate the proper anchor tag:</p> <pre><code> &lt;a href="/MyController/MyAction?myParams=Hello"&gt;some text&lt;/a&gt; </code></pre>
178,738
OnClick in Excel VBA
<p>Is there a way to catch a click on a cell in VBA with Excel? I am not referring to the <code>Worksheet_SelectionChange</code> event, as that will not trigger multiple times if the cell is clicked multiple times. <code>BeforeDoubleClick</code> does not solve my problem either, as I do not want to require the user to double click that frequently.</p> <p>My current solution does work with the <code>SelectionChange</code> event, but it appears to require the use of global variables and other suboptimal coding practices. It also seems prone to error.</p>
181,698
7
0
null
2008-10-07 14:34:13.723 UTC
7
2020-04-23 01:22:31.85 UTC
2019-12-18 09:53:07.657 UTC
Mark Biek
12,002
haslo
12,002
null
1
24
vba|excel
133,866
<p>Clearly, there is no perfect answer. However, if you want to allow the user to </p> <ol> <li>select certain cells </li> <li>allow them to change those cells, and</li> <li>trap each click,even repeated clicks on the same cell,</li> </ol> <p>then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event.</p> <p>One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own. </p> <p>If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows </p> <pre><code>Private Sub Worksheet_SelectionChange(ByVal Target As Range) 'prevent Select event triggering again when we extend the selection below Application.EnableEvents = False Target.Resize(1, 2).Select Application.EnableEvents = True End Sub </code></pre>
145,803
Targeting both 32bit and 64bit with Visual Studio in same solution/project
<p>I have a little dilemma on how to set up my visual studio builds for multi-targeting.</p> <p>Background: c# .NET v2.0 with p/invoking into 3rd party 32 bit DLL's, SQL compact v3.5 SP1, with a Setup project. Right now, the platform target is set to x86 so it can be run on Windows x64.</p> <p>The 3rd party company has just released 64 bit versions of their DLL's and I want to build a dedicated 64bit program.</p> <p>This raises some questions which I haven't got the answers to yet. I want to have the exact same code base. I must build with references to either the 32bit set of DLL's or 64bit DLL's. (Both 3rd party and SQL Server Compact)</p> <p>Can this be solved with 2 new sets of configurations (Debug64 and Release64) ?</p> <p>Must I create 2 separate setup projects(std. visual studio projects, no Wix or any other utility), or can this be solved within the same .msi?</p> <p>Any ideas and/or recommendations would be welcomed.</p>
145,903
8
1
null
2008-09-28 13:05:41.977 UTC
70
2020-04-06 05:34:54.35 UTC
2012-07-27 06:30:58.257 UTC
null
3,584
Magnus Johansson
3,584
null
1
113
.net|visual-studio|64-bit|x86-64
106,317
<p>Yes, you can target both x86 and x64 with the same code base in the same project. In general, things will Just Work if you create the right solution configurations in VS.NET (although P/Invoke to entirely unmanaged DLLs will most likely require some conditional code): the items that I found to require special attention are:</p> <ul> <li>References to outside managed assemblies with the same name but their own specific bitness (this also applies to COM interop assemblies)</li> <li>The MSI package (which, as has already been noted, will need to target either x86 or x64)</li> <li>Any custom .NET Installer Class-based actions in your MSI package</li> </ul> <p>The assembly reference issue can't be solved entirely within VS.NET, as it will only allow you to add a reference with a given name to a project once. To work around this, edit your project file manually (in VS, right-click your project file in the Solution Explorer, select Unload Project, then right-click again and select Edit). After adding a reference to, say, the x86 version of an assembly, your project file will contain something like:</p> <pre><code>&lt;Reference Include="Filename, ..., processorArchitecture=x86"&gt; &lt;HintPath&gt;C:\path\to\x86\DLL&lt;/HintPath&gt; &lt;/Reference&gt; </code></pre> <p>Wrap that Reference tag inside an ItemGroup tag indicating the solution configuration it applies to, e.g:</p> <pre><code>&lt;ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "&gt; &lt;Reference ...&gt;....&lt;/Reference&gt; &lt;/ItemGroup&gt; </code></pre> <p>Then, copy and paste the entire ItemGroup tag, and edit it to contain the details of your 64-bit DLL, e.g.:</p> <pre><code>&lt;ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' "&gt; &lt;Reference Include="Filename, ..., processorArchitecture=AMD64"&gt; &lt;HintPath&gt;C:\path\to\x64\DLL&lt;/HintPath&gt; &lt;/Reference&gt; &lt;/ItemGroup&gt; </code></pre> <p>After reloading your project in VS.NET, the Assembly Reference dialog will be a bit confused by these changes, and you may encounter some warnings about assemblies with the wrong target processor, but all your builds will work just fine.</p> <p>Solving the MSI issue is up next, and unfortunately this <i>will</i> require a non-VS.NET tool: I prefer Caphyon's <a href="http://www.advancedinstaller.com/" rel="noreferrer">Advanced Installer</a> for that purpose, as it pulls off the basic trick involved (create a common MSI, as well as 32-bit and 64-bit specific MSIs, and use an .EXE setup launcher to extract the right version and do the required fixups at runtime) very, very well. </p> <p>You can probably achieve the same results using other tools or the <a href="http://wix.sourceforge.net/" rel="noreferrer">Windows Installer XML (WiX) toolset</a>, but Advanced Installer makes things so easy (and is quite affordable at that) that I've never really looked at alternatives.</p> <p>One thing you <i>may</i> still require WiX for though, even when using Advanced Installer, is for your .NET Installer Class custom actions. Although it's trivial to specify certain actions that should only run on certain platforms (using the VersionNT64 and NOT VersionNT64 execution conditions, respectively), the built-in AI custom actions will be executed using the 32-bit Framework, even on 64-bit machines.</p> <p>This may be fixed in a future release, but for now (or when using a different tool to create your MSIs that has the same issue), you can use WiX 3.0's managed custom action support to create action DLLs with the proper bitness that will be executed using the corresponding Framework.</p> <hr> <p>Edit: as of version 8.1.2, Advanced Installer correctly supports 64-bit custom actions. Since my original answer, its price has increased quite a bit, unfortunately, even though it's still extremely good value when compared to InstallShield and its ilk...</p> <hr> <p>Edit: If your DLLs are registered in the GAC, you can also use the standard reference tags this way (SQLite as an example):</p> <pre><code>&lt;ItemGroup Condition="'$(Platform)' == 'x86'"&gt; &lt;Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86" /&gt; &lt;/ItemGroup&gt; &lt;ItemGroup Condition="'$(Platform)' == 'x64'"&gt; &lt;Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64" /&gt; &lt;/ItemGroup&gt; </code></pre> <p>The condition is also reduced down to all build types, release or debug, and just specifies the processor architecture.</p>
1,109,307
How to transfer files from one computer to another over the network using Java?
<p>I need a simple application, preferably a cross-platform one, that enables sending of files between two computers. </p> <p>It just need to accept and send the files, and show a progress bar. What applications could I use or how could I write one?</p>
1,109,406
9
1
null
2009-07-10 12:44:28.273 UTC
7
2009-10-02 17:45:45.06 UTC
2009-07-10 20:26:02.79 UTC
null
2,598
user95947
null
null
1
12
java|file|networking
45,104
<p><strong>Sending and Receiving Files</strong></p> <p>The sending and receiving of a file basically breaks down to two simple pieces of code.</p> <p>Recieving code:</p> <pre><code>ServerSocket serverSoc = new ServerSocket(LISTENING_PORT); Socket connection = serverSoc.accept(); // code to read from connection.getInputStream(); </code></pre> <p>Sending code:</p> <pre><code>File fileToSend; InputStream fileStream = new BufferedInputStream(fileToSend); Socket connection = new Socket(CONNECTION_ADDRESS, LISTENING_PORT); OutputStream out = connection.getOutputStream(); // my method to move data from the file inputstream to the output stream of the socket copyStream(fileStream, out); </code></pre> <p>The sending piece of code will be ran on the computer that is sending the code when they want to send a file.</p> <p>The receiving code needs to be put inside a loop, so that everytime someone wants to connect to the server, the server can handle the request and then go back to waiting on serverSoc.accept().</p> <p>To allow sending files between both computers, each computer will need to run the server (receiving code) to listen for incoming files, and they will both need to run the sending code when they want to send a file.</p> <p><strong>Progress Bar</strong></p> <p>The <code>JProgressBar</code> in Swing is easy enough to use. However, getting it to work properly and show current progress of the file transfer is slightly more difficult.</p> <p>To get a progress bar to show up on a form only involves dropping it onto a <code>JFrame</code> and perhaps setting <code>setIndeterminate(false)</code> so hat it shows that your program is working. </p> <p>To implement a progress bar correctly you will need to create your own implementation of a <a href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html" rel="noreferrer"><code>SwingWorker</code></a>. The Java tutorials have a good example of this in their<a href="http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html" rel="noreferrer">lesson in concurrency</a>.</p> <p>This is a fairly difficult issue on its's own though. I would recommend asking this in it's own question if you need more help with it.</p>
790,932
How to wrap text in LaTeX tables?
<p>I am creating a report in LaTeX which involves a few tables. I'm stuck on that as my cell data in the table is exceeding the width of the page. Can I somehow wrap the text so that it falls into the next line in the same cell of the table?</p> <p>Is it somehow related to the table's width? But as it's overshooting the page's width, will it make a difference?</p>
790,944
9
1
null
2009-04-26 14:26:47.683 UTC
135
2022-03-05 16:28:37.097 UTC
2019-04-24 12:18:26.807 UTC
null
10,607,772
null
68,920
null
1
596
text|latex|word-wrap
756,860
<p>Use p{width} for your column specifiers instead of l/r/c.</p> <pre><code>\begin{tabular}{|p{1cm}|p{3cm}|} This text will be wrapped &amp; Some more text \\ \end{tabular} </code></pre> <hr /> <p>EDIT: (based on the comments)</p> <pre><code>\begin{table}[ht] \centering \begin{tabular}{p{0.35\linewidth} | p{0.6\linewidth}} Column 1 &amp; Column2 \\ \hline This text will be wrapped &amp; Some more text \\ Some text here &amp; This text maybe wrapped here if its tooooo long \\ \end{tabular} \caption{Caption} \label{tab:my_label} \end{table} </code></pre> <p>we get:</p> <p><a href="https://i.stack.imgur.com/XHn2Z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XHn2Z.png" alt="enter image description here" /></a></p>
72,151
ORA-00933: SQL command not properly ended
<p>I'm using OLEDB provider for ADO.Net connecting to an Oracle database. In my loop, I am doing an insert:</p> <pre><code>insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '51', TO_DATE('03/23/2002', 'MM/DD/YYYY'), 0.000000, 0.000) </code></pre> <p>The first insert succeeds but the second one gives an error:</p> <pre><code>ORA-00933: SQL command not properly ended </code></pre> <p>What am I doing wrong?</p>
72,179
10
1
null
2008-09-16 13:27:53.823 UTC
1
2018-02-01 19:03:45.577 UTC
2011-10-18 15:52:44.177 UTC
John Sibly
321,731
null
10,589
null
1
5
sql|oracle|ora-00933
58,197
<p>To me it seems you're missing a <code>;</code> between the two statements:<br> <code>insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)</code><br> <strong><code>;</code></strong><br> <code>insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '51', TO_DATE('03/23/2002', 'MM/DD/YYYY'), 0.000000, 0.000)</code><br> <strong><code>;</code></strong><br> Try adding the <code>;</code> and let us know.</p>
884,007
Correct way to close nested streams and writers in Java
<p><strong>Note:</strong> This question and most of its answers date to before the release of Java 7. Java 7 provides <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="noreferrer">Automatic Resource Management</a> functionality for doing this easilly. If you are using Java 7 or later you should advance to <a href="https://stackoverflow.com/a/21723193">the answer of Ross Johnson</a>.</p> <hr> <p>What is considered the best, most comprehensive way to close nested streams in Java? For example, consider the setup:</p> <pre><code>FileOutputStream fos = new FileOutputStream(...) BufferedOS bos = new BufferedOS(fos); ObjectOutputStream oos = new ObjectOutputStream(bos); </code></pre> <p>I understand the close operation needs to be insured (probably by using a finally clause). What I wonder about is, is it necessary to explicitly make sure the nested streams are closed, or is it enough to just make sure to close the outer stream (oos)?</p> <p>One thing I notice, at least dealing with this specific example, is that the inner streams only seem to throw FileNotFoundExceptions. Which would seem to imply that there's not technically a need to worry about closing them if they fail.</p> <p>Here's what a colleague wrote:</p> <hr> <p>Technically, if it were implemented right, closing the outermost stream (oos) should be enough. But the implementation seems flawed.</p> <p>Example: BufferedOutputStream inherits close() from FilterOutputStream, which defines it as:</p> <pre><code> 155 public void close() throws IOException { 156 try { 157 flush(); 158 } catch (IOException ignored) { 159 } 160 out.close(); 161 } </code></pre> <p>However, if flush() throws a runtime exception for some reason, then out.close() will never be called. So it seems "safest" (but ugly) to mostly worry about closing FOS, which is keeping the file open.</p> <hr> <p>What is considered to be the hands-down best, when-you-absolutely-need-to-be-sure, approach to closing nested streams?</p> <p>And are there any official Java/Sun docs that deal with this in fine detail?</p>
884,182
10
1
null
2009-05-19 17:14:31.257 UTC
29
2016-07-08 10:15:29.437 UTC
2017-05-23 11:33:26.74 UTC
null
-1
null
109,474
null
1
96
java|java-io
46,522
<p>I usually do the following. First, define a template-method based class to deal with the try/catch mess</p> <pre><code>import java.io.Closeable; import java.io.IOException; import java.util.LinkedList; import java.util.List; public abstract class AutoFileCloser { // the core action code that the implementer wants to run protected abstract void doWork() throws Throwable; // track a list of closeable thingies to close when finished private List&lt;Closeable&gt; closeables_ = new LinkedList&lt;Closeable&gt;(); // give the implementer a way to track things to close // assumes this is called in order for nested closeables, // inner-most to outer-most protected final &lt;T extends Closeable&gt; T autoClose(T closeable) { closeables_.add(0, closeable); return closeable; } public AutoFileCloser() { // a variable to track a "meaningful" exception, in case // a close() throws an exception Throwable pending = null; try { doWork(); // do the real work } catch (Throwable throwable) { pending = throwable; } finally { // close the watched streams for (Closeable closeable : closeables_) { if (closeable != null) { try { closeable.close(); } catch (Throwable throwable) { if (pending == null) { pending = throwable; } } } } // if we had a pending exception, rethrow it // this is necessary b/c the close can throw an // exception, which would remove the pending // status of any exception thrown in the try block if (pending != null) { if (pending instanceof RuntimeException) { throw (RuntimeException) pending; } else { throw new RuntimeException(pending); } } } } } </code></pre> <p>Note the "pending" exception -- this takes care of the case where an exception thrown during close would mask an exception we might really care about.</p> <p>The finally tries to close from the outside of any decorated stream first, so if you had a BufferedWriter wrapping a FileWriter, we try to close the BuffereredWriter first, and if that fails, still try to close the FileWriter itself. (Note that the definition of Closeable calls for close() to ignore the call if the stream is already closed)</p> <p>You can use the above class as follows:</p> <pre><code>try { // ... new AutoFileCloser() { @Override protected void doWork() throws Throwable { // declare variables for the readers and "watch" them FileReader fileReader = autoClose(fileReader = new FileReader("somefile")); BufferedReader bufferedReader = autoClose(bufferedReader = new BufferedReader(fileReader)); // ... do something with bufferedReader // if you need more than one reader or writer FileWriter fileWriter = autoClose(fileWriter = new FileWriter("someOtherFile")); BufferedWriter bufferedWriter = autoClose(bufferedWriter = new BufferedWriter(fileWriter)); // ... do something with bufferedWriter } }; // .. other logic, maybe more AutoFileClosers } catch (RuntimeException e) { // report or log the exception } </code></pre> <p>Using this approach you never have to worry about the try/catch/finally to deal with closing files again.</p> <p>If this is too heavy for your use, at least think about following the try/catch and the "pending" variable approach it uses.</p>
499,137
How can I force a long string without any blank to be wrapped?
<p>I have a long string (a DNA sequence). It does not contain any whitespace character.</p> <p>For example:</p> <pre><code>ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTCGATGTAGCTAGTAGCATGTAGTGA </code></pre> <p>What would be the CSS selector to force this text to be wrapped in a <code>html:textarea</code> or in a <code>xul:textbox</code>?</p>
499,154
16
1
null
2009-01-31 16:44:16.81 UTC
43
2021-12-07 19:01:25.277 UTC
2019-04-24 12:29:14.827 UTC
null
10,607,772
Pierre
58,082
null
1
218
html|css|string|xul|word-wrap
176,755
<p>for block elements:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;textarea style="width:100px; word-wrap:break-word;"&gt; ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC &lt;/textarea&gt;</code></pre> </div> </div> </p> <p>for inline elements:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;span style="width:100px; word-wrap:break-word; display:inline-block;"&gt; ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC &lt;/span&gt;</code></pre> </div> </div> </p>
885,908
while (1) Vs. for (;;) Is there a speed difference?
<p>Long version...</p> <p>A co-worker asserted today after seeing my use of <code>while (1)</code> in a Perl script that <code>for (;;)</code> is faster. I argued that they should be the same hoping that the interpreter would optimize out any differences. I set up a script that would run 1,000,000,000 for loop iterations and the same number of while loops and record the time between. I could find no appreciable difference. My co-worker said that a professor had told him that the <code>while (1)</code> was doing a comparison <code>1 == 1</code> and the <code>for (;;)</code> was not. We repeated the same test with the 100x the number of iterations with C++ and the difference was negligible. It was however a graphic example of how much faster compiled code can be vs. a scripting language.</p> <p>Short version...</p> <p>Is there any reason to prefer a <code>while (1)</code> over a <code>for (;;)</code> if you need an infinite loop to break out of?</p> <p><strong>Note:</strong> If it's not clear from the question. This was purely a fun academic discussion between a couple of friends. I am aware this is not a super important concept that all programmers should agonize over. Thanks for all the great answers I (and I'm sure others) have learned a few things from this discussion.</p> <p><strong>Update:</strong> The aforementioned co-worker weighed in with a response below.</p> <p>Quoted here in case it gets buried.</p> <blockquote> <p>It came from an AMD assembly programmer. He stated that C programmers (the poeple) don't realize that their code has inefficiencies. He said today though, gcc compilers are very good, and put people like him out of business. He said for example, and told me about the <code>while 1</code> vs <code>for(;;)</code>. I use it now out of habit but gcc and especially interpreters will do the same operation (a processor jump) for both these days, since they are optimized.</p> </blockquote>
885,951
20
20
null
2009-05-20 02:34:08.763 UTC
38
2019-01-07 21:42:22.76 UTC
2012-10-16 12:00:02.88 UTC
null
527,702
null
105,170
null
1
164
c++|perl|optimization|performance
59,787
<p>In perl, they result in the same opcodes:</p> <pre><code>$ perl -MO=Concise -e 'for(;;) { print "foo\n" }' a &lt;@&gt; leave[1 ref] vKP/REFC -&gt;(end) 1 &lt;0&gt; enter -&gt;2 2 &lt;;&gt; nextstate(main 2 -e:1) v -&gt;3 9 &lt;2&gt; leaveloop vK/2 -&gt;a 3 &lt;{&gt; enterloop(next-&gt;8 last-&gt;9 redo-&gt;4) v -&gt;4 - &lt;@&gt; lineseq vK -&gt;9 4 &lt;;&gt; nextstate(main 1 -e:1) v -&gt;5 7 &lt;@&gt; print vK -&gt;8 5 &lt;0&gt; pushmark s -&gt;6 6 &lt;$&gt; const[PV "foo\n"] s -&gt;7 8 &lt;0&gt; unstack v -&gt;4 -e syntax OK $ perl -MO=Concise -e 'while(1) { print "foo\n" }' a &lt;@&gt; leave[1 ref] vKP/REFC -&gt;(end) 1 &lt;0&gt; enter -&gt;2 2 &lt;;&gt; nextstate(main 2 -e:1) v -&gt;3 9 &lt;2&gt; leaveloop vK/2 -&gt;a 3 &lt;{&gt; enterloop(next-&gt;8 last-&gt;9 redo-&gt;4) v -&gt;4 - &lt;@&gt; lineseq vK -&gt;9 4 &lt;;&gt; nextstate(main 1 -e:1) v -&gt;5 7 &lt;@&gt; print vK -&gt;8 5 &lt;0&gt; pushmark s -&gt;6 6 &lt;$&gt; const[PV "foo\n"] s -&gt;7 8 &lt;0&gt; unstack v -&gt;4 -e syntax OK </code></pre> <p>Likewise in GCC:</p> <pre><code>#include &lt;stdio.h&gt; void t_while() { while(1) printf("foo\n"); } void t_for() { for(;;) printf("foo\n"); } .file "test.c" .section .rodata .LC0: .string "foo" .text .globl t_while .type t_while, @function t_while: .LFB2: pushq %rbp .LCFI0: movq %rsp, %rbp .LCFI1: .L2: movl $.LC0, %edi call puts jmp .L2 .LFE2: .size t_while, .-t_while .globl t_for .type t_for, @function t_for: .LFB3: pushq %rbp .LCFI2: movq %rsp, %rbp .LCFI3: .L5: movl $.LC0, %edi call puts jmp .L5 .LFE3: .size t_for, .-t_for .section .eh_frame,"a",@progbits .Lframe1: .long .LECIE1-.LSCIE1 .LSCIE1: .long 0x0 .byte 0x1 .string "zR" .uleb128 0x1 .sleb128 -8 .byte 0x10 .uleb128 0x1 .byte 0x3 .byte 0xc .uleb128 0x7 .uleb128 0x8 .byte 0x90 .uleb128 0x1 .align 8 .LECIE1: .LSFDE1: .long .LEFDE1-.LASFDE1 .LASFDE1: .long .LASFDE1-.Lframe1 .long .LFB2 .long .LFE2-.LFB2 .uleb128 0x0 .byte 0x4 .long .LCFI0-.LFB2 .byte 0xe .uleb128 0x10 .byte 0x86 .uleb128 0x2 .byte 0x4 .long .LCFI1-.LCFI0 .byte 0xd .uleb128 0x6 .align 8 .LEFDE1: .LSFDE3: .long .LEFDE3-.LASFDE3 .LASFDE3: .long .LASFDE3-.Lframe1 .long .LFB3 .long .LFE3-.LFB3 .uleb128 0x0 .byte 0x4 .long .LCFI2-.LFB3 .byte 0xe .uleb128 0x10 .byte 0x86 .uleb128 0x2 .byte 0x4 .long .LCFI3-.LCFI2 .byte 0xd .uleb128 0x6 .align 8 .LEFDE3: .ident "GCC: (Ubuntu 4.3.3-5ubuntu4) 4.3.3" .section .note.GNU-stack,"",@progbits </code></pre> <p>So I guess the answer is, they're the same in many compilers. Of course, for some other compilers this may not necessarily be the case, but chances are the code inside of the loop is going to be a few thousand times more expensive than the loop itself anyway, so who cares?</p>
45,325
How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?
<p>Sometimes when I'm editing page or control the .designer files stop being updated with the new controls I'm putting on the page. I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the .designer file. I'm using Visual Studio 2008</p> <p><strong>EDIT:</strong> Sorry I should have noted I've already tried:</p> <ul> <li>Closing &amp; re-opening all the files &amp; Visual Studio</li> <li>Making a change to a runat="server" control on the page</li> <li>Deleting &amp; re-adding the page directive</li> </ul>
45,327
48
7
2013-01-21 06:23:37.473 UTC
2008-09-05 06:21:06.517 UTC
65
2021-04-04 13:21:58.343 UTC
2008-11-02 02:06:26.757 UTC
user3850
null
Glenn Slaven
2,975
null
1
420
asp.net|visual-studio|visual-studio-2008
334,578
<p>If you open the .aspx file and switch between design view and html view and back it will prompt VS to check the controls and add any that are missing to the designer file.</p> <p>In VS2013-15 there is a <strong>Convert to Web Application</strong> command under the <strong>Project</strong> menu. Prior to VS2013 this option was available in the right-click context menu for as(c/p)x files. When this is done you should see that you now have a *.Designer.cs file available and your controls within the Design HTML will be available for your control.</p> <p>PS: This should not be done in debug mode, as not everything is "recompiled" when debugging.</p> <p>Some people have also reported success by (making a backup copy of your .designer.cs file and then) deleting the .designer.cs file. Re-create an empty file with the same name.</p> <p>There are many comments to this answer that add tips on how best to re-create the designer.cs file.</p>
34,855,352
How, in general, does Node.js handle 10,000 concurrent requests?
<p>I understand that Node.js uses a single-thread and an event loop to process requests only processing one at a time (which is non-blocking). But still, how does that work, lets say 10,000 concurrent requests. The event loop will process all the requests? Would not that take too long?</p> <p>I can not understand (yet) how it can be faster than a multi-threaded web server. I understand that multi-threaded web server will be more expensive in resources (memory, CPU), but would not it still be faster? I am probably wrong; please explain how this single-thread is faster in lots of requests, and what it typically does (in high level) when servicing lots of requests like 10,000.</p> <p>And also, will that single-thread scale well with that large amount? Please bear in mind that I am just starting to learn Node.js.</p>
34,857,298
8
7
null
2016-01-18 12:56:56.193 UTC
425
2022-03-16 03:42:59.773 UTC
2019-06-17 11:05:47.9 UTC
null
10,262,805
null
3,591,953
null
1
637
node.js
193,780
<p>If you have to ask this question then you're probably unfamiliar with what most web applications/services do. You're probably thinking that all software do this:</p> <pre><code>user do an action │ v application start processing action └──&gt; loop ... └──&gt; busy processing end loop └──&gt; send result to user </code></pre> <p>However, this is not how web applications, or indeed any application with a database as the back-end, work. Web apps do this:</p> <pre><code>user do an action │ v application start processing action └──&gt; make database request └──&gt; do nothing until request completes request complete └──&gt; send result to user </code></pre> <p>In this scenario, the software spend most of its running time using 0% CPU time waiting for the database to return.</p> <h2>Multithreaded network app:</h2> <p>Multithreaded network apps handle the above workload like this:</p> <pre><code>request ──&gt; spawn thread └──&gt; wait for database request └──&gt; answer request request ──&gt; spawn thread └──&gt; wait for database request └──&gt; answer request request ──&gt; spawn thread └──&gt; wait for database request └──&gt; answer request </code></pre> <p>So the thread spend most of their time using 0% CPU waiting for the database to return data. While doing so they have had to allocate the memory required for a thread which includes a completely separate program stack for each thread etc. Also, they would have to start a thread which while is not as expensive as starting a full process is still not exactly cheap.</p> <h2>Singlethreaded event loop</h2> <p>Since we spend most of our time using 0% CPU, why not run some code when we're not using CPU? That way, each request will still get the same amount of CPU time as multithreaded applications but we don't need to start a thread. So we do this:</p> <pre><code>request ──&gt; make database request request ──&gt; make database request request ──&gt; make database request database request complete ──&gt; send response database request complete ──&gt; send response database request complete ──&gt; send response </code></pre> <p>In practice both approaches return data with roughly the same latency since it's the database response time that dominates the processing.</p> <p>The main advantage here is that we don't need to spawn a new thread so we don't need to do lots and lots of malloc which would slow us down.</p> <h2>Magic, invisible threading</h2> <p>The seemingly mysterious thing is how both the approaches above manage to run workload in "parallel"? The answer is that the database is threaded. So our single-threaded app is actually leveraging the multi-threaded behaviour of another process: the database.</p> <h2>Where singlethreaded approach fails</h2> <p>A singlethreaded app fails big if you need to do lots of CPU calculations before returning the data. Now, I don't mean a for loop processing the database result. That's still mostly O(n). What I mean is things like doing Fourier transform (mp3 encoding for example), ray tracing (3D rendering) etc.</p> <p>Another pitfall of singlethreaded apps is that it will only utilise a single CPU core. So if you have a quad-core server (not uncommon nowdays) you're not using the other 3 cores.</p> <h2>Where multithreaded approach fails</h2> <p>A multithreaded app fails big if you need to allocate lots of RAM per thread. First, the RAM usage itself means you can't handle as many requests as a singlethreaded app. Worse, malloc is slow. Allocating lots and lots of objects (which is common for modern web frameworks) means we can potentially end up being slower than singlethreaded apps. This is where node.js usually win.</p> <p>One use-case that end up making multithreaded worse is when you need to run another scripting language in your thread. First you usually need to malloc the entire runtime for that language, then you need to malloc the variables used by your script.</p> <p>So if you're writing network apps in C or go or java then the overhead of threading will usually not be too bad. If you're writing a C web server to serve PHP or Ruby then it's very easy to write a faster server in javascript or Ruby or Python.</p> <h2>Hybrid approach</h2> <p>Some web servers use a hybrid approach. Nginx and Apache2 for example implement their network processing code as a thread pool of event loops. Each thread runs an event loop simultaneously processing requests single-threaded but requests are load-balanced among multiple threads.</p> <p>Some single-threaded architectures also use a hybrid approach. Instead of launching multiple threads from a single process you can launch multiple applications - for example, 4 node.js servers on a quad-core machine. Then you use a load balancer to spread the workload amongst the processes.</p> <p>In effect the two approaches are technically identical mirror-images of each other.</p>
6,417,558
Modal Dialog not showing on top of other windows
<p>I am using <code>Window.ShowDialog()</code> to open a modal window in my WPF (MVVM) application, but it lets me navigate to other windows using the Windows taskbar (Windows 7).</p> <p>Consider this: I have 3 non-modal windows open in my application. Now One of these opens a modal window using <code>Window.ShowDialog()</code>. I also set <code>Application.MainWindow</code> as the owner of the modal window. This is so because I am using MVVM messaging and the message handler to open a new window is centralized in <code>App.xaml.cs</code>. The window does opens modally - no issues there. However, Windows 7 allows me to swtich to the other application windows from the taskbar. This leads to a situation where the modal window goes behind another window, which I prefer not to have.</p> <p>I can't do anything on other windows as long as I have the modal open, but it would be nice if the modal window always remained on top as long as it's open. Is there a way I can disable taskbar switching when the modal is open? FYI - all open windows launched from the app appear as separate entries on the taskbar.</p> <p>Thanks in advance!</p>
6,417,636
5
2
null
2011-06-20 21:08:44.73 UTC
6
2016-06-29 19:05:12.723 UTC
2015-05-22 04:41:34.59 UTC
null
4,714,970
null
429,954
null
1
27
wpf|showdialog
52,673
<p>There isn't any code to base this off of, but it sounds like you have left off some properties on the <code>Window</code> you've created and expected <a href="http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog.aspx"><code>ShowDialog</code></a> to apply additional "dialog" semantics:</p> <pre><code>Window window = new Window() { Title = "Modal Dialog", ShowInTaskbar = false, // don't show the dialog on the taskbar Topmost = true, // ensure we're Always On Top ResizeMode = ResizeMode.NoResize, // remove excess caption bar buttons Owner = Application.Current.MainWindow, }; window.ShowDialog(); </code></pre>
6,749,369
Oracle DateTime in Where Clause?
<p>I have sql something like this:</p> <pre><code>SELECT EMP_NAME, DEPT FROM EMPLOYEE WHERE TIME_CREATED &gt;= TO_DATE('26/JAN/2011','dd/mon/yyyy') </code></pre> <p>-> This returns 10 rows and TIME_CREATED = '26-JAN-2011'</p> <p>Now when i do this i don't get any rows back,</p> <pre><code>SELECT EMP_NAME, DEPT FROM EMPLOYEE WHERE TIME_CREATED = TO_DATE('26/JAN/2011','dd/mon/yyyy') </code></pre> <p>-> Took the greater than out</p> <p>Any reason why?</p>
6,749,403
5
1
null
2011-07-19 15:03:52.887 UTC
21
2016-05-17 15:37:44.713 UTC
2015-10-30 15:56:01.353 UTC
null
4,865,599
null
245,008
null
1
105
sql|oracle|time|date-arithmetic
534,235
<p>Yes: TIME_CREATED contains a date and a <strong>time</strong>. Use <code>TRUNC</code> to strip the time:</p> <pre><code>SELECT EMP_NAME, DEPT FROM EMPLOYEE WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy') </code></pre> <p><strong>UPDATE:</strong><br> As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column <code>TIME_CREATED</code> if it exists. An alternative approach without this problem is this:</p> <pre><code>SELECT EMP_NAME, DEPT FROM EMPLOYEE WHERE TIME_CREATED &gt;= TO_DATE('26/JAN/2011','dd/mon/yyyy') AND TIME_CREATED &lt; TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1 </code></pre>
6,459,758
parseInt(null, 24) === 23... wait, what?
<p>Alright, so I was messing around with parseInt to see how it handles values not yet initialized and I stumbled upon this gem. The below happens for any radix 24 or above.</p> <pre><code>parseInt(null, 24) === 23 // evaluates to true </code></pre> <p>I tested it in IE, Chrome and Firefox and they all alert true, so I'm thinking it must be in the specification somewhere. A quick Google search didn't give me any results so here I am, hoping someone can explain.</p> <p>I remember listening to a Crockford speech where he was saying <code>typeof null === "object"</code> because of an oversight causing Object and Null to have a near identical type identifier in memory or something along those lines, but I can't find that video now.</p> <p>Try it: <a href="http://jsfiddle.net/robert/txjwP/" rel="noreferrer">http://jsfiddle.net/robert/txjwP/</a></p> <p><strong>Edit</strong> Correction: a higher radix returns different results, 32 returns 785077<br> <strong>Edit 2</strong> From zzzzBov: <code>[24...30]:23, 31:714695, 32:785077, 33:859935, 34:939407, 35:1023631, 36:1112745</code></p> <hr> <p><strong>tl;dr</strong></p> <p>Explain why <code>parseInt(null, 24) === 23</code> is a true statement.</p>
6,459,925
6
11
null
2011-06-23 19:48:18.42 UTC
52
2013-07-05 16:03:16.07 UTC
2013-07-05 16:03:16.07 UTC
null
2,047,725
null
415,668
null
1
228
javascript|parseint
18,991
<p>It's converting <code>null</code> to the string <code>"null"</code> and trying to convert it. For radixes 0 through 23, there are no numerals it can convert, so it returns <code>NaN</code>. At 24, <code>"n"</code>, the 14th letter, is added to the numeral system. At 31, <code>"u"</code>, the 21st letter, is added and the entire string can be decoded. At 37 on there is no longer any valid numeral set that can be generated and NaN is returned.</p> <pre><code>js&gt; parseInt(null, 36) 1112745 &gt;&gt;&gt; reduce(lambda x, y: x * 36 + y, [(string.digits + string.lowercase).index(x) for x in 'null']) 1112745 </code></pre>
15,954,650
Python- how do I use re to match a whole string
<p>I am validating the text input by a user so that it will only accept letters but not numbers. so far my code works fine when I type in a number (e.g. 56), it warns me that I should only type letters and when I type in letters it doesn't return anything (like it should do). My problem is that it accepts it when I start by typing letters followed by numbers e.g. (s45). what it does is accept the first letter but not the whole string. I need it to accept the whole string.</p> <pre><code>def letterCheck(aString): if len(aString) &gt; 0: if re.match("[a-zA-Z]", aString) != None: return "" return "Enter letters only" </code></pre>
15,954,691
4
5
null
2013-04-11 17:00:38.133 UTC
2
2019-04-08 23:47:22.02 UTC
2015-07-15 13:44:04.537 UTC
null
100,297
null
2,141,691
null
1
34
python|string|match
32,566
<p>Anchor it to the start and end, and match <em>one or more</em> characters:</p> <pre><code>if re.match("^[a-zA-Z]+$", aString): </code></pre> <p>Here <code>^</code> anchors to the start of the string, <code>$</code> to the end, and <code>+</code> makes sure you match 1 or more characters.</p> <p>You'd be better off just using <a href="http://docs.python.org/2/library/stdtypes.html#str.isalpha"><code>str.isalpha()</code></a> instead though. No need to reach for the hefty regular expression hammer here:</p> <pre><code>&gt;&gt;&gt; 'foobar'.isalpha() True &gt;&gt;&gt; 'foobar42'.isalpha() False &gt;&gt;&gt; ''.isalpha() False </code></pre>
15,969,082
node.js async.series is that how it is supposed to work?
<pre><code>var async = require('async'); function callbackhandler(err, results) { console.log('It came back with this ' + results); } function takes5Seconds(callback) { console.log('Starting 5 second task'); setTimeout( function() { console.log('Just finshed 5 seconds'); callback(null, 'five'); }, 5000); } function takes2Seconds(callback) { console.log('Starting 2 second task'); setTimeout( function() { console.log('Just finshed 2 seconds'); callback(null, 'two'); }, 2000); } async.series([takes2Seconds(callbackhandler), takes5Seconds(callbackhandler)], function(err, results){ console.log('Result of the whole run is ' + results); }) </code></pre> <p>The output looks like below :</p> <pre><code>Starting 2 second task Starting 5 second task Just finshed 2 seconds It came back with this two Just finshed 5 seconds It came back with this five </code></pre> <p>I was expecting the takes2Second function to finish completely before the takes5Second starts. Is that how it is supposed to work. Please let me know. And the final function never runs. Thanks. </p>
15,969,256
5
0
null
2013-04-12 10:33:10.037 UTC
13
2016-04-20 09:11:18.49 UTC
null
null
null
null
1,780,678
null
1
34
javascript|node.js|asynchronous
63,740
<p>Not quite. You are executing the functions immediately (as soon as the array is evaluated), which is why they appear to start at the same time.</p> <p>The callback passed to each of the functions to be executed is internal to the async library. You execute it once your function has completed, passing an error and/or a value. You don't need to define that function yourself.</p> <p>The final function never runs in your case because the callback function that async needs you to invoke to move on to the next function in the series never actually gets executed (only your <code>callbackHandler</code> function gets executed).</p> <p>Try this instead:</p> <pre><code>async.series([ takes2Seconds, takes5seconds ], function (err, results) { // Here, results is an array of the value from each function console.log(results); // outputs: ['two', 'five'] }); </code></pre>
15,944,504
MsTest ClassInitialize and Inheritance
<p>I have a base class for my tests which is composed in the following way:</p> <pre><code>[TestClass] public abstract class MyBaseTest { protected static string myField = ""; [ClassInitialize] public static void ClassInitialize(TestContext context) { // static field initialization myField = "new value"; } } </code></pre> <p>Now I am trying to create a new test that inherits from the base, with the following signature:</p> <pre><code>[TestClass] public class MyTest : MyBaseTest { [TestMethod] public void BaseMethod_ShouldHave_FieldInitialized() { Assert.IsTrue(myField == "new value"); } } </code></pre> <p>The <code>ClassInitialize</code> is never called by the child tests ... What is the <strong>real and correct</strong> way of using test initialization with inheritance on MsTest?</p>
15,946,140
4
1
null
2013-04-11 08:54:40.083 UTC
7
2019-11-16 16:44:55.037 UTC
2013-12-20 18:22:25.107 UTC
null
24,908
null
236,243
null
1
80
c#|mstest
41,045
<p>Unfortunately you cannot achieve this that way because the <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.classinitializeattribute%28v=vs.100%29.aspx" rel="noreferrer">ClassInitializeAttribute Class</a> cannot be inherited.</p> <p>An inherited attribute can be used by the sub-classes of the classes that use it. Since the <code>ClassInitializeAttribute</code> cannot not be inherited, when the <code>MyTest</code> class is initialized the <code>ClassInitialize</code> method from the <code>MyBaseTest</code> class cannot be called.</p> <p>Try to solve it with another way. A less efficient way is to define again the <code>ClassInitialize</code> method in <code>MyTest</code> and just call the base method instead of duplicating the code.</p>
10,662,446
Invalid heap address and fatal signal 11
<p>Every so often my app will crash and my log will read:</p> <pre><code>@@@ ABORTING: INVALID HEAP ADDRESS IN dlfree Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1) </code></pre> <p>Sometimes <code>code=2</code>, but always <code>Fatal signal 11</code> and <code>invalid heap address</code>.</p> <p>I've tried researching what this means and how to fix it. <a href="https://stackoverflow.com/q/4973310/420015">This thread has been the most helpful</a>; however, I'm still without a solution. </p> <p>The error occurs when I run a couple of <code>AsyncTasks</code> to download several images.</p> <p>This is my main <code>AsyncTask</code></p> <pre><code>public class FetchArtistImages extends AsyncTask&lt;Void, Integer, String[]&gt; implements Constants { private final WeakReference&lt;Context&gt; contextReference; public FetchArtistImages(Context context) { contextReference = new WeakReference&lt;Context&gt;(context); } @Override protected String[] doInBackground(Void... params) { String[] projection = new String[] { Audio.Artists._ID, Audio.Artists.ARTIST }; String sortOrder = Audio.Artists.DEFAULT_SORT_ORDER; Uri uri = Audio.Artists.EXTERNAL_CONTENT_URI; Cursor c = contextReference.get().getContentResolver() .query(uri, projection, null, null, sortOrder); ArrayList&lt;String&gt; artistIds = new ArrayList&lt;String&gt;(); if (c != null) { int count = c.getCount(); if (count &gt; 0) { final int ARTIST_IDX = c.getColumnIndex(Audio.Artists.ARTIST); for (int i = 0; i &lt; count; i++) { c.moveToPosition(i); artistIds.add(c.getString(ARTIST_IDX)); } } c.close(); c = null; } return artistIds.toArray(new String[artistIds.size()]); } @Override protected void onPostExecute(String[] result) { for (int i = 0; i &lt; result.length; i++) { new LastfmGetArtistImages(contextReference.get()).executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, result[i]); } super.onPostExecute(result); } </code></pre> <p>Even though I've tried researching what's up with this, I still find myself lost when it comes to fixing it. If anyone has some insight, I'd definitely appreciate seeing it. The error isn't thrown every time I <code>execute</code> my <code>AsyncTasks</code>, but I can't find much of a pattern to help isolate why this is occurring. There are a couple of other threads on SO about <code>fatal signal 11</code>, but they don't provide much help in my case.</p>
11,812,665
2
3
null
2012-05-19 05:01:14.087 UTC
16
2021-10-21 18:16:48.327 UTC
2021-10-21 18:16:48.327 UTC
null
5,459,839
null
420,015
null
1
43
android|android-asynctask|heap-memory
44,917
<p>I just ran into the same issue and had it at a re-producable state. This is the error I was getting:</p> <blockquote> <p>08-04 17:37:05.491: A/libc(4233): @@@ ABORTING: INVALID HEAP ADDRESS IN dlfree 08-04 17:37:05.491: A/libc(4233): Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1)</p> </blockquote> <p>What it boiled down to is a function call being made from two different threads at the same time.</p> <p>More specifically, this function was BluetoothSocket's close() method. </p> <p>I checked the source code <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/bluetooth/BluetoothSocket.java#BluetoothSocket.close%28%29">at this website</a> , and the call is not synchronized (not sure if this changed since it is from Android 2.1).</p> <p>At any rate, do you maybe have a similar scenario where a function call is made from multiple threads? Can't say for sure from the source code you're showing.</p> <p>Also have you tried not using THREAD_POOL_EXECUTOR? According to <a href="http://developer.android.com/reference/android/os/AsyncTask.html">the android dev guide</a>:</p> <blockquote> <p>When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.</p> </blockquote>
10,477,294
How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?
<p>So essentially I'm looking for specifically a 4 digit code within two angle brackets within a text file. I know that I need to open the text file and then parse line by line, but I am not sure the best way to go about structuring my code after checking "for line in file". </p> <p>I think I can either somehow split it, strip it, or partition, but I also wrote a regex which I used compile on and so if that returns a match object I don't think I can use that with those string based operations. Also I'm not sure whether my regex is greedy enough or not...</p> <p>I'd like to store all instances of those found hits as strings within either a tuple or a list. </p> <p>Here is my regex: </p> <pre><code>regex = re.compile("(&lt;(\d{4,5})&gt;)?") </code></pre> <p>I don't think I need to include all that much code considering its fairly basic so far. </p>
10,477,490
2
5
null
2012-05-07 05:53:47.92 UTC
22
2019-06-10 16:01:23.927 UTC
2014-04-01 23:11:06.53 UTC
null
321,731
null
1,350,605
null
1
67
python|regex|file-io|text-mining|string-parsing
232,477
<pre><code>import re pattern = re.compile("&lt;(\d{4,5})&gt;") for i, line in enumerate(open('test.txt')): for match in re.finditer(pattern, line): print 'Found on line %s: %s' % (i+1, match.group()) </code></pre> <p>A couple of notes about the regex:</p> <ul> <li>You don't need the <code>?</code> at the end and the outer <code>(...)</code> if you don't want to match the number with the angle brackets, but only want the number itself</li> <li>It matches either 4 or 5 digits between the angle brackets</li> </ul> <p><strong>Update:</strong> It's important to understand that the <em>match</em> and <em>capture</em> in a regex can be quite different. The regex in my snippet above matches the pattern <em>with</em> angle brackets, but I ask to capture only the internal number, <em>without</em> the angle brackets.</p> <p>More about regex in python can be found here : <a href="https://docs.python.org/2/howto/regex.html" rel="noreferrer">Regular Expression HOWTO</a></p>
10,302,179
Hyphen, underscore, or camelCase as word delimiter in URIs?
<p>I'm designing an HTTP-based API for an intranet app. I realize it's a pretty small concern in the grand scheme of things, but: <strong>should I use hyphens, underscores, or camelCase to delimit words in the URIs?</strong></p> <hr /> <p>Here are my initial thoughts:</p> <p><strong>camelCase</strong></p> <ul> <li>possible issues if server is case-insensitive</li> <li>seems to have fairly widespread use in query string keys (<a href="http://api.example.com?**searchQuery**=..." rel="noreferrer">http://api.example.com?**searchQuery**=...</a>), but not in other URI parts</li> </ul> <p><strong>Hyphen</strong></p> <ul> <li>more aesthetically pleasing than the other alternatives</li> <li>seems to be widely used in the path portion of the URI</li> <li>never seen hyphenated query string key in the wild</li> <li><em>possibly</em> better for SEO (this may be a myth)</li> </ul> <p><strong>Underscore</strong></p> <ul> <li>potentially easier for programming languages to handle</li> <li>several popular APIs (Facebook, Netflix, <strike>StackExchange</strike>, etc.) are using underscores in all parts of the URI.</li> </ul> <p>I'm leaning towards underscores for everything. The fact that most of the big players are using them is compelling (see <a href="https://stackoverflow.com/a/608458/360570">https://stackoverflow.com/a/608458/360570</a>).</p>
18,450,653
8
5
null
2012-04-24 16:37:34.527 UTC
175
2022-07-06 11:35:45.037 UTC
2021-01-01 01:50:01.027 UTC
null
213,269
null
360,570
null
1
665
rest|url|uri|restful-url
280,251
<p>You should use hyphens in a crawlable web application URL. Why? Because the hyphen separates words (so that a search engine can index the individual words), and a hyphen is not a <a href="http://msdn.microsoft.com/en-us/library/20bw873z.aspx#WordCharacter" rel="noreferrer">word character</a>. Underscore is a word character, meaning it should be considered part of a word.</p> <p>Double-click this in Chrome: camelCase<br /> Double-click this in Chrome: under_score<br /> Double-click this in Chrome: hyphen-ated</p> <p>See how Chrome (I hear Google makes a search engine too) only thinks one of those is two words?</p> <p><code>camelCase</code> and <code>underscore</code> also require the user to use the <kbd>shift</kbd> key, whereas <code>hyphenated</code> does not.</p> <p>So if you should use hyphens in a crawlable web application, why would you bother doing something different in an intranet application? One less thing to remember.</p>
24,993,282
How does a language expand itself?
<p>I am learning C++ and I've just started learning about some of <a href="https://en.wikipedia.org/wiki/Qt_(software)">Qt</a>'s capabilities to code GUI programs. I asked myself the following question:</p> <p>How does C++, which previously had no syntax capable of asking the OS for a window or a way to communicate through networks (with APIs which I don't completely understand either, I admit) suddenly get such capabilities <strong>through libraries written in C++ themselves?</strong> It all seems terribly circular to me. What C++ instructions could you possibly come up with in those libraries?</p> <p>I realize this question might seem trivial to an experienced software developer but I've been researching for hours without finding any direct response. It's gotten to the point where I can't follow the tutorial about Qt because the existence of libraries is incomprehensible to me.</p>
24,993,453
15
14
null
2014-07-28 10:30:02.823 UTC
33
2021-08-25 10:26:58.227 UTC
2014-07-30 09:36:35.83 UTC
null
3,864,372
null
3,883,849
null
1
212
c++|libraries|bootstrapping
12,438
<p>A computer is like an onion, it has many <em>many</em> layers, from the inner core of pure hardware to the outermost application layer. Each layer exposes parts of itself to the next outer layer, so that the outer layer may use some of the inner layers functionality.</p> <p>In the case of e.g. Windows the operating system exposes the so-called WIN32 API for applications running on Windows. The Qt library uses that API to provide applications using Qt to its own API. You use Qt, Qt uses WIN32, WIN32 uses lower levels of the Windows operating system, and so on until it's electrical signals in the hardware.</p>
53,306,927
Chunksize irrelevant for multiprocessing / pool.map in Python?
<p>I try to utilize the pool multiprocessing functionality of python.</p> <p>Independent how I set the chunk size (under Windows 7 and Ubuntu - the latter see below with 4 cores), the amount of parallel threads seems to stay the same.</p> <pre><code>from multiprocessing import Pool from multiprocessing import cpu_count import multiprocessing import time def f(x): print("ready to sleep", x, multiprocessing.current_process()) time.sleep(20) print("slept with:", x, multiprocessing.current_process()) if __name__ == '__main__': processes = cpu_count() print('-' * 20) print('Utilizing %d cores' % processes) print('-' * 20) pool = Pool(processes) myList = [] runner = 0 while runner &lt; 40: myList.append(runner) runner += 1 print("len(myList):", len(myList)) # chunksize = int(len(myList) / processes) # chunksize = processes chunksize = 1 print("chunksize:", chunksize) pool.map(f, myList, 1) </code></pre> <p>The behaviour is the same whether I use <code>chunksize = int(len(myList) / processes)</code>, <code>chunksize = processes</code> or <code>1</code> (as in the example above).</p> <p>Could it be that the chunksize is set automatically to the amount of cores?</p> <p>Example for <code>chunksize = 1</code>:</p> <pre><code>-------------------- Utilizing 4 cores -------------------- len(myList): 40 chunksize: 10 ready to sleep 0 &lt;ForkProcess(ForkPoolWorker-1, started daemon)&gt; ready to sleep 1 &lt;ForkProcess(ForkPoolWorker-2, started daemon)&gt; ready to sleep 2 &lt;ForkProcess(ForkPoolWorker-3, started daemon)&gt; ready to sleep 3 &lt;ForkProcess(ForkPoolWorker-4, started daemon)&gt; slept with: 0 &lt;ForkProcess(ForkPoolWorker-1, started daemon)&gt; ready to sleep 4 &lt;ForkProcess(ForkPoolWorker-1, started daemon)&gt; slept with: 1 &lt;ForkProcess(ForkPoolWorker-2, started daemon)&gt; ready to sleep 5 &lt;ForkProcess(ForkPoolWorker-2, started daemon)&gt; slept with: 2 &lt;ForkProcess(ForkPoolWorker-3, started daemon)&gt; ready to sleep 6 &lt;ForkProcess(ForkPoolWorker-3, started daemon)&gt; slept with: 3 &lt;ForkProcess(ForkPoolWorker-4, started daemon)&gt; ready to sleep 7 &lt;ForkProcess(ForkPoolWorker-4, started daemon)&gt; slept with: 4 &lt;ForkProcess(ForkPoolWorker-1, started daemon)&gt; ready to sleep 8 &lt;ForkProcess(ForkPoolWorker-1, started daemon)&gt; slept with: 5 &lt;ForkProcess(ForkPoolWorker-2, started daemon)&gt; ready to sleep 9 &lt;ForkProcess(ForkPoolWorker-2, started daemon)&gt; slept with: 6 &lt;ForkProcess(ForkPoolWorker-3, started daemon)&gt; ready to sleep 10 &lt;ForkProcess(ForkPoolWorker-3, started daemon)&gt; slept with: 7 &lt;ForkProcess(ForkPoolWorker-4, started daemon)&gt; ready to sleep 11 &lt;ForkProcess(ForkPoolWorker-4, started daemon)&gt; slept with: 8 &lt;ForkProcess(ForkPoolWorker-1, started daemon)&gt; </code></pre>
53,307,813
1
3
null
2018-11-14 18:49:55.03 UTC
14
2019-02-11 18:34:53.073 UTC
null
null
null
user9098935
null
null
1
6
python|multithreading|multiprocessing|python-multiprocessing|python-multithreading
8,803
<p>Chunksize doesn't influence how many cores are getting used, this is set by the <code>processes</code> parameter of <code>Pool</code>. Chunksize sets how many items of the iterable you pass to <code>Pool.map</code>, are distributed per single worker-process <strong>at once</strong> in what <code>Pool</code> calls a "task" (figure below shows Python 3.7.1).</p> <p><a href="https://i.stack.imgur.com/Mmmah.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Mmmah.png" alt="task_python_3.7.1"></a></p> <p>In case you set <code>chunksize=1</code>, a worker-process gets fed with a new item, in a new task, only after finishing the one received before. For <code>chunksize &gt; 1</code> a worker gets a whole batch of items at once within a task and when it's finished, it gets the next batch if there are any left.</p> <p>Distributing items one-by-one with <code>chunksize=1</code> increases flexibility of scheduling while it decreases overall throughput, because drip feeding requires more inter-process communication (IPC).</p> <p>In my in-depth analysis of Pool's chunksize-algorithm <a href="https://stackoverflow.com/a/54032744/9059420">here</a>, I define the <strong>unit of work</strong> for processing <em>one</em> item of the iterable as <strong>taskel</strong>, to avoid naming conflicts with Pool's usage of the word "task". A task (as unit of work) consists of <code>chunksize</code> taskels.</p> <p>You would set <code>chunksize=1</code> if you cannot predict how long a taskel will need to finish, for example an optimization problem, where the processing time greatly varies across taskels. Drip-feeding here prevents a worker-process sitting on a pile of untouched items, while chrunching on one heavy taskel, preventing the other items in his task to be distributed to idling worker-processes. </p> <p>Otherwise, if all your taskels will need the same time to finish, you can set <code>chunksize=len(iterable) // processes</code>, so that tasks are only distributed once across all workers. Note that this will produce one more task than there are processes (processes + 1) in case <code>len(iterable) / processes</code> has a remainder. This has the potential to severely impact your overall computation time. Read more about this in the previously linked answer.</p> <hr> <p>FYI, that's the part of source code where <code>Pool</code> internally calculates the chunksize if not set:</p> <pre><code> # Python 3.6, line 378 in `multiprocessing.pool.py` if chunksize is None: chunksize, extra = divmod(len(iterable), len(self._pool) * 4) if extra: chunksize += 1 if len(iterable) == 0: chunksize = 0 </code></pre>
33,140,706
android: dynamically change FAB(Floating Action Button) icon from code
<p>How to change FAB icon in an Activity during runtime. I have this code -></p> <pre><code>FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabMainActivity); </code></pre> <p>I know this is possible using <code>fab.setBackgroundDrawable();</code> but i am a newbie to android, don't understand how to do this.</p> <p>Any help will be highly appreciated.</p> <p>Thanks</p>
33,141,376
5
6
null
2015-10-15 05:41:19.497 UTC
8
2021-10-15 07:59:16.16 UTC
null
null
null
null
1,479,735
null
1
55
android|material-design|floating-action-button
52,049
<p>Changing FloatingActionButton source:</p> <pre><code>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) { floatingActionButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_full_sad, context.getTheme())); } else { floatingActionButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_full_sad)); } </code></pre> <p>This can be replaced by following code from the support library instead:</p> <pre><code>floatingActionButton.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.ic_full_sad)); </code></pre>
33,176,332
How to change a value of a field using MySQL Workbench?
<p>I have installed <strong>MySQL Workbench</strong> and I have the following problem.</p> <p>I perform this simple select query:</p> <pre><code>SELECT * FROM spring_security.user; </code></pre> <p>that returns a list of rows.</p> <p>So, in the output area, I select a field of a specific row and I try to change its value. But I can't do it.</p> <p>Seems that is is impossible insert a new value for a specific field of a specific row.</p> <p>Why? How can I use this tool to change a value?</p>
33,177,518
4
7
null
2015-10-16 17:34:06.033 UTC
2
2021-04-19 13:46:17.453 UTC
2020-07-23 08:17:01.097 UTC
null
184,201
null
1,833,945
null
1
30
mysql|database|mysql-workbench|rdbms
45,432
<p>You can do easy with MySql Workbench this way :</p> <p>in menu database simply connect</p> <p>then select the database you need and then the table.</p> <p>Positioning the mouse over the table name in table schemas explore and so you can see on the rightside a table icon.</p> <p>Selecting/clicking this icon you can see the date in tabular form (like Toad).</p> <p>With this tabular form you can edit and apply the change</p> <p>Applying the change MySql Workbench show you the sql code and ask for confirm (the apply button is on the lower right corner of the table)</p>
22,696,886
How to iterate over array of objects in Handlebars?
<p>This might seem a silly question but I can't seem to find the answer anywhere.</p> <p>I'm hitting this Web API that returns an array of objects in JSON format:</p> <p><img src="https://i.stack.imgur.com/HUJSA.png" alt="array of objects"></p> <p>Handlebars docs shows the following example:</p> <pre><code>&lt;ul class="people_list"&gt; {{#each people}} &lt;li&gt;{{this}}&lt;/li&gt; {{/each}} &lt;/ul&gt; </code></pre> <p>In the context of:</p> <pre><code>{ people: [ "Yehuda Katz", "Alan Johnson", "Charles Jolley" ] } </code></pre> <p>In my case I don't have a name for the array, it's just the root object of the response. I've tried using <code>{{#each}}</code> with no luck.</p> <p>First time using Handlebars... What am I missing?</p> <p><strong>UPDATE</strong></p> <p>Here's a simplified fiddle to show you what I'm asking: <a href="http://jsfiddle.net/KPCh4/2/" rel="noreferrer">http://jsfiddle.net/KPCh4/2/</a></p> <p>Does handlebars require the context variable to be an object and not an array?</p>
22,697,178
6
3
null
2014-03-27 19:05:35.733 UTC
23
2020-08-21 13:06:16.56 UTC
2019-11-22 03:18:07.733 UTC
null
4,603,295
null
105,937
null
1
129
arrays|loops|each|handlebars.js
225,982
<p>You can pass <code>this</code> to each block. See here: <a href="http://jsfiddle.net/yR7TZ/1/" rel="noreferrer">http://jsfiddle.net/yR7TZ/1/</a></p> <pre class="lang-html prettyprint-override"><code>{{#each this}} &lt;div class="row"&gt;&lt;/div&gt; {{/each}} </code></pre>
13,382,149
IE10 on Windows 7 Side-by-Side IE8
<p>Can I install <a href="http://ie.microsoft.com/testdrive/Info/Downloads/Default.html">IE10 Preview for Windows 7</a> and keep the previous IE8 version for development testing?</p>
13,428,269
5
0
null
2012-11-14 15:46:23.577 UTC
2
2015-12-11 17:04:45.007 UTC
null
null
null
null
175,679
null
1
24
windows-7|internet-explorer-10
41,863
<p>I don't believe you will be able to run IE8 and IE10 side-by-side on the same machine. Instead, I would encourage you to use the <a href="http://blogs.msdn.com/b/ie/archive/2010/10/19/testing-sites-with-browser-mode-vs-doc-mode.aspx" rel="noreferrer">browser-emulation options</a> found within the F12 Developer Tools. From there you can instruct IE10 to behave as though it were IE8.</p> <p>If emulation isn't desirable, and you're not interested in downloading a <a href="http://www.microsoft.com/en-us/download/details.aspx?id=11575" rel="noreferrer">virtual machine image</a>, you could also consider exploring the <a href="http://www.browserstack.com/start" rel="noreferrer">BrowserStack service</a>. It will allow you to spin up IE8 on multiple versions of Windows, and view both remote and local files.</p>
13,535,560
C# vs F# for programmatic WPF GUIs
<p>I'm trying to decide where to draw the line on the use of F# and C# in enterprise software development. F# for mathematical code is a no-brainer. I like F# for GUI work even though it lacks GUI designer support but, of course, there is more resource availability of C# GUI people in industry. However, I am not too familiar with C#+XAML GUI development so I'm concerned about introducing bias.</p> <p>In the case of one client, they have dozens of similar GUIs that are quite static (changed yearly) and a few other GUIs that are very dynamic (e.g. business rules engines). They already have F# code live and are already investing in F# training so skills availability isn't an issue. My impression is that C#+XAML let you build static GUIs (a few sliders, a few text boxes etc.) easily but I cannot see how the GUI designer would help with programmatic GUIs like a business rules engine. Am I right in thinking that maintaining a battery of mostly-static GUIs (e.g. adding a new field to 100 separate GUIs) will require manual labor? Also, am I right in thinking that the GUI designer is of little use in the context of heavily programmatic GUIs so something like a business rules engine would be written primarily in C#+XAML with little use of the GUI designer?</p>
13,536,587
5
4
null
2012-11-23 20:50:18.967 UTC
10
2014-07-29 06:10:56.543 UTC
2012-11-24 00:33:37.63 UTC
null
13,924
null
13,924
null
1
38
c#|wpf|xaml|f#
10,732
<p>I've done a good amount of GUI and non-GUI programming in C# and F#, in work and play, heavy programmatic and static... and I believe your stated impression is accurate and practical. (note that I am more familiar with WinForms than with WPF, but I don't think the differences matter here).</p> <blockquote> <p>My impression is that C#+XAML let you build static GUIs (a few sliders, a few text boxes etc.) easily but I cannot see how the GUI designer would help with programmatic GUIs like a business rules engine.</p> </blockquote> <p>This is absolutely my experience. For mostly static GUIs, I prefer using the WinForms designer with C#. The tooling combo is great for these scenarios and is more productive than hand-coding the GUI with F# and no designer (now, if there were F# support with the designer, I would have no hesitation preferring that). <a href="http://code.google.com/p/im-only-resting/">I'm Only Resting</a> is an example where I have preferred C# with the WinForms designer over pure F#.</p> <p>And for heavy programmatic GUIs, I believe it is best to avoid the designer altogether, rather than to attempt to go half designer half programmatic (it gets real messy, real quick). So in these cases I definitely prefer hand-coding the GUIs in F#, since everyone knows F# is the more expressive language ;) <a href="http://code.google.com/p/fseye/">FsEye</a> is an example where I have preferred pure F# over C# with the WinForms designer.</p> <blockquote> <p>Am I right in thinking that maintaining a battery of mostly-static GUIs (e.g. adding a new field to 100 separate GUIs) will require manual labor?</p> </blockquote> <p>Probably. I don't believe there is really any ready solution for this problem since it is really quite a large one. But there might be some best practices out there for building a custom solution right for your suite of software.</p> <blockquote> <p>Also, am I right in thinking that the GUI designer is of little use in the context of heavily programmatic GUIs so something like a business rules engine would be written primarily in C#+XAML with little use of the GUI designer?</p> </blockquote> <p>Yes, like I said early, it is my belief that you ought not try to mix the GUI designer with heavy programmatic GUI programming.</p>
13,373,854
Binary Search Tree - Java Implementation
<p>I'm writing a program that utilizes a binary search tree to store data. In a previous program (unrelated), I was able to implement a linked list using an <a href="http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html" rel="noreferrer">implementation</a> provided with Java SE6. Is there something similar for a binary search tree, or will I need to "start from scratch"?</p>
13,373,914
6
2
null
2012-11-14 06:07:06.087 UTC
29
2019-08-07 04:22:25.177 UTC
null
null
null
user1696230
null
null
1
50
java|data-structures|tree
118,844
<p>You can use a <a href="https://docs.oracle.com/javase/10/docs/api/java/util/TreeMap.html" rel="noreferrer"><code>TreeMap data structure</code></a>. <code>TreeMap</code> is implemented as a <a href="http://en.wikipedia.org/wiki/Red%E2%80%93black_tree" rel="noreferrer">red black tree</a>, which is a self-balancing binary search tree.</p>
51,908,004
Install phpredis MAC OSX
<p>Can anyone help me install php-redis in MAC OSX .</p> <pre><code>brew install php-redis </code></pre> <p>not working.</p> <pre><code>pecl install php-redis </code></pre> <p>also not working getting - </p> <blockquote> <p>invalid package name/package file "php-redis".</p> <p>Homebrew Error: </p> </blockquote> <p><a href="https://i.stack.imgur.com/jJgg7.png" rel="noreferrer">homebrew_error</a></p>
52,925,300
4
6
null
2018-08-18 11:13:58.63 UTC
12
2022-07-16 18:46:56.487 UTC
2018-08-18 11:50:52.683 UTC
null
5,010,679
null
5,010,679
null
1
28
php|macos|redis|php-7.2
47,372
<pre><code>git clone https://www.github.com/phpredis/phpredis.git cd phpredis phpize &amp;&amp; ./configure &amp;&amp; make &amp;&amp; sudo make install </code></pre> <p>Add <code>extension=redis.so</code> in your php.ini</p> <pre><code>brew services restart [email protected] make test </code></pre> <p>You can check working or not</p> <pre><code>php -r "if (new Redis() == true){ echo \"\r\n OK \r\n\"; }" </code></pre>
20,386,331
Android Studio and android.support.v4.app.Fragment: cannot resolve symbol
<p>I am trying out Android Studio instead of Eclipse. I install it and then start a completely new project and follow the wizard. I add no code of my own.</p> <p>Then, I right-click to create a new component, a new Fragment:</p> <p><img src="https://i.stack.imgur.com/JfdGx.png" alt="enter image description here" /></p> <p>and choose a new fragment:</p> <p><img src="https://i.stack.imgur.com/Y119h.png" alt="enter image description here" /></p> <p>and as soon as I do, I see compile errors:</p> <p><img src="https://i.stack.imgur.com/X1Rlj.png" alt="enter image description here" /></p> <p>... so I start googling and find out that <a href="https://developer.android.com/tools/support-library/setup.html" rel="nofollow noreferrer">I need to install and reference support library 4</a>, and that I do. When I check the build.gradle (whatever that is, new to me coming from Eclipse), I see:</p> <p><img src="https://i.stack.imgur.com/UFDBl.png" alt="enter image description here" /></p> <p>but I change that to</p> <p><img src="https://i.stack.imgur.com/rx5RF.png" alt="enter image description here" /></p> <p>because they said so <a href="https://developer.android.com/tools/support-library/setup.html" rel="nofollow noreferrer">here</a>. After recompiling and all that, the error is still there. I then reference the .jar-file directly, like this:</p> <p><img src="https://i.stack.imgur.com/VqYj5.png" alt="enter image description here" /></p> <p>and again do recompile etc, but that doesn't help either.</p> <p>This behaviour seems very strange to me. What am I missing here? This is the SDK Manager view:</p> <p><img src="https://i.stack.imgur.com/rNEM3.png" alt="enter image description here" /></p>
20,388,380
25
2
null
2013-12-04 21:26:47.967 UTC
10
2022-09-23 00:07:34.713 UTC
2021-12-10 07:33:30.007 UTC
null
472,495
null
178,143
null
1
76
android|android-fragments|android-studio
169,564
<p>The symptom of this problem is usually that the build works fine from the command line (which means your <code>build.gradle</code> file is set up right) but you get syntax highlighting errors in the IDE. Follow This Steps To Solve The Problem: Click on <b>Tools</b> from the toolbar usually at the top part of your IDE, and then navigate to <b>Android</b> then navigate to <b>Sync Project with Gradle Files</b> button. We realize it's less than ideal that the IDE can't just take care of itself instead of forcing you to manually sync at the right time; we're tracking progress on this in <a href="https://code.google.com/p/android/issues/detail?id=63151" rel="noreferrer">https://code.google.com/p/android/issues/detail?id=63151</a></p>
20,693,895
Testable Controllers with dependencies
<p><strong>How can I resolve dependencies to a controller that is testable?</strong></p> <p>How it works: A URI is routed to a Controller, a Controller may have dependencies to perform a certain task.</p> <pre><code>&lt;?php require 'vendor/autoload.php'; /* * Registry * Singleton * Tight coupling * Testable? */ $request = new Example\Http\Request(); Example\Dependency\Registry::getInstance()-&gt;set('request', $request); $controller = new Example\Controller\RegistryController(); $controller-&gt;indexAction(); /* * Service Locator * * Testable? Hard! * */ $request = new Example\Http\Request(); $serviceLocator = new Example\Dependency\ServiceLocator(); $serviceLocator-&gt;set('request', $request); $controller = new Example\Controller\ServiceLocatorController($serviceLocator); $controller-&gt;indexAction(); /* * Poor Man * * Testable? Yes! * Pain in the ass to create with many dependencies, and how do we know specifically what dependencies a controller needs * during creation? * A solution is the Factory, but you would still need to manually add every dependencies a specific controller needs * etc. * */ $request = new Example\Http\Request(); $controller = new Example\Controller\PoorManController($request); $controller-&gt;indexAction(); </code></pre> <p><em>This is my interpretation of the design pattern examples</em></p> <p><strong>Registry:</strong> </p> <ul> <li>Singleton</li> <li>Tight coupling</li> <li>Testable? No</li> </ul> <p><strong>Service Locator</strong></p> <ul> <li>Testable? Hard/No (?)</li> </ul> <p><strong>Poor Man Di</strong></p> <ul> <li>Testable</li> <li>Hard to maintain with many dependencies</li> </ul> <p>Registry</p> <pre><code>&lt;?php namespace Example\Dependency; class Registry { protected $items; public static function getInstance() { static $instance = null; if (null === $instance) { $instance = new static(); } return $instance; } public function set($name, $item) { $this-&gt;items[$name] = $item; } public function get($name) { return $this-&gt;items[$name]; } } </code></pre> <p>Service Locator</p> <pre><code>&lt;?php namespace Example\Dependency; class ServiceLocator { protected $items; public function set($name, $item) { $this-&gt;items[$name] = $item; } public function get($name) { return $this-&gt;items[$name]; } } </code></pre> <p><strong>How can I resolve dependencies to a controller that is testable?</strong></p>
20,829,238
3
2
null
2013-12-19 23:47:59.853 UTC
13
2013-12-30 06:55:00.537 UTC
null
null
null
null
3,121,056
null
1
20
php|design-patterns|dependencies|registry|service-locator
3,029
<p>What would be the dependencies that you are talking about in a controller?</p> <p>The to major solution would be:</p> <ul> <li>injecting a factory of services in the controller through constructor</li> <li>using a DI container to pass in the specific services directly</li> </ul> <p>I am going to try to describe both approaches separately in detail.</p> <blockquote> <p><sub><strong>Note:</strong> all examples will be leaving out interaction with view, handling of authorization, dealing with dependencies of service factory and other specifics</sub></p> </blockquote> <p><br></p> <h1>Injection of factory</h1> <p>The <strong>simplified</strong> part of bootstrap stage, which deals with kicking off stuff to the controller, would look kinda like this </p> <pre><code>$request = //... we do something to initialize and route this $resource = $request-&gt;getParameter('controller'); $command = $request-&gt;getMethod() . $request-&gt;getParameter('action'); $factory = new ServiceFactory; if ( class_exists( $resource ) ) { $controller = new $resource( $factory ); $controller-&gt;{$command}( $request ); } else { // do something, because requesting non-existing thing } </code></pre> <p>This approach provides a clear way for extending and/or substituting the model layer related code simply by passing in a different factory as the dependency. In controller it would look something like this:</p> <pre><code>public function __construct( $factory ) { $this-&gt;serviceFactory = $factory; } public function postLogin( $request ) { $authentication = $this-&gt;serviceFactory-&gt;create( 'Authentication' ); $authentication-&gt;login( $request-&gt;getParameter('username'), $request-&gt;getParameter('password') ); } </code></pre> <p>This means, that, to test this controller's method, you would have to write a unit-test, which mock the content of <code>$this-&gt;serviceFactory</code>, the created instance and the passed in value of <code>$request</code>. Said mock would need to return an instance, which can accept two parameter.</p> <blockquote> <p><sub><strong>Note:</strong> The response to the user should be handled entirely by view instance, since creating the response is part of UI logic. Keep in mind that HTTP Location header is <strong>also</strong> a form of response.</sub></p> </blockquote> <p>The unit-test for such controller would look like:</p> <pre><code>public function test_if_Posting_of_Login_Works() { // setting up mocks for the seam $service = $this-&gt;getMock( 'Services\Authentication', ['login']); $service-&gt;expects( $this-&gt;once() ) -&gt;method( 'login' ) -&gt;with( $this-&gt;equalTo('foo'), $this-&gt;equalTo('bar') ); $factory = $this-&gt;getMock( 'ServiceFactory', ['create']); $factory-&gt;expects( $this-&gt;once() ) -&gt;method( 'create' ) -&gt;with( $this-&gt;equalTo('Authentication')) -&gt;will( $this-&gt;returnValue( $service ) ); $request = $this-&gt;getMock( 'Request', ['getParameter']); $request-&gt;expects( $this-&gt;exactly(2) ) -&gt;method( 'getParameter' ) -&gt;will( $this-&gt;onConsecutiveCalls( 'foo', 'bar' ) ); // test itself $instance = new SomeController( $factory ); $instance-&gt;postLogin( $request ); // done } </code></pre> <p>Controllers are supposed to be the <em>thinnest</em> part of the application. The responsibility of controller is: <em>take user input and, based on that input, alter the state of model layer (and in rare case - current view)</em>. That's it. </p> <p><br></p> <h1>With DI container</h1> <p>This other approach is .. well .. it's basically a trade of complexity (subtract in one place, add more on others). It also relays on having a <strong>real</strong> DI containers, instead of glorified service locators, like <a href="http://pimple.sensiolabs.org/" rel="nofollow noreferrer">Pimple</a>.</p> <p><strong>My recommendation:</strong> check out <a href="https://github.com/rdlowrey/Auryn" rel="nofollow noreferrer"><strong>Auryn</strong></a>.</p> <p>What a DI container does is, using either configuration file or reflection, it determines dependencies for the instance, that you want to create. Collects said dependencies. And passes in the constructor for the instance.</p> <pre><code>$request = //... we do something to initialize and route this $resource = $request-&gt;getParameter('controller'); $command = $request-&gt;getMethod() . $request-&gt;getParameter('action'); $container = new DIContainer; try { $controller = $container-&gt;create( $resource ); $controller-&gt;{$command}( $request ); } catch ( FubarException $e ) { // do something, because requesting non-existing thing } </code></pre> <p>So, aside from ability to throw exception, the bootstrapping of the controller stays pretty much the same.</p> <p>Also, at this point you should already recognize, that switching from one approach to other would mostly require complete rewrite of controller (and the associated unit tests).</p> <p>The controller's method in this case would look something like:</p> <pre><code>private $authenticationService; #IMPORTANT: if you are using reflection-based DI container, #then the type-hinting would be MANDATORY public function __construct( Service\Authentication $authenticationService ) { $this-&gt;authenticationService = $authenticationService; } public function postLogin( $request ) { $this-&gt;authenticatioService-&gt;login( $request-&gt;getParameter('username'), $request-&gt;getParameter('password') ); } </code></pre> <p>As for writing a test, in this case again all you need to do is provide some mocks for isolation and simply verify. But, in this case, <strong>the unit testing is simpler</strong>:</p> <pre><code>public function test_if_Posting_of_Login_Works() { // setting up mocks for the seam $service = $this-&gt;getMock( 'Services\Authentication', ['login']); $service-&gt;expects( $this-&gt;once() ) -&gt;method( 'login' ) -&gt;with( $this-&gt;equalTo('foo'), $this-&gt;equalTo('bar') ); $request = $this-&gt;getMock( 'Request', ['getParameter']); $request-&gt;expects( $this-&gt;exactly(2) ) -&gt;method( 'getParameter' ) -&gt;will( $this-&gt;onConsecutiveCalls( 'foo', 'bar' ) ); // test itself $instance = new SomeController( $service ); $instance-&gt;postLogin( $request ); // done } </code></pre> <p>As you can see, in this case you have one less class to mock.</p> <h2>Miscellaneous notes</h2> <ul> <li><p><strong>Coupling to the name</strong> (in the examples - "authentication"):</p> <p>As you might have notices, in both examples your code would be coupled to the name of service, which was used. And even if you use configuration-based DI container (as it is possible <a href="http://symfony.com/doc/current/components/dependency_injection/introduction.html#components-dependency-injection-loading-config" rel="nofollow noreferrer">in symfony</a>), you still will end up defining name of the specific class.</p></li> <li><p><strong>DI containers are not magic</strong>:</p> <p>The use of DI containers has been somewhat hyped in past couple years. It is not a silver bullet. I would even go as far as to say that: DI containers are incompatible with <a href="https://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29" rel="nofollow noreferrer">SOLID</a>. Specifically because they do not work with interfaces. You cannot really use polymorphic behavior in the code, that will be initialized by a DI container.</p> <p>Then there is the problem with configuration-based DI. Well .. it's just beautiful while project is tiny. But as project grows, the configuration file grows too. You can end up with glorious WALL of xml/yaml configuration, which is understood by only one single person in project.</p> <p>And the third issue is complexity. Good DI containers are <strong>not</strong> simple to make. And if you use 3rd party tool, you are introducing additional risks.</p></li> <li><p><strong>Too many dependencies</strong>:</p> <p>If your class has too many dependencies, then it is <strong>not</strong> a failure of DI as practice. Instead it is a <strong>clear indication</strong>, that your class is doing too many things. It is violating <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow noreferrer">Single Responsibility Principle</a>.</p></li> <li><p><strong>Controllers actually have (some) logic</strong>:</p> <p>The examples used above were extremely simple and where interacting with model layer through a single service. In real world your controller methods <strong>will</strong> contain control-structures (loops, conditionals, stuff).</p> <p>The most basic use-case would be a controller which handles contact form with as "subject" dropdown. Most of the messages would be directed to a service that communicates with some CRM. But if user pick "report a bug", then the message should be passed to a difference service which automatically create a ticket in bug tracker and sends some notifications.</p></li> <li><p><strong>It's PHP Unit</strong>:</p> <p>The examples of unit-tests are written using <a href="http://phpunit.de/manual/3.7/en/" rel="nofollow noreferrer">PHPUnit</a> framework. If you are using some other framework, or writing tests manually, you would have to make some basic alterations </p></li> <li><p><strong>You will have more tests</strong>:</p> <p>The unit-test example are not the entire set of tests that you will have for a controller's method. Especially, when you have controllers that are non-trivial. </p></li> </ul> <h3>Other materials</h3> <p>There are some .. emm ... tangential subjects. </p> <p><kbd>Brace for: <strong>shameless self-promotion</strong></kbd></p> <ul> <li><p><a href="https://stackoverflow.com/questions/3430181/acl-implementation">dealing with access control in MVC-like architecture</a></p> <p>Some frameworks have nasty habit of pushing the authorization checks (do not confuse with "authentication" .. different subject) in the controller. Aside from being completely stupid thing to do, it also introduces additional dependencies (often - globally scoped) in the controllers. </p> <p>There is another post which uses similar approach for introducing <a href="https://stackoverflow.com/a/18682856/727208">non-invasive logging</a></p></li> <li><p><a href="https://stackoverflow.com/a/16356866/727208">list of lectures</a></p> <p>It's kinda aimed at people who want to learn about MVC, but materials there are actually for general education in OOP and development practices. The idea is that, by the time when you are done with that list, MVC and other SoC implementations will only cause you to go <em>"Oh, this had a name? I thought it was just common sense."</em></p></li> <li><p><a href="https://stackoverflow.com/a/5864000/727208">implementing model layer</a></p> <p>Explains what those magical "services" are in the description above.</p></li> </ul>
3,619,753
How to use variant arrays in Delphi
<p>I have two Delphi7 programs: a COM automation server (EXE) and the other program which is using the automation server.</p> <p>I need to pass an array of bytes from one program to the other.</p> <p>After some searching I've found that using variant arrays is the way to go (correct me please if you know any better methods).</p> <p>My question is: How do I create a variant array in one program, and then how do I read its values in the other?</p> <p>I know about VarArrayCreate and VarArrayLowBound/VarArrayHighBound, but I'm unsure on how to do this properly.</p> <p>Thanks!</p>
3,620,800
2
0
null
2010-09-01 15:34:33.66 UTC
3
2015-02-25 19:29:19.49 UTC
2010-09-01 20:28:21.627 UTC
null
301,152
null
298,939
null
1
20
arrays|delphi|automation|delphi-7|variant
47,686
<p>You create it like that:</p> <p>Declarations first</p> <pre><code>var VarArray: Variant; Value: Variant; </code></pre> <p>Then the creation:</p> <pre><code>VarArray := VarArrayCreate([0, Length - 1], varVariant); </code></pre> <p>or you could also have</p> <pre><code>VarArray := VarArrayCreate([0, Length - 1], varInteger); </code></pre> <p>Depends on the type of the data. Then you iterate like this:</p> <pre><code>i := VarArrayLowBound(VarArray, 1); HighBound := VarArrayHighBound(VarArray, 1); while i &lt;= HighBound do begin Value := VarArray[i]; ... do something ... Inc(i); end; </code></pre> <p>Finally you clear the array when you don't need it anymore. EDIT: (This is optional, see <a href="https://stackoverflow.com/questions/897371/in-delphi-2009-do-i-need-to-free-variant-arrays">In Delphi 2009 do I need to free variant arrays?</a> )</p> <pre><code>VarClear(VarArray); </code></pre> <p>That is all there is to it. For another example look at the official <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/Variants_VarArrayCreate.html" rel="noreferrer">Embracadero Help</a></p> <p>EDIT:</p> <p>The array should be created only once. Then just use it like shown in the above example.</p>
3,868,786
WPF Sentinel objects and how to check for an internal type
<p>As some of you have discovered, a new feature (?) appeared WPF 4, where the data binding engine may pass your custom control instances of the class <strong>MS.Internal.NamedObject</strong> with the name "<strong>{DisconnectedItem}</strong>" into the DataContext - instead of the data item your code is expecting (this happens when a templated control is disconnected by its ItemsControl). These are called sentinel objects.</p> <p>In existing code, this can lead to spurious exceptions where the code is unprepared for it. These can be swallowed up by the data binding subsystem, or they can wreak havoc. Keep an eye on your debug console.</p> <p>Anyway, I learned about this on <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/e6643abc-4457-44aa-a3ee-dd389c88bd86/?prof=required" rel="noreferrer">this MSDN forum</a>. And there's a post by Sam Bent which <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/36aec363-9e33-45bd-81f0-1325a735cc45/#611fccf2-737f-4309-a793-4001488b23aa" rel="noreferrer">explains it all</a>. Go read it now, <em>you'll want to know this</em>. The essence is that these events should never have fired (that's the bug), so:</p> <blockquote> <p>Ignore the DataContextChanged event if the DataContext is a sentinel object.</p> </blockquote> <p>So, so I want to check my DataContext. But how? Consider:</p> <pre><code>public bool IsSentinelObject(object dataContext) { return (dataContext is MS.Internal.NamedObject); } </code></pre> <p>Guess what happens? It doesn't compile because MS.Internal.NamedObject is internal, and not accessible to me. Of course, I can hack it like this:</p> <pre><code>public bool IsSentinelObject(object dataContext) { return dataContext.GetType().FullName == "MS.Internal.NamedObject" || dataContext.ToString() == "{DisconnectedObject}"; } </code></pre> <p>(or something, which works). I have also followed Sam's suggestion to cache the object for later reference equality checks (it's a singleton).</p> <p>Of course, this means I don't have a problem, not really. But I'm curious, and this posting will be sure to benefit some users, so it's worth asking anyway:</p> <p>Is there a way I can exactly check the type against the internal NamedObject type, without resorting to string comparisons?</p>
3,868,835
2
2
null
2010-10-06 00:39:14.217 UTC
7
2014-06-05 20:42:58.223 UTC
2010-11-09 07:11:58.733 UTC
null
228,755
null
32,050
null
1
31
c#|.net|wpf|data-binding|wpf-4.0
6,233
<p>This one?</p> <pre><code>var disconnectedItem = typeof(System.Windows.Data.BindingExpressionBase) .GetField("DisconnectedItem", BindingFlags.Static | BindingFlags.NonPublic) .GetValue(null); </code></pre>
3,506,319
Android LinearLayout with color resource: What am I doing wrong?
<p>I followed <a href="http://developer.android.com/guide/topics/resources/color-list-resource.html" rel="noreferrer">this tutorial</a> to create a color state list for a particular Android view. I just want it to highlight when clicked so the user knows why the screen just changed. </p> <p>When the view is rendered, I get the following error:</p> <p>org.xmlpull.v1.XmlPullParserException: Binary XML file line #3: tag requires a 'drawable' attribute or child tag defining a drawable</p> <p>My color XML (in res/color/viewcolor.xml):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_pressed="true" android:color="#ff33ffff"/&gt; &lt;!-- pressed --&gt; &lt;item android:color="#ff000000"/&gt; &lt;!-- default --&gt; &lt;/selector&gt; </code></pre> <p>My layout XML (in res/layout/myview.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:id="@+id/myview" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="top" android:background="@color/viewcolor"&gt; &lt;!--crap in the layout--&gt; &lt;/LinearLayout&gt; </code></pre> <p>What did I miss?</p>
3,506,500
2
1
null
2010-08-17 19:45:01.05 UTC
21
2012-04-12 22:06:34.45 UTC
null
null
null
null
136,790
null
1
34
android|android-layout
50,022
<p>I remember that I worked around this error by using state drawable instead of state color. For some reason layout background just doesn't work with stateful colors. So try creating a stateful drawable (for example list of shape drawables with different colors) and use it as background.</p> <p>res/drawable/pressed.xml:</p> <pre><code>&lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" &gt; &lt;solid android:color="#ff33ffff" /&gt; &lt;/shape&gt; </code></pre> <p>res/drawable/normal.xml:</p> <pre><code>&lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" &gt; &lt;solid android:color="#ff000000" /&gt; &lt;/shape&gt; </code></pre> <p>res/drawable/background.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_pressed="true" android:drawable="@drawable/pressed" /&gt; &lt;item android:drawable="@drawable/normal" /&gt; &lt;/selector&gt; </code></pre> <p>Then use background.xml drawable as background :) </p>
9,277,948
Commas messing with number input in Javascript
<p>I have a page with some elements that are controlled by the user. One of these is a text input field, where the user is supposed to input a number. Everything works well if the user only inputs digits (EG 9000), but is the user uses comma notation (the being 9,000) javascript doesn't take the input as an integer.</p> <p>How can I remove the commas and/or force the input to an integer? I tried using parseint(), but it doesn't seem to work with commas.</p>
9,278,056
4
2
null
2012-02-14 13:44:52.747 UTC
3
2017-02-02 07:59:07.403 UTC
2017-02-02 07:59:07.403 UTC
null
1,903,116
null
502,816
null
1
31
javascript|string|user-input
30,148
<p>Use a global regular expression to replace <em>all</em> commas with an empty string:</p> <pre><code>var str = "12,345,678"; str = str.replace(/,/g, ""); parseInt(str, 10); </code></pre>
16,155,613
A valid provisioning profile matching the application's identifier could not be found
<p>This has been asked before, but the answers to previous questions are not solving my issue.</p> <p>I'm trying to build a simple Hello World app called (CalculatorBrain) from Stanford iTunes U courses. I can run it in the Simulator fine, but I'd like to get it on my iPhone 4S.</p> <p>I sync my iPhone 4S through iTunes on my Windows machine. Always have. Figured I should list this detail.</p> <p>Anyway, back to my Macbook (Mountain Lion). I'm running the most recent XCode 4.6.2 (4H1003) and my iPhone is also the most recent at 6.1.3 I believe.</p> <p>I went to the Provisioning Portal at the Apple developer page. I added my 4S. I called it JohnSmith, and gave it the phones UDID. </p> <p>In XCode, I opened the Organizer, Devices is highlighted by default. I put the passcode in my iPhone, and plugged it into my Macbook. Devices finds my iPhone. If I click on Provisioning Profiles and try 'Add Device to Provisioning Portal', I get a "A device with number already exists on this team." Great. I know it's added for sure then. All good news so far.</p> <p>In my Hello World app, CalculatorBrain-Info.plist my Bundle Identifier is "com.JohnSmith.CalculatorBrain". Bundle display name is "${PRODUCT_NAME}" and executable file is "${EXECUTABLE_NAME}" if that matters.</p> <p>In the Navigator, if I highlight my project, and bring up the Build Settings, under Code Signing Identity I get the options...</p> <p>Don't Sign Code</p> <p>Automatic Profile Selector - iPhone Developer - iPhone Distribution</p> <p>Identities without Provisioning Profiles - iPhone Developer: John Smith (R............K) - iPhone Distribution: John Smith (Y.............5)</p> <p>Other...</p> <p>I've tried all of these. I'm assuming I'm supposed to use the iPhone Developer: John Smith one... but it's saying it's an identity without Provisioning Profiles.</p> <p>What's going on here? What do I need to do to get this to work?</p>
16,158,836
4
1
null
2013-04-22 19:58:33.117 UTC
10
2015-02-16 13:07:08.65 UTC
2013-12-06 22:05:25.99 UTC
null
2,680,216
null
1,652,166
null
1
12
xcode|device|provisioning|portal
40,381
<p>Based on your description, it sounds like the missing element is that you need to go back to the 'Certificates, Identifiers, and Profiles' tool, generate a Development Provisioning Profile for the AppID of your HelloWorld app, then install that profile on your development machine. At a high level, this is composed of the following steps:</p> <ol> <li>Locate the AppID for your project in Xcode.</li> <li>Verify that you've setup that AppID in 'Certificates, Identifiers, and Profiles'.</li> <li>Create a Development Provisioning Profile for that AppId, your development certificate, and one or more registered test devices.</li> <li>Download and Install the Provisioning Profile in Xcode.</li> <li>Configure your project to Code Sign using this Profile and Linked Code Signing Identity.</li> <li>Build to device!</li> </ol> <p>The 'Code Signing Identity' build configuration item you have mentioned is very much dependent on both your project's settings as well as the Provisioning Profiles available on your development machine. I recently answered a tangentially related question <a href="https://stackoverflow.com/questions/15996468/what-are-code-signing-identities/16070915#16070915" title="What are code signing identities?">'What are code signing identities?'</a> that may be helpful in seeing what information Code Signing is using and how you can check that you've got your development machine setup to be able to Code Sign your project.</p> <p>...and now, on to more specific HOWTOs to help work through your Code Signing question:</p> <p><strong>Locating Project's AppID</strong></p> <p>The AppID uniquely defines an application in the iOS ecosystem and is one of the things you first create when starting a new Xcode project. This AppID is what you need to register in the 'Certificates, Identifiers, and Profiles' tool to get started with Provisioning.</p> <p><img src="https://i.stack.imgur.com/5mbBi.png" alt="Xcode AppId Setting"></p> <ol> <li>In the Project Navigator (CMD+1), click on your project name (likely 'CalculatorBrain'). This will present the project's settings.</li> <li>Select [Your Project Name] > Summary Tab as shown in the screen clipping from above (MyiOSApplication).</li> <li>Your iOS AppID is presented in the 'Bundle Identifier' field. Snag a copy of this string, you'll need it next.</li> </ol> <p><strong>Verify (or Setup) the AppID</strong></p> <ol> <li>Navigate to <a href="http://developer.apple.com/ios" rel="nofollow noreferrer">http://developer.apple.com/ios</a> and access the 'Certificates, Identifiers, and Profiles' tool.</li> <li>After logging in, select 'Identifiers'.</li> <li>Check that the AppID you found in the previous section is present in the list of App Identifiers. If so, take note of the App ID Name and skip to the next section, otherwise...</li> <li>Click the 'Add' (Plus) button in the upper right corner, provide a name for this App ID (can be whatever you want, just so long as it doesn't have special characters.)</li> <li>Scroll to the bottom of the page, and paste a copy of your App ID from the previous section in the 'Bundle ID' field. under 'Explicit App ID'.</li> <li>Click 'Continue'.</li> </ol> <p>Do note that the AppID must be unique across the iOS Ecosystem -- you may get an error if the AppID you've selected is already in use. If so, change your 'Bundle ID' to something unique -- just be sure to update the 'Bundle ID' setting in your Xcode project to match whatever you settle on.</p> <p><strong>Creating a Development Provisioning Profile</strong></p> <p>Now that the App ID is registered, you are now ready to create a Development Provisioning Profile linking your App ID, Development Certificate, and Test Device ID(s) together.</p> <ol> <li>Within the 'Certificates, Identities, Profiles' tool, navigate to 'Provisioning Profiles'.</li> <li>Click on the 'Add' (Plus) button in the upper right corner.</li> <li>Select 'iOS App Development' in the 'Select Type' step and then click 'Continue'.</li> <li>Select your App ID from the drop down list of App IDs and then click 'Continue'.</li> <li>Check the box next to your Development Certificate and then click 'Continue'.</li> <li>Check the box next to the test device(s) you want to authorize to install this app and then click 'Continue'.</li> <li>Key in a Profile Name (again omitting special characters) then click 'Generate'.</li> </ol> <p><strong>Download and Install Provisioning Profile</strong></p> <p>Once the Provisioning Profile is generated, the tool will provide you with a link to be able to download</p> <ol> <li>Download the Provisioning Profile by clicking on the 'Download' link.</li> <li>Drag Provisioning Profile from your Download location and drop it on the Xcode Dock Icon or double-click to open it.</li> </ol> <p><strong>Configure Code Signing Identity</strong></p> <p>Sounds like you already know where this is located, but just in case:</p> <ol> <li>In the Project Navigator (CMD+1), click on your project name (likely 'CalculatorBrain'). This will present the project's settings.</li> <li>Select [Your Project Name] > Build Settings Tab.</li> <li>Scroll to the 'Code Signing Identity' item.</li> </ol> <p>In theory you would like to use the 'Automatic Profile Selector' option which will attempt to match your AppID to an installed Provisioning Profile, but you can also scroll through the list and pick a specific mapping of Bundle ID/AppId to iOS Certificate.</p> <p>Also, my own Xcode doesn't always seem to catch on to changes to freshly-installed provisioning profiles -- It is unclear if this is just a quirk of my own Xcode install or if there is a bug in Xcode. Either way, quitting and relaunching Xcode seems to trigger a reindex/refresh of profiles.</p> <p>Anyway, select the option that matches your AppId/BundleId and your Developer Certificate.</p> <p>Assuming the problem was a missing/incomplete/expired Provisioning Profile, then this should help get you up and running. If not, we'll have to dig into other potential settings or certificates issues that could be tripping up your Code Signature operation.</p>
16,207,455
C# ref is it like a pointer in C/C++ or a reference in C++?
<p>I'm working with the <code>ref</code> and don't understand clearly <em>"Is it like a pointer as in C/C++ or it's like a reference in C++?"</em></p> <p>Why did I ask such a weak question as you thought for a moment? Because, when I'm reading C#/.NET books, msdn or talking to C# developers I'm becoming confused by the following reasons:</p> <ul> <li>C# developers suggest NOT to use <code>ref</code> in the arguments of a function, <code>e.g. ...(ref Type someObject)</code> doesn't smell good for them and they suggest <code>...(Type someObject)</code>, I really don't understand clearly this suggestion. The reasons I heard: better to work with the copy of object, then use it as a return value, not to corrupt memory by a reference etc... Often I hear such explanation about DB connection objects. As on my plain C/C++ experience, I really don't understand why to use a reference is a bad stuff in C#? I control the life of object and its memory allocations/re-allocations etc... I read in books and forums only advises <code>it's bad, because you can corrupt your connection and cause a memory leak by a reference lose</code>, so I control the life of object, I may control manually what I really want, so why is it bad?</li> <li>Nowadays reading different books and talk to different people, I don't clearly understand is <code>ref</code> a pointer (<code>*</code>) or a reference like in C++ by <code>&amp;</code> ? As I remember pointers in C/C++ always do allocate a space with a size of <code>void*</code> type - 4 bytes (the valid size depends on architecture), where hosts an address to a structure or variable. In C++ by passing a reference <code>&amp;</code> there is no new allocations from the heap/stack and you work with already defined objects in memory space and there is no sub-allocating memory for a pointer externally like in plain C. So what's the <code>ref</code> in C#? Does .NET VM handle it like a pointer in plain C/C++ and its <code>GC</code> allocates temporary space for a pointer or it does a work like reference in C++? Does <code>ref</code> work only with a managed types correctly or for value types like <code>bool, int</code> it's better to switch an <code>unsafe</code> code and pass through a pointer in unmanaged style?</li> </ul>
16,207,741
6
8
null
2013-04-25 06:01:48.78 UTC
26
2019-08-05 06:24:52.243 UTC
2013-04-25 17:01:33.173 UTC
null
894,862
null
894,862
null
1
41
c#|pointers|memory-management|reference|ref
49,814
<p>In C#, when you see something referring to a reference type (that is, a type declared with <code>class</code> instead of <code>struct</code>), then you're essentially always dealing with the object through a pointer. In C++, everything is a value type by default, whereas in C# everything is a reference type by default.</p> <p>When you say "ref" in the C# parameter list, what you're really saying is more like a "pointer to a pointer." You're saying that, in the method, that you want to replace not the contents of the object, but the reference to the object itself, in the code calling your method.</p> <p>Unless that is your intent, then you should just pass the reference type directly; in C#, passing reference types around is cheap (akin to passing a reference in C++).</p> <p>Learn/understand the difference between value types and reference types in C#. They're a major concept in that language and things are going to be really confusing if you try to think using the C++ object model in C# land.</p> <p>The following are essentially semantically equivalent programs:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;iostream&gt; class AClass { int anInteger; public: AClass(int integer) : anInteger(integer) { } int GetInteger() const { return anInteger; } void SetInteger(int toSet) { anInteger = toSet; } }; struct StaticFunctions { // C# doesn't have free functions, so I'll do similar in C++ // Note that in real code you'd use a free function for this. static void FunctionTakingAReference(AClass *item) { item-&gt;SetInteger(4); } static void FunctionTakingAReferenceToAReference(AClass **item) { *item = new AClass(1729); } }; int main() { AClass* instanceOne = new AClass(6); StaticFunctions::FunctionTakingAReference(instanceOne); std::cout &lt;&lt; instanceOne-&gt;GetInteger() &lt;&lt; "\n"; AClass* instanceTwo; StaticFunctions::FunctionTakingAReferenceToAReference(&amp;instanceTwo); // Note that operator&amp; behaves similar to the C# keyword "ref" at the call site. std::cout &lt;&lt; instanceTwo-&gt;GetInteger() &lt;&lt; "\n"; // (Of course in real C++ you're using std::shared_ptr and std::unique_ptr instead, // right? :) ) delete instanceOne; delete instanceTwo; } </code></pre> <p>And for C#:</p> <pre class="lang-cs prettyprint-override"><code>using System; internal class AClass { public AClass(int integer) : Integer(integer) { } int Integer { get; set; } } internal static class StaticFunctions { public static void FunctionTakingAReference(AClass item) { item.Integer = 4; } public static void FunctionTakingAReferenceToAReference(ref AClass item) { item = new AClass(1729); } } public static class Program { public static void main() { AClass instanceOne = new AClass(6); StaticFunctions.FunctionTakingAReference(instanceOne); Console.WriteLine(instanceOne.Integer); AClass instanceTwo = new AClass(1234); // C# forces me to assign this before // it can be passed. Use "out" instead of // "ref" and that requirement goes away. StaticFunctions.FunctionTakingAReferenceToAReference(ref instanceTwo); Console.WriteLine(instanceTwo.Integer); } } </code></pre>
16,345,777
Given URL is not allowed by the Application configuration
<p>I am trying to create facebook sign-in page according to <a href="https://developers.facebook.com/docs/facebook-login/getting-started-web/" rel="noreferrer">this</a> tutorial. I only changed the two lines </p> <pre><code>appId : '370675846382420', // App ID channelUrl : '//http://bp.php5.cz/channel.html', // Channel File </code></pre> <p>and I get the following error</p> <blockquote> <p>Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.</p> </blockquote> <p>What might be the problem?</p>
16,347,026
15
0
null
2013-05-02 19:02:21.46 UTC
13
2017-03-10 04:51:47.283 UTC
null
null
null
null
1,459,339
null
1
52
facebook|authentication|facebook-login|sign
137,422
<p>The problem is that whatever url you are currently hosting your app is not setup in your Application configuration. Go to your app settings and ensure the urls are matching.</p> <p><strong>Updated</strong></p> <p>Steps:</p> <ol> <li>Go to 'Basic' settings for your app</li> <li>Select 'Add Platform'</li> <li>Select 'Website'</li> <li>Put your website URL under 'Site URL'</li> </ol> <p><img src="https://i.stack.imgur.com/7p86n.jpg" alt="enter image description here"></p>
16,090,487
Find a string of text in an element and wrap some span tags round it
<p>I want to find a string of text in an element and wrap some span tags round it. E.g.</p> <p>From:</p> <pre><code>&lt;h2&gt;We have cows on our farm&lt;/h2&gt; </code></pre> <p>To:</p> <pre><code>&lt;h2&gt;We have &lt;span class='smallcaps'&gt;cows&lt;/span&gt; on our farm&lt;/h2&gt; </code></pre> <p>I've tried:</p> <pre><code>$("h2:contains('cow')").each(function() { $(this).text().wrap("&lt;span class='smallcaps'&gt;&lt;/span&gt;"); }); </code></pre> <p>But that only wraps the whole containing <code>h2</code> tag.</p>
16,090,562
6
0
null
2013-04-18 18:27:27.003 UTC
15
2019-12-26 21:46:40.717 UTC
2019-04-18 04:23:50.72 UTC
null
965,146
null
861,235
null
1
53
jquery|string|text
62,021
<pre><code>$("h2:contains('cow')").html(function(_, html) { return html.replace(/(cow)/g, '&lt;span class="smallcaps"&gt;$1&lt;/span&gt;'); }); </code></pre> <p><a href="http://jsfiddle.net/w5ze6/1/" rel="noreferrer">http://jsfiddle.net/w5ze6/1/</a></p>
11,708,112
How to send multiple values in a href link in PHP?
<p>I want to send multiple values to a different page using a <code>href</code> link. But what I retrieve is the first 2 values only, rest shows an error of undefined index.</p> <p>My code is:</p> <pre><code>&lt;?php echo "&lt;a href='index.php?choice=search&amp;cat=".$cat."&amp;subcat=".$subcat."&amp;srch=".$srch."&amp;page=".$next."'&gt; Next &lt;/a&gt;"; ?&gt; </code></pre> <p>I get the values of "choice" and "cat" only. Please tell me whats wrong in the above code.</p>
11,708,140
2
1
null
2012-07-29 09:23:35.883 UTC
1
2018-07-24 05:06:56.127 UTC
2018-07-24 05:06:56.127 UTC
null
1,462,282
null
1,462,282
null
1
2
php
40,359
<p>try using urlencode, as if there are any special characters in the strings, it could have an effect on the querystring as a whole;</p> <pre><code>echo "&lt;a href='index.php?choice=search&amp;cat=".urlencode($cat)."&amp;subcat=".urlencode($subcat)."&amp;srch=".urlencode($srch)."&amp;page=".urlencode($next)."'&gt; Next &lt;/a&gt;"; </code></pre> <p>Plus you had a space between srch and page, that could have been causing a problem.</p>
21,592,734
Conflict between jquery and bootstrap
<p>I have a code where I am including jquery files and bootstrap files in the header.php. I am running into issues where if I include the jquery file before bootstrap.js file, it messes up the other tabs on my webpage and basically even if i click on the other tabs it does not navigate me. </p> <p>I think there is a conflict between jquery and bootstrap. I am pasting my header.php file below for more reference. </p> <p>header.php</p> <pre><code>&lt;?php require_once "essentials.php"; //error_reporting(~0); //ini_set('display_errors', 1); ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;!--&lt;style&gt;{height:150px; width:1300px;}&lt;/style&gt;--&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;META HTTP-EQUIV="CACHE-CONTROL" CONTENT="Public"&gt; &lt;title&gt;&lt;?php echo $page_title?&gt;&lt;/title&gt; &lt;script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/bootstrap.js"&gt;&lt;/script&gt; &lt;script src="script_dbafactory.js?&lt;?php echo rand(0,511);?&gt;"&gt;&lt;/script&gt; &lt;link href="css/bootstrap.css" rel="stylesheet"&gt; &lt;!--&lt;link href="css/style_header.css" rel="stylesheet"&gt;--&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="row clearfix"&gt; &lt;div class="col-md-4 column"&gt; &lt;img alt="logo" src="./images/source.png"&gt; &lt;/div&gt; &lt;div class="col-md-8 column dbf"&gt; &lt;h2&gt; DBA Factory &lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row clearfix"&gt; &lt;div class="col-md-12 column"&gt; &lt;div class="tabbable" id="tabs-775712"&gt; &lt;ul class="nav nav-tabs"&gt; &lt;li&gt; &lt;a href="../dbafactory/home_page.php?sub=1" data-toggle="tab"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="../dbafactory/form_page.php?sub=2" data-toggle="tab"&gt;Submit a project&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="../dbafactory/view_table.php?sub=3" data-toggle="tab"&gt;All Projects&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#panel-4" data-toggle="tab"&gt;Innovative Ideas&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#panel-5" data-toggle="tab"&gt;Matchmaker&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#panel-6" data-toggle="tab"&gt;Meet the Team&lt;/a&gt; &lt;/li&gt; &lt;div class="dropdown"&gt; &lt;?php include "userlogin.php"; ?&gt; &lt;/div&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;!--&lt;script type="text/javascript"&gt; //Script to implement tabs $('#myTab a').click(function (e) { e.preventDefault() $(this).tab('show') }) &lt;/script&gt;--&gt; &lt;script&gt; $.noConflict(); $(document).ready(function (){ $('.dropdown-toggle').dropdown(); $('#userlogin').dropdown('toggle'); }); &lt;/script&gt; </code></pre> <p>Can someone please let me know how do i solve this issue? and how should i load all the js and css files to avoid any issues with the webpage. </p> <p>Thanks</p>
21,593,226
2
10
null
2014-02-06 02:15:31.94 UTC
2
2016-12-09 14:14:58.373 UTC
2014-02-18 12:17:35.57 UTC
null
607,004
null
2,840,460
null
1
5
javascript|php|jquery|css|twitter-bootstrap
45,765
<p>data-toggle="tab" for bootstrap means there has to have a [tab panel] for it, however, you only use it as nav, and it caused the problem.</p> <p>Please read: <a href="http://getbootstrap.com/javascript/#tabs" rel="noreferrer">http://getbootstrap.com/javascript/#tabs</a></p> <p>Also, use js closure can more easier to avoid js conflict issue:</p> <pre><code>(function($){ .... })(jQuery); </code></pre> <p>Please check the code below, you can use WinMerge to compare the code with your own:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;!--&lt;style&gt;{height:150px; width:1300px;}&lt;/style&gt;--&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;META HTTP-EQUIV="CACHE-CONTROL" CONTENT="Public"&gt; &lt;title&gt;&lt;?php echo $page_title ?&gt;&lt;/title&gt; &lt;script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet"&gt; &lt;!--&lt;link href="css/style_header.css" rel="stylesheet"&gt;--&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="row clearfix"&gt; &lt;div class="col-md-4 column"&gt; &lt;/div&gt; &lt;div class="col-md-8 column dbf"&gt; &lt;h2&gt; DBA Factory &lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row clearfix"&gt; &lt;div class="col-md-12 column"&gt; &lt;div class="tabbable" id="tabs-775712"&gt; &lt;ul class="nav nav-tabs"&gt; &lt;li&gt; &lt;a href="#panel-4"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#panel-4"&gt;Submit a project&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#panel-4"&gt;All Projects&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#panel-4"&gt;Innovative Ideas&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#panel-5"&gt;Matchmaker&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#panel-6"&gt;Meet the Team&lt;/a&gt; &lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a id="userlogin" role="button" data-toggle="dropdown" href="#"&gt;rdesai&lt;span class="caret"&lt;/span&gt;&lt;/a&gt; &lt;ul class="dropdown-menu" role="menu" aria-labelledby="userlogin"&gt; &lt;li role="presentation"&gt;&lt;a role="menuitem" tabindex="-1" href="#"&gt;Settings&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script&gt; (function($){ $(document).ready(function (){ $('.dropdown-toggle').dropdown(); $('#userlogin').dropdown('toggle'); }); })(jQuery); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
17,136,536
is ENOENT from fs.createReadStream uncatchable?
<p>I'm not able to catch ENOENT of fs.createReadStream(). Is this an asynchronous function , which throws exception in a different closure-chain ?</p> <pre><code>$ node -v v0.10.9 $ cat a.js fs = require('fs') try { x = fs.createReadStream('foo'); } catch (e) { console.log("Caught" ); } $ node a.js events.js:72 throw er; // Unhandled 'error' event ^ Error: ENOENT, open 'foo' </code></pre> <p>I am expecting 'Caught' to be printed rather than error stack !</p>
17,136,825
1
0
null
2013-06-16 18:49:57.783 UTC
7
2021-07-12 06:36:42.457 UTC
null
null
null
null
414,441
null
1
45
node.js
11,661
<p><code>fs.createReadStream</code> is asynchronous with the event emitter style and does not throw exceptions (which only make sense for synchronous code). Instead it will emit an error event.</p> <pre class="lang-js prettyprint-override"><code>const fs = require('fs') const stream = fs.createReadStream('foo'); stream.on('error', function (error) {console.log(&quot;Caught&quot;, error);}); stream.on('ready', function () {stream.read();}); </code></pre>
36,777,840
How to validate phone number in laravel 5.2?
<p>I want to validate user input phone number where number should be exactly 11 and started with 01 and value field should be number only. How do I do it using Laravel validation?</p> <p>Here is my controller:</p> <pre><code> public function saveUser(Request $request){ $this-&gt;validate($request,[ 'name' =&gt; 'required|max:120', 'email' =&gt; 'required|email|unique:users', 'phone' =&gt; 'required|min:11|numeric', 'course_id'=&gt;'required' ]); $user = new User(); $user-&gt;name= $request-&gt;Input(['name']); $user-&gt;email= $request-&gt;Input(['email']); $user-&gt;phone= $request-&gt;Input(['phone']); $user-&gt;date = date('Y-m-d'); $user-&gt;completed_status = '0'; $user-&gt;course_id=$request-&gt;Input(['course_id']); $user-&gt;save(); return redirect('success'); } </code></pre>
36,810,662
9
3
null
2016-04-21 18:36:32.297 UTC
20
2021-01-15 12:52:12.467 UTC
2016-04-23 11:31:09.567 UTC
null
6,196,521
null
6,196,521
null
1
70
php|laravel|laravel-5.2
221,104
<p>One possible solution would to use regex.</p> <pre><code>'phone' =&gt; 'required|regex:/(01)[0-9]{9}/' </code></pre> <p>This will check the input starts with 01 and is followed by 9 numbers. By using regex you don't need the <code>numeric</code> or <code>size</code> validation rules.</p> <p>If you want to reuse this validation method else where, it would be a good idea to create your own validation rule for validating phone numbers.</p> <p><a href="https://laravel.com/docs/5.4/validation#custom-validation-rules" rel="noreferrer">Docs: Custom Validation</a></p> <p>In your <code>AppServiceProvider</code>'s <code>boot</code> method:</p> <pre><code>Validator::extend('phone_number', function($attribute, $value, $parameters) { return substr($value, 0, 2) == '01'; }); </code></pre> <p>This will allow you to use the <code>phone_number</code> validation rule anywhere in your application, so your form validation could be:</p> <pre><code>'phone' =&gt; 'required|numeric|phone_number|size:11' </code></pre> <p>In your validator extension you could also check if the <code>$value</code> is numeric and 11 characters long.</p>
18,682,486
Why does Spring MVC need at least two contexts?
<p>In Spring MVC, there are two contexts. One is the application context or global context which is booted up by <code>ContextLoaderListener</code>. It takes all the configuration files mentioned in <code>contextConfigLocation</code> parameter.</p> <p>Now if you are using Spring MVC as well, then Dispatcher servlet is required, which boots up another container which is also known as web application container. This container takes the global container as a parent.</p> <p>When integrating struts1 with spring, there is only one context. Why does spring mvc need two? Is it possible to use only one context when using spring mvc?</p> <p>thanks!</p>
18,684,288
3
0
null
2013-09-08 10:03:30.343 UTC
23
2013-09-09 12:36:44.27 UTC
2013-09-09 08:55:12.42 UTC
null
1,276,804
null
676,319
null
1
22
java|spring|servlets|spring-mvc
13,234
<p>Imagine you had two separate Dispatchers, each serving a different purpose, and each having its own dependencies. You would configure those independently using separate contexts.</p> <p>If there is any shared configuration, this can go in the 'global' context.</p> <p>I don't think it's possible to have only one context using DispatcherServlet, as it creates its own context and links it to the parent context (via the FrameworkServlet superclass).</p> <p><a href="http://grepcode.com/file/repo1.maven.org/maven2/org.springframework/spring-webmvc/3.2.3.RELEASE/org/springframework/web/servlet/FrameworkServlet.java#FrameworkServlet.createWebApplicationContext%28org.springframework.context.ApplicationContext%29" rel="noreferrer"><code>FrameworkServlet.createWebApplicationContext</code></a></p>
18,460,469
Hibernate ManyToOne vs OneToOne
<p>I can't see any difference in the schema of a Many-To-One relationship vs a OneToOne relationship:</p> <pre><code>@Entity public class Order { @ManyToOne @JoinColumn(nullable = false) private Address address; </code></pre> <p>vs</p> <pre><code>@Entity public class Order { @OneToOne @JoinColumn(nullable = false) private Address address; </code></pre> <p>Is there any difference?</p>
18,463,748
4
0
null
2013-08-27 08:22:53.663 UTC
16
2020-07-06 06:43:07.297 UTC
null
null
null
null
249,571
null
1
51
hibernate|one-to-one|many-to-one
20,750
<p>They look exactly the same on schema but there is difference on Hibernate Layer.</p> <p>If you try something like that:</p> <pre><code>Address address = new Address(); Order order1 = new Order(); order1.setAddress(address); Order order2 = new Order(); order2.setAddress(address); save(); </code></pre> <p>Everything will be OK. But, after save if you try get Order:</p> <pre><code>@OneToOne case: org.hibernate.HibernateException: More than one row with the given identifier was found: 1 @ManyToOne case: SUCCESS </code></pre> <p>Of course, your Address class should looks different in both cases.</p>
43,455,911
Using es6 spread to concat multiple arrays
<p>We all know you can do:</p> <pre><code>let arr1 = [1,2,3]; let arr2 = [3,4,5]; let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5] </code></pre> <p>But how do you make this dynamic to concat N arrays?</p>
43,455,982
10
5
null
2017-04-17 17:01:55.29 UTC
10
2021-07-29 07:29:27.563 UTC
2018-07-24 05:05:29.887 UTC
null
2,093,695
null
1,205,871
null
1
63
javascript|ecmascript-6
80,765
<p>One option is to use <code>reduce</code>:</p> <pre><code>let arrs = [[1, 2], [3, 4], [5, 6]]; arrs.reduce((a, b) =&gt; [...a, ...b], []); </code></pre> <p>Of course, this is a slow solution (quadratic time). Alternatively, if you can use Lodash, <code>_.flatten</code> does exactly what you want, and does it more efficiently (linear time).</p> <p><strong>EDIT</strong></p> <p>Or, adapted from Xotic750's comment below,</p> <pre><code>[].concat(...arrs); </code></pre> <p>Which should be efficient (linear time).</p>
25,924,720
FileNotFoundError: [Errno 2]
<p>Synopsis: How do I read a file in Python? why must it be done this way?</p> <p>My problem is that I get the following error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\Terminal\Desktop\wkspc\filetesting.py", line 1, in &lt;module&gt; testFile=open("test.txt") FileNotFoundError: [Errno 2] No such file or directory: 'test.txt' </code></pre> <p>Which originates from the following code: (that is the entire '.py' file)</p> <pre><code>testFile=open("test.txt") print(testFile.read()) </code></pre> <p>"test.txt" is in the same folder as my program. I'm new to Python and do not understand why I am getting file location errors. I'd like to know the fix and why the fix has to be done that way.</p> <p>I have tried using the absolute path to the file, "C:\Users\Terminal\Desktop\wkspc\test.txt"</p> <p>Other details:</p> <pre><code>"Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32" Windows 7, 32 Bit </code></pre>
25,924,992
1
4
null
2014-09-19 00:55:42.27 UTC
3
2022-09-04 01:28:50.847 UTC
2014-09-19 01:46:03.057 UTC
null
4,056,507
null
4,056,507
null
1
2
python|python-3.x|file-io
42,823
<p>Since you are using IDLE(GUI) the script may not be launched from the directory where the script resides. I think the best alternative is to go with something like:</p> <pre><code>import os.path scriptpath = os.path.dirname(__file__) filename = os.path.join(scriptpath, 'test.txt') testFile=open(filename) print(testFile.read()) </code></pre> <p><code>os.path.dirname(__file__)</code> will find the directory where the currently running script resides. It then uses <code>os.path.join</code> to prepend <code>test.txt</code> with that path.</p> <p>If this doesn't work then I can only guess that <code>test.txt</code> isn't actually in the same directory as the script you are running.</p>
9,249,708
Is there a non Java alternative to OSGi?
<p>Is there an OSGi like framework that is based on C/C++? I have plenty of legacy code in C/C++ that would be too expensive to be ported to Java.</p>
9,324,514
3
3
null
2012-02-12 14:51:55.953 UTC
12
2018-06-29 23:09:51.543 UTC
2012-02-12 14:56:03.937 UTC
null
635,608
null
677,228
null
1
11
java|c++|osgi
8,512
<p>Here is a list of OSGi-like C/C++ frameworks I know of (and which are still active):</p> <ul> <li><a href="http://incubator.apache.org/celix/" rel="nofollow noreferrer">Apache Celix</a> [Language: C, License: Apache License 2.0]</li> <li><a href="http://sof.tiddlyspot.com/" rel="nofollow noreferrer">SOF</a> [Language: C++, License: Unknown]</li> <li><a href="http://www.commontk.org/index.php/Documentation/Plugin_Framework" rel="nofollow noreferrer">CTK</a> [Language: C++, License: Apache License 2.0]</li> <li><a href="http://www-vs.informatik.uni-ulm.de/proj/nosgi/" rel="nofollow noreferrer">nOSGi</a> [Language: C++, License: GPLv3]</li> <li><a href="http://www.appinf.com/en/products/osp.html" rel="nofollow noreferrer">Poco OSP</a> [Language: C++, License: Commercial]</li> <li><a href="http://cppmicroservices.org/" rel="nofollow noreferrer">CppMicroServices</a> [Language: C++, License: Apache License 2.0]</li> </ul> <p>This <a href="http://blog.cppmicroservices.org/2012/03/29/osgi-and-c++/" rel="nofollow noreferrer">blog post</a> gives a high-level overview about these frameworks.</p>
9,457,037
what does .dtype do?
<p>I am new to Python, and don't understand what <code>.dtype</code> does. <br>For example:</p> <pre><code>&gt;&gt;&gt; aa array([1, 2, 3, 4, 5, 6, 7, 8]) &gt;&gt;&gt; aa.dtype = "float64" &gt;&gt;&gt; aa array([ 4.24399158e-314, 8.48798317e-314, 1.27319747e-313, 1.69759663e-313]) </code></pre> <p>I thought dtype is a property of aa, which should be int, and if I assign <code>aa.dtype = "float64"</code> <br> then<code>aa</code> should become <code>array([1.0 ,2.0 ,3.0, 4.0, 5.0, 6.0, 7.0, 8.0])</code>.</p> <p>Why does it changes its value and size? <br>What does it mean?</p> <p>I was actually learning from a piece of code, and shall I paste it here:</p> <pre><code>def to_1d(array): """prepares an array into a 1d real vector""" a = array.copy() # copy the array, to avoid changing global orig_dtype = a.dtype a.dtype = "float64" # this doubles the size of array orig_shape = a.shape return a.ravel(), (orig_dtype, orig_shape) #flatten and return </code></pre> <p>I think it shouldn't change the value of the input array but only change its size. Confused of how the function works</p>
9,457,302
4
3
null
2012-02-26 20:52:19.85 UTC
10
2018-07-19 04:24:48.907 UTC
2018-07-19 04:24:48.907 UTC
null
266,068
null
1,233,157
null
1
19
python|numpy
39,383
<p>First off, the code you're learning from is flawed. It almost certainly doesn't do what the original author thought it did based on the comments in the code.</p> <p>What the author probably meant was this:</p> <pre><code>def to_1d(array): """prepares an array into a 1d real vector""" return array.astype(np.float64).ravel() </code></pre> <p>However, if <code>array</code> is always going to be an array of complex numbers, then the original code makes some sense.</p> <p>The only cases where viewing the array (<code>a.dtype = 'float64'</code> is equivalent to doing <code>a = a.view('float64')</code>) would double its size is if it's a complex array (<code>numpy.complex128</code>) or a 128-bit floating point array. For any other dtype, it doesn't make much sense.</p> <p>For the specific case of a <em>complex</em> array, the original code would convert something like <code>np.array([0.5+1j, 9.0+1.33j])</code> into <code>np.array([0.5, 1.0, 9.0, 1.33])</code>.</p> <p>A cleaner way to write that would be:</p> <pre><code>def complex_to_iterleaved_real(array): """prepares a complex array into an "interleaved" 1d real vector""" return array.copy().view('float64').ravel() </code></pre> <p>(I'm ignoring the part about returning the original dtype and shape, for the moment.)</p> <hr> <h1>Background on numpy arrays</h1> <p>To explain what's going on here, you need to understand a bit about what numpy arrays are. </p> <p>A numpy array consists of a "raw" memory buffer that is interpreted as an array through "views". You can think of all numpy arrays as views.</p> <p>Views, in the numpy sense, are just a different way of slicing and dicing the same memory buffer without making a copy.</p> <p>A view has a shape, a data type (dtype), an offset, and strides. Where possible, indexing/reshaping operations on a numpy array will just return a view of the original memory buffer.</p> <p>This means that things like <code>y = x.T</code> or <code>y = x[::2]</code> don't use any extra memory, and don't make copies of <code>x</code>.</p> <p>So, if we have an array similar to this:</p> <pre><code>import numpy as np x = np.array([1,2,3,4,5,6,7,8,9,10]) </code></pre> <p>We could reshape it by doing either:</p> <pre><code>x = x.reshape((2, 5)) </code></pre> <p>or </p> <pre><code>x.shape = (2, 5) </code></pre> <p>For readability, the first option is better. They're (almost) exactly equivalent, though. Neither one will make a copy that will use up more memory (the first will result in a new python object, but that's beside the point, at the moment.).</p> <hr> <h1>Dtypes and views</h1> <p>The same thing applies to the dtype. We can view an array as a different dtype by either setting <code>x.dtype</code> or by calling <code>x.view(...)</code>.</p> <p>So we can do things like this:</p> <pre><code>import numpy as np x = np.array([1,2,3], dtype=np.int) print 'The original array' print x print '\n...Viewed as unsigned 8-bit integers (notice the length change!)' y = x.view(np.uint8) print y print '\n...Doing the same thing by setting the dtype' x.dtype = np.uint8 print x print '\n...And we can set the dtype again and go back to the original.' x.dtype = np.int print x </code></pre> <p>Which yields:</p> <pre><code>The original array [1 2 3] ...Viewed as unsigned 8-bit integers (notice the length change!) [1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0] ...Doing the same thing by setting the dtype [1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0] ...And we can set the dtype again and go back to the original. [1 2 3] </code></pre> <p>Keep in mind, though, that this is giving you low-level control over the way that the memory buffer is interpreted. </p> <p>For example:</p> <pre><code>import numpy as np x = np.arange(10, dtype=np.int) print 'An integer array:', x print 'But if we view it as a float:', x.view(np.float) print "...It's probably not what we expected..." </code></pre> <p>This yields:</p> <pre><code>An integer array: [0 1 2 3 4 5 6 7 8 9] But if we view it as a float: [ 0.00000000e+000 4.94065646e-324 9.88131292e-324 1.48219694e-323 1.97626258e-323 2.47032823e-323 2.96439388e-323 3.45845952e-323 3.95252517e-323 4.44659081e-323] ...It's probably not what we expected... </code></pre> <p>So, we're interpreting the underlying bits of the original memory buffer as floats, in this case.</p> <p><strong>If we wanted to make a new copy with the ints recasted as floats, we'd use x.astype(np.float).</strong></p> <hr> <h1>Complex Numbers</h1> <p>Complex numbers are stored (in both C, python, and numpy) as two floats. The first is the real part and the second is the imaginary part.</p> <p>So, if we do:</p> <pre><code>import numpy as np x = np.array([0.5+1j, 1.0+2j, 3.0+0j]) </code></pre> <p>We can see the real (<code>x.real</code>) and imaginary (<code>x.imag</code>) parts. If we convert this to a float, we'll get a warning about discarding the imaginary part, and we'll get an array with just the real part.</p> <pre><code>print x.real print x.astype(float) </code></pre> <p><code>astype</code> makes a copy and converts the values to the new type.</p> <p>However, if we view this array as a float, we'll get a sequence of <code>item1.real, item1.imag, item2.real, item2.imag, ...</code>. </p> <pre><code>print x print x.view(float) </code></pre> <p>yields:</p> <pre><code>[ 0.5+1.j 1.0+2.j 3.0+0.j] [ 0.5 1. 1. 2. 3. 0. ] </code></pre> <p>Each complex number is essentially two floats, so if we change how numpy interprets the underlying memory buffer, we get an array of twice the length.</p> <p>Hopefully that helps clear things up a bit...</p>
18,545,905
Meteor without mongo
<p>With 0.6.5 release it is possible to develop non web apps with meteor. I rebuild it from scratch for ARM processor but I don't want DB support at all. (Mongo is a processor killer, has to high footprint and I simply don't need it)</p> <p>ARM should work as DDP client only, with this in mind I build it manually without mongo.</p> <p>And tried to build simplest app possible only 1 package at start (all standard packages removed)</p> <pre><code>meteor </code></pre> <p>and one file in server folder</p> <pre><code>main = function(argv){ return "DAEMON" } Meteor.setInterval(function(){ console.log("HellOnWorld"); },1000); </code></pre> <p>On machine with full meteor install it works as expected but without mongo installed I got errors</p> <pre><code>Unexpected mongo exit code 127. Restarting. Unexpected mongo exit code 127. Restarting. Initializing mongo database... this may take a moment. Unexpected mongo exit code 127. Restarting. Can't start mongod </code></pre> <p>Obviously I don't have and want mongo.</p> <p>Is there any way to start meteor without waiting for mongo db ?</p> <p>Meteor team plans to support other db's so it must be implemented sooner or later.</p>
18,546,761
6
5
null
2013-08-31 07:55:39.707 UTC
13
2015-11-29 02:35:22.487 UTC
2013-08-31 14:16:03.46 UTC
null
2,338,653
null
2,338,653
null
1
15
mongodb|meteor
10,759
<p><strong>UPDATE</strong></p> <p>For newer versions of Meteor you need to remove the <code>mongo</code> package. The mongo package is embedded in the <code>meteor-platform</code> package. So you need to remove that and add all the rest back (from <a href="https://github.com/meteor/meteor/tree/devel/packages/meteor-platform" rel="noreferrer">https://github.com/meteor/meteor/tree/devel/packages/meteor-platform</a>):</p> <pre><code>meteor remove meteor-platform meteor add meteor webapp logging tracker session ddp blaze spacebars templating check underscore jquery random ejson templating check underscore jquery random ejson </code></pre> <p>Then your app won't use Mongo anymore :).</p> <p>In dev mode you can get rid of mongo by setting the <code>MONGO_URL</code> environment variable to something else and start meteor. For example: <code>MONGO_URL=mongodb://nowhere meteor</code></p>
18,429,620
CSS background-size: cover replacement for Mobile Safari
<p>Hi I have several divs on my page which have background images that I want to expand to cover the entire div which in turn can expand to fill the width of the viewport.</p> <p>Obviously <code>background-size: cover</code> behaves unexpectedly on iOS devices. I've seen some examples of how to fix it, but I can't make them work in my situation. Ideally I'd prefer not to add extra <code>&lt;img&gt;</code> tags to the HTML but if it's the only way then I will.</p> <p>Here is my code:</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>.section { margin: 0 auto; position: relative; padding: 0 0 320px 0; width: 100%; } #section1 { background: url(...) 50% 0 no-repeat fixed; background-size: cover; } #section2 { background: url(...) 50% 0 no-repeat fixed; background-size: cover; } #section3 { background: url(...) 50% 0 no-repeat fixed; background-size: cover; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;div id="section1" class="section"&gt; ... &lt;/div&gt; &lt;div id="section2" class="section"&gt; ... &lt;/div&gt; &lt;div id="section3" class="section"&gt; ... &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <p>The question is, how can I get the background image to completely cover the section div, taking into account the variable width of the browser and the variable height of the content in the div?</p>
18,433,446
10
0
null
2013-08-25 13:45:22.657 UTC
33
2018-03-08 07:35:28.217 UTC
2018-03-08 07:35:28.217 UTC
null
5,096,465
null
862,410
null
1
57
html|css|mobile-safari
170,223
<p>I've had this issue on a lot of mobile views I've recently built. </p> <p>My solution is still a pure CSS Fallback</p> <p><a href="http://css-tricks.com/perfect-full-page-background-image/" rel="noreferrer">http://css-tricks.com/perfect-full-page-background-image/</a> as three great methods, the latter two are fall backs for when CSS3's cover doesn't work. </p> <p><strong>HTML</strong></p> <pre><code>&lt;img src="images/bg.jpg" id="bg" alt=""&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>#bg { position: fixed; top: 0; left: 0; /* Preserve aspect ratio */ min-width: 100%; min-height: 100%; } </code></pre>
20,019,522
Scrolling background - Sprite Kit
<p>So I tried to create an infinite scrolling background by using this post's solution (<a href="https://stackoverflow.com/questions/19349168/sprite-kit-side-scrolling">Sprite kit side scrolling</a>). However, I would want to make the image repeatable. As you can see in the video below, after the image has finished it's horizontal way, there is some empty gap.. I would like to make the image fill that gap, so repeat it endlessly.</p> <p><a href="http://www.youtube.com/watch?v=kyLTGz7Irrc" rel="nofollow noreferrer">http://www.youtube.com/watch?v=kyLTGz7Irrc</a> or <a href="https://vimeo.com/79555900" rel="nofollow noreferrer">https://vimeo.com/79555900</a> (password: spritekit)</p> <p>What I did : </p> <pre><code>for (int i = 0; i &lt; 2; i++) { SKSpriteNode * bg = [SKSpriteNode spriteNodeWithImageNamed:@"bgimage"]; bg.anchorPoint = CGPointZero; bg.position = CGPointMake(CGRectGetMidX(self.frame), self.frame.origin.y); bg.name = @"snow1"; [self addChild:bg]; } </code></pre> <p>and in update method:</p> <pre><code>[self enumerateChildNodesWithName:@"snow1" usingBlock: ^(SKNode *node, BOOL *stop) { SKSpriteNode *bg = (SKSpriteNode *) node; bg.position = CGPointMake(bg.position.x - 5, bg.position.y); if (bg.position.x &lt;= -bg.size.width) bg.position = CGPointMake(bg.position.x + bg.size.width * 2, bg.position.y); }]; </code></pre>
20,020,023
3
2
null
2013-11-16 14:22:48.873 UTC
13
2016-07-14 09:57:45.44 UTC
2017-05-23 12:24:54.597 UTC
null
-1
null
2,604,030
null
1
10
ios|iphone|ios7|xcode5|sprite-kit
10,548
<p>Anyway, I fixed it. Just in case someone else will need it, this is how I did it: </p> <pre><code> // Create 2 background sprites bg1 = [SKSpriteNode spriteNodeWithImageNamed:@"bg1"]; bg1.anchorPoint = CGPointZero; bg1.position = CGPointMake(0, 0); [self addChild:bg1]; bg2 = [SKSpriteNode spriteNodeWithImageNamed:@"bg2"]; bg2.anchorPoint = CGPointZero; bg2.position = CGPointMake(bg1.size.width-1, 0); [self addChild:bg2]; </code></pre> <p>then in the update method: </p> <pre><code> bg1.position = CGPointMake(bg1.position.x-4, bg1.position.y); bg2.position = CGPointMake(bg2.position.x-4, bg2.position.y); if (bg1.position.x &lt; -bg1.size.width) bg1.position = CGPointMake(bg2.position.x + bg2.size.width, bg1.position.y); if (bg2.position.x &lt; -bg2.size.width) bg2.position = CGPointMake(bg1.position.x + bg1.size.width, bg2.position.y); </code></pre>
27,572,387
Query that returns the size of a table in a SQLite database
<p>I have a SQLite database that contains a number of tables. We are writing a maintenance tool that will remove "stale" data from a table until that table's size is a certain percentage of the total database file or smaller.</p> <p>I know how to determine the size of the database file -- I do it by executing</p> <pre><code>PRAGMA PAGE_SIZE; </code></pre> <p>and</p> <pre><code>PRAGMA PAGE_COUNT; </code></pre> <p>in two separate queries and multiplying the two to get the file size in bytes. Yes, I know I can just take the size of the file in bytes, but this is similar to the way I've done it in other databases and I want to stick with it, at least for now.</p> <p>My problem is I don't know how to get the size of a TABLE. There has to be some way to do this. Can anyone point me in the right direction?</p>
36,627,097
3
5
null
2014-12-19 19:05:38.677 UTC
6
2022-03-13 06:41:22.503 UTC
null
null
null
null
784,187
null
1
30
database|sqlite
45,296
<p>There's no easy way to query the size of a table. So what I ended up doing is coming up with an estimate of the table's size by multiplying the number of rows by an estimate of the row's size. I manually summed the length of the integer columns (4 bytes each), plus the sum of the length of the long columns (8 bytes each), plus an estimate of the average length of the string columns using a query. Something like this:</p> <pre><code>SELECT COUNT(*) * -- The number of rows in the table ( 24 + -- The length of all 4 byte int columns 12 + -- The length of all 8 byte int columns 128 ) -- The estimate of the average length of all string columns FROM MyTable </code></pre> <p>The only problems with this are that:</p> <ul> <li>It will overestimate the size of any row with an integer or long column that can be null, and that happens to be null</li> <li>It will overestimate or underestimate the length of the string columns.</li> <li>It does not take into account the size of the indexes.</li> </ul> <p>This was good enough for our implementation. You might be able to do a better job computing the table's size with a more complicated query that takes nulls &amp; the actual length of the string columns into account.</p>
15,429,142
Add Maven repositories for a project in Eclipse?
<p>How can I add Maven repositories for a project. I'm using Eclipse Juno version: Juno Service Release 1 Build id: 20120920-0800 and using Fedora as my OS.</p>
15,433,090
3
0
null
2013-03-15 09:49:10.047 UTC
null
2019-12-04 10:29:49.16 UTC
2015-06-14 16:45:13.753 UTC
null
3,379,653
null
1,584,390
null
1
18
eclipse|repository|eclipse-juno
88,981
<p>You can include it in your <code>pom.xml</code>. Just add the repositories information inside the <code>&lt;project&gt;</code> tag</p> <pre><code>&lt;repositories&gt; &lt;repository&gt; &lt;id&gt;maven-restlet&lt;/id&gt; &lt;name&gt;Public online Restlet repository&lt;/name&gt; &lt;url&gt;http://maven.restlet.org&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; </code></pre>
15,134,720
Sitecore 'dynamic placeholders' with MVC
<p>I'm looking for a working Dynamic Placeholder solution in MVC. There are at least two good descriptions of this "pattern" for use with WebForms:</p> <ul> <li><a href="http://trueclarity.wordpress.com/2012/06/19/dynamic-placeholder-keys-in-sitecore/">http://trueclarity.wordpress.com/2012/06/19/dynamic-placeholder-keys-in-sitecore/</a></li> <li><a href="http://www.techphoria414.com/Blog/2011/August/Dynamic_Placeholder_Keys_Prototype">http://www.techphoria414.com/Blog/2011/August/Dynamic_Placeholder_Keys_Prototype</a></li> </ul> <p>And I also found this blog explaining how to do it with MVC:</p> <ul> <li><a href="http://blogs.perficient.com/portals/2012/10/17/sitecore-mvc-dynamic-placeholders/">http://blogs.perficient.com/portals/2012/10/17/sitecore-mvc-dynamic-placeholders/</a></li> </ul> <p>First I have tried to implement Techphoria's method (with GUIDs) using techniques from the MVC blogpost (extension of the SitecoreHelper) and I also tried implementing the last described method (uses number suffixes that are incremented Column_1, Column_2, etc).</p> <p>With all the variations I tried I didn't succeed in creating a working solution. My placeholders don't get properly named (I ended up with strange placeholder structures, or placeholders repeating themselves).</p> <p><strong>Without going into the specifics of my attempts, I would like to know if anyone else has a working solution ready that I could use.</strong></p> <p>If I can't find an already working solution, I will describe my problem in more detail and see if I can get that to work.</p>
15,135,796
2
0
null
2013-02-28 11:45:54.203 UTC
15
2016-07-19 13:23:26.27 UTC
2014-10-30 15:57:53.61 UTC
null
157,833
null
181,142
null
1
24
asp.net|asp.net-mvc|sitecore|sitecore6|sitecore-mvc
15,540
<p>I created this extension that creates dynamic placholders</p> <pre><code>public static class SitecoreHelper { public static HtmlString DynamicPlaceholder(this Sitecore.Mvc.Helpers.SitecoreHelper helper, string dynamicKey) { var currentRenderingId = RenderingContext.Current.Rendering.UniqueId; return helper.Placeholder(string.Format("{0}_{1}", dynamicKey, currentRenderingId)); } } </code></pre> <p>It creates a placeholder with the guid in the name. I also created a step in the pipeline that extracts the guid, and checks for placeholder settings.</p> <p>Code to get placeholder settings to the dynamic placeholder If you create a dynamic placeholder with @Html.Sitecore().DynamicPlaceholder("test") - the following code takes the setting from the placeholder settings named test</p> <pre><code> /// &lt;summary&gt; /// Handles changing context to the references dynamic "master" renderings settings for inserting the allowed controls for the placeholder and making it editable /// &lt;/summary&gt; public class GetDynamicKeyAllowedRenderings : GetAllowedRenderings { //text that ends in a GUID private const string DYNAMIC_KEY_REGEX = @"(.+)_[\d\w]{8}\-([\d\w]{4}\-){3}[\d\w]{12}"; public new void Process(GetPlaceholderRenderingsArgs args) { Assert.IsNotNull(args, "args"); string placeholderKey = args.PlaceholderKey; Regex regex = new Regex(DYNAMIC_KEY_REGEX); Match match = regex.Match(placeholderKey); if (match.Success &amp;&amp; match.Groups.Count &gt; 0) { placeholderKey = match.Groups[1].Value; } else { return; } // Same as Sitecore.Pipelines.GetPlaceholderRenderings.GetAllowedRenderings but with fake placeholderKey Item placeholderItem = null; if (ID.IsNullOrEmpty(args.DeviceId)) { placeholderItem = Client.Page.GetPlaceholderItem(placeholderKey, args.ContentDatabase, args.LayoutDefinition); } else { using (new DeviceSwitcher(args.DeviceId, args.ContentDatabase)) { placeholderItem = Client.Page.GetPlaceholderItem(placeholderKey, args.ContentDatabase, args.LayoutDefinition); } } List&lt;Item&gt; collection = null; if (placeholderItem != null) { bool flag; args.HasPlaceholderSettings = true; collection = this.GetRenderings(placeholderItem, out flag); if (flag) { args.CustomData["allowedControlsSpecified"] = true; args.Options.ShowTree = false; } } if (collection != null) { if (args.PlaceholderRenderings == null) { args.PlaceholderRenderings = new List&lt;Item&gt;(); } args.PlaceholderRenderings.AddRange(collection); } } } </code></pre> <p>The following code removes the guid from the chrome data in the pageeditor</p> <pre><code>/// &lt;summary&gt; /// Replaces the Displayname of the Placeholder rendering with the dynamic "parent" /// &lt;/summary&gt; public class GetDynamicPlaceholderChromeData : GetChromeDataProcessor { //text that ends in a GUID private const string DYNAMIC_KEY_REGEX = @"(.+)_[\d\w]{8}\-([\d\w]{4}\-){3}[\d\w]{12}"; public override void Process(GetChromeDataArgs args) { Assert.ArgumentNotNull(args, "args"); Assert.IsNotNull(args.ChromeData, "Chrome Data"); if ("placeholder".Equals(args.ChromeType, StringComparison.OrdinalIgnoreCase)) { string argument = args.CustomData["placeHolderKey"] as string; string placeholderKey = argument; Regex regex = new Regex(DYNAMIC_KEY_REGEX); Match match = regex.Match(placeholderKey); if (match.Success &amp;&amp; match.Groups.Count &gt; 0) { // Is a Dynamic Placeholder placeholderKey = match.Groups[1].Value; } else { return; } // Handles replacing the displayname of the placeholder area to the master reference Item item = null; if (args.Item != null) { string layout = ChromeContext.GetLayout(args.Item); item = Sitecore.Client.Page.GetPlaceholderItem(placeholderKey, args.Item.Database, layout); if (item != null) { args.ChromeData.DisplayName = item.DisplayName; } if ((item != null) &amp;&amp; !string.IsNullOrEmpty(item.Appearance.ShortDescription)) { args.ChromeData.ExpandedDisplayName = item.Appearance.ShortDescription; } } } } } </code></pre> <p><strong>Edit</strong></p> <p>The web.config include settings are included below:</p> <pre><code>&lt;sitecore&gt; &lt;pipelines&gt; &lt;getPlaceholderRenderings&gt; &lt;processor type="YourNamespace.Pipelines.GetPlaceholderRenderings.GetDynamicKeyAllowedRenderings, YourAssembly" patch:before="processor[@type='Sitecore.Pipelines.GetPlaceholderRenderings.GetAllowedRenderings, Sitecore.Kernel']"/&gt; &lt;/getPlaceholderRenderings&gt; &lt;getChromeData&gt; &lt;processor type="YourNamespace.Pipelines.GetChromeData.GetDynamicPlaceholderChromeData, YourAssembly" patch:after="processor[@type='Sitecore.Pipelines.GetChromeData.GetPlaceholderChromeData, Sitecore.Kernel']"/&gt; &lt;/getChromeData&gt; &lt;/pipelines&gt; &lt;/sitecore&gt; </code></pre>