pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
13,244,374
0
How can I get all component and widget Id of current Android window screen programmatically? <p>I use Robotium Framework for Android testing purpose and manually take component_id or index id or else part of Widgets from Hierarchy Viewer to put value at runtime for testing purpose.</p> <p>Is there any way to take component_id or index id or else part of Widgets Programmatically? So far I'm able to get package name and all activity names under that package application.</p>
17,329,894
0
Sorting Array [0] <pre><code>Array ( [0] =&gt; wilson ) Array ( [0] =&gt; umkk ) Array ( [0] =&gt; audiok ) Array ( [0] =&gt; Futurama ) </code></pre> <p>I have the above users array, i'm trying to sort it alphabetically so the result looks like this</p> <pre><code>audiok futurama umkk wilson </code></pre> <p>This is my php code from those lines:</p> <pre><code>$arr1 = explode("\n", $users); sort ($arr1); print_r($arr1); </code></pre> <p>Why isn't sort () working? It doesnt sort it at all.. what am i doing wrong? I'm new to php programming, i have looked on the php manual and have not been able to sort it after trying all these different examples posted there.</p> <p>Thanks in advanced.</p> <p>Edit:</p> <pre><code>preg_match_all('/control\?user=(.+?)&amp;data/', $linklong, $users) $users = $users[1][0];} </code></pre> <p>if i print $users all the users are displayed nicely, but when i tried to sort them it tells me is not array, so i took $users, and did explode to create the array... i'm sorry im not very programming savy –</p>
11,943,335
0
<p>You can use <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/HashMap.html" rel="nofollow"><code>HashMap&lt;K,V&gt;</code></a></p> <pre><code>Map&lt;String,int&gt; map = new HashMap&lt;String,int&gt;(); </code></pre>
6,519,919
0
<p><a href="http://php.net/manual/en/function.fsockopen.php" rel="nofollow">http://php.net/manual/en/function.fsockopen.php</a></p> <p>Will check if it is responding at all, if not don't show the iframe.</p>
20,222,136
0
<p>This is the solution I ended up using:</p> <pre><code>str = 'hi all, this is derp. thank you all to answer my query.'; temp_arr = str.split('.'); for (i = 0; i &lt; temp_arr.length; i++) { temp_arr[i]=temp_arr[i].trim() temp_arr[i] = temp_arr[i].charAt(0).toUpperCase() + temp_arr[i].substr(1).toLowerCase(); } str=temp_arr.join('. ') + '.'; return str; </code></pre>
35,771,922
0
<p>Add to your calling intent </p> <pre><code>mIntent. setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); </code></pre> <p>Add to the activity in menifest</p> <pre><code>android:launchMode="singleTop" </code></pre>
19,044,812
0
<p>Perl/Tk does not provide such functionality. So you would have to track the events yourself. Note that there are the <code>Any-KeyPress</code> and <code>Any-KeyRelease</code> events, so you don't have to create a binding for every key:</p> <pre><code>$mw-&gt;bind("&lt;Any-KeyPress&gt;" =&gt; sub { warn $_[0]-&gt;XEvent-&gt;K; # prints keysym }); </code></pre> <p>If you're on X11, then using the <code>X11::Protocol</code> module (which can be used within a Perl/Tk script) and calling the <code>QueryKeymap</code> method would give you the actually pressed keycodes. Here's a little script which demonstrates this:</p> <pre><code>use strict; use X11::Protocol; # Get the keycode-to-keysym mapping. Being lazy, I just parse # the output of xmodmap -pke. The "real" approach would be to # use X11 functions like GetKeyboardMapping() and the # X11::Keysyms module. my %keycode_to_keysym; { open my $fh, "-|", "xmodmap", "-pke" or die $!; while(&lt;$fh&gt;) { chomp; if (m{^keycode\s+(\d+)\s*=(?:\s*(\S+))?}) { if (defined $2) { $keycode_to_keysym{$1} = $2; } } else { warn "Cannot parse $_"; } } } my $x11 = X11::Protocol-&gt;new; while(1) { my $keyvec = $x11-&gt;QueryKeymap; for my $bit (0 .. 32*8-1) { if (vec $keyvec, $bit, 1) { warn "Active key: keycode $bit, keysym $keycode_to_keysym{$bit}\n"; } } sleep 1; } </code></pre>
10,492,551
0
<p>You can split strings using the answer to this <a href="http://stackoverflow.com/q/314824/111013">Stack Overflow Question</a>. </p> <p>Having this function created, you can use it like so: </p> <pre><code>Declare @postcodes varchar(128) SET @postcodes = '2130 2602' SELECT * FROM users JOIN dbo.Split(' ',@postcodes) postcodes ON users.postcode = postcodes.s </code></pre>
15,134,885
0
<p>This should be work</p> <pre><code>var regex = /^\d+(\.\d{1,2})?$/i; </code></pre>
9,685,706
0
<p>Try providing margins around your EditText Background like this,</p> <pre><code> &lt;EditText android:id="@+id/tickets_value" android:layout_width="50dip" android:layout_height="wrap_content" android:gravity="center" android:padding="5dip" /&gt; </code></pre>
7,998,299
0
Is the .value property of HTMLSelectElement reliable <p>Consider an html select box with an id of "MySelect". </p> <p>Is it safe to get the value of the selected option like this:</p> <pre><code>document.getElementById("MySelect").value; </code></pre> <p>rather than this:</p> <pre><code>var Sel = document.getElementById("MySelect"); var MyVal = Sel.option[MyVal.selectedIndex].value; </code></pre> <p>It appears to be safe but I've never seen documentation on it.</p>
24,913,209
0
<p>You can do this easily with <code>dplyr</code>. Assuming your data frame is named <code>df</code>, run:</p> <pre><code>library(dplyr) library(forecast) model_fits &lt;- group_by(df, Region) %&gt;% do(fit=auto.arima(.$Sales)) </code></pre> <p>The result is a data frame containing the model fits for each region:</p> <pre><code>&gt; head(model_fits) Source: local data frame [6 x 2] Groups: &lt;by row&gt; Region fit 1 A &lt;S3:Arima&gt; 2 B &lt;S3:Arima&gt; 3 C &lt;S3:Arima&gt; 4 D &lt;S3:Arima&gt; 5 E &lt;S3:Arima&gt; 6 F &lt;S3:Arima&gt; </code></pre> <p>You can get a list with each model fit like so:</p> <pre><code>&gt; model_fits$fit [[1]] Series: .$Sales ARIMA(0,0,0) with non-zero mean Coefficients: intercept 196.0000 s.e. 14.4486 sigma^2 estimated as 2088: log likelihood=-52.41 AIC=108.82 AICc=110.53 BIC=109.42 [[2]] Series: .$Sales ARIMA(0,0,0) with non-zero mean Coefficients: intercept 179.2000 s.e. 14.3561 sigma^2 estimated as 2061: log likelihood=-52.34 AIC=108.69 AICc=110.4 BIC=109.29 </code></pre>
12,935,540
0
Solr query with grouping not working <p>The following query works fine:</p> <pre><code>q=field_one:value_one AND -field_two:[* TO *] AND -field_three:[* TO *] </code></pre> <p>However, as soon as I put brackets in there I get no results</p> <pre><code>q=field_one:value_one AND (-field_two:[* TO *] AND -field_three:[* TO *]) </code></pre> <p>Aren't these two queries equivalent?</p> <p>Thanks all</p> <p><em>Dave</em></p> <p>NB: I'm doing this as I need to combine more 'AND's with 'OR's; rather than just because I like brackets.</p>
1,656,766
0
<p>Visual Studio has a fullscreen mode via pressing <kbd>Shift+Alt+Enter</kbd>.</p>
3,385,366
0
<p>This will be mostly client-side. You can take a look at something like <a href="http://www.webresourcesdepot.com/jquery-image-crop-plugin-jcrop/" rel="nofollow noreferrer">Jcrop</a>.</p>
13,718,734
0
<p>I guess you mean <strong>Vendor Specific Prefixes</strong>. I've found something interesting you might like: <a href="http://css3please.com/" rel="nofollow">http://css3please.com/</a>.</p> <p>Check this out for other related tools: <a href="http://css-tricks.com/tldr-on-vendor-prefix-drama/" rel="nofollow">http://css-tricks.com/tldr-on-vendor-prefix-drama/</a></p>
26,127,025
0
<p>Did you try <a href="http://stackoverflow.com/questions/16133706/push-listview-when-keyboard-appears-without-adjustpan">this</a>?</p> <p>You would need to use <code>setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL)</code> and <code>setStackFromBottom(true)</code> in your list. Hope it helps, it worked for me!</p>
34,479,246
0
<p>According to documentation <a href="https://docs.angularjs.org/api/ng/filter/orderBy" rel="nofollow">https://docs.angularjs.org/api/ng/filter/orderBy</a> you can pass expression as a string <code>'match'</code></p> <pre><code>var sortedMP = $filter('orderBy')(matchedProfiles, 'match'); </code></pre> <p>or function</p> <pre><code>var sortedMP = $filter('orderBy')(matchedProfiles, function(profile) { return profile.match; }); </code></pre>
10,350,631
0
<p>Here's a hint - use:</p> <pre><code>var t = Date.now(); </code></pre> <p>to get the current time (measured in milliseconds since 00:00:00 UTC on 01/01/1970) with millisecond <em>resolution</em>.</p> <p>Note that the result will still be limited in <em>accuracy</em> by the system hardware.</p> <p>On older browsers without <code>Date.now()</code>, use:</p> <pre><code>var t = new Date().valueOf(); </code></pre> <p>or the terser </p> <pre><code>var t = +new Date(); </code></pre> <p>The latter uses numeric coercion (the <code>+</code> prefix) to generate an automatic call to <code>.valueOf()</code>.</p>
25,623,997
0
<p>Could you try command below?</p> <pre><code>app/console doctrine:generate:entities PrintingProductesBundle:UserStamp </code></pre>
15,194,460
0
Tinyscrollbar for Mobiles <p>According to <a href="http://www.baijs.nl/tinyscrollbar/" rel="nofollow">Tinyscroll's website</a>, mobile scrolling is supposed to work. Under options you see:</p> <blockquote> <p><code>invertscroll: false</code> -- Enable mobile invert style scrolling.</p> </blockquote> <p>Has anybody actually gotten this to work? Help would be much appreciated. Thanks.</p> <p>My code is the standard HTML set up with my options configured as:</p> <pre><code>$.tiny.scrollbar = { options: { axis : 'y' // vertical or horizontal scrollbar? ( x || y ). , wheel : 40 // how many pixels must the mouswheel scroll at a time. , scroll : true // enable or disable the mousewheel. , lockscroll : true // return scrollwheel to browser if there is no more content. , size : 'auto' // set the size of the scrollbar to auto or a fixed number. , sizethumb : 'auto' // set the size of the thumb to auto or a fixed number. , invertscroll : true // enable scrolling for mobiles } }; </code></pre>
15,523,905
0
<p>If you just need to parse your json file on runtime, you can use <code>!define</code> with the <code>/file</code> option:</p> <pre><code>!define /file OPTIONS json.txt </code></pre> <p>It will define OPTIONS with the content of json.txt.</p> <p>If you want to utilize your json file in compile time to alter the generated exe, then you need some kind of precompiler, which is what you're actually doing.</p>
15,165,553
0
<p>This change in behavior in p392 is due to a <a href="https://github.com/flori/json/commit/d0a62f3ced7560daba2ad546d83f0479a5ae2cf2">security fix</a>. See the <a href="http://www.ruby-lang.org/en/news/2013/02/22/json-dos-cve-2013-0269/">p392 release announcement</a> for more details.</p> <p>Your code works with the addition of the <code>:create_additions</code> option in your call to <code>JSON.parse</code>:</p> <pre><code>require 'json' class Range def to_json(*a) { 'json_class' =&gt; self.class.name, 'data' =&gt; [ first, last, exclude_end? ] }.to_json(*a) end def self.json_create(o) new(*o['data']) end end puts JSON.parse((1..10).to_json, :create_additions =&gt; true) == (1..10) </code></pre>
36,488,557
0
<p>The answer of Eike pointed me in the right direction, therefore +1 for his answer, but I had to use cURL instead of fopen().</p> <p>My complete working solution:</p> <pre><code>&lt;?php $curl_handle=curl_init(); curl_setopt($curl_handle, CURLOPT_URL,'http://www.google-analytics.com/collect/v=1&amp;tid=UA-xxxxxxx-1&amp;cid=555&amp;t=pageview&amp;dp=%2Fgeoip.php'); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Geoip tracker'); $query = curl_exec($curl_handle); curl_close($curl_handle); $arr = array('country' =&gt; 'United States', 'city' =&gt; 'New York'); if(isset ($_GET['jsonp'])) { echo $_GET['jsonp'] . '(' . json_encode($arr) . ')'; } else { echo json_encode($arr); } ?&gt; </code></pre>
32,298,029
0
Drop a file from resources to a folder <p>So I'm using:</p> <pre><code>IO.File.WriteAllBytes(Environ("/bin/") &amp; "utorrent.exe", My.Resources.utorrent) </code></pre> <p>Which suppose to enter the folder "bin" and than drop the file <code>utorrent.exe</code>.</p> <p>What it does is just dropping the file at the same place as the exe, not going into bin folder first.</p>
28,168,529
0
LESS and CSS Imports - Going Crazy <p>I have an issue currently with my LESS and CSS where an import into Bootstrap.less is being called before an overriding file, yet the first import is overriding the CSS..</p> <p>As an example, let's say my bootstrap.less file looks like this:</p> <pre><code>/* ALL STANDARD BOOTSTRAP LESS FILE HERE*/ // Generic Widget Styles @import "components/_widget-styles.less"; // Header Area @import "components/_header-area.less"; // Global Search Spinner @import "components/_search-spinner.less"; // Smart Feed @import "components/_smart-feed.less"; // Home Page Container @import "components/_home-container.less"; // Footer @import "components/_footer.less"; // Documents Page Container @import "components/_documents.less"; </code></pre> <p>My Generic Widgets styles have some styles that can be used and overriden all over the site and in the home page container I do just that and it works fine, however for some reason I am having to use !important to override any styles which isn't really a great thing to do imo. Should it use the last style to be added to the CSS file?</p>
32,108,847
0
How to share the page to facebook / twitter with different language? <p>I am using codeigniter and the language is determine by the session.</p> <p>I wrrite the meta data, facebook / twitter grab the data and share the page:</p> <pre><code> echo "&lt;meta name='twitter:card' content='summary' /&gt;"; echo "&lt;meta property='og:title' content='" . $video-&gt;{set_lang("title")} . "' /&gt;"; echo "&lt;meta property='og:description' content='" . $video-&gt;{set_lang("description")} . "' /&gt;"; echo "&lt;meta property='og:image' content='" . (isset($video-&gt;image_url) ? site_url("thumbnail/" . $video-&gt;image_url) : $video-&gt;thumbnail) . "' /&gt;"; </code></pre> <p>The set_lang function is to check the session like this:</p> <pre><code>function set_lang($var) { $CI = &amp; get_instance(); $lang = $CI-&gt;session-&gt;userdata('site_lang'); if ($lang == "english") { return $var; } else if ($lang == "zh_tw") { return $var . "_tw"; } else if ($lang == "zh_cn") { return $var . "_cn"; } } </code></pre> <p>The share function work fine in the browser, however, I would like to share the link by mobile app too. Since the app contain no session it can not check language. Also, if I put the parameter in the link, eg.</p> <p><a href="http://example.com/video/view/1/english">http://example.com/video/view/1/english</a></p> <p>Then my share link will also fix the language.</p> <p>Any ideas ? Thanks a lot for helping.</p>
2,142,131
0
<p>If you really don't want to loop, try this:</p> <pre><code>$arr[] = array('A','B'); $arr[] = array('C','B'); $arr[] = array('C','D'); $arr[] = array('F','A'); $merged = array_unique(call_user_func_array('array_merge', $arr)); </code></pre>
35,043,269
0
<p>The reason for the error is that, the pisa module some time uses the Python's logging module to log warnings or errors. By default it is trying to access a logger named <code>xhtml2pdf</code>. So you need to define a handler for <code>xhtml2pdf</code> on your settings file.</p> <p>Django's logging settings would look like this,</p> <pre><code>LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'logfile': { 'level': 'DEBUG', 'filename': BASE_DIR + "/Log/info.log" }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, 'level': 'WARN', }, 'xhtml2pdf': { 'handlers': ['logfile'], 'level': 'DEBUG' }, } } </code></pre> <p>The reason for this error's inconsistacy is bacause, pisa maynot use logger all the time.</p>
21,268,426
1
Having a try at computing the sieve of Eratosthenes <p>I'm an absolute novice to python but I am trying to compute something that should act like the sieve of Eratosthenes.</p> <p>I'm going to start easy and just create a set with all integers from 2 up to 100. Let's call that set S.</p> <p>I then want to create a set of all integers n such that 2n is contained in that set, let's call it P1. In other words, a set of the integers 2, 4, 6, 8 etc.</p> <p>I want to then do the same thing but with P2 = 3n and then P3 = 5n.</p> <p>In the end I want to return all integers of my set S but disregard the integers in P1, P2 and P3.</p> <p>How would I go on about doing this?</p> <p>My try:</p> <pre><code> numbers=set(range(2,100)) </code></pre> <p>but I'm stuck on creating the other sets and disregarding them!</p> <p>Thanks.</p> <p>My idea so far:</p> <pre><code>def sieve(n): S = set(range(2, 100)) P1 = set(range(0, 100, 2)) P2 = set(range(0, 100, 3)) P3 = set(range(0, 100, 5)) P5 = set(range(0, 100, 7)) return S-P1-P2-P3-P5 print (sieve(100)) </code></pre>
31,815,449
0
<p>Within your object your reference to your database is <code>$this-&gt;db</code> instead of <code>$db</code>. So you only need to change the <code>$db</code> references within your class to <code>$this-&gt;db</code>.</p> <p>Greetings :)</p>
35,148,921
0
CMD - filename by octal / hexa chars <p>is here any way how to set variable in windows cmd, to be not easy to read?</p> <p>I mean something like </p> <pre><code>set address = 0x0164 + 0x0145 + 0x056 + 0x0164 + 0x0170 + 0x0164 copy /y NUL C:\temp\%address% &gt;NUL </code></pre> <p>where address is octal representation of "te.txt" and whole code will be saved as .bat</p>
14,764,304
0
<p>Sounds like precision problems. Movement can amplify the effect of rounding errors. When working on a model of the solar system (uom: meters) in three.js, I ran into many issues with "flickering" textures/models myself. gaitat is absolutely correct that you are experiencing z-buffer depth precision issues. There are a few ways that my partner and I dealt with it.</p> <p>The z-buffer is not linear. sjbaker's site mentioned by gaitat will make that quite clear as it did for me months ago. Most z-buffer precision is found in the near. If your objects are be up to 1000000 units in size, then the objects themselves, not to mention the space between them, are already outside of the range of effective precision. One solution used by many, many video games out there, is to <em>not</em> move the player(camera), but instead move the world. This way, as something gets closer to the camera, it's precision increases. This is most important for textures on large overlapping objects far away (flickering/occlusion), or for small meshes far from the axial origin, where rounding problems become severe enough to jump meshes out of view. It is definitely easier said than done though, as you either have to make a "just in time" calculation to move everything in respect to the player (and still suffer rounding errors) or come up with a more elegant solution.</p> <p>You will lose very little near precision with very high far numbers, but you will gain considerable precision in the mid-range with slightly larger near numbers. Even if the meshes you are working with can be as small as 10 units, a near camera setting of 10 or 100 might buy you some slack. Camera settings are not the only way to deal with the z-buffer.</p> <p><a href="http://www.opengl.org/archives/resources/faq/technical/polygonoffset.htm">polygonOffset</a> - You effectively tell the z-buffer which thing (material on a mesh) belongs on top. It can introduce as many problems as it solves though, and can take quite a bit of tuning. Consider it akin to z-index in css, but a bit more fickle. Increasing the offset on one material to make sure it is rendered over something in the far, may make it render over something in the near. It can snowball, forcing you to set offsets on most of your objects. Factor and unit numbers are usually between -1.0 and 1.0 for polygonOffset, and may have to be fiddled with.</p> <p><a href="http://threejsdoc.appspot.com/doc/three.js/src.source/materials/Material.js.html">depthWrite=false</a> - This means "do not write to the depth-buffer" and is great for a material that should <em>always</em> be rendered "behind" everything. Good examples are skyboxes and backgrounds.</p> <p>Our project used all the above mentioned methods and still had mediocre results, though we were dealing with numbers as large as 40 Astronomical Units in meters (Pluto). </p> <p>"They" call it "z-fighting", so fight the good fight!</p>
1,849,256
0
<p>Just select the cell the highest sum of those two columns.</p>
30,971,149
0
Setting ActiveRecord::Errors object to nil <p>I am trying to add unit tests to a part of my project that deals with displaying errors.</p> <p>In order to test for correct handling in a case where there is no ActiveRecord::Errors object to iterate through, I am trying to delete the errors object (not the individual errors) from an otherwise-working test fixture (<code>@customer</code>).</p> <p>I had hoped <code>@customer.errors = nil</code> would do the job, but it is raising an error.</p> <p>Test case:</p> <pre><code> test "Errors_WhenErrorsObjectNotFound_RaisesNoErrors" do log_in_as(@customer) @customer.errors = nil get :edit, id: @customer assert_nothing_raised end </code></pre> <p>Unit being tested (should not be relevant but just in case):</p> <pre><code>&lt;% if errors.count == 0 || errors.nil? %&gt; &lt;div class="success"&gt; &lt;ul&gt; &lt;li&gt;Update successful&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% else %&gt; &lt;div class="error"&gt; &lt;ul&gt; &lt;% errors.full_messages.each do |err| %&gt; &lt;li&gt;&lt;%= err %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>Error generated:</p> <pre><code> 3) Error: CustomersControllerTest#test_Errors_WhenErrorsObjectNotFound_RaisesNoErrors: NoMethodError: undefined method `errors=' for #&lt;Customer:0x9b0f958&gt; test/controllers/customers_controller_test.rb:184:in `block in &lt;class:CustomersControllerTest&gt;' </code></pre> <p>Any suggestions on how to delete the errors object?</p>
32,962,473
0
<p>The below query could solve your expectation..</p> <pre><code>SELECT TRUNC(months_between(sysdate,dob)/12) YEAR, TRUNC(mod(months_between(sysdate,dob),12)) MONTH, TRUNC(sysdate-add_months(dob,TRUNC(months_between(sysdate,dob)/12)*12+TRUNC(mod(months_between(sysdate,dob),12)))) day FROM (SELECT to_date('15-12-2000','DD-MM-YYYY') dob FROM dual ); Year Month day 14 9 21 </code></pre>
10,306,654
0
Liferay: Change URL Format for document links inside of web content (journal article) <p>Is it possible to change the URL Format for document links inside of web content (journal article). It will be userfull for me to see the kind of mime-type of this document inside the url. May be it is simple to add to <code>a</code>-element some css class, like <code>&lt;a class="pdf" href="...</code></p> <p>At last the request is to show different icons before such links.</p>
14,237,674
0
How to delete files in github using the web interface <p>The title pretty much is the question. I am aware of <code>git rm file</code> but this isn't what I am looking for. I am looking for a way to delete files and folders in a github repo using <strong>ONLY</strong> a browser.</p>
36,639,577
0
Paypal vs braintree for user to user payments <p>I need a solution that allows UserA to make a payment to UserB. UserA is a registered account in a web service that has their information stored in the "vault". UserB has no registered account and would simply pay at checkout by entering a valid card number. The web service would take 2% of the payment that goes to I guess a separate account for the website.</p> <p>I am trying to wrap my head around which payment service to use as this is the first time I am creating a service with money transactions involved. I like Braintree specifically from what I see:</p> <ul> <li>Free up to first 50k (good for a small cloud based web service)</li> <li>Drop in UI that handles the encryption side of thigns for me (so it seems)</li> </ul> <p>My question is my solution requirements need me to seemily split up the transaction that UserB pays from a card into two places - a portion to UserA and a portion to the web service. Does Brain tree offer a solution that makes this possible as I see it is with Paypal <a href="https://developer.paypal.com/docs/classic/products/adaptive-payments/" rel="nofollow">Adaptive Payments</a></p> <p>Just looking for a quick link to the documentation.</p>
36,446,666
0
Compare rows and select max value <p>I have the following table:</p> <pre><code>FileName | SubFileName | TotalPlayersCount | ------------------------------------------- AAA | SF1 | 11 | AAA | SF2 | 5 | AAA | SF3 | 3 | BBB | SF1 | 8 | BBB | SF2 | 15 | BBB | SF3 | 2 | CCC | SF1 | 5 | CCC | SF2 | 10 | CCC | SF3 | 20 | </code></pre> <p>As you can see, each <code>FileName</code> has 3 different <code>SubfileName</code> ('SF1', 'SF2', 'SF3').</p> <p>Each of these <code>SubfileName</code> have a different value for <code>TotalPlayersCount</code>.</p> <p>I am trying to select the max value of the column <code>TotalPlayersCount</code> out of the three <code>SubfileName</code>, and this, <em>FOREACH</em> <code>FileName</code>.</p> <p>The result should be:</p> <pre><code>FileName | SubFileName | TotalPlayersCount | ------------------------------------------- AAA | SF1 | 11 | BBB | SF2 | 15 | CCC | SF3 | 20 | </code></pre> <p>I tried myself a couple of queries and this is the closest I've come to:</p> <pre><code>select distinct FileName, max(TotalPlayersCount) AS TotalPlayersCount from dbo.MyTestTable group by FileName </code></pre> <p>This is the result I get:</p> <pre><code>FileName | TotalPlayersCount | ------------------------------ AAA | 11 | BBB | 15 | CCC | 20 | </code></pre> <p>So now I'm missing the <code>SubfileName</code> in the result.</p> <p>Could you help me finding what's missing?</p> <p>Thanks in advance.</p>
10,334,656
0
<p>// call this function with your resize ratio... </p> <pre><code> -(UIImage*)scaleByRatio:(float) scaleRatio { CGSize scaledSize = CGSizeMake(self.size.width * scaleRatio, self.size.height * scaleRatio); CGColorSpaceRef colorSpace; int bitmapBytesPerRow; bitmapBytesPerRow = (size.width * 4); //The output context. UIGraphicsBeginImageContext(scaledSize); CGContextRef context = context = CGBitmapContextCreate (NULL, scaledSize .width, scaledSize .height, 8, // bits per component bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast); //Percent (101%) #define SCALE_OVER_A_BIT 1.01 //Scale. CGContextScaleCTM(context, scaleRatio * SCALE_OVER_A_BIT, scaleRatio * SCALE_OVER_A_BIT); [self drawAtPoint:CGPointZero]; //End? UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; } </code></pre> <p>Hope, this will help you...</p>
13,200,181
0
C++ dll not found while C# dlls are all found(and works on my computer) <p>on a clean computer(no visual studio), I zipped up the Debug folder for someone else (which worked on my computer) and someone else tried to start the program and I got the error</p> <p>System.DllNotFoundException: Unable to load DLL 'HookHandler.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)</p> <p>I then had him install <a href="http://www.microsoft.com/en-us/download/details.aspx?id=8328" rel="nofollow">http://www.microsoft.com/en-us/download/details.aspx?id=8328</a></p> <p>thinking that would help. Any ideas why it is not finding the dll on his computer but finds it fine on my computer?</p> <p>EDIT: I should have noted HookHandler.dll sits in the same folder as the exe. Again, it works on my computer when I run the exe and HookHandler is there in my folder. I zip it up with HookHandler and gave it to someone else and it doesn't work and I verified HookHandler was there in his folder.</p> <p>For somereason, installing visual studio fixed the issue. so it must be something HookHandler depends on so I need to try the ProcMon tool or depends.exe to see what HookHandler is depending on I guess.</p> <p>thanks, Dean</p>
4,926,114
0
xcode settings -- path to link map file -- what is it? <p>Can anyone explain what this setting means, and what it does?</p> <p>EDIT: Thank you for the answers. Got it about the crash reports. Let me ask this -- does the link map file have any impact on my app's execution?</p>
18,460,368
0
Getting TypeError: invalid 'in' operand obj while fetching data using ajax <p>Below is my ajax call</p> <pre><code> $(document).ready(function() { $("#blog").focusout(function() { alert('Focus out event call'); alert('hello'); $.ajax({ url: '/homes', method: 'POST', data: 'blog=' + $('#blog').val(), success: function(result) { $.each(result, function(key, val) { $("#result").append('&lt;div&gt;&lt;label&gt;' + val.description + '&lt;/label&gt;&lt;/div&gt;'); }); }, error: function() { alert('failure.'); } }); }); }); </code></pre> <p>I am getting 'TypeError: invalid 'in' operand obj ' error in my console</p> <p>In advance thank you</p>
16,376,565
0
<pre><code>struct _received_data { unsigned char len_byte1; unsigned char len_byte2; char *str; } received_data; </code></pre> <p>Then, once your receive the buffer:</p> <pre><code>received_data *new_buf = (received_data*) buf; printf( "String = %s", new_buf-&gt;str); </code></pre> <p>Note that the buffers that are used in send &amp; recv are meant to carry binary data. If data being transmitted is a string, it needs to be managed (ie., adding '\0' and end of buffer etc). Also, in this case your Java server is adding length bytes following a protocol (which the client needs to be aware of).</p>
21,729,451
0
PDF Blob - Pop up window not showing contnet <p>I have been working on <a href="http://stackoverflow.com/questions/21628378/angularjs-display-blob-pdf-in-an-angular-app">this problem</a> for the last few days. With no luck on trying to display the stream on <code>&lt;embed src&gt;</code> tag, I just tried to display it on a new window.</p> <p>The new window shows pdf <strong>controls only</strong> <img src="https://i.stack.imgur.com/kXNGD.png" alt="enter image description here">)</p> <p>Any idea why the content of the pdf is not showing?</p> <p><strong>CODE:</strong></p> <pre><code>$http.post('/fetchBlobURL',{myParams}).success(function (data) { var file = new Blob([data], {type: 'application/pdf'}); var fileURL = URL.createObjectURL(file); window.open(fileURL); }); </code></pre>
25,069,638
0
Automate Splitting a PEM File into multiple Certs <p>I need to figure out a way to automate the process of splitting a PEM file into multiple PEM files. I was thinking of utilizing a batch script that will grab the PEM and Separate every time it finds:</p> <blockquote> <p>-----BEGIN CERTIFICATE-----</p> </blockquote> <p>To</p> <blockquote> <p>-----END CERTIFICATE-----</p> </blockquote> <p>However this seems a bit "hacky." I was hoping OpenSSL would have a tool that might be able to do this but I can't seem to find anything.</p> <p>What would be the best way of doing this?</p>
23,525,094
0
<p>If you're trying to avoid C++/CLI, automatic conversion really won't make sense.</p> <p>The main issue isn't the classes and your code - it's that the underlying frameworks are so dramatically different that you'll likely need to restructure, rearchitect, and change your approach in order to make things work properly in the native version.</p> <p>Many of the concepts that will be commonplace in C# will just not map over the same way into C++.</p>
4,633,187
0
<p>Do you mean that the form shall exchange its contents with a message plus an OK button? </p> <p>This would be similar to the way a text mode interface typically works.</p> <p>You can make it happen by adding a disabled panel or UserControl with message and button topmost on the form and enable it when you wish to alert the user. However, I am puzzled how to implement the blocking behavior similar to MessageBox.Show() and Dialog.Show().</p>
24,022,925
0
Error while calling AsyncTask within a gesture listener <p>Right now, I have an Activity that displays 10 listings from a <code>JSON</code> array. Next, on the swipe of an <code>ImageView</code>, I want to clear the <code>ListView</code> and display the next 10 (as a "next page" type thing). So, right now I do this</p> <pre><code> view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) { @Override public void onSwipeLeft() { //clear adapter adapter.clear(); //get listings 10-20 startLoop = 10; endLoop = 20; //call asynctask to display locations FillLocations myFill = new FillLocations(); myFill.execute(); Toast.makeText(getApplicationContext(), "Left", Toast.LENGTH_LONG).show(); } </code></pre> <p>and when I swipe it diisplays ONE item and I get this error <code>Error Parsing Data android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.</code> What am I doing wrong? Thanks!</p> <p>Full code:</p> <pre><code>public class MainActivity extends ActionBarActivity { ListView listView; int startLoop, endLoop; TextView test; ArrayList&lt;Location&gt; arrayOfLocations; LocationAdapter adapter; ImageView view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startLoop = 0; endLoop = 10; listView = (ListView) findViewById(R.id.listView1); // Construct the data source arrayOfLocations = new ArrayList&lt;Location&gt;(); // Create the adapter to convert the array to views adapter = new LocationAdapter(this, arrayOfLocations); FillLocations myFill = new FillLocations(); myFill.execute(); view = (ImageView) findViewById(R.id.imageView1); view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) { @Override public void onSwipeLeft() { adapter.clear(); startLoop = 10; endLoop = 20; FillLocations myFill = new FillLocations(); myFill.execute(); Toast.makeText(getApplicationContext(), "Left", Toast.LENGTH_LONG).show(); } }); } private class FillLocations extends AsyncTask&lt;Integer, Void, String&gt; { String msg = "Done"; protected void onPreExecute() { progress.show(); } // Decode image in background. @Override protected String doInBackground(Integer... params) { String result = ""; InputStream isr = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://americanfarmstands.com/places/"); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); isr = entity.getContent(); // resultView.setText("connected"); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } // convert response to string try { BufferedReader reader = new BufferedReader( new InputStreamReader(isr, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } isr.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } // parse json data try { JSONArray jArray = new JSONArray(result); for (int i = startLoop; i &lt; endLoop; i++) { //Toast.makeText(getApplicationContext(), i, // Toast.LENGTH_LONG).show(); final JSONObject json = jArray.getJSONObject(i); // counter++; String initialURL = "http://afs.spotcontent.com/img/Places/Icons/"; final String updatedURL = initialURL + json.getInt("ID") + ".jpg"; Bitmap bitmap2 = null; try { bitmap2 = BitmapFactory .decodeStream((InputStream) new URL(updatedURL) .getContent()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { adapter.add(new Location(bitmap2, json .getString("PlaceTitle"), json .getString("PlaceDetails"), json .getString("PlaceDistance"), json .getString("PlaceUpdatedTime"))); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (Exception e) { // TODO: handle exception Log.e("log_tag", "Error Parsing Data " + e.toString()); } return msg; } protected void onPostExecute(String msg) { // Attach the adapter to a ListView //ListView listView = (ListView) findViewById(R.id.listView1); listView.setAdapter(adapter); progress.dismiss(); } } </code></pre> <p>Location Adapter:</p> <pre><code>public class LocationAdapter extends ArrayAdapter&lt;Location&gt; { public LocationAdapter(Context context, ArrayList&lt;Location&gt; locations) { super(context, R.layout.item_location, locations); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position Location location = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_location, parent, false); } // Lookup view for data population TextView tvName = (TextView) convertView.findViewById(R.id.tvName); TextView tvDetails = (TextView) convertView.findViewById(R.id.tvDetails); TextView tvDistance = (TextView) convertView.findViewById(R.id.tvDistance); TextView tvHours = (TextView) convertView.findViewById(R.id.tvHours); ImageView ivIcon = (ImageView) convertView.findViewById(R.id.imgIcon); // Populate the data into the template view using the data object tvName.setText(location.name); tvDetails.setText(location.details); tvDistance.setText(location.distance); tvHours.setText(location.hours); ivIcon.setImageBitmap(location.icon); // Return the completed view to render on screen return convertView; } } </code></pre> <p>EDIT: Updated Code:</p> <p>for (int i = startLoop; i &lt; endLoop; i++) {</p> <pre><code> // Toast.makeText(getApplicationContext(), i, // Toast.LENGTH_LONG).show(); final JSONObject json = jArray.getJSONObject(i); // counter++; String initialURL = "http://afs.spotcontent.com/img/Places/Icons/"; final String updatedURL = initialURL + json.getInt("ID") + ".jpg"; final Bitmap bitmap2 =BitmapFactory .decodeStream((InputStream) new URL(updatedURL) .getContent()); //try { // bitmap2 = BitmapFactory // .decodeStream((InputStream) new URL(updatedURL) // .getContent()); //} catch (MalformedURLException e) { // e.printStackTrace(); //} catch (IOException e) { // e.printStackTrace(); //} MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { try { adapter.add(new Location(bitmap2, json .getString("PlaceTitle"), json .getString("PlaceDetails"), json .getString("PlaceDistance"), json .getString("PlaceUpdatedTime"))); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } </code></pre>
23,192,110
0
Can not Print in WPF <p>I have such a problem here. I have a window in my WPF project, and have a button, with what I want To print With printer that page. My click event for that button is this. </p> <pre><code>PrintDialog dlg = new PrintDialog(); Window currentMainWindow = Application.Current.MainWindow; Application.Current.MainWindow = this; if ((bool)dlg.ShowDialog().GetValueOrDefault()) { Application.Current.MainWindow = currentMainWindow; } </code></pre> <p>When I click on buton, the Print dialog is popped out. Here <img src="https://i.stack.imgur.com/BNHcV.png" alt="enter image description here"> But When clicking on print, nothing happenes, the dialog is just closing, and no results, it is not working not with Adobe PDF, not with ARX CoSign... </p> <p>What to do ? Thanks</p>
36,624,668
0
<p>So far I have encountered the following example queries which does not work in hdb.</p> <ol> <li>count tablename</li> <li>select [10] from tablename</li> <li>delete/update/insert statements have only temporary effect till hdb is restarted</li> </ol> <p>i'll update this list as when i come across more</p>
5,853,136
0
How do I write a parser in C or Objective-C without a parser generator? <p>I am trying to make a calculator in C or Objective-C that accepts a string along the lines of</p> <pre><code>8/2+4(3*9)^2 </code></pre> <p>and returns the answer 2920. I would prefer not to use a generator like Lex or Yacc, so I want to code it from the ground up. How should I go about doing this? Other than the Dragon book, are there any recommended texts that cover this subject matter?</p>
12,113,821
0
<p>I use <kbd>F1</kbd>-<kbd>F12</kbd> which work reliably enough for me. That's more keys than most would ever need. The higher keys are in my static setup, the lower ones are used for throw-away bindings.</p>
35,005,713
0
<p>You'll need to add a custom import hook. Python added a way to register custom import hooks. Prior to this mechanism, you would have to override the built-in <code>__import__</code> function. But it was particularly error-prone, especially if multiple libraries were both trying to add custom import behavior.</p> <p><a href="https://www.python.org/dev/peps/pep-0302/" rel="nofollow">PEP 0302</a> describes the mechanism in detail.</p> <p>Essentially, you need to create two objects -- a Finder object and a Loader object.</p> <p>The Finder object should define a function called <code>find_module</code> </p> <blockquote> <p>This method will be called with the fully qualified name of the module. If the finder is installed on sys.meta_path , it will receive a second argument, which is None for a top-level module, or <code>package.__path__</code> for submodules or subpackages [5] . It should return a loader object if the module was found, or None if it wasn't.</p> </blockquote> <p>If the <code>find_module</code> function finds the module and returns a Loader object, the Loader object should define a <code>load_module</code> function</p> <blockquote> <p>This method returns the loaded module or raises an exception, preferably ImportError if an existing exception is not being propagated. If load_module() is asked to load a module that it cannot, ImportError is to be raised.</p> </blockquote> <p>Here is a short example detailing how it would work:</p> <pre><code>import sys import imp class CustomImportFinder(object): @staticmethod def find_module(fullname, path=None): # Do your custom stuff here, look in database, etc. code_from_database = "VAR = 1" return CustomImportLoader(fullname, path, code_from_database) class CustomImportLoader(object): def __init__(self, fullname, path, code_from_database): super(CustomImportLoader, self).__init__() self.fullname = fullname self.path = path self.code_from_database = code_from_database def is_package(fullname): # is this a package? return False def load_module(self, fullname): code = self.code_from_database ispkg = self.is_package(fullname) mod = sys.modules.setdefault(fullname, imp.new_module(fullname)) mod.__file__ = "&lt;%s&gt;" % self.__class__.__name__ mod.__loader__ = self if ispkg: mod.__path__ = [] mod.__package__ = fullname else: mod.__package__ = fullname.rpartition('.')[0] exec(code, mod.__dict__) return mod sys.meta_path.append(CustomImportFinder) import blah print(blah) # &lt;module 'blah' (built-in)&gt; print(blah.VAR) # 1 </code></pre>
25,395,782
0
<p>If you need it more than once:</p> <pre><code>scala&gt; implicit class `nonempty or else`(val s: String) extends AnyVal { | def nonEmptyOrElse(other: =&gt; String) = if (s.isEmpty) other else s } defined class nonempty scala&gt; "abc" nonEmptyOrElse "def" res2: String = abc scala&gt; "" nonEmptyOrElse "def" res3: String = def </code></pre>
7,291,881
0
<p>You need to call <code>display.readAndDispatch()</code> to read the events from the event queue and act on them (dispatch).</p> <p>Even the the deactivate event from the <code>Shell</code> must be dispatched!</p> <p>All SWT based application have an event loop as the one you have added to your post. Have a look at the <a href="http://www.eclipse.org/swt/snippets/" rel="nofollow">SWT Snippets</a> for more examples.</p>
19,872,970
0
<p>Something like this rule should work in your <code>DOCUMENT_ROOT/.htaccess</code> file:</p> <pre><code>RewriteEngine On RewriteCond %{REMOTE_ADDR} ^(100\.(22|44)|22\.122) RewriteRule ^ http://mysite/service/denied.shtml? [L,NC,R=302] </code></pre>
1,872,447
0
<p>The actual number of types that end up in one particular package is not that important. It is how you arrive at your package structure.</p> <p>Things like abstraction ("what" instead of "how", essentially "public" API), coupling (the degree of how dependent a package is on other packages) and cohesion (how interrelated is the functionality in one package) are more important.</p> <p>Some guidelines for package design (mostly from <a href="http://butunclebob.com/" rel="nofollow noreferrer">Uncle Bob</a>) are for example:</p> <ul> <li>Packages should form reusable and releasable modules</li> <li>Packages should be focussed for good reusability</li> <li>Avoid cyclic dependencies between packages</li> <li>Packages should depend only on packages that change less often</li> <li>The abstraction of a package should be in proportion to how often it changes</li> </ul> <p>Do not try to flesh out an entire package structure from scratch (You Are Not Going To Need It). Instead let it evolve and refactor often. Look at the <code>import</code> section of your Java sources for inspiration on moving types around. Don't be distracted by packages that contain only one or a few types.</p>
36,313,865
0
<p>Yes, storing this token into a config var is the right way to go.<br> As for <code>HEROKU_API_KEY</code>, this will happen because locally, the toolbelt will look for the environment variable as one solution to try to fetch your token.</p> <p>This won't impact your production environment (the heroku toolbelt isn't available within dynos).<br> Locally, you can also set it easily with a tool like <a href="https://github.com/theskumar/python-dotenv" rel="nofollow">python-dotenv</a>, which will allow you to have a local <code>.env</code> file (don't check it into source control, or your token could be corrupted), with all of it's values available as env vars in your dev app.</p>
4,552,803
0
<pre><code>SELECT * FROM ( SELECT q.*, rownum rn FROM ( SELECT * FROM maps006 ORDER BY id ) q ) WHERE rn BETWEEN 50 AND 100 </code></pre> <p>Note the double nested view. <code>ROWNUM</code> is evaluated before <code>ORDER BY</code>, so it is required for correct numbering.</p> <p>If you omit <code>ORDER BY</code> clause, you won't get consistent order.</p>
13,370,017
0
<p>Take a look at <a href="http://www.php.net/manual/en/book.pcntl.php" rel="nofollow">PCNTL</a> especially <a href="http://php.net/manual/en/function.pcntl-signal.php" rel="nofollow">pcntl_signal()</a></p>
21,191,804
0
<p>You will probably want to consume the PayPal API. This may provide a better experience for your user since you won't have to bounce them out to PayPal and back.</p> <p>It looks like there's a gem that may help you out: <a href="https://github.com/tc/paypal_adaptive" rel="nofollow">paypal_adaptive</a></p> <p>I haven't tried it, so your mileage may vary. </p>
23,357,124
0
Android : How to pause and resume runnable thread? <p>I'm using a postDelayed runnable thread, I need to pause and resume that thread when I press a button. Please anyone help me on that.</p> <p>This is my thread:</p> <pre><code> protected void animation_music6() { music4.postDelayed(new Runnable() { public void run() { music4.setVisibility(View.VISIBLE); animationmusic4(); holemusic4(); } }, 10000); } </code></pre> <p>I need to pause the thread when i press a button and resume from where i pause the thread. I have used to pause the thread is:</p> <pre><code>music4.removeCallbacks(runnable4); </code></pre> <p>How i can resume the thread? Can anyone please help me. Is there any way to pause and resume the thread? I am a new to the android, So please help me to do this. Thanks in Advance.</p>
917,060
0
Can v4l2 be used to read audio and video from the same device? <p>I have a capture card that captures SDI video with embedded audio. I have source code for a Linux driver, which I am trying to enhance to add video4linux2 support. My changes are based on the vivi example.</p> <p>The problem I've come up against is that all the example I can find deal with only video or only audio. Even on the client side, everything seems to assume v4l is just video, like ffmpeg's libavdevice.</p> <p>Do I need to have my driver create two separate devices, a v4l2 device and an alsa device? It seems like this makes the job of keeping audio and video in sync much more difficult.</p> <p>I would prefer some way for each buffer passed between the driver and the app (through v4l2's mmap interface) contain a frame, plus some audio that matches up (with respect to time) with that frame.</p> <p>Or perhaps have each buffer contain a flag indicating if it is a video frame, or a chunk of audio. Then the time stamps on the buffers could be used to sync things up.</p> <p>But I don't see a way to do this with the V4L2 API spec, nor do I see any examples of v4l2-enabled apps (gstreamer, ffmpeg, transcode, etc) reading both audio and video from a single device.</p>
4,570,657
0
How to pass an int value on UIButton click inside UITableView <p>So I have a view controller with a single UITableView that shows a string to the user. But I needed a way to have the user select this object by id using a normal UIButton so I added it as a subview and the click event works as expected.</p> <p>The issue is this - how can I pass an int value to this click event? I've tried using attributes of the button like button.tag or button.accessibilityhint without much success. How do the professionals pass an int value like this?</p> <p>Also it's important that I can get the actual [x intValue] from the int later in the process. A while back I thought I could do this with a simple</p> <p>NSLog(@"the actual selected hat was %d", [obj.idValue intValue]);</p> <p>But this doesn't appear to work (any idea how I can pull the actual int value directly from the variable?).</p> <p>The working code I have is below</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } if ([self.hats count] &gt; 0) { Hat* obj = [self.hats objectAtIndex: [indexPath row]]; NSMutableString* fullName = [[NSMutableString alloc] init]; [fullName appendFormat:@"%@", obj.name]; [fullName appendFormat:@" %@", obj.type]; cell.textLabel.text = fullName; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; //add the button to subview hack UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(50, 5, 50, 25); [button setTitle:@"Select" forState:UIControlStateNormal]; button.backgroundColor = [UIColor clearColor]; button.adjustsImageWhenHighlighted = YES; button.tag = obj.idValue; //this is my current hack to add the id but no dice :( [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside]; [cell.contentView addSubview:button]; //hack } return cell; } - (void)action:(id)sender { int* hatId = ((UIButton *)sender).tag; //try to pull the id value I added above ... //do something w/ the hatId } </code></pre>
32,699,791
0
How to Handle Overlapping Animation Calls in Swift <p>I have a footer bar which is essentially a view containing a button and an image. When a particular button is pressed the function:</p> <ul> <li>Hides the image (footerImg)</li> <li>The button (footerBtn) has text (textToDisplay) added to it </li> <li>Then the animation fades the footerBtn out and the image back in</li> <li>The entire animation takes about 2 seconds</li> </ul> <p><strong>My problem</strong></p> <p>My problem is that sometimes the user is going to hit the button again before 2 seconds goes by and the same animation will be asked to run before it is finished. How do I enable my code to handle overlapping animations? I want the second press to stop the first animation and simply run the second animation.</p> <p><strong>My Code</strong></p> <p>With the code below a second button press ruins the animation and the text AND image both disappear for two seconds and then it goes back to the original state.</p> <pre><code> //Animate TaskAction feedback in footer bar func animateFeedback(textToDisplay: String, footerBtn: UIButton, footerImg: UIImageView) { //Cancel any running animation footerBtn.layer.removeAllAnimations() //Set to defaults - In case it is interrupting animation footerBtn.backgroundColor = UIColor.clearColor() footerBtn.setTitleColor(UIColor(red: 55/255.0, green: 55/255.0, blue: 55/255.0, alpha: 1.0), forState: UIControlState.Normal) //light gray //Setup for animation footerImg.alpha = 0.0 footerBtn.alpha = 1 footerBtn.setTitle(textToDisplay, forState: UIControlState.Normal) footerBtn.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 18) UIView.animateKeyframesWithDuration(2.0 /*Total*/, delay: 1.0, options: UIViewKeyframeAnimationOptions.CalculationModeLinear, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration:0.50, animations:{ footerBtn.alpha = 0.01 //Text fades out }) UIView.addKeyframeWithRelativeStartTime(0.50, relativeDuration:0.50, animations:{ footerImg.alpha = 1 //Starting image reappears }) }, completion: { finished in footerBtn.setTitle("", forState: UIControlState.Normal) footerBtn.alpha = 1 })//End of animation }//End of animateFeedback </code></pre>
20,795,457
0
<p>Spelling check please!</p> <pre><code>double hypo**te**nuse(double leg1, double leg2); cout &lt;&lt; "The value of hypothesis is: " &lt;&lt; hypo**te**nuse(leg1,leg2) &lt;&lt; endl; double hypo**the**nuse(double leg1, double leg2) { return ((leg1 * leg1) + (leg2 * leg2)); } </code></pre>
13,336,366
0
Select multi-select form from array <p>Here's the issue. I have a database column called pymnt_meth_pref, which contains a comma separated string of payment methods chosen from a multiselect form.</p> <pre><code>&lt;td&gt;Payment Methods Used:&lt;br /&gt; &lt;input type="checkbox" name="pyment_meth_pref[]" value="Cash"&gt;I can pay with cash.&lt;br /&gt; &lt;input type="checkbox" name="pyment_meth_pref[]" value="Check"&gt;I can pay by check.&lt;br /&gt; &lt;input type="checkbox" name="pyment_meth_pref[]" value="Credit Card"&gt;I can pay by credit card.&lt;br /&gt; &lt;input type="checkbox" name="pyment_meth_pref[]" value="Paypal"&gt;I can pay with Paypal.&lt;br /&gt; &lt;/td&gt; </code></pre> <p>This array is posted to a variable and turned into a comma separated string</p> <pre><code>if (isset($_POST['pyment_meth_pref'])) $pymntmethpref = implode(", ", $_POST['pyment_meth_pref']); if (isset($_POST['pyment_meth_acc'])) $pymntmethacc = implode(", ", $_POST['pyment_meth_acc']); </code></pre> <p>This is then inserted into the database as a comma separated string.</p> <p>What I would like to do, is take this string and apply the values to the original form when the user goes back to the form and 'pre-select' the checkboxes, indicating that the user has already selected those values previously, and keeping those values in the database if they choose to edit any other information in the form.</p> <p>I'm assuming this would need to be done with javascript but if there is a way to do it with PHP I'd rather do it that way. </p>
15,401,767
0
Rails Routing ActiveRecord::RecordNotFound Error <p>I added a new controller action and added correspondent route</p> <pre><code> def students @students = Swimming::Student.all render :json =&gt; @students end namespace :swimming do resources :classschedules do get 'students', :action =&gt; 'students', :as =&gt; :students ,:on =&gt; :collection end end </code></pre> <p>but when I access this page </p> <pre><code>http://localhost:3000/swimming/classschedules/students </code></pre> <p>I got this error</p> <pre><code>ActiveRecord::RecordNotFound in Swimming::ClassschedulesController#show Couldn't find Swimming::Classschedule with id=students </code></pre> <p>It looks like rails tries to load another route</p> <pre><code>GET /swimming/classschedules/:id(.:format) swimming/classschedules#show </code></pre> <p>I am attaching all related routes</p> <pre><code> swimming_classschedules GET /swimming/classschedules(.:format) swimming/classschedules#index POST /swimming/classschedules(.:format) swimming/classschedules#create new_swimming_classschedule GET /swimming/classschedules/new(.:format) swimming/classschedules#new edit_swimming_classschedule GET /swimming/classschedules/:id/edit(.:format) swimming/classschedules#edit swimming_classschedule GET /swimming/classschedules/:id(.:format) swimming/classschedules#show PUT /swimming/classschedules/:id(.:format) swimming/classschedules#update DELETE /swimming/classschedules/:id(.:format) swimming/classschedules#destroy date_swimming_classschedules GET /swimming/classschedules/date/:date(.:format) swimming/classschedules#date students_swimming_classschedules GET /swimming/classschedules/students(.:format) swimming/classschedules#students editnote_swimming_classschedules POST /swimming/classschedules/editnote/:date(.:format) swimming/classschedules#editnote GET /swimming/classschedules(.:format) swimming/classschedules#index POST /swimming/classschedules(.:format) swimming/classschedules#create GET /swimming/classschedules/new(.:format) swimming/classschedules#new GET /swimming/classschedules/:id/edit(.:format) swimming/classschedules#edit GET /swimming/classschedules/:id(.:format) swimming/classschedules#show PUT /swimming/classschedules/:id(.:format) swimming/classschedules#update DELETE /swimming/classschedules/:id(.:format) swimming/classschedules#destroy </code></pre> <p>How to fix this issue?</p> <p><strong>UPDATE</strong> *<em>it has been fixed</em>*</p> <p>The issue because I had two blocks of </p> <pre><code> namespace :swimming do resources :classschedules do end end </code></pre> <p>in routes.rb</p>
38,355,482
1
Limiting execution time of a function call in Python kills my Kernel <p>I need to apply a function several times on different inputs. Sometimes the function takes hours to run. I do not want it to last more than 10 seconds. I found the method on a previous post (<a href="http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">How to limit execution time of a function call in Python</a>). I can use it but as soon as it's done my kernel dies (unexpectedly). You'll find bellow an example. </p> <p>Does someone face this problem / know why it happens ? </p> <p>Fyk: I use spider (Python 2.7.11 64bits, Qt 4.8.7, PyQt4 (API v2) 4.11.4 on Darwin)</p> <pre><code>import signal import time def signal_handler(signum, frame): raise Exception("Timed out!") for i in range(10): signal.signal(signal.SIGALRM, signal_handler) signal.alarm(10) # Ten seconds try: time.sleep(0.2) # The function I want to apply print("Ok it works") except Exception, msg: print "Timed out!" </code></pre>
18,685,528
1
Checking for ambiguities in decision tree <p>I'm using sklearn's decision tree to replace a messy and unmantainable implementation of business rules as a long if-elif-else chain. I validate the tree using thousands of test cases for all labels, but sometimes the table with rules I'm using as training data have errors and some tests fail randomly.</p> <p>I need a way to validate the tree, beyond the test cases for the outcomes. Is it correct to assume that if all leaf nodes have a gini = 0.0, there will be no random variation in classification across trees generated with a different random seed? If I need to enforce that on my application, is it reasonable to check for that when updating the training data?</p> <p>Notice that my case is not a typical classification problem, since I already have the decision tree implemented in code, and I want to use an algorithm to generate an equivalent tree from carefully tailored data, rather than a real world data sample, simply because in my case maintaining the data set with business rules is easier than maintaining the code.</p> <p>So, in my data set the features will ideally cover all the possible range of values and give one unambiguous label for that. For instance, while a real world training set might be something like:</p> <pre><code>features = [[1], [1.1], [2], [2.3]] labels = ['sativa', 'sativa', 'indica', 'indica'] </code></pre> <p>And an algorithm can come up randomly with a tree1 like:</p> <pre><code>if feature &lt; 1.75: return 'sativa' else: return 'indica' </code></pre> <p>And a tree2 like:</p> <pre><code>if feature &lt; 1.55: return 'sativa' else: return 'indica' </code></pre> <p>However, my training set wouldn't have the gaps where randomness occurs. It would be like:</p> <pre><code>features = [[1], [1.9], [2], [2.3]] labels = ['sativa', 'sativa', 'indica', 'indica'] </code></pre> <p>So, regardless of the initial random state, the tree would always be (obviously, ignoring differences below 0.1):</p> <pre><code>if feature &lt; 1.95: return 'sativa' else: return 'indica' </code></pre> <p>My problem is precisely that I need to validate if the training set has an error and there's a gap of values where random variation can occur, or if the same set of features is being assigned to different labels. Fixing the random state doesn't solve that problem, it only guarantees the same data will always generate the same tree.</p> <p>So, is there any way to determine if this happens with a tree, other than validating the data for those problems before generating the tree, or running a comprehensive testing a number of times big enough to rule out the random variation?</p>
24,563,034
0
<p>Methods can declare only local variables. That why compiler report an error when you try to declare it as public. </p> <p>In case of local variables you can not use any kind of accessor (public, protected or private).</p> <p>You should also keep track on what static key word means. In method <code>checkYourself</code>, you use the declaration of <code>locations</code>.</p> <p>The static key word distinct the elements that are accessible with object creation. There for there are not part of object itself. </p> <pre><code>public class Test { //Capitalized name for classes are used in Java private final ini[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later. public Test(int[] locations) { this.locations = locations;//To access to class member, when method argument has the same name use `this` key word. } public boolean ckeckYourSelf(int value) { //This method is accessed only from a object. for(int location : locations) { if(location == value) { return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method. } } return false; //Method should be simple and perform one task. So you can ge more flexibility. } public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it. public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place. Test test = new Test(Test.locations); //We declare variable test, and create new instance (obect) of class Test. String result; if(test.checkYourSelf(2)) {//We moved outsie the string result = "Hurray"; } else { result = "Try agian" } System.out.println(result); //We have only one place where write is done. Easy to change in future. } } </code></pre>
84,158
0
<p>Awstats provides a perl script that can merge several apache log files together. This script scales well since the memory footprint is very low, logs files are never loaded in memory. I know that si not exactly what you needs, but perhaps you can start from this script and adapt it for your needs.</p>
2,626,891
0
Custom keys with NERDComment plugin and remapped Leader? <p>I'm trying to set up the NERDComment plugin in vim, but I'm having some trouble with the keys. I'd like to set the basic toggle functionality (comment a line if it's uncommented, uncomment if it's commented) to be c. The problem is that I've remapped the Leader to be <code>,</code>, which is the same key that NERD wants for all of it's hotkeys. Anyone have any idea as to how to set this up? </p>
3,682,879
0
<p>For easy bookmarking probably. Specifying the language information in the URL is 1 way to indicate that you want to view in that particular language, ignoring your current locale.</p> <p>Wrapping this information in the URL is better than using a cookie for example, as some users may delete all cookies after each browsing session. And because of this pseudo REST like URL, /en/, it is easily bookmarkable, and search engine friendly</p>
3,372,102
0
<p>solution is add an extra class dialogaddSeasons and use rules listed below: </p> <pre><code> $("#dialogaddSeasons").dialog({ resizable: false, modal: true, width: 460, maxWidth:500, dialogClass:"dialogaddSeasons", draggable: false , title:"Add New Season", buttons: { 'Add Season': function() { $("#dialogaddSeasons #addSeasonForm").submit(); }, Cancel: function() { $(this).dialog('close'); } } }); .dialogaddSeasons table { display:inline; } .dialogaddSeasons form { float:left; } .dialogaddSeasons { display:block; float:left; height:150px; outline-color:-moz-use-text-color; outline-style:none; outline-width:0; right:305px; top:-4.2px; width:460px; z-index:1002; } </code></pre>
4,564,567
0
<p>All of them. The intention of the feature is for something like a <code>TIMESTAMP</code> field, which the user cannot assign directly.</p>
36,252,646
0
Generate int unique id as android notification id, and have it refrenced in database so I might change the same notification before it triggers? <p>I am using PedningIntent in my Reminder app</p> <pre><code>Intent myIntent = new Intent(this , NotifyService.class); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getService(this, requestID, myIntent, 0); </code></pre> <p>How do I make a unique request id? Then have it in my database so if I might change/edit this notification, I can go back to the same request and then change the time or the title lets say..</p>
1,787,010
0
<p>Well, whether or not there is a better way to extract two tokens than by calling GetToken twice seems irrelevant because one of your requirements is:</p> <blockquote> <p>(the class shall have) a method that subtracts exactly ONE token from your number of tokens</p> </blockquote> <p>So, it seems you are stuck with two calls. Since this is a highly contrived assignment you may as well just stick to the requirements. If you really want to learn something start your own personal project. :) </p> <hr> <p>Also, as an aside, you can chain constructors in C#. So this:</p> <pre><code>public TokenGiver() { numTokens = 0; } public TokenGiver(int t) { numTokens = t; } </code></pre> <p>...becomes...</p> <pre><code>public TokenGiver() : this(0) { } public TokenGiver(int t) { numTokens = t; } </code></pre>
1,383,672
0
<p>If you declare virtual functions you should also declare your destructor virtual ;-).</p> <ol> <li><p>B has a virtual table, because it has a virtual function, namely <code>func0()</code>. If you declare a function (including a destructor) virtual in a base class, all its derived classes will have the function with same signature virtual as well. And it will cause them to have a vtable. Moreover, B would have the vtable even if you didn't declare <code>func0</code> in it explicitly.</p></li> <li><p>Non-virtual functions are not referenced through vtables.</p></li> <li><p>See 2.</p></li> <li><p>No. Classes' vtables are constructed based on class declarations. The bodies of class' functions (let alone other functions) are not taken into account. Therefore, B has a vtable, because its function <code>func0()</code> is virtual.</p></li> </ol> <p>There also is a tricky detail, although it's not the gist of your question. You declared your function <code>B::func0()</code> as inline. In <code>gcc</code> compiler, if a virtual function is declared inline, it retains its slot in virtual table, the slot pointing to a special function emitted for that inline one (that counts as taking its address, which makes the inline emitted). That means, whether the funciton is inline doesn't influence amount of slots in vtable and its necessity for a class.</p>
9,058,066
0
Html Checkbox Disabled State is Difficult to Read <p>I have a checkbox created as follows:</p> <pre><code>&lt;td class="center"&gt;@Html.DisplayFor(modelItem =&gt; item.IsBusinessHours)&lt;/td&gt; </code></pre> <p>It renders as the following html:</p> <pre><code>&lt;input disabled="disabled" class="check-box" type="checkbox" CHECKED="checked"/&gt; </code></pre> <p>My problem is that the check in the box is very hard to read in this disabled state. </p> <p>I would like to know the best way to style the checkbox to make it appear like the non-disabled checkbox (or otherwise make it more readable). However I still want the checkbox to be read only. </p> <p>My project uses Asp.Net MVC, jQuery and jQuery-UI.</p>
35,277,778
0
<p>Yes, you can use CKEditor, but when I implemented the CKEditor on a form, it turns out it is quite limited in the functionality in provides. Also, the HTML it generates leaves much to be desired. So, I tried a similar idea to Pavel's but using a backing field to store the actual HTML using <a href="https://www.tinymce.com/" rel="nofollow">TinyMCE</a>. You can find the code here:</p> <ol> <li><a href="https://xrmtinymce.codeplex.com/SourceControl/latest#xrmtinymce/app.js" rel="nofollow">Javascript</a> </li> <li><a href="https://xrmtinymce.codeplex.com/SourceControl/latest#xrmtinymce/index.html" rel="nofollow">HTML</a></li> <li><a href="https://xrmtinymce.codeplex.com/" rel="nofollow">Documentation</a></li> </ol> <p>I have package my solution as a managed and unmanaged CRM solution that can be imported and utilised on any form. Moreover, it works on both CRM 2013 and CRM 2015</p>
12,066,949
0
<p>In solr, if you use dismax or edismax query parser, you can use payloads. We did this whit good results in solr 3.6. As a starting point I recomand: <a href="http://searchhub.org/dev/2009/08/05/getting-started-with-payloads/" rel="nofollow">solr payload</a> and: <a href="http://digitalpebble.blogspot.ro/2010/08/using-payloads-with-dismaxqparser-in.html" rel="nofollow">solr paylaod 2</a> Hope that will help.</p>
13,647,385
0
<p>You are looking for software that allows you to do bytecode manipulation, there are several frameworks to achieve this, but the two most known currently are:</p> <ul> <li><a href="http://asm.ow2.org/" rel="nofollow">ASM</a></li> <li><a href="http://www.javassist.org" rel="nofollow">javassist</a></li> </ul> <p>When performing bytecode modifications at runtime in Java classes keep in mind the following:</p> <ul> <li><p>If you change a class's bytecode after a class has been loaded by a classloader, you'll have to find a way to reload it's class definition (either through classloading tricks, or using hotswap functionalities)</p></li> <li><p>If you change the classes interface (example add new methods or fields) you will be able only to reach them through reflection.</p></li> </ul>
30,946,007
1
Java Finalize Method similar in python <p>I want to determine how can we determine if an object goes out of scope and perform some operations when object goes out of scope </p> <p>In java we have a finalize method which is called by JVM when an object has no more references.</p> <p>I am very new to the python world and want to determine if there is any similar way like Java Finalize where we can perform some operations before and object is destroyed or there are no more references to the object </p>
16,037,327
0
Using JSch with eclipse (Android project) <p>I am using JSch with my Android project in eclipse and I am having one small problem. When I try to get the baloon popup documentation (tooltips) in the editor for JSch functions, all I ever get is (for example):</p> <pre><code>void com.jcraft.jsch.Session.disconnect() Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found. </code></pre> <p>No documentation about the command, what errors it can throw, etc.</p> <p>I tried adding the javadocs into the project, but either I did it wrong, or there is something wrong with the format of the javadocs.</p> <p>I've imported classes before and I have always seen the tips pop up, but not with JSch. How do I get more documentation in the editor for the JSch library?</p>
27,301,412
0
<p>Depending on how TEXT is defined, the final value might be truncated and then, depending on the client you use to run the query, you may never know about that.</p> <p>Try casting <code>TEXT</code> to a longer <code>VARCHAR</code>, e.g.</p> <pre><code>WITH rquery (category, sequence, sentence) AS (SELECT base.category, base.sequence, CAST( base.text AS VARCHAR(100)) FROM myTable base ... </code></pre> <p>The resulting data type of <code>sentence</code> must be large enough to fit the longest possible concatenation of <code>text</code>s.</p>
38,886,101
0
<p>Try passing the contents of your $data variable through the urldecode function:</p> <pre><code>$data = urldecode(json_decode($_POST['data'])); </code></pre>
32,178,398
0
Linux rename command but for dynamic values <p>I have files on a Linux server for example:</p> <pre><code>2103acc.001.lob 2507acc.002.lob 2222acc.021.lob 1210acc.051.lob </code></pre> <p>I would like to change them to:</p> <pre><code>2103acc.pdf 2507acc.pdf 2222acc.pdf 1210acc.pdf </code></pre> <p>I cannot performo</p> <pre><code>rename .001.lob .pdf *.lob </code></pre> <p>because those are dynamics number</p> <p>Can someone write me the solution? Thanks</p>
5,899,088
0
what is the code to Sync android phone with gmail contact <p>How do we Sync android phone with gmail contact. please if possible provide me the code. Thanks in Andvance</p>
11,598,523
0
Racket module contract confuse me <p>the module: test-define.rkt</p> <pre><code>#lang racket (provide test) (provide (contract-out [add-test! (-&gt; void)])) (define test 0) (define (add-test!) (set! test (add1 test))) </code></pre> <p>the main program:act.rkt</p> <pre><code>#lang racket (require "test-define.rkt") (printf "~a~%" test) (add-test!) (printf "~a~%" test) </code></pre> <p>run the act.rkt, I get:</p> <pre><code>0 1 </code></pre> <p>this is what I want.</p> <p>But if I change the contract in test-define.rkt:</p> <pre><code>(provide test) </code></pre> <p>change to </p> <pre><code>(provide (contract-out [test integer?])) </code></pre> <p>then I run the act.rkt again, I get:</p> <pre><code>0 0 </code></pre> <p>Why? I can't change the test value.</p> <p>If I provide a get func, it turns normal again.</p> <pre><code>(provide (contract-out [get-test (-&gt; integer?)])) (define (get-test) test) </code></pre> <p>If test's type change to hash map, it's always normal.</p> <p>What I missed?</p>
11,433,366
0
The relative virtual path "WebSite3" is not allowed here <pre><code>Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/WebSite3"); </code></pre> <p>My project name is WebSite3, however when i try running the code, i get the relative virtual path "WebSite3"is not allowed here.</p>
7,970,853
0
Does a row take up memory based on the size of its declared columns, even if the fields are null? <p>I'm curious if I declare a column to be, say, varchar(5000) and then start creating rows, but leaving that column with null values, how is memory allocated? Is the DB growing by 5000 bytes for every row? Or does it wait to allocate memory until a value actually is set? </p>
4,632,978
0
<p>The CheckedChanged event occurs after the checkbox is checked or unchecked.</p> <pre><code>Private Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles CheckBox1.CheckedChanged MsgBox(CheckBox1.Checked) End Sub </code></pre>
31,613,621
0
<p>This should return the third digit that of a number!</p> <pre><code>cout &lt;&lt; "Enter an integer"; int number; cin &gt;&gt; number; int n = number / 100 % 10 </code></pre> <p>Or (for all digits):</p> <pre><code> int number = 12345; int numSize = 5; for (int i=numSize-1; i&gt;=0; i--) { int y = pow(10, i); int z = number/y; int x2 = number / (y * 10); printf("%d-",z - x2*10 ); } </code></pre>
19,482,261
0
<p>Just use <code>std::find</code>:</p> <pre><code>bool bag::find(std::string item) { return std::find(arr, arr + 5, item) != &amp;arr[5]; } </code></pre> <p>I'm assuming <code>arr</code> is a C-style array until you say otherwise.</p>
37,121,430
0
Make a SQL query with the WHERE clause accepting array <p>I have an array of six elements (<code>$categories = array('dinner','casual','wedding')</code>) and I would like to make a SQL query that would look like this:</p> <p><code>SELECT * FROM produts WHERE id = /* values of array $categories... eg. (dinner || casual || wedding) */ </code></p>
39,651,450
0
How to add dictionary when we long press a word in android webview. <p>I wish to implement dictionary option in android webview text when webview is showing article from any online publication. When we long press on any word, it shows the option for 'search', 'copy' etc. I wish if I can add one option for dictionary there so that user can access dictionary either installed in phone or online one. Also if option for adding specific dictionary within the application will do even better. I tried to search a lot but stuck there and couldnt get an implementation strategy. </p>
664,151
0
<p>To answer the question in your title, I would wrap the <code>SocketOutputStream</code> in a <code>BufferedOutputStream</code> in a <code>DataOutputStream</code> and use the latter's <code>writeInt()</code> method repeatedly. Or you could use <code>ObjectOutputStream</code> in place of <code>DataOutputStream</code>, and serialize the array: <code>objOutStream.writeObject(theArray)</code>. To read it in again on the other end, just wrap the <code>SocketInputStream</code> in (1) a <code>DataInputStream</code> and use <code>readInt()</code> repeatedly, or (2) a <code>ObjectInputStream</code> and use <code>readObject()</code>.</p> <p>(If you don't have to interoperate with other languages, <code>Object*Stream</code> is easier on you)</p>