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
30,479,105
AngularJS - ng-disabled not working for Anchor tag
<p>I am using ng-disabled, I like it. It's working good for me for input and buttons. For anchor tag not working. How can I fix?</p> <p><code>HTML code</code></p> <pre><code>&lt;a ng-disabled="addInviteesDisabled()"&gt;Add&lt;/a&gt; </code></pre> <p><code>JS code</code></p> <pre><code> $scope.addInviteesDisabled = function() { return $scope.event.status === APP_CONSTANTS.STATUSES.PENDING_APPROVAL; }; </code></pre>
30,479,306
14
4
null
2015-05-27 09:57:45.88 UTC
11
2022-07-25 12:42:38.44 UTC
null
null
null
user4870812
null
null
1
66
javascript|html|angularjs
103,717
<p>There is no disabled attribute for hyperlinks. You can do this:</p> <pre><code>.disabled { cursor: not-allowed; } &lt;a ng-click="disabled()" ng-class="{disabled: addInviteesDisabled()}"&gt;Add&lt;/a&gt; $scope.disabled = function() { if($scope.addInviteesDisabled) { return false;} } </code></pre>
23,203,710
floating point operations per cycle - intel
<p>I have been looking for quite a while and cannot seem to find an official/conclusive figure quoting the number of single precision floating point operations/clock cycle that an Intel Xeon quadcore can complete. I have an Intel Xeon quadcore E5530 CPU.</p> <p>I'm hoping to use it to calculate the maximum theoretical FLOP/s my CPU can achieve.</p> <p>MAX FLOPS = (# Number of cores) * (Clock Frequency (cycles/sec) ) * (# FLOPS / cycle)</p> <p>Anything pointing me in the right direction would be useful. I have found this <a href="https://stackoverflow.com/questions/15655835/flops-per-cycle-for-sandy-bridge-and-haswell-sse2-avx-avx2">FLOPS per cycle for sandy-bridge and haswell SSE2/AVX/AVX2</a></p> <blockquote> <p>Intel Core 2 and Nehalem:</p> <p>4 DP FLOPs/cycle: 2-wide SSE2 addition + 2-wide SSE2 multiplication</p> <p>8 SP FLOPs/cycle: 4-wide SSE addition + 4-wide SSE multiplication</p> </blockquote> <p>But I'm not sure where these figures were found. Are they assuming a fused multiply add (FMAD) operation?</p> <p>EDIT: Using this, in DP I calculate the correct DP arithmetic throughput cited by Intel as 38.4 GFLOP/s (cited <a href="http://download.intel.com/support/processors/xeon/sb/xeon_5500.pdf" rel="noreferrer">here</a>). For SP, I get double that, 76.8 GFLOP/s. I'm pretty sure 4 DP FLOP/cycle and 8 SP FLOP/cycle is correct, I just want confirmation of how they got the FLOPs/cycle value of 4 and 8.</p>
23,204,280
1
4
null
2014-04-21 18:45:10.06 UTC
8
2014-04-22 20:15:55.657 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
3,495,341
null
1
10
cpu|intel|cpu-architecture|flops|nehalem
17,743
<p>Nehalem is capable of executing 4 DP or 8 SP FLOP/cycle. This is accomplished using SSE, which operates on packed floating point values, 2/register in DP and 4/register in SP. In order to achieve 4 DP FLOP/cycle or 8 SP FLOP/cycle the core has to execute 2 SSE instructions per cycle. This is accomplished by executing a MULDP and an ADDDP (or a MULSP and an ADDSP) per cycle. The reason this is possible is because Nehalem has separate execution units for SSE multiply and SSE add, and these units are pipelined so that the <code>throughput</code> is one multiply and one add per cycle. Multiplies are in the multiplier pipeline for 4 cycles in SP and 5 cycles in DP. Adds are in the pipeline for 3 cycles independent of SP/DP. The number of cycles in the pipeline is known as the <code>latency</code>. To compute peak FLOP/cycle all you need to know is the throughput. So with a throughput of 1 SSE vector instruction/cycle for both the multiplier and the adder (2 execution units) you have 2 x 2 = 4 FLOP/cycle in DP and 2 x 4 = 8 FLOP/cycle in SP. To actually sustain this peak throughput you need to consider latency (so you have at least as many independent operations in the pipeline as the depth of the pipeline) and you need to consider being able to feed the data fast enough. Nehalem has an integrated memory controller capable of very high bandwidth from memory which it can achieve if the data prefetcher correctly anticipates the access pattern of the data (sequentially loading from memory is a trivial pattern that it can anticipate). Typically there isn't enough memory bandwidth to sustain feeding all cores with data at peak FLOP/cycle, so some amount of reuse of the data from the cache is necessary in order to sustain peak FLOP/cycle.</p> <p>Details on where you can find information on the number of independent execution units and their throughput and latency in cycles follows.</p> <p>See page 105 <strong>8.9 Execution units</strong> of this document</p> <p><a href="http://www.agner.org/optimize/microarchitecture.pdf" rel="noreferrer">http://www.agner.org/optimize/microarchitecture.pdf</a></p> <p>It says that for Nehalem</p> <blockquote> <p>The floating point multiplier on port 0 has a latency of 4 for single precision and 5 for double and long double precision. The throughput of the floating point multiplier is 1 operation per clock cycle, except for long double precision on Core2. The floating point adder is connected to port 1. It has a latency of 3 and is fully pipelined.</p> </blockquote> <p>In order to get 8 SP FLOP/cycle you need 4 SP ADD/cycle and 4 SP MUL/cycle. The adder and the multiplier are on separate execution units, and dispatch out of separate ports, each can execute on 4 SP packed operands simultaneously using SSE packed (vector) instructions (4x32bit = 128bits). Both have throughput of 1 operation per clock cycle. In order to get that throughput, you need to consider the latency... how many cycles after the instruction issues before you can use the result.. so you have to issue several independent instructions to cover the latency. The multiplier in single precision has a latency of 4 and the adder of 3.</p> <p>You can find these same throughput and latency numbers for Nehalem in the Intel Optimization guide, table C-15a</p> <p><a href="http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-optimization-manual.html" rel="noreferrer">http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-optimization-manual.html</a></p>
23,298,295
How to make a shell executable node file using TypeScript
<p>Normally in node files I just put</p> <pre><code>#!/usr/bin/env node </code></pre> <p>at the top and make it executable to create a file that can be run from a bash terminal. However if I do that in a Typescript file, the compiler says "error TS1001: Unexpected character "#"" and refuses to compile it. So how can I make a shell executable node file with Typescript?</p>
25,299,690
7
8
null
2014-04-25 16:22:18.737 UTC
8
2021-02-03 14:18:16.663 UTC
null
null
null
null
862,295
null
1
39
node.js|bash|typescript|command-line-interface
16,741
<p>You were right to report the bug to Microsoft, and they were wrong to close it as <em>wontfix</em>.</p> <p>Until it <em>is</em> fixed, here's a workaround. Paste the following into a text file and save it as <code>shebangify</code>:</p> <pre><code>#!/usr/bin/env node var fs = require('fs'); var path = process.argv[2]; var data = "#!/usr/bin/env node\n\n"; data += fs.readFileSync(path); fs.writeFileSync(path, data); </code></pre> <p>(N.B. To keep this answer concise, the code above doesn't have any error-checking or other refinements, so use at your own risk or use <a href="https://gist.github.com/sampablokuper/b8fa8e49ae03a7ec290f">this</a> instead. Also, see <a href="https://stackoverflow.com/questions/15423774/nodejs-prepending-to-a-file">this SO question</a> for more info about prepending to files.)</p> <p>Make the file executable with by using a terminal to navigate to the file's directory and executing:</p> <pre><code>$ chmod +x shebangify </code></pre> <p>Once you have created a Typescript program (e.g. called <code>myscript.ts</code>) that you wish to compile and turn into a shell script (e.g. called <code>myscript</code>), do so by executing a sequence along these lines in your terminal:</p> <pre><code>$ tsc --out myscript myscript.ts ; ./shebangify myscript ; chmod +x myscript </code></pre>
5,253,858
Why does ContentResolver.requestSync not trigger a sync?
<p>I am trying to implement the Content-Provider-Sync Adapter pattern as discussed at <a href="http://dl.google.com/googleio/2010/android-developing-RESTful-android-apps.pdf" rel="noreferrer">Google IO</a> - slide 26. My content provider is working, and my sync works when I trigger it from the Dev Tools Sync Tester application, however when I call ContentResolver.requestSync(account, authority, bundle) from my ContentProvider, my sync is never triggered.</p> <pre><code>ContentResolver.requestSync( account, AUTHORITY, new Bundle()); </code></pre> <p>Edit -- added manifest snippet My manifest xml contains:</p> <pre><code>&lt;service android:name=".sync.SyncService" android:exported="true"&gt; &lt;intent-filter&gt; &lt;action android:name="android.content.SyncAdapter" /&gt; &lt;/intent-filter&gt; &lt;meta-data android:name="android.content.SyncAdapter" android:resource="@xml/syncadapter" /&gt; &lt;/service&gt; </code></pre> <p>--Edit</p> <p>My syncadapter.xml associated with my sync service contains: </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;sync-adapter xmlns:android="http://schemas.android.com/apk/res/android" android:contentAuthority="AUTHORITY" android:accountType="myaccounttype" android:supportsUploading="true" /&gt; </code></pre> <p>Not sure what other code would be useful. The account passed to requestSync is of "myaccounttype" and the AUTHORITY passed to the call matches my syc adapter xml.</p> <p>Is ContentResolver.requestSync the correct way to request a sync? It looks like the sync tester tool binds directly to the service and calls start sync, but that seems like it defeats the purpose of integrating with the sync architecture.</p> <p>If that is the correct way to request a sync then why would the sync tester work, but not my call to ContentResolver.requestSync? Is there something I need to pass in the bundle?</p> <p>I am testing in the emulator on devices running 2.1 and 2.2.</p>
5,255,360
3
4
null
2011-03-09 23:56:42.483 UTC
88
2022-05-18 09:32:58.987 UTC
2016-03-04 16:43:19.737 UTC
null
996,815
null
535,630
null
1
113
android|android-contentprovider|android-syncadapter
47,137
<p>Calling <code>requestSync()</code> will only work on an {Account, ContentAuthority} pair that is known to the system. Your app needs to go through a number of steps to tell Android that you are capable of synchronizing a specific kind of content using a specific kind of account. It does this in the AndroidManifest.</p> <p><strong>1. Notify Android that your application package provides syncing</strong></p> <p>First off, in AndroidManifest.xml, you have to declare that you have a Sync Service:</p> <pre><code>&lt;service android:name=".sync.mySyncService" android:exported="true"&gt; &lt;intent-filter&gt; &lt;action android:name="android.content.SyncAdapter" /&gt; &lt;/intent-filter&gt; &lt;meta-data android:name="android.content.SyncAdapter" android:resource="@xml/sync_myapp" /&gt; &lt;/service&gt; </code></pre> <p>The name attribute of the <code>&lt;service&gt;</code> tag is the name of your class to connect up sync... I'll talk to that in a second.</p> <p>Setting exported true makes it visible to other components (needed so <code>ContentResolver</code> can call it).</p> <p>The intent filter lets it catch an intent requesting sync. (This <code>Intent</code> comes from <code>ContentResolver</code> when you call <code>ContentResolver.requestSync()</code> or related scheduling methods.)</p> <p>The <code>&lt;meta-data&gt;</code> tag will be discussed below.</p> <p><strong>2. Provide Android a service used to find your SyncAdapter</strong></p> <p>So the class itself... Here's an example:</p> <pre><code>public class mySyncService extends Service { private static mySyncAdapter mSyncAdapter = null; public SyncService() { super(); } @Override public void onCreate() { super.onCreate(); if (mSyncAdapter == null) { mSyncAdapter = new mySyncAdapter(getApplicationContext(), true); } } @Override public IBinder onBind(Intent arg0) { return mSyncAdapter.getSyncAdapterBinder(); } } </code></pre> <p>Your class must extend <code>Service</code> or one of its subclasses, must implement <code>public IBinder onBind(Intent)</code>, and must return a <code>SyncAdapterBinder</code> when that's called... You need a variable of type <code>AbstractThreadedSyncAdapter</code>. So as you can see, that's pretty much everything in that class. The only reason it's there is to provide a Service, that offers a standard interface for Android to query your class as to what your <code>SyncAdapter</code> itself is. </p> <p><strong>3. Provide a <code>class SyncAdapter</code> to actually perform the sync.</strong></p> <p>mySyncAdapter is where the real sync logic itself is stored. Its <code>onPerformSync()</code> method gets called when it's time to sync. I figure you already have this in place.</p> <p><strong>4. Establish a binding between an Account-type and a Content Authority</strong></p> <p>Looking back again at AndroidManifest, that strange <code>&lt;meta-data&gt;</code> tag in our service is the key piece that establishes the binding between a ContentAuthority and an account. It externally references another xml file (call it whatever you like, something relevant to your app.) Let's look at sync_myapp.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;sync-adapter xmlns:android="http://schemas.android.com/apk/res/android" android:contentAuthority="com.android.contacts" android:accountType="com.google" android:userVisible="true" /&gt; </code></pre> <p>Okay, so what does this do? It tells Android that the sync adapter we've defined (the class that was called out in the name element of the <code>&lt;service&gt;</code> tag that includes the <code>&lt;meta-data&gt;</code> tag that references this file...) will sync contacts using a com.google style account.</p> <p>All your contentAuthority strings have to all match, and match with what you're syncing -- This should be a string you define, if you're creating your own database, or you should use some existing device strings if you're syncing known data types (like contacts or calendar events or what have you.) The above ("com.android.contacts") happens to be the ContentAuthority string for contacts type data (surprise, surprise.)</p> <p>accountType also has to match one of those known account types that are already entered, or it has to match one you're creating (This involves creating a subclass of AccountAuthenticator to get auth on your server... Worth an article, itself.) Again, "com.google" is the defined string identifying... google.com style account credentials (again, this should not be a surprise.)</p> <p><strong>5. Enable Sync on a given Account / ContentAuthority pair</strong></p> <p>Finally, sync has to be enabled. You can do this in the Accounts &amp; Sync page in the control panel by going to your app and setting the checkbox next to your app within the matching account. Alternately, you can do it in some setup code in your app:</p> <pre><code>ContentResolver.setSyncAutomatically(account, AUTHORITY, true); </code></pre> <p>For sync to occur, your account/authority pair must be enabled to sync (like above) <em>and</em> the overall global sync flag on the system must be set, <em>and</em> the device must have network connectivity. </p> <p>If your account/authority sync or the global sync are disabled, calling RequestSync() does have an effect -- It sets a flag that sync has been requested, and will be performed as soon as sync is enabled. </p> <p>Also, per <a href="https://stackoverflow.com/users/203905">mgv</a>, setting <code>ContentResolver.SYNC_EXTRAS_MANUAL</code> to true in the extras bundle of your requestSync will ask android to force a sync even if global sync is off (be respectful of your user here!)</p> <p>Finally, you can setup a periodic scheduled sync, again with ContentResolver functions.</p> <p><strong>6. Consider implications of multiple accounts</strong></p> <p>It is possible to have more than one account of the same type (two @gmail.com accounts set up on one device or two facebook accounts, or two twitter accounts, etc...) You should consider the application implications of doing that... If you have two accounts, you probably don't want to try to sync both of them into the same database tables. Maybe you need to specify that only one can be active at a time, and flush the tables and resync if you switch accounts. (through a property page that queries what accounts are present). Maybe you create a different database for each account, maybe different tables, maybe a key column in each table. All application specific and worthy of some thought. <code>ContentResolver.setIsSyncable(Account account, String authority, int syncable)</code> might be of interest here. <code>setSyncAutomatically()</code> controls whether an account/authority pair is <em>checked</em> or <em>unchecked</em>, whereas <code>setIsSyncable()</code> provides a way to uncheck and grey out the line so the user can't turn it on. You might set one account Syncable and the other not Syncable (dsabled).</p> <p><strong>7. Be aware of ContentResolver.notifyChange()</strong></p> <p>One tricky thing. <code>ContentResolver.notifyChange()</code> is a function used by <code>ContentProvider</code>s to notify Android that the local database has been changed. This serves two functions, first, it will cause cursors following that content uri to update, and in turn requery and invalidate and redraw a <code>ListView</code>, etc... It's very magical, the database changes and your <code>ListView</code> just updates automatically. Awesome. Also, when the database changes, Android will request Sync for you, even outside your normal schedule, so that those changes get taken off the device and synced to the server as rapidly as possible. Also awesome. </p> <p>There's one edge case though. If you pull from the server, and push an update into the <code>ContentProvider</code>, it will dutifully call <code>notifyChange()</code> and android will go, "Oh, database changes, better put them on the server!" (Doh!) Well-written <code>ContentProviders</code> will have some tests to see if the changes came from the network or from the user, and will set the boolean <code>syncToNetwork</code> flag false if so, to prevent this wasteful double-sync. If you're feeding data into a <code>ContentProvider</code>, it behooves you to figure out how to get this working -- Otherwise you'll end up always performing two syncs when only one is needed.</p> <p><strong>8. Feel happy!</strong></p> <p>Once you have all this xml metadata in place, and sync enabled, Android will know how to connect everything up for you, and sync should start working. At this point, a lot of things that are nice will just click into place and it will feel a lot like magic. Enjoy!</p>
18,453,145
How is std::function implemented?
<p>According to the sources I have found, a <em>lambda expression</em> is essentially implemented by the compiler creating a class with overloaded function call operator and the referenced variables as members. This suggests that the size of lambda expressions varies, and given enough references variables that size can be <em>arbitrarily large</em>.</p> <p>An <code>std::function</code> should have a <em>fixed size</em>, but it must be able to wrap any kind of callables, including any lambdas of the same kind. How is it implemented? If <code>std::function</code> internally uses a pointer to its target, then what happens, when the <code>std::function</code> instance is copied or moved? Are there any heap allocations involved?</p>
18,453,324
6
2
null
2013-08-26 21:16:13.503 UTC
38
2021-09-09 05:29:23.697 UTC
null
null
null
user2545918
null
null
1
115
c++|c++11|lambda
33,646
<p>The implementation of <code>std::function</code> can differ from one implementation to another, but the core idea is that it uses type-erasure. While there are multiple ways of doing it, you can imagine a trivial (not optimal) solution could be like this (simplified for the specific case of <code>std::function&lt;int (double)&gt;</code> for the sake of simplicity):</p> <pre><code>struct callable_base { virtual int operator()(double d) = 0; virtual ~callable_base() {} }; template &lt;typename F&gt; struct callable : callable_base { F functor; callable(F functor) : functor(functor) {} virtual int operator()(double d) { return functor(d); } }; class function_int_double { std::unique_ptr&lt;callable_base&gt; c; public: template &lt;typename F&gt; function(F f) { c.reset(new callable&lt;F&gt;(f)); } int operator()(double d) { return c(d); } // ... }; </code></pre> <p>In this simple approach the <code>function</code> object would store just a <code>unique_ptr</code> to a base type. For each different functor used with the <code>function</code>, a new type derived from the base is created and an object of that type instantiated dynamically. The <code>std::function</code> object is always of the same size and will allocate space as needed for the different functors in the heap.</p> <p>In real life there are different optimizations that provide performance advantages but would complicate the answer. The type could use small object optimizations, the dynamic dispatch can be replaced by a free-function pointer that takes the functor as argument to avoid one level of indirection... but the idea is basically the same.</p> <hr> <p>Regarding the issue of how copies of the <code>std::function</code> behave, a quick test indicates that copies of the internal callable object are done, rather than sharing the state.</p> <pre><code>// g++4.8 int main() { int value = 5; typedef std::function&lt;void()&gt; fun; fun f1 = [=]() mutable { std::cout &lt;&lt; value++ &lt;&lt; '\n' }; fun f2 = f1; f1(); // prints 5 fun f3 = f1; f2(); // prints 5 f3(); // prints 6 (copy after first increment) } </code></pre> <p>The test indicates that <code>f2</code> gets a copy of the callable entity, rather than a reference. If the callable entity was shared by the different <code>std::function&lt;&gt;</code> objects, the output of the program would have been 5, 6, 7.</p>
20,010,199
How to determine if a process runs inside lxc/Docker?
<p>Is there any way to determine if a process (script) runs inside an lxc container (~ Docker runtime)? I know that some programs are able to detect whether they run inside a virtual machine, is something similar available for lxc/docker?</p>
20,012,536
18
2
null
2013-11-15 20:42:04.983 UTC
57
2022-06-15 17:14:22.093 UTC
2018-04-07 22:40:47.343 UTC
null
895,245
null
2,216,860
null
1
231
linux|bash|docker
96,393
<p>The most reliable way is to check <code>/proc/1/cgroup</code>. It will tell you the control groups of the init process, and when you are <em>not</em> in a container, that will be <code>/</code> for all hierarchies. When you are <em>inside</em> a container, you will see the name of the anchor point. With LXC/Docker containers, it will be something like <code>/lxc/&lt;containerid&gt;</code> or <code>/docker/&lt;containerid&gt;</code> respectively.</p>
15,481,505
SQL Update after Joining Two Tables
<p>I am new to SQL, using Microsoft SQL Server Management Studio.</p> <p>I am trying to write a SQL statement that performs an update after two tables are joined.</p> <p>I have two tables: <code>myTable1</code> and <code>myTable2</code>. Both share a field <code>MyID</code>, which is going to be the field that I join on. <code>myTable1</code> contains a column called <code>BitToUpdate</code>. And MyTable2 contains a column called <code>BitToCheck</code>.</p> <p>I want to set <code>BitToUpdate</code> in <code>myTable1</code> to be 1 where <code>BitToCheck</code> in <code>myTable2</code> is 1 as well.</p> <p>Here is what I have:</p> <pre><code>SELECT M.MyID, BitToUpdate, BitToCheck INTO #temp_table FROM myTable1 as T1 LEFT JOIN myTable2 as T2 ON M.MyId = PO.MyId </code></pre> <p>So first I tried to join the two tables <code>myTable1</code> and <code>myTable2</code> on their IDs, and store the result in a temporary table.</p> <p>Next, I want to update <code>BitToUpdate</code> to be 1 where <code>BitToCheck</code> is 1.</p> <p>So to do that in the temporary table, I have:</p> <pre><code>UPDATE #temp_table SET `BitToUpdate` = 1 WHERE `BitToCheck` = 1 </code></pre> <p>This updates the <code>BitToUpdate</code> successfully in #temp_table. However, when I do a select on <code>myTable1</code>, I find that <code>BitToUpdate</code> is not changed. I suppose this makes sense as #temp_table isn't really a "pointer"....</p> <p>But what would be the correct way to approach this join and update?</p>
15,481,712
4
0
null
2013-03-18 16:10:32.22 UTC
2
2013-06-14 20:41:23.58 UTC
null
null
null
null
1,473,856
null
1
14
sql-server
86,470
<p>You don't need to use a <code>LEFT JOIN</code> here, since you are checking on a condition from table 2, so an <code>INNER JOIN</code> should be better here.</p> <pre><code>UPDATE T1 SET T1.BitToUpdate = 1 FROM myTable1 T1 INNER JOIN myTable2 T2 ON T1.MyId = T2.MyId WHERE T2.BitToCheck = 1 </code></pre>
15,313,807
Android : Maximum allowed width & height of bitmap
<p>Im creating an app that needs to decode large images to bitmaps to be displayed in a ImageView.</p> <p>If i just try to decode them straight to a bitmap i get the following error " Bitmap too large to be uploaded into a texture (1944x2592, max=2048x2048)"</p> <p>So to be able to show images with too high resolution im using: </p> <pre><code>Bitmap bitmap = BitmapFactory.decodeFile(path); if(bitmap.getHeight()&gt;=2048||bitmap.getWidth()&gt;=2048){ DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int width = metrics.widthPixels; int height = metrics.heightPixels; bitmap =Bitmap.createScaledBitmap(bitmap, width, height, true); } </code></pre> <p>This works but I don't really want to hardcode the maximum value of 2048 as I have in the if-statement now, but I cant find out how to get a the max allowed size of the bitmap for a device</p> <p>Any ideas? </p>
15,314,838
5
0
null
2013-03-09 17:36:55.277 UTC
12
2015-01-09 09:41:07.45 UTC
2013-07-19 07:14:00.667 UTC
null
1,765,573
null
1,079,218
null
1
29
android|bitmap
39,007
<p>This limit should be coming from the underlying OpenGL implementation. If you're already using OpenGL in your app, you can use something like this to get the maximum size:</p> <pre><code>int[] maxSize = new int[1]; gl.glGetIntegerv(GL10.GL_MAX_TEXTURE_SIZE, maxSize, 0); // maxSize[0] now contains max size(in both dimensions) </code></pre> <p>This shows that my both my Galaxy Nexus and Galaxy S2 have a maximum of 2048x2048.</p> <p>Unfortunately, if you're not already using it, the only way to get an OpenGL context to call this from is to create one(including the surfaceview, etc), which is a lot of overhead just to query a maximum size.</p>
15,408,371
cumulative distribution plots python
<p>I am doing a project using python where I have two arrays of data. Let's call them <em>pc</em> and <em>pnc</em>. I am required to plot a cumulative distribution of both of these on the same graph. For <em>pc</em> it is supposed to be a less than plot i.e. at (x,y), y points in <em>pc</em> must have value less than x. For <em>pnc</em> it is to be a more than plot i.e. at (x,y), y points in <em>pnc</em> must have value more than x.</p> <p>I have tried using histogram function - <code>pyplot.hist</code>. Is there a better and easier way to do what i want? Also, it has to be plotted on a logarithmic scale on the x-axis.</p>
15,419,072
5
2
null
2013-03-14 11:46:39.62 UTC
16
2022-01-06 15:43:27.12 UTC
2013-03-14 11:48:29.34 UTC
null
1,252,759
null
1,770,037
null
1
35
python|python-3.x|matplotlib
123,812
<p>You were close. You should not use plt.hist as numpy.histogram, that gives you both the values and the bins, than you can plot the cumulative with ease:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # some fake data data = np.random.randn(1000) # evaluate the histogram values, base = np.histogram(data, bins=40) #evaluate the cumulative cumulative = np.cumsum(values) # plot the cumulative function plt.plot(base[:-1], cumulative, c='blue') #plot the survival function plt.plot(base[:-1], len(data)-cumulative, c='green') plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/d6z5D.png" alt="enter image description here"></p>
15,005,436
errors when decode H.264 frames using ffmpeg
<p>I am getting the following errors when decoding H.264 frames received from the remote end of a H.264 based SIP video call. Appreciate any help in understanding there errors.</p> <pre><code>non-existing PPS 0 referenced decode_slice_header error non-existing PPS 0 referenced decode_slice_header error no frame! non-existing PPS 0 referenced decode_slice_header error non-existing PPS 0 referenced decode_slice_header error no frame! </code></pre>
15,011,264
3
0
null
2013-02-21 15:01:35.627 UTC
17
2022-07-23 19:48:53.89 UTC
2013-02-21 16:07:22 UTC
null
293,859
null
293,859
null
1
43
ffmpeg|h.264
68,138
<p>That just means that ffmpeg has not seen a keyframe yet, which carries SPS and PPS information. SPS and PPS are crucial in decoding an incoming frame/slice. Keyframes are sent periodically (i.e. every 5-10 seconds or more); so if it turns out that you joined a stream before the keyframe arrived; you will see this warning for every frame until a keyframe shows up.</p> <p>As soon as the keyframe shows up from the wire, ffmpeg will have enough information to decode that frame (and any subsequent frames until the next keyframe), so those warnings will go away.</p>
15,136,134
C# how to use enum with switch
<p>I can't figure out how to use switches in combination with an enum. Could you please tell me what I'm doing wrong, and how to fix it? I have to use an enum to make a basic calculator. </p> <pre><code>public enum Operator { PLUS, MINUS, MULTIPLY, DIVIDE } public double Calculate(int left, int right, Operator op) { int i = (int) op; switch(i) { case 0: { return left + right; } case 1: { return left - right; } case 2: { return left * right; } case 3: { return left / right; } default: { return 0.0; } } } </code></pre> <p>The end result should be something like this:</p> <pre><code>Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, PLUS)) Output: The sum of 5 and 5 is 10 </code></pre> <p>Could you guys please tell me how I'm messing up?</p>
15,136,162
11
0
null
2013-02-28 12:56:42.42 UTC
11
2019-10-11 07:27:35.953 UTC
2019-10-11 07:27:35.953 UTC
null
134,204
null
2,119,562
null
1
98
c#|enums|switch-statement|switch-expression
273,718
<p>You don't need to convert it</p> <pre><code>switch(op) { case Operator.PLUS: { // your code // for plus operator break; } case Operator.MULTIPLY: { // your code // for MULTIPLY operator break; } default: break; } </code></pre> <p>By the way, use brackets</p>
43,713,445
Selenium "Unable to find a matching set of capabilities" despite driver being in /usr/local/bin
<p>I'm trying to follow a tutorial about Selenium, <a href="http://selenium-python.readthedocs.io/getting-started.html" rel="noreferrer">http://selenium-python.readthedocs.io/getting-started.html</a>. I've downloaded the latest version of <code>geckodriver</code> and copied it to <code>/usr/local/bin</code>. However, when I try</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() </code></pre> <p>I get the following error message:</p> <pre><code>Traceback (most recent call last): File "/Users/kurtpeek/Documents/Scratch/selenium_getting_started.py", line 4, in &lt;module&gt; driver = webdriver.Firefox() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 152, in __init__ keep_alive=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 98, in __init__ self.start_session(desired_capabilities, browser_profile) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 188, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in execute self.error_handler.check_response(response) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Unable to find a matching set of capabilities [Finished in 1.2s with exit code 1] </code></pre> <p>From <a href="https://github.com/SeleniumHQ/selenium/issues/3884" rel="noreferrer">https://github.com/SeleniumHQ/selenium/issues/3884</a>, it seems like other users are experiencing similar issues, but the Selenium team is unable to reproduce it. How can I get Selenium working with Firefox? (It does work with <code>chromedriver</code> and a <code>webdriver.Chrome()</code> instance, so I suspect this might be a bug in Selenium).</p>
43,781,370
11
3
null
2017-05-01 02:19:01.227 UTC
5
2020-08-05 13:19:04.6 UTC
null
null
null
null
995,862
null
1
47
python|selenium
92,532
<p>Updating Firefox and Selenium solved it for me. I don't pretend to have an explanation for the root cause however.</p> <ul> <li>Updated Firefox 48 → 53</li> <li>Updated to Selenium 3.4.1</li> </ul> <p>I also reinstalled/updated <code>Geckodriver</code> using <code>Homebrew</code> and explicitly used it as an executable for Selenium <code>WebDriver</code>, but it turned out that it wasn't necessary to mitigate the <em>"Unable to find matching set of capabilities"</em> error.</p>
43,915,518
How to use custom password validators beside the django auth password validators?
<p>As the question above mentioned, I will trying to use a certain extra rule to validate a password during the registration process. The extra rule should be that a password is validate if it has at least one digit, one letter and one special character. </p> <p>My approach to solute this problem I've created a file named validators.py. </p> <pre><code>from django.core.exceptions import ValidationError class CustomPasswortValidator: def validate(value): # check for digit if not any(char.isdigit() for char in value): raise ValidationError(_('Password must contain at least 1 digit.')) # check for letter if not any(char.isalpha() for char in value): raise ValidationError(_('Password must contain at least 1 letter.')) # check for special character special_characters = "[~\!@#\$%\^&amp;\*\(\)_\+{}\":;'\[\]]" if not any(char in special_characters for char in value): raise ValidationError(_('Password must contain at least 1 letter.')) </code></pre> <p>My custom registration form looks like this: </p> <pre><code>from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegistrationForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) </code></pre> <p>I don't get it how I tell django, that my custom password validator should be use beside the django AUTH_PASSWORD_VALIDATORS.</p>
43,917,773
1
6
null
2017-05-11 12:32:02.507 UTC
9
2019-09-05 04:03:44.083 UTC
null
null
null
null
4,949,699
null
1
13
python|django|validation|passwords|registration
10,496
<p>So, as e4c5 mentioned, it is really simple and straightforward. </p> <p>My CustomPasswordValidator looks like this: </p> <pre><code>from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ class CustomPasswordValidator(): def __init__(self, min_length=1): self.min_length = min_length def validate(self, password, user=None): special_characters = "[~\!@#\$%\^&amp;\*\(\)_\+{}\":;'\[\]]" if not any(char.isdigit() for char in password): raise ValidationError(_('Password must contain at least %(min_length)d digit.') % {'min_length': self.min_length}) if not any(char.isalpha() for char in password): raise ValidationError(_('Password must contain at least %(min_length)d letter.') % {'min_length': self.min_length}) if not any(char in special_characters for char in password): raise ValidationError(_('Password must contain at least %(min_length)d special character.') % {'min_length': self.min_length}) def get_help_text(self): return "" </code></pre> <p>Just add it to the list of AUTH_PASSWORD_VALIDATORS in settings.py and that's it!</p> <pre><code>AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, { 'NAME': 'registration.validators.CustomPasswordValidator', },] </code></pre>
38,080,748
Convert pyspark string to date format
<p>I have a date pyspark dataframe with a string column in the format of <code>MM-dd-yyyy</code> and I am attempting to convert this into a date column.</p> <p>I tried:</p> <pre><code>df.select(to_date(df.STRING_COLUMN).alias('new_date')).show() </code></pre> <p>And I get a string of nulls. Can anyone help?</p>
41,273,036
6
3
null
2016-06-28 15:45:59.71 UTC
32
2021-12-25 16:21:51.85 UTC
2021-12-25 16:21:51.85 UTC
null
1,386,551
null
3,010,960
null
1
114
python|apache-spark|pyspark|apache-spark-sql
364,309
<p><strong>Update</strong> (1/10/2018):</p> <p>For Spark 2.2+ the best way to do this is probably using the <a href="http://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html#pyspark.sql.functions.to_date" rel="noreferrer"><code>to_date</code></a> or <a href="http://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html#pyspark.sql.functions.to_timestamp" rel="noreferrer"><code>to_timestamp</code></a> functions, which both support the <code>format</code> argument. From the docs:</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; from pyspark.sql.functions import to_timestamp &gt;&gt;&gt; df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) &gt;&gt;&gt; df.select(to_timestamp(df.t, 'yyyy-MM-dd HH:mm:ss').alias('dt')).collect() [Row(dt=datetime.datetime(1997, 2, 28, 10, 30))] </code></pre> <p><strong>Original Answer</strong> (for Spark &lt; 2.2)</p> <p>It is possible (preferrable?) to do this without a udf:</p> <pre class="lang-python prettyprint-override"><code>from pyspark.sql.functions import unix_timestamp, from_unixtime df = spark.createDataFrame( [(&quot;11/25/1991&quot;,), (&quot;11/24/1991&quot;,), (&quot;11/30/1991&quot;,)], ['date_str'] ) df2 = df.select( 'date_str', from_unixtime(unix_timestamp('date_str', 'MM/dd/yyy')).alias('date') ) print(df2) #DataFrame[date_str: string, date: timestamp] df2.show(truncate=False) #+----------+-------------------+ #|date_str |date | #+----------+-------------------+ #|11/25/1991|1991-11-25 00:00:00| #|11/24/1991|1991-11-24 00:00:00| #|11/30/1991|1991-11-30 00:00:00| #+----------+-------------------+ </code></pre>
7,698,706
How to pass a query string to Ajax call with jQuery?
<p>This is a follow up to <a href="https://stackoverflow.com/questions/7696540/how-to-update-database-with-jquery-without-refreshing-the-page">my previous question (unresolved)</a>. </p> <p>I fetch <code>items</code> from the database and display them in a for loop. I use jQuery to hide one of the rows. Now I need to get the <code>main_id</code> of that hidden row and pass it to <code>$.ajax</code>. In the original question Paul suggested to use <code>alert(this.attr("title"));</code> but this line stops the execution of the <code>$.ajax</code> call and the call is not executed. When I comment out the alert <code>alert(this.attr("title"));</code> then the ajax call goes through. In that case, I get an error because the <code>display_false()</code> function in the handler does not get the value of the <code>main_id</code>. </p> <p>This is the html of the "hide" link with <code>title=%s</code>.</p> <pre><code>&lt;a class="false" title=%s href="/useradminpage?main_id=%s&amp;display=false"&gt;&lt;span class="small"&gt;(hide)&lt;/span&gt;&lt;/a&gt; </code></pre> <p>So I need to pass the value of the <code>main_id</code> stored in <code>alert(this.attr("title"));</code> to the function <code>display_false()</code> when the ajax call is executed.</p> <p>How can I do this?</p> <p>The relevant code is below:</p> <p><strong>The Script</strong></p> <pre><code> self.response.out.write(""" &lt;html&gt; &lt;head&gt; &lt;link type="text/css" rel="stylesheet" href="/stylesheets/main.css" /&gt; &lt;title&gt;User Admin Page&lt;/title&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function() { alert("1 - document ready is called") $("a.false").click(function(e) { $(this).closest("tr.hide").hide("slow"); e.preventDefault(); alert("2 - row is hidden") }); $("a.false").click(function() { alert("3 - ajax") //the following alert stops the ajax call from executing alert(this.attr("title")); $.ajax({ url: "/useradminpage?main_id=%s&amp;display=false", data: {main_id: "title"} success: function(data) { display_false() alert(4 - "returned"); } }); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; """) </code></pre> <p><strong>HTML</strong></p> <pre><code>#-----------main table------------# main_id = self.request.get("main_id") self.response.out.write("""&lt;table class="mytable"&gt; &lt;tr class="head"&gt; &lt;th width="80%"&gt;links&lt;/th&gt;&lt;th&gt;edit tags&lt;/th&gt; &lt;/tr&gt; """) query = Main.all() query.filter("owner", user) query.filter("display", True) query.order("-date") cursor = self.request.get("cursor") if cursor: query.with_cursor(cursor) e = query.fetch(100) cursor = query.cursor() for item in e: main_id = item.key().id() self.response.out.write(""" &lt;tr class="hide"&gt; &lt;td&gt;&lt;a href="%s" target="_blank"&gt;%s&lt;/a&gt;&lt;span class=small&gt; (%s) &lt;/span&gt;&lt;br /&gt; &lt;span class=small&gt;%s&lt;/span&gt; &lt;a href="/edit?main_id=%s"&gt;&lt;span class="small"&gt;(edit)&lt;/span&gt;&lt;/a&gt; &lt;a class="false" title=%s href="/useradminpage?main_id=%s&amp;display=false"&gt;&lt;span class="small"&gt;(hide)&lt;/span&gt;&lt;/a&gt; &lt;a href="/comment?main_id=%s"&gt;&lt;span class="small"&gt;(comments)&lt;/span&gt;&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="/tc?url=%s&amp;main_id=%s&amp;user_tag_list=%s" title="edit tags"&gt;%s&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; """ % tuple([item.url, item.title, urlparse(item.url).netloc, f1.truncate_at_space(item.pitch), main_id, main_id, main_id, main_id, item.url, main_id, (", ".join(item.tag_list)), (", ".join(item.tag_list)),])) self.response.out.write("""&lt;/tbody&gt;&lt;/table&gt;""") display = self.request.get("display") def display_false(): if display == "false": main_id = self.request.get("main_id") #I tried to get the "title" but this does not work #main_id = self.request.get("title") k = Main.get_by_id(int(main_id)) k.display = False k.put() display_false() ... </code></pre> <p><strong>Update</strong></p> <p>Updated the code according to <a href="https://stackoverflow.com/questions/7698706/how-to-pass-a-query-string-to-ajax-call-with-jquery/7698722#7698722">James Montagne's answer (with a few changes)</a>. Now, for some reason, document ready is not loading, and the call to hide the row is not working, but ajax call to update the database is working. What am I doing wrong?</p> <pre><code>&lt;script&gt; $(document).ready(function() { alert("1 - document ready is called") $("a.false").click(function(e) { $(this).closest("tr.hide").hide("slow"); var main_id = this.attr("title"); var display = "false"; e.preventDefault(); alert("2 - row is hidden") }); $("a.false").click(function() { alert("3 - ajax"); $.ajax({ url: "/useradminpage?main_id=%s&amp;display=false", data: {main_id: "main_id", display: "display")}, success: function(data) { display_false() alert(4 - "returned"); } }); }); }); &lt;/script&gt; </code></pre>
7,698,722
2
0
null
2011-10-08 17:59:19.27 UTC
0
2014-07-16 10:37:46.32 UTC
2017-05-23 10:27:08.297 UTC
null
-1
null
215,094
null
1
8
javascript|jquery|query-string
61,373
<p>You don't need to alert that value, you need to pass it. Currently you are passing the string <code>title</code>.</p> <pre><code> $.ajax({ url: "/useradminpage?main_id=%s&amp;display=false", data: {main_id: this.attr("title")} success: function(data) { display_false() alert(4 - "returned"); } }); </code></pre>
7,880,706
How to get array of float audio data from AudioQueueRef in iOS?
<p>I'm working on getting audio into the iPhone in a form where I can pass it to a (C++) analysis algorithm. There are, of course, many options: the AudioQueue tutorial <a href="http://trailsinthesand.com/exploring-iphone-audio-part-3/">at trailsinthesand</a> gets things started.</p> <p>The audio callback, though, gives an <code>AudioQueueRef</code>, and I'm finding Apple's documentation thin on this side of things. Built-in methods to write to a file, but nothing where you actually peer inside the packets to see the data.</p> <p>I need data. I don't want to write anything to a file, which is what all the tutorials — and even Apple's convenience I/O objects — seem to be aiming at. Apple's <code>AVAudioRecorder</code> (infuriatingly) will give you levels and write the data, but not actually give you access to it. Unless I'm missing something...</p> <p>How to do this? In the code below there is <code>inBuffer-&gt;mAudioData</code> which is tantalizingly close but I can find no information about what format this 'data' is in or how to access it.</p> <p>AudioQueue Callback:</p> <pre><code>void AudioInputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp *inStartTime, UInt32 inNumberPacketDescriptions, const AudioStreamPacketDescription *inPacketDescs) { static int count = 0; RecordState* recordState = (RecordState*)inUserData; AudioQueueEnqueueBuffer(recordState-&gt;queue, inBuffer, 0, NULL); ++count; printf("Got buffer %d\n", count); } </code></pre> <p>And the code to write the audio to a file:</p> <pre><code>OSStatus status = AudioFileWritePackets(recordState-&gt;audioFile, false, inBuffer-&gt;mAudioDataByteSize, inPacketDescs, recordState-&gt;currentPacket, &amp;inNumberPacketDescriptions, inBuffer-&gt;mAudioData); // THIS! This is what I want to look inside of. if(status == 0) { recordState-&gt;currentPacket += inNumberPacketDescriptions; } </code></pre>
7,967,738
2
0
null
2011-10-24 19:18:10.427 UTC
8
2017-06-22 13:45:44.283 UTC
null
null
null
null
395,295
null
1
13
objective-c|ios|core-audio|avaudiorecorder|audioqueue
3,676
<pre><code> // so you don't have to hunt them all down when you decide to switch to float: #define AUDIO_DATA_TYPE_FORMAT SInt16 // the actual sample-grabbing code: int sampleCount = inBuffer-&gt;mAudioDataBytesCapacity / sizeof(AUDIO_DATA_TYPE_FORMAT); AUDIO_DATA_TYPE_FORMAT *samples = (AUDIO_DATA_TYPE_FORMAT*)inBuffer-&gt;mAudioData; </code></pre> <p>Then you have your (in this case <code>SInt16</code>) array <code>samples</code> which you can access from <code>samples[0]</code> to <code>samples[sampleCount-1]</code>.</p>
7,972,780
How do I find all the Points in a Path in Android?
<p>Awhile back I asked a question to see if I was able to find a pair of specific points in a path; however, this time I want to know if there is a way to know all points in a path? (I couldn't find a method that did so, which is unfortunate because Java provides a way to do this, just not Android?)</p> <p>The reason I ask this is because I have multiple geometric graphs and I want to compare the points to see where they intersect.</p> <p>I appreciate any helpful responses</p>
7,974,774
2
0
null
2011-11-01 20:55:53.82 UTC
10
2019-05-21 08:22:43.887 UTC
null
null
null
null
412,286
null
1
17
java|android|path|point
24,733
<p>If you have created a <code>Path</code> that means that in some point of your code, you know the exact (Geo)point. Why don't you put this point(s) on a <code>ArrayList</code> or something similar?</p> <p>So for example before doing:</p> <pre><code>path.lineTo(point.x, point.y); </code></pre> <p>you can do:</p> <pre><code>yourList.add(point); path.lineTo(point.x, point.y); </code></pre> <p>And later you can get all your points from the <code>ArrayList</code>. Note you that you can take advantage of the <a href="http://developer.android.com/guide/practices/design/performance.html#foreach" rel="nofollow">Enhanced For Loop Syntax</a> of <code>ArrayList</code> that execute up to three times faster.</p>
8,289,307
array_push for associative arrays
<p>I'm trying to extend an assoc array like this, but PHP doesn't like it.</p> <p>I receive this message:</p> <pre><code>Warning: array_push() expects parameter 1 to be array, null given </code></pre> <p>Here's my code:</p> <pre><code>$newArray = array(); foreach ( $array as $key =&gt; $value ) { $array[$key + ($value*100)] = $array[$key]; unset ( $array[$key] ); array_push ( $newArray [$key], $value ); } //} print_r($newArray); </code></pre> <p>Where did I go wrong?</p>
8,289,346
2
5
null
2011-11-27 21:42:20.373 UTC
2
2015-04-22 06:36:22.263 UTC
2011-11-27 21:46:10.54 UTC
null
995,876
null
1,052,507
null
1
26
php|arrays|associative-array|array-push
98,153
<p>This is your problem:</p> <p>$newArray[$key] is null cause $newArray is an empty array and has not yet values.</p> <p>You can replace your code, with </p> <pre><code>array_push( $newArray, $value ); </code></pre> <p>or instead of array_push to use</p> <pre><code>$newArray[$key] = $value; </code></pre> <p>so you can keep the index of your $key.</p>
8,162,419
python logging specific level only
<p>I'm logging events in my python code uing the python logging module. I have 2 logging files I wish to log too, one to contain user information and the other a more detailed log file for devs. I've set the the two logging files to the levels I want (usr.log = INFO and dev.log = ERROR) but cant work out how to restrict the logging to the usr.log file so only the INFO level logs are written to the log file as opposed to INFO plus everthing else above it e.g. INFO, WARNING, ERROR and CRITICAL.</p> <p>This is basically my code:-</p> <pre><code>import logging logger1 = logging.getLogger('') logger1.addHandler(logging.FileHandler('/home/tmp/usr.log') logger1.setLevel(logging.INFO) logger2 = logging.getLogger('') logger2.addHandler(logging.FileHandler('/home/tmp/dev.log') logger2.setLevel(logging.ERROR) logging.critical('this to be logged in dev.log only') logging.info('this to be logged to usr.log and dev.log') logging.warning('this to be logged to dev.log only') </code></pre> <p>Any help would be great thank you.</p>
8,163,115
2
0
null
2011-11-17 05:11:18.393 UTC
10
2014-04-19 22:47:20.68 UTC
null
null
null
null
788,462
null
1
34
python
25,650
<p>I am in general agreement with David, but I think more needs to be said. To paraphrase <a href="http://www.imdb.com/title/tt0093779/quotes">The Princess Bride</a> - I do not think this code means what you think it means. Your code has:</p> <pre><code>logger1 = logging.getLogger('') ... logger2 = logging.getLogger('') </code></pre> <p>which means that <code>logger1</code> and <code>logger2</code> are the <em>same</em> logger, so when you set the level of <code>logger2</code> to ERROR you actually end up setting the level of <code>logger1</code> at the same time. In order to get two different loggers, you would need to supply two different logger names. For example:</p> <pre><code>logger1 = logging.getLogger('user') ... logger2 = logging.getLogger('dev') </code></pre> <p>Worse still, you are calling the logging module's <code>critical()</code>, <code>info()</code> and <code>warning()</code> methods and expecting that both loggers will get the messages. This only works because you used the empty string as the name for both <code>logger1</code> and <code>logger2</code> and thus they are not only the same logger, they are also the root logger. If you use different names for the two loggers as I have suggested, then you'll need to call the <code>critical()</code>, <code>info()</code> and <code>warning()</code> methods on each logger individually (i.e. you'll need two calls rather than just one).</p> <p>What I think you really want is to have two different <a href="http://docs.python.org/library/logging.html#handler-objects">handlers</a> on a single logger. For example:</p> <pre><code>import logging mylogger = logging.getLogger('mylogger') handler1 = logging.FileHandler('usr.log') handler1.setLevel(logging.INFO) mylogger.addHandler(handler1) handler2 = logging.FileHandler('dev.log') handler2.setLevel(logging.ERROR) mylogger.addHandler(handler2) mylogger.setLevel(logging.INFO) mylogger.critical('A critical message') mylogger.info('An info message') </code></pre> <p>Once you've made this change, then you can use <a href="http://docs.python.org/library/logging.html#filter-objects">filters</a> as David has already mentioned. Here's a quick sample filter:</p> <pre><code>class MyFilter(object): def __init__(self, level): self.__level = level def filter(self, logRecord): return logRecord.levelno &lt;= self.__level </code></pre> <p>You can apply the filter to each of the two handlers like this:</p> <pre><code>handler1.addFilter(MyFilter(logging.INFO)) ... handler2.addFilter(MyFilter(logging.ERROR)) </code></pre> <p>This will restrict each handler to only write out log messages at the level specified.</p>
5,527,100
Why does maven not copy the properties files during the build process?
<p>Nothing I've found has been able to help me solve this one specific case. I recently switched from a plain old java web app project (which was working) to a maven web project. I get the following runtime exception:</p> <pre><code>java.util.MissingResourceException: Can't find bundle for base name com.myapp.config, locale en </code></pre> <p>I am using Netbeans to create a JSF 2.0, Spring, and Hibernate web app. I have the following directory structure:</p> <blockquote> <p>src\main\java\com\myapp &nbsp;&nbsp;&nbsp;&nbsp;Contains config.properties<br/> src\main\resources &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Empty<br/><br/> target\myapp\WEB-INF\classes\com\myapp &nbsp;&nbsp;&nbsp;&nbsp;Contains compiled class files without config.properties<br/> src\main\java\com\myapp &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Contains config.properties<br/></p> </blockquote> <p>Inspection of the WAR file in the target folder does not show any sign of the properties file so it's as if the Maven build plug-in is not copying over properties files. I know there is a tag you can place inside the pom but it didn't work for me. The link below mentions that the resources folder (empty for me) has its contents included during the build but if that is the case, how do you do it from Netbeans? I just want the properties file to be packaged with my war so it is accessible when it is deployed to the server. <br/><br/> <a href="http://maven.apache.org/plugins/maven-war-plugin/examples/adding-filtering-webresources.html">http://maven.apache.org/plugins/maven-war-plugin/examples/adding-filtering-webresources.html</a></p> <p>pom.xml:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.myapp&lt;/groupId&gt; &lt;artifactId&gt;myapp&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;name&gt;myapp&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;java.net&lt;/id&gt; &lt;name&gt;Repository hosting the Java EE 6 artifacts&lt;/name&gt; &lt;url&gt;http://download.java.net/maven/2&lt;/url&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;javax.faces&lt;/groupId&gt; &lt;artifactId&gt;jsf-api&lt;/artifactId&gt; &lt;version&gt;2.1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-web-api&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-hibernate3&lt;/artifactId&gt; &lt;version&gt;2.0.8&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.amazonaws&lt;/groupId&gt; &lt;artifactId&gt;aws-java-sdk&lt;/artifactId&gt; &lt;version&gt;1.1.8&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;net.authorize&lt;/groupId&gt; &lt;artifactId&gt;java-anet-sdk&lt;/artifactId&gt; &lt;version&gt;1.4.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.15&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;2.3.2&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.6&lt;/source&gt; &lt;target&gt;1.6&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.1.1&lt;/version&gt; &lt;configuration&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;finalName&gt;${artifactId}&lt;/finalName&gt; &lt;/build&gt; &lt;profiles&gt; &lt;profile&gt; &lt;id&gt;endorsed&lt;/id&gt; &lt;activation&gt; &lt;property&gt; &lt;name&gt;sun.boot.class.path&lt;/name&gt; &lt;/property&gt; &lt;/activation&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;!-- javaee6 contains upgrades of APIs contained within the JDK itself. As such these need to be placed on the bootclasspath, rather than classpath of the compiler. If you don't make use of these new updated API, you can delete the profile. On non-SUN jdk, you will need to create a similar profile for your jdk, with the similar property as sun.boot.class.path in Sun's JDK.--&gt; &lt;compilerArguments&gt; &lt;bootclasspath&gt;${settings.localRepository}/javax/javaee-endorsed-api/6.0/javaee-endorsed-api-6.0.jar${path.separator}${sun.boot.class.path}&lt;/bootclasspath&gt; &lt;/compilerArguments&gt; &lt;/configuration&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-endorsed-api&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/profile&gt; &lt;/profiles&gt; &lt;properties&gt; &lt;netbeans.hint.deploy.server&gt;gfv3ee6&lt;/netbeans.hint.deploy.server&gt; &lt;/properties&gt; </code></pre> <p></p>
5,527,209
5
0
null
2011-04-03 02:01:34.217 UTC
3
2022-01-11 11:34:40.807 UTC
2011-04-06 18:32:54.7 UTC
null
111,331
null
689,437
null
1
18
maven|java-ee-6|resourcebundle
46,718
<p>What is your project's build path configured to be in Netbeans? You might try changing it to <code>src/main/webapp/WEB-INF/classes</code>. This way class files compiled from your <code>src/main/java</code> folder and any resources you have under <code>src/main/resources</code> should get included in the generated WAR. You would then be able to access your config.properties file if you place it under the <code>src/main/resources</code> folder.</p> <p>You might also review any <code>includes</code> sections in your pom.xml and ensure you're not accidentally excluding something (if you explicitly include some things, you're likely implicitly excluding everything else).</p>
5,031,116
Joining aggregated values back to the original data frame
<p>One of the design patterns I use over and over is performing a "group by" or "split, apply, combine (SAC)" on a data frame and then joining the aggregated data back to the original data. This is useful, for example, when calculating each county's deviation from the state mean in a data frame with many states and counties. Rarely is my aggregate calculation only a simple mean, but it makes a good example. I often solve this problem the following way:</p> <pre><code>require(plyr) set.seed(1) ## set up some data group1 &lt;- rep(1:3, 4) group2 &lt;- sample(c("A","B","C"), 12, rep=TRUE) values &lt;- rnorm(12) df &lt;- data.frame(group1, group2, values) ## got some data, so let's aggregate group1Mean &lt;- ddply( df, "group1", function(x) data.frame( meanValue = mean(x$values) ) ) df &lt;- merge( df, group1Mean ) df </code></pre> <p>Which produces nice aggregate data like the following:</p> <pre><code>&gt; df group1 group2 values meanValue 1 1 A 0.48743 -0.121033 2 1 A -0.04493 -0.121033 3 1 C -0.62124 -0.121033 4 1 C -0.30539 -0.121033 5 2 A 1.51178 0.004804 6 2 B 0.73832 0.004804 7 2 A -0.01619 0.004804 8 2 B -2.21470 0.004804 9 3 B 1.12493 0.758598 10 3 C 0.38984 0.758598 11 3 B 0.57578 0.758598 12 3 A 0.94384 0.758598 </code></pre> <p>This works, but are there alternative ways of doing this which improve on readability, performance, etc?</p>
5,031,270
5
1
null
2011-02-17 15:40:42.323 UTC
12
2015-02-20 11:59:36.73 UTC
2015-02-20 11:58:27.75 UTC
null
1,851,712
null
37,751
null
1
19
r|plyr
5,737
<p>One line of code does the trick:</p> <pre><code>new &lt;- ddply( df, "group1", transform, numcolwise(mean)) new group1 group2 values meanValue 1 1 A 0.48742905 -0.121033381 2 1 A -0.04493361 -0.121033381 3 1 C -0.62124058 -0.121033381 4 1 C -0.30538839 -0.121033381 5 2 A 1.51178117 0.004803931 6 2 B 0.73832471 0.004803931 7 2 A -0.01619026 0.004803931 8 2 B -2.21469989 0.004803931 9 3 B 1.12493092 0.758597929 10 3 C 0.38984324 0.758597929 11 3 B 0.57578135 0.758597929 12 3 A 0.94383621 0.758597929 identical(df, new) [1] TRUE </code></pre>
5,473,542
Case insensitive string comparison
<p>I would like to compare two variables to see if they are the same, but I want this comparison to be case-insensitive.</p> <p>For example, this would be case sensitive:</p> <pre><code>if($var1 == $var2){ ... } </code></pre> <p>But I want this to be case insensitive, how would I approach this?</p>
5,473,569
6
0
null
2011-03-29 13:45:30.837 UTC
9
2018-01-04 11:15:54.583 UTC
2011-03-29 14:20:48.54 UTC
null
327,038
null
111,731
null
1
84
php|if-statement|case-insensitive
93,763
<p>This is fairly simple; you just need to call <a href="http://php.net/manual/en/function.strtolower.php"><code>strtolower()</code></a> on both variables.</p> <p>If you need to deal with Unicode or international character sets, you can use <a href="http://php.net/manual/en/function.mb-strtolower.php"><code>mb_strtolower()</code></a>.</p> <p>Please note that other answers suggest using <a href="http://php.net/manual/en/function.strcasecmp.php"><code>strcasecmp()</code></a>&mdash;that function <em>does not handle multibyte characters,</em> so results for any UTF-8 string will be bogus.</p>
5,048,371
Are Javascript arrays primitives? Strings? Objects?
<p>Are arrays merely objects in disguise? Why/why not? In what way(s) are they (such/not)?</p> <p>I have always thought of arrays and objects in JS as essentially the same, primarily because accessing them is identical.</p> <pre><code>var obj = {'I': 'me'}; var arr = new Array(); arr['you'] = 'them'; console.log(obj.I); console.log(arr.you); console.log(obj['I']); console.log(arr['you']); </code></pre> <p>Am I mislead/mistaken/wrong? What do I need to know about JS literals, primitives, and strings/objects/arrays/etc...?</p> <p>Are arrays/objects merely strings in disguise? Why/why not? In what way(s) are they (such/not)?</p>
5,048,482
7
8
null
2011-02-19 02:03:02.003 UTC
15
2014-06-30 23:03:13.347 UTC
2014-06-30 23:03:13.347 UTC
null
502,381
null
451,969
null
1
34
javascript|arrays|javascript-objects
20,720
<p>Arrays are objects.</p> <p>However, unlike regular objects, arrays have certain special features. </p> <ol> <li><p>Arrays have an additional object in their prototype chain - namely <code>Array.prototype</code>. This object contains so-called Array methods which can be called on array instances. (List of methods is here: <a href="http://es5.github.com/#x15.4.4" rel="noreferrer">http://es5.github.com/#x15.4.4</a>)</p></li> <li><p>Arrays have a <code>length</code> property (which is live, ergo, it auto-updates) (Read here: <a href="http://es5.github.com/#x15.4.5.2" rel="noreferrer">http://es5.github.com/#x15.4.5.2</a>)</p></li> <li><p>Arrays have a special algorithm regarding defining new properties (Read here: <a href="http://es5.github.com/#x15.4.5.1" rel="noreferrer">http://es5.github.com/#x15.4.5.1</a>). If you set a new property to an array and that property's name is a sting which can be coerced to an integer number (like <code>'1'</code>, <code>'2'</code>, <code>'3'</code>, etc.) then the special algorithm applies (it is defined on p. 123 in the spec)</p></li> </ol> <p>Other than these 3 things, arrays are just like regular objects.</p> <p>Read about arrays in the spec: <a href="http://es5.github.com/#x15.4" rel="noreferrer">http://es5.github.com/#x15.4</a></p>
4,979,681
How to properly free a std::string from memory
<p>What's the best way to delete an std::string from memory allocated on the heap when I'm done using it? Thanks!</p>
4,979,705
7
14
null
2011-02-12 18:05:58.803 UTC
20
2022-02-26 16:01:39.88 UTC
2011-02-12 18:16:33.643 UTC
null
435,224
null
435,224
null
1
55
c++|string
92,065
<p><code>std::string</code> is just a normal class<sup>1</sup>, so the usual rules apply.</p> <p>If you allocate <code>std::string</code> objects on the stack, as globals, as class members, ... you don't need to do anything special, when they go out of scope their destructor is called, and it takes care of freeing the memory used for the string automatically.</p> <pre><code>int MyUselessFunction() { std::string mystring="Just a string."; // ... return 42; // no need to do anything, mystring goes out of scope and everything is cleaned up automatically } </code></pre> <p>The only case where you have to do something is when you allocate an <code>std::string</code> on the heap using the <code>new</code> operator; in that case, as with any object allocated with <code>new</code>, you have to call <code>delete</code> to free it.</p> <pre><code>int MyUselessFunction() { // for some reason you feel the need to allocate that string on the heap std::string * mystring= new std::string("Just a string."); // ... // deallocate it - notice that in the real world you'd use a smart pointer delete mystring; return 42; } </code></pre> <p>As implied in the example, in general it's pointless to allocate a <code>std::string</code> on the heap, and, when you need that, still you should encapsulate such pointer in a smart pointer to avoid even risking memory leaks (in case of exceptions, multiple return paths, ...).</p> <hr /> <ol> <li><p>Actually <code>std::string</code> is defined as</p> <pre><code>namespace std { typedef std::basic_string&lt;char&gt; string; }; </code></pre> <p>so it's a synonym for the instantiation of the <code>basic_string</code> template class for characters of type <code>char</code> (this doesn't change anything in the answer, but on SO you <em>must</em> be pedantic even on newbie questions).</p></li> </ol>
5,347,962
How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?
<p>I am trying to connect minicom to a serial device that is connected via a USB-to-serial adapter. This is a PL2303 and from everything I've read no additional drivers are required. The device is recognised as a PL2303.</p> <p>I'm a beginner at minicom. Is this the correct command to execute? Or do I need to configure something?</p> <pre><code>$ sudo minicom --device /dev/ttyUSB0 minicom: cannot open /dev/ttyUSB0: No such file or directory $ sudo lsusb -v Bus 002 Device 006: ID 067b:2303 Prolific Technology, Inc. PL2303 Serial Port Device Descriptor: bLength 18 bDescriptorType 1 $ tail /var/log/syslog #then removed and attached the device. Mar 13 23:31:49 ubuntu kernel: [807996.786805] usb 2-1: pl2303 converter now attached to ttyUSB0 Mar 13 23:34:44 ubuntu kernel: [808172.155129] usb 2-1: USB disconnect, address 7 Mar 13 23:34:44 ubuntu kernel: [808172.156321] pl2303 ttyUSB0: pl2303 converter now disconnected from ttyUSB0 Mar 13 23:34:44 ubuntu kernel: [808172.156374] pl2303 2-1:1.0: device disconnected Mar 13 23:34:52 ubuntu kernel: [808179.497856] usb 2-1: new full speed USB device using uhci_hcd and address 8 Mar 13 23:34:52 ubuntu kernel: [808179.785845] pl2303 2-1:1.0: pl2303 converter detected Mar 13 23:34:52 ubuntu kernel: [808179.872309] usb 2-1: pl2303 converter now attached to ttyUSB0 </code></pre>
6,719,367
10
5
null
2011-03-18 04:08:55.377 UTC
40
2019-06-10 19:00:13.97 UTC
2018-04-15 15:51:16.94 UTC
null
63,550
null
326,089
null
1
75
linux|serial-port|usb|hardware-interface
615,312
<p>First check with <code>dmesg | grep tty</code> if system recognize your adapter. Then try to run minicom with <code>sudo minicom -s</code>, go to "Serial port setup" and change the first line to <code>/dev/ttyUSB0</code>. </p> <p>Don't forget to save config as default with "Save setup as dfl". It works for me on Ubuntu 11.04 on VirtualBox. </p>
5,041,494
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
<p>Is there any way to select/manipulate CSS pseudo-elements such as <code>::before</code> and <code>::after</code> (and the old version with one semi-colon) using jQuery?</p> <p>For example, my stylesheet has the following rule:</p> <pre class="lang-css prettyprint-override"><code>.span::after{ content:'foo' } </code></pre> <p>How can I change 'foo' to 'bar' using vanilla JS or jQuery?</p>
5,734,583
25
5
null
2011-02-18 12:53:10.7 UTC
290
2021-10-15 19:11:43.037 UTC
2020-11-12 12:24:37.557 UTC
null
8,620,333
null
580,527
null
1
1,096
javascript|jquery|css|jquery-selectors|pseudo-element
819,989
<p>You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:</p> <p>In HTML:</p> <pre><code>&lt;span&gt;foo&lt;/span&gt; </code></pre> <p>In jQuery:</p> <pre><code>$('span').hover(function(){ $(this).attr('data-content','bar'); }); </code></pre> <p>In CSS: </p> <pre class="lang-css prettyprint-override"><code>span:after { content: attr(data-content) ' any other text you may want'; } </code></pre> <p>If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:</p> <p>In HTML:</p> <pre><code>&lt;span&gt;foo&lt;/span&gt; </code></pre> <p>In jQuery:</p> <pre><code>$('span').hover(function(){ $(this).addClass('change').attr('data-content','bar'); }); </code></pre> <p>In CSS: </p> <pre class="lang-css prettyprint-override"><code>span.change:after { content: attr(data-content) ' any other text you may want'; } </code></pre>
12,158,737
display/hide textbox based on drop down list
<p>For-example I've got a code:</p> <pre><code>&lt;form name="myform"&gt; &lt;table&gt; &lt;td&gt; &lt;select name="one" onchange="if (this.selectedIndex=='other'){this.myform['other'].style.visibility='visible'}else {this.myform['other'].style.visibility='hidden'};"&gt; &lt;option value="" selected="selected"&gt;Select...&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;3&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="other"&gt;Other&lt;/option&gt; &lt;/select&gt; &lt;input type="textbox" name="other" style="visibility:hidden;"/&gt; &lt;/td&gt; &lt;/table&gt; &lt;/form&gt; </code></pre> <p>I need the textbox to appear when option "other" is selected. The above code is not working :(</p>
12,158,819
8
0
null
2012-08-28 11:56:20.803 UTC
2
2016-08-18 09:41:35.287 UTC
null
null
null
null
1,403,386
null
1
6
javascript|html
91,153
<p><code>selectedIndex</code> gives an index i.e. a number, so the index for "other" is 8, you can get the value of the selected option from the value property of the select element. To access the form a control is in use the elements form property <code>this.form</code>, also your you table cells should be in a row.</p> <pre><code>&lt;form name="myform"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;select name="one" onchange="if (this.value=='other'){this.form['other'].style.visibility='visible'}else {this.form['other'].style.visibility='hidden'};"&gt; &lt;option value="" selected="selected"&gt;Select...&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;3&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="other"&gt;Other&lt;/option&gt; &lt;/select&gt; &lt;input type="textbox" name="other" style="visibility:hidden;"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; </code></pre>
12,504,464
iOS 6 UITabBarController supported orientation with current UINavigation controller
<p>I have an iPhone app I am updating to iOS 6 that is having rotation issues. I have a <code>UITabBarController</code> with 16 <code>UINavigationCotrollers</code>. Most of the subviews can work in portrait or landscape but some of them are portrait only. With iOS 6 things are rotating when they shouldn't.</p> <p>I tried subclassing the tabBarController to return the <code>supportedInterfaceOrienations</code> of the current navigationController's selected viewController:</p> <pre><code>- (NSUInteger)supportedInterfaceOrientations{ UINavigationController *navController = (UINavigationController *)self.selectedViewController; return [navController.visibleViewController supportedInterfaceOrientations]; } </code></pre> <p>This got me closer. The view controller won't rotate out of position when visible, but if I am in landscape and switch tabs the new tab will be in landscape even if it isn't supported.</p> <p>Ideally the app will only be in the supported orienation of the current visible view controller. Any ideas?</p>
12,505,461
4
0
null
2012-09-19 23:57:04.68 UTC
23
2015-11-05 16:42:21.937 UTC
2015-11-05 16:42:21.937 UTC
null
2,713,079
null
307,906
null
1
17
uinavigationcontroller|rotation|uitabbarcontroller|orientation|ios6
16,906
<p>Subclass your <code>UITabBarController</code> overriding these methods:</p> <pre><code>-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // You do not need this method if you are not supporting earlier iOS Versions return [self.selectedViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation]; } -(NSUInteger)supportedInterfaceOrientations { return [self.selectedViewController supportedInterfaceOrientations]; } -(BOOL)shouldAutorotate { return YES; } </code></pre> <p>Subclass your <code>UINavigationController</code> overriding these methods:</p> <pre><code>-(NSUInteger)supportedInterfaceOrientations { return [self.topViewController supportedInterfaceOrientations]; } -(BOOL)shouldAutorotate { return YES; } </code></pre> <p>Then implement these methods in your viewControllers that you do not want to rotate:</p> <pre><code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } -(BOOL)shouldAutorotate { return NO; } -(NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } </code></pre> <p>And for viewControllers that you do want to rotate:</p> <pre><code> - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } -(NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAllButUpsideDown; } -(BOOL)shouldAutorotate { return YES; } </code></pre> <p>Your tabbarController should be added as the RootviewController of the app window. If you plan to support the default orientations, all but upsidedown is default for iPhone, then you do not need to do anything else. If you want to support upside-down or if you do not want to support another of the orientations, then you need to set the appropriate values in app delegate and/or info.plist.</p>
12,081,894
Backbone Router navigate and anchor href
<p>In a backbone-enabled app, I have seen code that continues to use <code>&lt;a href="#foo"&gt;&lt;/a&gt;</code>, while the anchor click is handled by a backbone event handler. </p> <p>Alternatively, the navigation to #foo can be handled by:</p> <pre><code>Router.history.navigate("foo"); </code></pre> <p>I believe the latter is the superior approach because it allows easy migration to and from HTML5's pushState functionality. And if we do use pushState, Backbone would be able to gracefully degrade to #foo for browsers that do not support pushState.</p> <p>As I am still new to Backbone, can someone more experienced and knowledgable confirm that this is the case?</p>
12,082,118
4
1
null
2012-08-22 21:47:46.507 UTC
14
2017-09-15 18:56:59.39 UTC
2012-08-22 21:59:15.167 UTC
null
9,021
null
422,283
null
1
23
javascript|backbone.js
20,732
<p>I personally have <code>pushState</code> enabled and use the approach taken in Tim Branyen's backbone-boilerplate of <a href="https://github.com/tbranyen/backbone-boilerplate/blob/master/app/main.js#L22">adding a click handler</a> that sends all link clicks to <code>navigate</code> unless they have a <code>data-bypass</code> attribute:</p> <pre><code>$(document).on("click", "a:not([data-bypass])", function(evt) { var href = { prop: $(this).prop("href"), attr: $(this).attr("href") }; var root = location.protocol + "//" + location.host + Backbone.history.options.root; if (href.prop &amp;&amp; href.prop.slice(0, root.length) === root) { evt.preventDefault(); Backbone.history.navigate(href.attr, true); } }); </code></pre> <p>This works pretty well and as @nickf mentions has the advantage that you don't have to use the hash/hashbang hack, even for browsers that do not support pushState.</p>
12,546,499
Tint image using CSS without overlay
<p>Is it possible to tint an image with a specific color using CSS without an overlay in a WebKit browser?</p> <p><strong>Failed attempts</strong></p> <ul> <li>Managed to tint the image sepia or an arbitrary color using <code>hue-rotate</code> but couldn't find a way to tint it with a specific color.</li> <li>Creating a "tint" SVG filter and calling it with <code>-webkit-filter: url(#tint)</code> doesn't work on Chrome.</li> <li>All possible combinations of <code>opacity</code>/<code>box-shadow</code> css properties with <code>drop-shadow</code>/<code>opacity</code> filters don't generate the desired effect.</li> </ul> <p><strong>Ideas</strong></p> <ul> <li>Given a color, wouldn't it be possible to combine the HSB filters (<code>hue-rotate</code>, <code>saturation</code>, <code>brightness</code>) to generate its tint? </li> </ul>
12,546,549
5
6
null
2012-09-22 18:20:56.94 UTC
10
2017-02-17 04:41:22.463 UTC
2012-09-22 22:36:44.08 UTC
null
143,378
null
143,378
null
1
36
css|svg|webkit|image-manipulation
78,039
<p>Eventually it will be, using <em>shaders</em>. See the W3C Docs on Filters.</p> <p><strong>At the moment</strong>, what is possible for instance is:</p> <pre><code>-webkit-filter: grayscale; /*sepia, hue-rotate, invert....*/ -webkit-filter: brightness(50%); </code></pre> <p><strong>See</strong> </p> <ul> <li><a href="http://davidwalsh.name/css-filters" rel="noreferrer">David Walsh on CSS Filters</a></li> <li><a href="https://stackoverflow.com/questions/10465464/apply-a-rose-tint-or-change-entire-documents-brightness-in-css-js-jquery-html">Stackoverflow: apply a rose tint...</a>: </li> <li><a href="https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#recommendation" rel="noreferrer">W3C Filter Effects 1.0 Docs - 38.2.5. Other uniform variables: the CSS shaders parameters</a></li> </ul> <p><strong>Update</strong>:</p> <p><em>Adobe</em> released its HTML5 based <a href="http://html.adobe.com/webstandards/csscustomfilters/cssfilterlab/" rel="noreferrer">CSS Filter Labs</a> with support for <a href="http://html.adobe.com/webstandards/csscustomfilters/" rel="noreferrer">custom filters</a> (Shaders) on supported browsers:</p> <p><img src="https://i.stack.imgur.com/fLXsz.png" alt="enter image description here"></p>
12,073,513
Insert using LEFT JOIN and INNER JOIN
<p>Hey all i am trying to figure out how to go about inserting a new record using the following query:</p> <pre><code>SELECT user.id, user.name, user.username, user.email, IF(user.opted_in = 0, 'NO', 'YES') AS optedIn FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id ORDER BY user.id; </code></pre> <p>My <code>INSERT</code> query so far is this:</p> <pre><code>INSERT INTO user SELECT * FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id; </code></pre> <p>However, i am not sure how to do <code>VALUE('','','','', etc etc)</code> when using left and inner joins.</p> <p>So what i am looking to do is this:</p> <p><code>User</code> table:</p> <pre><code>id | name | username | password | OptIn -------------------------------------------------------------------- 562 Bob Barker bBarker [email protected] 1 </code></pre> <p>And also the <code>user_permission</code> table</p> <pre><code>user_id | Permission_id ------------------------- 562 4 </code></pre> <p><strong>UPDATE</strong> So like this?</p> <pre><code>INSERT INTO user (name, username, password, email, opted_in) VALUES ('Bbarker','Bbarker','blahblahblah','[email protected]',0); INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(),4); </code></pre>
12,073,552
3
2
null
2012-08-22 12:47:47.71 UTC
17
2022-04-07 10:33:24.083 UTC
2018-07-08 13:55:30.803 UTC
null
1,009,717
null
277,480
null
1
58
mysql|left-join|inner-join
310,107
<p>You have to be specific about the columns you are selecting. If your <code>user</code> table had four columns <code>id, name, username, opted_in</code> you must select exactly those four columns from the query. The syntax looks like:</p> <pre><code>INSERT INTO user (id, name, username, opted_in) SELECT id, name, username, opted_in FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id </code></pre> <p>However, there does not appear to be any reason to join against <code>user_permission</code> here, since none of the columns from that table would be inserted into <code>user</code>. In fact, this <code>INSERT</code> seems bound to fail with primary key uniqueness violations.</p> <p>MySQL does not support inserts into multiple tables at the same time. You either need to perform two <code>INSERT</code> statements in your code, using the last insert id from the first query, or create an <code>AFTER INSERT</code> trigger on the primary table.</p> <pre><code>INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0); /* Gets the id of the new row and inserts into the other table */ INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4) </code></pre> <p>Or using a <a href="http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html" rel="nofollow noreferrer">trigger</a>:</p> <pre><code>CREATE TRIGGER creat_perms AFTER INSERT ON `user` FOR EACH ROW BEGIN INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4) END </code></pre>
18,856,376
Android: Why can't I create a handler in new thread
<p>I had a problem creating a handler in new thread. This is my code:</p> <pre><code> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { public void run() { Handler handler = new Handler(); } }).start(); } </code></pre> <p>But it raised an error! Can someone please explain this to me? Thanks so much!</p> <p>Here are the details of my error:</p> <pre><code>09-17 18:05:29.484: E/AndroidRuntime(810): FATAL EXCEPTION: Thread-75 09-17 18:05:29.484: E/AndroidRuntime(810): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 09-17 18:05:29.484: E/AndroidRuntime(810): at android.os.Handler.&lt;init&gt;(Handler.java:197) 09-17 18:05:29.484: E/AndroidRuntime(810): at android.os.Handler.&lt;init&gt;(Handler.java:111) 09-17 18:05:29.484: E/AndroidRuntime(810): at com.example.handler.MainActivity$1.run(MainActivity.java:57) 09-17 18:05:29.484: E/AndroidRuntime(810): at java.lang.Thread.run(Thread.java:856) </code></pre>
18,857,260
4
5
null
2013-09-17 17:38:52.767 UTC
9
2019-01-31 17:49:07.05 UTC
2019-01-31 17:49:07.05 UTC
null
8,202,589
null
2,781,314
null
1
31
java|android|multithreading|handler
34,285
<p>You could also use a <code>HandlerThread</code> like this:</p> <pre><code>HandlerThread thread = new HandlerThread("MyHandlerThread"); thread.start(); Handler handler = new Handler(thread.getLooper()); </code></pre> <p><code>HandlerThread</code>s have a <code>Looper</code> associated with them, so this wouldn't throw an exception.</p>
3,817,409
Is John Resig's OO JavaScript implementation production safe?
<p>For a long time I have been throwing around the idea of making my JavaScript more object oriented. I have looked at a few different implementations of this as well but I just cannot decide if it is necessary or not.</p> <p>What I am trying to answer are the following questions</p> <ul> <li>Is <a href="http://ejohn.org/blog/simple-javascript-inheritance/" rel="noreferrer">John Resig's</a> simple inheritance structure safe to use for production?</li> <li>Is there any way to be able to tell how well it has been tested?</li> <li>Besides <a href="http://code.google.com/p/joose-js/" rel="noreferrer">Joose</a> what other choices do I have for this purpose? I need one that is easy to use, fast, and robust. It also needs to be compatible with jQuery.</li> </ul>
3,817,570
3
4
null
2010-09-28 22:14:27.37 UTC
19
2010-09-30 10:19:44.09 UTC
2010-09-30 10:19:44.09 UTC
null
258,127
null
244,061
null
1
24
javascript|jquery|oop
2,153
<p>Huh. It looks much more complicated than it needs to be, to me.</p> <p>Actually looking more closely I really take exception to what it is doing with providing <code>this._super()</code> whilst in a method, to call the superclass method.</p> <p>The code introduces a reliance on <code>typeof==='function'</code> (unreliable for some objects), <code>Function#toString</code> (argh, function decomposition is also unreliable), and deciding whether to wrap based on whether you've used the sequence of bytes <code>_super</code> in the function body (even if you've only used it in a string. and if you try eg. <code>this['_'+'super']</code> it'll fail).</p> <p>And if you're storing properties on your function objects (eg <code>MyClass.myFunction.SOME_PRIVATE_CONSTANT</code>, which you might do to keep namespaces clean) the wrapping will stop you from getting at those properties. And if an exception is thrown in a method and caught in another method of the same object, <code>_super</code> will end up pointing at the wrong thing.</p> <p>All this is just to make calling your superclass's method-of-the-same name easier. But I don't think that's especially hard to do in JS anyway. It's too clever for its own good, and in the process making the whole less reliable. (Oh, and <code>arguments.callee</code> isn't valid in Strict Mode, though that's not really his fault since that occurred after he posted it.)</p> <p>Here's what I'm using for classes at the moment. I don't claim that this is the “best” JS class system, because there are <em>loads</em> of different ways of doing it and a bunch of different features you might want to add or not add. But it's very lightweight and aims at being ‘JavaScriptic’, if that's a word. (It isn't.)</p> <pre><code>Function.prototype.makeSubclass= function() { function Class() { if (!(this instanceof Class)) throw 'Constructor function requires new operator'; if ('_init' in this) this._init.apply(this, arguments); } if (this!==Object) { Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype; Class.prototype= new Function.prototype.makeSubclass.nonconstructor(); } return Class; }; Function.prototype.makeSubclass.nonconstructor= function() {}; </code></pre> <p>It provides:</p> <ol> <li><p>protection against accidental missing <code>new</code>. The alternative is to silently redirect <code>X()</code> to <code>new X()</code> so missing <code>new</code> works. It's a toss-up which is best; I went for explicit error so that one doesn't get used to writing without <code>new</code> and causing problems on other objects not defined like that. Either way is better than the unacceptable JS default of letting <code>this.</code> properties fall onto <code>window</code> and mysteriously going wrong later.</p></li> <li><p>an inheritable <code>_init</code> method, so you don't have to write a constructor-function that does nothing but call the superclass constructor function.</p></li> </ol> <p>and that's really all.</p> <p>Here's how you might use it to implement Resig's example:</p> <pre><code>var Person= Object.makeSubclass(); Person.prototype._init= function(isDancing) { this.dancing= isDancing; }; Person.prototype.dance= function() { return this.dancing; }; var Ninja = Person.makeSubclass(); Ninja.prototype._init= function() { Person.prototype._init.call(this, false); }; Ninja.prototype.swingSword= function() { return true; }; var p= new Person(true); p.dance(); // =&gt; true var n = new Ninja(); n.dance(); // =&gt; false n.swingSword(); // =&gt; true // Should all be true p instanceof Person &amp;&amp; n instanceof Ninja &amp;&amp; n instanceof Person </code></pre> <p>Superclass-calling is done by specifically naming the method you want and <code>call</code>ing it, a bit like in Python. You <em>could</em> add a <code>_super</code> member to the constructor function if you wanted to avoid naming <code>Person</code> again (so you'd say <code>Ninja._super.prototype._init.call</code>, or perhaps <code>Ninja._base._init.call</code>).</p>
3,898,781
How can I change a button's color on hover?
<p>I need to change the color of a button on hover.</p> <p>Here is my solution, but it doesn't work.</p> <pre><code>a.button { display: -moz-inline-stack; display: inline-block; width: 391px; height: 62px; background: url("img/btncolor.png") no-repeat; line-height: 62px; vertical-align: text-middle; text-align: center; color: #ebe6eb; font-family: Zenhei; font-size: 39px; font-weight: normal; font-style: normal; text-shadow: #222222 1px 1px 0; } a.button a:hover{ background: #383; } </code></pre>
3,898,783
3
0
null
2010-10-10 02:37:55.28 UTC
5
2019-08-07 12:03:18.887 UTC
2015-12-10 15:04:39.967 UTC
null
2,181,514
null
428,137
null
1
27
css|button|hover
225,343
<p><code>a.button a:hover</code> means "a link that's being hovered over that is a child of a link with the class <code>button</code>".</p> <p>Go instead for <code>a.button:hover</code>.</p>
3,850,074
Regex Until But Not Including
<p>For regex what is the syntax for search until but not including? Kinda like:</p> <pre class="lang-none prettyprint-override"><code>Haystack: The quick red fox jumped over the lazy brown dog Expression: .*?quick -&gt; and then everything until it hits the letter "z" but do not include z </code></pre>
3,850,095
3
0
null
2010-10-03 14:08:06.06 UTC
50
2018-03-06 22:35:18.47 UTC
2018-03-06 22:35:18.47 UTC
null
5,432,315
null
409,958
null
1
102
regex|search|regex-lookarounds
135,996
<p>The explicit way of saying "search until <code>X</code> but not including <code>X</code>" is:</p> <pre><code>(?:(?!X).)* </code></pre> <p>where <code>X</code> can be any regular expression. </p> <p>In your case, though, this might be overkill - here the easiest way would be </p> <pre><code>[^z]* </code></pre> <p>This will match anything except <code>z</code> and therefore stop right before the next <code>z</code>.</p> <p>So <code>.*?quick[^z]*</code> will match <code>The quick fox jumps over the la</code>. </p> <p>However, as soon as you have more than one simple letter to look out for, <code>(?:(?!X).)*</code> comes into play, for example</p> <p><code>(?:(?!lazy).)*</code> - match anything until the start of the word <code>lazy</code>. </p> <p>This is using a <strong><a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">lookahead assertion</a></strong>, more specifically a negative lookahead. </p> <p><code>.*?quick(?:(?!lazy).)*</code> will match <code>The quick fox jumps over the</code>.</p> <p><strong>Explanation:</strong></p> <pre><code>(?: # Match the following but do not capture it: (?!lazy) # (first assert that it's not possible to match "lazy" here . # then match any character )* # end of group, zero or more repetitions. </code></pre> <p>Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: <code>\bfox\b</code> will only match the complete word <code>fox</code> but not the fox in <code>foxy</code>.</p> <p><strong>Note</strong> </p> <p>If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending <code>(?s)</code> to the regex, but that doesn't work in all regex engines (notably JavaScript).</p> <p><strong>Alternative solution:</strong></p> <p>In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a <code>?</code> to the <code>*</code> quantifier, it will try to match as few characters as possible from the current position:</p> <pre><code>.*?(?=(?:X)|$) </code></pre> <p>will match any number of characters, stopping right before <code>X</code> (which can be any regex) or the end of the string (if <code>X</code> doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around <code>X</code> in order to reliably isolate it from the alternation)</p>
22,714,760
What happens exactly when a 32bit integer overflows on a 64bit machine?
<p>The situation is the following:</p> <ol> <li>a 32bit integer overflows</li> <li>malloc, which is <em>expecting</em> a 64bit integer uses this integer as input</li> </ol> <p><strong>Now on a 64bit machine, which statement is correct (if any at all)</strong>:</p> <p>Say that the signed binary integer 11111111001101100000101011001000 is simply negative due to an overflow. This is a practical existing problem since you might want to allocate more bytes than you can describe in a 32bit integer. But then it gets read in as a 64bit integer.</p> <ol> <li><code>Malloc</code> reads this as a 64bit integer, finding <code>11111111001101100000101011001000################################</code> with # being a wildcard bit representing whatever data is stored after the original integer. In other words, it read a result close to its maximum value 2^64 and tries to allocate some quintillion bytes. It fails.</li> <li><code>Malloc</code> reads this as a 64bit integer, casting to <code>0000000000000000000000000000000011111111001101100000101011001000</code>, possibly because it is how it is loaded into a register leaving a lot of bits zero. It does not fail but allocates the negative memory as if reading a positive unsigned value.</li> <li><code>Malloc</code> reads this as a 64bit integer, casting to <code>################################11111111001101100000101011001000</code>, possibly because it is how it is loaded into a register with # a wildcard representing whatever data was previously in the register. It fails quite unpredictably depending on the last value.</li> <li>The integer does not overflow at all because even though it is 32bit, it is still in a 64bit register and therefore malloc works fine.</li> </ol> <p>I actually tested this, resulting in the malloc failing (which would imply either 1 or 3 to be correct). I assume 1 is the most logical answer. I also know the fix (using size_t as input instead of int).</p> <p>I'd just really want to know what actually happens. For some reason I don't find any clarification on how 32bit integers are actually treated on 64bit machines for such an unexpected 'cast'. I'm not even sure if it being in a register actually matters.</p>
22,715,376
3
11
null
2014-03-28 13:52:05.787 UTC
8
2014-04-20 14:41:20.553 UTC
2014-04-20 14:41:20.553 UTC
null
760,948
null
3,472,774
null
1
19
c++|c|32bit-64bit
5,486
<p>Once an integer overflows, using its value results in undefined behavior. A program that uses the result of an <code>int</code> after the overflow is invalid according to the standard -- essentially, all bets about its behavior are off.</p> <p>With this in mind, let's look at what's going to happen on a computer where negative numbers are stored in two's complement representation. When you add two large 32-bit integers on such a computer, you get a negative result in case of an overflow.</p> <p>However, according to C++ standard, the type of <code>malloc</code>'s argument, i.e. <a href="https://stackoverflow.com/a/1089204/335858"><code>size_t</code>, is always unsigned</a>. When you convert a negative number to an unsigned number, it gets sign-extended (<a href="https://stackoverflow.com/a/21769421/335858">see this answer for a discussion and a reference to the standard</a>), meaning that the most significant bit of the original (which is <code>1</code> for all negative numbers) is set in the top 32 bits of the unsigned result.</p> <p>Therefore, what you get is a modified version of your third case, except that instead of "wildcard bit <code>#</code>" it has ones all the way to the top. The result is a gigantic unsigned number (roughly 16 <a href="http://en.wikipedia.org/wiki/Exbibyte" rel="nofollow noreferrer">exbibytes</a> or so); naturally <code>malloc</code> fails to allocate that much memory.</p>
10,911,757
How can I use PDO to fetch a results array in PHP?
<p>I'm just editing my search script after reading up on <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="noreferrer">SQL injection</a> attacks. I'm trying to get the same functionality out of my script using <a href="https://en.wikipedia.org/wiki/PHP#Development_and_community" rel="noreferrer">PDO</a> instead of a regular MySQL connection. So I've been reading other posts about PDO, but I am unsure. Will these two scripts give the same functionality?</p> <p>With PDO:</p> <pre><code>$pdo = new PDO('mysql:host=$host; dbname=$database;', $user, $pass); $stmt = $pdo-&gt;prepare('SELECT * FROM auction WHERE name = :name'); $stmt-&gt;bindParam(':name', $_GET['searchdivebay']); $stmt-&gt;execute(array(':name' =&gt; $name); </code></pre> <p>With regular MySQL:</p> <pre><code>$dbhost = @mysql_connect($host, $user, $pass) or die('Unable to connect to server'); @mysql_select_db('divebay') or die('Unable to select database'); $search = $_GET['searchdivebay']; $query = trim($search); $sql = &quot;SELECT * FROM auction WHERE name LIKE '%&quot; . $query . &quot;%'&quot;; if(!isset($query)){ echo 'Your search was invalid'; exit; } //line 18 $result = mysql_query($trim); $numrows = mysql_num_rows($result); mysql_close($dbhost); </code></pre> <p>I go on with the regular example to use</p> <pre><code>while($i &lt; $numrows){ $row = mysql_fetch_array($result); </code></pre> <p>to create an array of matching results from the database. How do I do this with PDO?</p>
10,911,850
2
6
null
2012-06-06 09:44:38.677 UTC
14
2021-10-14 18:48:38.87 UTC
2021-09-22 23:18:17.217 UTC
null
63,550
null
1,420,321
null
1
46
php|mysql|pdo
228,866
<p>Take a look at the <a href="http://www.php.net/manual/en/pdostatement.fetchall.php" rel="noreferrer"><code>PDOStatement.fetchAll</code></a> method. You could also use <a href="http://www.php.net/manual/en/pdostatement.fetch.php" rel="noreferrer"><code>fetch</code></a> in an iterator pattern.</p> <p>Code sample for <code>fetchAll</code>, from the PHP documentation:</p> <pre><code>&lt;?php $sth = $dbh-&gt;prepare("SELECT name, colour FROM fruit"); $sth-&gt;execute(); /* Fetch all of the remaining rows in the result set */ print("Fetch all of the remaining rows in the result set:\n"); $result = $sth-&gt;fetchAll(\PDO::FETCH_ASSOC); print_r($result); </code></pre> <p>Results:</p> <pre><code>Array ( [0] =&gt; Array ( [NAME] =&gt; pear [COLOUR] =&gt; green ) [1] =&gt; Array ( [NAME] =&gt; watermelon [COLOUR] =&gt; pink ) ) </code></pre>
11,195,692
json_encode PHP array as JSON array not JSON object
<p>I have the following array in PHP:</p> <pre><code>Array ( [0] =&gt; Array ( [id] =&gt; 0 [name] =&gt; name1 [short_name] =&gt; n1 ) [2] =&gt; Array ( [id] =&gt; 2 [name] =&gt; name2 [short_name] =&gt; n2 ) ) </code></pre> <p>I want to JSON encode it as a JSON array, producing a string like the following:</p> <pre><code>[ { &quot;id&quot;:0, &quot;name&quot;:&quot;name1&quot;, &quot;short_name&quot;:&quot;n1&quot; }, { &quot;id&quot;:2, &quot;name&quot;:&quot;name2&quot;, &quot;short_name&quot;:&quot;n2&quot; } ] </code></pre> <p>But when I call <a href="http://uk3.php.net/json_encode" rel="noreferrer"><code>json_encode</code></a> on this array, I get the following:</p> <pre><code>{ &quot;0&quot;:{ &quot;id&quot;:0, &quot;name&quot;:&quot;name1&quot;, &quot;short_name&quot;:&quot;n1&quot; }, &quot;2&quot;:{ &quot;id&quot;:2, &quot;name&quot;:&quot;name2&quot;, &quot;short_name&quot;:&quot;n2&quot; } } </code></pre> <p>Which is an object instead of an array.</p> <p>How can I get <code>json_encode</code> to encode my array as an array, instead?</p>
18,977,473
4
0
null
2012-06-25 19:06:27.41 UTC
30
2021-06-15 14:29:33.32 UTC
2021-06-15 14:29:33.32 UTC
null
2,844,319
user677607
null
null
1
133
php|json
191,759
<p>See <a href="https://datatracker.ietf.org/doc/html/rfc8259#section-5" rel="noreferrer">Arrays</a> in RFC 8259 <strong>The JavaScript Object Notation (JSON) Data Interchange Format</strong>:</p> <blockquote> <p>An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.</p> <p>array = begin-array [ value *( value-separator value ) ] end-array</p> </blockquote> <p>You are observing this behaviour because your array is not sequential - it has keys <code>0</code> and <code>2</code>, but doesn't have <code>1</code> as a key.</p> <p>Just having numeric indexes isn't enough. <code>json_encode</code> will only encode your PHP array as a JSON array if your PHP array is sequential - that is, if its keys are 0, 1, 2, 3, ...</p> <p>You can reindex your array sequentially using the <a href="http://uk3.php.net/array_values" rel="noreferrer"><code>array_values</code></a> function to get the behaviour you want. For example, the code below works successfully in your use case:</p> <pre class="lang-php prettyprint-override"><code>echo json_encode(array_values($input)). </code></pre>
12,876,222
Declaring a global array
<p>Hi. I recently learned PHP and am trying to declare a global array so I can access inside a function. But I seem to be missing something because I get the error 'Undefined variable:' </p> <p>Here is my code:</p> <pre><code>global $second_array; $second_array = array(); function operatii($v) { $var1 = $second_array[count($second_array)-1]; $var2 = $second_array[count($second_array)-2]; $rez = null; echo $var1 . $var2 . "este?"; } for ($i = 0; $i &lt; count($a); $i++){ if ($a[$i] === "+" || $a[$i] === "-" || $a[$i] === "*" || $a[$i] === "/" ) { operatii($a[$i]); } else { array_push($second_array, $a[$i]); } } </code></pre> <p>I seem to be able to use the <code>$second_array</code> in the for loop, but can't use it in the operatii function.<br> How can I solve this problem?</p>
12,876,327
3
2
null
2012-10-13 19:26:14.503 UTC
3
2016-04-18 09:34:07.58 UTC
2012-10-13 19:41:01.38 UTC
null
352,765
null
985,482
null
1
18
php|global
86,359
<p>There are two ways to reference a global variable in PHP:</p> <ol> <li>Use the <code>global</code> keyword at the start of every function that uses the variable.</li> <li>Use the <code>$GLOBALS</code> array.</li> </ol> <p>Of these, I recommend sticking with the second, since it makes it absolutely clear at all times that the variable is a global.</p> <p>One of the problems with globals is keeping track of where they're being used; using the <code>$GLOBALS</code> array mitigates this issue to some extent.</p> <p>However, there are still issues with using globals; it's generally considered poor practice to use too many globals in your code. Having worked with a number of legacy systems that used globals extensively, I can vouch for the fact that they can cause a lot of headaches for future developers.</p> <p>Using globals also makes it harder to write formal test suites for your code (ie unit tests).</p> <p>My recommendation would therefore be to avoid using globals at all where possible. They are necessary in some cases, but the more you can avoid them, and instead pass variables into your functions and classes rather than making them global, the better things will be.</p> <p>So to summarise:</p> <p>If you must use globals, reference them with <code>$GLOBALS['varname']</code>, but it's usually better not to use them at all.</p> <p>Hope that helps.</p>
13,025,026
what should go into completion in presentViewController?
<p>I am using <code>presentViewController</code> in xcode and not sure what should go into completion. </p> <p>The code given by xcode documentation:</p> <pre><code>- (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion NS_AVAILABLE_IOS(5_0); </code></pre> <p>Example that i am using: </p> <pre><code>[self presentViewController:second animated:YES completion:&lt;#^(void)completion#&gt;]; </code></pre> <p>What should go into completion?</p>
13,025,138
4
0
null
2012-10-23 06:56:17.103 UTC
7
2016-04-20 19:43:24.79 UTC
2012-10-23 06:58:26.68 UTC
null
1,388,966
null
1,152,000
null
1
25
iphone|ios
43,626
<p>You can use the below code instead:</p> <pre><code>[self presentViewController:second animated:YES completion:^{ }]; </code></pre> <p>or you can simply pass NULL</p> <pre><code>[self presentViewController:second animated:YES completion:NULL]; </code></pre> <p>The completion block is used for doing any tasks after presenting the view controller , the code written inside the completion block will execute only after the view is presented.</p>
12,970,395
Is it possible to automatically set UTF16 file encoding when opening a file of that type?
<p>I edit all kinds of files with Vim (as I'm sure most Vim users do). One bug bear I have is what Vim does when I come across a file with an odd encoding. Most editors (these days) make a good stab at detecting file encodings. However, Vim generally doesn't. And you have to type, for example:</p> <pre><code>:e ++enc=utf-16le </code></pre> <p>To re-read the file in UTF-16 (Otherwise you get a mass of @ signs)</p> <p>I've been searching around and have seen scripts like <code>set_utf8.vim</code> which can detect a specific file encoding. However, is there are more general solution? I'm a bit bored of having to manually work out what the file encoding is and consulting the help every time I open an unusual file.</p>
12,971,235
3
0
null
2012-10-19 08:38:48.85 UTC
9
2017-03-21 19:03:13.897 UTC
null
null
null
null
193,128
null
1
27
vim
13,311
<p>Adding the encoding name to <code>'fileencodings'</code> should do the trick:</p> <pre><code>:set fencs=ucs-bom,utf-16le,utf-8,default,latin1 </code></pre> <p>Alternatively, there are plugins like <a href="http://www.vim.org/scripts/script.php?script_id=2721" rel="noreferrer">AutoFenc</a> and <a href="http://www.vim.org/scripts/script.php?script_id=1708" rel="noreferrer">fencview</a>.</p>
12,955,337
Angular.js Backbone.js and other MV* patterned js libraries?
<p>I am quite newbie to web application, and more specifically to this <code>MV*</code>pattern. We are making a web application and we thinking of departing from jQuery, not completely, but we are trying to implement a client side language with MVC, MVVM, or MVP support. Basically something that separates views from model. Being new to this <code>MV*</code> pattern I stumbled upon <a href="http://codebrief.com/2012/01/the-top-10-javascript-mvc-frameworks-reviewed/" rel="nofollow noreferrer"><strong>this site</strong>.</a></p> <p>It basically list (almost!) all client side language/framework that support this <code>MV*</code> pattern, and after visiting it I am really confused. Because according to this site..</p> <blockquote> <p>At the end of the day, Ember.js is the only framework which has everything I desire. I recently ported a relatively small Backbone.js application over to Ember.js and, despite some small performance issues, I am much happier with the resulting code base. Being championed by Yehuda Katz, the community around Ember.js is also amazing. This is definitely the framework to watch out for.</p> </blockquote> <p>But on SO, I found <a href="https://stackoverflow.com/a/9408089">this</a>, and it makes me think that angular is much better, while on SO again, <a href="https://stackoverflow.com/a/10264263">this</a>, and <a href="https://stackoverflow.com/a/11260673">this</a> which makes me think it might be backbone what I am looking for.</p> <p>To make the matter worse, the tests show totally different result. Here </p> <p><a href="http://jsfiddle.net/HusVw/1/" rel="nofollow noreferrer">http://jsfiddle.net/HusVw/1/</a> <code>Backbone clear winner</code> </p> <p><a href="http://jsfiddle.net/ericf/NrpcQ/" rel="nofollow noreferrer">http://jsfiddle.net/ericf/NrpcQ/</a> <code>Backbone winner again</code> </p> <p><a href="http://jsperf.com/angular-vs-knockout-vs-extjs-vs-backbone/2" rel="nofollow noreferrer">http://jsperf.com/angular-vs-knockout-vs-extjs-vs-backbone/2</a> <code>angular winner for less data for more its knockout</code> </p> <p><a href="http://jsperf.com/knockout-js-vs-direct-dom-manipulation/3" rel="nofollow noreferrer">http://jsperf.com/knockout-js-vs-direct-dom-manipulation/3</a> <code>Backbone again</code></p> <p><a href="http://jsperf.com/angular-vs-knockout-vs-ember/33" rel="nofollow noreferrer">http://jsperf.com/angular-vs-knockout-vs-ember/33</a> <code>no way its ember as the site mentioned</code></p> <p>So, basically this all is totally confusing me, I can't decide what in web's name I should learn, and what should I implement in the site. As in tests <code>Backbone</code> clearly stands out, but I've heard a lot about <code>knockout</code>, but the SO links I mentioned say about <code>angular</code>? I know it might be dependent on the application I am currently developing, but I want a broader view, what would be useful not only for this project, but for a longer term? In which case you'd prefer which framework? Or Should I just learn them all?(jk, can't really do that in a plausible time.)</p> <p>To make things more f**** up, I heard about <a href="http://www.dartlang.org/" rel="nofollow noreferrer">dart</a>, and <a href="http://en.wikipedia.org/wiki/Dart_%28programming_language%29" rel="nofollow noreferrer">wiki</a> says..</p> <blockquote> <p>The goal of Dart is "ultimately to replace JavaScript as the lingua franca of web development on the open web platform."</p> </blockquote> <p>So if js is going to be replaced, why the hack I am even considering learning these js libraries/framework(s)?</p> <p>So, basically, its all messed up and I am totally confused? Can any one please help me decide?</p>
12,955,586
2
3
null
2012-10-18 13:01:08.92 UTC
12
2014-12-02 14:59:33.077 UTC
2017-05-23 10:28:22.727 UTC
null
-1
null
710,925
null
1
30
javascript|web-applications|backbone.js|frameworks|knockout.js
11,816
<p>There is probably no objective answer, but here's my 2 cents:</p> <p>Backbone usually leads to much larger code bases that are more difficult to maintain. Similar to the anecdote in your links, I've worked on one project where the code shrank from 2500 lines with Backbone to 600 lines with Angular. Knockout probably would have yielded equally small (=good) results. My colleagues have moved away from Backbone to Knockout and were much happier afterwards.</p> <p>The advantage of Backbone is that it is really lightweight and gives you more options to structure things. That also means you can do more performance tuning, so it can be faster. Those very same aspects are also its disadvantage: You <strong>need</strong> to structure things yourself which means: more code, more complicated and potentially more bugs. </p> <p>Regarding the tests you mention: They are hardly objective, since they emphasize one very particular use case. Also, they were posted by the author of Backbone himself, so obviously they show Backbone in a good light. For normal UIs, performance should not be a problem no matter which of the 3 (Backbone, Angular, Knockout) you choose. One caveat for Angular: If you want to dynamically display more than 2000 elements on your page, it could be problematic (see the answer of Angular's creator himself here: <a href="https://stackoverflow.com/questions/9682092/databinding-in-angularjs">How does data binding work in AngularJS?</a>).</p> <p>About Dart: Its goal is to be a language, not just a MV* framework within a language. That is a completely different beast and if you simply need a MV* framework, Dart would be overkill. Also, Dart is still very young and not natively supported in most browsers.</p>
12,747,554
Connect to SQL Server through PDO using SQL Server Driver
<p>I am trying to connect to an existing SQL Server database using PDO with the <a href="http://www.microsoft.com/en-us/download/details.aspx?id=20098" rel="noreferrer">drivers provided by Microsoft</a>.</p> <p>I have seen examples using odbc, dblib, mssql, etc., however I believe the connection string with these drivers should use 'sqlsrv'?</p> <p>Are there any good examples of how to properly do this? If I should be doing this via some other method please let me know. Thanks!</p>
12,748,489
6
0
null
2012-10-05 13:41:27.493 UTC
15
2021-03-03 06:55:11.663 UTC
2016-11-07 14:35:29.5 UTC
null
721,073
null
548,802
null
1
34
php|sql-server|windows|pdo
121,955
<p>Well that's the best part about PDOs is that it's pretty easy to access any database. Provided you have installed those drivers, you should be able to just do:</p> <pre><code>$db = new PDO("sqlsrv:Server=YouAddress;Database=YourDatabase", "Username", "Password"); </code></pre>
16,908,650
What is the difference between delete and calling destructor in C++
<p>As stated in the title, here is my code:</p> <pre><code>class Foo { public: Foo (int charSize) { str = new char[charSize]; } ~Foo () { delete[] str; } private: char * str; }; </code></pre> <p>For this class what would be the difference between:</p> <pre><code>int main () { Foo* foo = new Foo(10); delete foo; return 0; } </code></pre> <p>and</p> <pre><code>int main () { Foo* foo = new Foo(10); foo-&gt;~Foo(); return 0; } </code></pre>
16,908,669
2
4
null
2013-06-04 01:56:28.583 UTC
8
2017-05-03 03:27:13.623 UTC
2014-08-11 07:46:23.337 UTC
null
3,622,940
null
1,114,357
null
1
14
c++|memory-management|destructor
7,965
<p>Calling a destructor releases the resources owned by the object, but it does not release the memory allocated to the object itself. The second code snippet has a memory leak.</p>
16,714,917
Using QueueClient.OnMessage in an azure worker role
<p>I have an Azure worker role that is responsible for checking 4 service bus queues. Currently, I just the looping method to manually check the queues.</p> <pre><code>while(true) { //loop through my queues to check for messages } </code></pre> <p>With the Azure SDK 2.0 came the ability to listen for messages rather than polling for them. But Every example I've seen uses a console app with Console.ReadKey(). Is there a way to have the worker role sit and wait on messages too? </p> <p>I tried:</p> <pre><code>public override void Run() { _queueProcessors.ForEach(x =&gt; x.OnMessage(Process); } </code></pre> <p>where _queueProcessors is a list of QueueClients and Process is a private method that handles the messages. However, the worker role would register them and then restart.</p> <p>So anyone know how to make a queue client sit and wait on a message?</p>
16,739,691
1
0
null
2013-05-23 13:13:27.513 UTC
16
2021-04-20 23:33:00.76 UTC
2015-01-05 19:14:59.35 UTC
null
1,515,209
null
807,851
null
1
19
c#|azure|azure-worker-roles|azureservicebus|azure-servicebus-queues
15,041
<p>Following is a code sample for this:</p> <pre><code>using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using Microsoft.WindowsAzure.ServiceRuntime; using System.Diagnostics; using System.Net; using System.Threading; namespace WorkerRoleWithSBQueue1 { public class WorkerRole : RoleEntryPoint { // The name of your queue const string QueueName = &quot;demoapp&quot;; ManualResetEvent CompletedEvent = new ManualResetEvent(false); // QueueClient is thread-safe. Recommended that you cache // rather than recreating it on every request QueueClient Client; public override void Run() { OnMessageOptions options = new OnMessageOptions(); options.AutoComplete = true; // Indicates if the message-pump should call complete on messages after the callback has completed processing. options.MaxConcurrentCalls = 1; // Indicates the maximum number of concurrent calls to the callback the pump should initiate options.ExceptionReceived += LogErrors; // Allows users to get notified of any errors encountered by the message pump Trace.WriteLine(&quot;Starting processing of messages&quot;); // Start receiveing messages Client.OnMessage((receivedMessage) =&gt; // Initiates the message pump and callback is invoked for each message that is recieved, calling close on the client will stop the pump. { try { // Process the message Trace.WriteLine(&quot;Processing Service Bus message: &quot; + receivedMessage.SequenceNumber.ToString()); } catch { // Handle any message processing specific exceptions here } }, options); CompletedEvent.WaitOne(); } private void LogErrors(object sender, ExceptionReceivedEventArgs e) { if (e.Exception != null) { Trace.WriteLine(&quot;Error: &quot; + e.Exception.Message); } } public override bool OnStart() { // Set the maximum number of concurrent connections ServicePointManager.DefaultConnectionLimit = 12; // Create the queue if it does not exist already Trace.WriteLine(&quot;Creating Queue&quot;); string connectionString = &quot;*** provide your connection string here***&quot;; var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString); if (!namespaceManager.QueueExists(QueueName)) { namespaceManager.CreateQueue(QueueName); } // Initialize the connection to Service Bus Queue Client = QueueClient.CreateFromConnectionString(connectionString, QueueName); Trace.WriteLine(&quot;Sending messages...&quot;); // populate some messages for (int ctr = 0; ctr &lt; 10; ctr++) { Client.Send(new BrokeredMessage()); } return base.OnStart(); } public override void OnStop() { // Close the connection to Service Bus Queue Client.Close(); CompletedEvent.Set(); // complete the Run function base.OnStop(); } } } </code></pre>
17,108,943
how to use Exist in List<string> in C#
<p>I have to find if string exist in a list to avoid duplicates inserts: Here is example from Microsoft site:</p> <pre><code>using System; using System.Collections.Generic; public class Example { public static void Main() { List&lt;string&gt; dinosaurs = new List&lt;string&gt;(); dinosaurs.Add("Compsognathus"); dinosaurs.Add("Amargasaurus"); dinosaurs.Add("Oviraptor"); dinosaurs.Add("Velociraptor"); dinosaurs.Add("Deinonychus"); dinosaurs.Add("Dilophosaurus"); dinosaurs.Add("Gallimimus"); dinosaurs.Add("Triceratops"); Console.WriteLine(); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } Console.WriteLine("\nTrueForAll(EndsWithSaurus): {0}", dinosaurs.TrueForAll(EndsWithSaurus)); Console.WriteLine("\nFind(EndsWithSaurus): {0}", dinosaurs.Find(EndsWithSaurus)); Console.WriteLine("\nFindLast(EndsWithSaurus): {0}", dinosaurs.FindLast(EndsWithSaurus)); Console.WriteLine("\nFindAll(EndsWithSaurus):"); List&lt;string&gt; sublist = dinosaurs.FindAll(EndsWithSaurus); foreach(string dinosaur in sublist) { Console.WriteLine(dinosaur); } Console.WriteLine( "\n{0} elements removed by RemoveAll(EndsWithSaurus).", dinosaurs.RemoveAll(EndsWithSaurus)); Console.WriteLine("\nList now contains:"); foreach(string dinosaur in dinosaurs) { Console.WriteLine(dinosaur); } Console.WriteLine("\nExists(EndsWithSaurus): {0}", dinosaurs.Exists(EndsWithSaurus)); } // Search predicate returns true if a string ends in "saurus". private static bool EndsWithSaurus(String s) { return s.ToLower().EndsWith("saurus"); } } </code></pre> <p>Is it possible to replace <code>EndsWithSaurus</code> function with lambda expression? Thanks everybody for your input!! Here is a working code: </p> <pre><code> if (dinosaurs.Any(e =&gt; e.EndsWith("saurus"))) Console.WriteLine("saurus exists"); if (dinosaurs.Exists(e =&gt; e.EndsWith("saurus"))) Console.WriteLine("saurus exists"); </code></pre>
17,109,042
2
4
null
2013-06-14 12:54:48.343 UTC
3
2014-03-13 10:19:07.243 UTC
2014-03-13 10:19:07.243 UTC
null
817,365
null
201,889
null
1
19
c#
83,930
<p>Try this:</p> <pre><code>if (dinosaurs.Exists(e =&gt; e.EndsWith("saurus"))) Console.WriteLine("saurus exists"); </code></pre> <p>The answer with <code>Any()</code> works fine too. The difference is just the <code>Exists()</code> method comes from <code>List&lt;T&gt;</code> itself and the <code>Any()</code> is just one of the great Linq extension methods (and will require <code>using System.Linq</code>)</p>
16,997,034
How to pass parameters dynamically to Spring beans
<p>I am new to Spring.</p> <p>This is the code for bean registration:</p> <pre><code>&lt;bean id="user" class="User_Imple"&gt; &lt;/bean&gt; &lt;bean id="userdeff" class="User"&gt; &lt;/bean&gt; </code></pre> <p>and this is my bean class:</p> <pre><code>public class User_Imple implements Master_interface { private int id; private User user; // here user is another class public User_Imple() { super(); } public User_Imple(int id, User user) { super(); this.id = id; this.user = user; } // some extra functions here.... } </code></pre> <p>and this is my main method to perform action:</p> <pre><code>public static void main(String arg[]) { ApplicationContext context = new ClassPathXmlApplicationContext("/bean.xml"); Master_interface master = (Master_interface)context.getBean("user"); // here is my some operations.. int id = ... User user = ... // here is where i want to get a Spring bean User_Imple userImpl; //want Spring-managed bean created with above params } </code></pre> <p>Now I want to call this constructor with parameters, and these parameters are generated dynamically in my main methods. This is what I mean by I want to pass dynamically – not statically, like declared in my <code>bean.config</code> file.</p>
16,997,105
5
0
null
2013-06-08 07:07:38.72 UTC
10
2021-02-12 20:03:32.66 UTC
2014-11-12 08:24:21.897 UTC
null
849,076
null
1,615,868
null
1
29
java|spring|javabeans
119,611
<p>Please have a look at <a href="http://static.springsource.org/spring/docs/2.5.3/reference/beans.html#beans-factory-collaborators" rel="nofollow">Constructor injection</a>.</p> <p>Also, Have a look at <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/InitializingBean.html" rel="nofollow">IntializingBean</a> and <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/config/BeanPostProcessor.html" rel="nofollow">BeanPostProcessor</a> for other life cycle interception of a springbean.</p>
16,888,095
Facebook Login API HTTPS Issue
<p>The website I'm working on has a Facebook login option, but recently a user reported it wasn't working for them. I disabled my extensions etc, I got this error in my console:</p> <pre><code>Blocked a frame with origin "https://www.facebook.com" from accessing a frame with origin "http://static.ak.facebook.com". The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match. </code></pre> <p>Is there an option I can feed to the API that will get it to work on the same protocols? FYI, the primary website runs on HTTP (no S).</p> <p>It is especially odd because it seems like it stopped working all of a sudden (but it is possible this was always a problem as I am new and am learning this system).</p> <p>I have this code at the foot of my page:</p> <pre><code>&lt;div id="fb-root"&gt;&lt;/div&gt; &lt;script&gt; window.fbAsyncInit = function() { FB.init({ appId : ..., // App ID status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true, // parse XFBML channel: '//...mychannel.../channel' }); FB.Event.subscribe('auth.authResponseChange', function(fbResponse) { // function that logs in user }); }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); &lt;/script&gt; </code></pre>
19,188,493
4
5
null
2013-06-02 22:56:58.243 UTC
4
2015-05-03 12:04:31.213 UTC
2013-06-07 01:49:30.78 UTC
null
210,920
null
210,920
null
1
31
facebook-javascript-sdk|facebook-login
17,777
<p>For what it's worth, I managed to fix this issue by converting to HTTPS (which is what I should have been doing anyway).</p>
16,767,231
What are the reduceAdd, reduceSum , reduceRemove functions in crossfilter? How should they be used?
<p>Can someone explain in simple terms how reduce function with its arguments <code>reduceAdd</code>, <code>reduceSum</code>, <code>reduceRemove</code> works in <code>crossfilter</code>? </p>
19,285,051
2
1
null
2013-05-27 06:08:52.64 UTC
33
2018-11-21 03:12:48.38 UTC
2018-11-21 03:12:48.38 UTC
null
63,810
null
2,070,920
null
1
33
javascript|crossfilter
15,097
<p>Remember that map reduce reduces a dataset by keys of a particular dimension. For example lets use a crossfilter instance with records:</p> <pre><code>[ { name: "Gates", age: 57, worth: 72000000000, gender: "m" }, { name: "Buffet", age: 59, worth: 58000000000, gender: "m" }, { name: "Winfrey", age: 83, worth: 2900000000, gender: "f" }, { name: "Bloomberg", age: 71, worth: 31000000000, gender: "m" }, { name: "Walton", age: 64, worth: 33000000000, gender: "f" }, ] </code></pre> <p>and dimensions name, age, worth, and gender. We will reduce the gender dimension using the reduce method.</p> <p>First we define the reduceAdd, reduceRemove, and reduceInitial callback methods.</p> <p><code>reduceInitial</code> returns an object with the form of the reduced object and the initial values. It takes no parameters.</p> <pre><code>function reduceInitial() { return { worth: 0, count: 0 }; } </code></pre> <p><code>reduceAdd</code> defines what happens when a record is being 'filtered into' the reduced object for a particular key. The first parameter is a transient instance of the reduced object. The second object is the current record. The method will return the augmented transient reduced object.</p> <pre><code>function reduceAdd(p, v) { p.worth = p.worth + v.worth; p.count = p.count + 1; return p; } </code></pre> <p><code>reduceRemove</code> does the opposite of <code>reduceAdd</code> (at least in this example). It takes the same parameters as <code>reduceAdd</code>. It is needed because group reduces are updated as records are filtered and sometimes records need to be removed from a previously computed group reduction.</p> <pre><code>function reduceRemove(p, v) { p.worth = p.worth - v.worth; p.count = p.count - 1; return p; } </code></pre> <p>Invoking the reduce method would look like this:</p> <pre><code>mycf.dimensions.gender.reduce(reduceAdd, reduceRemove, reduceInitial) </code></pre> <p>To take a peek at the reduced values, use the <code>all</code> method. To see the top n values use the <code>top(n)</code> method.</p> <pre><code>mycf.dimensions.gender.reduce(reduceAdd, reduceRemove, reduceInitial).all() </code></pre> <p>The returned array would (should) look like:</p> <pre><code>[ { key: "m", value: { worth: 161000000000, count: 3 } }, { key: "f", value: { worth: 35000000000, count: 2 } }, ] </code></pre> <p>The goals of reducing a dataset is to derive a new dataset by first grouping records by common keys, then reducing a dimension those groupings into a single value for each key. In this case we grouped by gender and reduced the worth dimension of that grouping by adding the values of records that shared the same key.</p> <p>The other reduceX methods are convience methods for the reduce method.</p> <p>For this example <code>reduceSum</code> would be the most appropriate replacement.</p> <pre><code>mycf.dimensions.gender.reduceSum(function(d) { return d.worth; }); </code></pre> <p>Invoking <code>all</code> on the returned grouping would (should) look like:</p> <pre><code>[ { key: "m", value: 161000000000 }, { key: "f", value: 35000000000 }, ] </code></pre> <p><code>reduceCount</code> will count records</p> <pre><code>mycf.dimensions.gender.reduceCount(); </code></pre> <p>Invoking <code>all</code> on the returned grouping would (should) look like:</p> <pre><code>[ { key: "m", value: 3 }, { key: "f", value: 2 }, ] </code></pre> <p>Hope this helps :)</p> <p>Source: <a href="https://github.com/square/crossfilter/wiki/API-Reference">https://github.com/square/crossfilter/wiki/API-Reference</a></p>
17,097,263
Automatic versioning of Android build using git describe with Gradle
<p>I have searched extensively, but likely due to the newness of Android Studio and Gradle. I haven't found any description of how to do this. I want to do basically exactly what is described in <a href="https://stackoverflow.com/questions/14895123/auto-version-numbering-your-android-app-using-git-and-eclipse-on-linux">this post</a>, but with Android Studio, Gradle and Windows rather than Eclipse and Linux.</p>
32,245,036
10
1
null
2013-06-13 21:19:13.533 UTC
34
2022-01-05 08:18:37.083 UTC
2019-06-13 14:20:44.627 UTC
null
1,083,957
null
1,452,472
null
1
43
android|git|gradle|android-build|auto-versioning
24,901
<p>A more proper and lean way to achieve the result which gained traction lately would be to use <a href="https://github.com/ajoberstar/grgit" rel="nofollow noreferrer">grgit integration</a>, which uses <a href="https://www.eclipse.org/jgit/" rel="nofollow noreferrer">JGit Java libray</a>. As it uses JGit it doesn't even require git to be installed to work (which simplifies things in build pipelines).</p> <p>Here's a basic example showing a similar (but with some additional information in gitVersionName string) solution:</p> <pre><code>plugins { id 'org.ajoberstar.grgit' version '4.1.1' } ext { gitVersionCode = grgit.tag.list().size() gitVersionName = grgit.describe(tags: true, always: true) } android { defaultConfig { versionCode gitVersionCode versionName gitVersionName } } [...] </code></pre> <p>As you can see in <a href="https://ajoberstar.org/grgit/grgit-reference.html" rel="nofollow noreferrer">Grgit API documentation</a> the <a href="https://ajoberstar.org/grgit/grgit-describe.html" rel="nofollow noreferrer">describe operation</a> provides additional information other than most recent tag reachable in history:</p> <blockquote> <p>Find the most recent tag that is reachable from HEAD. If the tag points to the commit, then only the tag is shown. Otherwise, it suffixes the tag name with the number of additional commits on top of the tagged object and the abbreviated object name of the most recent commit.</p> </blockquote> <p>Anyhow, it won't tell if the state is dirty or not. This information can be easily added by looking at the <a href="https://github.com/ajoberstar/gradle-git/issues/63" rel="nofollow noreferrer">clean status</a> of the repo, and appending a string if it's not clean.</p>
16,805,306
jQuery return ajax result into outside variable
<p>I have some problem using ajax.</p> <p>How can I assign all result from ajax into outside variable ?</p> <p>I google it up and found this code..</p> <pre><code>var return_first = (function () { var tmp = null; $.ajax({ 'async': false, 'type': "POST", 'global': false, 'dataType': 'html', 'url': "ajax.php?first", 'data': { 'request': "", 'target': arrange_url, 'method': method_target }, 'success': function (data) { tmp = data; } }); return tmp; }); </code></pre> <p>but not work for me..</p> <p>Can anybody tell what is wrong about that code ?</p>
16,805,366
7
4
null
2013-05-29 04:04:46.063 UTC
21
2021-09-23 07:57:59.947 UTC
2017-08-16 17:01:32.497 UTC
null
1,768,052
null
1,768,052
null
1
52
jquery|ajax|variables
194,601
<p>You are missing a comma after</p> <pre><code>'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' } </code></pre> <p>Also, if you want <code>return_first</code> to hold the result of your anonymous function, you need to make a function call:</p> <pre><code>var return_first = function () { var tmp = null; $.ajax({ 'async': false, 'type': "POST", 'global': false, 'dataType': 'html', 'url': "ajax.php?first", 'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' }, 'success': function (data) { tmp = data; } }); return tmp; }(); </code></pre> <p>Note <code>()</code> at the end.</p>
25,929,315
tar removing leading '/' from member names
<p>I got an error when I append > <code>/dev/null</code> to tar command, anyone know what's going on in second example?</p> <p>good:</p> <pre><code> tar -cvf $kname /var/www </code></pre> <p>bad:</p> <pre><code> tar -cvf $kname /var/www &gt; /dev/null error:tar: Removing leading `/' from member names </code></pre>
25,929,424
4
6
null
2014-09-19 08:14:46.537 UTC
4
2021-08-26 08:42:38.42 UTC
2014-09-19 08:20:12.843 UTC
null
854,132
null
854,132
null
1
27
linux|tar
75,102
<p>The "good" version is also displaying the same message you've just missed it.</p> <p>If you don't like the behaviour, search for "leading", in manual. First hit:</p> <pre><code>-P, --absolute-names don't strip leading '/'s from file names </code></pre>
25,483,410
Duplicate files during packaging of APK app-debug-unaligned.apk
<p>I got this error <code>Duplicate files during packaging of APK app-debug-unaligned.apk</code> when put 2 jar files :</p> <ul> <li><p><code>httpclient-4.3.5.jar</code></p></li> <li><p><code>httpmime-4.3.5.jar</code></p> <p>into the <code>libs</code> folder after <code>Sync with Gradle</code> and <code>Run</code>.</p></li> </ul> <p>If user 1 jar file - <code>httpmime-4.3.5.jar</code>, I will not get this error.</p> <p>Please help me how to avoid this error &amp; still can use 2 jar files in above also,</p> <p>Thanks,</p> <p>p/s : I use Android Studio version 0.8.6.</p> <p><code>Error Detail</code></p> <blockquote> <p>Error:duplicate files during packaging of APK ...\app\build\outputs\apk\app-debug-unaligned.apk Path in archive: META-INF/DEPENDENCIES Origin 1: ...\app\libs\httpclient-4.3.5.jar Origin 2: ...\app\libs\httpmime-4.3.5.jar</p> </blockquote> <p><code>build.gradle</code></p> <pre><code>android { compileSdkVersion 20 buildToolsVersion '20.0.0' defaultConfig { applicationId 'com.app' minSdkVersion 9 targetSdkVersion 20 versionCode 1 versionName '1.0' } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { } packagingOptions { exclude 'META-INF/LICENSE.txt' } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:support-v4:20.0.0' compile 'com.android.support:appcompat-v7:20.0.0' compile 'com.google.android.gms:play-services:5.2.08' compile 'com.viewpagerindicator:library:2.4.1@aar' compile 'de.hdodenhof:circleimageview:1.2.0' compile files('libs/httpmime-4.3.5.jar') } </code></pre> <p><code>UPDATE</code> I changed from <code>compile files('libs/httpmime-4.3.5.jar')</code> to use Maven Link. I got same error again after put 2 maven link together:</p> <pre><code> compile 'org.apache.httpcomponents:httpmime:4.4-alpha1' compile 'org.apache.httpcomponents:httpcore:4.4-alpha1' </code></pre> <p>This is the warning</p> <blockquote> <p>Warning:Dependency org.apache.httpcomponents:httpclient:4.4-alpha1 is ignored for debug as it may be conflicting with the internal version provided by Android. In case of problem, please repackage it with jarjar to change the class packages </p> <p>Warning:Dependency org.apache.httpcomponents:httpclient:4.4-alpha1 is ignored for release as it may be conflicting with the internal version provided by Android. In case of problem, please repackage it with jar to change the class packages</p> </blockquote> <p>Please help me fix.</p> <p><strong>SOULITION</strong> I know good answer now by addding these lines will fix <code>Duplicate files</code> error :</p> <pre><code>packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/LGPL2.1' } </code></pre>
25,483,809
5
10
null
2014-08-25 10:01:17.1 UTC
9
2017-04-16 04:02:14.307 UTC
2014-08-26 03:07:56.023 UTC
null
2,522,405
null
2,522,405
null
1
49
android|http|jar|android-studio|apache-commons-httpclient
26,623
<p>You can replace <code>compile files('libs/httpmime-4.3.5.jar')</code> with this compile <code>'org.apache.httpcomponents:httpmime:4.3.5'</code>. </p> <p>Also you are duplicating the dependencies <code>compile fileTree(include: ['*.jar'], dir: 'libs')</code> already includes <code>compile files('libs/httpmime-4.3.5.jar')</code> </p>
4,352,209
Conversion from UTF8 to ASCII
<p>I have a text read from a XML file stored in UTF8 encoding. C# reads it perfectly, I checked with the debugger, but when I try to convert it to ASCII to save it in another file I get a ? char in places where there was a conflicting character. For instance, this text: </p> <pre><code>string s = "La introducción masiva de las nuevas tecnologías de la información"; </code></pre> <p>Will be saved as </p> <pre><code>"La introducci?n masiva de las nuevas tecnolog?as de la informaci?n" </code></pre> <p>I cannot just replace them for their latin (a, e, i, o, u) vowels because some words in spanish would miss the sense. I've already tried <a href="https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-ascii-equivalent">this</a> and <a href="https://stackoverflow.com/questions/497782/how-to-convert-a-string-from-utf8-to-ascii-single-byte-in-c">this</a> questions with no sucess. So Im hoping someone can help me. The selected answer in the second one didnt even compiled...!</p> <p>In case someone wants to take a look, my code is this one:</p> <pre><code>private void WriteInput( string input ) { byte[] byteArray = Encoding.UTF8.GetBytes(input); byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray); string finalString = Encoding.ASCII.GetString(asciiArray); string inputFile = _idFile + ".in"; var batchWriter = new StreamWriter(inputFile, false, Encoding.ASCII); batchWriter.Write(finalString); batchWriter.Close(); } </code></pre>
4,352,230
2
0
null
2010-12-04 06:06:34.247 UTC
7
2010-12-04 06:32:26.897 UTC
2017-05-23 12:26:09.273 UTC
null
-1
null
420,447
null
1
15
c#|encoding|utf-8|ascii
54,801
<p>Those characters have no mapping in ASCII. Review an ASCII table, like <a href="http://en.wikipedia.org/wiki/ASCII" rel="noreferrer">Wikipedia's</a>, to verify this. You might be interested in the Windows 1252 encoding, or "extended ASCII", as it's sometimes called, which has code points for many accented characters, Spanish included.</p> <pre><code>var input = "La introducción masiva de las nuevas tecnologías de la información"; var utf8bytes = Encoding.UTF8.GetBytes(input); var win1252Bytes = Encoding.Convert( Encoding.UTF8, Encoding.GetEncoding("windows-1252"), utf8bytes); File.WriteAllBytes(@"foo.txt", win1252Bytes); </code></pre>
9,975,382
Adding space between columns of a TableLayout
<p>I have a TableLayout where I add dynamically TableRows. In each TableRow, I add a Button.</p> <p>I just would like to add some space between my columns (which are my buttons) but I can't figure out how... I've tried to change all the possible margins but it doesn't work :( So maybe I made a mistake in my code where I inflate them from XML files:</p> <pre><code>private void createButtons(final CategoryBean parentCategory) { final List&lt;CategoryBean&gt; categoryList = parentCategory.getCategoryList(); title.setText(parentCategory.getTitle()); // TODO à revoir int i = 0; TableRow tr = null; Set&lt;TableRow&gt; trList = new LinkedHashSet&lt;TableRow&gt;(); for (final CategoryBean category : categoryList) { TextView button = (TextView) inflater.inflate(R.layout.button_table_row_category, null); button.setText(category.getTitle()); if (i % 2 == 0) { tr = (TableRow) inflater.inflate(R.layout.table_row_category, null); tr.addView(button); } else { tr.addView(button); } trList.add(tr); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CategoryBean firstChild = category.getCategoryList() != null &amp;&amp; !category.getCategoryList().isEmpty() ? category .getCategoryList().get(0) : null; if (firstChild != null &amp;&amp; firstChild instanceof QuestionsBean) { Intent intent = new Intent(CategoryActivity.this, QuestionsActivity.class); intent.putExtra(MainActivity.CATEGORY, category); startActivityForResult(intent, VisiteActivity.QUESTION_LIST_RETURN_CODE); } else { Intent intent = new Intent(CategoryActivity.this, CategoryActivity.class); intent.putExtra(MainActivity.CATEGORY, category); startActivityForResult(intent, VisiteActivity.CATEGORY_RETURN_CODE); } } }); i++; } for (TableRow tableRow : trList) { categoryLaout.addView(tableRow); } } </code></pre> <p>My button_table_row_category.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/buttonTableRowCategory" style="@style/ButtonsTableRowCategory" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/validate" /&gt; </code></pre> <p>My table_row_category.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TableRow xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tableRowCategory" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="100dp" android:gravity="center" android:padding="5dp" &gt; &lt;/TableRow&gt; </code></pre> <p>Thank you for your help.</p>
9,991,691
4
4
null
2012-04-02 11:14:42.9 UTC
2
2015-02-06 12:17:39.017 UTC
2012-04-02 11:36:46.42 UTC
null
1,160,207
null
1,294,968
null
1
14
android|divider|android-tablelayout
45,570
<p>In the case of a TableLayout, Buttons themselves are the columns. That means you have to advise the Buttons to keep some space inbetween. You can do this by using layout parameters. They are much easier to set in XML, but it also works programmatically. It's important that you always use the LayoutParam class of the <strong>parent layout</strong> of the element where you apply it - in this case the parent is a TableRow:</p> <pre><code>// Within createButtons(): android.widget.TableRow.LayoutParams p = new android.widget.TableRow.LayoutParams(); p.rightMargin = DisplayHelper.dpToPixel(10, getContext()); // right-margin = 10dp button.setLayoutParams(p); // DisplayHelper: private static Float scale; public static int dpToPixel(int dp, Context context) { if (scale == null) scale = context.getResources().getDisplayMetrics().density; return (int) ((float) dp * scale); } </code></pre> <p>Most dimension attributes in Android take pixels if you set them programmatically - therefore you should use something like my dpToPixel() method. Please, don't EVER use pixel values in Android! You will regret it later on.</p> <p>If you don't want the rightmost button to have this margin, just check with an IF and don't add the LayoutParam on it.</p> <hr> <p><strong>Solution in XML:</strong></p> <p>To avoid the LayoutInflater erasing your XML-defined attributes, do this while inflating (taken from <a href="https://stackoverflow.com/questions/5288435/layout-params-of-loaded-view-are-ignored">Layout params of loaded view are ignored</a>):</p> <pre><code>View view = inflater.inflate( R.layout.item /* resource id */, MyView.this /* parent */, false /*attachToRoot*/); </code></pre> <hr> <p><strong>Alternative</strong>: Use a GridView like so: <a href="https://stackoverflow.com/questions/982386/android-simple-gridview-that-displays-text-in-the-grids">Android: Simple GridView that displays text in the grids</a></p>
10,156,623
Mongoose.js instance.save() callback not firing
<pre><code>var mongo = require('mongoose'); var connection = mongo.createConnection('mongodb://127.0.0.1/test'); connection.on("error", function(errorObject){ console.log(errorObject); console.log('ONERROR'); }); var Schema = mongo.Schema; var BookSchema = new Schema({ title : {type : String, index : {unique : true}}}); var BookModel = mongo.model('abook', BookSchema); var b = new BookModel({title : 'aaaaaa'}); b.save( function(e){ if(e){ console.log('error') }else{ console.log('no error') }}); </code></pre> <p>Neither the 'error', or 'no error' are printed to the terminal. What's more the connection.on 'error' doesn't seem to fire either. I have confirmed that MongoDb is running.</p>
10,200,999
3
0
null
2012-04-14 19:24:06.167 UTC
8
2018-11-27 17:55:05.617 UTC
null
null
null
null
146,099
null
1
25
mongodb|mongoose
19,515
<p>this is a case where you are adding the model to the global mongoose object but opening a separate connection <code>mongo.createConnection()</code> that the models are not part of. Since the model has no connection it cannot save to the db.</p> <p>this is solved either by connecting to mongo on the global mongoose connection:</p> <pre><code>var connection = mongo.createConnection('mongodb://127.0.0.1/test'); // becomes var connection = mongo.connect('mongodb://127.0.0.1/test'); </code></pre> <p>or by adding your models to your separate connection:</p> <pre><code>var BookModel = mongo.model('abook', BookSchema); // becomes var BookModel = connection.model('abook', BookSchema); </code></pre>
9,826,792
How to invoke Objective-C method from Javascript and send back data to Javascript in iOS?
<p>In iOS, how can I call an Objective-C method from Javascript in a <code>UIWebView</code> and have it send data back to the Javascript? I know that this could be done on OS X using the Webkit library, but is this possible on iOS? How does PhoneGap achieve this?</p>
9,827,105
3
0
null
2012-03-22 16:47:23.047 UTC
41
2019-11-10 22:15:50.747 UTC
2019-11-10 22:15:50.747 UTC
null
4,370,109
null
189,006
null
1
32
javascript|ios|objective-c|uiwebview
41,304
<p>There is an API to call JavaScript directly from Objective-C, <em>but you cannot call Objective-C directly from Javascript.</em></p> <h2>How to tell your Objective-C code to do something from the Javascript in your WebView</h2> <p>You have to serialize your Javascript action into a special URL and intercept that URL in the UIWebView's delegate's <code>shouldStartLoadWithRequest</code> method.</p> <pre><code>- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; </code></pre> <p>There you can deserialize that special URL and interpret it to do what you want on the Objective-C side. (You should return <code>NO</code> in the above <code>shouldStartLoadWithRequest</code> method so the UIWebView doesn't use your bogus URL to actually make an HTTP request to load a webpage.)</p> <h2>How to Run Javascript Code from Objective-C</h2> <p>Then you can run Javascript from Objective-C by calling this method on your webview.</p> <pre><code>- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script; </code></pre> <h1>Example Code</h1> <p>I recommend using a bogus URL scheme so it will be easy to tell the difference between your action URLs and legit requests. You can make this request in the Javascript along these lines:</p> <pre><code>// JavaScript to send an action to your Objective-C code var myAppName = 'myfakeappname'; var myActionType = 'myJavascriptActionType'; var myActionParameters = {}; // put extra info into a dict if you need it // (separating the actionType from parameters makes it easier to parse in ObjC.) var jsonString = (JSON.stringify(myActionParameters)); var escapedJsonParameters = escape(jsonString); var url = myAppName + '://' + myActionType + "#" + escapedJsonParameters; document.location.href = url; </code></pre> <p>Then in the <code>UIWebView.delegate</code>'s <code>shouldStartLoadWithRequest</code> method, you can inspect the URL scheme and fragment to check if it's a normal request or one of your special actions. (The fragment of a URL is what comes after the <code>#</code>.)</p> <pre><code>- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { // these need to match the values defined in your JavaScript NSString *myAppScheme = @"myfakeappname"; NSString *myActionType = @"myJavascriptActionType"; // ignore legit webview requests so they load normally if (![request.URL.scheme isEqualToString:myAppScheme]) { return YES; } // get the action from the path NSString *actionType = request.URL.host; // deserialize the request JSON NSString *jsonDictString = [request.URL.fragment stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; // look at the actionType and do whatever you want here if ([actionType isEqualToString:myActionType]) { // do something in response to your javascript action // if you used an action parameters dict, deserialize and inspect it here } // make sure to return NO so that your webview doesn't try to load your made-up URL return NO; } </code></pre> <p>(Read <a href="https://stackoverflow.com/a/8606842/168594">this answer</a> if you need help deserializing your json string into an NSDictionary.)</p>
28,323,023
Coordinate (x,y) list to be sort with a spiral algorithm
<p>I have a list of coordinate to be sorted with a spiral algorithm. My need is to start on the middle of the area and "touch" any coordinate.</p> <p>To simplify this is the representation of the (unsorted) list of coordinates (x,y marked with a "dot" on following image).</p> <p>CSV list of coordinates is available <a href="https://drive.google.com/file/d/0B4eeMjRbvj62am9rR1dRSWRDdmM/view?usp=sharing" rel="nofollow noreferrer">here</a>.<br/> X increase from left to right<br/> Y increases from TOP to BOTTOM<br/></p> <p><img src="https://i.stack.imgur.com/gHbk4.png" alt="unsorted list of coordinates"> Every coordinate is not adjacent to the following one but are instead distanciated by 1 or 2 dice (or more in certain case).</p> <p>Starting from the center of the area, I need to touch any coordinate with a spiral movement:</p> <p><img src="https://i.stack.imgur.com/v9SUj.gif" alt="spiral approach"></p> <p>to parse each coordinate I've drafted this PHP algorithm:</p> <pre><code> //$missing is an associative array having as key the coordinate "x,y" to be touched $direction = 'top'; $distance = 1; $next = '128,127'; //starting coordinate $sequence = array( $next; ) unset($missing[$next]); reset($missing); $loopcount = 0; while ($missing) { for ($loop = 1; $loop &lt;= 2; $loop++) { for ($d = 1; $d &lt;= $distance; $d++) { list($x,$y) = explode(",", $next); if ($direction == 'top') $next = ($x) . "," . ($y - 1); elseif ($direction == 'right') $next = ($x + 1) . "," . ($y); elseif ($direction == 'bottom') $next = ($x) . "," . ($y + 1); elseif ($direction == 'left') $next = ($x - 1) . "," . ($y); if ($missing[$next]) { unset($missing[$next]); //missing is reduced every time that I pass over a coordinate to be touched $sequence[] = $next; } } if ($direction == 'top') $direction = 'right'; elseif ($direction == 'right') $direction = 'bottom'; elseif ($direction == 'bottom') $direction = 'left'; elseif ($direction == 'left') $direction = 'top'; } $distance++; } </code></pre> <p>but as coordinate are not equidistant from each other, I obtain this output:</p> <p><img src="https://i.stack.imgur.com/F3aRS.png" alt="sorted list of coordinates"></p> <p>As is clearly visible, the movement in the middle is correct whereas and accordingly with the coordinate position, at a certain instant the jump between each coordinate are not anymore coherent.</p> <p>How can I modify my code to obtain an approach like this one, instead?</p> <p><img src="https://i.stack.imgur.com/ppzDS.png" alt="expected sorted list of coordinates"></p> <p><strong>To simplify/reduce the problem</strong>: Imagine that dots on shown above image are cities that the salesman have to visit cirurarly. Starting from the "city" in the middle of the area, the next cities to be visited are the ones located near the starting point and located on North, East, Soutch and West of the starting point. The salesman cannot visit any further city unless all the adjacent cities in the round of the starting point hadn't been visited. All the cities must be visited only one time.</p>
28,859,674
2
8
null
2015-02-04 13:48:02.577 UTC
8
2015-03-06 15:51:37.953 UTC
2015-03-04 15:01:05.287 UTC
null
2,362,364
null
2,362,364
null
1
15
php|sorting|coordinates|spiral
2,193
<p><strong>Algorithm design</strong></p> <p>First, free your mind and don't think of a spiral! :-) Then, let's formulate the algorithms constraints (let's use the salesman's perspective):</p> <p>I am currently in a city and am looking where to go next. I'll have to find a city:</p> <ul> <li>where I have not been before</li> <li>that is as close to the center as possible (to keep spiraling)</li> <li>that is as close as possible to my current city</li> </ul> <p>Now, given these three constraints you can create a deterministic algorithm that creates a spiral (well at least for the given example it should, you probably can create cases that require more effort).</p> <p><strong>Implementation</strong></p> <p>First, because we can walk in any direction, lets generally use the <a href="http://en.wikipedia.org/wiki/Euclidean_distance" rel="noreferrer">Euclidean distance</a> to compute distances.</p> <p>Then to find the next city to visit:</p> <pre><code>$nextCost = INF; $nextCity = null; foreach ($notVisited as $otherCity) { $cost = distance($current_city, $other_city) + distance($other_city, $centerCity); if ($cost &lt; $nextCost) { $nextCost = $cost; $nextCity = $otherCity; } } // goto: $nextCity </code></pre> <p>Just repeat this until there are no more cities to visit.</p> <p>To understand how it works, consider the following picture:</p> <p><img src="https://i.stack.imgur.com/WV9xs.png" alt="enter image description here"></p> <p>I am currently at the yellow circle and we'll assume the spiral up to this point is correct. Now compare the length of the yellow, pink and blue lines. The length of those lines is basically what we compute using the distance functions. You will find that in every case, the next correct city has the smallest distance (well, at least as long as we have as many points everywhere, you probably can easily come up with a counter-example).</p> <p>This should get you started to implement a solution for your problem.</p> <p><strong>(Correctness) Optimization</strong></p> <p>With the current design, you will have to compare the current city to all remaining cities in each iteration. However, some cities are not of interest and even in the wrong direction. You can further optimize the correctness of the algorithm by excluding some cities from the search space before entering the <code>foreach</code> loop shown above. Consider this picture:</p> <p><img src="https://i.stack.imgur.com/rME2K.png" alt="enter image description here"></p> <p>You will not want to go to those cities now (to keep spiraling, you shouldn't go backwards), so don't even take their distance into account. Albeit this is a little more complicated to figure out, if your data points are not as evenly distributed as in your provided example, this optimization should provide you a healthy spiral for more disturbed datasets.</p> <p><strong>Update: Correctness</strong></p> <p>Today it suddenly struck me and I rethought the proposed solution. I noticed a case where relying on the two euclidean distances might yield unwanted behavior:</p> <p><img src="https://i.stack.imgur.com/viRIK.png" alt="enter image description here"></p> <p>It is easily possible to construct a case where the blue line is definitely shorter than the yellow one and thus gets preferred. However, that would break the spiral movement. To eliminate such cases we can make use of the travel direction. Consider the following image (I apologize for the hand-drawn angles):</p> <p><img src="https://i.stack.imgur.com/rxSDi.png" alt="enter image description here"></p> <p>The key idea is to compute the angle between the previous travel direction and the new travel direction. We are currently at the yellow dot and need to decide where to go next. Knowing the previous dot, we can obtain a vector representing the previous direction of the movement (e.g. the pink line).</p> <p>Next, we compute the vector to each city we consider and compute the angle to the previous movement vector. If that vector is &lt;= 180 deg (case 1 in the image), then the direction is ok, otherwise not (case 2 in the image).</p> <pre><code>// initially, you will need to set $prevCity manually $prevCity = null; $nextCost = INF; $nextCity = null; foreach ($notVisited as $otherCity) { // ensure correct travel direction $angle = angle(vectorBetween($prevCity, $currentCity), vectorBetween($currentCity, $otherCity)); if ($angle &gt; 180) { continue; } // find closest city $cost = distance($current_city, $other_city) + distance($other_city, $centerCity); if ($cost &lt; $nextCost) { $nextCost = $cost; $nextCity = $otherCity; } } $prevCity = $currentCity; // goto: $nextCity </code></pre> <p>Pay attention to compute the angle and vectors correctly. If you need help on that, I can elaborate further or simply ask a new question.</p>
9,810,624
how to get coordinates of the center of the viewed area in google maps using Google Maps JavaScript API v3
<p>How to get coordinates using javascript Google Maps JavaScript API v3 of the center of the currently viewed area on google maps? Thanks</p>
9,810,671
2
0
null
2012-03-21 18:26:16.813 UTC
14
2018-04-10 21:55:55.423 UTC
null
null
null
null
266,250
null
1
68
javascript|google-maps-api-3
60,635
<p>You can call:</p> <pre><code>map.getCenter(); </code></pre> <p>to return a LatLng object.</p>
10,141,841
Difference between std::set and std::priority_queue
<p>Since both <code>std::priority_queue</code> and <code>std::set</code> (and <code>std::multiset</code>) are data containers that store elements and allow you to access them in an ordered fashion, and have same insertion complexity <code>O(log n)</code>, what are the advantages of using one over the other (or, what kind of situations call for the one or the other?)?</p> <p>While I know that the underlying structures are different, I am not as much interested in the difference in their implementation as I am in the comparison their <strong>performance</strong> and <strong>suitability</strong> for various uses.</p> <p><strong>Note:</strong> I know about the no-duplicates in a set. That's why I also mentioned <code>std::multiset</code> since it has the exactly same behavior as the <code>std::set</code> but can be used where the data stored is allowed to compare as equal elements. So please, don't comment on single/multiple keys issue.</p>
10,141,916
4
4
null
2012-04-13 13:33:22.747 UTC
32
2019-09-21 12:31:08.137 UTC
2012-04-13 13:43:17.683 UTC
null
884,412
null
884,412
null
1
92
c++|algorithm|sorting|priority-queue
32,878
<p>A priority queue <em>only</em> gives you access to <em>one</em> element in sorted order -- i.e., you can get the highest priority item, and when you remove that, you can get the next highest priority, and so on. A priority queue also allows duplicate elements, so it's more like a multiset than a set. [Edit: As @Tadeusz Kopec pointed out, building a heap is also linear on the number of items in the heap, where building a set is O(N log N) unless it's being built from a sequence that's already ordered (in which case it is also linear).]</p> <p>A set allows you full access in sorted order, so you can, for example, find two elements somewhere in the middle of the set, then traverse in order from one to the other.</p>
9,984,223
What happens to git commits created in a detached HEAD state?
<p>This is what happened:</p> <p>I have a branch A. On branch A I committed a bunch of changes. I was not happy with the code, so I checked out the previous commit in branch A. I then made a bunch more changes and committed them on branch A. Now I can not find this commit anywhere. Did I lose this code?</p>
9,984,260
7
5
null
2012-04-02 21:38:04.407 UTC
38
2022-03-28 14:00:01.363 UTC
2012-04-02 21:58:32.787 UTC
null
123,109
null
321,721
null
1
178
git
56,507
<p>The old commit is still in the reflog.</p> <pre><code>git reflog </code></pre> <p>This will show a list of commits, and the "lost" commit should be in there. You can make it into a new branch. For example, if the SHA-1 is ba5a739, then you can make a new branch named "new-branch" at the old commit with:</p> <pre><code>git branch new-branch ba5a739 </code></pre> <p>Note that "lost" commits will get deleted when the database is pruned.</p>
11,488,730
How do I 'send an image back', behind textboxes?
<p>You can view my problem:</p> <p><img src="https://i.stack.imgur.com/3INFZ.png" alt="enter image description here"></p> <p><a href="https://i.stack.imgur.com/cGoEU.png" rel="noreferrer">http://i.stack.imgur.com/cGoEU.png</a></p> <p>That image is covering my login form. How do I get it to move behind the textboxes &amp; sign in button?</p> <p>This is my code:</p> <pre><code>&lt;img src="C:\Users\George\Documents\HTML\My Local Soccer\pics\icons\gradient box.gif" style="position:absolute; top: 155px; left: 480px; width:auto; height:auto;"&gt; &lt;input type="text" class="tb7" value="Username" style="margin-left: 563px" maxlength="20" onfocus="if(this.value == 'Username') {this.value='';}" /&gt; &lt;/br&gt; &lt;input type="text" class="tb8" value="Password" style="margin-left: 563px;" maxlength="20" onfocus="if(this.value =='Password') {this.value='';}"/&gt; &lt;input type="image" height="25px" width="67px" style="vertical-align:top;" src="C:\Users\George\Documents\HTML\My Local Soccer\pics\icons\sign in.gif" /&gt; </code></pre>
11,495,591
7
2
null
2012-07-15 01:37:12.81 UTC
null
2012-07-16 22:39:43.823 UTC
2012-07-15 01:52:28.43 UTC
null
1,448,464
null
1,526,317
null
1
5
html|css|image|button|textbox
65,014
<p>Try:</p> <pre><code>&lt;div id="form_wrapper" style="background-image:url('img/yellow.png');"&gt; &lt;img src="C:\Users\George\Documents\HTML\My Local Soccer\pics\icons\gradient box.gif" style="position:absolute; top: 155px; left: 480px; width:auto; height:auto;"&gt; &lt;input type="text" class="tb7" value="Username" style="margin-left: 563px" maxlength="20" onfocus="if(this.value == 'Username') {this.value='';}" /&gt; &lt;/br&gt; &lt;input type="text" class="tb8" value="Password" style="margin-left: 563px;" maxlength="20" onfocus="if(this.value =='Password') {this.value='';}"/&gt; &lt;input type="image" height="25px" width="67px" style="vertical-align:top;" src="C:\Users\George\Documents\HTML\My Local Soccer\pics\icons\sign in.gif" /&gt; &lt;/div&gt; </code></pre> <p>Enjoy and good luck!</p>
11,685,608
Convention of faces in OpenGL cubemapping
<p>What is the convention OpenGL follows for cubemaps?</p> <p>I followed this convention (found on a website) and used the correspondent GLenum to specify the 6 faces <code>GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT</code> but I always get wrong Y, so I have to invert Positive Y with Negative Y face. Why?</p> <pre><code> ________ | | | pos y | | | _______|________|_________________ | | | | | | neg x | pos z | pos x | neg z | | | | | | |_______|________|________|________| | | | | | neg y | |________| </code></pre>
11,690,553
2
0
null
2012-07-27 10:04:00.563 UTC
12
2012-07-27 19:20:23.207 UTC
null
null
null
null
914,693
null
1
20
opengl|3d|geometry|glsl
6,429
<blockquote> <p>but I always get wrong Y, so I have to invert Positive Y with Negative Y face. Why?</p> </blockquote> <p>Ah, yes, this is one of the most odd things about Cube Maps. Rest assured, you're not the only one to fall for it. You see:</p> <p>Cube Maps have been specified to follow the RenderMan specification (for whatever reason), and RenderMan assumes the images' origin being in the upper left, contrary to the usual OpenGL behaviour of having the image origin in the lower left. That's why things get swapped in the Y direction. It totally breaks with the usual OpenGL semantics and doesn't make sense at all. But now we're stuck with it.</p> <p><em>Take note that upper left, vs. lower left are defined in the context of identity transformation from model space to NDC space</em></p>
11,939,653
Google AdWords: remove iframe added by tracking conversion code
<p>I want to add Google AdWords to my site but the script I'm supposed to add creates an iframe in the dom. This iframe is visible and moves down 13px (its height) all my page.</p> <p>Is there any way to avoid this? If not, can I hide it without affecting Google AdWords functionality? (It is an empty iframe).</p>
12,112,832
5
2
null
2012-08-13 17:56:34.94 UTC
8
2017-09-08 16:18:16.163 UTC
null
null
null
null
310,276
null
1
55
google-ads-api
30,199
<p>There's an easy fix that doesn't affect the functionality of the code snippet. I've done this with no adverse effects. Just place the script within a hidden div like below and it should do the trick:</p> <pre><code>&lt;div style="display:none"&gt; &lt;script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"&gt; &lt;/script&gt; &lt;/div&gt; </code></pre>
19,856,630
Are private methods really safe?
<p>In Java the <code>private</code> access modifier consider as safe since it is not visible outside of the class. Then outside world doesn't know about that method either. </p> <p>But I thought Java reflection can use to break this rule. Consider following case:</p> <pre class="lang-java prettyprint-override"><code>public class ProtectedPrivacy{ private String getInfo(){ return "confidential"; } } </code></pre> <p>Now from another class I am going to get Info:</p> <pre class="lang-java prettyprint-override"><code>public class BreakPrivacy{ public static void main(String[] args) throws Exception { ProtectedPrivacy protectedPrivacy = new ProtectedPrivacy(); Method method = protectedPrivacy.getClass().getDeclaredMethod("getInfo", null); method.setAccessible(true); Object result = method.invoke(protectedPrivacy); System.out.println(result.toString()); } } </code></pre> <p>At this moment I just thought still private method safe since to do some thing like above we must know method name. But if class which contain private method written by some one else we don't have visibility of those.</p> <p>But my point become invalid since below line of code.</p> <pre class="lang-java prettyprint-override"><code>Method method[] = new ProtectedPrivacy().getClass().getDeclaredMethods(); </code></pre> <p>Now this <code>method[]</code> contains all the things need to do above thing. My question is, is there a way to avoid this kind of things doing using Java reflection?</p> <p>I am quote some point from <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html" rel="nofollow">Java Documentation</a> to clarify my question.</p> <blockquote> <p>Tips on Choosing an Access Level: </p> <p>If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.</p> </blockquote>
19,856,710
7
8
null
2013-11-08 10:22:27.103 UTC
15
2016-03-15 21:34:09.263 UTC
2016-03-15 21:34:09.263 UTC
null
573,032
null
1,869,846
null
1
92
java|reflection|private|access-modifiers
5,996
<p>It depends on what you mean by "safe". If you're running with a security manager that allows this sort of thing, then yes, you can do all kinds of nasty things with reflection. But then in that kind of environment the library can probably just be modified to make the method public anyway.</p> <p>Access control is effectively "advisory" in an environment like that - you're effectively trusting the code to play nicely. If you <em>don't</em> trust the code you're running, you should use a more restrictive security manager.</p>
3,689,868
Why is EhCacheProvider deprecated?
<p>I am configuring my hibernate project to use a 2nd-level cache provider, so that I can take advantage of query caching.</p> <p>I added a dependency to ehcache:</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;net.sf.ehcache&lt;/groupId&gt; &lt;artifactId&gt;ehcache-core&lt;/artifactId&gt; &lt;version&gt;2.2.0&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>I think that the provider class I want to use is:</p> <pre><code>net.sf.ehcache.hibernateEhCacheProvider </code></pre> <p>When I look at the referenced libraries in eclipse, I see the <code>@Deprecated</code> annotation on <code>EhCacheProvider</code>, and also on <code>SingletonEhCacheProvider</code>. What gives? Is there an up-to-date replacement provider that I can use?</p> <p>I am using hibernate version 3.4.0.GA, in case it matters.</p>
3,690,212
4
0
null
2010-09-11 05:04:52.213 UTC
15
2019-02-19 21:02:12.04 UTC
2010-09-11 10:44:09.113 UTC
null
203,907
null
166,850
null
1
20
hibernate|caching|ehcache|terracotta
27,688
<blockquote> <p>What gives? Is there an up-to-date replacement provider that I can use?</p> </blockquote> <p>They have been deprecated in favor of the classes implementing the new Hibernate 3.3/3.5 SPI with its <code>CacheRegionFactory</code>. These implementations are respectively:</p> <ul> <li><code>net.sf.ehcache.hibernate.EhCacheRegionFactory</code></li> <li><code>net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</code></li> </ul> <p>Benefits of the new SPI include:</p> <blockquote> <ul> <li>The SPI removed synchronization in the Hibernate cache plumbing. It is left up to the caching implementation on how to control concurrent access. Ehcache, starting with 1.6, removed syncrhonization in favour of a CAS approach. The results, for heavy workloads are impressive.</li> <li>The new SPI provides finer grained control over cache region storage and cache strategies. Ehcache 2.0 takes advantage of this to reduce memory use. It provides read only, nonstrict read write and read write strategies, all cluster safe.</li> <li>Ehcache 2.0 is readily distributable with Terracotta Server Array. This gives you cluster safe operation (coherency), HA and scale beyond the limits of an in-process cache, which is how most Hibernate users use Ehcache today. There is the existing ehcache.jar and ehcache-terracotta.jar which provides the client library. (...)</li> </ul> </blockquote> <p>You are thus encouraged to use the new implementations. Configuration is done via the following property:</p> <pre><code>&lt;property name="hibernate.cache.region.factory_class"&gt; net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory &lt;/property&gt; </code></pre> <p>That replaces the <code>hibernate.cache.provider_class</code> property.</p> <h3>References</h3> <ul> <li>Hibernate Blog <ul> <li><a href="http://relation.to/Bloggers/Ehcache20SupportsNewHibernate33CachingProvider" rel="noreferrer">Ehcache 2.0 supports new Hibernate 3.3 caching provider</a></li> </ul></li> <li>EhCache documentation <ul> <li><a href="http://ehcache.org/documentation/hibernate-upgrade.html" rel="noreferrer">Upgrading From Ehcache versions prior to 2.0</a> </li> <li><a href="http://ehcache.org/documentation/hibernate.html" rel="noreferrer">Hibernate Second Level Cache</a></li> </ul></li> </ul>
3,485,455
using group() breaks getSelectCountSql in magento
<p>When I'm using </p> <pre><code>$collection-&gt;getSelect()-&gt;group('entity_id') </code></pre> <p>or </p> <pre><code>$collection-&gt;groupByAttribute('entity_id') </code></pre> <p>It breaks getSelectCountSql and I'm getting 1 record and 1 page. Magento does </p> <pre><code>$countSelect-&gt;columns('COUNT(DISTINCT e.entity_id)'); </code></pre> <p>Is there a way to fix it?</p> <p>I run into it,While overriding _prepareCollection of Mage_Adminhtml_Block_Catalog_Product_Grid</p> <p>Thanks</p>
4,219,386
5
2
null
2010-08-14 22:54:33.033 UTC
11
2017-01-18 09:01:58.973 UTC
2011-11-30 07:18:33.903 UTC
null
430,112
null
189,815
null
1
8
magento
10,566
<p>I updated the <strong>lib/Varien/Data/Collection/Db.php</strong> file to allow this as I had to have it work. You'll have to keep track of this for upgrades but it works. </p> <pre><code>public function getSelectCountSql() { $this-&gt;_renderFilters(); $countSelect = clone $this-&gt;getSelect(); $countSelect-&gt;reset(Zend_Db_Select::ORDER); $countSelect-&gt;reset(Zend_Db_Select::LIMIT_COUNT); $countSelect-&gt;reset(Zend_Db_Select::LIMIT_OFFSET); $countSelect-&gt;reset(Zend_Db_Select::COLUMNS); // Count doesn't work with group by columns keep the group by if(count($this-&gt;getSelect()-&gt;getPart(Zend_Db_Select::GROUP)) &gt; 0) { $countSelect-&gt;reset(Zend_Db_Select::GROUP); $countSelect-&gt;distinct(true); $group = $this-&gt;getSelect()-&gt;getPart(Zend_Db_Select::GROUP); $countSelect-&gt;columns("COUNT(DISTINCT ".implode(", ", $group).")"); } else { $countSelect-&gt;columns('COUNT(*)'); } return $countSelect; } </code></pre>
3,453,177
Convert Python datetime to rfc 2822
<p>I want to convert a Python datetime to an RFC 2822 datetime. I've tried these methods to no avail:</p> <pre><code>&gt;&gt;&gt; from email.Utils import formatdate &gt;&gt;&gt; import datetime &gt;&gt;&gt; formatdate(datetime.datetime.now()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/email /utils.py", line 159, in formatdate now = time.gmtime(timeval) TypeError: a float is required </code></pre>
3,453,277
5
0
null
2010-08-10 20:33:24.817 UTC
4
2021-11-15 15:51:03.727 UTC
2017-03-25 17:27:29.377 UTC
null
1,204,332
null
26,235
null
1
35
python|datetime|rfc2822
21,150
<p>Here's some working code, broken down into simple pieces just for clarity:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; import time &gt;&gt;&gt; from email import utils &gt;&gt;&gt; nowdt = datetime.datetime.now() &gt;&gt;&gt; nowtuple = nowdt.timetuple() &gt;&gt;&gt; nowtimestamp = time.mktime(nowtuple) &gt;&gt;&gt; utils.formatdate(nowtimestamp) 'Tue, 10 Aug 2010 20:43:53 -0000' </code></pre> <p>Explanation: <code>email.utils.formatdate</code> wants a timestamp -- i.e., a float with seconds (and fraction thereof) since the epoch. A <code>datetime</code> instance doesn't give you a timestamp directly -- but, it <em>can</em> give you a time-tuple with the <code>timetuple</code> method, and <code>time.mktime</code> of course can then make a timestamp from such a tuple.</p> <p>EDIT: In Python 3.3 and newer you can do the same in less steps:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; from email import utils &gt;&gt;&gt; nowdt = datetime.datetime.now() &gt;&gt;&gt; utils.format_datetime(nowdt) 'Tue, 10 Feb 2020 10:06:53 -0000' </code></pre> <p>See <code>format_datetime</code> <a href="https://docs.python.org/3/library/email.utils.html#email.utils.format_datetime" rel="nofollow noreferrer">docs</a> for details on usage.</p>
3,498,539
How to search a folder and all of its subfolders for files of a certain type
<p>I am trying to search for all files of a given type in a given folder and copy them to a new folder.</p> <p>I need to specify a root folder and search through that folder and all of its subfolders for any files that match the given type.</p> <p>How do I search the root folder's subfolders and their subfolders? It seems like a recursive method would work, but I cannot implement one correctly.</p>
3,498,573
5
0
null
2010-08-17 00:48:04.257 UTC
18
2021-02-26 23:18:24.22 UTC
2019-12-06 19:40:18.007 UTC
null
128,421
null
427,494
null
1
76
ruby|file-io|recursion
57,883
<p>You want the <a href="https://ruby-doc.org/stdlib-2.6.3/libdoc/find/rdoc/Find.html" rel="nofollow noreferrer">Find</a> module. <code>Find.find</code> takes a string containing a path, and will pass the parent path along with the path of each file and sub-directory to an accompanying block. Some example code:</p> <pre><code>require 'find' pdf_file_paths = [] Find.find('path/to/search') do |path| pdf_file_paths &lt;&lt; path if path =~ /.*\.pdf$/ end </code></pre> <p>That will recursively search a path, and store all file names ending in .pdf in an array.</p>
3,664,077
Why can't enum constructors be protected or public in Java?
<p>The whole question is in the title. For example:</p> <pre><code>enum enumTest { TYPE1(4.5, "string1"), TYPE2(2.79, "string2"); double num; String st; enumTest(double num, String st) { this.num = num; this.st = st; } } </code></pre> <p>The constructor is fine with the default or <code>private</code> modifier, but gives me a compiler error if given the <code>public</code> or <code>protected</code> modifiers.</p>
3,664,096
5
1
null
2010-09-08 01:46:43.39 UTC
25
2018-07-16 01:14:55.253 UTC
null
null
null
null
243,500
null
1
82
java|enums|constructor
47,945
<p>Think of Enums as a class with a finite number of instances. There can never be any different instances beside the ones you initially declare.</p> <p>Thus, you cannot have a public or protected constructor, because that would allow more instances to be created.</p> <p><em>Note: this is probably not the official reason. But it makes the most sense for me to think of <code>enums</code> this way.</em></p>
3,249,700
Convert Degrees/Minutes/Seconds to Decimal Coordinates
<p>In one part of my code I convert from decimal coordinates to degrees/minutes/seconds and I use this:</p> <pre><code>double coord = 59.345235; int sec = (int)Math.Round(coord * 3600); int deg = sec / 3600; sec = Math.Abs(sec % 3600); int min = sec / 60; sec %= 60; </code></pre> <p>How would I convert back from degrees/minutes/seconds to decimal coordinates?</p>
3,249,890
7
6
null
2010-07-14 19:24:16.89 UTC
6
2018-04-20 20:59:45.867 UTC
2010-07-14 19:28:01.227 UTC
null
76,337
null
98,814
null
1
19
c#
49,993
<p>Try this:</p> <pre><code>public double ConvertDegreeAngleToDouble( double degrees, double minutes, double seconds ) { //Decimal degrees = // whole number of degrees, // plus minutes divided by 60, // plus seconds divided by 3600 return degrees + (minutes/60) + (seconds/3600); } </code></pre>
3,833,013
Continue PHP execution after sending HTTP response
<p>How can I have PHP 5.2 (running as apache mod_php) send a complete HTTP response to the client, and then keep executing operations for one more minute? </p> <p><strong>The long story:</strong></p> <p>I have a PHP script that has to execute a few long database requests and send e-mail, which takes 45 to 60 seconds to run. This script is called by an application that I have no control over. I need the application to report any error messages received from the PHP script (mostly invalid parameter errors). </p> <p>The application has a timeout delay shorter than 45 seconds (I do not know the exact value) and therefore registers every execution of the PHP script as an error. Therefore, I need PHP to send the complete HTTP response to the client as fast as possible (ideally, as soon as the input parameters have been validated), and then run the database and e-mail processing. </p> <p>I'm running mod_php, so <code>pcntl_fork</code> is not available. I could work my way around this by saving the data to be processed to the database and run the actual process from <code>cron</code>, but I'm looking for a shorter solution.</p>
3,833,095
13
6
null
2010-09-30 17:05:06.543 UTC
29
2019-02-12 13:35:19.823 UTC
null
null
null
null
236,047
null
1
69
php|fork
44,204
<p>Have the script that handles the initial request create an entry in a processing queue, and then immediately return. Then, create a separate process (via cron maybe) that regularly runs whatever jobs are pending in the queue.</p>
3,269,686
Short rot13 function - Python
<p>I am searching for a short and cool rot13 function in Python ;-) I've written this function:</p> <pre><code>def rot13(s): chars = "abcdefghijklmnopqrstuvwxyz" trans = chars[13:]+chars[:13] rot_char = lambda c: trans[chars.find(c)] if chars.find(c)&gt;-1 else c return ''.join( rot_char(c) for c in s ) </code></pre> <p>Can anyone make it better? E.g supporting uppercase characters.</p>
3,269,756
20
2
null
2010-07-17 00:33:29.673 UTC
25
2021-05-14 02:38:15.987 UTC
2017-12-16 20:01:04.097 UTC
null
42,223
null
393,157
null
1
77
python|string|encoding
130,285
<p><code>maketrans()</code>/<code>translate()</code> solutions…</p> <h2>Python 2.x</h2> <pre><code>import string rot13 = string.maketrans( &quot;ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz&quot;, &quot;NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm&quot;) string.translate(&quot;Hello World!&quot;, rot13) # 'Uryyb Jbeyq!' </code></pre> <h2>Python 3.x</h2> <pre><code>rot13 = str.maketrans( 'ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz', 'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm') 'Hello World!'.translate(rot13) # 'Uryyb Jbeyq!' </code></pre>
8,133,712
Execute javascript code straight before page submit
<p>There are a few similar questions to this but none quite the same.</p> <p>I want to know if there is an event that can be used to execute some JS before a page is submitting (i.e. POSTed).</p>
8,133,751
5
0
null
2011-11-15 08:56:11.523 UTC
7
2020-04-20 19:44:57.19 UTC
2011-11-15 20:31:05.77 UTC
null
18,061
null
478,513
null
1
37
javascript
56,382
<p>If you are working with the form, you can use <strong>onsubmit</strong> event.</p> <p>Using jQuery you can do that with </p> <pre><code>$('#myform').submit(function() { // your code here }); </code></pre>
8,295,131
Best practices for SQL varchar column length
<p>Every time is set up a new SQL table or add a new <code>varchar</code> column to an existing table, I am wondering one thing: what is the best value for the <code>length</code>. </p> <p>So, lets say, you have a column called <code>name</code> of type <code>varchar</code>. So, you have to choose the length. I cannot think of a name > 20 chars, but you will never know. But instead of using 20, I always round up to the next 2^n number. In this case, I would choose 32 as the length. I do that, because from an computer scientist point of view, a number 2^n looks more <code>even</code> to me than other numbers and I'm just assuming that the architecture underneath can handle those numbers slightly better than others.</p> <p>On the other hand, MSSQL server for example, sets the default length value to 50, when you choose to create a varchar column. That makes me thinking about it. Why 50? is it just a random number, or based on average column length, or what?</p> <p>It could also be - or probably is - that different SQL servers implementations (like MySQL, MSSQL, Postgres, ...) have different best column length values.</p>
8,295,254
8
0
null
2011-11-28 11:26:43.983 UTC
84
2019-07-05 11:56:22.647 UTC
2014-05-30 14:41:06.903 UTC
null
165,055
null
282,144
null
1
340
mysql|sql|sql-server|postgresql
290,697
<p>No DBMS I know of has any "optimization" that will make a <code>VARCHAR</code> with a <code>2^n</code> length perform better than one with a <code>max</code> length that is not a power of 2.</p> <p>I think early SQL Server versions actually treated a <code>VARCHAR</code> with length 255 differently than one with a higher maximum length. I don't know if this is still the case. </p> <p>For almost all DBMS, the actual storage that is required is only determined by the number of characters you put into it, not the <code>max</code> length you define. So from a storage point of view (and most probably a performance one as well), it does not make any difference whether you declare a column as <code>VARCHAR(100)</code> or <code>VARCHAR(500)</code>. </p> <p>You should see the <code>max</code> length provided for a <code>VARCHAR</code> column as a kind of constraint (or business rule) rather than a technical/physical thing.</p> <p>For PostgreSQL the best setup is to use <code>text</code> without a length restriction and a <code>CHECK CONSTRAINT</code> that limits the number of characters to whatever your business requires. </p> <p>If that requirement changes, altering the check constraint is much faster than altering the table (because the table does not need to be re-written)</p> <p>The same can be applied for Oracle and others - in Oracle it would be <code>VARCHAR(4000)</code> instead of <code>text</code> though. </p> <p>I don't know if there is a physical storage difference between <code>VARCHAR(max)</code> and e.g. <code>VARCHAR(500)</code> in SQL Server. But apparently there is a performance impact when using <code>varchar(max)</code> as compared to <code>varchar(8000)</code>. </p> <p>See <a href="http://rusanu.com/2010/03/22/performance-comparison-of-varcharmax-vs-varcharn/" rel="noreferrer">this link</a> (posted by Erwin Brandstetter as a comment)</p> <p><strong>Edit 2013-09-22</strong></p> <p>Regarding bigown's comment: </p> <p>In Postgres versions before 9.2 (which was not available when I wrote the initial answer) a change to the column definition <em>did</em> rewrite the whole table, see e.g. <a href="http://blog.endpoint.com/2012/11/postgres-alter-column-problems-and.html" rel="noreferrer">here</a>. Since 9.2 this is no longer the case and a quick test confirmed that increasing the column size for a table with 1.2 million rows indeed only took 0.5 seconds. </p> <p>For Oracle this seems to be true as well, judging by the time it takes to alter a big table's <code>varchar</code> column. But I could not find any reference for that.</p> <p>For MySQL <a href="http://dev.mysql.com/doc/refman/5.5/en/alter-table.html#idm47496385802240" rel="noreferrer">the manual says</a> "<em>In most cases, <code>ALTER TABLE</code> makes a temporary copy of the original table</em>". And my own tests confirm that: running an <code>ALTER TABLE</code> on a table with 1.2 million rows (the same as in my test with Postgres) to increase the size of a column took 1.5 minutes. In MySQL however you can <em>not</em> use the "workaround" to use a check constraint to limit the number of characters in a column.</p> <p>For SQL Server I could not find a clear statement on this but the execution time to increase the size of a <code>varchar</code> column (again the 1.2 million rows table from above) indicates that <strong>no</strong> rewrite takes place.</p> <p><strong>Edit 2017-01-24</strong></p> <p>Seems I was (at least partially) wrong about SQL Server. See <a href="https://dba.stackexchange.com/a/162117/1822">this answer from Aaron Bertrand</a> that shows that the declared length of a <code>nvarchar</code> or <code>varchar</code> columns makes a huge difference for the performance. </p>
7,852,287
Using Selenium WebDriver to retrieve the value of an HTML input
<p>In the HTML of a web application there is the following code:</p> <pre class="lang-html prettyprint-override"><code>&lt;input type=&quot;text&quot; name=&quot;prettyTime&quot; id=&quot;prettyTime&quot; class=&quot;ui-state-disabled prettyTime&quot; readonly=&quot;readonly&quot;&gt; </code></pre> <p>A string displaying the time is actually shown on the page.</p> <p>In Selenium WebDriver, I have a <code>WebElement</code> object referring to the <code>&lt;input&gt;</code> using:</p> <pre><code>WebElement timeStamp = waitForElement(By.id(&quot;prettyTime&quot;)); </code></pre> <p>I want to get the value of the <code>WebElement</code>, or, in other words, what is printed on the page. I tried all the <code>WebElement</code> getters and nothing has been retrieving the actual value that the user sees.</p>
7,907,327
10
0
null
2011-10-21 16:17:28.353 UTC
19
2022-03-29 00:23:09.053 UTC
2022-03-29 00:06:11.213 UTC
null
63,550
null
912,404
null
1
145
java|selenium|selenium-webdriver
278,830
<p>This is kind of hacky, but it works.</p> <p>I used <code>JavascriptExecutor</code> and added a <code>div</code> to the HTML, and changed the text in the <code>div</code> to <code>$('#prettyTime').val()</code></p> <p>I then used Selenium to retrieve the <code>div</code> and grab its value. After testing the correctness of the value, I removed the div that was just created.</p>
8,260,881
What is the most elegant way to check if all values in a boolean array are true?
<p>I have a boolean array in java: </p> <pre><code>boolean[] myArray = new boolean[10]; </code></pre> <p>What's the most elegant way to check if all the values are true?</p>
8,260,897
13
4
null
2011-11-24 17:41:19.633 UTC
13
2022-09-22 05:29:11.767 UTC
2013-06-01 15:09:17.007 UTC
null
597,657
null
824,903
null
1
81
java|arrays|boolean
154,646
<pre><code>public static boolean areAllTrue(boolean[] array) { for(boolean b : array) if(!b) return false; return true; } </code></pre>
4,299,315
Writing/Drawing over a PDF template document in PHP
<p>I'd like to be able to write/overlay text over an existing pdf document using PHP. What I am hoping to do is have a pdf document that can act as a template, and fill in the gaps by opening the template doc, overlaying the relevant text, and serving the result as a new document. The template document is a single page so page merging/manipulation is not necessary.</p> <p>Are there any free libraries that can do this? Anywhere I should look? Most searches I've done seem to deal with merging documents/adding pages, instead of overlaying content over an existing page. </p> <p>Thanks.</p> <p>*EDIT: Here is what I did: 1. Download FPDF 2. Download FPDI + FPDF_TPL from</p> <p><a href="http://www.setasign.de/products/pdf-php-solutions/fpdi/downloads/" rel="noreferrer">http://www.setasign.de/products/pdf-php-solutions/fpdi/downloads/</a></p> <p>Here is some sample code for any future wanderers (adapted from the samples at www.setasign.de):</p> <pre><code>&lt;?php include('fpdf.php'); include('fpdi.php'); // initiate FPDI $pdf =&amp; new FPDI(); // add a page $pdf-&gt;AddPage(); // set the sourcefile $pdf-&gt;setSourceFile('templatedoc.pdf'); // import page 1 $tplIdx = $pdf-&gt;importPage(1); // use the imported page as the template $pdf-&gt;useTemplate($tplIdx, 0, 0); // now write some text above the imported page $pdf-&gt;SetFont('Arial'); $pdf-&gt;SetTextColor(255,0,0); $pdf-&gt;SetXY(25, 25); $pdf-&gt;Write(0, "This is just a simple text"); $pdf-&gt;Output('newpdf.pdf', 'D'); ?&gt; </code></pre>
4,299,330
3
3
null
2010-11-28 21:53:07.537 UTC
17
2020-08-18 10:47:27.433 UTC
2010-11-28 22:42:21.407 UTC
null
335,423
null
335,423
null
1
53
php|pdf
51,346
<p>Have a look at the <a href="http://www.setasign.de/products/pdf-php-solutions/fpdi/" rel="noreferrer">FPDI Library</a> an add on to <a href="http://www.fpdf.org/" rel="noreferrer">FPDF</a> for template annotation.</p> <p>It can also bolt-on to <a href="http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=tcpdf" rel="noreferrer">TCPDF</a>, another popular PHP PDF library. An existing PDF is used as the base of a page, instead of a blank, after that the procedures are the same as regular PDF creation.</p>
4,494,664
Binary coded decimal (BCD) to Hexadecimal conversion
<p>can someone explain to me how to convert <a href="http://en.wikipedia.org/wiki/Binary-coded_decimal" rel="noreferrer">BCD</a> to Hexadecimal? For example how can i convert 98(BCD) to Hexadecimal. Thanks.</p>
4,494,778
5
0
null
2010-12-20 22:34:58.27 UTC
1
2017-11-15 15:55:10.683 UTC
2010-12-20 22:39:44.62 UTC
null
1,588
null
700,801
null
1
9
hex|bcd
70,785
<p>I don't quite understand your question, but I'm guessing that e.g. someone gives you a number 98 encoded in BCD, which would be:</p> <p><strong>1001 1000</strong></p> <p>and you are supposed to get:</p> <p><strong>62H</strong></p> <p>What I would propose:</p> <p>1) convert BCD-encoded value to decimal value (D)</p> <p>2) convert D to hexadecimal value.</p> <p>Depending on which programming language you choose, this task will be easier or harder.</p> <p>EDIT: In Java it could be:</p> <pre><code> byte bcd = (byte)0x98; // BCD value: 1001 1000 int decimal = (bcd &amp; 0xF) + (((int)bcd &amp; 0xF0) &gt;&gt; 4)*10; System.out.println( Integer.toHexString(decimal) ); </code></pre>
4,813,995
Set Alpha/Opacity of Layout
<p>Is it possible to set and get the Alpha/Opacity of a Layout and all it's child views? I'm not talking about the background. Say a collection of Video Controls like Play, Pause and Progressbar in a Relative Layout.</p> <p>I can use animation to fade in and out but wanted to know if there was a direct method I could use.</p>
4,814,651
5
0
null
2011-01-27 08:06:35.353 UTC
10
2016-02-08 12:43:14.723 UTC
null
null
null
null
553,462
null
1
20
java|android|user-interface
18,256
<p>You can set the alpha on the layout and it's children (or any other view for that matter) using AlphaAnimation with 0 duration and setFillAfter option.</p> <p>Example:</p> <pre><code>AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F); alpha.setDuration(0); // Make animation instant alpha.setFillAfter(true); // Tell it to persist after the animation ends // And then on your layout yourLayout.startAnimation(alpha); </code></pre> <p>You can use one animation for multiple components to save memory. And do reset() to use again, or clearAnimation() to drop alpha.</p> <p>Though it looks crude and hacked it's actually a good way to set alpha on set ov views that doesn't take much memory or processor time.</p> <p>Not sure about getting current alpha value though.</p>
4,633,681
Git: Ignoring Version-Controlled Files
<p>The .gitignore file is very useful in ignoring some of the files that we don't want to control. Unfortunately, it cannot be used when the file is already under version control. For example, my .gitignore (which is already added to git) file might be different than what my coworker wants it to be (e.g. I want to ignore Vim files). Whenever I make changes to this file, git shows it as a modified file. So my questions:</p> <ol> <li>Is there any way to ignore changes for a certain file, which is already controlled by Git?!</li> <li>Is there any way to commit these changes, but keep it for myself only? Obviously, I don't want to use a branch, because I am working on a certain branch.</li> </ol>
4,633,860
6
2
null
2011-01-08 11:41:19.26 UTC
23
2021-09-12 03:16:03.627 UTC
2015-04-22 10:57:53.747 UTC
null
411,177
null
196,697
null
1
58
git|gitignore
17,701
<p>If you want to exclude files that are specific to your process (such as Vim temporary files), edit the (local) file <code>.git/info/exclude</code> and add your exclusion patterns there. This file is designed for developer-specific exclusions rather than <code>.gitignore</code>, which is designed for project-wide exclusions.</p> <p>The short summary is, everybody should agree on what is added to <code>.gitignore</code>. For files where you don't agree, use <code>.git/info/exclude</code>.</p>
4,596,467
Order Of Execution of the SQL query
<p>I am confused with the order of execution of this query, please explain me this. I am confused with when the join is applied, function is called, a new column is added with the Case and when the serial number is added. Please explain the order of execution of all this.</p> <pre><code>select Row_number() OVER(ORDER BY (SELECT 1)) AS 'Serial Number', EP.FirstName,Ep.LastName,[dbo].[GetBookingRoleName](ES.UserId,EP.BookingRole) as RoleName, (select top 1 convert(varchar(10),eventDate,103)from [3rdi_EventDates] where EventId=13) as EventDate, (CASE [dbo].[GetBookingRoleName](ES.UserId,EP.BookingRole) WHEN '90 Day Client' THEN 'DC' WHEN 'Association Client' THEN 'DC' WHEN 'Autism Whisperer' THEN 'DC' WHEN 'CampII' THEN 'AD' WHEN 'Captain' THEN 'AD' WHEN 'Chiropractic Assistant' THEN 'AD' WHEN 'Coaches' THEN 'AD' END) as Category from [3rdi_EventParticipants] as EP inner join [3rdi_EventSignup] as ES on EP.SignUpId = ES.SignUpId where EP.EventId = 13 and userid in ( select distinct userid from userroles --where roleid not in(6,7,61,64) and roleid not in(1,2)) where roleid not in(19, 20, 21, 22) and roleid not in(1,2)) </code></pre> <p>This is the function which is called from the above query.</p> <pre><code>CREATE function [dbo].[GetBookingRoleName] ( @UserId as integer, @BookingId as integer ) RETURNS varchar(20) as begin declare @RoleName varchar(20) if @BookingId = -1 Select Top 1 @RoleName=R.RoleName From UserRoles UR inner join Roles R on UR.RoleId=R.RoleId Where UR.UserId=@UserId and R.RoleId not in(1,2) else Select @RoleName= RoleName From Roles where RoleId = @BookingId return @RoleName end </code></pre>
4,596,739
7
2
null
2011-01-04 17:20:32.327 UTC
53
2022-08-03 21:03:45.897 UTC
2016-01-19 13:48:12.99 UTC
null
4,196,578
null
357,261
null
1
43
sql-server
99,269
<p>SQL is a declarative language. The result of a query must be what you would get if you evaluated as follows (from Microsoft):</p> <blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/ms189499.aspx" rel="nofollow noreferrer">Logical Processing Order of the SELECT statement</a></p> <p>The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.</p> <ol> <li>FROM</li> <li>ON</li> <li>JOIN</li> <li>WHERE</li> <li>GROUP BY</li> <li>WITH CUBE or WITH ROLLUP</li> <li>HAVING</li> <li>SELECT</li> <li>DISTINCT</li> <li>ORDER BY</li> <li>TOP</li> </ol> </blockquote> <p>The optimizer is free to choose any order it feels appropriate to produce the best execution time. Given any SQL query, is basically impossible to anybody to pretend it knows the execution order. If you add detailed information about the schema involved (exact tables and indexes definition) and the estimated cardinalities (size of data and selectivity of keys) then one can take a <em>guess</em> at the probable execution order.</p> <p>Ultimately, the only correct 'order' is the one described ion the actual execution plan. See <a href="http://msdn.microsoft.com/en-us/library/ms190233.aspx" rel="nofollow noreferrer">Displaying Execution Plans by Using SQL Server Profiler Event Classes</a> and <a href="http://msdn.microsoft.com/en-us/library/ms178071.aspx" rel="nofollow noreferrer">Displaying Graphical Execution Plans (SQL Server Management Studio)</a>.</p> <p>A completely different thing though is how do queries, subqueries and expressions project themselves into 'validity'. For instance if you have an aliased expression in the SELECT projection list, can you use the alias in the WHERE clause? Like this:</p> <pre><code>SELECT a+b as c FROM t WHERE c=...; </code></pre> <p>Is the use of <code>c</code> alias valid in the where clause? The answer is NO. Queries form a syntax tree, and a lower branch of the tree cannot be reference something defined higher in the tree. This is not necessarily an order of 'execution', is more of a syntax parsing issue. It is equivalent to writing this code in C#:</p> <pre><code>void Select (int a, int b) { if (c = ...) then {...} int c = a+b; } </code></pre> <p>Just as in C# this code won't compile because the variable <code>c</code> is used before is defined, the SELECT above won't compile properly because the alias <code>c</code> is referenced lower in the tree than is actually defined.</p> <p>Unfortunately, unlike the well known rules of C/C# language parsing, the SQL rules of how the query tree is built are somehow esoteric. There is a brief mention of them in <a href="http://msdn.microsoft.com/en-us/library/ms190623%28v=sql.90%29.aspx" rel="nofollow noreferrer">Single SQL Statement Processing</a> but a detailed discussion of how they are created, and what order is valid and what not, I don't know of any source. I'm not saying there aren't good sources, I'm sure some of the good SQL books out there cover this topic.</p> <p>Note that the syntax tree order does not match the visual order of the SQL text. For example the ORDER BY clause is usually the last in the SQL text, but as a syntax tree it sits above everything else (it sorts the <em>output</em> of the SELECT, so it sits above the SELECTed columns so to speak) and as such is <em>is</em> valid to reference the <code>c</code> alias:</p> <pre><code>SELECT a+b as c FROM t ORDER BY c; </code></pre>
4,812,146
Truncate table in Oracle getting errors
<p>I got the problem is when I run following command in Oracle, I encounter the error.</p> <pre><code>Truncate table mytable; </code></pre> <p><strong>Errors:</strong></p> <pre><code>ORA-02266: unique/primary keys in table referenced by enabled foreign keys </code></pre> <p>I found that, this mytable has relationship with other tables. That's why Truncate command cannot proceed anymore. How to delete data from myTable with the SQL scripts using Truncate command?</p>
4,812,162
9
0
null
2011-01-27 02:35:39.073 UTC
7
2020-07-07 07:40:15.177 UTC
2011-01-27 22:13:33.403 UTC
null
135,152
null
2,555,911
null
1
34
sql|oracle|plsql
67,109
<p>You have to swap the TRUNCATE statement to DELETE statements, slower and logged but that's the way to do it when constraints are in place.</p> <pre><code>DELETE mytablename; </code></pre> <p>Either that or you can find the foreign keys that are referencing the table in question and disable them temporarily.</p> <pre><code>select 'ALTER TABLE '||TABLE_NAME||' DISABLE CONSTRAINT '||CONSTRAINT_NAME||';' from user_constraints where R_CONSTRAINT_NAME='&lt;pk-of-table&gt;'; </code></pre> <p><em>Where <code>pk-of-table</code> is the name of the primary key of the table being truncated</em><br></p> <p>Run the output of the above query. When this has been done, remember to enable them again, just change <code>DISABLE CONSTRAINT</code> into <code>ENABLE CONSTRAINT</code></p>
4,633,177
C: How to wrap a float to the interval [-pi, pi)
<p>I'm looking for some nice C code that will accomplish effectively:</p> <pre><code>while (deltaPhase &gt;= M_PI) deltaPhase -= M_TWOPI; while (deltaPhase &lt; -M_PI) deltaPhase += M_TWOPI; </code></pre> <p>What are my options?</p>
4,635,752
15
1
null
2011-01-08 08:54:54.573 UTC
28
2017-01-31 03:12:19.643 UTC
2012-05-10 19:53:02.823 UTC
null
44,390
null
435,129
null
1
45
c|math|floating-point|intervals|modulo
47,650
<p><strong>Edit Apr 19, 2013:</strong></p> <p>Modulo function updated to handle boundary cases as noted by aka.nice and arr_sea:</p> <pre><code>static const double _PI= 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348; static const double _TWO_PI= 6.2831853071795864769252867665590057683943387987502116419498891846156328125724179972560696; // Floating-point modulo // The result (the remainder) has same sign as the divisor. // Similar to matlab's mod(); Not similar to fmod() - Mod(-3,4)= 1 fmod(-3,4)= -3 template&lt;typename T&gt; T Mod(T x, T y) { static_assert(!std::numeric_limits&lt;T&gt;::is_exact , "Mod: floating-point type expected"); if (0. == y) return x; double m= x - y * floor(x/y); // handle boundary cases resulted from floating-point cut off: if (y &gt; 0) // modulo range: [0..y) { if (m&gt;=y) // Mod(-1e-16 , 360. ): m= 360. return 0; if (m&lt;0 ) { if (y+m == y) return 0 ; // just in case... else return y+m; // Mod(106.81415022205296 , _TWO_PI ): m= -1.421e-14 } } else // modulo range: (y..0] { if (m&lt;=y) // Mod(1e-16 , -360. ): m= -360. return 0; if (m&gt;0 ) { if (y+m == y) return 0 ; // just in case... else return y+m; // Mod(-106.81415022205296, -_TWO_PI): m= 1.421e-14 } } return m; } // wrap [rad] angle to [-PI..PI) inline double WrapPosNegPI(double fAng) { return Mod(fAng + _PI, _TWO_PI) - _PI; } // wrap [rad] angle to [0..TWO_PI) inline double WrapTwoPI(double fAng) { return Mod(fAng, _TWO_PI); } // wrap [deg] angle to [-180..180) inline double WrapPosNeg180(double fAng) { return Mod(fAng + 180., 360.) - 180.; } // wrap [deg] angle to [0..360) inline double Wrap360(double fAng) { return Mod(fAng ,360.); } </code></pre>
14,574,518
How does using the try statement avoid a race condition?
<p>When determining whether or not a file exists, how does using the try statement avoid a "race condition"?</p> <p>I'm asking because a highly upvoted <a href="https://stackoverflow.com/a/85237/1217270">answer</a> (update: it was deleted) seems to imply that using <code>os.path.exists()</code> creates an opportunity that would not exist otherwise. </p> <p>The example given is: </p> <pre><code>try: with open(filename): pass except IOError: print 'Oh dear.' </code></pre> <p>But I'm not understanding how that avoids a race condition compared to:</p> <pre><code>if not os.path.exists(filename): print 'Oh dear.' </code></pre> <p>How does calling <code>os.path.exists(filename)</code> allow the attacker to do something with the file that they could not already do?</p>
14,575,508
3
0
null
2013-01-29 02:05:18.167 UTC
10
2014-04-14 20:32:35.047 UTC
2017-05-23 10:31:14.63 UTC
null
-1
null
1,217,270
null
1
31
python|race-condition
14,288
<p>The race condition is, of course, between your program and some other code that operates on file (race condition always requires at least two parallel processes or threads, see <a href="http://en.wikipedia.org/wiki/Race_condition" rel="noreferrer">this</a> for details). That means using <code>open()</code> instead of <code>exists()</code> may really help only in two situations:</p> <ol> <li>You check for existence of a file that is created or deleted by some background process (however, if you run inside a web server, that often means there are many copies of your process running in parallel to process HTTP requests, so for web apps race condition is possible even if there are no other programs).</li> <li>There may be some malicious program running that is trying to crash your code by destroying the file at the moments you expect it to exist.</li> </ol> <p><code>exists()</code> just performs a single check. If file exists, it may be deleted a microsecond after <code>exists()</code> returned <code>True</code>. If file is absent, it may be created immediately.</p> <p>However, <code>open()</code> not just tests for file existence, but also opens the file (and does these two actions atomically, so nothing can happen between the check and the opening). Usually files can not be deleted while they are open by someone. That means that inside <code>with</code> you may be completely sure: file really exists now since it is open. Though it's true only inside <code>with</code>, and the file still may be deleted immediately after <code>with</code> block exits, putting code that needs file to exist inside <code>with</code> guarantees that code will not fail.</p>
14,858,075
Set the develop branch as the default for a pull request
<p>I want to make the pull request merge into develop from the feature branch by default.</p> <p>I'm advocating the use of git flow, so when a pull request is submitted for a feature, the pull request needs to get merged into develop, and not master.</p> <p>Some of the managers commented that being human, there is a possibility that the team leads could overlook that fact and merge the pull request into master by mistake, causing issues with the release later on.</p> <p>We want to mitigate the risks of merge hell so this would go a long way in achieving this goal.</p> <p>Edit: I'm using a fork of gitflow called hubflow(<a href="http://datasift.github.com/gitflow/">http://datasift.github.com/gitflow/</a>). By default, when a feature branch is created <code> git hf feature start [tik-123] </code> the feature branch is created per spec but also gets pushed up to origin. We want this for collaboration. Once the feature is complete, the dev will go to the feature branch in github and issue a pull request. The team leads will then review the pull request and merge the feature into dev if the feature is slated for release in the sprint.</p>
14,858,326
4
3
null
2013-02-13 16:22:38.293 UTC
9
2020-09-30 07:17:40.947 UTC
2013-02-16 17:10:40.2 UTC
null
1,050,482
null
860,947
null
1
38
git|github|git-flow|pull-request|hubflow
27,467
<p>Alternatively make <code>develop</code> the default branch that everyone sees when visiting the project. The downside is that anyone who clones it will get an unstable branch by default but all pull requests will go to the develop branch by default too.</p>
14,727,557
PhpStorm code completion doesn't show core classes/extensions
<p>I'm having trouble with PHPStorm. I just started new project created a couple of my own classes, in one of them I created PDO object.</p> <pre><code>$this-&gt;cnn = new PDO("sqlite:db/base.db"); </code></pre> <p>Now when I want to see what kind of methods this object has via crtl + whitespace, I get no suggestions. Then I tried to see the list of classes available to me with.</p> <pre><code>$newClass = new </code></pre> <p>And when I pressed ctrl + whitespace it only showed me the classes I created.</p> <p>So the question is, what do i need to do, to make PhpStorm see all the classes that are available (not just the ones i created).</p> <p>P.S. when i ctrl + click on PDO (which is underlined) it says that class is undefined</p> <p>P.P.S. in project settings i have selected php 5.4 language language and selected interpreter (php 5.4.7, using xampp)</p>
14,729,292
2
3
null
2013-02-06 11:08:42.117 UTC
8
2013-11-06 14:44:58.81 UTC
2013-02-06 11:12:37.5 UTC
null
1,695,458
null
940,539
null
1
46
php|ide|xampp|phpstorm
20,829
<p>I've solved the issue. File > Invalidate Caches did the trick!</p>
14,730,046
Is the shortcircuit behaviour of Python's any/all explicit?
<p>Prompted by the discussion <a href="https://stackoverflow.com/a/14721700/174728">here</a></p> <p>The <a href="http://docs.python.org/2/library/functions.html#all" rel="noreferrer">docs</a> suggest some equivalent code for the behaviour of <a href="http://docs.python.org/2/library/functions.html#all" rel="noreferrer"><code>all</code></a> and <a href="http://docs.python.org/2/library/functions.html#any" rel="noreferrer"><code>any</code></a></p> <p>Should the behaviour of the equivalent code be considered part of the definition, or can an implementation implement them in a non-shortcircuit manner?</p> <p>Here is the relevant excerpt from cpython/Lib/test/test_builtin.py</p> <pre><code>def test_all(self): self.assertEqual(all([2, 4, 6]), True) self.assertEqual(all([2, None, 6]), False) self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6]) self.assertRaises(RuntimeError, all, TestFailingIter()) self.assertRaises(TypeError, all, 10) # Non-iterable self.assertRaises(TypeError, all) # No args self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args self.assertEqual(all([]), True) # Empty iterator S = [50, 60] self.assertEqual(all(x &gt; 42 for x in S), True) S = [50, 40, 60] self.assertEqual(all(x &gt; 42 for x in S), False) def test_any(self): self.assertEqual(any([None, None, None]), False) self.assertEqual(any([None, 4, None]), True) self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6]) self.assertRaises(RuntimeError, all, TestFailingIter()) self.assertRaises(TypeError, any, 10) # Non-iterable self.assertRaises(TypeError, any) # No args self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args self.assertEqual(any([]), False) # Empty iterator S = [40, 60, 30] self.assertEqual(any(x &gt; 42 for x in S), True) S = [10, 20, 30] self.assertEqual(any(x &gt; 42 for x in S), False) </code></pre> <p>It doesn't do anything to enforce the shortcircuit behaviour</p>
14,866,380
4
4
null
2013-02-06 13:16:57.397 UTC
7
2022-08-19 22:46:13.623 UTC
2019-05-08 03:38:59.087 UTC
null
202,229
null
174,728
null
1
53
python|short-circuiting|language-specifications
9,107
<p><strong>The behaviour is guaranteed</strong>. I've contributed a <a href="http://bugs.python.org/file29131/mywork.patch" rel="noreferrer">patch</a>, which was accepted and <a href="http://bugs.python.org/issue17255" rel="noreferrer">merged</a> recently, so if you grab the latest sources you will see that the short-circuiting behaviour is now explicitly enforced. </p> <pre><code>git clone https://github.com/python/cpython.git grep Short-circuit cpython/Lib/test/test_builtin.py </code></pre>
44,522,626
Difference between NSRange and NSMakeRange
<p>Is there any difference between: </p> <pre><code>NSRange(location: 0, length: 5) </code></pre> <p>and:</p> <pre><code>NSMakeRange(0, 5) </code></pre> <p>Because <code>Swiftlint</code> throws a warning when I use <code>NSMakeRange</code>, but I don't know why.</p> <p>Thanks for the Help :-) </p>
44,522,963
2
1
null
2017-06-13 13:14:42.14 UTC
1
2022-03-23 11:59:48.067 UTC
2018-04-16 03:17:55.897 UTC
null
503,099
null
7,927,982
null
1
30
swift|nsrange|swiftlint
4,705
<p>The only difference between them is that</p> <pre><code>NSRange(location: 0, length: 5) </code></pre> <p>is an initializer for <code>NSRange</code> while </p> <pre><code>NSMakeRange(0, 5) </code></pre> <p>is a function which creates a new <code>NSRange</code> instance (by using the same initializer inside most likely) and actually is redundant in <code>Swift</code>. <code>Swift</code> has simply inherited it from <code>Objective-C</code>. I would stick to the former</p>
63,538,665
How to type `request.query` in express using TypeScript?
<p>I'm running an <code>express.js</code> application using TypeScript. Every time I try to process <code>request.query.foo</code> I get the following error:</p> <pre><code>Argument of type 'string | ParsedQs | string[] | ParsedQs[] | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. </code></pre> <p>Setup:</p> <pre><code>import { Request, Response, Router } from 'express'; const router = Router(); function getHandler(request: Request, response: Response) { const { query } = request; query.foo; // string | QueryString.ParsedQs | string[] | QueryString.ParsedQs[] | undefined } router.route('/') .get(getHandler) </code></pre> <p>Is there a proper way to type <code>request.query</code> without casting?</p>
73,089,957
6
7
null
2020-08-22 16:43:11.74 UTC
6
2022-07-23 10:29:48.02 UTC
null
null
null
null
3,215,856
null
1
32
typescript|express|url|types|request
20,527
<h2>Definition</h2> <p>The <code>Request</code> is a generic which accepts additional definitions:</p> <pre class="lang-js prettyprint-override"><code>interface Request&lt; P = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query, Locals extends Record&lt;string, any&gt; = Record&lt;string, any&gt; &gt; extends core.Request&lt;P, ResBody, ReqBody, ReqQuery, Locals&gt; {} </code></pre> <p>Source: <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express/index.d.ts#L112-L117" rel="nofollow noreferrer">https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express/index.d.ts#L112-L117</a></p> <h3>Example</h3> <pre class="lang-js prettyprint-override"><code>interface RequestParams {} interface ResponseBody {} interface RequestBody {} interface RequestQuery { foo: string; } function getHandler( request: Request&lt;RequestParams, ResponseBody, RequestBody, RequestQuery&gt;, response: Response ) { const { query } = request; query.foo; // string } </code></pre>
44,861,149
Keras: use Tensorboard with train_on_batch()
<p>For the keras functions <code>fit()</code> and <code>fit_generator()</code> there is the possibility of tensorboard visualization by passing a <code>keras.callbacks.TensorBoard</code> object to the functions. For the <code>train_on_batch()</code> function there obviously are no callback available. Are there other options in keras to create a Tensorboard in this case?</p>
44,890,471
2
1
null
2017-07-01 12:52:23.873 UTC
9
2021-05-03 13:56:46.927 UTC
null
null
null
null
4,391,129
null
1
22
keras|tensorboard
10,790
<p>I think that currently, the only option is to use TensorFlow code. In <a href="https://stackoverflow.com/a/37915182/4391129">this stack<strong>overflow</strong> answer</a> I found a way to create a TensorBoard log manually.<br /> Thus a code sample with the Keras <code>train_on_batch()</code> could look like this:</p> <pre><code># before training init writer (for tensorboard log) / model writer = tf.summary.FileWriter(...) model = ... # train model loss = model.train_on_batch(...) summary = tf.Summary(value=[tf.Summary.Value(tag=&quot;loss&quot;, simple_value=value), ]) writer.add_summary(summary) </code></pre> <p><strong>Note:</strong> For this example in TensorBoard you have to choose <em>Horizontal Axis</em> &quot;RELATIVE&quot; as no step is passed to the summary.</p>
38,961,115
"Build failed" on Database First Scaffold-DbContext
<p>I'm trying to generate classes from a database (EntityFramework's database first approach).</p> <p>For convenience, I'm more or less walking along with this tutorial: <a href="https://docs.efproject.net/en/latest/platforms/full-dotnet/existing-db.html" rel="noreferrer">https://docs.efproject.net/en/latest/platforms/full-dotnet/existing-db.html</a></p> <p>I'm at a point where I am running the equivalent of this line of code in the Visual Studio Package Manager Console:</p> <pre><code>Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Verbose </code></pre> <p>This line of code is generating the error (with -Verbose mode on):</p> <pre><code>Using startup project 'EFSandbox'. Using project 'EntityFrameworkCore' Build started... Build failed. </code></pre> <p>I see no other options that produce any meaningful output, and I see no documentation on this particular error. If it helps at all, this project does not have a project.json file, currently. Everything is in the .csproj file, which I have not manually edited.</p>
40,322,226
21
9
null
2016-08-15 18:49:34.69 UTC
12
2021-11-13 08:53:46.947 UTC
null
null
null
null
4,970,405
null
1
117
c#|entity-framework-core
137,661
<h3>Two most important tips:</h3> <p>[1] - Make sure that your project builds <strong>completely</strong> before you run a new scaffold command.</p> <p>Otherwise...</p> <ul> <li>You'll start writing a line of code.</li> <li>You'll realize a required DB column is missing from your model.</li> <li>You'll go to try to scaffold it.</li> <li>Twenty minutes later you'll realize the reason your build (and scaffold command) is failing is because you literally have a half written line of code. Oops!</li> </ul> <p>[2] - Check into source control or make a copy:</p> <ul> <li>Allows you to easily verify what changed.</li> <li>Allows rollback if needed.</li> </ul> <p>You can get some very annoying 'chicken and egg' problems if you get unlucky or make a mistake.</p> <hr /> <h3>Other problems:</h3> <p>If you have multiple DLLs make sure you aren't generating into the <strong>wrong project</strong>. A 'Build failed' message can occur for many reasons, but the dumbest would be if you don't have EFCore installed in the project you're scaffolding into.</p> <p>In the package manager console there is a <code>Default project</code> dropdown and that's probably where your new files ended up if you're missing an expected change.</p> <p>A better solution than remembering to set a dropdown is to add the <code>-Project</code> switch to your scaffolding command.</p> <p>This is the full command I use:</p> <h3>For EF Core 2</h3> <blockquote> <p>Scaffold-DbContext -Connection &quot;Server=(local);Database=DefenderRRCart;Integrated Security=True;Trusted_Connection=True;&quot; -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir RRStoreContext.Models -context RRStoreContext -Project RR.DataAccess -force</p> </blockquote> <h3>For EF Core 3</h3> <blockquote> <p>dotnet ef dbcontext scaffold &quot;Server=tcp:XXXXX.database.windows.net,1433;Initial Catalog=DATABASE_NAME;Persist Security Info=False;User ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;&quot; Microsoft.EntityFrameworkCore.SqlServer -o DB.Models --context-dir DB.Contexts --context RRDBContext --project RR.EF.csproj --force --use-database-names</p> </blockquote> <p>Note: -force will overwrite files but not remove ones that don't exist any more. If you delete tables from your DB you must delete the old entity files yourself (just sort in Explorer by date and delete the old ones).</p> <hr /> <h2>Full Scaffolding reference:</h2> <h3>EF Core 2:</h3> <p><a href="https://docs.efproject.net/en/latest/miscellaneous/cli/powershell.html#scaffold-dbcontext" rel="noreferrer">https://docs.efproject.net/en/latest/miscellaneous/cli/powershell.html#scaffold-dbcontext</a> (this</p> <h3>EF Core 3:</h3> <p><a href="https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet" rel="noreferrer">https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet</a></p>
31,579,507
iOS9 GoogleAnalytics and NSAppTransportSecurity
<p>I am running into trouble due to the new security opportunity from Apple's iOS9 to restrict ssl requests to any kind of servers.</p> <p>See reference: <a href="https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33" rel="nofollow noreferrer">https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33</a></p> <p>Actually, I want to make use of the default and not allow any kind of connection NSAllowsArbitraryLoads: false</p> <pre><code>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt; &lt;dict&gt; &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt; &lt;false/&gt; &lt;/dict&gt; </code></pre> <p>Of course some connections are intended and I retrieve data from own servers as well as from third party servers.</p> <p>Either you can now sniff the app's traffic, which is generated by third party tools, or you make use of logging all network traffic, referenced here: <a href="https://stackoverflow.com/questions/31193579/how-can-i-figure-out-which-url-is-being-blocked-by-app-transport-security?answertab=votes#tab-top">How can I figure out which URL is being blocked by App Transport Security?</a></p> <p>It is easy to track down all occurring errors in this log (not too hard to look for an error code). In this way I was easily able to see what connections were being established and maybe failed, due to load limitations (of course, good software engineers know by heart ;) )</p> <p>Any kind of third party tracker or the own network setup is running just fine, despite from Google Analytics. At first I downloaded the last Example codes and had a look at them, of course you cannot expect a library to already support most recent beta systems, nevertheless, I gave it a try. And it failed as soon as the NSAllowsArbitraryLoads is set to false/NO</p> <p>Even with limiting as few as possible for the third party I was not able to make it run:</p> <pre><code>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt; &lt;dict&gt; &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt; &lt;false/&gt; &lt;key&gt;NSExceptionDomains&lt;/key&gt; &lt;dict&gt; &lt;key&gt;ssl.google-analytics.com&lt;/key&gt; &lt;dict&gt; &lt;key&gt;NSRequiresCertificateTransparency&lt;/key&gt; &lt;true/&gt; &lt;key&gt;NSThirdPartyExceptionMinimumTLSVersion&lt;/key&gt; &lt;string&gt;TLSv1.2&lt;/string&gt; &lt;key&gt;NSThirdPartyExceptionRequiresForwardSecrecy&lt;/key&gt; &lt;false/&gt; &lt;key&gt;NSThirdPartyExceptionAllowsInsecureHTTPLoads&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;/dict&gt; </code></pre> <p>Also tried google-analytics.com and to include subdomains NSIncludesSubdomains:true. And, as the simple website call in browser of "<a href="https://google-analytics.com" rel="nofollow noreferrer">https://google-analytics.com</a>" redirects to "<a href="https://www.google.com/analytics/" rel="nofollow noreferrer">https://www.google.com/analytics/</a>" I also tried to allow google.com as additional exception domain, which also fails.</p> <p>Even had a look at the supported ssl-ciphers, I think they are no problem here:</p> <pre><code>nmap --script ssl-enum-ciphers -p 443 ssl.google-analytics.com | TLSv1.2: | ciphers: | TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA (dh 256) - C | TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (dh 256) - A | TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (dh 256) - A | TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (dh 256) - A | TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (dh 256) - A | TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (dh 256) - A | TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (dh 256) - A | TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (dh 256) - A | TLS_ECDHE_RSA_WITH_RC4_128_SHA (dh 256) - A | TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C | TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A | TLS_RSA_WITH_AES_128_CBC_SHA256 (rsa 2048) - A | TLS_RSA_WITH_AES_128_GCM_SHA256 (rsa 2048) - A | TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A | TLS_RSA_WITH_AES_256_CBC_SHA256 (rsa 2048) - A | TLS_RSA_WITH_AES_256_GCM_SHA384 (rsa 2048) - A | TLS_RSA_WITH_RC4_128_MD5 (rsa 2048) - A | TLS_RSA_WITH_RC4_128_SHA (rsa 2048) - A </code></pre> <p>So, the google analytics tracking still fails for requests like: <a href="https://ssl.google-analytics.com/collect?[....]" rel="nofollow noreferrer">https://ssl.google-analytics.com/collect?[....]</a></p> <p>Has anyone come up with a solution or maybe found some kind of mistake in my approach?</p>
31,694,233
1
0
null
2015-07-23 06:17:56.703 UTC
8
2017-06-30 13:23:39.623 UTC
2017-06-30 13:23:39.623 UTC
null
1,033,581
null
464,016
null
1
20
ios|swift|ssl|google-analytics|ios9
3,952
<p>Actually the above configuration was slightly wrong, I found a working approach.</p> <p>-- Short story start --</p> <p>Basically, the above approach was mostly correct, but I came up to check the configuration again, when I had a look at the established network connection from Mac OS 10.10 and OS 10.11</p> <pre><code>openssl s_client -connect ssl.google-analytics.com:443 -status </code></pre> <p>Mac OS 10.10 made use of TLSv1.2, while Mac OS 10.11 for whatever reason used TLSv1.0</p> <p>-- Short story end --</p> <p>So, after rethinking the attributes, I removed the Certificate transparency <code>NSRequiresCertificateTransparency</code>, as the default is also set to be false and not true. The following configuration now works for me:</p> <pre><code>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt; &lt;dict&gt; &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt; &lt;false/&gt; &lt;key&gt;NSExceptionDomains&lt;/key&gt; &lt;dict&gt; &lt;key&gt;ssl.google-analytics.com&lt;/key&gt; &lt;dict&gt; &lt;key&gt;NSThirdPartyExceptionMinimumTLSVersion&lt;/key&gt; &lt;string&gt;TLSv1.2&lt;/string&gt; &lt;key&gt;NSThirdPartyExceptionRequiresForwardSecrecy&lt;/key&gt; &lt;false/&gt; &lt;key&gt;NSThirdPartyExceptionAllowsInsecureHTTPLoads&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/dict&gt; </code></pre> <p>Additional note: although google makes use of this "experimental standard" (certificate transparency):<a href="https://en.wikipedia.org/wiki/Certificate_Transparency" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Certificate_Transparency</a> It seems to not make use of it in google analytics :-)</p>
48,857,858
How to create colour box with fixed width and height in flutter?
<p>I am trying to create a color box with fixed width and height in a flutter. How to achieve this?</p>
48,869,889
2
0
null
2018-02-18 23:47:18.23 UTC
2
2021-04-25 05:52:17.95 UTC
2021-01-20 05:42:08.597 UTC
user10563627
null
null
4,211,520
null
1
30
flutter|dart|flutter-layout|flutter-widget
73,038
<p>Wrap any widget in a <a href="https://docs.flutter.io/flutter/widgets/SizedBox-class.html" rel="noreferrer"><code>SizedBox</code></a> to force it to match a fixed size.</p> <p>As for background colors or border, use <a href="https://docs.flutter.io/flutter/widgets/DecoratedBox-class.html" rel="noreferrer"><code>DecoratedBox</code></a>.</p> <p>You can then combine both, which leads to</p> <pre><code>const SizedBox( width: 42.0, height: 42.0, child: const DecoratedBox( decoration: const BoxDecoration( color: Colors.red ), ), ), </code></pre> <p>You may as well use <a href="https://docs.flutter.io/flutter/widgets/Container-class.html" rel="noreferrer"><code>Container</code></a> which is a composition of many widgets including those two from above. Which leads to :</p> <pre><code>new Container( height: 42.0, width: 42.0, color: Colors.red, ) </code></pre> <p>I tend to prefer the first option. Because <code>Container</code> prevents the use of 'const' constructor. But both works and do the same.</p>
34,694,813
How can "[" be an operator in the PHP language specification?
<p>On the <a href="http://php.net/manual/en/language.operators.precedence.php" rel="noreferrer">http://php.net/manual/en/language.operators.precedence.php</a> webpage, the second highest precedence level contains a left-associative operator called <code>[</code>.</p> <p>I don't understand that. Is it the <code>[</code> used to access/modify array entries, as in <code>$myArray[23]</code> ? I cannot imagine any code snippet where we would need to know the "precedence" of it wrt other operators, or where the "associativity" of <code>[</code> would be useful.</p>
34,695,955
3
0
null
2016-01-09 14:42:32.437 UTC
6
2016-04-11 12:59:12.013 UTC
null
null
null
null
1,893,768
null
1
46
php|specifications
1,641
<p>This is a very valid question.</p> <h2>1. Precedence in between [...]</h2> <p>First there is never an ambiguity to what PHP should evaluate first when looking at the right side of the <code>[</code>, since the bracket requires a closing one to go with it, and so every operator in between has precedence over the opening bracket. </p> <p>Example:</p> <pre><code>$a[1+2] </code></pre> <p>The <code>+</code> has precedence, i.e. first <em>1+2</em> has to be evaluated before PHP can determine which element to retrieve from <em>$a</em>.</p> <p>But the operator precedence list is not about this.</p> <h2>2. Associativity</h2> <p>Secondly there is an order of evaluating consecutive pairs of <code>[]</code>, like here:</p> <pre><code>$b[1][2] </code></pre> <p>PHP will first evaluate <code>$b[1]</code> and then apply <code>[2]</code> to that. This is left-to-right evaluation and is what is intended with <em>left associativity</em>.</p> <p>But the question at hand is not so much about associativity, but about precedence with regards to other operators. </p> <h2>3. Precedence over operators on the left side</h2> <p>The list states that <code>clone</code> and <code>new</code> operators have precedence over <code>[</code>, and this is not easy to test.</p> <p>First of all, most of the constructs where you would combine <code>new</code> with square brackets are considered invalid syntax. For example, both of these statements:</p> <pre><code>$a = new myClass()[0]; $a = new myClass[0]; </code></pre> <p>will give a parsing error:</p> <blockquote> <p>syntax error, unexpected '['</p> </blockquote> <p>PHP requires you to add parentheses to make the syntax valid. So there is no way we can test the precedence rules like this.</p> <p>But there is another way, by using a variable containing a class name:</p> <pre><code>$a = new $test[0]; </code></pre> <p>This <em>is</em> valid syntax, but now the challenge is to make a class that creates something that acts like an array.</p> <p>This is not trivial to do, as an object property is referenced like this: <code>obj-&gt;prop</code>, not like <code>obj["prop"]</code>. One can however use the <a href="http://php.net/manual/en/class.arrayobject.php" rel="nofollow noreferrer"><em>ArrayObject</em> class</a> which can deal with square brackets. The idea is to extend this class and redefine the <a href="http://php.net/manual/en/arrayobject.offsetget.php" rel="nofollow noreferrer"><em>offsetGet</em> method</a> to make sure a freshly made object of that class has array elements to return.</p> <p>To make objects printable, I ended up using the magical method <a href="http://php.net/manual/en/language.oop5.magic.php#object.tostring" rel="nofollow noreferrer"><em>__toString</em></a>, which is executed when an object needs to be cast to a string.</p> <p>So I came up with this set-up, defining two similar classes:</p> <pre><code>class T extends ArrayObject { public function __toString() { return "I am a T object"; } public function offsetGet ($offset) { return "I am a T object's array element"; } } class TestClass extends ArrayObject { public function __toString() { return "I am a TestClass object"; } public function offsetGet ($offset) { return "I am a TestClass object's array element"; } } $test = "TestClass"; </code></pre> <p>With this set-up we can test a few things.</p> <h3>Test 1</h3> <pre><code>echo new $test; </code></pre> <p>This statement creates a new <em>TestClass</em> instance, which then needs to be converted to string, so the <em>__toString</em> method is called on that new instance, which returns:</p> <blockquote> <p>I am a TestClass object</p> </blockquote> <p>This is as expected.</p> <h3>Test 2</h3> <pre><code>echo (new $test)[0]; </code></pre> <p>Here we start with the same actions, as the parentheses force the <code>new</code> operation to be executed first. This time PHP does not convert the created object to string, but requests array element 0 from it. This request is answered by the <em>offsetGet</em> method, and so the above statement outputs:</p> <blockquote> <p>I am a TestClass object's array element</p> </blockquote> <h3>Test 3</h3> <pre><code>echo new ($test[0]); </code></pre> <p>The idea is to force the opposite order of execution. Sadly enough, PHP does not allow this syntax, so will have to break the statement into two in order to get the intended evaluation order:</p> <pre><code>$name = $test[0]; echo new $name; </code></pre> <p>So now the <code>[</code> is executed first, taking the first character of the value of <em>$test</em>, i.e. <em>"T"</em>, and then <code>new</code> is applied to that. That's why I defined also a <em>T</em> class. The <code>echo</code> calls <em>__toString</em> on that instance, which yields:</p> <blockquote> <p>I am a T object</p> </blockquote> <p>Now comes the final test to see which is the order when no parentheses are present:</p> <h3>Test 4</h3> <pre><code>echo new $test[0]; </code></pre> <p>This is valid syntax, and...</p> <h2>4. Conclusion</h2> <p>The output is:</p> <blockquote> <p>I am a T object</p> </blockquote> <p>So in fact, PHP applied the <code>[</code> before the <code>new</code> operator, despite what is stated in the <a href="http://php.net/manual/en/language.operators.precedence.php" rel="nofollow noreferrer">operator precedence table</a>! </p> <h2>5. Comparing <code>clone</code> with <code>new</code></h2> <p>The <code>clone</code> operator has similar behaviour in combination with <code>[</code>. Strangely enough, <code>clone</code> and <code>new</code> are not completely equal in terms of syntax rules. Repeating test 2 with <code>clone</code>:</p> <pre><code>echo (clone $test)[0]; </code></pre> <p>yields a parsing error:</p> <blockquote> <p>syntax error, unexpected '['</p> </blockquote> <p>But test 4 repeated with <code>clone</code> shows that <code>[</code> has precedence over it.</p> <p>@bishop informed that this reproduces the long standing documentation bug <a href="http://bugs.php.net/bug.php?id=61513" rel="nofollow noreferrer">#61513: "<code>clone</code> operator precedence is wrong"</a>.</p>
29,320,817
Lodash union of arrays of objects
<p>I'd like to use the <code>_.union</code> function to create a union of two arrays of objects. Union works with arrays of primitives only as it uses === to examine if two values are equal.</p> <p>I'd like to compare objects using a key property: objects with the same key property would be regarded equal. Is there a nice functional way to achieve that ideally using lodash?</p>
29,322,081
7
0
null
2015-03-28 18:17:28.157 UTC
3
2021-09-28 04:43:54.113 UTC
null
null
null
null
2,364,915
null
1
17
javascript|lodash
42,033
<p>A non pure lodash way to do this but using the array.concat function you are able to do this pretty simply along <code>uniq()</code>:</p> <pre><code>var objUnion = function(array1, array2, matcher) { var concated = array1.concat(array2) return _.uniq(concated, false, matcher); } </code></pre> <p>An alternative approach would be to use <a href="https://lodash.com/docs#flatten">flatten()</a> and <a href="https://lodash.com/docs#uniq">uniq()</a>:</p> <pre><code>var union = _.uniq(_.flatten([array1, array2]), matcherFn); </code></pre>
44,816,723
Get size of specific repository in Nexus 3
<p>How can I get a size of specific repository in Nexus 3? </p> <p>For example, Artifactory shows the repository "size on disk" via UI.</p> <p>Does Nexus have something similar? If not - how can I get this information by script?</p>
51,218,049
3
0
null
2017-06-29 05:04:56.14 UTC
10
2022-08-23 08:46:55.98 UTC
2017-07-03 13:35:59.27 UTC
null
637,589
null
637,589
null
1
27
nexus|nexus3
13,896
<p>You can use admin task with groovy script nx-blob-repo-space-report.groovy from <a href="https://issues.sonatype.org/browse/NEXUS-14837" rel="noreferrer">https://issues.sonatype.org/browse/NEXUS-14837</a> - for me turned out too slow</p> <p>Or you can get it from database: </p> <ol> <li><p>login with user-owner nexus installation on nexus server (e.g. nexus) </p></li> <li><p>go to application directory (e.g. /opt/nexus): </p> <p><code>$ cd /opt/nexus</code></p></li> <li><p>run java orient console: </p> <p><code>$ java -jar ./lib/support/nexus-orient-console.jar</code></p></li> <li><p>connect to local database (e.g. /opt/sonatype-work/nexus3/db/component): </p> <p><code>&gt; CONNECT PLOCAL:/opt/sonatype-work/nexus3/db/component admin admin</code></p></li> <li><p>find out repository row id in @RID column by repository_name value: </p> <p><code>&gt; select * from bucket limit 50;</code></p></li> <li><p>get sum for all assets with repo row id found in the previous step: </p> <p><code>&gt; select sum(size) from asset where bucket = #15:9;</code></p></li> </ol> <p>result should be like (apparently in bytes):<br> <code>+----+------------+ |# |sum | +----+------------+ |0 |224981921470| +----+------------+ </code></p> <p>nexus database connection steps took from <a href="https://support.sonatype.com/hc/en-us/articles/115002930827-Accessing-the-OrientDB-Console" rel="noreferrer">https://support.sonatype.com/hc/en-us/articles/115002930827-Accessing-the-OrientDB-Console</a></p> <h3>another useful queries</h3> <p>summary size by repository name (instead 5 and 6 steps): </p> <pre><code>&gt; select sum(size) from asset where bucket.repository_name = 'releases'; </code></pre> <p>top 10 repositories by size: </p> <pre><code>&gt; select bucket.repository_name as repository,sum(size) as bytes from asset group by bucket.repository_name order by bytes desc limit 10; </code></pre>
39,353,073
How I can send mouse click in powershell?
<p>How I can send mouse click on this position with this code. I want my mouse to go there and click.</p> <pre><code>[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($xposi,$yposi) </code></pre>
39,360,715
2
0
null
2016-09-06 15:47:55.36 UTC
10
2020-12-23 00:57:54.353 UTC
2020-12-23 00:57:54.353 UTC
null
1,783,163
null
6,672,266
null
1
9
powershell|events|click|mouse
66,333
<p>If you don't feel like writing your own function, the <a href="http://wasp.codeplex.com/" rel="noreferrer">Windows Automation Snapin for Powershell</a> has a Send-Click function. Alternatively you can import some functionality from the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms646260(v=vs.85).aspx" rel="noreferrer">windows API using mouse_event</a> although I would recommend <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx" rel="noreferrer">SendInput</a> as it supersedes mouse_event. Below is a fully functional sample that uses P/Invoke to get the functionality you want and send a left click to a specified screen coordinate.</p> <pre><code>$cSource = @' using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; public class Clicker { //https://msdn.microsoft.com/en-us/library/windows/desktop/ms646270(v=vs.85).aspx [StructLayout(LayoutKind.Sequential)] struct INPUT { public int type; // 0 = INPUT_MOUSE, // 1 = INPUT_KEYBOARD // 2 = INPUT_HARDWARE public MOUSEINPUT mi; } //https://msdn.microsoft.com/en-us/library/windows/desktop/ms646273(v=vs.85).aspx [StructLayout(LayoutKind.Sequential)] struct MOUSEINPUT { public int dx ; public int dy ; public int mouseData ; public int dwFlags; public int time; public IntPtr dwExtraInfo; } //This covers most use cases although complex mice may have additional buttons //There are additional constants you can use for those cases, see the msdn page const int MOUSEEVENTF_MOVED = 0x0001 ; const int MOUSEEVENTF_LEFTDOWN = 0x0002 ; const int MOUSEEVENTF_LEFTUP = 0x0004 ; const int MOUSEEVENTF_RIGHTDOWN = 0x0008 ; const int MOUSEEVENTF_RIGHTUP = 0x0010 ; const int MOUSEEVENTF_MIDDLEDOWN = 0x0020 ; const int MOUSEEVENTF_MIDDLEUP = 0x0040 ; const int MOUSEEVENTF_WHEEL = 0x0080 ; const int MOUSEEVENTF_XDOWN = 0x0100 ; const int MOUSEEVENTF_XUP = 0x0200 ; const int MOUSEEVENTF_ABSOLUTE = 0x8000 ; const int screen_length = 0x10000 ; //https://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx [System.Runtime.InteropServices.DllImport("user32.dll")] extern static uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize); public static void LeftClickAtPoint(int x, int y) { //Move the mouse INPUT[] input = new INPUT[3]; input[0].mi.dx = x*(65535/System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width); input[0].mi.dy = y*(65535/System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height); input[0].mi.dwFlags = MOUSEEVENTF_MOVED | MOUSEEVENTF_ABSOLUTE; //Left mouse button down input[1].mi.dwFlags = MOUSEEVENTF_LEFTDOWN; //Left mouse button up input[2].mi.dwFlags = MOUSEEVENTF_LEFTUP; SendInput(3, input, Marshal.SizeOf(input[0])); } } '@ Add-Type -TypeDefinition $cSource -ReferencedAssemblies System.Windows.Forms,System.Drawing #Send a click at a specified point [Clicker]::LeftClickAtPoint(600,600) </code></pre>
2,725,254
Custom UIButton + subviews = no events
<p>Basically I have a custom UIButton and this custom button contains subviews. If I add those subviews to my UIButton, then the button stops responding to event changes. I.e if I tap on it it doesn't respond to the selector. I have everything set as <code>userInteractionEnabled</code>. I also tried adding touchbegan and this is working. If I remove those subviews, the UIButton works again. </p> <p>How Do I get the tap events from the button?</p>
2,725,390
1
0
null
2010-04-27 21:24:58.717 UTC
9
2013-04-09 12:46:57.023 UTC
2013-04-09 12:46:57.023 UTC
null
644,348
null
281,300
null
1
26
objective-c|iphone|uibutton
8,462
<p>The subviews should have <code>userInteractionEnabled</code> set to <code>NO</code>. What is happening here is that the subviews are getting the touch events instead of the UIButton. If that doesn't work another option is to override <code>hitTest:withEvent:</code> in your custom UIButton so that it always returns itself and does not ask its subviews if they should handle the event. See the <a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/instm/UIView/hitTest:withEvent:" rel="noreferrer">UIView docs</a> for more details.</p>
32,174,560
Port forwarding in docker-machine?
<p>Since <code>boot2docker</code> is deprecated I've switched to <code>docker-machine</code> but I don't know how to open a port from <code>docker-machine</code>. In <code>boot2docker</code> I could do like this:</p> <pre><code>boot2docker ssh -L 27017:localhost:27017 </code></pre> <p>This would forward port 27017 from VirtualBox to localhost 27017 as long as the SSH connection is open. Note that I'm not looking for a way to open the port permanently in VirtualBox. How can I achieve this with <code>docker-machine</code>? </p>
32,175,164
6
0
null
2015-08-24 04:41:43.167 UTC
20
2017-08-27 15:20:18.927 UTC
2015-08-24 11:01:18.193 UTC
null
398,441
null
398,441
null
1
51
docker|boot2docker|docker-machine
37,180
<p>You can still access the VBoxmanage.exe command from the VirtualBox used by docker machine:</p> <pre><code>VBoxManage controlvm "boot2docker-vm" natpf1 "tcp-port27017,tcp,,27017,,27017"; </code></pre> <ul> <li>Use <code>docker-machine info</code> to get the name of your vm.</li> <li>use <code>modifyvm</code> if the vm isn't started yet.</li> </ul> <p>See a practical example in <a href="https://stackoverflow.com/a/31353343/6309">this answer</a>.</p> <hr> <p>That is the current workaround, pending the possibility to pass argument to <code>docker-machine ssh</code>: see <a href="https://github.com/docker/machine/issues/691" rel="noreferrer">issue 691</a>.</p> <p>The other workaround is to <em>not</em> forward port, and use directly the IP of the VM:</p> <pre><code> $(docker-machine ip default) </code></pre> <hr> <p>As <a href="https://stackoverflow.com/questions/32174560/port-forwarding-in-docker-machine/32175164?noredirect=1#comment78771301_32175164">commented</a> by <a href="https://stackoverflow.com/users/1481755/sdc">sdc</a>:</p> <blockquote> <p>You can confirm that port forwarding is set up correctly with </p> </blockquote> <pre><code> VBoxManage showvminfo boot2docker-vm | grep "NIC.* Rule" </code></pre>