pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
23,008,642 | 0 | How to use jQuery with phantomjs <p>I'm trying to do a simple test of jQuery with phantomjs:</p> <pre><code>var url = 'http://www.google.com/'; var page = require('webpage').create(); page.open(url, function () { page.injectJs('jquery.min.js'); page.evaluate(function () { console.log($('title').text()); }); phantom.exit() }); </code></pre> <p>This should print out the title, but instead nothing happens. Can somebody tell me what's wrong?</p> |
19,369,315 | 0 | |
5,861,584 | 0 | <p>It is possible with TPC inheritance but it will include a lot of complication to your design. For example: </p> <ul> <li>you will have to move shared properties to the base class</li> <li>you will probably have to maintain some mappings manually in EDMX (at least I had when I did the sample on screenshot)</li> <li>you will have only single <code>ObjectSet<Tasks></code> and you will have to use <code>OfType</code> to query only Projects or Services</li> <li>you will have to use unique Id per <code>Task</code> = across both Project and Service tables (can be achieved by correctly configured identities in database)</li> </ul> <p>It will look like:</p> <p><img src="https://i.stack.imgur.com/kNZrC.png" alt="enter image description here"></p> <p>Another option is using interface on your entity objects instead of parent class. You can define interface in your partial part of entity object and handle retrieving both Projects and Services by yourselves where your UI will expect only list of types implementing your interface.</p> |
35,923,144 | 0 | Test CharSequences for equality in JUnit <p>The following test runs successfully:</p> <pre><code>assertEquals(a.toString(), b.toString()); </code></pre> <p>The following does not:</p> <pre><code>assertEquals(a, b); </code></pre> <p><code>a</code> is a <code>StringBuilder</code>, while <code>b</code> is a <code>CharSequence</code> of a different type.</p> <p>Is there some way to test <code>CharSequence</code>s for equality without converting them to <code>String</code>s first?</p> |
24,722,323 | 0 | Using gif image and saving <p>I tried to add gif image into a canvas and after adding, gif was static but when I change some other object property, i.e. <code>Kinetic.Text();</code>s <code>setY()</code> property, gif image moved to another step of an animation.</p> <p>Is any way, how to to add <strong>gif image</strong> into a <em>layer</em> and then use </p> <pre><code>stage.toDataURL({ callback: function(dataUrl) { //callback }) }); </code></pre> <p>to save as a gif image? Or does exist any different mechanism how to achieve this effect?</p> |
4,429,759 | 0 | <p>Try changing the order of the handlers (remove then add). In this example I have removed all but the AJAX/script handler.</p> <pre><code><system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <remove name="WebServiceHandlerFactory-ISAPI-2.0"/> <remove name="WebServiceHandlerFactory-ISAPI-2.0-64"/> <remove name="WebServiceHandlerFactory-ISAPI-4.0_32bit"/> <remove name="WebServiceHandlerFactory-ISAPI-4.0_64bit"/> <!--<add name="WebServiceHandlerFactory-Integrated-4.0" ...</handlers> </code></pre> |
29,332,446 | 0 | MongoDB PHP Limit the returning values of a field <pre><code>{ name : "name 1", field : [ { random:"value 1", random2:"second value" } { random:"value 2", random2:"second value 2" } { random:"value 3", random2:"second value 3" } { random:"value 4", random2:"second value 4" } ] } { name : "name 2", field : [ { random:"value 5", random2:"second value" } { random:"value 6", random2:"second value 6" } { random:"value 7", random2:"second value 7" } { random:"value 8", random2:"second value 8" } { random:"value 9", random2:"second value 9" } ] } </code></pre> <p>i have a collection like this. what i want to do is, when i query this collection, i want only first 2 arrays of the field to return.</p> <p>expected return:</p> <pre><code>{ name : "name 1", field : [ { random:"value 1", random2:"second value" } { random:"value 2", random2:"second value 2" } ] } { name : "name 2", field : [ { random:"value 5", random2:"second value" } { random:"value 6", random2:"second value 6" } ] } </code></pre> <p>i've checked <a href="http://docs.mongodb.org/manual/reference/operator/query-modifier/" rel="nofollow">Query Modifiers</a> but they are sorting/limiting the documents, not fields in the documents.</p> <p>So how can i accomplish this?</p> |
30,182,767 | 0 | <p>When using <code>get_template_part</code>, the first parameter defines the base template name (e.g. <code>content</code>, which loads <code>content.php</code>) and the second parameter loads a suffixed version if available. Therefore your call</p> <pre><code>get_template_part('content', 'single-ourNews'); </code></pre> <p>is looking for a file named <code>content-single-ourNews.php</code> first, then falls back to <code>content.php</code> in case the first one is not available. I'm not sure whether the <code>get_template_part</code> function converts the suffix parameter to something like <code>single-ournews</code> or <code>single-our-news</code> before appending it to the first parameter, be sure to test a few variants of that.</p> <p>I'm not 100% sure if the function behaves differently or not in child themes and parent themes. One option is to override the parent's <code>single.php</code> in the child theme and modify it directly with </p> <pre><code>if ($post->post-type === 'ourNews') { get_template_part('content', 'single-ourNews'); } else { get_template_part('content'); } </code></pre> <p>Lastly, WordPress will look for a file <code>single-[cptslug].php</code> before loading a template for a custom post type's single view.</p> |
11,778,961 | 0 | <p><a href="http://docs.python.org/library/functions.html#zip" rel="nofollow"><code>zip</code></a> will stop as soon as <em>any</em> of its iterables stop (because otherwise it wouldn't know what to fill in the blanks with!):</p> <blockquote> <p>The returned list is truncated in length to the length of the shortest argument sequence. </p> </blockquote> <p>If you want to pad the shorter iterables to the length of the longest, use <a href="http://docs.python.org/library/itertools.html#itertools.izip_longest" rel="nofollow"><code>izip_longest</code></a> (which takes an optional parameter to use as the fill value).</p> |
23,020,467 | 0 | <p>For amd64, you need to use "syscall" - and use different registers - instead of "int 0x80":</p> <p><a href="http://cs.lmu.edu/~ray/notes/linuxsyscalls/">http://cs.lmu.edu/~ray/notes/linuxsyscalls/</a></p> <p><a href="http://blog.rchapman.org/post/36801038863/linux-system-call-table-for-x86-64">http://blog.rchapman.org/post/36801038863/linux-system-call-table-for-x86-64</a></p> <p><a href="http://crypto.stanford.edu/~blynn/rop/">http://crypto.stanford.edu/~blynn/rop/</a></p> <p>Here's a good example:</p> <p><a href="http://stackoverflow.com/questions/9506353/how-to-invoke-a-system-call-via-sysenter-in-inline-assembly-x86-amd64-linux">How to invoke a system call via sysenter in inline assembly (x86/amd64 linux)?</a></p> <pre><code>#include <unistd.h> int main(void) { const char hello[] = "Hello World!\n"; const size_t hello_size = sizeof(hello); ssize_t ret; asm volatile ( "movl $1, %%eax\n\t" "movl $1, %%edi\n\t" "movq %1, %%rsi\n\t" "movl %2, %%edx\n\t" "syscall" : "=a"(ret) : "g"(hello), "g"(hello_size) : "%rdi", "%rsi", "%rdx", "%rcx", "%r11" ); return 0; </code></pre> |
8,427,895 | 0 | Is there .net implementation of TeX <p>T<sub>E</sub>X is a typesetting system written by Donald E. Knuth. <a href="http://miktex.org/about" rel="nofollow">MiKT<sub>E</sub>X</a> is an up-to-date implementation of T<sub>E</sub>X and related programs for Windows (all current variants).</p> <p>Is there .NET implementation of T<sub>E</sub>X?</p> |
34,870,744 | 0 | <p>Based on the example from the <a href="http://rssphp.net/examples/" rel="nofollow">RSS parser</a>, each <code>$item</code> is an associative array with keys such as <code>title</code> and <code>description</code>. <code>['title']</code> is an array literal containing one string, <code>'title'</code>, if you want to access the title for an item, you would use <code>$item['title']</code> giving you something like:</p> <pre><code>$title = $item->addChild('title', $item['title']); //add title node </code></pre> |
13,358,921 | 0 | How do I create this layout in android <p>How do I create this layout in android </p> <pre><code>--------------------- |col1 | col2 | col3 | | col1 | col2 | --------------------- </code></pre> <p>The first row is 3 columns equal width, and the second row is 2 row equal width. Is it possible to create this in TableLayout ? I did try width android:layout_span="2" for the last cell, but it does not end up in equal width.</p> <pre><code><TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> <TableRow android:layout_marginTop="6dp"> <Button android:id="@+id/button1" android:layout_weight="33" android:textStyle="bold" android:text="@string/percent" /> <Button android:id="@+id/button2" android:layout_weight="33" android:textStyle="bold" android:text="@string/percent" /> <Button android:id="@+id/button8" android:layout_weight="33" android:textStyle="bold" android:text="@string/percent" /> </TableRow> <TableRow android:layout_marginTop="6dp"> <Button android:id="@+id/button3" android:layout_weight="60" android:textStyle="bold" android:text="@string/percent" /> <Button android:id="@+id/button4" android:layout_weight="40" android:layout_span="2" android:textStyle="bold" android:text="@string/percent" /> </TableRow> </TableLayout> </code></pre> |
28,249,410 | 0 | How can I access my php file from javascript in my directory structure? <p>I have the following directory structure in my PHP project (framework: <a href="https://github.com/panique/mini" rel="nofollow">https://github.com/panique/mini</a>)</p> <pre><code>application --controller ----album.php --libs ----s3demo.php --model public --css --img --js ----application.js </code></pre> <p>In the application.js (inside js folder) I have the following code</p> <pre><code> signature: { endpoint: "s3demo.php" }, </code></pre> <p>How can I access the s3demo.php (in the libs folder) from my javascript (application.js in the js folder)? I have tested with relative path ../../application/libs/s3demo.php and even tried to go through my controller album.php but cant access the file.</p> <p>s3demo.php includes access codes to my Amazon S3 account so I want to have it outside my public folder.</p> <p>Any suggestion?</p> <p>Edit</p> <p>After I read the documentation (again) I changed the javascript to</p> <pre><code>signature: { endpoint: url + "/album/uploadImage" }, </code></pre> <p>And created a new function in album.php</p> <pre><code>public function uploadImage() { return APP . '/libs/s3demo.php'; } </code></pre> <p>But this does not work either. I think I understand routes. The javascript calls the function in album.php and the funtion return the s3demo.php. But it feels wrong to return a php-file.</p> |
40,130,528 | 0 | <p>To upload large binary files using CURL you'll need to use <code>--data-binary</code> flag. </p> <p>In my case it was: </p> <pre><code> curl -X PUT --data-binary @big-file.iso https://example.com </code></pre> <p><strong>Note:</strong> this is really an extended version of @KarlC comment, which actually is the proper answer. </p> |
29,646,395 | 0 | <p>Your problem is you lack any form or execution in the given example.</p> <p>You can use PDO start with this tutorial: <a href="http://www.mysqltutorial.org/php-querying-data-from-mysql-table/" rel="nofollow">http://www.mysqltutorial.org/php-querying-data-from-mysql-table/</a></p> <p>I would also look up, PHP Classes tutorial, Preventing SQL Injection, Basic PHP OOP and PHP Sessions Tutorial. You may find that this can be implemented more easily with a PHP framework but its better to have a handle on what is happening if you intend to do any code work.</p> |
6,267,383 | 0 | UIPickerView: numberOfRowsInComponent is being called twice for same component and is not displaying row titles <p>I'm trying to setup a login form for my application and it is the UIPickerView is not showing the row data. What I am seeing is that the numberOfRowsInComponent is being called twice? But titleForRow is only being called once per row.</p> <p>Debug output:</p> <pre><code>2011-06-07 11:07:31.096 myECG[19689:207] numberOfRowsInComponent: 2 : 0 2011-06-07 11:07:31.096 myECG[19689:207] numberOfRowsInComponent: 2 : 0 2011-06-07 11:07:31.098 myECG[19689:207] USA : 0 2011-06-07 11:07:31.098 myECG[19689:207] Canada : 0 </code></pre> <p><strong>LoginViewController.h</strong></p> <pre><code>#import <UIKit/UIKit.h> @interface LoginViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate> { IBOutlet UITextField *emailField; IBOutlet UITextField *passswordField; IBOutlet UIButton *loginButton; IBOutlet UIActivityIndicatorView *loginIndicator; IBOutlet UIPickerView *pickerView; NSMutableArray *sites; } @property (nonatomic, retain) UITextField *emailField; @property (nonatomic, retain) UITextField *passwordField; @property (nonatomic, retain) UIButton *loginButton; @property (nonatomic, retain) UIActivityIndicatorView *loginIndicator; @property (nonatomic, retain) UIPickerView *pickerView; @property (nonatomic, retain) NSMutableArray *sites; -(IBAction) login:(id) sender; @end </code></pre> <p><strong>LoginViewController.m</strong> #import "LoginViewController.h" #import "myECGViewController.h"</p> <pre><code>@implementation LoginViewController @synthesize emailField, passwordField, loginButton, loginIndicator, pickerView, sites; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } //NSLog(@"%@", sites); return self; } - (void)dealloc { [super dealloc]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; sites = [[NSMutableArray alloc] init]; [sites addObject:@"Canada"]; [sites addObject:@"USA"]; //[pickerView selectRow:1 inComponent:0 animated:YES]; // Do any additional setup after loading the view from its nib. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return NO; } -(IBAction) login:(id) sender { loginIndicator.hidden = FALSE; [loginIndicator startAnimating]; loginButton.enabled = FALSE; // Do login NSLog(@"E:%@ P:%@", emailField.text, passswordField.text); } -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { return 1; } -(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { NSLog(@"%@ : %d", [sites objectAtIndex:row], component); return [sites objectAtIndex:row]; } - (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { NSLog(@"numberOfRowsInComponent: %d : %d", [sites count], component); return [sites count]; } -(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSLog(@"Selected: %@", [sites objectAtIndex:row]); } @end </code></pre> <p>Any help is appreciated.</p> |
9,268,642 | 0 | <p>My guess, you need to add i=0; at the beginning.</p> |
40,889,214 | 0 | Upload file with carrierwave without name <p>It's me again. I try to upload some yaml files with carrierwave. Everything works fine till now. </p> <p>So, as you know for carrierwave the forms looks like the follow:</p> <pre><code><%= form_for @resume, html: { multipart: true } do |f| %> <%= f.label :name %><br> <%= f.text_field :name, :required => true %> <%= f.label :attachment %><br> <%= f.file_field :attachment, :required => true %> <br><br> <%= f.submit "Save", class: "btn btn-primary" %> <% end %> </code></pre> <p>What i want to do now is to remove the "name" field. I don't need it. So i thought its quite easy, just remove the "name" part of the form. But then I got an error while upload:</p> <pre><code>Name can't be blank </code></pre> <p>So I tried now nearly everything... I had set the <code>required => false</code> same result. I went to Github and tooked a look at their how-to... there are methods to overwrite the name, but nobody cares about upload a file without a name. May somebody can tell me how i can upload a file without this name field?</p> <p>Thanks!</p> <p>Edit:</p> <p>My resume.rb model:</p> <pre><code>class Resume < ActiveRecord::Base mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model. end </code></pre> <p>My AttachmentUploader:</p> <pre><code>class AttachmentUploader < CarrierWave::Uploader::Base storage :file def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end def extension_white_list %w(yml) end def filename "something.jpg" if original_filename # This is the part where i'm trying around right now. end end </code></pre> |
21,011,149 | 0 | <p>Do you have the methods for it? If you don't try get the methods out first by using:</p> <pre><code>print server.system.listMethods() </code></pre> <p>After you found out your method, get the signature so it's easier for you to do a search on it.</p> |
7,662,456 | 0 | <p>From the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf" rel="nofollow">C++ Standard ( Working Draft )</a>, section 5 on binary operators</p> <blockquote> <p>Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows: — If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed. — If either operand is of type long double, the other shall be converted to long double. — Otherwise, if either operand is double, the other shall be converted to double. — Otherwise, if either operand is float, the other shall be converted to float.</p> </blockquote> <p>And also section 4.8</p> <blockquote> <p>A prvalue of floating point type can be converted to a prvalue of another floating point type. If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values. Otherwise, the behavior is undefined</p> </blockquote> <p>The upshot of this is that you can avoid unnecessary conversions by specifying your constants in the precision dictated by the destination type, provided that you will not lose precision in the calculation by doing so (ie, your operands are exactly representable in the precision of the destination type ).</p> |
24,390,366 | 0 | ravendb linq query does not use overriden equals method? <p>This works :</p> <pre><code>IQueryable<Record> query = _db.Query<Record>() .Statistics(out stats) .Where(r => r.Keywords.Any( k => k.Value.Equals(searchInputModel.Keyword.Value))); </code></pre> <p>but this doesn't</p> <pre><code> IQueryable<Record> queryBorked = _db.Query<Record>() .Statistics(out stats) .Where(r => r.Keywords.Any( k => k.Equals(searchInputModel.Keyword))); </code></pre> <p>even though I have overridden equals and hashcode for the Keyword class like below, so only value is checked for equality :</p> <pre><code>protected bool Equals(Keyword other) { return string.Equals(Value, other.Value, StringComparison.InvariantCultureIgnoreCase); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Keyword) obj); } </code></pre> <p>And hashcode :</p> <pre><code>public override int GetHashCode() { unchecked { return (Value.ToLower().GetHashCode() * 397); //return (Value.ToLower().GetHashCode()*397) ^ Vocab.ToLower().GetHashCode(); } } </code></pre> <p>Does ravendb use a different equality check ?</p> |
9,180,820 | 0 | <p>A more jqueryish way than using just regular expressions: </p> <pre><code>var path = $('<a>', {href: 'http://google.com/foo/bar.py'})[0].pathname.replace(/\.(.+)$/,'') </code></pre> |
30,217,582 | 0 | <p>Look at this post here: <a href="http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx" rel="nofollow">Thread safe random number generation</a></p> <p>In short: Random() is not thread safe, nor was it designed to be.</p> |
25,869,285 | 0 | Can Anyone tell me how can i solve this Exception <pre><code>class Revers { static void temp(String k) { int x; char ch[]= k.toCharArray(); //Convert String into character char p[]=k.toCharArray(); //Convert String into character x=k.length(); System.out.println(x); for(int i=0;i<x;x--,i++) { p[i]=ch[x]; `/*Exception comes here*/` System.out.println(p[i]); } } public static void main(String... s) { String g="HEllo java"; temp(g); //passig g as argument } } </code></pre> |
1,216,211 | 0 | <p>Before you get started, do not use macro names that begin with an underscore - these are reserved for compiler and standard library writers, and must not be used in your own code.</p> <p>Additionally, I would say that the macros you suggest are all ver bad ideas, because they hide from the reader what is going on. The only justification for them seems to be to save you a very small amount of typing. Generally, you should only be using macros when there is no sensible alternative. In this case there is one - simply write the code.</p> |
12,271,011 | 0 | <p>1) please read tutorial about <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting" rel="nofollow noreferrer">JTable that's contains TableRowSorter example</a>, issue about RowSorter must be in your code</p> <p>2) by default you can to use follows definition for ColumnClass, </p> <pre><code>public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } </code></pre> <p>3) or you can to hardcode that </p> <pre><code> @Override public Class<?> getColumnClass(int colNum) { switch (colNum) { case 0: return Integer.class; case 1: return Double.class; case 2: return Long.class; case 3: return Boolean.class; case 4: return String.class; case 5: return Icon.class; default: return String.class; } } </code></pre> <p>4) or override <code>RowSorter</code> (notice crazy code)</p> <p><img src="https://i.stack.imgur.com/Q6S63.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/0wouS.png" alt="enter image description here"></p> <pre><code>import com.sun.java.swing.Painter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import javax.swing.*; import javax.swing.table.*; public class JTableSortingIconsForNimbus extends JFrame { private static final long serialVersionUID = 1L; private JTable table; private JTable table1; private static Icon ascendingSortIcon; private static Icon descendingSortIcon; public JTableSortingIconsForNimbus() { Object[] columnNames = {"Type", "Company", "Shares", "Price"}; Object[][] data = { {"Buy", "IBM", new Integer(1000), new Double(80.50)}, {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)}, {"Sell", "Apple", new Integer(3000), new Double(7.35)}, {"Buy", "Nortel", new Integer(4000), new Double(20.00)} }; DefaultTableModel model = new DefaultTableModel(data, columnNames) { private static final long serialVersionUID = 1L; @Override public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; table = new JTable(model) { private static final long serialVersionUID = 1L; @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); int firstRow = 0; int lastRow = table.getRowCount() - 1; if (row == lastRow) { ((JComponent) c).setBackground(Color.red); } else if (row == firstRow) { ((JComponent) c).setBackground(Color.blue); } else { ((JComponent) c).setBackground(table.getBackground()); } return c; } }; table.setPreferredScrollableViewportSize(table.getPreferredSize()); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.NORTH); table1 = new JTable(model) { private static final long serialVersionUID = 1L; @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); int firstRow = 0; int lastRow = table1.getRowCount() - 1; if (row == lastRow) { ((JComponent) c).setBackground(Color.red); } else if (row == firstRow) { ((JComponent) c).setBackground(Color.blue); } else { ((JComponent) c).setBackground(table1.getBackground()); } return c; } }; table1.setPreferredScrollableViewportSize(table1.getPreferredSize()); JScrollPane scrollPane1 = new JScrollPane(table1); //UIDefaults nimbusOverrides = new UIDefaults(); //nimbusOverrides.put("Table.ascendingSortIcon", ascendingSortIcon); //nimbusOverrides.put("Table.descendingSortIcon", descendingSortIcon); //table1.putClientProperty("Nimbus.Overrides", nimbusOverrides); //UIManager.getLookAndFeelDefaults().put("Table.ascendingSortIcon", ascendingSortIcon); //UIManager.getLookAndFeelDefaults().put("Table.descendingSortIcon", descendingSortIcon); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].ascendingSortIconPainter", new FillPainter1(new Color(255, 255, 191))); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].descendingSortIconPainter", new FillPainter1(new Color(191, 255, 255))); SwingUtilities.updateComponentTreeUI(table1); add(scrollPane1, BorderLayout.SOUTH); TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel()) { @Override public void toggleSortOrder(int column) { if (column >= 0 && column < getModelWrapper().getColumnCount() && isSortable(column)) { List<SortKey> keys = new ArrayList<SortKey>(getSortKeys()); if (!keys.isEmpty()) { SortKey sortKey = keys.get(0); if (sortKey.getColumn() == column && sortKey.getSortOrder() == SortOrder.DESCENDING) { setSortKeys(null); return; } } } super.toggleSortOrder(column); } }; table.setRowSorter(sorter); table1.setRowSorter(sorter); } static class FillPainter1 implements Painter<JComponent> { private final Color color; public FillPainter1(Color c) { color = c; } @Override public void paint(Graphics2D g, JComponent object, int width, int height) { g.setColor(color); g.fillRect(0, 0, width - 1, height - 1); } } public static void main(String[] args) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); ascendingSortIcon = UIManager.getLookAndFeelDefaults().getIcon("Table.ascendingSortIcon"); descendingSortIcon = UIManager.getLookAndFeelDefaults().getIcon("Table.descendingSortIcon"); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].ascendingSortIconPainter", new FillPainter1(new Color(127, 255, 191))); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].descendingSortIconPainter", new FillPainter1(new Color(191, 255, 127))); } catch (Exception fail) { } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JTableSortingIconsForNimbus frame = new JTableSortingIconsForNimbus(); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } </code></pre> |
17,380,924 | 0 | <p>Session data is stored server-side.</p> <p>Cookie data is stored client-side.</p> |
32,960,039 | 0 | <p><code>success</code> and <code>error</code> are <strong>never</strong> <code>set</code>, actually, unless your server is configured to execute <code>html</code> files as <code>php</code>, you won't be able to retrieve <strong>anything</strong> inside <code>contact.html</code>.</p> <p>rename <code>contact.html</code> to <code>contact.php</code> and try:</p> <pre><code>header("Location: contact.php?success=1"); </code></pre> <p>AND</p> <pre><code>header("Location: contact.php?error=1"); </code></pre> <hr> <p><strong>Important:</strong><br> In order to execute <code>php</code> files they need to have <code>.php</code> as file extension, otherwise, as @BurningCrystals said, they're just plaintext.</p> |
7,370,935 | 1 | Django:Map urls to class like in web.py <p>i am learning django but gave web.py a try first. while reading django's documentation i found that in i need to check for the request type in each method.. like:</p> <pre><code>def myview(): if request.method == "POST": #blah balh #ke$ha (jst kiddn) else: #(balh)x2 </code></pre> <p>can the web.py type classes be implemented in django like</p> <pre><code>class myView(): def GET(self): #cool def POST(self): #double cool </code></pre> <p>it would be super cool</p> |
12,299,901 | 0 | Changing XML to JSON in PHP <p>My site was pulling in a shopping API, using XML, and I'd like to switch it to the Google Shopping API, which uses JSON or Atom.</p> <p>I can't seem to work out how to get the following to work in JSON or Atom, any help much appreciated.</p> <pre><code>$query = str_replace(' ', '%', $row['title']); $url = "http://api-url-here.com/query?q='".$query."'%20AND%20currency%3AGBP&key=key-here&rows=8&start=0&format=xml"; $response = file_get_contents($url); $xml = simplexml_load_string($response); //print_r($xml); $recommended = Array(); for($i=0; $i<count($xml->products->product); $i++){ $item = Array( $xml->products->product[$i]->merchant, $xml->products->product[$i]->price, $xml->products->product[$i]->url, $xml->products->product[$i]->imageUrl, $xml->products->product[$i]->title ); array_push($recommended , $item); } $i = 0; foreach($recommended as $item){ $i++; $row['item'.$i.'-merch'] = (String) $item[0]; $row['item'.$i.'-price'] = (String) $item[1]; $row['item'.$i.'-url'] = (String) $item[2]; $row['item'.$i.'-img'] = (String) $item[3]; $row['item'.$i.'-title'] = (String) $item[4]; $row['more-products'] = "Recommended"; } </code></pre> <p>I apologise for the complete noob question but my usual dev is on holiday and I'm pretty new at code.</p> <p>Any help much appreciated.</p> |
14,034,468 | 0 | <p>OK using </p> <pre><code>$(".fb-recommendations-bar").data("href", href); </code></pre> <p>instead of</p> <pre><code>$(".fb-recommendations-bar").attr("data-href", href); </code></pre> <p>and</p> <pre><code>FB.XFBML.parse(); </code></pre> <p>or</p> <pre><code>FB.XFBML.parse(document.getElementById('.fb-recommendations-bar')); </code></pre> <p>instead of</p> <pre><code>FB.XFBML.RecommendationsBar.markRead(href); </code></pre> <p>works!</p> |
20,975,390 | 0 | <pre><code> In the PHP part you need add two more headers : header("Access-Control-Allow-Origin: *"); header('Access-Control-Allow-Methods: GET, POST'); Add the two line of coding with the: header('Content-Type: application/json'); change the: echo (json_encode($data)); to: print $my_json = json_encode($data); or: print_r ($my_json); Hope it will work. </code></pre> |
12,667,002 | 0 | C++ "Cannot declare parameter to be of abstract type <p>I'm trying to implement generic wrapper in C++ that will be able to compare two things. I've done it as follows:</p> <pre><code>template <class T> class GameNode { public: //constructor GameNode( T value ) : myValue( value ) { } //return this node's value T getValue() { return myValue; } //ABSTRACT //overload greater than operator for comparison of GameNodes virtual bool operator>( const GameNode<T> other ) = 0; //ABSTRACT //overload less than operator for comparison of GameNodes virtual bool operator<( const GameNode<T> other ) = 0; private: //value to hold in this node T myValue; }; </code></pre> <p>It would seem to be I can't overload the '<' and '>' operators in this way, so I'm wondering what I can do to get around this.</p> |
29,877,161 | 0 | <p>In your <code>onCreate()</code> after drawer layout and list are found call:</p> <pre><code>mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, mDrawerList); drawerToggle.setDrawerIndicatorEnabled(false); </code></pre> <p>From the <a href="https://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#setDrawerLockMode(int,%20android.view.View)" rel="nofollow">Javadoc</a>:</p> <blockquote> <pre><code>public void setDrawerLockMode (int lockMode, View drawerView) </code></pre> <p>Enable or disable interaction with the given drawer.</p> <p>This allows the application to restrict the user's ability to open or close the given drawer. DrawerLayout will still respond to calls to openDrawer(int), closeDrawer(int) and friends if a drawer is locked.</p> </blockquote> |
38,435,463 | 0 | <p>Try to use this </p> <pre><code>[self.tableView scrollToRowAtIndexPath:YOUR_INDEX_PATH_OF_SECTION atScrollPosition:UITableViewScrollPositionTop animated:YES] </code></pre> |
20,503,856 | 0 | SQL query: for each state with specific number of sailors <p>I'm starting to learn to write SQL queries. However, I'm still struggling with that. I had to write a query that gives back for each state that has more than 5 sailors the sailor id and the total number of reservations that he has made. The schemas are as following:</p> <p><code>Slr</code> (<code>sid</code>, <code>sname</code>, <code>rating</code>, <code>state</code>) and <code>Reserves</code> (<code>sid</code>, <code>bid</code>, <code>day</code>). </p> <p>Here's my trial:</p> <pre><code>Select slr.state, slr.sid, count(*) From slr left join Reserves on slr.sid=reserves.sid Group By s.state Having count(*) >= 5 </code></pre> <p>I know it's not correct, but what can I change ?</p> |
28,695,664 | 0 | <p>For those early adapting people on the CofeeScript era, here's another equivalent for it.</p> <pre><code>val for key,val of objects </code></pre> <p>Which may be better than this because the <code>objects</code> can be reduced to be typed again and decreased readability.</p> <pre><code>objects[key] for key of objects </code></pre> |
15,305,083 | 0 | View disappears when I set `translatesAutoresizingMaskIntoConstraints` to `NO` <p>I don't know if this is a bug or I'm doing something wrong:</p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UIWindow *window = [self window]; UIViewController *main = [[UIViewController alloc] init]; UIViewController *vc1 = [[UIViewController alloc] init]; UIViewController *vc2 = [[UIViewController alloc] init]; [main addChildViewController:vc1]; [main addChildViewController:vc2]; UIView *mainView = [main view]; UIView *v1 = [vc1 view]; UIView *v2 = [vc2 view]; [v1 setBackgroundColor:[UIColor redColor]]; [v2 setBackgroundColor:[UIColor blueColor]]; [v1 setTranslatesAutoresizingMaskIntoConstraints:NO]; [v2 setTranslatesAutoresizingMaskIntoConstraints:NO]; [v1 setClipsToBounds:YES]; [v2 setClipsToBounds:YES]; [mainView setBackgroundColor:[UIColor yellowColor]]; [mainView addSubview:v1]; [mainView addSubview:v2]; NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:v1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:mainView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]; [mainView addConstraint:constraint]; constraint = [NSLayoutConstraint constraintWithItem:v1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:240.0]; [mainView addConstraint:constraint]; constraint = [NSLayoutConstraint constraintWithItem:v2 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:v1 attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]; [mainView addConstraint:constraint]; [window setRootViewController:main]; [window setBackgroundColor:[UIColor greenColor]]; [window makeKeyAndVisible]; [main release]; [vc1 release]; [vc2 release]; return YES; } </code></pre> <p><code>v1</code> and <code>v2</code> appears nowhere when I launch the app.</p> <p>If I comment out:</p> <pre><code>[v1 setTranslatesAutoresizingMaskIntoConstraints:NO]; [v2 setTranslatesAutoresizingMaskIntoConstraints:NO]; </code></pre> <p>Cocoa wouldn't be able to satisfy my constraints because of the autoresizing mask that was translated into constraints.</p> |
21,951,353 | 0 | <blockquote> <p>Is it possible in Z's constructor to put Z at the end of X's list</p> </blockquote> <p>Yes, if Z has access to X's list.</p> <blockquote> <p>Which way is better?</p> </blockquote> <p>This depends on the semantics. Is the list something closely related with Z's responsibilities or more with Y's?</p> |
950,003 | 0 | <p>Change:</p> <pre><code>$('.removeitem').click(function(){ $(this).prev().parent().remove(); return false; }); </code></pre> <p>to:</p> <pre><code>$('.removeitem').live("click", function(){ $(this).prev().parent().remove(); return false; }); </code></pre> |
4,383,846 | 0 | <p>Quite a few systems have a function <code>asprintf</code> in their standard C libraries that does exactly what you do here: allocate and <code>sprintf</code>.</p> |
25,340,351 | 0 | <p>Whatever <code>JOIN</code> syntax you've used there, I'm not familiar with it. You also had the following, which is incorrect:</p> <pre><code>`j`.`user_id=$user_id` </code></pre> <p>If you're going to use the backticks, it would be this:</p> <pre><code>`j`.`user_id` = $user_id </code></pre> <p>Assuming <code>$user_id</code> is an integer (I also put single quotes around this type in the <code>WHERE</code> clause in case <code>$user_id</code> is empty for some reason; this helps prevent unnecessary syntax errors). However, backticks are rarely necessary (when column names are also reserved words or there is a space, for instance).</p> <p>Putting it together, with my own syntax style:</p> <pre><code>SELECT j.job_id , j.user_id , b.business_name , b.contract_person , b.mobile_number , b.email , b.id FROM ci_jobs_apply AS j INNER JOIN ci_business AS b ON j.job_id = b.id WHERE j.user_id = '$user_id' </code></pre> |
9,952,633 | 0 | <p><a href="http://docs.python.org/py3k/library/collections.html#counter-objects" rel="nofollow"><code>collections.Counter</code></a> exists for precisely this kind of work:</p> <pre><code>>>> collections.Counter(i[1] for i in L).most_common() [(2, 2), (1, 1), (5, 1)] </code></pre> |
38,075,266 | 0 | <p>This is example from "CLR via C#" book:</p> <pre><code>private static async Task<String> IssueClientRequestAsync(String serverName, String message) { using (var pipe = new NamedPipeClientStream(serverName, "PipeName", PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) { pipe.Connect(); // Must Connect before setting ReadMode pipe.ReadMode = PipeTransmissionMode.Message; // Asynchronously send data to the server Byte[] request = Encoding.UTF8.GetBytes(message); await pipe.WriteAsync(request, 0, request.Length); // Asynchronously read the server's response Byte[] response = new Byte[1000]; Int32 bytesRead = await pipe.ReadAsync(response, 0, response.Length); return Encoding.UTF8.GetString(response, 0, bytesRead); } // Close the pipe } </code></pre> <p>Here executing thread is released just after <code>WriteAsync</code> call. After network driver completes its work, execution will continue until ReadAsync, when thread will be released again until data is read.</p> |
37,307,025 | 0 | <p>Definitely. Best practice is a separate file for each View Controller or other major class.</p> <p>Refer to this <a href="https://itunes.apple.com/us/course/developing-ios-8-apps-swift/id961180099" rel="nofollow">awesome free course from Stanford</a> for a very nice introduction on MVC (Model-View-Controller).</p> |
36,934,200 | 0 | <p>This? It should work if there are more than 2 rows.</p> <pre><code>WITH NotesWithId AS ( SELECT ID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), note FROM Notes ) SELECT [note1] = CASE WHEN [ID] % 2 <> 0 THEN [note] ELSE NULL END, [note2] = CASE WHEN [ID] % 2 = 0 THEN [note] ELSE NULL END FROM NotesWithId; </code></pre> |
24,676,805 | 0 | sans-serif-light with "fake bold" <p>I have set up the following theme for my app:</p> <pre><code><style name="AppTheme" parent="Theme.Sherlock.Light"> <item name="android:textViewStyle">@style/RobotoTextViewStyle</item> </style> <style name="RobotoTextViewStyle" parent="android:Widget.TextView"> <item name="android:fontFamily">sans-serif-light</item> </style> </code></pre> <p>Therefor when I create a <code>TextView</code> I get the "roboto light" font which I want. Some <code>TextView</code>s however, I would like to set the <code>textStyle="bold"</code> attribute but it doesn't work since the light font doesn't have a "native" (?) bold variant.</p> <p>On the other side if I programmatically use the <code>setTypeface</code> method I could get a bold font:</p> <pre><code>textView.setTypeface(textView.getTypeface(), Typeface.BOLD); </code></pre> <p><em>This font is derived from the roboto light and looks really good.</em></p> <hr> <p>I would like to have <strong>this bold light font</strong> but I wonder what the most elegant way to do it is.</p> <ol> <li><p>Can it be done solely using xml?</p></li> <li><p>What is the best implementation if I need to create a "<code>BoldTextView extends TextView</code>"?</p></li> </ol> |
6,616,498 | 0 | I want my app to be spreadable easily <p>How can I communicate the download link from one user who has it to one who does not? If all they have are their android phones. Bluetooth? Would I send a contact card. </p> <p>Are there less cumbersome ways that pairing? </p> |
35,451,042 | 0 | Byte code version mismatch when using subset <p>I have been working on the same R script now for 5 months, had some minor coding problems, but this morning I got a problem that makes me unable to run the whole script. To clean my imported data I use a lot of subset(), but this morning when running the code I got the Warning:</p> <pre><code>Error in subset(T23810, date < as.Date("2015-10-22")) : byte code version mismatch </code></pre> <p>It appears that I only get this warning after trying to run a subset function, but it blocks my whole script at the moment. What could be the cause and solution for this?</p> <p><strong>EDIT: Reproducible example</strong></p> <pre><code>x = structure(list(names = structure(c(11L, 3L, 5L, 27L, 26L, 15L, 18L, 13L, 8L, 2L, 22L, 12L, 1L, 25L, 29L, 31L, 6L, 23L, 28L, 14L, 19L, 4L, 10L, 16L, 9L, 17L, 21L, 30L, 7L, 6L, 27L, 26L, 12L, 13L, 14L, 4L, 28L, 15L, 31L, 23L, 1L, 22L, 11L, 18L, 3L, 20L, 8L, 5L, 16L, 2L, 25L, 30L, 21L, 4L, 6L, 3L, 5L, 27L, 14L, 11L, 26L, 31L, 13L, 18L, 15L, 1L, 23L, 2L, 8L, 28L, 30L, 20L, 22L, 12L, 10L, 16L, 21L, 25L, 17L, 24L, 32L, 31L, 23L, 26L, 1L, 18L, 11L, 12L, 3L, 15L, 27L, 28L, 5L, 22L, 6L, 17L, 20L, 2L, 8L, 21L, 30L, 13L, 25L, 24L, 7L, 4L, 10L, 16L, 14L), .Label = c("50/50", "Babylon", "Big Rock Market", "Core Gut", "Customs House", "David's Dropoff", "David's Dropoff Deep", "Diamond Rock", "Giles Quarter", "Green Island", "Greer Gut", "Hole in the Corner", "Hot Springs", "Ladder Labyrinth", "Man O War", "Mount Michel", "Muck Dive", "Outer Limits", "Poriotes Point", "Porites Point", "Rays & Anchors", "Shark Shoals", "Tedran", "Tent Boulders", "Tent Deep", "Tent Reef", "Tent Wall", "Third Encounter", "Torens Point", "Torrens Point", "Twilight Zone", "Wells Bay" ), class = "factor")), .Names = "names", row.names = c(NA, -109L ), class = "data.frame") </code></pre> <p>Then if I execute the following:</p> <pre><code>x[x=="Torens Point"] = "Torrens Point" x[x=="Poriotes Point"] = "Porites Point" x = droplevels(subset(x, names != "Muck Dive")) </code></pre> <p>I get the error: </p> <pre><code>Error in subset(x, names != "Muck Dive") : byte code version mismatch </code></pre> |
31,668,833 | 0 | remove unused/bad index to speed up response from table <p>Hi I have table with stat below</p> <pre><code>Rows : 4,639,162 Reserved : 7,183,216 KB Data : 5,978,536 KB Index Size : 1,199,840 KB Unused : 4,840 KB </code></pre> <p>I have used <code>sp_spaceused 'TableName'</code> for this stat.</p> <p>And table information is like below</p> <pre><code>index_name index_description index_keys IX_tbl_tablename_1 nonclustered located on PRIMARY lng_clientid, str_facility_mims, str_group, str_eq_circ_id, int_tml_no IX_tbl_tablename_fullreport nonclustered located on PRIMARY str_eq_circ_id, str_facility, str_group IX_tbl_tablename_lng_clientid nonclustered located on PRIMARY lng_clientid PK_tbl_tablename_1 clustered, unique, primary key located on PRIMARY lng_id, lng_clientid </code></pre> <p>I am not expert on index but does these index seems okay ?? </p> <p>EDIT : I am Concerned about different Index created and having some common columns. Eg : Clustered Index is created with lngid and clientid , but there is non-clustered index too with only clientid. So is okay ??</p> |
6,627,981 | 0 | <p>Redis is fast, but it can't be as fast as a direct memory access. It requires constructing a request, posting it, waiting for a response, decoding that response, and returning that value to your application. Redis runs as a separate process, so you will have to pay this price for inter-process communication even when it is located on the same machine.</p> <p>That it is only twelve times slower by your benchmark is still impressive.</p> |
12,476,551 | 0 | <p>In order to move from one page to another, you need to use a variable to show what page the user is currently reading. Previous and Next would then update the page number and display the appropriate page:</p> <pre><code>file = ['page1.txt', 'page2.txt', 'page3.txt', 'page4.txt'] pagecount = len(file) page = 1 # initialize to a default page if inp == '1': page = 1 read(file[page-1]) # pages are 1-4, subscripts are 0-3 # ... pages 2-4 go here elif inp == '+': # whatever key you use for Next page = min(page+1, pagecount) # don't go beyond last page read(file[page-1]) elif inp == '-': # switch statements use "if .. elif .. elif .. else" page = max(page-1, 1) read(file[page-1]) </code></pre> <p>After you get that version working, you can generalize it to allow an arbitrary number of pages by constructing the file name from the page number instead of storing filenames in a list. And you only need one "read" for your input loop -- since every key reads a page you can factor that out of each individual key.</p> |
3,314,587 | 0 | <p>You need this:</p> <pre><code>#menuBar #test2 a:hover{ background:url("../images/btTest.jpg") no-repeat top; } </code></pre> <p>To be this:</p> <pre><code>#menuBar #test2:hover a { background:url("../images/btTest.jpg") no-repeat top; } </code></pre> <p>To get it to stick when you move to the <code>.subMenu</code>. This will not work for IE6 (if you care).</p> <p>Also these:</p> <pre><code>#menuBar #test2 a:hover + .subMenu { //submenu show up display:block; } #menuBar li .subMenu:hover { //keep submenu show up when hover in submenu display: block; } </code></pre> <p>Should be able to be replaced with just this:</p> <pre><code>#menuBar li:hover .subMenu { display: block; } </code></pre> |
2,723,779 | 0 | <p>If you want the file and line numbers, you do not need to parse the StackTrace string. You can use System.Diagnostics.StackTrace to create a stack trace from an exception, with this you can enumerate the stack frames and get the filename, line number and column that the exception was raised. Here is a quick and dirty example of how to do this. No error checking included. For this to work a PDB needs to exist with the debug symbols, this is created by default with debug build.</p> <pre><code>using System; using System.Diagnostics; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { try { TestFunction(); } catch (Exception ex) { StackTrace st = new StackTrace(ex, true); StackFrame[] frames = st.GetFrames(); // Iterate over the frames extracting the information you need foreach (StackFrame frame in frames) { Console.WriteLine("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber()); } } Console.ReadKey(); } static void TestFunction() { throw new InvalidOperationException(); } } } </code></pre> <p>The output from the above code looks like this</p> <pre> D:\Source\NGTests\ConsoleApplication1\Program.cs:TestFunction(30,7) D:\Source\NGTests\ConsoleApplication1\Program.cs:Main(11,9) </pre> |
30,321,914 | 0 | Callout click is not working in iPhone simulator 4s in iOS <p>I have created annotation view over current latitude and longitude and used image over it using custom annotation. It works fine and created custom callout using Apple example MapCallout <a href="https://developer.apple.com/library/ios/samplecode/MapCallouts/Introduction/Intro.html" rel="nofollow">https://developer.apple.com/library/ios/samplecode/MapCallouts/Introduction/Intro.html</a> [used flag portion to set image and click portion from purple pin notation ] but my click is working fine in iPhone simulator 5 and later but click not working in iPhone 4S simulator over callout, I have tried by many ways but did not get success. Can any one suggest what I have missed to set for iPhone 4s to run click over callout.</p> <p>My Code is as follows in view Annotation,</p> <pre><code>- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { MKAnnotationView *returnedAnnotationView = nil; if([annotation isKindOfClass:[MAKRSampleAnnotation class]]) { returnedAnnotationView = [MAKRSampleAnnotation createViewAnnotationForMapView:self.mapView annotation:annotation]; // provide the annotation view's image returnedAnnotationView.image = [UIImage imageNamed:@"map_pointer_yellow.png"]; // trying to click using this in 4s , working in iPhone 5 and later UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; [rightButton addTarget:nil action:nil forControlEvents:UIControlEventTouchUpInside]; ((MKPinAnnotationView *)returnedAnnotationView).rightCalloutAccessoryView = rightButton; return returnedAnnotationView; } return returnedAnnotationView; } </code></pre> <p>I have spent much time to fix this but not get luck to make it out.</p> <p>Thanks.</p> |
11,233,344 | 0 | <p>A few suggestions:</p> <h2>ADJACENCY TEST</h2> <p>The test in FindAdjacent will only find diagonal neighbours at the moment</p> <pre><code> if (i != 0 && j != 0) </code></pre> <p>If you also want to find left/right/up/down neighbours you would want to use</p> <pre><code> if (i != 0 || j != 0) </code></pre> <h2>ADJACENCY LOOP</h2> <p>I think your code looks suspicious in FindAdjacent at the line</p> <pre><code>for (vector<Node*>::iterator iter = mClosedList.begin(); iter != mClosedList.end(); iter++) </code></pre> <p>I don't really understand the intention here. I would have expected mClosedList to start empty, so this loop will never execute, and so nothing will ever get added to mOpenList.</p> <p>My expectation at this part of the algorithm would be for you to test for each neighbour whether it should be added to the open list. </p> <h2>OPENLIST CHECK</h2> <p>If you look at the <a href="http://en.wikipedia.org/wiki/A%2a_search_algorithm" rel="nofollow">A* algorithm on wikipedia</a> you will see that you are also missing the section starting</p> <pre><code>if neighbor not in openset or tentative_g_score < g_score[neighbor] </code></pre> <p>in which you should also check in FindAdjacent whether your new node is already in the OpenSet before adding it, and if it is then only add it if the score is better.</p> |
25,695,837 | 0 | Setting up PHPMyAdmin on Amazon EC2 <p>I've installed PHPMyAdmin on my Amazon EC2 instance using the following:</p> <pre><code>yum --enablerepo=epel install phpmyadmin </code></pre> <p>Then symlinked it to /var/www/html with</p> <pre><code>ln -s /usr/share/phpmyadmin /var/www/html </code></pre> <p>When I navigate to /phpmyadmin in my browser, it gives me a 403 Forbidden saying I can't access /phpmyadmin/ on the server.</p> <p>Thanks for any help.</p> |
26,790,091 | 0 | <p>I solved and I'm writing for the user having the same problem:</p> <p>Insert the option <code>cache:false</code> in the $.ajax method as below:</p> <pre><code>$.ajax({ url: options.path, data: options.data, method: options.method, success: options.success, cache: false, error: options.error && function(){ location.href = Router.root; }, complete: function (request) { Devmanager.toolbar(request); NProgress.isStarted() && NProgress.done(); } }); </code></pre> |
36,822,396 | 0 | <p>Make a parent Component whose child will be <code>MyComponent</code></p> <pre><code>class ParentComponent extends React.Component { componentDidMount() { // make api call apiCall.then((data) => { this.setState({ reqData : data, }) }) } getComponentToRender() { if(typeof this.state.reqData === 'undefined') { return false; } else { return ( <MyComponent data={result.data}/> ) } } render() { const componentToRender = this.getComponentToRender(); return ( <div> <componentToRender /> </div> ) } } </code></pre> <p>Now, render your ParentComponent irrespective of the api call. Once, the <code>ParentComponent</code> is mounted, it will automatically trigger the rendering of <code>MyComponent</code>.</p> |
10,399,248 | 0 | MYSQL accepts only root accounts <p>I've got a real big problem. I have LAMP on my computer. When I try to connect to mysql not with root account (via phpmyadmin) - phpmyadmin says that it cannot connect to mysql. So, I can connect to mysql only via root.</p> |
14,562,537 | 0 | <p><code>this</code> is always a local variable and therefore it is overwritten in every function.</p> <p>What you might do is pointing to your class e.g. <code>var myClass = this;</code> and use <code>myClass</code> instead of <code>this</code>.</p> <pre><code> this.checkSections = function(){ var myClass = this; jQuery('#droppable #section').each( function() { nextId = jQuery(this).next().attr('id'); if (nextId != 'small' && nextId != 'large'){ jQuery(this).remove(); myClass.sections --; myClass.followArticles = 0; }else{ articles = 0; obj = jQuery(this).next(); while (nextId == 'small' || nextId == 'large'){ articles++; obj = obj.next() nextId = obj.attr('id'); //alert(nextId); } myClass.followArticles = articles; alert(myClass .sections); } }); } </code></pre> |
18,109,716 | 0 | Avoid default activerecord primary index creation <p>I am trying to workout how to advise/tell activerecord not to create it's primary index by default.</p> <p>Anyone know how i can achieve this ?</p> <pre><code>class CreateHouse < ActiveRecord::Migration def change create_table :houses do |table| table.string :name, :null => false, :unique => true table.integer :number, :null => false, :unique => true table.string :category, :null => false table.timestamps(:null => false) end add_index :houses, [:category, :number], :unique => true end end </code></pre> <p>THANKS</p> |
25,491,750 | 0 | removing commas from numbers in CSV file <p>I have a file that has many columns and I only need two of those columns. I am getting the columns I need using </p> <pre><code>cut -f 2-3 -d, file1.csv > file2.csv </code></pre> <p>The issue I am having is that the first column is ID and once it gets past <code>999</code> it becomes <code>1,000</code> and so it is treated as an extra column now. I cant get rid of all commas because I need them to separate the data. Is there a way to use <code>sed</code> to remove commas that only show up between <code>0-9</code>? </p> |
26,505,054 | 0 | <p>When compiling project A maven will first try to look-up the project dependencies B, C, D, E. He will look at the local repository (usually a hidden directory .m2 under user’s home directory) or a remote repository. </p> <p>In your case B, C, D, E are your local projects and not third-party so executing maven install for B, C, D, E. will compile them and copy them to local repository. When you do maven install on A they will not be compiled again.</p> |
3,894,219 | 0 | <p>Solution:</p> <pre><code>SELECT tag, COUNT(*)AS tags_count FROM ( SELECT post_n, tag FROM tags ORDER BY post_n DESC LIMIT 20 ) AS temp GROUP BY tag HAVING tags_count>=2 ORDER BY post_n DESC LIMIT 5 </code></pre> <p>Of course need to change limit in the first selection, otherwise there will be plenty to choose from.</p> <p>P. S. Sorry that is poorly formulated question, my english very bad.</p> |
22,923,884 | 0 | <p>To understand why these kind of operations seem non-trivial in NoSQL implementations, it's good to think about why NoSQL exists (and has become very popular) at all.</p> <p>When you look at an early NoSQL implementation like memcached, the first use case was very simple, but very important: a blazingly fast cache for distributed data, to cache for example web page data. Very quickly stuff like clustering and sharding was added, so not all data has to be available everywhere at once at every single node in the cluster, but can be gathered on demand.</p> <p>NoSQL is very different from relational data storage. Don't overuse it. Consider relational databases as well, as they are sometimes far more suited for what you are trying to accomplish. In everything you design, ask yourself "Does this scale well?".</p> <p>Okay, back to your question. It is in general bad practice to do wildcard searches. You prepare your data in a way that you can retrieve your data in a scalable way.</p> <p>Redis is a very chique solution, allowing you to overcome a lot of NoSQL limitations in an elegant way.</p> <p>If getting "a list of all users" isn't something you have to do very often, or doesn't need to scale well, is always "I really always want <strong>all</strong> users" because it's for a daily scan anyway, use <code>HSCAN</code>. <code>SCAN</code> operations with a proper batch size don't get in the way of other clients, you can just retrieve your records a couple of thousand at a time, and after a few calls you've got everything.</p> <p>You can also store your users in a <code>SET</code>. There's no ordering in a set, so no pagination. It can help to keep your user names unique.</p> <p>If you want to do things like "get me all users that start with the letter 'a'", I'd use a <code>ZSET</code>. I'd wait a week or two for <code>ZRANGEBYLEX</code> which is just about to be released, in the works as we speak. Or use an ORM like Josiah Carlsons's 'rom' package.</p> <p>When you ask yourself "But now I have to do three calls instead of one when storing my data...?!": yup, that's how it works. If you need atomicity, use a Lua script, or MULTI+EXEC pipelining. Lua is generally easier.</p> <p>You can also ask yourself if using a <code>HSET</code> is needed. Do you need to retrieve the individual data members? Each key or member has some overhead. On top of that, <code>HGETALL</code> has a Big-O specification of <code>O(N)</code>, so it doesn't scale well. It might be better to serialize your row as a whole, using JSON or MsgPack, and store it in one <code>HSET</code> member, or just a simple <code>GET</code>/<code>SET</code>. Also read up on <code>SORT</code>.</p> <p>Hope this helps, TW</p> |
1,000,153 | 0 | <p>You could also use this to check if the Visual Studio Designer is running the code: </p> <pre><code>public static bool DesignMode { get { return (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv"); } } </code></pre> <p>Then in Form_Load: </p> <pre><code>if (!DesignMode) { // Run code that breaks in Visual Studio Designer (like trying to get a DB connection) } </code></pre> <p>However, this is less elegant than using the <code>LicensManager.UsageMode</code>, but it works (until Microsoft changes the name of the process Visual Studio runs under). </p> |
36,200,498 | 0 | <p>here is a slightly better solution that would still allow you to have nil values </p> <p>(please note that nil.to_i is 0 as well as any "text".to_i is also 0)</p> <pre><code>def my_method(str) Integer(str.gsub(/\s/, '')) rescue ArgumentError => e nil end </code></pre> <p>Example of use:</p> <pre><code>my_method('1000') => 1000 my_method('1 000') => 1000 my_method(' ') => nil my_method('some_text') => nil my_method('1.000') => nil my_method('1,000') => nil </code></pre> <p>If you want to treat <code>.</code> and <code>,</code> you can adapt the regex in gsub.</p> |
36,737,499 | 0 | <p>You may want to draw a white rectangle the size of the entire canvas, beneath the actual content of the canvas.</p> <pre><code>// get the canvas 2d context var ctx = canvas.getContext('2d'); // set the ctx to draw beneath your current content ctx.globalCompositeOperation = 'destination-over'; // set the fill color to white ctx.fillStyle = 'white'; // apply fill starting from point (0,0) to point (canvas.width,canvas.height) // these two points are the top left and the bottom right of the canvas ctx.fillRect(0, 0, canvas.width, canvas.height); </code></pre> <p>You have to apply these lines before generating your toDataUrl() stream.</p> <p>Idea taken from: <a href="http://www.mikechambers.com/blog/2011/01/31/setting-the-background-color-when-generating-images-from-canvas-todataurl/" rel="nofollow">http://www.mikechambers.com/blog/2011/01/31/setting-the-background-color-when-generating-images-from-canvas-todataurl/</a></p> |
39,379,716 | 0 | <p>You might be able to do this using a Base model such as:</p> <pre><code>@GET("mypath") Call<MyBaseModel<List<MyModel>>> getData(); </code></pre> <p>implement the Callback in the fragment as</p> <pre><code>Callback<MyBaseModel<List<?>>> </code></pre> <p>An example of an MyBaseModel would be:</p> <pre><code>public class MyBaseModel<Data> { private String page; private Data[] results; public String getPage() { return page; } public Data[] getResults() { return results; } } </code></pre> <p>The onResponse should return the:</p> <pre><code> Callback<MyBaseModel<?>> </code></pre> <p>then just check if the result is an instance of your model using 'instanceOf'</p> |
23,989,913 | 0 | <p>Calculating the length of a floating-point number decimal representation doesn't make much sense, as its underlying representation is binary. For example 0.1 in decimal form yields an infinite number of digits in binary.</p> <p>C has no intrinsic decimal type, so you will have to represent your number with some ad-hoc type, and shave off insignificant digits on the right. C-strings are not the worse choice for that.</p> |
6,426,802 | 0 | <p>You want a modal <strong>view</strong>. All <code>UIViewControllers</code> are able to present a modal view by using the following method:</p> <pre><code>[self presentModalViewController:yourViewController animated:YES]; </code></pre> <p>Check the Apple reference guides for more information and samples.</p> |
30,853,179 | 0 | <p>Script <strong>program</strong>:</p> <pre><code>#!/bin/bash for file in "$@";do echo "$file" done </code></pre> <p>Run program:</p> <pre><code>path/to/program filename1.* path/to/program filename1.* filename2.* path/to/program filename1.ext1 filename1.ext2 etc... </code></pre> |
15,089,599 | 0 | Callback function issue jquery <p>I have an issue with an if in a callback function and I don't understand why.</p> <p>After clicking on a div, the text is changing as I would like, but after the first shot it doesn't work anymore.</p> <p>My code is :</p> <pre><code><div id="2">message</div> <div id="1">dfdfgdfgrr</div> <script src="jquery.js"></script> <script> $(function () { $('#2').toggle(); function test() { $(document).on('click', '#1', function () { $('#2').toggle(300, function() { if($('#1').text('show')){ $('#1').text('hide'); }else{ $('#1').text('show'); } }); }); } test(); }); </script> </code></pre> <p><a href="http://jsfiddle.net/manguo_manguo/cydjY/" rel="nofollow">http://jsfiddle.net/manguo_manguo/cydjY/</a></p> |
26,988,098 | 0 | how to adjust div width based on other div postion <p>I have two div's one is <code>div-content</code>(red color) and second is <code>div-content2</code>(yellow color).<code>div-content</code> size is 0 to 50% and <code>div-content2</code> size 50% to 100%.</p> <p>Now In my screen 50% <code>div-content</code> and 50% <code>div-content2</code></p> <p>I need <code>div-content1</code> drag left to right <code>div-content1</code> width is 70 .In that time <code>div-content2</code> will be 30.if <code>div-content2</code> drag right to left width is 65 , in that time <code>div-content</code> width 35</p> <p>finely when increases and content remain content will auto adjust So Please give me any Idea.</p> <p>I am now to Stackoverflow .if i wrong to write Please guided me . </p> <p>Thanks in Advanced </p> |
10,640,235 | 0 | Sending email directly from my OSX app <p>I'm working on an OSX app which will handle an opt-in mailing list. I have a database containing opt-in email addresses, and the goal is for the user to click one button and have the app build a custom email update, then send out an email update to all members of the mailing list. This would be used for things such as updating fans about a band's performance, etc.</p> <p>I found lots of information for the iOS mailComposer, but nothing for something comparable in OSX. I did find a reference to a message framework, but for some reason can not find the documentation for it in the library (I'm sure it must be there somewhere...) The only other information I found suggested using a mailto: URL, which somewhat defeats the automated process I'm hoping to achieve.</p> <p>Can anyone point me in the right direction? Is there a specific framework I could research to determine how to active this goal?</p> |
31,661,277 | 0 | <p>At the end of the code you missed one )</p> <pre><code>else { console.log("I'll keep practicing coding and racing.") } </code></pre> |
27,086,850 | 0 | <p>The problem is that when you try to <code>getWidth</code>, your <code>ImageView</code> have not been appeared on the screen, so it always returns 0. So there are two ways, you can get the width:</p> <p><strong><em>First way</em></strong></p> <p>You need to <code>measure</code> your <code>ImageView</code> and then get the <code>measuredWidth</code>:</p> <pre><code>holder.photoPost = (ImageView) convertView.findViewById(R.id.photoPost); holder.photoPost.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); int targetHeight = holder.photoPost.getMeasuredWidth() * (9/16); </code></pre> <p><strong><em>Second way</em></strong></p> <p>Add <code>onGlobalLayoutListener</code> to your <code>ImageView</code> and then, you will be able to get the width:</p> <pre><code>holder.photoPost = (ImageView) convertView.findViewById(R.id.photoPost); holder.photoPost.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { holder.photoPost.getViewTreeObserver() .removeOnGlobalLayoutListener(this); } else { holder.photoPost.getViewTreeObserver() .removeGlobalOnLayoutListener(this); } int targetHeight = holder.photoPost.getWidth() * (9/16) } }); </code></pre> |
33,179,790 | 0 | <p>I use to think about a reference as an alias for another object. If you apply this to people, the alias is a nickname.</p> <p>For example, if you have:</p> <pre><code>Person Robert; Person& Bob = Robert; </code></pre> <p>you only have one person, but you sometimes call him Robert and sometimes call him Bob. But he is still the same person. </p> <p>Trying to involve Bob's address into this just makes it harder. I find it easier to just consider references at the abstract level - two names for the same thing.</p> |
13,727,723 | 0 | <p><strong>val</strong> and <strong>text</strong> are functions, you must add () to call them and get their results. If you juste write <strong>val</strong> or <strong>text</strong>, it's the reference to the function itself (and in js, a function is an object).</p> <pre><code>myfield.val( mytext.text() ); </code></pre> <p>this will set the value of input field 'myfield' with the text inside the element 'mytext'</p> <p>Try to do the same in your code</p> <pre><code>$("#TheForm #LessonNumber1 #LineNumber1 #Speaker").val( $('your_selector').text() ); </code></pre> |
3,804,134 | 0 | <p>Here's an alternative for you:</p> <pre><code>DateTime.Now.ToString("d", new CultureInfo("de-DE")) </code></pre> <p>German's use <code>.</code> as the date separator.</p> |
29,297,508 | 0 | <p>Don't panic, the World has been saved. The solution is to wrap Airborne and whatever else in a module:</p> <pre><code>module MyHelpers include Airborne include Capybara::DSL end </code></pre> <p>Then pass that:</p> <pre><code>World(MyHelpers) </code></pre> |
3,428,771 | 0 | <blockquote> <p>3: Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?</p> </blockquote> <p>The first part of this question is hard to answer without a technological context. If the cluster platform includes the ability to make calls on remote objects as if they were local objects (e.g. as is possible with EJBs using RMI or IIOP under the hood) then yes it can be done. For example, the JVM resident singleton objects could be proxies for a cluster-wide singleton object, that was initially located / wired via JNDI or something. But cluster-wide singletons are a potential bottleneck because each call on one of the singleton proxies results in an (expensive) RPC to a single remote object.</p> <p>The second part of the question is that Spring Bean Factories can be configured with different scopes. The default is for singletons (scoped at the webapp level), but they can also be session or request scoped, or an application can define its own scoping mechanism.</p> |
32,368,621 | 0 | <p>Try this</p> <pre><code> DataTable dt1 = new DataTable(); dt1.Columns.Add("Name", typeof(string)); dt1.Rows.Add(new string[] {"Mani"}); dt1.Rows.Add(new string[] {"Ram"}); dt1.Rows.Add(new string[] {"Guna"}); dt1.Rows.Add(new string[] {"Praveen"}); dt1.Rows.Add(new string[] {"Jai"}); DataTable dt2 = new DataTable(); dt2.Columns.Add("Name", typeof(string)); dt2.Rows.Add(new string[] {"kumar"}); dt2.Rows.Add(new string[] {"bharath"}); dt2.Rows.Add(new string[] {"ashok"}); dt2.Rows.Add(new string[] {"vikram"}); dt2.Rows.Add(new string[] {"san"}); DataTable dt3 = dt1.Copy(); foreach (DataRow row in dt2.AsEnumerable()) { dt3.Rows.Add(row.ItemArray); } dataGridView1.DataSource = dt3; </code></pre> |
14,486,647 | 0 | Google map does not load when load inline content using jquery load <p>I have an issue with google map. I load inline content (including content map) with jquery .load() and the map is doesn't load or it won't show. it just display blank.</p> <p>My code to load inline content with jquery load()</p> <pre><code>$('#content').load(' #content > *', function(){ function initialize(address, num, zoom) { var geo = new google.maps.Geocoder(), latlng = new google.maps.LatLng(-34.397, 150.644), myOptions = { 'zoom': zoom, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }, map = new google.maps.Map(document.getElementById("map_canvas_" + num), myOptions); geo.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { // status } }); }}); </code></pre> <p>As you can see, I have re-initialize the map but it still produce blank map not rendering map content.</p> <p>Here the map code in the html content that loaded.</p> <pre><code><script type="text/javascript"> jQuery(document).ready(function() { initialize("'.$address.'",'.$num.','.$zoom.'); }); </script> <div class="shortcode map"> <div id="map_canvas_'.$num.'" style="display: block;width:'.$width.';height:'.$height.';" class="map-container">&nbsp;</div> </div> </code></pre> <p>Any workaround would be great.</p> <p>Regards,</p> |
34,606,142 | 0 | use panGestureRecognizer or touch events to drag and move an item ios <p>I am moving items in the view by touching them to the place where i leave it i am using touch events <code>touchesBegin</code> , <code>touchesMoved</code> , <code>touchesEnd</code><br> and in <code>touchesMoved</code> i move the item.frame to the new location and it works with me but then i found a code that use <code>panGestureRecognizer</code><br> and then i cant determine what to use </p> <p>the code to handle pan was </p> <pre><code>- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer { if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) { CGPoint translation = [recognizer translationInView:self.superview]; CGPoint translatedCenter = CGPointMake(self.center.x + translation.x, self.center.y + translation.y); [self setCenter:translatedCenter]; [recognizer setTranslation:CGPointZero inView:self]; } </code></pre> <p><strong>given that i need the exact coordinates of the point i am touching</strong> </p> |
6,721,447 | 0 | <p>I notice the first URL shows the location "houston" in the description text. The second URL attempts to show location in the title, showing Location Unknown instead. The second URL <strong>does</strong> show a location "NYC" in the description text. </p> <p>It may be your framework/library does not have the 'city' datum available at the time it is printing the title. </p> |
35,914,341 | 0 | <h2>UPDATE</h2> <p>When the device is stationary again, with screen off and on battery for a period of time, Doze applies the full CPU and network restrictions on <strong>PowerManager.WakeLock, AlarmManager alarms, and GPS/Wi-Fi scans</strong>.</p> <p>Visit <a href="http://developer.android.com/intl/in/training/monitoring-device-state/doze-standby.html#whitelisting-cases" rel="nofollow">Use Cases for Whitelisting</a> for more detail.</p> <blockquote> <p>The table below highlights the acceptable use cases for requesting or being on the Battery Optimizations exceptions whitelist. In general, your app should not be on the whitelist unless Doze or App Standby break the core function of the app or there is a technical reason why your app cannot use GCM high-priority messages.</p> </blockquote> <p><a href="http://developer.android.com/intl/in/preview/api-overview.html#doze_on_the_go" rel="nofollow">android n developer</a> says</p> <p>Doze is particularly likely to affect activities that AlarmManager <strong>alarms</strong> and <strong>timers manage</strong>, because alarms in <strong>Android 5.1 (API level 22) or lower do not fire when the system is in Doze</strong>.</p> <p>Android 6.0 (API level 23) introduces two new AlarmManager methods: <code>setAndAllowWhileIdle()</code> and <code>setExactAndAllowWhileIdle()</code>. With these methods, you can set alarms that will fire even if the device is in Doze.</p> <p><strong>Note</strong>: Neither <code>setAndAllowWhileIdle()</code> nor <code>setExactAndAllowWhileIdle()</code> can fire alarms more than once per 15 minutes per app.</p> <p><a href="http://developer.android.com/intl/in/training/monitoring-device-state/doze-standby.html#testing_doze_and_app_standby" rel="nofollow">Testing with Doze and App Standby</a> </p> |
2,691,167 | 0 | <p>A C# null is not the same as a database NULL.</p> <p>In your insertion code you probably need to pick up that the value is "N/A"/null and then insert a DBNull instead. What does your DB insertion code look like?</p> |
11,442,677 | 0 | <p><a href="http://developer.android.com/guide/topics/data/data-storage.html#filesInternal" rel="nofollow">The documentation</a> has a pretty decent guide on how to best access the filesystem.</p> |
38,160,571 | 0 | Using PHP to Search and Replace POST vars in docx document <p>I am trying to do a search and replace on a Microsoft Word docx document. The odd problem I am having is that, of the 7 posted vars, 1 and 5 do not replace. In checking Chrome Tools, they all appear in the posted form data. The names are all spelled correctly too. </p> <p>To explain this code, I am opening a template doc, copying it to another name (the named file which will be downloaded), replacing text in document.xml, then replacing text in the footer. Then I close the file and download it. It downloads, except, the vars $pname and $hca2name do not replace inside of the document. All other vars are properly replaced.</p> <p>Any thoughts are very much appreciated. Thank you. Here is the code:</p> <pre><code><?php $pname = (string) $_POST['pname']; $countyres = (string) $_POST['countyres']; $a1name = (string) $_POST['a1name']; $a2name = (string) $_POST['a2name']; $hca1name = (string) $_POST['hca1name']; $hca2name = (string) $_POST['hca2name']; $atty = (string) $_POST['atty']; $countyres = (string) $_POST['countyres']; $fn = 'POA-'.$pname.'.docx'; $s = "docs_archive/PA-poas2no.docx"; $wordDoc = "POA-".$pname.".docx"; copy($s, $wordDoc); $zip = new ZipArchive; //This is the main document in a .docx file. $fileToModify = 'word/document.xml'; if ($zip->open($wordDoc) === TRUE) { //Read contents into memory $oldContents = $zip->getFromName($fileToModify); //Modify contents: $newContents = str_replace('{pname}', $pname, $oldContents); $newContents = str_replace('{a1name}', $a1name, $newContents); $newContents = str_replace('{a2name}', $a2name, $newContents); $newContents = str_replace('{hca1name}', $hca1name, $newContents); $newContents = str_replace('{hca2name}', $hca2name, $newContents); $newContents = str_replace('{atty}', $atty, $newContents); $newContents = str_replace('{countyres}', $countyres, $newContents); //Delete the old... $zip->deleteName($fileToModify); //Write the new... $zip->addFromString($fileToModify, $newContents); //Open Footer and change vars there $ft = 'word/footer1.xml'; $oldft = $zip->getFromName($ft); $newft = str_replace('{pname}', $pname, $oldft); $zip->deleteName($ft); $zip->addFromString($ft, $newft); $zip->close(); header('Content-Description: File Transfer'); header("Content-Type: application/force-download"); header('Content-Type: application/msword'); header('Content-Disposition: attachment; filename="'.$fn.'"'); header('Content-Transfer-Encoding: binary'); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); readfile($fn); unlink($fn); exit(); } ?> </code></pre> |
24,219,696 | 0 | drawstring bold and normal text <p>have code:</p> <pre><code>using (Graphics g = Graphics.FromImage(pictureBox1.Image)) { Font drawFont = new Font("Arial", 12); Font drawFontBold = new Font("Arial", 12, FontStyle.Bold); SolidBrush drawBrush = new SolidBrush(Color.Black); g.DrawString("this is normal", drawFont, drawBrush, new RectangleF(350f, 250f, 647, 200)); g.DrawString(" and this is bold text", drawFontBold, drawBrush, new RectangleF(350f, 250f, 647, 200)); } </code></pre> <p>I need to get</p> <blockquote> <p>this is normal <strong>and this is bold text</strong></p> </blockquote> <p>But I receive overlay of second text on first</p> |
13,032,782 | 0 | <p>It seems that my question was nonsence. Here's my code:</p> <pre><code>PreparedStatement stmt = con.prepareStatement(query); stmt.setLong(1, key); stmt.execute(query); </code></pre> <p><code>query</code> is (obiously) String. What fixed the problem is removing <code>query</code> from <code>stmt.execute(query)</code></p> <p>I'm still not sure if the behavior of <code>execute()</code> in such a case is correct.</p> |
1,684,823 | 0 | <p>Also check to make sure the intermediate directories are also permissioned as 755, as all the directories in the path need to be executable to be traversed.</p> |
13,336,467 | 0 | .NET CLR / Framework detection at runtime <p>Is it possible to determine at runtime:</p> <ol> <li><p>Which version of the .NET framework the application is targeting?</p></li> <li><p>If the application is targeting a full or client profile of the framework?</p></li> </ol> <p>I have tried using <code>Environment.Version</code> however this produces highly inaccurate results. Equally, I have been unable to find any solutions for determining which profile is being used.</p> |
24,203,376 | 0 | <p>The commands are not described in Part 2 of the Specification but rather in <strong><a href="http://www.trustedcomputinggroup.org/files/static_page_files/72C33D71-1A4B-B294-D02C7DF86630BE7C/TPM%20Main-Part%203%20Commands_v1.2_rev116_01032011.pdf" rel="nofollow">Part 3 - Commands</a></strong>. </p> <p>The <code>TPM_seal</code> command is defined in section 10.1 on page 72. Line 1331 shows you how the command has to look like.</p> <p>Also note that the returnvalue <code>rv</code> does not tell you whether the command was successfully executed on the TPM. It just tells you whether TBS was able to send the command and recieve the response. You have to decode the <code>pabResult</code> buffer.</p> <p>You should also look at my answer to your <a href="http://stackoverflow.com/questions/24145810/sealing-data-using-tpm-in-windows">other question</a>.</p> |
10,227,882 | 0 | <p>Since <code>friend</code> relationships aren't inherited, you need to declare <code>convertF</code> as a friend of both classes. But you need this only if the function needs access the internals of these classes - are you sure the public interface of the classes doesn't suffice?</p> <p>One further reason to try to avoid such a double friend is that it would create a circular dependency between these classes via the signature of <code>convertF</code>. </p> <p><strong>Update:</strong> This is exactly why you can't declare your friend function the way you show above. For this to work, the compiler would need to know the full definition of <code>iFraction</code> while it is still not finished with the definition of the base class <code>Fraction</code>, which is impossible.</p> <p>Technically it could work the other way around, by forward declaring <code>iFraction</code>. Although I still wouldn't consider it a good solution. Are you sure your class hierarchy is right?</p> |
40,977,608 | 0 | <p>The error you are receiving in your code is due to the following line <code>if (character.ToString() = "space")</code></p> <p>You are attempting to assign the string literal "space" to <code>character.ToString()</code>, I also have this error in my comment which I can't edit anymore.</p> <p>Here's a snippet that will check the key code against an enum instead of a string, it will then call the <code>HandleComparison</code> method if Space was pressed, and then clear out the <code>StringBuilder</code></p> <p>The only issue I found here is that pressing Shift will prefix the string with <code><shift></code>, so some additional logic will have to be applied for action keys, but this is a base to get you started with a working code sample.</p> <p>I hope this helps.</p> <pre><code>class Program { private static StringBuilder builder; static void Main(string[] args) { using (var api = new KeystrokeAPI()) { builder = new StringBuilder(); api.CreateKeyboardHook(HandleKeyPress); Application.Run(); } } private static void HandleKeyPress(KeyPressed obj) { // To be more reliable, lets use the KeyCode enum instead if (obj.KeyCode == KeyCode.Space) { // Spacebar was pressed, let's check the word and flush the StringBuilder HandleComparison(builder.ToString()); builder.Clear(); return; } // Space wasn't pressed, let's add the word to the StringBuilder builder.Append(obj); } // Handle comparison logic here, I.E check word if exists on blacklist private static void HandleComparison(string compareString) { Console.WriteLine(compareString); } } </code></pre> |
34,208,877 | 0 | Erlang's FSM code_change function usage <p>I'm learning Erlang and I've learned about hot code loading, but I don't know how the gen_fst behavior's code_change function works. I also can't find any example of it.</p> <p>Should I create an action like so:</p> <pre><code>upgrade() -> gen_fsm:send_event(machine_name, upgrade). </code></pre> <p>And have a handler in the states like so:</p> <pre><code>some_state(upgrade, State) -> code:purge(?MODULE), compile:file(?MODULE), code:load_file(?MODULE), {next_state, some_state, State, 1000}. </code></pre> <p>I've tried this, but the <code>code_change/4</code> function doesn't execute. How should I correctly implement hot code loading in my FSM?</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.