pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
703,934 | 0 | <p>I would skip the database for reasons listed above. A simple hash in memory will perform about as fast a lookup in the database. </p> <p>Even if the database was a bit faster for the lookup, you're still wasting time with the DB having to parse the query and create a plan for the lookup, then assemble the results and send them back to your program. Plus you can save yourself a dependency.</p> <p>If you plan on moving other parts of your program to a persistent store, then go for it. But a hashmap should be sufficient for your use.</p> |
22,418,254 | 0 | C pthread_barrier synchronization issues <p>I'm new to learning about <code>pthread_barriers</code> and how they work. Basically I have two arrays and two threads, one thread finds the max of array A and another finds the min of array B and stores them in global variables. They need to synchronize right before they make a trade (the max of A is passed to B and the min of B is passed to A) so that array B has all higher values than A - almost like a sorting problem, if you will. I keep getting wildly incorrect results and I'm sure I'm missing something simple;</p> <p><strong>I initialize the barrier with</strong></p> <pre><code> pthread_barrier_t bar; pthread_barrier_init( &bar, NULL, 2); </code></pre> <p><strong>The thread code for A</strong></p> <pre><code>void *minimize_a( void *arg ) int i; int size_a = *((int *) arg); // first location is count of values int *a = ((int *) arg) + 1; // a[] will be array of values while(1){ i = index_of_max( a, size_a ); max = a[i]; // offer max for trade pthread_barrier_wait( &bar ); if( max <= min ) return NULL; // test to end trading rounds a[i] = min; // trade } </code></pre> <p><strong>The thread code for B</strong></p> <pre><code> void *maximize_b( void *arg ) int i; int size_b = *((int *) arg); // first location is count of values int *b = ((int *) arg) + 1; // b[] will be array of values while(1){ i = index_of_min( b, size_b ); min = b[i]; // new min found pthread_barrier_wait( &bar ); if( max <= min ) return NULL; // test to end trading rounds b[i] = max; // trade } </code></pre> <p>If I'm correct in understanding, once both threads hit pthread_barrier_wait, they will have successfuly synchronized and can keep continuing, correct? I always get crazy results like the following:</p> <p><strong>Before</strong></p> <p><code>a: 1, 3, 5, 6, 7, 8, 9</code></p> <p><code>b: 2, 4</code></p> <p><strong>After</strong></p> <p><code>a: 0, 0, 0, 0, 0, 0, 0</code></p> <p><code>b: 2, 4</code></p> <p>The values array</p> <pre><code>int values[] = { // format of each set of values: // count of value n, then n integer values 7, 1,3,5,6,7,8,9, // this set of values starts at index 0 2, 2,4, // starts at index 8 5, 1,3,5,7,9, // starts at index 11 5, 0,2,4,6,8 // starts at index 17 } </code></pre> <p>How the threads are made</p> <pre><code>rc = pthread_create( &threads[0], NULL, &minimize_a, (void *) &values[0] ); if( rc ){ printf( "** could not create m_a thread\n" ); exit( -1 ); } rc = pthread_create( &threads[1], NULL, &maximize_b, (void *) &values[8] ); if( rc ){ printf( "** could not create m_b thread\n" ); exit( -1 ); } </code></pre> <p>Any tips, suggestions, or help please?</p> |
25,172,873 | 0 | Preventing polymer template-soup <p>I find myself often writing deep levels of nested templates because I can't figure out how to write fairly simple conditions in any other way. This leads to a thousand template nodes in my DOM tree and it's just a mess.</p> <p>To give an example, the following is a snippet from a custom select-box (written in Jade. "<em>template#option</em>" --> <code><template id="option"></code>, etc.)</p> <pre><code>// note that this template is user-replaceable which is why it's out here template#option span {{ label }} #dropdown template( repeat='{{ option, ix in options }}' ) template( if='{{ !option.hidden }}' ) .option( data-ix='{{ ix }}' class='{{ option.active ? "active" : "" }}' ) template( bind='{{ option }}' ref='option' ) </code></pre> <p>I'm just looking for help in cleaning this up. I feel like I <em>should</em> be able to write something like:</p> <pre><code>#dropdown .option( template repeat='{{ option, ix in options }}' if='{{ !option.hidden }}' data-ix='{{ ix }}' class='{{ option.active ? "active" : "" }}' ) template( bind='{{ option }}' ref='option' ) </code></pre> <p>But I can't seem to get anything similar to that to work.</p> |
33,541,643 | 0 | <pre><code>java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet] </code></pre> <p>Your <code>HackySwipeBackLayout</code> is missing a constructor:</p> <pre><code>public HackySwipeBackLayout(Context context, AttributeSet attrs) { super(context, attrs); } </code></pre> <p>If you look more closely at the <a href="https://github.com/chrisbanes/PhotoView/blob/master/sample/src/main/java/uk/co/senab/photoview/sample/HackyViewPager.java" rel="nofollow"><code>HackyViewPager</code></a>, you'll notice that it is in there too. As a matter of fact, <em>any</em> view that needs to support inflating from xml should have this constructor defined. You may find the <a href="http://developer.android.com/intl/es/training/custom-views/create-view.html#subclassview" rel="nofollow">documentation on how to create custom views</a> helpful too.</p> <hr> <p>Edit: since your intention is to catch the exception thrown, make sure to catch the <code>ArrayIndexOutOfBoundsException</code> accordingly:</p> <pre><code>@Override public boolean onInterceptTouchEvent(MotionEvent ev) { try { return super.onInterceptTouchEvent(ev); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); return false; } } </code></pre> <p>That should stop your app from crashing on this particular exception, but is of course not a 'fix' for the underlying issue that is causing the <code>ArrayIndexOutOfBoundsException</code> to be thrown in the first place. It may or may not lead to the desired behaviour. Either way, consider opening a <a href="https://github.com/liuguangqiang/SwipeBack/issues" rel="nofollow">ticket</a> with the maintainer of the SwipeBack repo.</p> |
18,309,217 | 0 | <p>Refer to this tutorial/example for the solar system using CSS3: </p> <p><a href="http://neography.com/experiment/circles/solarsystem/" rel="nofollow">CSS3 Solar System</a></p> |
13,149,973 | 0 | <p>I haven't really done much image-processing, so this is just a long shot, but couldn't you do something like this:</p> <pre><code>function addPercentageToNumber($number, $minPercentage, $maxPercentage) { return $number + rand( ($number / 100) * $minPercentage, ($number / 100) * $maxPercentage ); } // Base color $r2 = rand(0, 255); // Add 10-20% $r2 = addPercentageToNumber($r2, 10, 20); </code></pre> <p>You would also need to add some code to handle what happens when a result would be <code>>255</code> and so on. Hope this helps you a little atleast. :-)</p> |
4,948,045 | 0 | <p><code>inter_byte</code> is a reference to an array of bytes. You are only allocating the actual array of bytes once (with the <code>new byte[5]</code>. You need to do that in your loop.</p> |
7,609,388 | 0 | <p><code>adb</code> is not in your <code>PATH</code>. </p> <p>Bash will first try to look for a binary called <code>adb</code> in your Path, and not in the current directory. Therefore, if you are currently in the <code>platform-tools</code> directory, just call</p> <pre><code>./adb --help </code></pre> <p>The dot is your current directory, and this tells Bash to use <code>adb</code> from there.</p> <p>Otherwise, you can add <code>platform-tools</code> to your <code>PATH</code>, by placing a line like this in your <code>~/.profile</code> or <code>~/.bash_profile</code>, then re-starting the Terminal. On Linux, you might want to modify <code>~/.bashrc</code> instead, <a href="http://www.joshstaiger.org/archives/2005/07/bash_profile_vs.html">depending on what is used</a>.</p> <pre><code>export PATH=/Users/espireinfolabs/Desktop/soft/android-sdk-mac_x86/platform-tools:$PATH </code></pre> <p>If you've installed the platform tools somewhere else, change the path accordingly. For Android Studio on OS X, for example, you'd use the following—note the double-quotes that prevent a possible space from breaking the path syntax:</p> <pre><code>export PATH="/Users/myuser/Library/Android/sdk/platform-tools":$PATH </code></pre> |
35,268,897 | 0 | <p>Here is the solution :</p> <p><pre> Create a MultiConverter:</p> <pre><code> public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var dataContext = values[0]; var dg = (DataGrid)values[1]; var i = (DataGridCell)values[2]; var col = i.Column.DisplayIndex; var row = dg.Items.IndexOf(i.DataContext); if (row >= 0 && col >= 0) { DataTable td1 = ((CheckXmlAppWpf.ViewModel.MainWindowViewModel) (dataContext)).GenericDataTable; DataTable td2 = ((CheckXmlAppWpf.ViewModel.MainWindowViewModel)(dataContext)).GenericDataTable2; if (!td1.Rows[row][col].Equals(td2.Rows[row][col])) { GetCell(dg, row, col).Background = Brushes.Yellow; } } return SystemColors.AppWorkspaceColor; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new System.NotImplementedException(); } } </code></pre> <p>Use it in the xaml:</p> <code><DataGrid x:Name="DataGrid" Margin="5,5,5,5" ItemsSource="{Binding GenericDataTable}" attachedBehaviors:DataGridColumnsBehavior.BindableColumns="{Binding GridColumns}" AutoGenerateColumns="False" EnableRowVirtualization="False"> <DataGrid.Resources> <Style TargetType="DataGridCell"> <Setter Property="Background"> <Setter.Value> <MultiBinding Converter="{StaticResource NameToBrushMultiValueConverter}" > <MultiBinding.Bindings> <Binding RelativeSource="{RelativeSource AncestorType=Window}" Path="DataContext" /> <Binding RelativeSource="{RelativeSource AncestorType=DataGrid}"></Binding> <Binding RelativeSource="{RelativeSource Self}"/> </MultiBinding.Bindings> </MultiBinding> </Setter.Value> </Setter> </Style> </DataGrid.Resources> </DataGrid> </code></pre> <p></p> |
16,330,347 | 0 | <p>Try to use the following on your listview.</p> <pre><code>listview.addHeaderView(v); </code></pre> <p>Also rememeber, you must call this method before calling setAdapter() on your listview.</p> <p>include your linearlayout where you have the user details and the tabs and add it as a header to the list.</p> |
20,768,118 | 0 | Assigning onkeyup event to multiple objects at once <p>I am working with qualtrics and I am trying to customize their matrix control. I am trying to loop through a matrix with 8 rows and 4 columns where each cell contains a textbox and assign each textbox an onkeyup event like so: </p> <pre><code>for (var j=1; j< 9; j++){ row_txt[j] = []; for (var k=1; k<5; k++){ txt1= $('QR~QID2~'+j+'~'+k); txt1.onkeyup=function(){alert(j+','+k);}; } } </code></pre> <p>However, the onkeyup event returns "9,5" for each textbox changed. Why isn't it displaying the correct indices? How can I assign the same onkeyup event to multiple objects with the corresponding parameters j and k ?</p> <p>Thank you </p> |
3,512,899 | 0 | <p>You're going to have to write an add on.</p> <p>Tabs look like windows to content so you can use a regular DOM Window object to discover some info about the current tab and do some things - close(), focus(), resizeTo() etc. Problem is Firefox and other modern browser suppress or ignore some of these events due to the default popup blocking behaviour. In addition, content cannot tell how many tabs are open, or what's running in them for security reasons so there would be no way to poll them for example. Best that you can do is is call window.opener from one window to find out which other one opened it.</p> <p>The only way you're going to get full level of access is by writing an add-on. Every browser has its own way of writing add ons, some of which will be easier to write than others. </p> |
11,117,110 | 0 | <p>I used <code>form.setText(Html.fromHtml(text));</code> and it works fine.</p> |
22,460,842 | 0 | MySQL Query To Produce Output Per Month Based On Variable Duration Entries <p>Ok, so I have a table that contains payments associated with dates and durations.</p> <p>Example data:</p> <pre><code>purchase_id date_purchased user_id duration (in months) amount_income 1 2013-12-28 00:00:00 1 2 £15 2 2014-01-04 00:00:00 2 1 £10 3 2014-02-04 00:00:00 3 6 £40 </code></pre> <p>*So the longer duration users pay for, the less they pay per month overall.</p> <p>What I'm trying to display is the total income per month based on this table. So a payment of £15 over 2 months would mean £7.50 income per month for 2 months.</p> <p>Sample output:</p> <pre><code>Month Amount 2013-12 £7.50 2014-01 £17.50 2014-02 £6.66 2014-03 £6.66 2014-04 £6.66 2014-05 £6.66 2014-06 £6.66 2014-07 £6.66 </code></pre> <p>This output corresponds to the sample input above. Hopefully it clarifies the breakdown of the income per month.</p> <p>Any ideas how to do this in a query?</p> |
40,139,193 | 0 | <p>Check to see if your version provides a variable named "yylineno", many of them do.</p> <p>I know flex 2.6.0 does.</p> |
24,432,502 | 0 | Force Storyboard to present specific base localization <p>I have a story board with base localisation (The story board itself is not localised) I wish to use base locazation to localize the app and still to be able to change the localization from within the app itself.</p> <p>Right now I am dong so with this approach -</p> <pre><code>+(NSString*)localizedStringForKey:(NSString*) key { NSBundle* languageBundle = [self localizationBundle]; NSString* str=[languageBundle localizedStringForKey:key value:@"" table:nil]; return str; } </code></pre> <p><strong>But</strong> this works only for dynamic strings that I assign in the code. Is there any way to force the story board to use specific base localizatio or should I give up using this option and create all the strings in code ?</p> <p>Thanks SHani</p> |
21,205,623 | 0 | Delete all messages in queue Websphere 8.5 SIB via JMX <p>I want to delete all the messages in a queue configured in Websphere 8.5 SIB. Below are two approaches I tried, but none of them seem to be working and each throws a different exception. Can someone please advise on what is the correct way to achieve this.</p> <p><strong>Approach 1</strong></p> <pre><code>MBeanServerConnection connection = getServerConnection(); connection.invoke(new ObjectName("WebSphere:*,type=SIBQueuePoint,name=jms.queue.MY_QUEUE"), "deleteAllQueuedMessages", null, null); </code></pre> <p>This approach throws the below exception.</p> <blockquote> <p>javax.management.InstanceNotFoundException: WebSphere:type=SIBQueuePoint,name=jms.queue.MY_QUEUE</p> </blockquote> <p><strong>Approach 2</strong></p> <pre><code>MBeanServerConnection connection = getServerConnection(); ObjectName objQueue = new ObjectName(WAS85_RESOURCE_URL + ",type=SIBQueuePoint"); Set<ObjectName> objNames = connection.queryNames(objQueue, null); for(ObjectName objName: objNames) { String qName = connection.getAttribute(objName,"identifier").toString(); if(qName.equals("jms.queue.MY_QUEUE")) { connection.invoke(objName, "deleteAllQueuedMessages", null, null); } } </code></pre> <p>This approach throws the below exception.</p> <blockquote> <p>javax.management.ReflectionException: Target method not found: com.ibm.ws.sib.admin.impl.JsQueuePoint.deleteAllQueuedMessages</p> </blockquote> |
28,342,101 | 0 | <p><code>IEnumerable<T></code> extends <code>IEnumerable</code>, so if you're implementing <code>IEnumerable<T></code>, you are automatically also implementing <code>IEnumerable</code>.</p> <p><code>IEnumerable</code> exists for one reason: because C# 1.0 did not have generics. Because of that, we now have to implement <code>IEnumerable</code> all the time, which is just kind of annoying.</p> <p>Your implementation is correct: when implementing IEnumerable, just have it call the generic version.</p> <pre><code>IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } </code></pre> |
19,606,523 | 0 | Using continue to skip iteration in foreach from inside a swich <pre><code>$arr = array('no want to print','foo','bar'); foreach($arr as $item){ switch($item){ case 'foo': $item = 'bar'; break; case 'not want to print': continue; break; } echo $item; } </code></pre> <p><a href="http://codepad.org/Ytkd8x2M" rel="nofollow">http://codepad.org/Ytkd8x2M</a></p> <p>But 'not want to print' is printed, Why does continue don't apply to the foreach?</p> |
39,533,353 | 0 | <p>Are you able to sort the group in Descending order? I have an idea but it will be less work for you if they're grouped newest to oldest.</p> <p><strong>WhileReadingRecords:</strong></p> <p>In each group you'll need to determine the 1st and 6th visit. (You're currently suppressing any groups with less than 6.) To do this, I would make a Shared Variable called <code>Counter</code> that increments by one every record <em>and</em> resets every time it reaches a new group. (Set it to zero in the Group Header.)</p> <p>Next you'll need two more Shared Variables called <code>FirstDate</code> and <code>SixthDate</code>. These populate with the date value if <code>Counter</code> equals one or six respectively. Just like <code>Counter</code> you'll reset these every time the group changes.</p> <p><strong>WhilePrintingRecords:</strong></p> <p>If everything works, you should now have the two dates values you need for calculations. Add an additional clause in your current Suppression formula:</p> <pre><code>.... AND DateDiff("d", FirstDate, SixthDate) </code></pre> |
17,337,706 | 0 | <p>I created a class named "MyTileOverlay" by extending TilesOverlay and it contins this class:</p> <p><a href="https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java?r=1086" rel="nofollow">https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java?r=1086</a></p> <p>Then when setting up the mapview, I do this:</p> <pre><code>this.mTilesOverlay = new MyTileOverlay(mProvider, this.getBaseContext()); </code></pre> <p>As instructed by kurtzmarc, I used handleTile() to check whether all tiles are being loaded or not:</p> <pre><code>@Override public void handleTile(final Canvas pCanvas, final int pTileSizePx, final MapTile pTile, final int pX, final int pY) { Drawable currentMapTile = mTileProvider.getMapTile(pTile); if (currentMapTile == null) { currentMapTile = getLoadingTile(); Log.d("Tile Null", "Null"); } else { Log.d("Tile Not Null", "Not Null"); } if (currentMapTile != null) { mTileRect.set(pX * pTileSizePx, pY * pTileSizePx, pX * pTileSizePx + pTileSizePx, pY * pTileSizePx + pTileSizePx); onTileReadyToDraw(pCanvas, currentMapTile, mTileRect); } if (DEBUGMODE) { mTileRect.set(pX * pTileSizePx, pY * pTileSizePx, pX * pTileSizePx + pTileSizePx, pY * pTileSizePx + pTileSizePx); mTileRect.offset(-mWorldSize_2, -mWorldSize_2); pCanvas.drawText(pTile.toString(), mTileRect.left + 1, mTileRect.top + mDebugPaint.getTextSize(), mDebugPaint); pCanvas.drawLine(mTileRect.left, mTileRect.top, mTileRect.right, mTileRect.top, mDebugPaint); pCanvas.drawLine(mTileRect.left, mTileRect.top, mTileRect.left, mTileRect.bottom, mDebugPaint); } } </code></pre> <p>This method ensures whether the loading procedure is finalized or not:</p> <pre><code>@Override public void finaliseLoop() { Log.d("Loop Finalized", "Finalized"); } </code></pre> <p>I can also use this method to identify whether all tiles have been loaded or not:</p> <pre><code>public int getLoadingBackgroundColor() { return mLoadingBackgroundColor; } </code></pre> <p>Hope this help someone!</p> |
32,179,601 | 0 | How to re-initialise data-sort on jQuery DataTables? <p>I am using jQuery Datatables in my project and I have made "custom value" sorting available on a column by using the attribute <code>data-sort</code> as described here: <a href="https://datatables.net/examples/advanced_init/html5-data-attributes.html" rel="nofollow">https://datatables.net/examples/advanced_init/html5-data-attributes.html</a></p> <p>Works fine. But now I am using Javascript/jQuery to update the values of these attributes, and the dataTable doesn't take into account the new values, it still sorts using the original values.</p> <p>Update is done on the attribute directly as such:</p> <pre><code>$('td#myColumnId').attr('data-order', newValue); </code></pre> <p>How can I force my dataTable to re-initialise my custom sort values?</p> <p>So far I have tried <code>.draw()</code> and <code>.dataTable()</code> but unfortunately that is not working.</p> <p>I'm looking forward to a possible solution.</p> |
36,821,726 | 0 | <p>Yes, you can. The Amazon SNS API is accessible and works using an HTTP protocol. All SDKs are just utility tools to make this communication easier.</p> <p>As you can see from the <a href="http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html" rel="nofollow">AWS SNS API docs here</a>, it is a matter of sending a <code>POST</code> request with correctly formulated HTTP Headers and body.</p> <pre><code>POST / HTTP/1.1 x-amz-sns-message-type: Notification x-amz-sns-message-id: da41e39f-ea4d-435a-b922-c6aae3915ebe x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic x-amz-sns-subscription-arn: arn:aws:sns:us-west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55 Content-Length: 761 Content-Type: text/plain; charset=UTF-8 Host: ec2-50-17-44-49.compute-1.amazonaws.com Connection: Keep-Alive User-Agent: Amazon Simple Notification Service Agent { "Type" : "Notification", "MessageId" : "da41e39f-ea4d-435a-b922-c6aae3915ebe", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Subject" : "test", "Message" : "test message", "Timestamp" : "2012-04-25T21:49:25.719Z", "SignatureVersion" : "1", "Signature" : "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55" } </code></pre> <p>You may learn how to sign and build correct requests in their docs (link provided above). So, you don't have to use SDK, and make your own requests. But, I would suggest using the SDK, since it addresses many security issues for you.</p> |
21,020,840 | 0 | <p>The second argument to <code>addEventListener</code> should be a function. You're not passing a function, you're calling the function immediately and passing the result. Change to:</p> <pre><code>document.getElementById("showF").addEventListener("click", function() { sacardatos('P1.txt','container'); }, false); </code></pre> |
7,302,698 | 0 | <p>Most likely it does not work because of your match pattern:</p> <ul> <li>the <code>{R:1}</code> will only match <code>(.*)</code> in your pattern, and will never match <code>files/123...</code></li> <li>URL in match pattern always starts with no leading slash: should be <code>files/\d+...</code> and not <code>/files/\d+...</code></li> </ul> <p>Try this one instead (works fine for me):</p> <pre><code><rule name="1" stopProcessing="true"> <match url="^files/\d+/.*\.html$" /> <action type="Redirect" url="default.aspx?url={R:0}" redirectType="Permanent" /> </rule> </code></pre> |
14,671,771 | 0 | Delete file after printing <p>I'm trying to delete a file after printing it without success.</p> <p>Practically, I need to print a PDF which is temporary generated (with text and image), then, when the printing process is done, I'd like to remove it.</p> <p>Currently the PDF is being saved in Documents directory. Is it a good idea to save it in Temp folder? But then I'd have to remove it anyways. I also have a tableView which shows the PDF the user <strong>saved</strong>, so I need to show only those (and not those <strong>temporarily</strong> generated)</p> <p>I've tried with UIPrinterInteractionController's delegate methods, but without any luck. </p> <pre><code>-(void)printInteractionControllerDidDismissPrinterOptions:(UIPrintInteractionController *)printInteractionController{ NSError *error; NSFileManager *fileMgr = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",PDFNameString]]; if ([fileMgr removeItemAtPath:filePath error:&error] != YES) { UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:NSLocalizedString(@"UnableToDeleteFile", @"Unable to delete file: %@"),[error localizedDescription]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease]; [alert show]; } NSLog(@"Dismissed"); } </code></pre> <p>The alert view pops up just when the printing options view leaves place to "Sending to printer.." view. It doesn't even delete the file, it says</p> <p>Cocoa error code 4.</p> <p>Does anyone know what method can I use to remove a file when the printing process is done?</p> <p><strong>EDIT</strong></p> <p>I NSLog'd if the file existed, and it doesn't. How is this possible?</p> |
26,345,855 | 0 | Finding specific duplicates when one field is different <p>I have a SQL DB table that has some data duplication. I need to find records based on the fact that none of the "duplicate" records has a value of Null value in one of the fields. i.e.</p> <pre><code>ID Name StartDate 1 Fred 1/1/1945 2 Jack 2/2/1985 3 Mary 3/3/1999 4 Fred null 5 Jack 5/5/1977 6 Jack 4/4/1985 7 Fred 10/10/2001 </code></pre> <p>In the example above I need to find Jack and Mary but not Fred. I assume some sort of Self Join or Union but have run into a mental block on what exactly would give me my desired results. </p> |
12,169,535 | 0 | <p>Something like this may get the job done:</p> <pre><code><?php function multi_attach_mail($to, $files, $sendermail){ // email fields: to, from, subject, and so on $from = "Files attach <".$sendermail.">"; $subject = date("d.M H:i")." F=".count($files); $message = date("Y.m.d H:i:s")."\n".count($files)." attachments"; $headers = "From: $from"; // boundary $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; // headers for attachment $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // multipart boundary $message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; // preparing attachments for($i=0;$i<count($files);$i++){ if(is_file($files[$i])){ $message .= "--{$mime_boundary}\n"; $fp = @fopen($files[$i],"rb"); $data = @fread($fp,filesize($files[$i])); @fclose($fp); $data = chunk_split(base64_encode($data)); $message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" . "Content-Description: ".basename($files[$i])."\n" . "Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; } } $message .= "--{$mime_boundary}--"; $returnpath = "-f" . $sendermail; $ok = @mail($to, $subject, $message, $headers, $returnpath); if($ok){ return $i; } else { return 0; } } ?> </code></pre> <p>I got that from the <a href="http://www.php.net/manual/en/function.mail.php" rel="nofollow">comments section of the mail function's page on php.net</a>. You can go there to see more examples of similar functions.</p> |
29,532,816 | 0 | PHP - Method with parameters as a parameter to other method <p>I am trying to get result from this method (1st param is the service name, 2nd is method with its own parameters):</p> <pre><code>$userFacade->getSet('users', 'findBy([], [\'id\' => \'DESC\'])') </code></pre> <p>This is the getSet method:</p> <pre><code>public function getSet($service, $function) { return new Set($this->$service->getRepository()->$function); } </code></pre> <p>All I want to achieve is to make writing of calls of the repository's functions easier. I haven't found anything useful yet because I don't know the proper term to search for (if there is one). I just wonder whether it's possible (how?) or not (ok...).</p> <p>Now I get an error:</p> <pre><code>Cannot read an undeclared property EntityRepository::$findBy([], ['id' => 'DESC']) </code></pre> |
40,390,809 | 0 | <p>I found this solution. But it's not very nice . </p> <pre><code>std::vector<int> list = {1,2,3,4}; std::vector<int> newList; std::for_each(list.begin(), list.end(),[&newList](int val){newList.push_back(val*2);}); </code></pre> |
20,885,994 | 0 | <p>Try this</p> <pre><code><Grid Background="LightGray" > <Grid.Triggers> <EventTrigger RoutedEvent="MouseEnter"> <BeginStoryboard> <Storyboard > <DoubleAnimation From="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Grid_Bd" Duration="0:0:0.1"></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="MouseLeave"> <BeginStoryboard> <Storyboard > <DoubleAnimation From="1" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Grid_Bd" Duration="0:0:0.1"></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger> </Grid.Triggers> <Grid Height="50" Width="50"> <Border x:Name="TextBlock_Bd" Opacity="0" BorderBrush="Blue" BorderThickness="1"/> <TextBlock Text="Hello !!" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock.Triggers> <EventTrigger RoutedEvent="MouseEnter"> <BeginStoryboard> <Storyboard > <DoubleAnimation From="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="TextBlock_Bd" Duration="0:0:0.1"></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="MouseLeave"> <BeginStoryboard> <Storyboard > <DoubleAnimation From="1" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="TextBlock_Bd" Duration="0:0:0.1"></DoubleAnimation> </Storyboard> </BeginStoryboard> </EventTrigger> </TextBlock.Triggers> </TextBlock> </Grid> <Border x:Name="Grid_Bd" Opacity="0" BorderBrush="Red" BorderThickness="1"/> </Grid> </code></pre> |
23,677,340 | 0 | <p>The syntax is like , please update as</p> <p>ALTER TABLE employee ADD CONSTRAINT fk_department </p> <p>FOREIGN KEY (departmentID) </p> <p>references department (departmentID);</p> |
8,530,194 | 0 | jQuery add empty label tags next to every radio button or checkbox <p>I need a simple jQuery code that will add an empty label tag next to every radio button or checkbox</p> <p>So for example:</p> <pre><code>$('input[type="radio"]').next().add("<label for="radio"></label>"); $('input[type="checkbox"]').next().add("<label for="checkbox"></label>"); </code></pre> <p>How can I accomplish this?</p> <p>Thanks.</p> |
14,734,445 | 0 | Java annotation processing API accessing import statements <p>I am writing an AnnotationProcessor which is supposed to generate java code. It should generate a derived interface from certain existing interfaces.</p> <p>For this purpose I need to find the import statements of the original input code, so that I can output it in the generated java file.</p> <p>How can this be done?</p> |
22,605,095 | 0 | JTable with different JComboBox-es for each row <p>I created <code>JTable</code> that contains information about employees. In this JTable I added the column called "Qualifications". This column is represented by <code>JComboBox</code> (different content at each row). For instance:</p> <pre><code>Row 1 | JComboBox(){"Programmer","Web"} Row 2 | JComboBox(){"Writer","Editor"} </code></pre> <p>The <code>JComboBox</code> content is taken from the <code>List<String> employees[row].getQualification()</code>.</p> <p>The problem is that the selected item in Row 1 and Row 2 is "Programmer", however "Programmer" should not appear in Row 2. Only when I click on <code>JComboBox</code>, the correct list appears, i.e. Row 2 - {"Writer","Editor"}.</p> <pre><code> TableColumn column = table.getColumnModel().getColumn(5); column.setCellRenderer(getRenderer()); private TableCellRenderer getRenderer() { return new TableCellRenderer() { private JComboBox<String> box = new JComboBox<String>(); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { for (String q : employees[row].getQualification()) box.addItem(q); box.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); box.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); return box; } }; } </code></pre> |
2,862,538 | 0 | <p>Use interfaces when you have several things that can perform a common set of actions. How they do those actions can be different, but when as far as using the classes they act the same.</p> <p>A good real world example is like a network drive vs a regular hard drive. Either way you can perform basic file operations. How they're actually done is different, but most of the time when you want to do something on a drive you don't care if it's a network drive or a physical one. That's an interface.</p> <p>In hardware, different keyboards are designed differently, they (could) have buttons in different locations, but none of that matters to the computer. The computer's view of a keyboard's interface is the same regardless of any aspects other than it sends key strokes.</p> |
27,103,075 | 0 | <p>In that context <code>$data</code> appears to be just a text. Probably you want <a href="http://knockoutjs.com/documentation/text-binding.html" rel="nofollow">text binding</a> like:</p> <pre><code><span data-bind="text: $data"></span> </code></pre> <p><a href="http://jsfiddle.net/bkdsuqax/1/" rel="nofollow">Jsfiddle</a></p> |
15,820,692 | 0 | <p>Found this <a href="http://www.openldap.org/faq/data/cache/883.html" rel="nofollow">FAQ</a> and it's not possible to have both classes because they are structurally different, so I have to choose one, which I think inetOrgPerson is a better option.</p> |
20,919,317 | 0 | how to use $group in mongodb/mongoose aggregation in grouping the subdocuments? <p>This corresponds to my question on <a href="http://stackoverflow.com/questions/20919149/how-to-use-mapreduce-in-mongoose-mongodb-query-subdocument">how to use mapreduce in mongoose/mongodb query subdocument?</a>, in that question, I used the map reduce to query the subdocument.</p> <p>Now I tried the solution of aggregation to query all the messages sent from 'user1'</p> <pre><code>model.aggregate( { $match: {user:'username'} }, // query the document { $unwind: "$msgs" }, // break the 'msgs' array into subdocuments { $match: { "msgs.s" : 'user1'} }, // match the filed in subdocuments { $project: { _id: 0, 'msgs.d':1,'msgs.m':1,'msgs.r':1 }}, // project the fileds { $group : { _id : "$_id", msgs : { $addToSet : "$msgs" } }}, // don't know how to group the data { $sort: {"msgs.d " : -1} }, function (err, data ) { if(err) callback(err); else callback(null,data); }) </code></pre> <p>the results I got is </p> <pre><code>[ { msgs: { m: 'I want to meet you', d: Sat Jan 04 2014 08:52:54 GMT+0000 (GMT), r: false } }, { msgs: { m: 'I want to meet you', d: Sat Jan 04 2014 08:53:02 GMT+0000 (GMT), r: false } }, { msgs: { m: 'I want to meet youd', d: Sat Jan 04 2014 08:53:06 GMT+0000 (GMT), r: false } }, ] </code></pre> <p>it is right results, but still not in good format, I think I don't know how to use the $group to group the subdocument into a flatten array.</p> <p>The result I want is </p> <pre><code>{'msgs':[ { m: 'I want to meet you', d: Sat Jan 04 2014 08:52:54 GMT+0000 (GMT), r: false }, { m: 'I want to meet you', d: Sat Jan 04 2014 08:53:02 GMT+0000 (GMT), r: false }, { m: 'I want to meet youd', d: Sat Jan 04 2014 08:53:06 GMT+0000 (GMT), r: false }, ]} </code></pre> <p>how to use the $group in aggregation?</p> <p>if I uncomment the $group in the query.</p> <p>the result I got is like the following</p> <pre><code>[ { _id: null, msgs:[ [Object], [Object], [Object], [Object], [Object] ] } ] </code></pre> <p>Thanks for JohnnyHK 's answer, it helps me a lot in understanding the aggregate. Now I have two more little problems</p> <p><strong>1.</strong> the subdocuments I fetched is not sorted according to the time, in my code, I used <code>{ $sort: {"msgs.d " : -1} }</code> in the query to sort all the subdocuments , but failed to work</p> <p><strong>2.</strong> If I need to add a 'sender' field in the results accompanied with all his sent messages, how can I do it in the $group I tried this way </p> <pre><code>{ $group : { sender : "$msgs.s", msgs : { $addToSet : "$msgs" } }} </code></pre> <p>or</p> <pre><code>{ $group : { sender : sender, msgs : { $addToSet : "$msgs" } }} </code></pre> <p>doesn't work</p> <p><strong>3.</strong> the current result gives me two levels of array, can I remove the first outer array, since it is not needed</p> |
10,950,584 | 0 | <p>Well, it turned out to be simpler than I thought. I decided to read the code of the plugin and modify it by commenting out the code that sorts my output.</p> <p>That is when I found a variable 'sortResults:true' in defaults. So, all I needed was to set that variable to false. I didn't find this in the documentation though.</p> <p><code>$('#search').autocomplete ( { url: "index.php", sortResults: false } )</code></p> <p>Now the output is in the exact order that I require.</p> <p>I got the idea of reading the code to find/solve the problem from here : <a href="http://stackoverflow.com/questions/2594297/jquery-autocomplete-plugin-is-messing-up-the-order-of-my-data">jQuery "Autocomplete" plugin is messing up the order of my data</a> (That isn't the same plugin)</p> <p>Thanks. :) </p> |
23,472,474 | 0 | <p>Another thing, make sure your connection is ok, reading <a href="http://docs.php.net/manual/pl/mysqli.construct.php" rel="nofollow">http://docs.php.net/manual/pl/mysqli.construct.php</a>,</p> <pre><code>mysqli_connect("localhost","root","","boats4u")or die(mysqli_error());; </code></pre> <p>will return an object anyway, so</p> <pre><code>or die(mysqli_error()); </code></pre> <p>won't execute because connect returns and object with ->connect_errno set</p> |
4,744,020 | 0 | How do I add multiple controls to a DataGridTemplateColumn of a datagrid using wpf? <p>I have several instances where I would like to have several controls in a single column in a datagrid.</p> <p>For example, I have a dataset that contains images with matching description, image source, timestamp, geotag, etc. I would like to display this information with a thumbnail image in one column and the majority of data in either a textbox or a label. Other datasets I have require textbox / checkbox, or textbox / combobox.</p> <p>When I attempt to add a second control I receive an error reporting that The property "VisualTree" is set more than once.</p> <pre><code><DataGridTemplateColumn Header="Data" Width="100"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Label Name="Description" Content="{Binding Desc}"></Label> <Label Name="Camera" Content="{Binding Camera}"></Label> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </code></pre> |
10,944,155 | 0 | <pre><code>for ( i = 0; i < MaxNum; i++) { $('li#' + i + '').html('<img src="http://www.address.com/somephp.php?Num="'+i+'" />'); } </code></pre> |
9,493,799 | 0 | <p>The problem is it takes a while for the scheduler to start the new tasks as it tries to determine if a task is long-running. You can tell the TPL that a task is long running as a parameter of the task:</p> <pre><code>for (int index = 0; index < numberOfTasks; index++) { int capturedIndex = index; rudeTasks.Add(Task.Factory.StartNew(() => { Console.WriteLine("Starting rude task {0} at {1}ms", capturedIndex, timer.ElapsedMilliseconds); Thread.Sleep(3000); }, TaskCreationOptions.LongRunning)); } </code></pre> <p>Resulting in:</p> <pre><code>Starting rude task 0 at 11ms Starting rude task 1 at 13ms Starting rude task 2 at 15ms Starting rude task 3 at 19ms Short-running task 0 running at 45ms Short-running task 1 running at 45ms Short-running task 2 running at 45ms Short-running task 3 running at 45ms Finished waiting for short tasks at 46ms Finished waiting for rude tasks at 3019ms </code></pre> |
10,199,617 | 0 | <p>Use :</p> <pre><code>$text = new Zend_Form_Element_Textarea('Text'); $text->setOptions(array('cols' => '4', 'rows' => '4')); </code></pre> |
23,612,601 | 0 | <p>It is because of the type of image, .jpg images will always be untransparent and you will see the square white box, i always use .png with transparency and no white box appears. </p> <p>Good luck</p> |
11,120,758 | 0 | Call Javascript functions from PHP <p>A common problem is that for validation you need to run the same code on the server and on the client. On a JavaScript heavy page there are many other function you like to share between both sides. Since you can't run PHP on the client I wounder if it's possible to run a Javascript function from PHP. I am thinking about <a href="http://en.wikipedia.org/wiki/Server-side_JavaScript" rel="nofollow">server-side JS</a> like <a href="http://en.wikipedia.org/wiki/Rhino_%28JavaScript_engine%29" rel="nofollow">Rhino</a> but I have no idea how to include it to PHP.</p> |
30,556,802 | 1 | Simple update field in elasticsearch <p>I started using Elsaticsearch and Sense few weeks ago. Now I need to bulk update String field in all the documents of certain index as follows: If the String starts with "+", update the field to same value without the "+".</p> <p>old: number: "+212112233" new: number: "212112233"</p> <p>Is there a simple way for me to do it with the REST DSL or do I need to use Python?</p> <p>Thanks!</p> |
17,626,663 | 0 | Can I connect any android device with ubuntu? <p>I came to know that we can use <code>adb</code> commands to detect android devices. But posts I read were specifically for HTC phones. So I want to know that can I connect any of my android device with ubuntu 12.x ? Or I will need to change some settings of that device? There are some local devices as well as sony xperia, about which I am thinking to buy but I want to make sure that by <code>adb</code> commands can I connect and use all devices equally on ubuntu or it varies from device to device?</p> |
38,540,009 | 0 | Create automatic tasks in wordpress <p>I want to make wordpress create automatic tasks from a text file and assign them to the users. Acctually the text file should be separated in paragraphs and each paragraph should be assigned to the users as a job. What can I do? Do we have a plugin for this process?</p> <p>Thanks</p> |
4,808,048 | 0 | <p>try putting a clustered index on the view. that will make the view persisted to disk like a normal table and your tables won't have to be accessed every time.</p> <p>that should speed things up a bit.</p> <p>for better answer please post the link to your original question to see if a better solution can be found.</p> |
6,382,543 | 0 | <p>You have a couple of choices. You can isolate the common functionality into a third object that <code>Class1</code> and <code>Class2</code> share (aggregation), or you can actually create a hierarchy of objects (inheritance). I'll talk about inheritance here.</p> <p>JavaScript doesn't have classes, it's a prototypical language. An object instance is "backed" by a <em>prototype</em> object. If you ask the instance for a property it doesn't have (and functions are attached to objects as properties), the JavaScript interpreter checks the prototype behind the object to see if <em>it</em> has the property (and if not, the prototype behind <em>that</em> object, etc., etc.). This is how prototypical inheritance works.</p> <p>JavaScript is an unusual prototypical language in that, until recently, there was no way to create an object and assign its prototype <em>directly</em>; you had to do it through constructor functions. If you're using class-based terminology, you're probably going to be more comfortable with constructor functions anyway. :-)</p> <p>Here's a basic inheritance setup (this is not how I would actually do this, more on that below):</p> <pre><code>// Constructs an Vehicle instance function Vehicle(owner) { this.owner = owner; } // Who's this Vehicle's owner? Vehicle.prototype.getOwner = function() { return this.owner; }; // Constructs a Car instance function Car(owner) { // Call super's initialization Vehicle.call(this, owner); // Our init this.wheels = 4; } // Assign the object that will "back" all Car instances, // then fix up the `constructor` property on it (otherwise // `instanceof` breaks). Car.prototype = new Vehicle(); Car.prototype.constructor = Car; // A function that drives the car Car.prototype.drive = function() { }; </code></pre> <p>Now we can use <code>Car</code> and get the features of <code>Vehicle</code>:</p> <pre><code>var c = new Car("T.J."); alert(c.getOwner()); // "T.J.", retrived via Vehicle.prototype.getOwner </code></pre> <p>The above is a bit awkward and it has a couple of issues with when things happen that can be tricky. It also has the problem that most of the functions are anonymous, and I don't like anonymous functions (function names <a href="http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html" rel="nofollow">help your tools help you</a>). It's also awkward to call your prototype's version of a function if you also have a copy of it (e.g., a "supercall" — not an uncommon operation with hierarchies). For that reason, you see a lot of "frameworks" for building hierarchies, usually using class-based terminology. Here's a list of some of them:</p> <ul> <li>The <code>Class</code> feature of <a href="http://prototypejs.org/" rel="nofollow">Prootype</a>, a general-purpose JavaScript library</li> <li>Dean Edwards' <a href="http://code.google.com/p/base2/" rel="nofollow">base2</a></li> <li>John Resig's <a href="http://ejohn.org/blog/simple-javascript-inheritance/" rel="nofollow">Simple JavaScript Inheritance</a> (Resig being the person who created jQuery)</li> <li>Er, um, <a href="http://blog.niftysnippets.org/2009/09/simple-efficient-supercalls-in.html" rel="nofollow">mine</a> — which as far as I know is being used by about three people. I did it because I had issues with decisions each of the above made. I will be updating it to not use class terminology (and actually releasing it as a tiny library, rather than just a blog post), because none of these adds classes to JavaScript, and acting as though they do misses the point of JavaScript prototypical model.</li> </ul> <p>Of those four, I'd recommend Resig's or mine. Resig's uses function decompilation (calling <code>toString</code> on function instances, which has never been standardized and doesn't work on some platforms), but it works even if function decompilation doesn't work, it's just slightly less efficient in that case.</p> <p>Before jumping on any of those, though, I encourage you to look at the <a href="http://javascript.crockford.com/prototypal.html" rel="nofollow">true prototypical approach</a> advocated by Douglas Crockford (of JSON fame, also a big wig at YUI). Crockford had a great deal of input on the <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" rel="nofollow">latest version of ECMAScript</a>, and some of his ideas (most notably <code>Object.create</code>) are now part of the latest standard and are finding their way into browsers. Using <code>Object.create</code>, you can <em>directly</em> assign a prototype to an object, without having a constructor function.</p> <p>I prefer constructor functions (with my syntactic help) for places where I need inheritance, but Crockford's approach is valid, useful, and gaining popularity. It's something you should know about and understand, and then choose when or whether to use.</p> |
34,214,325 | 0 | <p>I recommend using a <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html" rel="nofollow">ScheduledThreadPoolExecutor</a> with a core pool size of <code>1</code> and optionally with a thread priority of <code>Thread.NORM_PRIORITY + 1</code> (use a <a href="https://guava-libraries.googlecode.com/svn/tags/release05/javadoc/com/google/common/util/concurrent/ThreadFactoryBuilder.html" rel="nofollow">ThreadFactoryBuilder</a> to create a <code>ThreadFactory</code> with higher than standard priority) for the UI thread - this will let you schedule tasks such as the counter increment using <code>ScheduledThreadPoolExecutor#scheduleAtFixedRate</code>. Don't execute anything other than UI tasks on this executor - execute your CPU tasks on a separate <code>ThreadPoolExecutor</code> with standard priority; if you have e.g. 16 logical cores then create a <code>ThreadPoolExecutor</code> with 16 core threads to make full use of your computer when the UI thread is idle, and let the virtual machine take care of ensuring that the UI thread executes its jobs when it's supposed to.</p> |
8,943,778 | 0 | <p>To initialize many contacts in a loop you may want to do something like this:</p> <pre><code>Contact *FirstOne = new Contact(); Contact *current = FirstOne; while(...) { current->next = new Contact(); current = current->next; //do stuff to current, like adding info } </code></pre> <p>That way you are building up your Contact list. After that <code>*FirstOne</code> ist the first and <code>*current</code> is the last element of your list. Also you may want to make sure that the constructor sets *next to NULL to detect the end of the list.</p> |
9,524,898 | 0 | <p><strong>Updated Answer</strong>: I still have spent way too much time on this :-), especially when it ended up so simple. <em>It allows for a background to be sized based on the height of the container</em>, which seems to be different than yunzen's solution. <strong>Now does use <code>margin: 0 auto;</code></strong>. Still grows with container height.</p> <p><a href="http://jsfiddle.net/CNxCb/219/"><strong>View the new answer.</strong></a></p> <p>You can <a href="http://jsfiddle.net/CNxCb/214/"><strong>view the original, more complex answer</strong></a> which does not use <code>auto</code> margin. </p> <h2>HTML:</h2> <pre><code><div id="Bkg"> <div id="Content">Content goes here. </div> </div> </code></pre> <h2>CSS:</h2> <pre><code>#Bkg { width: 100%; min-width: 300px; /* equals width of content */ background:url('http://dummyimage.com/400x20/ffff00/000000&text=Center') repeat-y top center; padding-bottom: 50px; } #Content { width: 300px; margin: 0 auto; } </code></pre> |
4,598,017 | 0 | Counting process instances using Batch <p>Im trying to count the number of php-cgi.exe processes on my server 2003 system using "tasklist" and grep <a href="http://gnuwin32.sourceforge.net/packages/grep.htm" rel="nofollow">for windows</a>. I would like to avoid writing to any temp files.</p> <pre><code>call set _proc_cnt = tasklist /fi "Imagename eq php-cgi.exe" /nh /fo CSV| grep -c -e "php-cgi" echo %_proc_cnt% pause </code></pre> <p>Heres what I get when I run that</p> <pre><code>C:\Users\gm\Desktop>call set _proc_cnt = tasklist /fi "Imagename eq php-cgi.exe" /nh /fo CSV | grep -c -e "php-cgi" 0 C:\Users\gm\Desktop>echo ECHO is on. C:\Users\gm\Desktop>pause Press any key to continue . . . </code></pre> <p>Does anyone have any tips on why that doesnt work?</p> |
28,801,361 | 0 | LinkedLists, building a toString method for custom linked list class <p>I'm struggling with completing this <code>toString()</code> method within my linked list class called <code>LString</code></p> <p>The class creates an LString object that mimics String and StringBuilder with a linked list rather than an array. It creates strings out of linked lists.</p> <p>Here is the code for the method:</p> <pre><code>public String toString(){ StringBuilder result = new StringBuilder(); node curr = front; while (curr != null){ result.append(curr.data); curr = curr.next; } return result.toString(); } </code></pre> <p>I have tried several different things, and I think I'm close to figuring it out. But I can't move forward from this error message:</p> <pre><code>Running constructor, length, toString tests (10 tests) Starting tests: .......E.E Time: 0.009 There were 2 failures: 1) t11aLStringOfStringToString[1](LStringTest$LStringOfStringTest) org.junit.ComparisonFailure: LString("ab").toString() is wrong. expected:<[a]b> but was:<[]b> at org.junit.Assert.assertEquals(Assert.java:115) at LStringTest$LStringOfStringTest.t11aLStringOfStringToString(LStringTest.java:221) ... 10 more 2) t11aLStringOfStringToString[2](LStringTest$LStringOfStringTest) org.junit.ComparisonFailure: LString("This is a long string.").toString() is wrong. expected:<[This is a long string].> but was:<[].> at org.junit.Assert.assertEquals(Assert.java:115) at LStringTest$LStringOfStringTest.t11aLStringOfStringToString(LStringTest.java:221) ... 10 more Test Failed! (2 of 10 tests failed.) Test failures: abandoning other phases. </code></pre> <p>The <code>LString</code> class uses another class, LStringTest.java to do various tests. This error message is from running LStringTest.java, but the method that I'm working on is within LString. It is the, <code>LString("ab").toString() is wrong</code> bit.</p> <p>For some context, here is the rest of my class:</p> <pre><code>public class LString { // 2. Fields node front; //node tail; int size; // 1. Node class private class node { char data; node next; //constructors //1. default public node (){ } //2. data public node (char newData){ this.data = newData; } //3. data + next public node (char newData, node newNext){ this.data = newData; this.next = newNext; } } // 3. Constructors public LString(){ this.size = 0; this.front = null; } public LString(String original) { for (int i =0; i < original.length(); i++) { this.front = new node(original.charAt(i)); } this.size = original.length(); } // 4. Methods public int length() { return this.size; } public int compareTo(LString anotherLString) { return 0; } public boolean equals(Object other) { if (other == null || !(other instanceof LString)) { return false; } else { LString otherLString = (LString)other; return true; } } public char charAt(int index) { return 'a'; } public void setCharAt(int index, char ch) { ch = 'a'; } public LString substring(int start, int end) { return null; } public LString replace(int start, int end, LString lStr) { return null; } //append public void append(char data){ this.size++; if (front == null){ front = new node(data); return; } node curr = front; while (curr.next != null){ curr = curr.next; } curr.next = new node(data); } //prepend public void prepend (char data){ /*node temp = new node(data); temp.next = front; front = temp;*/ front = new node(data, front); size++; } //delete public void delete(int index){ //assume that index is valid if (index == 0){ front = front.next; } else { node curr = front; for (int i = 0; i < index - 1; i++){ curr = curr.next; } curr.next = curr.next.next; } size--; } //toString public String toString(){ StringBuilder result = new StringBuilder(); //result.append('['); node curr = front; while (curr != null){ //result.append('['); result.append(curr.data); curr = curr.next; //result.append(']'); //if (curr.next != null){ //} } //result.append(']'); return result.toString(); } //add (at an index) public void add(int index, char data){ if (index == 0){ front = new node(data, front); } else { node curr = front; for (int i = 0; i < index - 1; i++){ curr = curr.next; } curr.next = new node(data, curr.next); } } } </code></pre> |
28,754,371 | 0 | Sublime Text 3 Hides scrollbars <p>I would prefer to always see the scroll-bars in Sublime Text 3. The current behavior is for them to remain hidden until you start scrolling. Is there a setting I can change to make it behave this way? Is it part of the theme? Right now I am making the scroll-bars larger by modifying my theme (<a href="https://packagecontrol.io/packages/Theme%20-%20Cyanide">Cyanide</a>)... I have</p> <pre><code>// in Cyanide.sublime-theme [ { "class": "scroll_bar_control", "attributes": ["horizontal"], "content_margin": [3, 4] //makes horiz scrollbar taller }, { "class": "scroll_bar_control", "content_margin": [1, 3] //makes vert scrollbar taller } ] </code></pre> |
33,196,959 | 0 | <p>If you are using a function inside the template, it generally will run twice times. That is the way AngularJS ensures the function was ran.</p> <p><a href="http://jsfiddle.net/iagomelanias/U3pVM/19526/" rel="nofollow noreferrer">You can see the same happening in this JSFIddle example.</a></p> <p><a href="https://i.stack.imgur.com/PZ8sM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PZ8sM.png" alt="enter image description here"></a></p> <p><strong>HTML:</strong></p> <pre><code><div ng-app> <div ng-controller="ExampleCtrl"> {{hey()}} </div> </div> </code></pre> <p><strong>JS:</strong></p> <pre><code>function ExampleCtrl($scope) { $scope.hey = function() { console.log('here i am'); } } </code></pre> <h2>So, what to do?</h2> <p>Do not load the data using a function in the template, load it directly when the controller is initialized. <a href="http://jsfiddle.net/iagomelanias/U3pVM/19528/" rel="nofollow noreferrer">As in this example.</a></p> <pre><code>function ExampleCtrl($scope, $http) { $http.get(...); } </code></pre> <p><strong><em>PS:</strong> are you not using the get method from jQuery, yep? Please. AngularJS has your own http methods. <a href="https://docs.angularjs.org/api/ng/service/$http" rel="nofollow noreferrer">See here</a>.</em></p> |
1,339,035 | 0 | <p>I believe it's just the nature of a browser to often request the favicon.ico file for whatever reason, whether or not it even exists.</p> |
22,039,248 | 0 | <p>Well, you aren't sending any data to the server, so the server doesn't know there have been any changes.</p> <p>You can use a submit button:</p> <pre><code><a4j:commanButton process="listShuttleId" value="Submit"> </code></pre> <p>or you can have the changes sent to server as they're happening by putting this inside the listShuttle:</p> <pre><code><a4j:support event="onlistchanged" /> </code></pre> |
33,553,724 | 0 | <p>With this type of problem getting the time spent splitting the data up for parallel processing and then putting it back together to be less than the time to process it in a sequence can be tricky. </p> <p>In the problem above, if i'm interpreting it correctly you are generating two sequences of data, each in parallel. So these sequences can't communicate with each other during this process to see if they have a later date. Once all of the data for both sequences is finished then you form it into a map. and then split that map back into a sequence and start processing it. </p> <p>The first pair of dates, (first loc) and (first mob), will be sitting for quite a while before they can be compared to see if they should go into the final result. so the best speedup may come from simply removing the call to zipmap.</p> <p><code>time/after?</code> is very fast so you will <b>almost certainly loose time</b> by calling pmap here, though it's good to know how to do it anyway. You can get aroung the inability of the anonymous function macro to handle nested anonymous functions by making one of tham a call to <code>fn</code> like so:</p> <pre><code>(keep (fn [x] (when (pmap #(later-date? (second x) after) zip)) [(first %) (second %)]) </code></pre> <p>Another approach is to </p> <ol> <li>break it into partitions, </li> <li>do all the processing on each partition, and </li> <li>merge them back together. </li> </ol> <p>Then <b>adjust the partition size until you see a benefit</b> over the splitting costs. </p> <p>This has been discussed <a href="http://stackoverflow.com/questions/1702705/how-to-efficiently-apply-a-medium-weight-function-in-parallel">here</a>, and <a href="http://stackoverflow.com/questions/2103599/better-alternative-to-pmap-in-clojure-for-parallelizing-moderately-inexpensive-f">here</a></p> |
20,624,287 | 0 | <p><code><li></code> has optional close tags, so if the browser sees another <code><li></code> before a correpsonding <code></li></code>, it implicitly inserts a close for the previous tag. You can verify this using the DOM inspector in your browser's developer tools. This means that Item 3's "subitems" are actually siblings to Item 3.</p> <p><img src="https://i.stack.imgur.com/3p7X0.png" alt="DOM view"></p> <ul> <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/grouping-content.html#the-li-element" rel="nofollow noreferrer">Relevant WHATWG spec showing optional close tag</a></li> <li><a href="http://www.w3.org/TR/html-markup/li.html" rel="nofollow noreferrer">W3 spec showing optional close tag</a></li> </ul> |
13,687,738 | 0 | OpenRasta Unit Testing GET results in 404 error <p>I've completed my implementation of my first OpenRasta RESTful webservice and have successfully got the GET requests I wish for working.</p> <p>Therefore I've taken some 'inspiration' from Daniel Irvine with his post <a href="http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/" rel="nofollow">http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/</a> to built a automated test project to test the implmentation.</p> <p>I've created my own test class but I'm constantly getting a 404 error as the reponse status code.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenRasta.Hosting.InMemory; using PoppyService; using OpenRasta.Web; using System.IO; using System.Runtime.Serialization.Json; using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework; namespace PoppyServiceTests { //http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/ [TestFixture] class OpenRastaJSONTestMehods { [TestCase("http://localhost/PoppyService/users")] public static void GET(string uri) { const string PoppyLocalHost = "http://localhost/PoppyService/"; if (uri.Contains(PoppyLocalHost)) GET(new Uri(uri)); else throw new UriFormatException(string.Format("The uri doesn't contain {0}", PoppyLocalHost)); } [Test] public static void GET(Uri serviceuri) { using (var host = new InMemoryHost(new Configuration())) { var request = new InMemoryRequest() { Uri = serviceuri, HttpMethod = "GET" }; // set up your code formats - I'm using // JSON because it's awesome request.Entity.ContentType = MediaType.Json; request.Entity.Headers["Accept"] = "application/json"; // send the request and save the resulting response var response = host.ProcessRequest(request); int statusCode = response.StatusCode; NUnit.Framework.Assert.AreEqual(200, statusCode, string.Format("Http StatusCode Error: {0}", statusCode)); // deserialize the content from the response object returnedObject; if (response.Entity.ContentLength > 0) { // you must rewind the stream, as OpenRasta // won't do this for you response.Entity.Stream.Seek(0, SeekOrigin.Begin); var serializer = new DataContractJsonSerializer(typeof(object)); returnedObject = serializer.ReadObject(response.Entity.Stream); } } } } </code></pre> <p>}</p> <p>If I navigate to the Uri manually in the browser I'm getting the correct responce and HTTP 200.</p> <p>It's possibly something to do with my Configuration class, but if I test all the Uris manaully again I get the correct result.</p> <pre><code>public class Configuration : IConfigurationSource { public void Configure() { using (OpenRastaConfiguration.Manual) { ResourceSpace.Has.ResourcesOfType<TestPageResource>() .AtUri("/testpage").HandledBy<TestPageHandler>().RenderedByAspx("~/Views/DummyView.aspx"); ResourceSpace.Has.ResourcesOfType<IList<AppUser>>() .AtUri("/users").And .AtUri("/user/{appuserid}").HandledBy<UserHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<AuthenticationResult>() .AtUri("/user").HandledBy<UserHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<Client>>() .AtUri("/clients").And .AtUri("/client/{clientid}").HandledBy<ClientsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<Agency>>() .AtUri("/agencies").And .AtUri("/agency/{agencyid}").HandledBy<AgencyHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<ClientApps>>() .AtUri("/clientapps/{appid}").HandledBy<ClientAppsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<Client>() .AtUri("/agencyclients").And .AtUri("/agencyclients/{agencyid}").HandledBy<AgencyClientsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<Client>() .AtUri("/agencyplususerclients/{appuserid}").HandledBy<AgencyPlusUserClientsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<Permission>>() .AtUri("/permissions/{appuserid}/{appid}").HandledBy<PermissionsHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<Role>>() .AtUri("/roles").And .AtUri("/roles/{appuserid}").And.AtUri("/roles/{appuserid}/{appid}").HandledBy<RolesHandler>().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType<IList<AppVersion>>() .AtUri("/userappversion").And .AtUri("/userappversion/{appuserid}").HandledBy<UserAppVersionHandler>().AsJsonDataContract(); } } } </code></pre> <p>Any suggestions would be greatfully received.</p> |
9,368,417 | 0 | DataSets in C#.NET -- How to access related tables via a universal row <p>I have a situation where previously a simple DataTable worked (because I was using an DataAdapter that only hit <em>one</em> table in my relation system). Recently however I'm joining three tables (done in the query that gets sent to my rdb) and it looks can only access one via a DataTable.</p> <p>Is there a way to iterate over some universal row (i.e. one row that has columns of all tables joined via a foreign key link) element in a DataSet?</p> <p>Also currently all of this data from three tables is getting put into a single DataTable via OdbcDataAdapter.Fill(myDataTable). I would really like to be able to do something like:</p> <pre><code>string s1 = myDataTable.Rows[i]["table1.someCol"], s2 = myDataTable.Rows[i]["table2.someCol"]; </code></pre> <p>Are either of these possible, and if not how should one handle this situation? Thanks in advance.</p> |
36,015,321 | 0 | <p>You can use <code>duplicated</code> to subset the data and then call <code>table</code>:</p> <pre><code>table(subset(df, !duplicated(paste(col1, col2)), select = col1)) #app chh gg # 1 1 2 </code></pre> <p>As a second option, here's a dplyr approach:</p> <pre><code>library(dplyr) distinct(df) %>% count(col1) # or distinct(df, col1, col2) if you have other columns #Source: local data frame [3 x 2] # # col1 n # (fctr) (int) #1 app 1 #2 chh 1 #3 gg 2 </code></pre> |
5,559,029 | 0 | Quickly switching buffers in Vim normal mode <p>Recently I found out that I'm <a href="http://stackoverflow.com/questions/102384/using-vims-tabs-like-buffers/103590#103590">"using tabs incorrectly" in Vim</a>. I've been trying to just use buffers in Vim since, assisted through <a href="https://github.com/fholgado/minibufexpl.vim/">MiniBufExplorer</a>, but I find it painful because of how many keystrokes it takes to change buffers from normal mode. With tabs, I can just do <kbd>g</kbd><kbd>t</kbd> or <kbd>g</kbd><kbd>T</kbd> to hop back and forth between tabs in normal mode, and I can also do <kbd>NUMBER</kbd><kbd>g</kbd><kbd>t</kbd> to go to a specific tab.</p> <p>With buffers, I either have to enter command mode with <code>:bn</code>, <code>:bp</code>, or with MiniBufExplorer, use <kbd>Ctrl + k</kbd> or <kbd>Ctrl + Up</kbd> to hop up to the buffer window, scroll left or right with <kbd>h</kbd> and <kbd>l</kbd> and then hit <kbd>Enter</kbd> to select the buffer I want. Or I can do something involving a leader sequence, but it always requires removing multiple fingers away from home row. That's a real pain.</p> <p>How can I get something equivalent switching tabs in normal mode to switch buffers in normal mode, so I can do something like <kbd>g</kbd><kbd>n</kbd>/<kbd>g</kbd><kbd>p</kbd> for <code>:bn</code>/<code>:bp</code> and <kbd>NUMBER</kbd><kbd>g</kbd><kbd>n</kbd> for <code>:buf NUMBER</code>?</p> |
32,635,832 | 0 | How to serialize integer to ApplicationDataContainer <p>I am porting an old game to Windows 10 store app. I can write and then read string to app settings:</p> <pre><code>ApplicationDataContainer^ localSettings = ApplicationData::Current->LocalSettings; localSettings->Values->Insert("keyS", "hello"); String^ valueS = safe_cast<String^>(localSettings->Values->Lookup("keyS")); </code></pre> <p>I also can put <code>int</code> value:</p> <pre><code>localSettings->Values->Insert("keyI", 123); </code></pre> <p>But how do I read it?</p> <pre><code>??? valueI = safe_cast<???>(localSettings->Values->Lookup("keyI")); </code></pre> <p><code>Lookup</code> returns <code>Platform::Object^</code>, so how do I cast it to <code>int</code>?</p> |
35,961,657 | 0 | <p>If you look closely to the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html" rel="nofollow">Collections API</a>, you will see that you have two options at your disposal:</p> <p>1) make your GetTraders class implement the Comparable interface and call</p> <pre><code>public static <T extends Comparable<? super T>> void sort(List<T> list) </code></pre> <p>2) create a new Comparator for the GetTraders class and call</p> <pre><code>public static <T> void sort(List<T> list, Comparator<? super T> c) </code></pre> <p>The first solution is the easiest one but if you need to sort the GetTraders objects according to multiple criteria then the second one is the best choice.</p> <p>As pointed out by @Vaseph, if you are using Java 8 instead, life suddenly becomes easier because all you need to do is:</p> <pre><code>traders.sort((GetTraders trade1, GetTraders trade2) -> { return trade1.getBusinessName().compareTo(trade2.getBusinessName()); }); </code></pre> <p>But if you are having troubles with the Comparable and Comparator interfaces, I would encourage you to first try the pre-Java-8 solutions before diving into the magic world of the functional interfaces.</p> <hr> <p>For the sake of completeness, please also find below an example of each solution:</p> <p>1) Comparable-based solution:</p> <pre><code>import java.util.ArrayList; import java.util.Collections; import java.util.List; public class GetTraders1 implements Comparable<GetTraders1> { private String getTraderLegalName; private String businessName; private Object status; public GetTraders1(String getTraderLegalName, String businessName, String status) { this.getTraderLegalName=getTraderLegalName; this.businessName=businessName; this.status=status; } @Override public int compareTo(GetTraders1 that) { return this.getTraderLegalName.compareTo(that.getTraderLegalName); } @Override public String toString() { return "GetTraders [getTraderLegalName=" + getTraderLegalName + ", businessName=" + businessName + ", status=" + status + "]"; } public static void main(String[] args) { GetTraders1 getTraders1 = new GetTraders1("1", "bn", "status"); GetTraders1 getTraders2 = new GetTraders1("2", "bn", "status"); GetTraders1 getTraders3 = new GetTraders1("3", "bn", "status"); List<GetTraders1> list = new ArrayList<>(); list.add(getTraders3); list.add(getTraders2); list.add(getTraders1); System.out.println(list); Collections.sort(list); System.out.println(list); } } </code></pre> <p>2) Comparator-based solution</p> <pre><code>import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class GetTraders2 { private String getTraderLegalName; private String businessName; private Object status; public GetTraders2(String getTraderLegalName, String businessName, String status) { this.getTraderLegalName=getTraderLegalName; this.businessName=businessName; this.status=status; } @Override public String toString() { return "GetTraders [getTraderLegalName=" + getTraderLegalName + ", businessName=" + businessName + ", status=" + status + "]"; } public static void main(String[] args) { GetTraders2 getTraders1 = new GetTraders2("1", "bn", "status"); GetTraders2 getTraders2 = new GetTraders2("2", "bn", "status"); GetTraders2 getTraders3 = new GetTraders2("3", "bn", "status"); List<GetTraders2> list = new ArrayList<>(); list.add(getTraders3); list.add(getTraders2); list.add(getTraders1); System.out.println(list); Collections.sort(list, new Comparator<GetTraders2>() { @Override public int compare(GetTraders2 o1, GetTraders2 o2) { return o1.getTraderLegalName.compareTo(o2.getTraderLegalName); } }); System.out.println(list); } } </code></pre> |
18,484,561 | 0 | <p>This is not a very nice fix but it works:</p> <p>CSS:</p> <pre><code>.new-tab-opener { display: none; } </code></pre> <p>HTML:</p> <pre><code><a data-href="http://www.google.com/" href="javascript:">Click here</a> <form class="new-tab-opener" method="get" target="_blank"></form> </code></pre> <p>Javascript:</p> <pre><code>$('a').on('click', function (e) { var f = $('.new-tab-opener'); f.attr('action', $(this).attr('data-href')); f.submit(); }); </code></pre> <p>Live example: <a href="http://jsfiddle.net/7eRLb/" rel="nofollow">http://jsfiddle.net/7eRLb/</a></p> |
8,387,988 | 0 | <p>Perhaps the most natural thing to do here is to present the login view controller modally. When the user has logged in successfully, the first controller can then push the third view controller onto the navigation stack. This way, the back button will lead directly back to the first view controller, and the user will understand why.</p> |
14,888,591 | 0 | google maps marker clusterer not working in IE7 & IE8 due to an 'is null or not an object' error <p><a href="http://expertforum.ro/extra/harta-bugetelor/primarii.html" rel="nofollow">I have a google Map</a> (js api v3) + marker clusterer which doesn't display in Internet Explorer 7 & 8 - I get the classical js error:</p> <blockquote> <p>Message: 'addresses[...].lt' is null or not an object</p> </blockquote> <p>On the other hand, <a href="http://expertforum.ro/extra/harta-bugetelor/judete.html" rel="nofollow">this other example</a> which uses a very similar json file, but doesn't use marker clusterer - displays the same error, but renders the markers on the map.</p> <p>So I'm not even sure it's .json syntax error, rather something that bothers the marker clusterer instance, but I have no idea what</p> |
5,810,714 | 0 | <p>I think you just need the <a href="http://office.microsoft.com/en-us/access-help/all-distinct-distinctrow-top-predicates-HA001231351.aspx" rel="nofollow">DISTINCT</a> keyword:</p> <p>Basically:</p> <pre><code>SELECT DISTINCT F2, F3, F4 FROM Table; </code></pre> |
26,631,222 | 0 | cannot resolve method setGroup <p>I wanted to assign a notification to a group with <code>setGroup()</code> for stacking notifications and summarising them. </p> <p>Like <a href="https://developer.android.com/training/wearables/notifications/stacks.html" rel="nofollow">HERE</a></p> <pre><code>final static String GROUP_KEY_SAPPHIRE = "group_key_emails"; NotificationCompat.Builder oneBuilder = new NotificationCompat.Builder(this); oneBuilder.setSmallIcon(R.drawable.warning_icon) .setContentTitle("Warning: ") .setContentText(message) .setPriority(0x00000002) .setLights(Color.GREEN, 500, 500) .setGroup(GROUP_KEY_SAPPHIRE) .addAction (R.drawable.ic_action_accept_dark, getString(R.string.ok), warningPendingIntent); NotificationManager oneNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); oneNotificationManager.notify(NOTIFICATION_ID, oneBuilder.build()); editText.setText(""); </code></pre> <p>But I always got the response that the method setGroup couldn't be resolved. I've imported the <strong>.v4.support library</strong>.</p> <p>Thanks in advance</p> |
19,145,414 | 0 | NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning. Source: http://nltk.org/ |
23,194,727 | 0 | <p>dynamically allocate memory for a <code>int</code>.<br> everytime you get a element satisfying the condition and add the element to a dynamically allocated array of integer.<br> use <code>realloc()</code> to increase the size of the <code>int</code> array pointed by some pointer and add the new element to that array.<br> use counter to know the number of elements in array.</p> |
37,662,348 | 0 | <p>This is a <a href="https://github.com/bower/bower/issues/2262" rel="nofollow">permissions with Bower</a>, as suggested from the error (not a Cloud9 specific issue).</p> <p>Use the following to fix it:</p> <p><code>sudo chown -R $USER:$GROUP ~/.npm</code></p> <p><code>sudo chown -R $USER:$GROUP ~/.config</code></p> |
30,688,497 | 0 | <p>You just need to add a space between <code>a++</code> and <code>{</code>:</p> <pre><code>for var a = 0; a < 10; a++ { println(a) } </code></pre> |
40,864,199 | 0 | Couldn't get facebook Pages and groups details with facebook C# SDK <p>I have integrated facebook DLL into my desktop application (C#.Net), in this one need to authenticate facebook account via OAuth and its working correctly. I got Access Token also and email too. But i want to access users pages and groups also, for this i have mentioned extendedPermissions like below:</p> <p>FacebookExtendedPermissions = "email,user_groups,publish_stream,manage_pages"</p> <p>I have used below block of code for getting users Page details:</p> <pre><code> FacebookClient _fb = new FacebookClient(); _fb.AccessToken = FacebookOAuthResult.AccessToken; dynamic results = _fb.Get("/me/accounts"); </code></pre> <p>But i'm gatting empty value in data. What i'm doing wrong here can't get it.</p> <p>I have tried in other way too like this:</p> <pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/me/accounts?access_token=" + longLivedToken); request.AutomaticDecompression = DecompressionMethods.GZip; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string html = reader.ReadToEnd(); } </code></pre> <p>But again no luck. Any help or pointers will be much appreciated. Thanks in advance.</p> |
27,120,879 | 0 | <p>Use 2 variables. First variable will store the last execution date and the next one will store the version. Whenever you execute the script, first check if the date is same. If yes, increment the version else set the version to 1. Export the variables so that they retain their values.</p> <pre><code>if [ "`date +'%Y%m%d'`" == "$LAST_EXEC_DATE" ]; then (( VERSION += 1 )) else VERSION=1 LAST_EXEC_DATE=`date +"%Y%m%d"` fi export LAST_EXEC_DATE export VERSION </code></pre> |
7,480,440 | 0 | Canvas Height & Width Problem <p>My Problem is I am Using Face Detector Example from Following Link but How To Find Square Height & Width and Replace Image on Square Same as Square Height & Width.Sorry for Bad English Communication.</p> <p><a href="http://downloads.ziddu.com/downloadfile/9930500/AndroidFaceDetector_files_100520a.zip.html" rel="nofollow">http://downloads.ziddu.com/downloadfile/9930500/AndroidFaceDetector_files_100520a.zip.html</a></p> <p>Please Help Me.</p> |
412,696 | 0 | <p>While I adore the grep solution for its elegance and for reminding (or teaching) me about a method in Enumerable that I'd forgotten (or overlooked completely), it's slow, slow, slow. I agree 100% that creating the <code>Array#mode</code> method is a good idea, however - this is Ruby, we don't need a library of functions that act on arrays, we can create a mixin that adds the necessary functions <em>into</em> the Array class itself.</p> <p>But the inject(Hash) alternative uses a sort, which we also don't really need: we just want the value with the highest occurrence.</p> <p>Neither of the solutions address the possibility that more than one value may be the mode. Maybe that's not an issue in the problem as stated (can't tell). I think I'd want to know if there was a tie, though, and anyway, I think we can improve a little on the performance.</p> <pre><code>require 'benchmark' class Array def mode1 sort_by {|i| grep(i).length }.last end def mode2 freq = inject(Hash.new(0)) { |h,v| h[v] += 1; h } sort_by { |v| freq[v] }.last end def mode3 freq = inject(Hash.new(0)) { |h,v| h[v] += 1; h } max = freq.values.max # we're only interested in the key(s) with the highest frequency freq.select { |k, f| f == max } # extract the keys that have the max frequency end end arr = Array.new(1_000) { |i| rand(100) } # something to test with Benchmark.bm(30) do |r| res = {} (1..3).each do |i| m = "mode#{i}" r.report(m) do 100.times do res[m] = arr.send(m).inspect end end end res.each { |k, v| puts "%10s = %s" % [k, v] } end </code></pre> <p>And here's output from a sample run.</p> <pre><code> user system total real mode1 34.375000 0.000000 34.375000 ( 34.393000) mode2 0.359000 0.000000 0.359000 ( 0.359000) mode3 0.219000 0.000000 0.219000 ( 0.219000) mode1 = 41 mode2 = 41 mode3 = [[41, 17], [80, 17], [72, 17]] </code></pre> <p>The "optimised" mode3 took 60% of the time of the previous record-holder. Note also the multiple highest-frequency entries.</p> <p>EDIT</p> <p>A few months down the line, I noticed <a href="http://stackoverflow.com/questions/412169/ruby-how-to-find-item-in-array-which-has-the-most-occurrences/1909239#1909239">Nilesh's answer</a>, which offered this:</p> <pre><code>def mode4 group_by{|i| i}.max{|x,y| x[1].length <=> y[1].length}[0] end </code></pre> <p>It doesn't work with 1.8.6 out of the box, because that version doesn't have Array#group_by. ActiveSupport has it, for the Rails developers, although it seems about 2-3% slower than mode3 above. Using the (excellent) <a href="http://github.com/marcandre/backports" rel="nofollow noreferrer">backports</a> gem, though, produces a 10-12% <em>gain</em>, as well as delivering a whole pile of 1.8.7 and 1.9 extras.</p> <p>The above applies to <strong>1.8.6</strong> only - and mainly only if installed on Windows. Since I have it installed, here's what you get from IronRuby 1.0 (on .NET 4.0):</p> <pre><code>========================== IronRuby ===================================== (iterations bumped to **1000**) user system total real mode1 (I didn't bother :-)) mode2 4.265625 0.046875 4.312500 ( 4.203151) mode3 0.828125 0.000000 0.828125 ( 0.781255) mode4 1.203125 0.000000 1.203125 ( 1.062507) </code></pre> <p>So in the event that performance is super-critical, benchmark the options on your Ruby version & OS. <a href="http://en.wiktionary.org/wiki/your_mileage_may_vary" rel="nofollow noreferrer">YMMV</a>.</p> |
3,068,812 | 0 | Deleting remote branches? <p>When I run git branch -a, it prints out like this, for ex:</p> <pre><code>branch_a remotes/origin/branch_a </code></pre> <p>Few questions:</p> <ol> <li>What does branch_a indicate?</li> <li>What does remotes/origin/branch_a indicate?</li> <li>How do I delete remotes/origin/branch_a?</li> </ol> |
40,975,525 | 0 | How to know if message is continuation of conversation? <p>This might be a stupid question, but I haven't come across any mention of it in the docs.</p> <p>How do I know when a message is a continuation of a previous interaction? For example, with BotFather, you send /setdescription and BotFather tells you to send details. You send details and BotFather knows the details are a description for the specified bot.</p> <p>How does it know about the bot I previously specified?</p> <p>I want to avoid fully-qualified commands (for lack of a better term) like:</p> <pre><code>/command [parameter] [parameter] </code></pre> <p>and turn them into:</p> <pre><code>[command] <reaction> [parameter] <reaction> [parameter] </code></pre> <p>Any tips?</p> <p>EDIT: for right now, I'm simply setting 'status' flags on users every time they finish a step in a multi-step operation. I check that tag after receiving every message to determine if a user is in the middle of an operation. It's rather tedious. I wonder if there's a better way / something built in to the API.</p> |
2,369,455 | 0 | <p>I recommend you start by reading up on computational color theory. Wikipedia is actually a fine place to educate yourself on the subject. Try looking up a color by name on Wikipedia. You will find more than you expect. Branch out from there until you've got a synopsis of the field.</p> <p>As you develop your analytic eye, focus on understanding your favorite (or most despised) interface colors and palettes in terms of their various representations in different colorspaces: RGB, HSB, HSL. Keep Photoshop/GIMP open so you can match the subjective experience of palettes to their quantifiable aspects. See how your colors render on lousy monitors. Notice what always remains readable, and which color combos tend to yield uncharismatic or illegible results. Pay attention to the emotional information conveyed by specific palettes. You will quickly see patterns emerge. For example, you will realize that high saturation colors are best avoided in UI components except for special purposes.</p> <p>Eventually, you'll be able to analyze the output of the palette generators recommended here, and you'll develop your own theories about what makes a good match, and how much contrast is needed to play well on most displays.</p> <p>(To avoid potential frustration, you might want to skip over to Pantone's free color perception test. It's best taken on a color calibrated display. If it says you have poor color perception, then numeric analysis is extra important for you.)</p> |
31,425,670 | 0 | Why php-fpm from official Docker image doesn't work for me? <p>I try to run a new container from <code>php:fpm</code>:</p> <p><code>docker run --name fpmtest -d -p 80:9000 php:fpm</code></p> <p>By default, it exposes port 9000 in its <a href="https://github.com/docker-library/php/blob/32887c1de338d0ad582393b5f1dafd292334423f/5.6/fpm/Dockerfile" rel="nofollow">Dockerfile</a>.</p> <p>Then I log in into container and create index.html file:</p> <pre><code>$ docker exec -i -t fpmtest bash root@2fb39dd6a40b:/var/www/html# echo "Hello, World!" > index.html </code></pre> <p>And inside the container I try to get this content with <code>curl</code>:</p> <pre><code># curl localhost:9000 curl: (56) Recv failure: Connection reset by peer </code></pre> <p>Outside the container I get another error:</p> <pre><code>$ curl localhost curl: (52) Empty reply from server </code></pre> |
5,655,522 | 0 | <p>The C++ runtime dlls you need are the ones provided with the compiler as redistributable package and exactly this one! Other redist packages won't necessary work because of the manifests embedded in the executables which require an exact version (checked by a hash value of the binaries in the side by side assembly directory C:\Windows\SxS)</p> <p>So you are right with the redistributable but you need the one that was installed with the compiler not one from a best guess from the internet. The exact versions can be looked at in the manifest files (XML)</p> |
1,803,047 | 0 | <p>I have finished this, just to let anyone know who may have this problem in the future. It turns out the reason there was nothing being taken in was because ADO tries to determine a column type. If other values in this column are not of said type, it removes them completely.</p> <p>To counter this, you need to create a schema.ini file, like so:</p> <pre><code>StreamWriter writer = new StreamWriter(File.Create(dir + "\\schema.ini")); writer.WriteLine("[" + fileToBeRead + "]"); writer.WriteLine("ColNameHeader = False"); writer.WriteLine("Format = CSVDelimited"); writer.WriteLine("CharacterSet=ANSI"); int iColCount = dTable.Columns.Count + 1; for (int i = 1; i < iColCount; i++) { writer.WriteLine("Col" + i + "=Col" + i + "Name Char Width 20"); } //writer.WriteLine("Col1=Col1Name Char Width 20"); //writer.WriteLine("Col2=Col1Name Char Width 20"); //etc. writer.Close(); </code></pre> <p>Thanks for everyone's suggestions!</p> |
34,332,386 | 0 | <p>If you are not locked in to using SWT, you could use the e(fx)clipse e4 renderer for JavaFX instead.</p> <p>e(fx)clipse has more possibilities to control the lifecycle of the application. For example you can return a <code>Boolean</code> from <code>@PostContextCreate</code> to signal whether you want to continue the startup or not. You will not be able to use <code>EPartService</code> here though, but you can roll your own login dialog using dependency injection as greg-449 has described it in his answer.</p> <pre class="lang-java prettyprint-override"><code>public class StartupHook { @PostContextCreate public Boolean startUp(IEclipseContext context) { // show your login dialog LoginManager loginManager = ContextInjectionFactory.make(LoginManager.class, context); if(!loginManager.askUserToLogin()) { return Boolean.FALSE; } return Boolean.TRUE; } } </code></pre> <p>(You can also restart the application. Form more details see <a href="http://tomsondev.bestsolution.at/2014/11/03/efxclipse-1-1-new-features-api-to-restart-your-e4-app-on-startup/" rel="nofollow">http://tomsondev.bestsolution.at/2014/11/03/efxclipse-1-1-new-features-api-to-restart-your-e4-app-on-startup/</a>). </p> |
28,355,888 | 0 | <p>Try calling <code>plt.draw()</code> inside of your "updated" function like so:</p> <pre><code>def updated(val): z1 = sz1.val lines=lines_param(z1) #clear out the old lines and plot the new ones plt.cla() for y in lines: plt.plot(x_m, y, linewidth=.2) plt.draw() </code></pre> <p>I was unable to get your code running on my machine because I am not sure how the data your 'foo' directory is structured. If you could post the format of your data it would be easier to debug your issue.</p> |
28,796,109 | 0 | <p>Swift solutions for easy copy pasting:</p> <pre><code>navigationController?.popViewControllerAnimated(true) </code></pre> |
3,439,713 | 0 | <p>that is not actually mysql_fetch_array error. this error message says that this function's argument is wrong.<br> and this argument returned by mysql_query() function<br> so it means that there was an error during query execution, on the mysql side.<br> ans mysql has plenty of error messages, quite informative ones.</p> <p>Thus, instead of <em>guessing</em>, you have to get in touch with <strong>certain error message</strong> that will tell you what is wrong. </p> <p>to achieve that, always run your queries this way:</p> <pre><code>$sql = "SELECT * FROM persons"; $res = mysql_query($sql) or trigger_error(mysql_error().$sql); </code></pre> |
18,609,387 | 0 | <p>You can use jQuery <a href="http://api.jquery.com/event.stopPropagation/" rel="nofollow">stop propagation</a> function , it prevents events from bubling</p> |
30,360,850 | 0 | Double error in Web.config file ASP.NET MVC <p>So when I publish my application I these following errors which I do not get in local mode.</p> <blockquote> <p>"System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."</p> </blockquote> <p>So it is said that I'm supposed to write the following code in my Web.config to solve this first error:</p> <pre><code><trustLevel name="Full"> </code></pre> <p>So I did, but then, I got this error:</p> <blockquote> <p>"This configuration section cannot be used at this path. This happens when the site administrator has locked access to this section using from an inherited configuration file."</p> </blockquote> <p>It apparently has to do with the machine.config (which I cannot find)...</p> <p>Does anyone have a proper solution for this?</p> <p>If you wish to test it yourselves, here is the URL:</p> <p><a href="http://wideart.se/Exhibition" rel="nofollow">http://wideart.se/Exhibition</a></p> <p>Regards</p> |
12,848,068 | 0 | how to set default number keyboard in edittext <p>using EditText i want to use phone keyboard (with letters) by default(!), but using </p> <pre><code>android:inputType="phone" </code></pre> <p>android disables letters input when i change keyboard softly. and i'm also need to use letters when it need how should i declare inputType or something else to use phone keyboard by default and don't lose letters input ability?</p> |
5,903,314 | 0 | <p>Without seeing more info / code all I can suggest is that you call <code>session_write_close()</code> before making any cURL calls and see if that improves anything.</p> <p>However, the most probable scenario is that your cURL speed is not related to the <code>PHPSESSID</code> cookie.</p> |
36,632,150 | 0 | How to do a partial sum of table rows in LiveCycle - Javascript <p>I have 4 rows (and 3 columns) in a table. The last row is the total. I need to sum only the first two rows, excluding the last one. The problem is they are all calculated values from different tables, how do I do it? I am new to Adobe LiveCycle and Javascript.</p> <p>This is what I currently have:</p> <pre><code>var times = xfa.resolveNodes("Row2[*].Time"); this.rawValue = Calculate.SumRawValues(times); </code></pre> <p>I am trying something like this:</p> <pre><code>var times = xfa.resolveNodes("Row2[*].Time"); var timesFlushing = xfa.resolveNode("Row2[2].Time"); this.rawValue = Calculate.SumRawValues(times) - timesFlushing.value; </code></pre> <p>or something like this:</p> <pre><code>var times = xfa.resolveNodes("Row2[*].Time"); this.rawValue = Calculate.SumRawValues(times) - xfa.resolveNode("Row2[2].Time"); </code></pre> <p>or even this:</p> <pre><code>this.rawValue = Row2.Time + xfa.resolveNode("Row2[1].Time") </code></pre> <p>Clearly I am new to this and none of these work. Help please??? Comments?</p> |
39,386,954 | 0 | <p>Do one thing , create a new visual studio 2010 solution and <code>import</code> the files . Everything will work fine .</p> <p>This error frequently occurs if you declare a variable in a loop or a try or if block and then attempt to access it from an enclosing code block or a separate code block. </p> <p>Better delete the designer file. You can then right-click on the page, in the solution explorer, and there is an option like <strong><code>Convert to Web Application</code></strong>, which will regenerate your designer file.</p> |
40,631,907 | 0 | <p>solved and works like a charm by moving the entire code related to app config from app.py in init.py (excepting app.run()) and in app.py import app</p> |
4,846,459 | 0 | <p>Vista has some <a href="http://en.wikipedia.org/wiki/Windows_Registry#Registry_virtualization" rel="nofollow">virtualization</a> support.</p> <p>One thing that you could do for keys under <a href="http://en.wikipedia.org/wiki/Windows_Registry#HKEY_CURRENT_USER_.28HKCU.29" rel="nofollow">HKCU</a> is create a new user profile and run the app with matching credentials in order to force usage of a specific <a href="http://en.wikipedia.org/wiki/Windows_Registry#HKEY_CURRENT_USER_.28HKCU.29" rel="nofollow">HKCU</a>.</p> <p>If you are feeling brave have a look at the registry <a href="http://www.wotsit.org/list.asp?search=registry&button=GO!" rel="nofollow">file format</a>.</p> <p><strong>Edit:</strong></p> <p><a href="http://www.sandboxie.com/" rel="nofollow">Sandboxie</a> looks interesting. Registry specific <a href="http://www.sandboxie.com/index.php?SandboxHierarchy#keys" rel="nofollow">features</a> </p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.