pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
28,315,071 | 0 | CakePHP containable behaviour with conditions <p>From the following array, I need that <code>Exercise</code> array should contain <code>UserExercise</code> array only if in <code>UserExercise</code> array <code>user_id = 1</code></p> <pre><code>Array ( [0] => Array ( [ExerciseGroup] => Array ( [id] => 1 [name] => Chests [date_added] => 2015-01-30 00:00:00 [date_updated] => 2015-02-02 19:30:49 ) [Exercise] => Array ( [0] => Array ( [id] => 9 [group_id] => 1 [name] => Dumbell [date_added] => 2015-02-02 15:00:49 [date_updated] => 2015-02-02 19:30:49 [UserExercise] => Array ( [0] => Array ( [id] => 1 [user_id] => 2 [exercise_id] => 9 [sets] => 3 [reps] => 4 [mon] => [tue] => [wed] => 1 [thr] => [fri] => [sat] => [sun] => [date_added] => 2015-02-03 00:00:00 [date_updated] => 2015-02-03 19:18:56 ) ) ) [1] => Array ( [id] => 10 [group_id] => 1 [name] => Bench Press [date_added] => 2015-02-02 15:00:49 [date_updated] => 2015-02-02 19:30:49 [UserExercise] => Array ( ) ) [2] => Array ( [id] => 11 [group_id] => 1 [name] => Parallel [date_added] => 2015-02-02 15:00:49 [date_updated] => 2015-02-02 19:30:49 [UserExercise] => Array ( ) ) ) ) ) </code></pre> <p>ExerciseGroup Model</p> <pre><code><?php class ExerciseGroup extends AppModel { public $name = 'ExerciseGroup'; public $actsAs = array('Containable'); public $hasMany = array('Exercise' => array( 'className' => 'Exercise', 'foreignKey' => 'group_id', 'dependent' => true )); } ?> </code></pre> <p>Exercise Model:</p> <pre><code><?php class Exercise extends AppModel { public $name = 'Exercise'; public $actsAs = array('Containable'); public $hasMany = array('UserExercise' => array( 'className' => 'UserExercise', 'foreignKey' => 'exercise_id', 'dependent' => true )); } ?> </code></pre> <p>Controller Query I tried:</p> <pre><code>$this -> paginate = array( 'conditions' => array(), 'contain' => array('ExerciseGroup' => array('conditions' => array('Exercise.UserExercise.user_id' => 1))), 'recursive' => 2, 'limit' => $this -> ExerciseGroup -> find('count') ); $exercises = $this -> paginate('ExerciseGroup'); </code></pre> <p>The Error is get is <code>Model "ExerciseGroup" is not associated with model "ExerciseGroup" [CORE\Cake\Model\Behavior\ContainableBehavior.php, line 342]</code></p> |
14,048,600 | 0 | jQuery: Multiple Checkbox Select and price determination <p>I'm trying to create a "digital breakfast/lunch/dinner list", where over the space of 2 weeks parents can select whether or not their child needs to have breakfast, lunch and/or dinner. These values will be multiplied against different rates for each meal to determine an invoice amount. The parent clicks a submission button which returns the total value. Here's what I've got so far:</p> <p>Web Form:</p> <pre><code><input type="checkbox" name="breakfast"> <input type="checkbox" name="lunch"> <input type="checkbox" name="dinner"> </code></pre> <p>There are 14 days, with this repeated for each. So in total I have 42 checkboxes.</p> <p>jQuery:</p> <pre><code>var numBreakfast = $("input:checkbox[name='breakfast']").size(); var numLunch = $("input:checkbox[name='lunch']").size(); var numDinner = $("input:checkbox[name='dinner']").size(); var totalPrice = numBreakfast * priceBreakfast + numLunch * priceLunch + numDinner * priceDinner </code></pre> <p>I think I've got this correct, but when I call the total I keep getting $0.00 returned.</p> <p>Any ideas?</p> |
4,064,009 | 0 | <p>Concerning your first question, have a look at the following SQL code:</p> <p>CREATE TABLE 'test' ('col' varchar(10) NOT NULL, 'col2' varchar(25) NULL);</p> <p>ALTER TABLE 'test' ADD CONSTRAINT 'U' UNIQUE ('col');</p> <p>Here a table "test" is created, containing a collumn "col" which has 10 digits and must be unique.</p> <p>(unfortunately I can't help you concerning SugarCRM)</p> |
18,781,251 | 0 | <p>Set checked to <code>false</code>, then call <code>button('refresh')</code>:</p> <pre><code>$(this).prop('checked', false).button('refresh'); </code></pre> <h3><a href="http://jsfiddle.net/mbAwC/16/" rel="nofollow">Here's a fiddle</a></h3> |
23,678,500 | 1 | Classifying new occurances - Multinomial Naive Bayes <p>So I have currently trained a Multinomial Naive Bayes classifier, using <code>[SKiLearn][1]</code> Now what I can do is classify test data by using predict.</p> <p>But if I want to run this every night, as a script, I clearly need to always have a classifier already trained up! Now what I'd like to be able to do, is take classifier coefficients, informative words, and use these to classify new data. </p> <p>Is this possible - to develop my own method for classification? Or should I be simply training the SkiLearn classifier nightly?</p> <p>EDIT: One thing, it seems I can do, is retain and <a href="http://stackoverflow.com/questions/10592605/save-naivebayes-classifier-to-disk-in-scikits-learn">save my trained classifier</a>. </p> <p>However with logistic regression, you can take the coefficients and use these on new data. Is there anything similar to this for NB?</p> |
10,047,304 | 0 | <p>Fix your query as below:</p> <pre><code>"create table option (id integer primary key autoincrement," + "volume boolean not null, vibrate boolean not null, theme text not null); " + "create table score (id integer primary key autoincrement," + "score text not null, difficulty text not null, date date not null);"; </code></pre> <p>You have missed semi-colon and left an extra comma in your query</p> |
41,054,871 | 1 | Python Word Count Test Cases <p>Hi I am trying to submit python word count program and I get the following errors now problem is there is not any data in python word count which is having london bridge is falling down etc Test run works fine only submit is problem. Please guide.</p> <pre class="lang-py prettyprint-override"><code>import logging import sys import string from util import logfile logging.basicConfig(filename=logfile, format='%(message)s', level=logging.INFO, filemode='w') def word_count(): # For this exercise, write a program that serially counts the number of occurrences # of each word in the book Alice in Wonderland. # # The text of Alice in Wonderland will be fed into your program line-by-line. # Your program needs to take each line and do the following: # 1) Tokenize the line into string tokens by whitespace # Example: "Hello, World!" should be converted into "Hello," and "World!" # (This part has been done for you.) # # 2) Remove all punctuation # Example: "Hello," and "World!" should be converted into "Hello" and "World" # # 3) Make all letters lowercase # Example: "Hello" and "World" should be converted to "hello" and "world" # # Store the the number of times that a word appears in Alice in Wonderland # in the word_counts dictionary, and then *print* (don't return) that dictionary # # In this exercise, print statements will be considered your final output. Because # of this, printing a debug statement will cause the grader to break. Instead, # you can use the logging module which we've configured for you. # # For example: # logging.info("My debugging message") # # The logging module can be used to give you more control over your # debugging or other messages than you can get by printing them. Messages # logged via the logger we configured will be saved to a # file. If you click "Test Run", then you will see the contents of that file # once your program has finished running. # # The logging module also has other capabilities; see # https://docs.python.org/2/library/logging.html # for more information. word_counts = {} for line in sys.stdin: data = line.strip().split(" ") for i in data: key = i.translate(string.maketrans("",""),string.punctuation).lower() if key in word_counts.keys(): word_counts[key] += 1 else: word_counts[key] = 1 print word_counts word_count() </code></pre> <p>Evaluating...</p> <blockquote> <p>[FAILED] Wrong word found: 'a' where it should be 'ccc' Inputs: ('a bb bb ccc ccc ccc dddd dddd dddd dddd', 2) Output: [('dddd', 4), ('a', 1)]</p> <p>[FAILED] Wrong word found: 'bridge' where it should be 'falling' Inputs: ('london bridge is falling down falling down falling down london bridge is falling down my fair lady', 5) Output: [('down', 4), ('bridge', 2), ('falling', 4), ('fair', 1), ('is', 2)]</p> </blockquote> |
11,937,074 | 0 | How to launch caching of many pages on Zend? <p>I have an "article" controller and a "view" action. My action takes an id parameter, allowing the visitor to view the article with a specific id (get the info from a mysql database). I want to create a script that generates all my caches instantly. Indeed, I don't want to wait that my visitors visit the articles for my cache files to be generated. Any hint of how I can do this?</p> |
32,943,945 | 0 | What does pipe character do in vim command mode? (for example, :vimgrep /pattern/ file | another_cmd) <p>What does pipe character do in vim command mode?</p> <p>For example, <code>:vimgrep /pattern/ file | copen</code></p> <p>Does it act like a pipe in Linux Command Line? Contents of <code>vimgrep</code> gets piped to <code>copen</code>?</p> <p>Or does it separate commands like <code>;</code> in Command Line?</p> |
22,402,603 | 0 | test browser supports the style or not <p>I can do the following to check if the browser doesn't support column-count css3 property then use my own code:</p> <pre><code>if (!('WebkitColumnCount' in document.body.style || 'MozColumnCount' in document.body.style || 'OColumnCount' in document.body.style || 'MsColumnCount' in document.body.style || 'columnCount' in document.body.style)) {//my own code here} </code></pre> <p>But how can I check that background-image animation support?</p> <p>This type of changing image source with css3 only works on chrome browsers.</p> <pre><code>0%{background-image: url(image-1);} 50%{background-image: url(image-2);} 100%{background-image: url(image-3);} </code></pre> <p>So, I wanted to know is there any technique that we can test that it is supported by the browser or not?</p> <p><strong>Update</strong></p> <p>I just tried like this code which is even not checking @keyframes style support:</p> <pre><code>if (('@keyframes' in document.body.style || '@-webkit-keyframes' in document.body.style)) { //if(!('from' in @keyframes || 'from' in @webkit-keyframes)){ //code in here alert('test'); //} } </code></pre> <p>So even can I not test that @keyframes supported by browser or not?</p> <hr> <p><strong>Solution:</strong></p> <p>I've found from <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations/Detecting_CSS_animation_support" rel="nofollow">mdn</a></p> <pre><code>var animation = false, animationstring = 'animation', keyframeprefix = '', domPrefixes = 'Webkit Moz O ms Khtml'.split(' '), pfx = ''; if( elm.style.animationName !== undefined ) { animation = true; } if( animation === false ) { for( var i = 0; i < domPrefixes.length; i++ ) { if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) { pfx = domPrefixes[ i ]; animationstring = pfx + 'Animation'; keyframeprefix = '-' + pfx.toLowerCase() + '-'; animation = true; break; } } } </code></pre> |
13,523,520 | 0 | <p>Yes, so once you download the app, go to the settings and click on the rate and review button. You can also directly search the app in the store and rate/review it there after you've installed it.</p> <p>Arun</p> |
17,346,542 | 0 | <p>Have you tried creating your busy indicator object globally rather than inside this specific function (I also don't understand the scope of this "initialize" function... I assume this is app-specific code).</p> <p>In your app's .js file (yourProject\apps\yourApp\common\yourApp.js) do something like this:</p> <pre><code>var busy; function wlCommonInit() { busy = new WL.BusyIndicator(); </code></pre> <p>Then, in your <code>initialize()</code> function, call <code>busy.show()</code> and <code>busy.hide()</code> when required.</p> |
3,139,382 | 0 | regular expression that extracts words from a string <p>I want to extract all words from a java String.</p> <p>word can be written in any european language, and does not contain spaces, only alpha symbols.</p> <p>it can contain hyphens though.</p> |
36,535,948 | 0 | Fluent Assertions: Approximately compare two 2D rectangular arrays <p>I'm able to approximately compare two 2D rectangular arrays in Fluent Assertions like this:</p> <pre><code>float precision = 1e-5f; float[,] expectedArray = new float[,] { { 3.1f, 4.5f}, { 2, 4} }; float[,] calculatedArray = new float[,] { { 3.09f, 4.49f}, { 2, 4} }; for (int y = 0; y < 2; ++y) { for (int x = 0; x < 2; ++x) { calculatedArray[y,x].Should().BeApproximately(expectedArray[y,x], precision); } } </code></pre> <p>but is there a cleaner way of achieving this (without the for loops)? For example, something in the same vein as this (which is for 1D arrays):</p> <pre><code>double[] source = { 10.01, 8.01, 6.01 }; double[] target = { 10.0, 8.0, 6.0 }; source.Should().Equal(target, (left, right) => Math.Abs(left-right) <= 0.01); </code></pre> <p>The above solution for a 1D array comes from the question: <a href="http://stackoverflow.com/questions/17054636/fluent-assertions-compare-two-numeric-collections-approximately">Fluent Assertions: Compare two numeric collections approximately</a></p> |
27,728,804 | 0 | <p>First of all, <code>Where(x => x is Video)</code> can be replaced by <code>OfType<Video>()</code>.<br> Second, for fluent syntax it's better to use <code>ParallelEnumerable.ForAll</code> extension method:</p> <pre><code>media.OfType<Video>() .AsParallel() .ForAll(this.Update) </code></pre> |
29,137,028 | 0 | <p>That is not the intended use of exceptions and is bad practice. Exceptions are intended for those conditions that are not forseable and/or outside of the control of the current developer. </p> <p>In your case you can predict that some users will not be 'test' users, otherwise why have the test. What you are doing here is to use an exception just to return an alternative message that you then echo. So you do not need to throw an exception, simply return an alternative message that indicates this.</p> |
24,704,323 | 0 | <p>I've got a similar error message. I solved it by adding <code><form method="post" {{ form_enctype(form) }}></code> to my form tag.</p> |
28,712,813 | 0 | <pre><code>s = ["hello how are you?", "I am fine.What are you doing?", "Hey, I am having a haircut. See you at Hotel KingsMen at 10 am."] s.join.scan(/Hotel\s(.+)?\sat\s(.+)?\./).flatten #=> ["KingsMen", "10 am"] </code></pre> <p>Regex description:</p> <ol> <li><p><code>\s</code> - any whitespace character, </p></li> <li><p><code>.</code> - any character, <code>.+</code> - one or more of any character, <code>()</code> - capture everything inside, so <code>(.+)</code> - capture one or more characters</p></li> <li><p><code>a?</code> means zero or one of <code>a</code></p></li> </ol> |
25,591,225 | 0 | <p>Another difference is that <code>openFileOutputStream</code> opens / creates a file in the the device's "internal" storage.</p> <p>Reference:</p> <ul> <li>Android API Guides > <a href="http://developer.android.com/guide/topics/data/data-storage.html#filesInternal" rel="nofollow">Storage Options</a></li> </ul> |
6,846,405 | 0 | CSV file generation error <p>I'm working on a project for a client - a wordpress plugin that creates and maintains a database of organization members. I'll note that this plugin creates a new table within the wordpress database (instead of dealing with the data as custom_post_type meta data). I've made a lot of modifications to much of the plugin, but I'm having an issue with a feature (that I've left unchanged).</p> <p>One half of this feature does a csv import and insert, and that works great. The other half of this sequence is a feature to download the contents of this table as a csv. This part works fine on my local system, but fails when running from the server. I've poured over each portion of this script and everything seems to make sense. I'm, frankly, at a loss as to why it's failing.</p> <p>The php file that contains the logic is simply linked to. The file:</p> <pre><code><?php // initiate wordpress include('../../../wp-blog-header.php'); // phpinfo(); function fputcsv4($fh, $arr) { $csv = ""; while (list($key, $val) = each($arr)) { $val = str_replace('"', '""', $val); $csv .= '"'.$val.'",'; } $csv = substr($csv, 0, -1); $csv .= "\n"; if (!@fwrite($fh, $csv)) return FALSE; } //get member info and column data $table_name = $wpdb->prefix . "member_db"; $year = date ('Y'); $members = $wpdb->get_results("SELECT * FROM ".$table_name, ARRAY_A); $columns = $wpdb->get_results("SHOW COLUMNS FROM ".$table_name, ARRAY_A); // echo 'SQL: '.$sql.', RESULT: '.$result.'<br>'; //output headers header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"members.csv\""); //open output stream $output = fopen("php://output",'w'); //output column headings $data[0] = "ID"; $i = 1; foreach ($columns as $column){ //DIAG: echo '<pre>'; print_r($column); echo '</pre>'; $field_name = ''; $words = explode("_", $column['Field']); foreach ($words as $word) $field_name .= $word.' '; if ( $column['Field'] != 'id' && $column['Field'] != 'date_updated' ) { $data[$i] = ucwords($field_name); $i++; } } $data[$i] = "Date Updated"; fputcsv4($output, $data); //output data foreach ($members as $member){ // echo '<pre>'; print_r($member); echo '</pre>'; $data[0] = $member['id']; $i = 1; foreach ($columns as $column){ //DIAG: echo '<pre>'; print_r($column); echo '</pre>'; if ( $column['Field'] != 'id' && $column['Field'] != 'date_updated' ) { $data[$i] = $member[$column['Field']]; $i++; } } $data[$i] = $member['date_updated']; //echo '<pre>'; print_r($data); echo '</pre>'; fputcsv4($output, $data); } fclose($output); ?> </code></pre> <p>So, obviously, a routine wherein a query is run, <code>$output</code> is established with <code>fopen</code>, each row is then formatted as comma delimited and <code>fwrite</code>d, and finally the file is <code>fclose</code>d where it gets pushed to a local system.</p> <p>The error that I'm getting (from the server) is </p> <pre><code>Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found. </code></pre> <p>But it clearly is getting found, its just failing. If I enable <code>phpinfo()</code> (PHP Version 5.2.17) at the top of the file, I definitely get a response - notably <code>Cannot modify header information</code> (I'm pretty sure because <code>phpinfo()</code> has already generated a header). All the expected data does get printed to the bottom of the page (after all the phpinfo diagnostics), however, so that much at least is working correctly.</p> <p>I am guessing there is something preventing the <code>fopen</code>, <code>fwrite</code>, or <code>fclose</code> functions from working properly (a server setting?), but I don't have enough experience with this to identify exactly what the problem is. </p> <p>I'll note again that this works exactly as expected in my test environment (localhost/XAMPP, netbeans).</p> <p>Any thoughts would be most appreciated. </p> <h3>update</h3> <p>Ok - spent some more time with this today. I've tried each of the suggested fixes, including @Rudu's <code>writeCSVLine</code> fix and @Fernando Costa's <code>file_put_contents()</code> recommendation. The fact is, they all work locally. Either just <code>echo</code>ing or the <code>fopen</code>,<code>fwrite</code>,<code>fclose</code> routine, doesn't matter, works great. </p> <p>What does seem to be a problem is the inclusion of the <code>wp-blog-header.php</code> at the start of the file and then the additional <code>header()</code> calls. (The path is definitely correct on the server, btw.)</p> <p>If I comment out the <code>include</code>, I get a csv file downloaded with some errors planted in it (because <code>$wpdb</code> doesn't exist. And if comment out the <code>header</code>s, I get all my data printed to the page. </p> <p>So... any ideas what could be going on here?<br> Some obvious conflict of the wordpress environment and the proper creation of a file. </p> <p>Learning a lot, but no closer to an answer... Thinking I may need to just avoid the wordpress stuff and do a manual sql query. </p> |
20,698,630 | 0 | <p>An accept handler may only take an error code as a parameter, see: <a href="http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/AcceptHandler.html" rel="nofollow">AcceptHandler</a>. </p> <p>I recommend making <code>acceptor</code> a member of <code>CServerSocket</code> then changing the call to <code>async_accept</code> to:</p> <pre><code>acceptor.async_accept(*socket, std::bind(&CServerSocket::OnAccept, this, std::placeholders::_1)); </code></pre> <p>and accessing <code>acceptor</code> within the <code>OnAccept</code> member function.</p> |
2,944,991 | 0 | rails backgroundjob running jobs in parallel? <p>I'm very happy with By so far, only I have this one issue:</p> <p>When one process takes 1 or 2 hours to complete, all other jobs in the queue seem to wait for that one job to finish. Worse still is when uploading to a server which time's out regularly.</p> <p>My question: is Bj running jobs in parallel or one after another?</p> <p>Thank you, Damir</p> |
29,885,134 | 0 | <p>The problem is that you're assigning the return value of <code>volunteer.time_in.push</code> back to <code>volunteer.time_in</code>. The return value is the new length of the array, not the array itself.</p> <p>So change that line to just:</p> <pre><code>volunteer.time_in.push(date); </code></pre> |
38,318,805 | 0 | Count the number of occurrences of each word <p>I'm trying to count the number of occurrences of each word in the function <code>countWords</code> I believe i started the for loop in the function properly but how do I compare the words in the arrays together and count them and then delete the duplicates? Isn't it like a fibonacci series or am I mistaken? Also <code>int n</code> has the value of 756 because thats how many words are in the array and <code>wordsArray</code> are the elements in the array. </p> <pre><code>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> int *countWords( char **words, int n); int main(int argc, char *argv[]) { char buffer[100]; //Maximum word size is 100 letters FILE *textFile; int numWords=0; int nextWord; int i, j, len, lastChar; char *wordPtr; char **wordArray; int *countArray; int *alphaCountArray; char **alphaWordArray; int *freqCountArray; char **freqWordArray; int choice=0; //Check to see if command line argument (file name) //was properly supplied. If not, terminate program if(argc == 1) { printf ("Must supply a file name as command line argument\n"); return (0); } //Open the input file. Terminate program if open fails textFile=fopen(argv[1], "r"); if(textFile == NULL) { printf("Error opening file. Program terminated.\n"); return (0); } //Read file to count the number of words fscanf(textFile, "%s", buffer); while(!feof(textFile)) { numWords++; fscanf(textFile, "%s", buffer); } printf("The total number of words is: %d\n", numWords); //Create array to hold pointers to words wordArray = (char **) malloc(numWords*sizeof(char *)); if (wordArray == NULL) { printf("malloc of word Array failed. Terminating program.\n"); return (0); } //Rewind file pointer and read file again to create //wordArray rewind(textFile); for(nextWord=0; nextWord < numWords; nextWord++) { //read next word from file into buffer. fscanf(textFile, "%s", buffer); //Remove any punctuation at beginning of word i=0; while(!isalpha(buffer[i])) { i++; } if(i>0) { len = strlen(buffer); for(j=i; j<=len; j++) { buffer[j-i] = buffer[j]; } } //Remove any punctuation at end of word len = strlen(buffer); lastChar = len -1; while(!isalpha(buffer[lastChar])) { lastChar--; } buffer[lastChar+1] = '\0'; //make sure all characters are lower case for(i=0; i < strlen(buffer); i++) { buffer[i] = tolower(buffer[i]); } //Now add the word to the wordArray. //Need to malloc an array of chars to hold the word. //Then copy the word from buffer into this array. //Place pointer to array holding the word into next //position of wordArray wordPtr = (char *) malloc((strlen(buffer)+1)*sizeof(char)); if(wordPtr == NULL) { printf("malloc failure. Terminating program\n"); return (0); } strcpy(wordPtr, buffer); wordArray[nextWord] = wordPtr; } //Call countWords() to create countArray and replace //duplicate words in wordArray with NULL countArray = countWords(wordArray, numWords); if(countArray == NULL) { printf("countWords() function returned NULL; Terminating program\n"); return (0); } //Now call compress to remove NULL entries from wordArray compress(&wordArray, &countArray, &numWords); if(wordArray == NULL) { printf("compress() function failed; Terminating program.\n"); return(0); } printf("Number of words in wordArray after eliminating duplicates and compressing is: %d\n", numWords); //Create copy of compressed countArray and wordArray and then sort them alphabetically alphaCountArray = copyCountArray(countArray, numWords); freqCountArray = copyCountArray(alphaCountArray, numWords); int *countWords( char **wordArray, int n) { return NULL; int i=0; int n=0; for(i=0;i<n;i++) { for(n=0;n<wordArray[i];n++) { } } } </code></pre> |
37,535,624 | 1 | condition parameter adjustment <p>I try to use 'IF' in python in order to achieve the algorithm that can automatically ajust the value of a parameter in 'IF' according to some stock trasactions. </p> <pre><code>if self.sellcount==0 and int(time.time())-self.programstarttime>600: if cur_sum/total_sum>0.15: Other Code else: if cur_sum/total_sum>0.35: Other Code </code></pre> <p>I try to achieve that if my algorithm do not sell any stock for 10 minutes, the algorithm can automatically change the condition from 0.35 to 0.15. However, the code above will change from 0.15 to 0.35 after selling stocks for one time. I want the code to keep 0.15 after selling stocks for one time.</p> |
34,235,714 | 0 | <p>Something like below<br> I removed WHERE clause and modified rows for d.month and sum(d.spend)<br> Haven't tested, but should be close to working version</p> <pre><code>SELECT d.account_id, d.product, CASE WHEN d.month >= DATE_ADD(CURRENT_DATE() ,-5,"MONTH") THEN d.month ELSE NULL END AS d_month, SUM(CASE WHEN d.month >= DATE_ADD(CURRENT_DATE() ,-5,"MONTH") THEN d.spend ELSE 0 END) AS d_spend, u.lifetime_product_spend FROM FLATTEN(data_source, product) d LEFT JOIN ( SELECT account_id, product, SUM(product_spend)/1000000 lifetime_product_spend FROM usage GROUP BY account_id, product ) u ON (d.account_id = u.account_id AND d.product = u.product) GROUP BY 1, 2, 3, 5 </code></pre> |
6,135,346 | 0 | <p>Almost any framework, if used properly, will do. Spring / Spring MVC is a good choice:</p> <ul> <li>it supports custom url mappings</li> <li>ORM support</li> <li>Caching support - this will be very important for your scalability</li> </ul> |
30,883,647 | 0 | <p><strong>For prerecorded audio:</strong> in the Android zip we only included the english files - in the iOS zip we've included the whole language set. </p> <p>Either grab the languages from the iOS demo or download them from <a href="https://www.dropbox.com/sh/0d4qx8xpeka6gh4/AADtdtsEFAezvvKdG3M7hKjja?dl=0" rel="nofollow">here</a> (replace those in the SKMaps.zip/Advisor/Languages folder)</p> <p><strong>For text-to-speech:</strong> you already have the config files in the default SKMaps.zip so no additinal work is needed - just switch the advisor language and make sure that the TTS options is used and it should work (see the <a href="http://developer.skobbler.com/getting-started/android#sec017" rel="nofollow">documentation</a> chapter for details)</p> |
22,002,428 | 0 | <p>Yes. You are doing the correct thing. Thats the short answer.</p> <p>However, if you are new to git, you might get caught or stuck, so I'll walk you through the process here.</p> <p>If you have not yet committed your changes you can do the following on the remote:</p> <pre><code>git stash git checkout -b my-new-branch-name master git stash apply git add . git commit -m 'committing new changes' git push origin my-new-branch-name </code></pre> <p>The git-stash command just stores your changes temporarily so you can checkout safely, and then git-stash apply reapplies them. This only works for uncommitted changes.</p> <p>If you have already committed your changes to master, you will want to simply create the branch the same way your original post says, but then you probably also want to remove your changes from the local master branch.</p> <pre><code>git branch my-new-branch-name master git reset --hard origin/master </code></pre> <p>This will create your new branch with the new commits, and then reset your local master branch to whatever was in the remote master branch.</p> <p>Now with that done, you can go to your local machine (or any other clone of the same repo), and pull down that branch.</p> <pre><code>git fetch git checkout my-new-branch-name </code></pre> |
28,989,357 | 0 | Unable to click radio button in Internet explorer using Selenium webdriver <p>I am not able to get the radio button clicked using Selenium web driver.</p> <p>The html is as follows</p> <pre><code><input name="PersonalDetails.Paperless" class="input-validation-error" id="Paperless" type="radio" data-val-required="Contract notes selection is required" data-val="true" value="true"/> </code></pre> <p>The code to click is below. It works in Chrome and FireFox but not in Ie</p> <pre><code>driver.FindElement(By.CssSelector("label[for='OnlineAndPost']")).Click(); </code></pre> |
19,583,109 | 0 | Embed Google+ domain API in google site <p>I am new in Google+ API and glad that Google finally released Google+ domain API. I have read the documentation and follow through the 'get started' but stumbled on the quick start app that can only use Java and Python. I was expecting that I would be able to embed the Google+ domain API in the company's google site as an app or gadget or widget.</p> <p>Has anyone had similar problem or find the solution?</p> |
25,770,507 | 0 | Creating instances of a covariant type class from instances of a non-covariant one <p>Suppose I've got a simple type class whose instances will give me a value of some type:</p> <pre><code>trait GiveMeJustA[X] { def apply(): X } </code></pre> <p>And I've got some instances:</p> <pre><code>case class Foo(s: String) case class Bar(i: Int) implicit object GiveMeJustAFoo extends GiveMeJustA[Foo] { def apply() = Foo("foo") } implicit object GiveMeJustABar extends GiveMeJustA[Bar] { def apply() = Bar(13) } </code></pre> <p>Now I have a similar (but unrelated) type class that does the same thing but is covariant in its type parameter:</p> <pre><code>trait GiveMeA[+X] { def apply(): X } </code></pre> <p>In its companion object we tell the compiler how to create instances from instances of our non-covariant type class:</p> <pre><code>object GiveMeA { implicit def fromGiveMeJustA[X](implicit giveMe: GiveMeJustA[X]): GiveMeA[X] = new GiveMeA[X] { def apply() = giveMe() } } </code></pre> <p>Now I'd expect <code>implicitly[GiveMeA[Foo]]</code> to compile just fine, since there's only one way to get a <code>GiveMeA[Foo]</code> given the pieces we have here. But it doesn't (at least not on either 2.10.4 or 2.11.2):</p> <pre><code>scala> implicitly[GiveMeA[Foo]] <console>:16: this.GiveMeA.fromGiveMeJustA is not a valid implicit value for GiveMeA[Foo] because: hasMatchingSymbol reported error: ambiguous implicit values: both object GiveMeJustAFoo of type GiveMeJustAFoo.type and object GiveMeJustABar of type GiveMeJustABar.type match expected type GiveMeJustA[X] implicitly[GiveMeA[Foo]] ^ <console>:16: error: could not find implicit value for parameter e: GiveMeA[Foo] implicitly[GiveMeA[Foo]] ^ </code></pre> <p>If we get rid of our irrelevant <code>GiveMeJustA</code> instance, it works:</p> <pre><code>scala> implicit def GiveMeJustABar: List[Long] = ??? GiveMeJustABar: List[Long] scala> implicitly[GiveMeA[Foo]] res1: GiveMeA[Foo] = GiveMeA$$anon$1@2a4f2dcc </code></pre> <p>This is in spite of the fact that there's no way we can apply <code>GiveMeA.fromGiveMeJustA</code> to this instance to get a <code>GiveMeA[Foo]</code> (or any subtype of <code>GiveMeA[Foo]</code>).</p> <p>This looks like a bug to me, but it's possible that I'm missing something. Does this make any sense? Is there a reasonable workaround?</p> |
21,864,780 | 0 | <p>If you want to center an element in a wrapper that is smaller than the element and you can use <code>absolute</code>:</p> <pre><code> #page{ position: absolute; width: 1600px; top: 0; left:-100%; right:-100%; margin-left: auto; margin-right: auto; } </code></pre> <p>example:<a href="http://jsfiddle.net/pavloschris/T5d8W/" rel="nofollow">http://jsfiddle.net/pavloschris/T5d8W/</a></p> |
5,848,186 | 0 | regex to replace 0 in list but not 0 of 10, 20, 30, etc. - using js replace <p>I'm trying to create a regex to replace zeros in list with an empty value but not replace the zeros in ten, twenty, thirty, etc.</p> <blockquote> <p>list = 0,1,0,20,0,0,1,,1,3,10,30,0</p> <p>desired list = ,1,,20,,,1,,1,3,10,30,</p> </blockquote> <p>Using this in the javascript replace function</p> <p>Any help/tips appreciated!</p> |
914,492 | 0 | Detect when resources loaded via ajax <p>I recently asked how to detect when all resources of a page have been loaded, such as images and stylesheets. The answer came back, use the $(window).load(); method in jQuery.</p> <p>My question now is how do I detect when content is done loading via AJAX. AJAX injects some img elements, say, into the DOM... how can I tell when those images have finished loading?</p> |
34,490,799 | 0 | Cannot read property 'addEventListener' of undefined <pre><code> function asign(id){ return document.getElementById(id) ; } var b = ['p','q','r','s','t','u','v']; var a = ['fname','lname','email','password','r_password','g_m',"g_f"] ; for (i=0;i<a.length;i++) { var x = {} ; x[b[i]] = asign(a[i]) ; x[i].addEventListener('click', function() { alert(x[i].value) ;} ,false) ; } </code></pre> <p>I want just array of variables and IDs asign with them in for loop .</p> |
13,499,017 | 0 | Tracking php process on framework <p>I have a php framework is running on linux machine basicly every requests redirect to index.php by .htaccess </p> <pre><code>Options +FollowSymLinks IndexIgnore */* RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !.*jpg$|!.*gif$|!.*png$|!.*jpeg$|!.*bmp$ RewriteRule . index.php </code></pre> <p>One of my php started to run %100 CPU i want to track which progress is that but when i check process with </p> <p>ps aux | grep 23791</p> <pre><code>user 23791 0.3 0.8 30460 15288 ? S 12:32 0:01 /usr/bin/php /home/user/public_html/index.php </code></pre> <p>As normal, request redirect to index.php.But i have to find which request is this.</p> <p>Is there any way to debug this problem ?</p> <p>Thanks.</p> |
32,578,695 | 0 | Sublime text2, Replace all messes up the upper-case lower-case <p>The replace all option messes up the lower-case formation in Sublime Text 2. For example: </p> <p>When I want to replace all the classes named "example1" to "hidethis"<br> I get "hideThis". </p> <p>This is getting annoying, especially when I am going to do this procedure to URLs. </p> <p>Is there any way to disable that option?</p> |
24,156,219 | 0 | Why won't the logged in name display? <p>I'm trying to show a welcome message to the logged in user that says "Hello Jordan" for example. I can't seem to figure out what I'm doing wrong. I'll give below my admin index.php source code and an image of my MySQL database.</p> <p><img src="https://i.stack.imgur.com/Y1oAD.png" alt="MySQL Database"></p> <p><strong>admin index.php</strong></p> <pre><code><?php session_start(); include_once('../includes/connection.php'); if (isset($_SESSION['logged_in'])) { // Display Index ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Jordan CMS</title> <link rel="stylesheet" href="../assets/style.css" /> </head> <body> <div class="container"> <a href="index.php" id="logo">CMS</a> <? echo "Hello" . $_SESSION['username']; ?> <br /> <ol> <li><a href="add.php">Add Article</a></li> <li><a href="delete.php">Delete Article</a></li> <li><a href="pages.php">Add Page</a></li> <li><a href="users.php">Add Users</a></li> <li><a href="logout.php">Logout</a></li> </ol> </div> </body> </html> <?php } else { // Display Login if (isset($_POST['username'], $_POST['password'])) { $username = $_POST['username']; $password = md5($_POST['password']); if (empty($username) or empty($password)) { $error = 'All fields are required!'; } else { $query = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?"); $query->bindValue(1, $username); $query->bindValue(2, $password); $query->execute(); $num = $query->rowCount(); if ($num == 1) { // user entered correct details $_SESSION['logged_in'] = true; header('Location: index.php'); exit(); } else { // user entered false details $error = 'Incorrect details!'; } } } ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Jordan CMS</title> <link rel="stylesheet" href="../assets/style.css" /> </head> <body> <div class="container"> <a href="index.php" id="logo">CMS</a> <br /><br /> <form action="index.php" method="post" autocomplete="off"> <input type="text" name="username" placeholder="Username" /> <input type="password" name="password" placeholder="Password" /> <input type="submit" value="Login" /> </form> <?php if (isset($error)) { ?> <small style="color: #AA0000;"><?php echo $error; ?></small> <?php } ?> </div> </body> </html> <?php } ?> </code></pre> |
13,183,847 | 0 | Frames in Internet Explorer 9: CSS styles not loaded correctly <p>I have a web site with URL <a href="http://myapp.herokuapp.com/welcome.php" rel="nofollow">http://myapp.herokuapp.com/welcome.php</a> and I am redirecting a domain www.example.com to that PHP page as FRAME. When I try to load www.example.com from IE9, I get this error:</p> <pre><code>CSS3111: @font-face encountered unknown error. abeatbyKai.TTF </code></pre> <p>That font is placed here: <a href="http://myapp.herokuapp.com/common/fonts/abeatbyKai.TTF" rel="nofollow">http://myapp.herokuapp.com/common/fonts/abeatbyKai.TTF</a></p> <p>My CSS file is called from welcome.php like this:</p> <pre><code><link rel="stylesheet" href="css/iflikeu.welcome.0.1.css" type="text/css" /> </code></pre> <p>This is the code of my CSS:</p> <pre><code>@font-face { font-family: 'abeat'; src: url(../common/fonts/abeatbyKai.TTF); } </code></pre> <p>If I enter as <code>src: url('http://myapp.herokuapp.com/common/fonts/abeatbyKai.TTF');</code> still doesn't work.</p> <p>Another example: this image is loaded from welcome.php like this</p> <pre><code><a id="enLang" class="btn lang_flag" href="#" onclick="changeLanguage('userLangWelcome','en');"><img src="common/images/flags/en.png"/></a> </code></pre> <p>On the CSS file, this is the code:</p> <pre><code>.lang_flag img { width: 25px; height: 12px; vertical-align: middle; } </code></pre> <p>However, the image is not displayed. Just the button (<code>btn</code>).</p> <p><strong>This error only occurs in IE when there is a FRAME redirection.</strong> If I load directly <a href="http://myapp.herokuapp.com/welcome.php" rel="nofollow">http://myapp.herokuapp.com/welcome.php</a> from IE it works, and www.example.com from any other browser works as well.</p> <p>Any ideas? Thanks</p> |
24,056,952 | 0 | <p>To change the order status you must first enable order auto complete </p> <p><strong>system->config->sales</strong></p> <p>Disable Order Auto Complete set it to <strong>No</strong>,then go to the order in sales and click <strong>create invoice</strong> on the upper right handside then scroll the page to the bottom and click sent comment once your done with that click ship and click submit comment and the order status will change to complete.</p> |
28,775,570 | 0 | <p><strong>This XSD will allow your first example XML but not your second:</strong></p> <pre><code><?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="rule" type="RuleType"/> <xs:complexType name="RuleType"> <xs:choice> <xs:element name="setting" minOccurs="1" maxOccurs="unbounded" /> <xs:element ref="rule" minOccurs="1" maxOccurs="unbounded" /> </xs:choice> <xs:attribute name="condition" use="required"/> </xs:complexType> </xs:schema> </code></pre> <p><strong>Read the XSD like this:</strong> <em>Each <code>rule</code> can consist of either one or more <code>setting</code> elements or one or more other <code>rule</code> elements (recursively).</em></p> |
15,662,232 | 0 | <p>Ok, it's simple, I just misread the standard... From the C++ 11, §5 [expr] p9:</p> <blockquote> <p>Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. <em>The purpose is to yield a common type, which is also the type of the result.</em> This pattern is called the usual arithmetic conversions, ...</p> </blockquote> |
13,058,432 | 0 | <p>Generally you'll have to fetch back out the <code>id</code> values of the inserted rows. This is unless you can create another key that is used in place of that which can be procedurally generated in advance.</p> <p>While <code>INSERT</code> statements with multiple rows is significantly faster, the price you pay is a lack of precision. If your <code>id</code> values are issued sequentially, which is the default behavior, then you can be reasonably assured that the <code>LAST_INSERT_ID()</code> represents the ID of the first row inserted, so you could perhaps calculate the ID of the rows using the method you propose, though starting at index 0.</p> <p>Remember that multiple submissions do not affect the <code>LAST_INSERT_ID()</code> result because this value is per-connection. It is only changed if you perform a subsequent query on the same database handle. Operations in other requests will not affect it.</p> <p>Databases that are clustered or multi-master may issue non-sequential identifiers in which case this won't work. This is also unreliable in an <code>INSERT IGNORE</code> situation where the number of rows actually inserted could be less than the number of rows provided.</p> |
8,165,611 | 0 | <p>As shown on this site: <a href="http://jquerymobile.com/demos/1.0rc4/docs/api/events.html" rel="nofollow">http://jquerymobile.com/demos/1.0rc4/docs/api/events.html</a> there is an event called 'vmouseover' which stands a 'Normalized event for handling touch or mouseover events'.</p> <p>That is what you need, a possibility to change something on an event, which is in fact the mouseover (formerly known as hover).</p> <p>in Jquery 1.7 you could use </p> <pre><code>$("#yourElement").on("vmouseover", function(event){ $(this).css('color', 'green') $(this).css('background-color', 'red') }); </code></pre> <p>Apply this for your different elements in the calender and it should work.</p> <p>On(): <a href="http://api.jquery.com/on/" rel="nofollow">http://api.jquery.com/on/</a></p> <p>Css(): <a href="http://api.jquery.com/css/" rel="nofollow">http://api.jquery.com/css/</a></p> <p>and next time: provide some example code of what you already tried!!</p> <p>zY</p> |
23,224,993 | 0 | Reverse comma separated column values in SQL Server <p>I have following column which contains values separated by comma. How do I convert it to a result set which gives following out put in SQL Server?</p> <pre><code>DECLARE @TBL AS TABLE (COLUMN1 NVARCHAR(100)) INSERT INTO @TBL SELECT 'AUD,BRL,GBP,CAD,CLP' SELECT COLUMN1 FROM @TBL COLUMN1 ------- AUD,BRL,GBP,CAD,CLP </code></pre> <p>Result I wanted:</p> <pre><code>COLUMN1 ------- AUD BRL GBP CAD CLP </code></pre> |
13,240,074 | 0 | <p>Because its including the border width. Try:</p> <pre><code>.two{ width: 100%; margin: 0; padding: 0; border: 0; } </code></pre> |
32,434,008 | 0 | <p>There are a couple of options:</p> <ol> <li><p>Find out the ID of the category you want to to display, creating it if necessary. Then go to <code>System > Configuration > Web > Default Pages</code> in your admin and enter the following for the <code>Default web url</code> option: catalog/category/view/id/99 (where 99 is the id of the category).</p></li> <li><p>Create a normal CMS page, assign it as the homepage in <code>System > Configuration > Web > Default Pages</code> then call a category list.phtml with </p> <p><code>{{block type="catalog/product_list" category_id="99" template="catalog/product/list.phtml"}}</code></p></li> </ol> |
26,008,475 | 0 | <p>Base address for the board is assigned to the board by the operating system on start-up.</p> <p>OS does a scanning of the PCI devices in the board and allots each device a non-conflicting address range.ie. OS writes the BAR during startup. BAR is a register (Read/Writable) which is implemented inside the PCI card. OS uses configuration cycles to write the to the BAR.</p> |
21,386,161 | 0 | SVN confusion: "local add, incoming add upon merge" What do the words actually refer to? <p>I'm pretty new to subversion and the docs just aren't making sense to me. I was wondering if someone could break down this error message (from <code>svn st</code>) into plain English, as well as the other one I get <code>local delete, incoming delete upon merge</code>. </p> <p>To be precise about my question:</p> <ol> <li>What does <code>local add</code> (or <code>local delete</code>) refer to?</li> <li>What does <code>incoming add</code> (or <code>incoming delete</code>) refer to?</li> </ol> <p>What's mystifying to me is that the branch has absolutely nothing to do with the files that receive these errors. In other words, it doesn't add or delete any of these files locally (what I presume <code>local add/delete</code> means). Besides, if I had deleted the file locally, why would that be in conflict with a deletion in the repo (<code>incoming</code>) anyway?</p> <h2>Background Information</h2> <p>How I got here: I merged <code>trunk</code> into my <code>branch</code> and am trying to commit to my branch.</p> <p>P.S. I've (tried to) read <a href="http://stackoverflow.com/a/12874875/1431728">Managing trunk and feature branches: local delete, incoming delete upon merge</a>, but there's too much terminology. Other questions/answers I've read here on SO don't seem to apply or else are hard to understand.</p> |
36,522,860 | 0 | Android studio - unwanted tab dragging <p>I have an EXTREMELY annoying problem with Android Studio. Scenario:</p> <p>1) Switch tabs by clicking on a tab;</p> <p>2) First action in the new tab is to highlight some code via the mouse.</p> <p>In some cases dragging the mouse after the left click drags the tab as if I'd clicked on the tab and wanted to reposition it.</p> <p>I have not been able to discern any pattern to the phenomenon; for example, the time between switching tabs and the left click, the position of the left click.</p> <p>Any suggestions as to how to stop this?</p> |
4,562,298 | 0 | How to edit a file in Vim with all lines ending in ^M except the last line ending in ^M^J <p>I have a bunch of files that I need to look at. All lines in these files end in ^M (\x0D) except the very last line that ends in ^M^J (\x0D\x0A).</p> <p>Obviously, Vim determines the filetype to be DOS with the effect that the file's entire content is displayed on one single line like so:</p> <pre><code>some text foo^Mmore text and^Ma few control-m^Ms and more and more </code></pre> <p>Since I don't want to change the files' content: is there a setting in Vim that allows to look at these files with the new lines as I'd expect them to be?</p> |
8,416,523 | 0 | <p>To solve this problem, you need to figure out when the last quarter was. Then it's as easy as going back from there. Here's how I would do it:</p> <pre><code>$minute = idate('i'); $qdiff = $minute % 15; $lastQuarter = time() - $qdiff*60; echo date('Y-m-d H:i', $lastQuarter); </code></pre> <p>Try to figure out what my code is doing. Especially learn how to use the <a href="http://php.net/modulo" rel="nofollow">modulo</a> operator since it's very useful for a large set of numeric problems!</p> |
23,113,929 | 1 | Getting wrong output when working with tuple and list in Python <p>Trying to learn some python and I have the following task:</p> <ol> <li>Get a phrase from the user as an input.</li> <li>Check if the input contains a consonant from a consonants tuple\list that I declare in the code.</li> <li>For every consonant in the user input, print the consonant followed by the letter 'o' and the consonant itself.</li> </ol> <p>For example:</p> <ul> <li>User types the word 'something' as an input</li> <li>Output should be: 'sosomometothohinongog' (vowels do not exist in the consonant tuple and hence are not being appended).</li> </ul> <p>This is my code:</p> <pre><code>#!/usr/bin/python consonant = ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z') def isConsonant(user): for consonant in user: print consonant + "o" + consonant var = raw_input("type smth: ") isConsonant(var) </code></pre> <p>Here is what I get:</p> <pre><code>root@kali:~/py_chal# ./5.py type smth: test tot eoe sos tot </code></pre> <p>I have trouble with:</p> <ul> <li>The code treats vowels as consonants even though they are not in the list (notice the 'e').</li> <li>the 'print' method adds a new line - This was solved by importing the sys module and using 'write'.</li> </ul> <p>Any tips are greatly appreciated.</p> |
5,864,043 | 0 | Vector push_back in while and for loops returns SIGABRT signal (signal 6) (C++) <p>I'm making a C++ game which requires me to initialize 36 numbers into a vector. You can't initialize a vector with an initializer list, so I've created a while loop to initialize it faster. I want to make it push back 4 of each number from 2 to 10, so I'm using an int named fourth to check if the number of the loop is a multiple of 4. If it is, it changes the number pushed back to the next number up. When I run it, though, I get SIGABRT. It must be a problem with fourth, though, because when I took it out, it didn't give the signal. Here's the program:</p> <pre><code>for (int i; i < 36;) { int fourth = 0; fourth++; fourth%=4; vec.push_back(i); if (fourth == 0) { i++; } } </code></pre> <p>Please help!</p> |
37,793,857 | 1 | How to write this ajax call in Python <p>I have a ajax call but I have to call it from a Python script. This is the ajax call:</p> <pre><code>$.ajax({ dataType: "json", type: "GET", url: "saytts", data: {text: self.tts()} }); </code></pre> <p>I tried the package Requests but it's not working. Can someone translate this ajax call to a python request?</p> <p>Thank you.</p> |
24,660,202 | 0 | Dimplejs can deal with array of objects in each Json Object <p>I'm trying to create vis with array of objects and in each object there is another array of objects.</p> <pre><code> dataTest.push({"userId": d["userId"], "LevAvg": d["LevAvg"], "Changes": [{ "Day": formattedDate, "Lev": d["Lev"], "Class": d["Class"], "ActiveLocation": d["ActiveLocation"] }] }); </code></pre> <p>i can create vis in X axis userId Y axis is days and each of the values in the array of user is bubble?</p> |
3,720,883 | 0 | SCJP: can't widen and then box, but you can box and then widen <p>I'm studying for the SCJP exam and I ran into an issue I can't really wrap my head around.</p> <p>The book says you can't widen and then box, but you can box and then widen. The example for not being able to box is a method expecting a Long and the method being invoked with a byte.</p> <p>Their explanation is:</p> <blockquote> <p>Think about it…if it tried to box first, the byte would have been converted to a Byte. Now we're back to trying to widen a Byte to a Long, and of course, the IS-A test fails.</p> </blockquote> <p>But that sounds like box and then widen and not widen and then box to me.</p> <p>Could anyone clarify the whole box and widen vs widen and box for me because as it stands the book isn't exactly clear on the issue.</p> <p>Edit: To clarify: I'm talking about pages 252 and 253 of the SCJP sun certified programmer for java 6 book. <a href="http://books.google.be/books?id=Eh5NcvegzMkC&pg=PA252#v=onepage&q&f=false" rel="nofollow noreferrer">http://books.google.be/books?id=Eh5NcvegzMkC&pg=PA252#v=onepage&q&f=false</a></p> |
33,486,232 | 0 | <p>Why not using <a href="https://github.com/amirarcane/recent-images" rel="nofollow">recent-images</a> library? It makes thumbnails of device photos and set them in gridview, you can custom it for your purpose.</p> |
8,503,241 | 0 | <p>I think those are bugs in Xcode (you can try changing the font, but I don't think the direction can be changed).</p> <p>However, it is generally preferable to write your strings in English and then use internationalization (i18n) techniques to convert and display them in Arabic at runtime. A quick google revealed this <a href="http://rudifa.wordpress.com/2009/12/12/i18n-of-my-iphone-app/" rel="nofollow">blogpost</a>. This solves two issues:</p> <ol> <li>You can support any number of languages.</li> <li>You can store your Arabic text in a separate file and edit it with an external editor, making it easier to work with.</li> </ol> |
13,748,350 | 0 | <p>Just to extend @ohmi's answer:</p> <ol> <li>You cannot prevent passes from being installed on more than one device - e.g. if user enables iCloud for Passbook, the passes will get synced automatically across devices.</li> <li>Considering your links to pkpasses are public, you may want to consider introducing one-time download links, but while it can fill your needs just fine, users can be really disappointed if it's impossible to re-add passes that they manually deleted. So I wouldn't recommend such solution. </li> <li>You can make you pkpass links kind of private, so only GET request originating from your application and carrying a specific value for specific header field (e.g. auth_token), will receive a pkpass file, however this way you almost disable pass distribution via email or via sharing URLs to passes and make pass updating probably impossible.</li> </ol> |
29,887,838 | 0 | Multiple rows are not showing when we convert the table data into XML in SQL <p>I have two table as given below.</p> <p><code>OrderHeader</code>:</p> <pre><code>PKOrderHeader CustomerCode DocumentRef SiteCode 1 JOE TEST1 TH 2 POL TEST2 CO 3 GEO TEST3 KH </code></pre> <p><code>OrderDetails</code>:</p> <pre><code>FKOrderHeader ProductCode RotationLineNo 1 PRD1 1 1 PRD2 2 2 PRD3 2 3 PRD4 3 </code></pre> <p>I need to get the XML string as below after converting the table data as XML string</p> <pre><code><ORDERS> <SO> <HD> <PKOrderHeader>1</PKOrderHeader> <CustomerCode>JOE</CustomerCode> </HD> <HO> <DocumentRef>TEST1</DocumentRef> <SiteCode>TH</SiteCode> </HO> <LO> <FKOrderHeader>1</FKOrderHeader> <ProductCode>PRD1</ProductCode> <RotationLineNo>1</RotationLineNo> </LO> <LO> <FKOrderHeader>1</FKOrderHeader> <ProductCode>PRD2</ProductCode> <RotationLineNo>2</RotationLineNo> </LO> </SO> <SO> <HD> <PKOrderHeader>2</PKOrderHeader> <CustomerCode>POL</CustomerCode> </HD> <HO> <DocumentRef>TEST2</DocumentRef> <SiteCode>CO</SiteCode> </HO> <LO> <FKOrderHeader>2</FKOrderHeader> <ProductCode>PRD2</ProductCode> <RotationLineNo>2</RotationLineNo> </LO> </SO> <SO> <HD> <PKOrderHeader>3</PKOrderHeader> <CustomerCode>GOE</CustomerCode> </HD> <HO> <DocumentRef>TEST3</DocumentRef> <SiteCode>KH</SiteCode> </HO> <LO> <FKOrderHeader>3</FKOrderHeader> <ProductCode>PRD3</ProductCode> <RotationLineNo>3</RotationLineNo> </LO> </SO> </ORDERS> </code></pre> <p>The query that I used to generate the XML string is as given</p> <pre><code> SELECT (SELECT PKOrderHeader, CustomerCode FROM #OrderHeader FOR XML PATH(''), TYPE) AS HD, (SELECT DocumentRef, SiteCode FROM #OrderHeader FOR XML PATH(''), TYPE) AS HO, (SELECT FKOrderHeader, ProductCode, RotationLineNo FROM #OrderDetail FOR XML PATH(''), TYPE) AS LO FOR XML PATH('SO'), ROOT('ORDERS') </code></pre> <p>But when I generated the XML string I am getting only the single rows data as XML string as liken given below. Also the LO section is also not showing the multiple rows.</p> <pre><code><ORDERS> <SO> <HD> <PKOrderHeader>1</PKOrderHeader> <CustomerCode>JOE</CustomerCode> </HD> <HO> <DocumentRef>TEST1</DocumentRef> <SiteCode>TH</SiteCode> </HO> <LO> <FKOrderHeader>1</FKOrderHeader> <ProductCode>PRD1</ProductCode> <RotationLineNo>1</RotationLineNo> </LO> </SO> </ORDERS> </code></pre> <p>So can anyone help me to get multiple row data as XML string?</p> |
19,079,070 | 1 | Retrieving comments using python libclang <p>In the following header file I'd like to get the corresponding <code>+reflect</code> comment to the class and member variable:</p> <pre><code>#ifndef __HEADER_FOO #define __HEADER_FOO //+reflect class Foo { public: private: int m_int; //+reflect }; #endif </code></pre> <p>Using the python bindings for libclang and the following script:</p> <pre><code>import sys import clang.cindex def dumpnode(node, indent): print ' ' * indent, node.kind, node.spelling for i in node.get_children(): dumpnode(i, indent+2) def main(): index = clang.cindex.Index.create() tu = index.parse(sys.argv[1], args=['-x', 'c++']) dumpnode(tu.cursor, 0) if __name__ == '__main__': main() </code></pre> <p>Gives me this output:</p> <pre><code>CursorKind.TRANSLATION_UNIT None CursorKind.TYPEDEF_DECL __builtin_va_list CursorKind.CLASS_DECL type_info CursorKind.CLASS_DECL Foo CursorKind.CXX_ACCESS_SPEC_DECL CursorKind.CXX_ACCESS_SPEC_DECL CursorKind.FIELD_DECL m_int </code></pre> <p>The problem is that the comments are missing. Are they stripped by the preprocessor? Is there any way to prevent that?</p> |
32,608,933 | 0 | is it possible to change the dpi of a canvas image in HTML5? <p>I have learnt that Canvas images in general have 96 dpi. Is it possible to change the dpi of the image data of Canvas. Can i say like convert the 96 dpi image to 200 dpi? Thanks in advance. I looked at this post <a href="http://stackoverflow.com/questions/14488849/higher-dpi-graphics-with-html5-canvas">Higher DPI graphics with HTML5 canvas</a> but looks like this is upscaling.</p> |
30,937,969 | 0 | <p>From my experience, I just do not do this.</p> <p>I find it much better to pass two dates rather than a range, and then use <code>>=</code> & <code><=</code> in crystal.</p> |
6,487,407 | 0 | <p>Yes, but what is the point?</p> <pre><code>Response.Cookies.Add(new HttpCookie("UserID", "JLovus") {Expires = DateTime.Now.AddMinutes(30)}); </code></pre> |
14,069,663 | 0 | <p>Yes, this is absolutely possible with Scrapy. If you're just opening a list of URLs that you know rather than scraping the site it I'd say Scrapy is overkill.</p> <p>I would recommend <a href="http://lxml.de/" rel="nofollow">lxml</a> for HTML parsing, it's simple and considerably faster than BeautifulSoup (can be as much as two orders of magnitude). And <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">requests</a> for HTTP because it's super simple.</p> <p>In the snippet below I'm using an XPath query to find the correct definition description element. <code>//dl[dt/text()='term']//dd/text()</code> is essentially saying "find the definition list (dl) element that has a definition term with text content of 'term' (<code>//dl[dt/text()='term']</code>) and then find all definition description (dd) elements and get their text content (<code>//dd/text()</code>)".</p> <pre><code>from StringIO import StringIO import requests from lxml import etree response = requests.get("http://www.tripadvisor.in/members/SomersetKeithers") parser = etree.HTMLParser() tree = etree.parse(StringIO(response.text), parser) def get_definition_description(tree, term): description = tree.xpath("//dl[dt/text()='%s']//dd/text()" % term) if len(description): return description[0].strip() print get_definition_description(tree, "Age:") print get_definition_description(tree, "Gender:") print get_definition_description(tree, "Location:") </code></pre> |
22,140,090 | 0 | delRowData doesn't update the rowcount in groupText <p>I am trying to delete a row from jqgrid using the method <code>delRowData</code> which is using the grouping feature. When i delete a row from the jqgrid it doesn't seem to be updating the count in the groupText. Below is the code I have tried</p> <pre><code><html> <head> <link rel="stylesheet" type="text/css" href="jquery-ui-custom.css" /> <link rel="stylesheet" type="text/css" href="ui.jqgrid.css" /> <script src="js/jquery.js" type="text/javascript"></script> <script src="js/jquery-ui-custom.min.js" type="text/javascript"></script> <script src="js/grid.locale-en.js" type="text/javascript"></script> <script src="js/jquery.jqGrid.js" type="text/javascript"></script> <script src="js/jquery.contextmenu.js" type="text/javascript"></script> <script type="text/javascript"> jQuery(document).ready(function(){ var mydata = [ {id:"9",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"}, {id:"1",invdate:"2010-05-24",name:"test",note:"note",tax:"10.00",total:"2111.00"} , {id:"2",invdate:"2010-05-25",name:"test2",note:"note2",tax:"20.00",total:"320.00"}, {id:"3",invdate:"2007-09-01",name:"test3",note:"note3",tax:"30.00",total:"430.00"}, {id:"29",invdate:"2007-09-01",name:"test3",note:"note3",amount:"450.00",tax:"40.00",total:"430.00"}, {id:"4",invdate:"2007-10-04",name:"test",note:"note",tax:"10.00",total:"210.00"}, {id:"5",invdate:"2007-10-05",name:"test2",note:"note2",tax:"20.00",total:"320.00"}, {id:"6",invdate:"2007-09-06",name:"test3",note:"note3",tax:"30.00",total:"430.00"}, {id:"7",invdate:"2007-10-04",name:"test",note:"note",tax:"10.00",total:"210.00"}, {id:"8",invdate:"2007-10-03",name:"test2",note:"note2",amount:"300.00",tax:"21.00",total:"320.00"}, {id:"19",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"40.00",total:"430.00"}, {id:"11",invdate:"2007-10-01",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"12",invdate:"2007-10-02",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"13",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"35.00",total:"430.00"}, {id:"14",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"15",invdate:"2007-10-05",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"16",invdate:"2007-09-06",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"}, {id:"17",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"18",invdate:"2007-10-03",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"21",invdate:"2007-10-01",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"22",invdate:"2007-10-02",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"23",invdate:"2007-09-01",name:"test3",note:"note3",amount:"450.00",tax:"30.00",total:"430.00"}, {id:"24",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"25",invdate:"2007-10-05",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"26",invdate:"2007-09-06",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"}, {id:"27",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"28",invdate:"2007-10-03",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"} ]; jQuery("#list3").jqGrid({ data: mydata, datatype: "local", height: 400, colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'], colModel:[ {name:'id',index:'id', width:60, sorttype:"int"}, {name:'invdate',index:'invdate', width:90, sorttype:"date"}, {name:'name',index:'name', width:100}, {name:'amount',index:'amount', width:80, align:"right"}, {name:'tax',index:'tax', width:80, align:"right"}, {name:'total',index:'total', width:80,align:"right",sorttype:"float"}, {name:'note',index:'note', width:150, sortable:false} ], rowNum:100, rowList:[10,20,30], pager: '#pager3', sortname: 'amount asc, tax', viewrecords: true, sortorder: "asc", loadonce: true, multiSort: true, grouping : true, groupingView : { groupField : ['invdate'], groupColumnShow : [false], groupText : ['<b>{0} - ({1})</b>'], groupCollapse : false, groupOrder: ['asc'], groupSummary : [false], plusicon : 'ui-icon ui-icon-triangle-1-e', minusicon : 'ui-icon ui-icon-triangle-1-s' }, caption: "Load Once Example" }); jQuery("#deleteButton").click(function(){ var rowid = $("#list3").jqGrid ("getGridParam", "selrow"); jQuery("#list3").jqGrid("delRowData",rowid); }); }); </script> </head> <body> <table id="list3"></table> <button id="deleteButton">Delete Row</button> </body> </html> </code></pre> <p>I hope I have explained my problem. Please let me know if anything else need to be added.</p> <p>BTW I am using jqgrid version : "4.5.4"</p> <p>Thanks in advance</p> <p>Mobin</p> |
33,062,662 | 0 | <p>You can set background on animation complete callback something like this:</p> <pre><code>$('#SwWcSbDoTh').on('click',function(){ $('#B').animate({opacity: 1,complete:function(){ $("body").css("opacity","0.25");}},1000); }); </code></pre> |
35,880,927 | 0 | Jackson serialize generic collection <p>I want to use Jackson to serialize an object include a generic collection type. This is the interface:</p> <pre><code>public interface PagingAdapter <Id extends Serializable, T extends Entity<Id>> extends Serializable { public List<T> getItem(); public void setItem(List<T> items); public Boolean hasNextPage(); public Integer getTotalPage(); public Integer getPageSize(); public void setPageSize(int pageSize); public Long getTotalItem(); public void setTotalItem(Long totalItem); public void setCurrentPage(Integer currentPage); public Integer getCurrentPage(); public Class<T> getEntityType(); public void setEntityType(Class<T> entityType); } </code></pre> <p>and this is the implementation:</p> <pre><code>public class PagingAdapterImpl<Id extends Serializable, T extends Entity<Id>> implements PagingAdapter<Id,T> { private static Integer DEFAULT_PAGE_SIZE = 20; private Class<T> entityType; private List<T> items = null; private Integer pageSize = DEFAULT_PAGE_SIZE; private Integer currentPage = 0; private Long totalItem; public PagingAdapterImpl(List<T> items, int currentPage, int pageSize, long totalItem) { super(); this.items = items; this.pageSize = pageSize; this.currentPage = currentPage; this.totalItem = totalItem; } public PagingAdapterImpl(){ } @Override public Class<T> getEntityType() { return entityType; } @Override public void setEntityType(Class<T> entityType) { this.entityType = entityType; } @Override public List<T> getItem() { return items; } @Override public void setItem(List<T> items) { this.items = items; } @Override public Boolean hasNextPage() { return false; } @Override public Integer getTotalPage() { int rs = (int) (getTotalItem() % getPageSize() == 0 ? getTotalItem() / getPageSize() : getTotalItem() / getPageSize() + 1); return 0; } @Override public Integer getPageSize() { return this.pageSize; } @Override public Long getTotalItem() { return this.totalItem; } @Override public void setTotalItem(Long totalItem) { this.totalItem = totalItem; } @Override public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } @Override public Integer getCurrentPage() { return currentPage; } @Override public void setPageSize(int pageSize) { this.pageSize = pageSize; } } </code></pre> <p>I'm using RestEasy with Jackson 1.9. Output of a rest method return instance of this object now like this:</p> <pre><code>{ "status": 0, "data": { "entityType": null, "pageSize": 1, "currentPage": 1, "totalItem": 1, "item": [], "totalPage": 0 } } </code></pre> <p>The "item" property cannot be serialized to a JSON array. How can I fix this problem?</p> <pre><code>public class PagingAdapterSerializer extends JsonSerializer<PagingAdapter<Long, Entity<Long>>> { @Override public void serialize(PagingAdapter<Long, Entity<Long>> value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeObjectField("item",value.getItem()); jgen.writeObjectField("totalItem",value.getTotalPage()); jgen.writeObjectField("pageSize",value.getPageSize()); jgen.writeObjectField("totalItem",value.getTotalItem()); jgen.writeObjectField("currentPage",value.getCurrentPage()); jgen.writeEndObject(); } </code></pre> <p>This is my custom serializer. But it doesn't works</p> |
26,929,722 | 0 | How to get the x y position of a view after zoom-in in android <p>I am Beginner for android, am looking for xy position of a view in zoom-in page but i tried a lot i cant able to get that.I used this below coding, but im getting the same position before and after the zoom. Please any one post the code for finding the xy position after zoom it. </p> <pre><code> private int fieldImgXY[] = new int[2]; v.getLocationOnScreen(fieldImgXY); Log.v("Log",fieldImgXY[0]+" "+fieldImgXY[1]); </code></pre> <p>My full code:</p> <pre><code> zoom = (ZoomView) findViewById(R.id.maincontainerScroller); imageView = new ImageView(this); imageView.setImageResource(R.drawable.ic_launcher); imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); zoom.addView(imageView); imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub v.getLocationOnScreen(fieldImgXY); Log.v("Log",fieldImgXY[0]+" "+fieldImgXY[1]); } }); </code></pre> |
5,991,604 | 0 | Windows Phone 7 Silverlight using session <p>I am creating a Windows 7 mobile Silverlight project. I use Rest api for authentication using a class say <strong>Authentication</strong>. I get an authentication token as a response and I assign it to a class property <strong>AuthToken</strong> because I need to use this in different places. Is there any way to store this AuthToken in session or any thing else. Because I did not find any session example in wp7. Thanks</p> |
26,709,268 | 0 | <p>Anyways, I get the answer. All we have to make a call to.</p> <pre><code>getCompleteInfo() </code></pre> <p>Rest is on manipulation of the output.</p> |
752,490 | 0 | Security risks of an un-encrypted connection across an international WAN? <p>The organisation for which I work has an international WAN that connects several of its regional LANs. One of my team members is working on a service that receives un-encrypted messages directly from a FIX gateway in Tokyo to an app server in London, via our WAN. The London end always initiates the authenticated connection, and at no point do these messages leave our WAN. </p> <p>But our local security guru suggests that we should be encrypting these messages as a <a href="http://www.darkreading.com/story/showArticle.jhtml?articleID=216403220" rel="nofollow noreferrer">WAN apparently has significantly more security risk than a LAN</a>. How much easier is it really to break into a WAN than a LAN? And what other security risks does a WAN pose in this context?</p> <p><strong>UPDATE:</strong> Many thanks for your answers. I've decided to encrypt the connection, mainly because it's clear that the WAN does introduce extra security vulnerabilities due to the hardware being outside of our physical control. </p> |
32,818,434 | 0 | Source code space mess <p>I have my code perfectly tabbed in Notepad++, but it is a mess in the source code in Google Chrome.</p> <p><a href="https://i.stack.imgur.com/9BPyw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9BPyw.png" alt="Google Chrome"></a> <a href="https://i.stack.imgur.com/BCNWp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BCNWp.png" alt="Notepad++"></a></p> <p>How can I fix this?</p> <p>Thanks in advance!</p> |
14,720,587 | 0 | Convert int to bytes - different result in Java & Actionscript <p>I would like to convert integers to bytes. I have an example in Actionscript and I need to convert it to Java. For the sake of simplicity let's assume only one number, 1234. This is my Java code:</p> <pre><code>int[] a = {1234}; ByteBuffer byteBuffer = ByteBuffer.allocate(a.length * 4); IntBuffer intBuffer = byteBuffer.asIntBuffer(); intBuffer.put(a); byte[] array = byteBuffer.array(); for (int i=0; i < array.length; i++) { Log.i(T, i + ": " + array[i]); } </code></pre> <p>This gives me the following result:</p> <pre><code>0 : 0 1 : 0 2 : 4 3 : -46 </code></pre> <p>While in Actionscript I have this:</p> <pre><code>var c:ByteArray = new ByteArray; c.writeInt(1234); for(var p:uint=0; p<c.length; p++) { trace(p+" : "+c[p]); } </code></pre> <p>And the result:</p> <pre><code>0 : 0 1 : 0 2 : 4 3 : 210 </code></pre> <p>What am I doing wrong, why is the result different? Thanks!</p> |
35,371,043 | 1 | Use python requests to download CSV <p>Here is my code: </p> <pre><code>import csv import requests with requests.Session() as s: s.post(url, data=payload) download = s.get('url that directly download a csv report') </code></pre> <p>This gives me the access to the csv file. I tried different method to deal with the download:</p> <p>This will give the the csv file in one string:</p> <pre><code>print download.content </code></pre> <p>This print the first row and return error: _csv.Error: new-line character seen in unquoted field</p> <pre><code>cr = csv.reader(download, dialect=csv.excel_tab) for row in cr: print row </code></pre> <p>This will print a letter in each row and it won't print the whole thing:</p> <pre><code>cr = csv.reader(download.content, dialect=csv.excel_tab) for row in cr: print row </code></pre> <p>My question is what is what's the most efficient way to read a csv file in this situation. And how to download the actual csv file.</p> <p>thanks </p> |
27,269,665 | 0 | <p>There is a command to show all the commit logs history since the beginning in a branch</p> <pre><code>git log </code></pre> <p>after execting this command, you will find that each commit or log has commit id and Author with its date, copy the commit ID and right this command:</p> <pre><code>git show COMMIT_ID </code></pre> <p>The command above will show the commit details by the author assigned to this commit id</p> <p>Another solution it to write something like this:</p> <pre><code>git whatchanged --since '04/14/2013' --until '05/22/2014' </code></pre> <p>The code above it like git log however with filters (range)</p> |
12,156,209 | 0 | How recive data from SQL Server to Android Application, in autonomous manner? <p>I have created a web service which, querying a SQL Server, retrives several tables. I'm consuming this web service using KSoap2 package in Android application, and I want maintain alligned the tables on SQL Server and tables on Android Application. Many of the tables in SQL Server remain the same over time, but some others change frequently. I need an automatic mechanism for update the tables on Android Application, on the initiative of Server. I think I need a socket on Android application, for listening a signal transmitted from SQL Server, the meaning of which is "the data in some tables are changed". So, then, I can use the web service call for retrieves new data. Is this possible? anyone has suggestions?</p> |
14,542,067 | 0 | <p>Sounds like you should be using radio buttons instead. To do that with check boxes you'll need to manually uncheck the boxes on the .checked event.</p> |
9,541,141 | 0 | <p>The code is actually working great, but only in <em>Processing</em>, not in <em>Processing.js</em> even though this fonctionnality appear in both reference pages <a href="http://processingjs.org/reference/PImage/" rel="nofollow">http://processingjs.org/reference/PImage/</a></p> |
21,981,320 | 0 | <p>Whenever I want to decouple the implementation of a piece of logic from where it's needed - in this case the knowledge of "how much data is enough" - I think of a callback function.</p> <p>Presumably the set of all possible data that your class can collect is known (<code>name</code>, <code>age</code>, <code>sex</code> & <code>location</code> in your example). This means all <em>clients</em> of your class (can) know about it also, without increasing the amount of coupling & dependence.</p> <p>My solution is to create an "evaluator" class that encapsulates this logic. An instance of a subclass of this class is created by the client and handed to the data collector at the time of the initial request for data; this object is responsible for deciding (and telling the "collector") when enough data has been collected.</p> <pre><code>#include <string> // The class that decides when enough data has been collected // (Provided to class "collector" by its clients) class evaluator { public: virtual ~evaluator() {}; // Notification callbacks; Returning *this aids in chaining virtual evaluator& name_collected() { return *this; } virtual evaluator& age_collected() { return *this; } virtual evaluator& sex_collected() { return *this; } virtual evaluator& location_collected() { return *this; } // Returns true when sufficient data has been collected virtual bool enough() = 0; }; // The class that collects all the data class collector { public: void collect_data( evaluator& e ) { bool enough = false; while ( !enough ) { // Listen to data source... // When data comes in... if ( /* data is name */ ) { name = /* store data */ enough = e.name_collected().enough(); } else if ( /* data is age */ ) { age = /* store data */ enough = e.age_collected().enough(); } /* etc. */ } } // Data to collect std::string name; int age; char sex; std::string location; }; </code></pre> <p>In your example, you wanted a particular client to be able to specify that the combination of <code>age</code> and <code>sex</code> is sufficient. So you subclass <code>evaluator</code> like so:</p> <pre><code>class age_and_sex_required : public evaluator { public: age_and_sex_required() : got_age( false ) , got_sex( false ) { } virtual age_and_sex_required& age_collected() override { got_age = true; return *this; } virtual age_and_sex_required& sex_collected() override { got_sex = true; return *this; } virtual bool enough() override { return got_age && got_sex; } private: bool got_age; bool got_sex; }; </code></pre> <p>The client passes an instance of this class when requesting data:</p> <pre><code>collector c; c.collect_data( age_and_sex_required() ); </code></pre> <p>The <code>collect_data</code> method quits and returns when the <code>age_and_sex_required</code> instance reports that the amount of data collected is "enough", and you haven't built any logic, knowledge, enums, whatever, into the <code>collector</code> class. Also, the logic of what constitutes "enough" is <em>infinitely configurable</em> with no further changes to the <code>collector</code> class.</p> <p>----- EDIT -----</p> <p>An alternate version would <em>not</em> use a class with the <code>..._collected()</code> methods but simply a single (typedef'd) function that accepts the <code>collector</code> as a parameter and returns <code>boolean</code>:</p> <pre><code>#include <functional> typedef std::function< bool( collector const& ) > evaluator_t; </code></pre> <p>The code in <code>collector::collect_data(...)</code> would simply call</p> <pre><code>enough = e( *this ); </code></pre> <p>each time a piece of data is collected.</p> <p>This would eliminate the necessity of the separate <code>evaluator</code> abstract interface, but would add dependence on the <code>collector</code> class itself, as the object passed as the <code>evaluator_t</code> function would be responsible for checking the state of the <code>collector</code> object to evaluate whether enough data has been collected (and would require the <code>collector</code> to have sufficient public interface to inquire about its state):</p> <pre><code>bool age_and_sex_required( collector const& c ) { // Assuming "age" and "sex" are initialized to -1 and 'X' to indicate "empty" // (This could be improved by changing the members of "collector" to use // boost::optional<int>, boost::optional<char>, etc.) return (c.age >= 0) && (c.sex != 'X'); } </code></pre> |
33,032,545 | 0 | How to handle incoming request error 'Request Too Large' in Google App Engine? <p>We provided our GAE Servlet POST URL as Webhook to third party service that sends data. According to <a href="https://cloud.google.com/appengine/docs/quotas?hl=en#Requests" rel="nofollow">GAE</a> - "Each incoming HTTP request can be no larger than 32MB."</p> <p>Sometimes third party service sends data more than 40MB which gets rejected by GAE server as 'Request Too Large' error. The service retries continuously on the other end upto 100 times and blocks further requests until retries completed if webhook URL doesn't return a 200 HTTP response code.</p> <p>Is it possible to handle such requests and send 200 HTTP response code with GAE?</p> |
32,245,312 | 0 | <p>NUnit version 3 will support running tests in parallel, this works good with a Selenium Grid:</p> <p>Adding the attribute to a class: <code>[Parallelizable(ParallelScope.Self)]</code> will run your tests in parallel with other test classes.</p> <blockquote> <p>• ParallelScope.None indicates that the test may not be run in parallel with other tests. </p> <p>• ParallelScope.Self indicates that the test itself may be run in parallel with other tests.</p> <p>• ParallelScope.Children indicates that the descendants of the test may be run in parallel with respect to one another.</p> <p>• ParallelScope.Fixtures indicates that fixtures may be run in parallel with one another.</p> </blockquote> <p><a href="https://github.com/nunit/docs/wiki/Parallel-Test-Execution" rel="nofollow noreferrer">NUnit Framework-Parallel-Test-Execution</a></p> |
30,055,142 | 0 | <p>In order to load extensions, you should add "extensions" in "module" section in project.json. For example:</p> <p>{ ... "module": ["cocos2d", "extensions"] }</p> |
37,024,635 | 0 | How to cd to a directory on remote machine and run the script present in that directory <p>When I do this</p> <pre><code>ssh host@someip "cd /target && ls" </code></pre> <p>the files on remote machine are displayed.</p> <p>Now, I am trying to run a file on the remote machine.</p> <pre><code>ssh host@someip "cd /target && ./file.sh" </code></pre> <p>When i do this it reaches the folder named target on the remote machine but the file is executed on local machine. How to make file.sh also run on remote machine ?</p> |
18,347,687 | 0 | Django: Reverse not found > {% url %} in template <p>This problem seems simple and it is described multiple times in SO, but I still can't figure out why it isn't working in my case.</p> <p>So, I have a url declared in <strong>urls.py</strong></p> <pre><code>urlpatterns = patterns('', url(r'^(?P<country>[-\w]+)/$', CountryListView.as_view(), name='list_by_country'),) </code></pre> <p>and in my <strong>template</strong> I'm calling the url</p> <pre><code><a href="{% url 'list_by_country' country.country__name %}" >{{ country.country__name }}</a> </code></pre> <p>However, I am getting the <strong>error message</strong> that the url could not be reversed</p> <pre><code>Reverse for 'list_by_country' with arguments '(u'United Kingdom',)' and keyword arguments '{}' not found </code></pre> <p>What is causing the reverse error? Are spaces in the argument maybe not allowed?</p> <hr> |
564,591 | 0 | <p>My simple answer combined with those answer is:</p> <ul> <li>Create your application/program using thread safety manner </li> <li>Avoid using public static variable in all places</li> </ul> <p>Therefore it usually fall into this habit/practice easily but it needs some time to get used to: </p> <p>program your logic (not the UI) in functional programming language such as F# or even using Scheme or Haskell. Also functional programming promotes thread safety practice while it also warns us to always code towards purity in functional programming. If you use F#, there's also clear distinction about using mutable or immutable objects such as variables. </p> <hr> <p>Since method (or simply functions) is a first class citizen in F# and Haskell, then the code you write will also have more disciplined toward less mutable state. </p> <p>Also using the lazy evaluation style that usually can be found in these functional languages, you can be sure that your program is safe fromside effects, and you'll also realize that if your code needs effects, you have to clearly define it. IF side effects are taken into considerations, then your code will be ready to take advantage of composability within components in your codes and the multicore programming.</p> |
39,232,832 | 0 | How to stop tab change from running fragment onCreateView in Andriod <p>I have three tabs using the implementation below and they perform very well. When tab is changed the proper fragment is load and so on. The problem is that, when i get to the last tab and comeback to the first fragment, its like its oncreateview method is always triggered again running the other codes it in causing duplicates. Any help will be greatly appreciated.</p> <p>//Activity on the tab is based</p> <pre><code>public class Dashboard extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; private MyViewPagerAdapter myViewPagerAdapter; private int[] tabIcon = {R.drawable.ic_home, R.drawable.ic_message, R.drawable.ic_person}; android.support.v7.widget.Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dashboard); //Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); //Tablayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); tabLayout.getTabAt(0).setIcon(tabIcon[0]); tabLayout.getTabAt(1).setIcon(tabIcon[1]); tabLayout.getTabAt(2).setIcon(tabIcon[2]); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { switch(tab.getPosition()) { case 0: viewPager.setCurrentItem(0); toolbar.setTitle("Home"); break; case 1: viewPager.setCurrentItem(1); toolbar.setTitle("Messages"); break; case 2: viewPager.setCurrentItem(2); toolbar.setTitle("Profile"); break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } private void setupViewPager(ViewPager viewPager){ myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager()); myViewPagerAdapter.addFragments(new CategoryFragment(), "Categories"); myViewPagerAdapter.addFragments(new MessagesFragment(), "Messages"); myViewPagerAdapter.addFragments(new ProfileFragment(), "Profile"); viewPager.setAdapter(myViewPagerAdapter); } //View Pager Adapter public class MyViewPagerAdapter extends FragmentPagerAdapter { ArrayList<Fragment> fragments = new ArrayList<>(); ArrayList<String> tabTitles = new ArrayList<>(); public void addFragments(Fragment fragments, String titles){ this.fragments.add(fragments); this.tabTitles.add(titles); } public MyViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return fragments.size(); } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public CharSequence getPageTitle(int position) { //return tabTitles.get(position); return null; } } @Override public void onBackPressed() { super.onBackPressed(); } </code></pre> <p>}</p> <p>//Main first fragment code public class CategoryFragment extends Fragment {</p> <pre><code>private DBHandler dbHandler; private ListView listView; private ListAdapter adapter; ArrayList<Categories> categoriesList = new ArrayList<Categories>(); public CategoryFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); //Setting up the basic categories dbHandler = new DBHandler(view.getContext()); //Get Categories from database final Cursor cursor = dbHandler.getCategories(0); if (cursor != null) { if(cursor.moveToFirst()){ do{ Categories categories = new Categories(); categories.set_id(cursor.getInt(0)); categories.set_categoryname(cursor.getString(2)); categories.set_categoriescaption(cursor.getString(3)); categoriesList.add(categories); }while (cursor.moveToNext()); } cursor.close(); } listView = (ListView) view.findViewById(R.id.categories); adapter = new CategoryAdapter(view.getContext(), R.layout.cursor_row, categoriesList); listView.setAdapter(adapter); listView.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Integer cid = (int) (long) adapter.getItemId(position); TextView categoryname = (TextView) view.findViewById(R.id.cursor); String cname = categoryname.getText().toString(); Intent i = new Intent(view.getContext(), CategoryList.class); i.putExtra("categoryname", cname); i.putExtra("categoryid", cid); startActivity(i); } } ); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } </code></pre> <p>}</p> <p>So when i swipe back here from the last tab. OncreateView runs again. How can i handle that and prevent duplicates. Thank you</p> |
10,781,084 | 0 | If my app deletes a post it made to a user's wall, will all likes and shares made by other people also be deleted? <p>Lets say I have a FB app I've created, and for whatever reason the server code for the app is responsible for posting stories to the app user's wall (using a token).</p> <p>Now let's say we want to take down that post at a later date - easy, right? Because the app created the post, it owns it, and using the ID it received originally it can take that post down. (I presume the ID I get back is actually an "object id" referring to my content, rather than specifically to the post on the user's wall - correct?)</p> <p>Here's the thing though. What if one or more friends of the user shared that story to their own wall - what if this happened a number of times, spreading through the friend relationship tree further and further. Does my app still have the power to remove all of these posts, because it created the original post?</p> <p>Additionally, what if the original user deleted the post themselves from their wall, but not until it had been shared by his/her friends? Would this have the same effect (delete everywhere), or would it only be that one specific post being removed? Would my app get an error when it tried to delete the post itself if the post had already been deleted by the user? </p> <p>The reason I ask is because, if my app deleted the original post that it made to the user's wall, I would want <em>all</em> of the shared posts or likes to also be deleted, no matter where they were down the friend chain. I don't want to delete my original post and assume all is well, only to discover that because it was shared several times down the chain that it is still visible somewhere. </p> <p>In case it's relevant, the "post" my app will make would require a custom image and a specific return URL - I tried the <code>/user_id/links</code> graph API and it didnt work (there's a bug with it). So I'd be most likely using <code>/user_id/feed</code> to make the post.</p> |
9,318,941 | 0 | WordPress post query <p>I am trying to show posts with the tag "medical" if they are a child of page 843, and so far, I have everything mostly working. I need to get some HTML within this if statement so that I can enclose it all in a div, and also to set an opening and closing ul for the list.</p> <p>Can someone please help me get over this last hump? I'm just not sure where to add the HTML.</p> <pre><code><?php if (843 == $post->post_parent) { global $post; $myposts = get_posts('numberposts=10&tag=medical&order=DESC'); foreach($myposts as $post) : ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; } ?> </code></pre> |
2,864,958 | 0 | <p>Checkout this BackgroundWorker <a href="http://www.agiledeveloper.com/articles/BackgroundWorker.pdf" rel="nofollow noreferrer">sample document</a>.</p> |
18,324,045 | 0 | Is using of MemoryMappedFile instance, opened by MemoryMappedFile.OpenExisting method threadsafe? <p>In my WCF service I need to provide functionality of files downloading with supporting of <code>Range</code> HTTP header for chunked downloading. The first call to <code>GetFile</code> method of service creates new <code>MemoryMappedFile</code> instance from file on disk. Let's assume that in time when MMF created by the first request and that request still processing, the second call to <code>GetFile</code> method of service opening existing MMF and returning streamed response to client. What happens if MMF will be disposed (and source file closed on MemoryMappedFile disposing) by thread which create it? Should second call successfully read all content from already opened ViewStream or no?</p> <p>I had wrote small test and seems that till MemoryMappedFile opened by <code>OpenExisting</code> method, it's lifetime extended and source file keeps opened. Is this true, or I missed some pitfall? I can't find any documentation for such case in MSDN.</p> <p><strong>Update</strong>: added additional Thread.Sleep call after existing MMF opened before obtaining MapView of file to simulate threads race</p> <pre><code>private static readonly string mapName = "foo"; private static readonly string fileName = @"some big file"; static void Main(string[] args) { var t1 = Task.Factory.StartNew(OpenMemoryMappedFile); var t2 = Task.Factory.StartNew(ReadMemoryMappedFile); Task.WaitAll(t1, t2); } private static void OpenMemoryMappedFile() { var stream = File.OpenRead(fileName); using (var mmf = MemoryMappedFile.CreateFromFile(stream, mapName, 0, MemoryMappedFileAccess.Read, null, HandleInheritability.None, false)) { Console.WriteLine("Memory mapped file created"); Thread.Sleep(1000); // timeout for another thread to open existing MMF } Console.WriteLine("Memory mapped file disposed"); } private static void ReadMemoryMappedFile() { Thread.Sleep(100); //wait till MMF created var buffer = new byte[1024 * 1024]; //1MB chunk long totalLength = 0; using (var f = File.OpenRead(fileName)) { totalLength = f.Length; } using (var mmf = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.Read)) { Console.WriteLine("Existing MMF opened successfully"); Thread.Sleep(2000); //simulate threads race using (var viewStream = mmf.CreateViewStream(0, 0, MemoryMappedFileAccess.Read)) { Console.WriteLine("View of file mapped successfully"); File.Delete(Path.GetFileName(fileName)); using (var fileStream = File.Open(Path.GetFileName(fileName), FileMode.CreateNew, FileAccess.Write)) using (var writer = new BinaryWriter(fileStream)) { int readBytes; do { readBytes = viewStream.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, readBytes); Console.Write("{0:P}% of target file saved\r", fileStream.Length / (float)totalLength); Thread.Sleep(10); //simulate network latency } while (readBytes > 0); Console.WriteLine(); Console.WriteLine("File saved successfully"); } } } } </code></pre> |
39,565,783 | 0 | <p>We had a similar problem with iReport at work, however in our case it sometimes worked (generated the text in correct font and size) and some times didn't (stuck at default font with size 10).</p> <p>As it turned out, server-side we were using iReport in version <strong>5.5.0</strong>, and while some people generated their <code>.jasper</code> report files with correct desktop iReport version, others used newer desktop iReport <strong>5.6.0</strong> which failed to generate a report file compatible with older server-side version.</p> <p>After we settled on one version (which we decided to be the older <strong>5.5.0</strong> to avoid changes on server side) the problem has been solved.</p> <hr> <p><strong>tl;dr:</strong> Remember to generate your reports with the same version of iReport that you use to print them.</p> |
10,328,270 | 0 | <p>Turns out it was a programmer error</p> <p>I was calling a webmethod that did not exist.</p> <p>There was no method called MyFunction</p> |
33,021,653 | 0 | Searching Efficiency - Which is faster comparing 10 ints or one 30 bytes string? <p>I'm going to make a sentiment analysis project, with a website frontend to use it. It's designed to analise twitter posts. The analised documents will be put in a database. </p> <p>I'm going to group retrieved posts by the search term in the database. </p> <p>In order to make the database operations faster, I wouldn't like to compare search terms in strings, the idea is to transform the search terms into numbers and use them to find entries in the database.</p> <p>The function I thought of to transform the strings in numbers would be something as follows:</p> <ul> <li>a = 067</li> <li>b = 068</li> <li>...</li> <li>ab = 067068</li> <li>abc = 067068069</li> <li>abcd => i1= 067068069 and i2 = 070</li> </ul> <p>This way, for a 30 length string, I would require 10 ints.</p> <p>So 2 questions: 1- Would there be a better function to transform a 30 length string to a number, without ANY collision ?</p> <p>2- In the case there isn't, in a database filed with a million search terms, would it be better to compare 10 ints per item, or compare 30 length string per item ? Something like </p> <pre><code>Select from terms where i1 == search.i1 and i2 = search.i2 and ... i10 == search.i10 </code></pre> <p>OR</p> <pre><code>Select from terms where term like search.term </code></pre> <p>Thanks for your attention.</p> |
18,770,048 | 0 | Variable affecting its parent variable <p>The title might seems weird, but I don't really know how to describe this situation as I'm a beginner in JavaScript.</p> <p>Here's the code :</p> <pre><code>a={}; var b=a; b['a']='x'; console.log(a); </code></pre> <p>the result will be:</p> <pre><code>Object { a="x"} </code></pre> <p>shouldn't it be a blank object because I set 'x' to variable b only ?</p> |
35,007,108 | 0 | <p>You can coerce a CF type to an NS type by first re-binding the CFMakeCollectable function so that it takes 'void *' and returns 'id', and then using that function to perform the coercion:</p> <pre><code>ObjC.bindFunction('CFMakeCollectable', [ 'id', [ 'void *' ] ]); var cfString = $.CFStringCreateWithCString(0, "foo", 0); // => [object Ref] var nsString = $.CFMakeCollectable(cfString); // => $("foo") </code></pre> <p>To make this easier to use in your code, you might define a .toNS() function on the Ref prototype:</p> <pre><code>Ref.prototype.toNS = function () { return $.CFMakeCollectable(this); } </code></pre> <p>Here is how you would use this new function with a CFString constant:</p> <pre><code>ObjC.import('CoreServices') $.kUTTypeHTML.toNS() // => $("public.html") </code></pre> |
8,333,998 | 0 | Grails sequence generation for Oracle 11g <p>I realize this is more of a hibernate question than Grails. In a load balanced (2 nodes) environment I see that the ids of my objects are jumping around quite a bit. Even without restarting the app server I see that the numbers skip 10 sometimes 20 numbers. I suspect the hibernate session is caching a block of sequence values. <strong>Is there a way to control this behavior with grails 1.3.7 ?</strong> Essentially I am OK with server pulling nextval from DB every time it needs one.</p> <p>My domain object sequence declaration (same for 2 objects):</p> <pre><code>static mapping = { id generator:'sequence', params:[sequence:'MY_SEQ'] } </code></pre> |
9,824,257 | 0 | <p><img src="https://i.stack.imgur.com/FtJkK.png" alt="enter image description here"></p> <p>Please go through this link: <a href="http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S1" rel="nofollow noreferrer">Nine Options for Managing Persistent User State in Your ASP.NET Application</a></p> |
Subsets and Splits