pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
16,860,338 | 0 | <p>I had a similar problem and the solution that I found was to replace the startActivityForResult functionality by storing the result into the shared preferences and loading them later in onResume. Check the full discussion <a href="http://stackoverflow.com/q/16837679/2436683">here</a>.</p> |
18,134,031 | 0 | <p>Maybe you are confused by the fact, that the class <code>Ordering</code> is declared as <code>Ordering<T></code>, but the return value of the <code>onResultOf</code> method is <code>Ordering<F></code>.</p> <p>The first type argument of the <code>Function</code>, you are providing to <code>onResultOf</code> is the type argument of the result.</p> <p>That also means, that <code>Value</code> is not forced to be a subtype of <code>Map.Entry</code>.</p> |
19,243,491 | 0 | <p>I've been fighting with something like what you show (only one major tick in the axis range). None of the matplotlib tick formatter satisfied me, so I use <code>matplotlib.ticker.FuncFormatter</code> to achieve what I wanted. I haven't tested with twin axes, but my feeling is that it should work anyway.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib import ticker import numpy as np #@Mark: thanks for the suggestion :D mi, ma, conv = 4, 8, 1./3. x = np.linspace(mi, ma, 20) y = 1 / (x ** 4) fig, ax = plt.subplots() ax.plot(x, y) # plot the lines ax.set_xscale('log') #convert to log ax.set_yscale('log') ax.set_xlim([0.2, 1.8]) #large enough, but should show only 1 tick def ticks_format(value, index): """ This function decompose value in base*10^{exp} and return a latex string. If 0<=value<99: return the value as it is. if 0.1<value<0: returns as it is rounded to the first decimal otherwise returns $base*10^{exp}$ I've designed the function to be use with values for which the decomposition returns integers """ exp = np.floor(np.log10(value)) base = value/10**exp if exp == 0 or exp == 1: return '${0:d}$'.format(int(value)) if exp == -1: return '${0:.1f}$'.format(value) else: return '${0:d}\\times10^{{{1:d}}}$'.format(int(base), int(exp)) # here specify which minor ticks per decate you want # likely all of them give you a too crowed axis subs = [1., 3., 6.] # set the minor locators ax.xaxis.set_minor_locator(ticker.LogLocator(subs=subs)) ax.yaxis.set_minor_locator(ticker.LogLocator(subs=subs)) # remove the tick labels for the major ticks: # if not done they will be printed with the custom ones (you don't want it) # plus you want to remove them to avoid font missmatch: the above function # returns latex string, and I don't know how matplotlib does exponents in labels ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.yaxis.set_major_formatter(ticker.NullFormatter()) # set the desired minor tick labels using the above function ax.xaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format)) ax.yaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format)) </code></pre> <p>The figure that I get is the following <img src="https://i.stack.imgur.com/HfNWP.png" alt="enter image description here">:</p> <p>Of course you can set different minor locators for x and y axis and you can wrap everything from <code>ticks_format</code> to the end into a function that accepts an axes instance <code>ax</code> and <code>subs</code> or <code>subsx</code> and <code>subsy</code> as input parameters.</p> <p>I hope that this helps you</p> |
19,077,984 | 0 | <p>I have no idea of how windows works, but I'd think that you don't put Magento into <code>C:\Program Files (x86)\PHP\v5.3</code>. So my guess is that the root folder of the virtual host (or whatever equivalent of those on IIS are) is not correctly defined.<br> can you check that?</p> <p>ps: any particular reason you're not using a linux server? I think this is going to give you a lot of troubles down the road.</p> |
11,701,097 | 0 | <p>In addition to <strong>JapanPro's</strong> answer:<br> Your HTML can have :</p> <pre><code><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </code></pre> <p>instead of an implicit header declaration: </p> <pre><code>HTTP-header (Content-Type: text/html; charset=UTF-8) </code></pre> |
21,599,421 | 0 | <p>It doesn't matter how you pass the arguments to below,</p> <pre><code>while ((i = getopt_long(argc, argv, "MCFA:acdegphinNorstuVv?wxl", longopts, &lop)) != EOF) switch (i) { ... case 'a': flag_all++; break; case 'n': flag_not |= FLAG_NUM; break; ... </code></pre> <p>Just the cases <code>a</code> & <code>n</code> are enabled which is processed later with the respective flags set. </p> |
13,207,244 | 0 | Programmatically adding UITextField to a dropdownlist <p>I have a tableview controlled by a UITableViewController. In this UITableViewController class I have added a <code>UITextField</code> programmatically to my UINavigationItem by adding these lines to my viewDidLoad method :</p> <pre><code>CGRect passwordTextFieldFrame = CGRectMake(20.0f, 100.0f, 280.0f, 31.0f); UITextField *passwordTextField = [[UITextField alloc] initWithFrame:passwordTextFieldFrame]; passwordTextField.placeholder = @"Password"; passwordTextField.backgroundColor = [UIColor whiteColor]; passwordTextField.textColor = [UIColor blackColor]; passwordTextField.font = [UIFont systemFontOfSize:14.0f]; passwordTextField.borderStyle = UITextBorderStyleRoundedRect; passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing; passwordTextField.returnKeyType = UIReturnKeyDone; passwordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; passwordTextField.tag = 2; passwordTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; passwordTextField.delegate = self; // ADD THIS LINE self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:passwordTextField]; </code></pre> <p>The <code>UITextField</code> is displayed correctly on my navigationbar but when I click it the textFieldDidBeginEditing never fires.</p> <p>I have added the to my header file along with the textFieldDidBeginEditing method.</p> <p>I tried doing the exact same thing in a view controlled by UIViewController and here the textFieldDidBeginEditing gets fired when I click the "textfield" - So I suspect the fact that I am adding the textfield to a UITableViewController is what's causing trouble.</p> <p>You might think - why didn't you add a "uinavigationbutton" to the "NavigationBar" instead - but I can't as the uidropdownmenu that I want to call when the button is being clicked only accepts a "UITextField".</p> |
24,953,980 | 0 | Default Concurrency strategy for Query Cache in Hibernate using ECache <p>I was wondering about the default concurrency strategy for the Query level caching in Hibernate if we do not provide it explicitly. I have gone through the link <a href="https://docs.jboss.org/hibernate/orm/4.0/manual/en-US/html/performance.html#performance-cache" rel="nofollow">https://docs.jboss.org/hibernate/orm/4.0/manual/en-US/html/performance.html#performance-cache</a> but unable to find the exact solution. Any help? Thanks.</p> |
29,945,339 | 0 | <p>You cannot find socat libraries because there are none. socat is implemented as a monolithic executable (it does link to the standard system libraries though). You can download <a href="http://www.dest-unreach.org/socat/" rel="nofollow">socat</a> sources and copy-paste required functionality.</p> |
18,390,045 | 0 | <p>You can do this using <code>hoist</code> from the <code>mmorph</code> package. <code>hoist</code> lets you modify the base monad of anything that implements <code>MFunctor</code> (which is most monad transformers):</p> <pre><code>hoist :: (MFunctor t) => (forall x . m x -> n x) -> t m r -> t n r </code></pre> <p>You can then use it for your problem like this:</p> <pre><code>co' tma ma = hoist (co ma) tma </code></pre> <p>Then you're done!</p> <p>To understand why that works, let's go through the types step by step:</p> <pre><code>co :: (Monad m) => m a -> m a -> m a ma :: (Monad m) => m a co ma :: (Monad m) => m a -> m a hoist (co ma) :: (Monad m, MFunctor t) => t m a -> t m a tma :: (Monad m, MFunctor t) => t m a hoist (co ma) tma :: (Monad m, MFunctor t) => t m a </code></pre> <p>Note that <code>hoist</code> has certain laws it must satisfy that ensure that it does "the right thing" that you would expect:</p> <pre><code>hoist id = id hoist (f . g) = hoist f . hoist g </code></pre> <p>These are just functor laws, guaranteeing that <code>hoist</code> behaves intuitively.</p> <p><code>hoist</code> is provided in the <code>Control.Monad.Morph</code> module of the <code>mmorph</code> package, which you can find <a href="http://hackage.haskell.org/package/mmorph" rel="nofollow">here</a>. The bottom of the main module has <a href="http://hackage.haskell.org/packages/archive/mmorph/1.0.0/doc/html/Control-Monad-Morph.html#g:3" rel="nofollow">a tutorial</a> teaching how to use the package</p> |
18,594,451 | 0 | ActiveDirectory DirectorySearcher: why is FindOne() slower than FindAll() and why are properties omitted? <p>I have a loop that retrieves some info from ActiveDirectory. It turned out to be a big performance bottleneck.</p> <p>This snippet (inside a loop that executed it 31 times) took 00:01:14.6562500 (1 minute and 14 seconds):</p> <pre><code>SearchResult data = searcher.FindOne(); System.Diagnostics.Trace.WriteLine(PropsDump(data)); </code></pre> <p>Replacing it with this snippet brought it down to 00:00:03.1093750 (3 secconds):</p> <pre><code>searcher.SizeLimit = 1; SearchResultCollection coll = searcher.FindAll(); foreach (SearchResult data in coll) { System.Diagnostics.Trace.WriteLine(PropsDump(data)); } </code></pre> <p>The results are exactly identical, the same properties are returned in the same order. I found some info on memory leaks in <a href="http://stackoverflow.com/questions/1135013/is-directorysearcher-sizelimit-1-for-findall-equal-to-findone-directoryse">another thread</a>, but they did not mention performance (I'm on .Net 3.5).</p> <hr> <p>The following is actually a different question but it gives some background on why I'm looping in the first place:</p> <p>I wanted to get all the properties in one single query, but I cannot get the DirectorySearcher to return all the wanted properties in one go (it omits about 30% of the properties specified in PropertiesToLoad (also tried setting it in the constructor wich makes no difference), I found someone else had the same problem and <a href="http://forums.asp.net/t/1822574.aspx/1" rel="nofollow">this is his solution (to loop through them)</a>. When I loop through them like this, either using FindOne() or FindAll() I do get all the properties, But actually it all feels like a workaround.</p> <p>Am I missing something?</p> <hr> <p>Edit:</p> <p>Seems like the problem was with the way I got the first DirectoryEntry on which I was using the DirectorySearcher.</p> <p>This was the code that caused the DirectorySearcher only to return some of the properties:</p> <pre><code>private static DirectoryEntry GetEntry() { DirectoryContext dc = new DirectoryContext(DirectoryContextType.DirectoryServer, "SERVERNAME", "USERNAME", "PASSWORD"); Forest forest = Forest.GetForest(dc); DirectorySearcher searcher = forest.GlobalCatalogs[0].GetDirectorySearcher(); searcher.Filter = "OU=MyUnit"; searcher.CacheResults = true; SearchResultCollection coll = searcher.FindAll(); foreach (SearchResult m in coll) { return m.GetDirectoryEntry(); } throw new Exception("DirectoryEntry not found"); } </code></pre> <p>After replacing that big mouthfull with just this line, the DirectorySearcher returned all the properties and looping was no longer needed:</p> <pre><code>private static DirectoryEntry GetEntry2() { return new DirectoryEntry(@"LDAP://SERVERNAME/OU=MyUnit,DC=SERVERNAME,DC=local", "USERNAME", "PASSWORD"); } </code></pre> <p>Now it takes less than one 18th of a second to get all wanted properties of 31 entries. So, it seems that two different instances of the same DirectoryEntry can give different results depending on the way it was constructed... feels a bit creepy!</p> <hr> <p>Edit</p> <p>Used <a href="http://www.jetbrains.com/decompiler/" rel="nofollow">JetBrains DotPeek</a> to look at the implementation. The FindOne function starts like this:</p> <pre><code>public SearchResult FindOne() { SearchResult searchResult1 = (SearchResult) null; SearchResultCollection all = this.FindAll(false); ... </code></pre> <p>My first reaction was Argh! no wonder... but then I noticed the argument. FindAll has a private version that accepts a boolean, this is the start of FindAll:</p> <pre><code>[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public SearchResultCollection FindAll() { return this.FindAll(true); } private SearchResultCollection FindAll(bool findMoreThanOne) { ... // other code this.SetSearchPreferences(adsSearch, findMoreThanOne); </code></pre> <p>So this gives slightly more insight, but does not really explain much.</p> |
13,427,097 | 0 | <p>Give your text box a id for example "txtInput" give your iframe a id for example "myIframe" on the button give it no navigation so it stays on current page and use the onclick="myFunction()"</p> <p>in the function you can use this (excuse me if this is slightly wrong its been a while since I have used HTML</p> <pre><code> function myFunction() { var iframe = document.getElementById("myIframe"); var input = document.getElementById("txtInput").text; //check to see if there is a valid url in the text box be carefull if there are multiple links in the text box it will put them all in and the iframe will go to 127.0.0.1 or search engine due to incorrect URL var isURL=new RegExp(/(((f|ht)(tp|tps):\/\/)[\w\d\S]+)/,g); iframe.src = input.match(isURL); } </code></pre> <p>If you do not want to mess with regular expresions you can just simply use the following.</p> <pre><code>function myFunction() { var iframe = document.getElementById("myIframe"); var input = document.getElementById("txtInput").text; iframe.src = isURL; } </code></pre> |
38,546,526 | 0 | <p>Try this... In Eclipse, go to the Servers menu and right click 'New.' In the 'New Server' window find the 'Configure runtime environments' link (<a href="http://i.stack.imgur.com/Cvkmd.jpg" rel="nofollow">See Pic 1</a>) and once there you then click the server that needs the updated JRE upgrade and then Click 'Edit'. In the Edit Server Runtime Environment Window there should be a Java home textfield where you can put the jdk that you upgraded to. (<a href="http://i.stack.imgur.com/51I8r.jpg" rel="nofollow">See Pic 2</a>)</p> <p>NOTE: This was done in Eclipse Kepler in the time of this writing. Should work in later versions as well.</p> |
20,431,810 | 0 | Exit status of child spawned in a pipe <p>Simple question but I cannot find a good answer - here goes with an example:</p> <p>"world.pl" spawns "hello.pl" in a child and processes its stdout. "world.pl" needs to know the exit status of "hello.pl". Making a system call is not an option, since "world.pl" needs to process the stdout of "hello.pl". I am also trying to avoid fork(). Question: How can "world.pl" find the exit status of "hello.pl"? Using perl v5.12.4 on Darwin, if it matters. Thanks in advance, - M.</p> <pre><code>#!/opt/local/bin/perl -w ## hello.pl <name> [more names] exit 1 if ($#ARGV < 0); foreach (@ARGV) { print "Hello, $_\n" } exit 0; </code></pre> <p>The other part ...</p> <pre><code>#!/opt/local/bin/perl -w ## world.pl name [more names ...] open (FP, "./hello.pl @ARGV |") or die "$0: Cannot open pipe: $!\n"; while (<FP>) { print } close FP; my $status = 0; # Want this to be exit status of the process "hello.pl" exit $status; </code></pre> |
40,858,469 | 0 | <p>As per you are not using AsyncTask, you can't get the opportunity of onProgressUpdate feature. So, you have to update your progress bar status manually like using own thread and you have already do. But, I solved my problem using below source code, you can check it: </p> <pre><code> private void createThread(){ Runnable runable = new updateProgressStatus(); progressUpdateThread = new Thread(runnable); progressUpdateThread.start(); } public class updateProgressStatus implements Runnable { public void run() { while(Thread.currentThread()==progressUpdateThread) try { Thread.sleep(1000); progressHandler.sendMessage(YOUR MESSAGE ); } catch (InterruptedException e) { // Interrupt problem Thread.currentThread().interrupt(); } catch (Exception e) { e.printStackTrace(); } } } private Handler progressHandler = new Handler(){ @Override public void handleMessage(Message message) { // Now, update your progress bar status progress.setProgress(message.what); } }; </code></pre> |
21,829,967 | 0 | <p>Instead of opening the Google Glass camera app, you could take the picture yourself: <a href="http://developer.android.com/training/camera/cameradirect.html" rel="nofollow">http://developer.android.com/training/camera/cameradirect.html</a></p> <p>This is even mentioned in the GDK reference:</p> <blockquote> <p>Building your own logic with the Android Camera API. Follow these guidelines if you are using this method:</p> <ul> <li>Take a picture on a camera button click and a video on a long click, just like Glass does.</li> <li>Indicate to the user whether a picture was taken or a video was recorded.</li> <li>Keep the screen on during capture.</li> </ul> </blockquote> |
8,576,109 | 0 | <p>That's impossible to tell, since it depends on the actual runtime environment. A JIT, AOT or Hotspot compiler may very well optimize away the potential method overhead.</p> |
11,655,044 | 0 | Lazy list items are not clicking per item only per row <p>I have been breaking my head trying to get this working but I can't to save my life, I was hoping one of you guys knew how to do it. Basically, I have a list of nature pictures that are loading in a lazy ListView, but my problem is that I can only make the row clickable. I need to make the the individual images clickable. Everything else works like a charm, I really appreciate the help.</p> <p>Activity:</p> <pre><code>public class AmainActivityNature extends Activity { ListView list; LazyAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); list=(ListView)findViewById(R.id.list); adapter=new LazyAdapter(this, mStrings, mphotos); list.setAdapter(adapter); Button bLeft = (Button) findViewById(R.id.buttonLeft); bLeft.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent mainIntentOne = new Intent(AmainActivityNature.this, AmainActivityNature.class); AmainActivityNature.this.startActivity(mainIntentOne); /* Finish splash activity so user cant go back to it. */ AmainActivityNature.this.finish(); /* Apply our splash exit (fade out) and main entry (fade in) animation transitions. */ overridePendingTransition(R.anim.animation_enterl, R.anim.animation_leaver); } }); Button bRight = (Button) findViewById(R.id.buttonRight); bRight.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent("com.testing.image.AMAINACTIVITYNATURE")); finish(); } }); list.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { switch (arg2) { case 0: Intent newActivity0 = new Intent(AmainActivityNature.this,NatureTwoOne.class); startActivity(newActivity0); break; case 1: Intent newActivity1 = new Intent(AmainActivityNature.this,NatureTwoTwo.class); startActivity(newActivity1); break; case 2: Intent newActivity2 = new Intent(AmainActivityNature.this,NatureTwoThree.class); startActivity(newActivity2); break; case 3: Intent newActivity3 = new Intent(AmainActivityNature.this,NatureTwoFour.class); startActivity(newActivity3); break; case 4: Intent newActivity4 = new Intent(AmainActivityNature.this,NatureTwoFive.class); startActivity(newActivity4); break; case 5: Intent newActivity5 = new Intent(AmainActivityNature.this,NatureTwoSix.class); startActivity(newActivity5); break; case 6: Intent newActivity6 = new Intent(AmainActivityNature.this,NatureTwoSeven.class); startActivity(newActivity6); break; case 7: Intent newActivity7 = new Intent(AmainActivityNature.this,NatureTwoEight.class); startActivity(newActivity7); break; case 8: Intent newActivity8 = new Intent(AmainActivityNature.this,NatureTwoNine.class); startActivity(newActivity8); break; case 9: Intent newActivity9 = new Intent(AmainActivityNature.this,NatureTwoTen.class); startActivity(newActivity9); break; case 10: Intent newActivity10 = new Intent(AmainActivityNature.this,NatureTwoEleven.class); startActivity(newActivity10); break; case 11: Intent newActivity11 = new Intent(AmainActivityNature.this,NatureTwoTwoelve.class); startActivity(newActivity11); break; case 12: Intent newActivity12 = new Intent(AmainActivityNature.this,NatureTwoThirteen.class); startActivity(newActivity12); break; case 13: Intent newActivity13 = new Intent(AmainActivityNature.this,NatureTwoFourteen.class); startActivity(newActivity13); break; case 14: Intent newActivity14 = new Intent(AmainActivityNature.this,NatureTwoFifteen.class); startActivity(newActivity14); break; case 15: Intent newActivity15 = new Intent(AmainActivityNature.this,NatureTwoSixteen.class); startActivity(newActivity15); break; case 16: Intent newActivity16 = new Intent(AmainActivityNature.this,NatureTwoSeventeen.class); startActivity(newActivity16); break; case 17: Intent newActivity17 = new Intent(AmainActivityNature.this,NatureTwoEighteen.class); startActivity(newActivity17); break; case 18: Intent newActivity18 = new Intent(AmainActivityNature.this,NatureTwoNineteen.class); startActivity(newActivity18); break; case 19: Intent newActivity19 = new Intent(AmainActivityNature.this,NatureTwoTwoenty.class); startActivity(newActivity19); break; case 20: Intent newActivity20 = new Intent(AmainActivityNature.this,NatureTwoTwoentyone.class); startActivity(newActivity20); break; case 21: Intent newActivity21 = new Intent(AmainActivityNature.this,NatureTwoTwoentytwo.class); startActivity(newActivity21); break; case 22: Intent newActivity22 = new Intent(AmainActivityNature.this,NatureTwoTwoentythree.class); startActivity(newActivity22); break; case 23: Intent newActivity23 = new Intent(AmainActivityNature.this,NatureTwoTwoentyfour.class); startActivity(newActivity23); break; case 24: Intent newActivity24 = new Intent(AmainActivityNature.this,NatureTwoTwoentyfive.class); startActivity(newActivity24); break; default: // Nothing do! } } }); Button b=(Button)findViewById(R.id.button1); b.setOnClickListener(listener); } @Override public void onDestroy() { list.setAdapter(null); super.onDestroy(); } public OnClickListener listener=new OnClickListener(){ @Override public void onClick(View arg0) { adapter.imageLoader.clearCache(); adapter.notifyDataSetChanged(); } }; private String[] mphotos={ "http:testingsite.com/naturemain/2.jpg", "http:testingsite.com/naturemain/4.jpg", "http:testingsite.com/naturemain/6.jpg", "http:testingsite.com/naturemain/8.jpg", "http:testingsite.com/naturemain/10.jpg", "http:testingsite.com/naturemain/12.jpg", "http:testingsite.com/naturemain/14.jpg", "http:testingsite.com/naturemain/16.jpg", "http:testingsite.com/naturemain/18.jpg", "http:testingsite.com/naturemain/20.jpg", "http:testingsite.com/naturemain/22.jpg", "http:testingsite.com/naturemain/24.jpg", "http:testingsite.com/naturemain/26.jpg", "http:testingsite.com/naturemain/28.jpg", "http:testingsite.com/naturemain/30.jpg", "http:testingsite.com/naturemain/32.jpg", "http:testingsite.com/naturemain/34.jpg", "http:testingsite.com/naturemain/36.jpg", "http:testingsite.com/naturemain/38.jpg", "http:testingsite.com/naturemain/40.jpg", "http:testingsite.com/naturemain/42.jpg", "http:testingsite.com/naturemain/44.jpg", "http:testingsite.com/naturemain/46.jpg", "http:testingsite.com/naturemain/48.jpg", "http:testingsite.com/naturemain/50.jpg" }; private String[] mStrings={ "http:testingsite.com/naturemain/1.jpg", "http:testingsite.com/naturemain/3.jpg", "http:testingsite.com/naturemain/5.jpg", "http:testingsite.com/naturemain/7.jpg", "http:testingsite.com/naturemain/9.jpg", "http:testingsite.com/naturemain/11.jpg", "http:testingsite.com/naturemain/13.jpg", "http:testingsite.com/naturemain/15.jpg", "http:testingsite.com/naturemain/17.jpg", "http:testingsite.com/naturemain/19.jpg", "http:testingsite.com/naturemain/21.jpg", "http:testingsite.com/naturemain/23.jpg", "http:testingsite.com/naturemain/25.jpg", "http:testingsite.com/naturemain/27.jpg", "http:testingsite.com/naturemain/29.jpg", "http:testingsite.com/naturemain/31.jpg", "http:testingsite.com/naturemain/33.jpg", "http:testingsite.com/naturemain/35.jpg", "http:testingsite.com/naturemain/37.jpg", "http:testingsite.com/naturemain/39.jpg", "http:testingsite.com/naturemain/41.jpg", "http:testingsite.com/naturemain/43.jpg", "http:testingsite.com/naturemain/45.jpg", "http:testingsite.com/naturemain/47.jpg", "http:testingsite.com/naturemain/49.jpg" }; @Override public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuInflater menuinflater = getMenuInflater(); menuinflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.inflate: startActivity(new Intent("com.testing.image.ABOUTUS")); return true; } return false; } } </code></pre> <p>Row XML:</p> <pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" > <ImageView android:id="@+id/image" android:layout_width="150dip" android:layout_height="120dip" android:scaleType="centerCrop" android:src="@drawable/backgroundimage" /> <TextView android:layout_width="20dip" android:layout_height="1dip" /> <TextView android:layout_width="1dip" android:layout_height="150dip" /> <ImageView android:id="@+id/photo" android:layout_width="150dip" android:layout_height="120dip" android:scaleType="centerCrop" android:src="@drawable/stub" /> <TextView android:id="@+id/text" android:layout_width="1dip" android:layout_height="1dip" /> </LinearLayout> </code></pre> <p>Main XML:</p> <pre><code><ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> </code></pre> <p>Sub-Activity:</p> <pre><code>public class NatureTwoOne extends Activity { ImageView image; private class BackgroundTask extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String...url) { //--- download an image --- Bitmap bitmap = DownloadImage(url[0]); return bitmap; } protected void onPostExecute(Bitmap bitmap) { ImageView image = (ImageView) findViewById(R.id.imageView1); bitmaptwo=bitmap; image.setImageBitmap(bitmap); } } private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response= -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection )) throw new IOException("Not an HTTP connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK){ in = httpConn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; } private Bitmap DownloadImage(String URL) { Bitmap bitmap = null; InputStream in = null; try { in = OpenHttpConnection(URL); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e1){ Toast.makeText(this,e1.getLocalizedMessage(), Toast.LENGTH_LONG).show(); e1.printStackTrace(); } return bitmap; } public static Bitmap bitmaptwo; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.wallpaper); new BackgroundTask().execute("http:testingsite.com/natureone/1.jpg"); Button setWallpaper = (Button) findViewById(R.id.button3); setWallpaper.setOnClickListener(new OnClickListener() { public void onClick(View view) { WallpaperManager wManager; Toast noSong = Toast.makeText(NatureTwoOne.this, "Background Set", Toast.LENGTH_SHORT); noSong.show(); try { // bitmap = BitmapFactory.decodeFile(null); wManager = WallpaperManager.getInstance(getApplicationContext()); wManager.setBitmap(bitmaptwo); } catch (IOException e) { e.printStackTrace(); } } }); Button bLeft = (Button) findViewById(R.id.buttonLeft); bLeft.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent mainIntentOne = new Intent(NatureTwoOne.this, NatureTwoFifty.class); NatureOneOne.this.startActivity(mainIntentOne); if(bitmaptwo != null){ bitmaptwo.recycle(); } /* Finish splash activity so user cant go back to it. */ NatureOneOne.this.finish(); /* Apply our splash exit (fade out) and main entry (fade in) animation transitions. */ overridePendingTransition(R.anim.animation_enterl, R.anim.animation_leaver); } }); Button bRight = (Button) findViewById(R.id.buttonRight); bRight.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent("com.testing.image.NATURETWOTWO")); if(bitmaptwo != null){ bitmaptwo.recycle(); } finish(); } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if(bitmaptwo != null){ bitmaptwo.recycle(); } finish(); } return super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuInflater menuinflater = getMenuInflater(); menuinflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.inflate: startActivity(new Intent("com.testing.image.ABOUTUS")); return true; } return false; } } </code></pre> <p>Adapter:</p> <pre><code>public class LazyAdapter extends BaseAdapter { private Activity activity; private String[] data; private String[] dataone; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyAdapter(Activity a, String[] d, String[] mphotos) { activity = a; data=d; dataone = mphotos; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader=new ImageLoader(activity.getApplicationContext()); } public int getCount() { return data.length; } public int getCountOne() { return dataone.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.item, null); TextView text=(TextView)vi.findViewById(R.id.text);; ImageView image=(ImageView)vi.findViewById(R.id.image); ImageView photos=(ImageView)vi.findViewById(R.id.photo); text.setText("item "+position); imageLoader.DisplayImage(data[position], image); imageLoader.DisplayImage(dataone[position], photos); return vi; } } </code></pre> |
37,887,446 | 0 | <p>There is no problem in your code, but the problem in client request, because Content-Type should be like below if you want to upload image,</p> <pre><code>multipart/form-data; boundary="123123" </code></pre> <p>try to remove the Content-Type header and test, i will put one example for server code and client request</p> <p>Server code:</p> <pre><code>@RequestMapping(method = RequestMethod.POST, value = "/users/profile") public ResponseEntity<?> handleFileUpload(@RequestParam("name") String name, @RequestParam(name="file", required=false) MultipartFile file) { log.info(" name : {}", name); if(file!=null) { log.info("image : {}", file.getOriginalFilename()); log.info("image content type : {}", file.getContentType()); } return new ResponseEntity<String>("Uploaded",HttpStatus.OK); } </code></pre> <p>Client Request using Postman</p> <p>with image <a href="https://i.stack.imgur.com/CnHoV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CnHoV.png" alt="enter image description here"></a></p> <p>without image</p> <p><a href="https://i.stack.imgur.com/UVE1t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UVE1t.png" alt="enter image description here"></a></p> <p>Curl example:</p> <p>without image, with Content-Type</p> <pre><code>curl -X POST -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "name=test" "http://localhost:8080/api/users/profile" </code></pre> <p>without image, without Content-Type</p> <pre><code>curl -X POST -F "name=test" "http://localhost:8080/api/users/profile" </code></pre> |
40,250,979 | 0 | <p>The way to resolve this issue is to force the file to use 8-bit encoding. You could run this PowerShell script to change the encoding of all .SQL files in the current directory and its subdirectories.</p> <pre><code>Get-ChildItem -Recurse *.sql | foreach { $FileName = $_.FullName; [System.Io.File]::ReadAllText($FileName) | Out-File -FilePath $FileName -Encoding UTF8; } </code></pre> |
25,684,497 | 0 | Can I execute a stored procedure 'detached' (not keeping DB connection open) on PostgreSQL? <p>I want to execute a long-running stored procedure on PostgreSQL 9.3. Our database server is (for the sake of this question) guaranteed to be running stable, but the machine calling the stored procedure can be shut down at any second (Heroku dynos get cycled every 24h).</p> <p>Is there a way to run the stored procedure 'detached' on PostgreSQL? I do not care about its output. Can I run it asynchronously and then let the database server keep working on it while I close my database connection?</p> <p>We're using Python and the <a href="http://initd.org/psycopg/docs/" rel="nofollow">psycopg2 driver</a>, but I don't care so much about the implementation itself. If the possibility exists, I can figure out how to call it.</p> <p>I found notes on the <a href="http://initd.org/psycopg/docs/advanced.html#async-support" rel="nofollow">asynchronous support</a> and the <a href="http://aiopg.readthedocs.org/en/0.3/index.html" rel="nofollow">aiopg library</a> and I'm wondering if there's something in those I could possibly use.</p> |
38,184,474 | 0 | How to setJpegQuality(int i) Camera2API? <p>Please help me to understand how i can set <code>setJpegQuality(int i)</code> in my Camera2API? </p> <p>I have surfed google and there are not a lot sample how to do it in CameraAPI, but there are any samples how to make it with Camera2API...</p> <p>I have found <a href="https://developer.android.com/reference/android/hardware/Camera.Parameters.html#setJpegQuality(int)" rel="nofollow">this</a> , but <strong>maybe anyone know how to set it for Camera2API?</strong></p> <p>Thanks!</p> |
11,758,085 | 0 | <p>The short answer is that you cannot do it. At least not officially...</p> <p>see <a href="http://stackoverflow.com/questions/5564263/iphone-vpn-connect-app">iPhone VPN connect app</a></p> <p>However, you may be able to point your app to through an existing VPN channel if it already exists. I would recommend creation of instructions for the user on how to create the VPN connection.</p> |
29,531,583 | 0 | <p>You can just do this:</p> <pre><code>echo $memus[0]['name']; </code></pre> <p>Or if you want all of them</p> <pre><code>foreach ($memus as $memu) { echo $memu['name']; } </code></pre> |
16,265,491 | 0 | Infix, prefix or postfix order trough BST to get descending order of printed elements <p>I know that if we print the BST in the infix order i will get ascending order of elements the tree contains. How to get descending order? Using postfix or prefix?</p> |
12,069,487 | 0 | Editing response content on doView() <p>I have a simple <code>JSR 286</code> Portlet that displays a user manual (pure <code>HTML</code> code, not <code>JSP</code>).</p> <p>Actually, my <code>doView</code> method, just contains this : </p> <pre class="lang-java prettyprint-override"><code>public class UserManualPortlet extends GenericPortlet { @Override protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException { PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher( "/html/usermanual.html"); rd.include(request, response); } } </code></pre> <p>This works as expected, however I'm having trouble when including images. I'm aware that the path to images should be something like : </p> <pre class="lang-java prettyprint-override"><code><img src='<%=renderResponse.encodeURL(renderRequest.getContextPath() + "/html/image.jpg")%>'/> </code></pre> <p>However, my HTML file containing the user manual is used elsewhere, so I would like to preserve it as a pure HTML file.</p> <p>Is there a way to dynamically <strong>replace</strong> my classic <code>images urls</code> by something like the example above ? Perhaps using the <code>PrintWriter</code> of the response ?</p> <p>If such thing is not possible, I thing I would need to generate a <code>JSP</code> file during my <code>Maven</code> build.</p> <p>Any solution or ideas are welcome.</p> |
11,443,082 | 0 | Can't Post facebook URL using facebook SDK <p>I have a webapplication that I use to reshare existing post as follow 1)get the post details using <a href="https://graph.facebook.com/UserID_postID?access_token=AAA" rel="nofollow">https://graph.facebook.com/UserID_postID?access_token=AAA</a> (works fine) 2)fill the a data of the new post from the old one and try to resend it but there is some strange behviour if I use oldpost.link = newpost.link it doesnt nothing appear on the wall but if I used oldpost.link="\""newpost.link+"\"" works and the post appear on facebook wall but the link appears corputted as invalid.invalid/</p> <p>function getPost(userID, postID, token) { jQuery.getJSON("https://graph.facebook.com/" + userID + "_" + postID + "?access_token=" + token, function (post) { here is the code any idea please </p> <pre><code> var newPost = {}; newPost.message = "hi"; if (post.link != "" && post.link != null && post.link != "undefined") { newPost.link = "\"" + post.link + "\""; } if (post.name != "" && post.name != null && post.name != "undefined") { newPost.name = "\"" + post.name + "\""; } if (post.picture != "" && post.picture != null && post.picture != "undefined") { newPost.picture = "\"" + post.picture + "\""; } if (post.description != "" && post.description != null && post.description != "undefined") { newPost.description = "\"" + post.description + "\""; } doPost(newPost); }); } function doPost(newPost) { FB.api('/me/feed', 'post', newPost, function (response) { if (!response || response.error) { alert(' Denied Access'); } else { alert('Success'); } }); } </code></pre> |
22,750,035 | 0 | Using ANTLR3 in a C++ program <p>I'm currently working on an application that takes a string (a function of a single variable ' x') as input and outputs the derivative of that function. The latter half of the program is not the problem at the moment, the only thing I am having trouble with is "reading" a function from a string. I am using ANTLRv3 for C to try to achieve this goal, but I can't seem to get it to work. Currently I am missing the "antlr3.h" header file, which I can't seem to find anywhere. My second problem is invoking the generated parser, what would the C(++) code for that be (the ANTLR code is posted below)? How do I get it to work?</p> <p>Thanks in advance,</p> <p>Ties</p> <pre><code>grammar Expression; options { language = C; } @header { #ifndef PI #define PI 3.1415926535897 #endif // PI #ifndef E #define E 2.7182818284590 #endif // E #include "ExpressionTree.h" #include <vector> #include <cstdlib>} parse returns [Functor* func] : e=addExp EOF {func = $e.func;} ; addExp returns [Functor* func] @init {std::vector<Functor*> addList; std::vector<bool> opList;} : e1=multExp {addList.push_back($e1.func);} (o=('+'|'-') e2=multExp {opList.push_back($o.text == '+'); addList.push_back($e2.func);})* { if(addList.size() == 1) { func = addList[0]; } else { Functor* current = addList[0]; for(int i = 0; i<opList.size(); i++) { if(opList[i]) { current = new Plus(current, addList[i+1]); } else { current = new Minus(current, addList[i+1]); } } func = current; }}; multExp returns [Functor* func] @init { std::vector<Functor*> mulList; std::vector<bool> opList;} : e1=powExp {mulList.push_back($e1.func);} (o=('*'|'/') e2=powExp {opList.push_back($o.text == '*'); mulList.push_back($e2.func);})* { if(mulList.size() == 1) { func = addList[0]; } else { Functor* current = mulList[0]; for(int i = 0; i<opList.size(); i++) { if(opList[i]) { current = new Times(current, mulList[i+1]); } else { current = new Divides(current, mulList[i+1]); } } func = current; }}; powExp returns [Functor* func] @init { std::vector<Functor*> expList; } : e1=unarExp {expList.push_back($e1.func);} ('^' e2=unarExp {expList.push_back($e2.func);})? { if(expList.size() == 1) { func = expList[0]; } else { func = new Power(expList[0], expList[1]); }}; unarExp returns [Functor* func] : SQRT '(' e=addExp ')' {func = new Sqrt($e.func);} | SIN '(' e=addExp ')' {func = new Sin($e.func);} | COS '(' e=addExp ')' {func = new Cos($e.func);} | TAN '(' e=addExp ')' {func = new Tan($e.func);} | EXP '(' e=addExp ')' {func = new Exp($e.func);} | LOG '(' e=addExp ')' {func = new Log($e.func);} | ABS '(' e=addExp ')' {func = new Abs($e.func);} | MAX '(' e1=addExp ',' e2=addExp ')' {func = new Max($e1.func,$e2.func);} | MIN '(' e1=addExp ',' e2=addExp ')' {func = new Min($e1.func,$e2.func);} | e=atom {func = $e.func;} ; atom returns [Functor* func] : INT {func = new Constant(atoi($INT.text));} | FLOAT {func = new Constant(atof($FLOAT.text));} | 'pi' {func = new Constant(PI);} | 'e' {func = new Constant(E);} | 'x' {func = new Variable();} | '(' e=addExp ')' {func = $e.func;} ; SQRT: 'Sqrt'; SIN : 'Sin'; COS : 'Cos'; TAN : 'Tan'; EXP : 'Exp'; LOG : 'Log'; ABS : 'Abs'; MAX : 'Max'; MIN : 'Min'; INT : '0'..'9'+; FLOAT : ('0'..'9')+ '.' ('0'..'9')* EXPONENT? | '.' ('0'..'9')+ EXPONENT? | ('0'..'9')+ EXPONENT ; WS : ( ' ' | '\t') {$channel=HIDDEN;}; fragment EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; </code></pre> |
7,477,544 | 0 | <pre><code>SELECT RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(MM, Op_Date)), 2) + '/' + CONVERT(VARCHAR,DATEPART(yyyy,Op_Date)) </code></pre> |
35,136,050 | 0 | How do I apply a function to all elements of a column that have the same value in another column? <p>I have a long dataframe, that consists of the identifier for a group and a corresponding value. See an example below:</p> <pre><code>FamilyMass Family Body.Mass 1 Chrysochloridae 22.04 2 Chrysochloridae 24.05 3 Chrysochloridae 52.34 4 Chrysochloridae 38.30 5 Chrysochloridae 37.16 6 Chrysochloridae 55.76 7 Chrysochloridae 434.04 8 Chrysochloridae 108.35 9 Chrysochloridae 21.99 10 Chrysochloridae 62.60 11 Tenrecidae 152.25 12 Tenrecidae 6.69 </code></pre> <p>I need to calculate the cumsum of all values in the second column for each batch of elements with the same value in the first column. So, in the first case, I would calculate the cumsum for the first 10 values, as they all correspond to Chrysochloridae, and then calculate the cumsum for the following two entries and store them in a different place. </p> <p>I tried breaking the dataframe into smaller lists, each contaning a vector with the respective Body Mass entries using a loop, but so far I haven't succeeded.</p> <p>Is there any way to solve the problem? Forgive me if it's a basic question, I'm very new to R and programming in general.</p> |
37,779,035 | 0 | <p>Try this</p> <pre><code> $criteria = array( "prices" => array( $request['min'] ? $request['min'] : false, $request['max'] ? $request['max'] : false ), "colors" => $request['color'] ? $request['color'] : false, "sizes" => $request['size'] ? $request['size'] : false ); $products = Product::with(['sizes' => function ($query) use ($criteria) { if($criteria['sizes']) { foreach ($criteria['sizes'] as $size) { $query->where('size', '=', $size); } } }])->where(function ($query) use ($criteria) { if($criteria['colors']) { foreach ($criteria['colors'] as $color) { $query->where('color_id', '=', $color); } } if( $criteria['prices'][0] && $criteria['prices'][1] ) { $query->whereBetween('price', $criteria['prices'] ); } })->get(); </code></pre> |
19,966,306 | 0 | <p>Two potential sources of the problem, you shouldn't store your files with spaces in their names and you haven't specified a type for your video.</p> <p>The SRC should contain a valid URL and therefore you should have %20 or + in your PHP string in stead of the spaces.</p> <p>Note: As mentioned by Fisk, your php tags are wrong due to the spacing. You use the PHP echo short-form by replacing </p> <pre><code>< ?php echo $vid; ? > by <?= $vid; ?> </code></pre> |
18,873,778 | 0 | Building a jekyll site from java <p>I have a java (GWT) web app with products, where users can add products and set their description and price etc.</p> <p>I am thinking about the following flow: whenever a product is updated, run a jekyll build and deploy.</p> <p>this way the eventual site with all the products will be completely static (with some extra javascript to handle shoppingcart etc), and thus very fast indeed.</p> <p>Is there a way to call 'jekyll build' from java servlet? I don't have much experience with this... Any suggestions?</p> |
8,946,877 | 0 | grails not using cache <p>I've noticed a slow down on my site and after turning on <code>debug 'org.hibernate.SQL'</code> I see where the troubles are. I've set a domain class to be cached using....</p> <pre><code>class Foo{ ... static mapping ={ cache 'read-only' } String name //<-- simple data type, no associations String description //<-- simple data type, no associations } </code></pre> <p>My hibernate config looks like this...</p> <pre><code>hibernate { cache.use_second_level_cache=true cache.use_query_cache=true cache.provider_class='net.sf.ehcache.hibernate.EhCacheProvider' } </code></pre> <p>my query looks like this (in a web flow)...</p> <pre><code>def wizardFlow = { ... def flow.foos = Foo.list([sort:"name", order:"asc", cache:true]) // def flow.foos = Foo.findAll([cache:true]) <--- same result, no caching } </code></pre> <p>I would think that either the query cache or second level cache would stop the database from being hit but my log is loaded with...</p> <pre><code>select ... from thing thing0_ where thing0_.id=? select ... from thing thing0_ where thing0_.id=? select ... from thing thing0_ where thing0_.id=? select ... from thing thing0_ where thing0_.id=? </code></pre> <p>Can anyone shed some light on what might be happening? Other queries are acting as they should!</p> <p>I'm using Grails 1.3.7</p> <p>Lastly, here is my ehcache.xml...</p> <pre><code><?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" > <diskStore path="java.io.tmpdir"/> <cacheManagerEventListenerFactory class="" properties=""/> <defaultCache maxElementsInMemory="1000000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="true" diskPersistent="false" /> <cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="10000" timeToIdleSeconds="300" /> <cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="10000" timeToIdleSeconds="300" /> </ehcache> </code></pre> |
7,628,581 | 0 | <p>Just naming:</p> <ul> <li><a href="http://projects.gnome.org/ORBit2/" rel="nofollow">orbit2</a> <sup>1</sup>, also pyorbit etc.</li> <li><a href="http://omniorb.sourceforge.net" rel="nofollow">omniORB</a></li> <li><p><a href="http://www.theaceorb.com" rel="nofollow">TAO</a> (<em>has already been mentioned</em>)</p> <p><sup>1</sup> On my Ubuntu box, <code>apt-rdepends -r liborbit2</code> returns 5530 lines...</p></li> </ul> |
22,532,224 | 0 | <p>in advance, you can through this way to build your view:</p> <p><strong>first</strong> create an Template in your view folder</p> <pre><code><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta content="MajidGolshadi" name="author"> <?php echo $html_head; ?> <title></title> </head> <body> <div id="content"> <?php echo $content; ?> </div> <div id="footer"> <?php echo $html_footer; ?> </div> </body> </html> </code></pre> <p><strong>second</strong> create an library to load your view automaticaly</p> <pre><code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Template { private $data; private $js_file; private $css_file; private $CI; public function __construct() { $this->CI =& get_instance(); $this->CI->load->helper('url'); // default CSS and JS that they must be load in any pages $this->addJS( base_url('assets/js/jquery-1.7.1.min.js') ); $this->addCSS( base_url('assets/css/semantic.min.css') ); } public function show( $folder, $page, $data=null, $menu=true ) { if ( ! file_exists('application/views/'.$folder.'/'.$page.'.php' ) ) { show_404(); } else { $this->data['page_var'] = $data; $this->load_JS_and_css(); $this->init_menu(); if ($menu) $this->data['content'] = $this->CI->load->view('template/menu.php', $this->data, true); else $this->data['content'] = ''; $this->data['content'] .= $this->CI->load->view($folder.'/'.$page.'.php', $this->data, true); $this->CI->load->view('template.php', $this->data); } } public function addJS( $name ) { $js = new stdClass(); $js->file = $name; $this->js_file[] = $js; } public function addCSS( $name ) { $css = new stdClass(); $css->file = $name; $this->css_file[] = $css; } private function load_JS_and_css() { $this->data['html_head'] = ''; if ( $this->css_file ) { foreach( $this->css_file as $css ) { $this->data['html_head'] .= "<link rel='stylesheet' type='text/css' href=".$css->file.">". "\n"; } } if ( $this->js_file ) { foreach( $this->js_file as $js ) { $this->data['html_head'] .= "<script type='text/javascript' src=".$js->file."></script>". "\n"; } } } private function init_menu() { // your code to init menus // it's a sample code you can init some other part of your page } } </code></pre> <p><strong>third</strong> load your library in every controller constructor and then use this lib to load you view automatically</p> <p>to load additional js in your view you can use <code>addJS</code> method in this way:</p> <pre><code>$this->template->addJS("your_js_address"); </code></pre> <p>for Css:</p> <pre><code>$this->template->addCSS("your_css_address"); </code></pre> <p>and to show your page content call your view file with <code>show</code> method</p> <pre><code>$this->template->show("your_view_folder", "view_file_name", $data); </code></pre> <p>i hope this codes help you</p> |
33,023,158 | 0 | <blockquote> <p>You just need to play with <code>$success</code> like this:</p> </blockquote> <pre><code><?php // Define some constants define("RECIPIENT_NAME", "YOURNAME"); define("RECIPIENT_EMAIL", "[email protected]"); define("EMAIL_SUBJECT", "Visitor Message"); // Read the form values $success = false; $senderEmail = isset($_POST['senderEmail']) ? preg_replace("/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail']) : ""; $message = isset($_POST['message']) ? preg_replace("/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message']) : ""; // If all values exist, send the email if ($senderEmail && $message) { $formSubmitted = true; $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">"; $headers = "From: " . $senderEmail . " <" . $senderEmail . ">"; $success = mail($recipient, EMAIL_SUBJECT, $message, $headers); } // Return an appropriate response to the browser if (isset($_GET["ajax"])) { echo $success ? "success" : "error"; } ?> <!--Your contact.php page--> <form class="o-form" id="contactForm" action="php/contact.php" method="post"> <input type="email" name="senderEmail" id="senderEmail" required="required" placeholder="email"> <textarea name="message" id="message" required="required placeholder=" message"></textarea> <input type="submit" value="send" class="send-button"> </form> </div> </div> </div> </div> <div class="copyright"> <span> anthonygallina </span> </div> </footer> <div class="th-popup"> <div class="massage-th"> <h1>Thank You!</h1> <p>We apreciate your visit to our home page. We will contact you soon!</p> </div> </div> <script src="js/jquery-1.11.1.min.js"></script> <script src="js/all.js"></script> <script src="js/jquery.mixitup.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/idangerous.swiper.min.js"></script> <script> <?php if($formSubmitted) { if ($success) { $msg="<p>Thanks for sending your message! We'll get back to you soon.</p>"; } else { $msg="<p>There was a problem sending your message. Please try again.</p>"; } //Open your confirmation or error model here using $msg } ?> </script> </body> </html> </code></pre> |
28,577,597 | 0 | <p>You can only transpose a 2D array. You can use <code>numpy.matrix</code> to create a 2D array. This is three years late, but I am just adding to the possible set of solutions:</p> <pre><code>import numpy as np m = np.matrix([2, 3]) m.T </code></pre> |
38,917,572 | 0 | No find member in std::vector <p>Is there any particular reason why <code>std::vector</code> does not have a member function <code>find</code>? Instead you have to call <code>std::find</code> (and <code>#include <algorithm></code>).</p> <p>The reason why I ask is that I think it would be a good thing to be able to change container class in some piece of implementation without having to change the code wherever the container is accessed. Say I replace an <code>std::vector</code> where the implementation uses <code>std::find</code> with an <code>std::map</code>. Then I also have to replace the call of <code>std::find</code> with a call to the member <code>find</code>, unless I want to keep the linear complexity of <code>std::find</code>. Why not just have a member <code>find</code> for all container classes, which finds an element with whatever algorithm is best suited for each container?</p> |
32,969,099 | 0 | ActionView::Template::Error: undefined method `children' for nil:NilClas <p>Hello i have an Rspec Test im tring to do for an User controller index action. For user authentication i coded it myself and not using any gems. </p> <p>I get this error when truing to run the test. I looked up all solutions and nothing worked. </p> <pre><code> 2) UsersController GET #index redirects visitor Failure/Error: user_logged_in ActionView::Template::Error: undefined method `children' for nil:NilClass </code></pre> <p>Here is the Test.</p> <pre><code>require "rails_helper" RSpec.describe UsersController, type: :controller do let!(:user) { create(:user) } let!(:users) do users = [] 3.times { users << create(:user) } users end describe "GET #index" do before do user_logged_in create(users) end it "user renders template and shows users" do get :index expect(response).to render_template(:index) expect(response).to have_http_status(:success) expect(assigns(:users)).to eq(users) end it "redirects visitor" do get :index it { expect(response).to redirect_to(root_path) } end end end </code></pre> <p>Here is rails_helper</p> <pre><code>ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) abort("The Rails environment is running in production mode!") if Rails.env.production? require 'spec_helper' require 'rspec/rails' require "shoulda/matchers" ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| config.fixture_path = "#{::Rails.root}/spec/fixtures" config.include FactoryGirl::Syntax::Methods config.use_transactional_fixtures = true config.infer_spec_type_from_file_location! config.include Capybara::DSL end def admin_logged_in visit login_path fill_in 'Email', with: admin.email fill_in 'Password', with: admin.password click_button 'Log In' end def user_logged_in visit login_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password click_button 'Log In' end </code></pre> |
29,973,869 | 0 | SSH freely inside AWS VPC <p>How do I configure my EC2 machines inside a VPC to be able to ssh without password or key between them?</p> <p>What i'm trying to do is access one machine (which has a public IP) and from this machine access all others freely.</p> <p>Is it even possible?</p> |
21,042,127 | 0 | Spock Integration Test interaction not counted <p>I want to write an integration test for my Grails User Class.</p> <p>I have a <code>afterUpdate()</code>method which calls the afterUpdate method in the userService which calls another service. </p> <p>Now I want to verify that the call to the other service is done correctly. If I debug the code, the method is called correctly. but my test always fails and says the method isn't called:</p> <pre><code> def "After Update for User"() { given: RedisService.metaClass.'static'.del = {String key -> true} User user = new User() user.save(flush: true) when: user.afterUpdate() then: 1 * redisService.del(!null) } </code></pre> <p>I have tried different things like</p> <pre><code>then: 1 * user.userService.afterUpdate(!null) 1 * userService.redisService.del(!null) 1 * redisService.del(!null) </code></pre> <p>but they are all failing.</p> <p>I allways get:</p> <pre><code>| Failure: After Update for User(com.boxcryptor.server.RedisCacheIntegrationSpec) | Too few invocations for: 1 * user.userService.afterUpdate(!null) (0 invocations) Unmatched invocations (ordered by similarity): None Too few invocations for: 1 * redisService.del(!null) (0 invocations) Unmatched invocations (ordered by similarity): None </code></pre> <p><strong>Update:</strong></p> <p>the after Update Method is really simple:</p> <pre><code>def afterUpdate(User user) { deleteETagCache(user) } def deleteETagCache(User user) { redisService.del(user.id.toString()) } </code></pre> |
27,847,909 | 0 | <p>add style before your <code><script></code> tag like this and fix the height of your autocomplete, it will show scroll if results don't fit in the specified height.</p> <pre><code><style> .ui-autocomplete { max-height: 100px; // set whatever you want overflow-y: auto; overflow-x: hidden; //this will prevent horizontal scrollbar } * html .ui-autocomplete { height: 100px; } </style> </code></pre> |
24,447,848 | 0 | Prefix 0 in Razor Textbox value <p>Here is my Razor text box</p> <pre><code>@Html.TextBoxFor(model => model.ShortBufferHour,new { @maxlength = "2",Style="text-align:center;"}) </code></pre> <p>It shows the <code>Hours</code> as <code>7</code>. How to prefix a <code>0</code> in case of single digit hour. So that the textbox content be <code>07</code></p> |
1,392,852 | 0 | How do I send a PDF in a MemoryStream to the printer in .Net? <p>I have a PDF created in memory using iTextSharp and contained in a MemoryStream. I now need to translate that MemoryStream PDF into something the printer understands.</p> <p>I've used Report Server in the past to render the pages to the printer format but I cant use it for this project.</p> <p>Is there a native .Net way of doing this? For example, GhostScript would be OK if it was a .Net assembly but I don't want to bundle any non .Net stuff along with my installer.</p> <p>The PrintDocument class in .Net is great for sending content to the printer but I still need to translate it from a PDF stream into GDI at the page level.</p> <p>Any good hints?</p> <p>Thanks in advance</p> <p>Ryan</p> |
7,542,869 | 0 | <p>Solved thanks to David Heffernan.</p> <p>On my main window i added a static window field which references my main window.</p> <pre><code>public static Window main; Public MainWindow() { main = this; } </code></pre> <p>On the windows I need to hide from task manager and ALT+TAB, I made my main window its owner:</p> <pre><code>public HiddenWindow() { this.Owner = MainWindow.main; } </code></pre> <p>Its really simple, it hides the window from the 'tasks' tab on task manager and also stop people from ALT+TABing into your program.</p> |
17,702,642 | 0 | <p>Make sure the path to database is right, if you can see the table in you database, then the path is wrong, it could be looking to some other database. just an idea</p> |
31,186,636 | 0 | <p>After digging on cxf forums, I found the answer.</p> <pre><code>Map<String, String> nsMap = new HashMap<>(); nsMap.put("prefix1", "url1"); nsMap.put("prefix2", "url2"); nsMap.put("prefix3", "url3"); nsMap.put("prefix4", "url4"); nsMap.put("prefix5", "http://www.w3.org/2001/04/xmlenc#"); Client client = ClientProxy.getClient(port); client.getRequestContext().put("soap.env.ns.map", nsMap); </code></pre> <p><strong>I would be appreciated if anyone know on how to do the same for <code><soap:Header></code></strong></p> |
303,001 | 0 | <p>I've also had great success using Aptana's Jaxer + jQuery to parse pages. It's not as fast or 'script-like' in nature, but jQuery selectors + real JavaScript/DOM is a lifesaver on more complicated (or malformed) pages.</p> |
27,075,452 | 0 | <p>Simply put, put an ampersand and then amp; as shown below.</p> <blockquote> <p>&amp;amp;</p> </blockquote> |
28,403,532 | 0 | <p>Your best bet is to provide a method to clean up the library. The end user will have to call it (presumably based on handling application lifecycle in the container). You could also provide a <code>Listener</code> for those cases when it is used in a compatible servlet container (e.g., Tomcat), but your end user will still have to be aware and put the descriptor in the web.xml.</p> <p>The only other alternative is that your end user is going to have to create a Listener that manages to get the thread to die. I have had to do this on several occasions and it is not pretty. It usually involves using reflection to get ahold of the thread and killing it. Of course, the ThreadDeath exception is handled by some libraries and the threads refuse to die. This then requires more significant use of reflection to clean up the mess.</p> <p>Your end users are much better off if you give them an easy way to clean up the library. It sucks that they have to know about your implementation details, but they already do because you are keeping the app from unloading.</p> |
11,102,103 | 0 | How do I get KnowledgeArticleViewStat data from a Visualforce page via SQL queries? <p>I am trying to display information about Knowledge Articles on my page. One of the things I want to display is the most viewed article stat.</p> <p>I have a Visualforce Apex component that looks like this:</p> <pre><code><apex:component controller="Component_Query" access="global"> <apex:attribute name="QueryString" type="String" required="true" access="global" assignTo="{!queryString}" description="A valid SOQL query in string form." /> <apex:variable value="{!results}" var="results"/> <apex:componentBody /> </apex:component> </code></pre> <p>I have a Visualforce page that looks like this:</p> <pre><code><apex:page > <table id="articles"> <knowledge:articleList articleVar="article" sortBy="mostViewed" pageSize="5"> <tr> <td>{!article.articlenumber}</td> <td><a target="_parent" href="{!URLFOR($Action.KnowledgeArticle.View, article.id)}">{!article.title}</a></td> <td>{!article.articletypelabel}</td> <td>{!article.lastpublisheddate}</td> <td> <c:Query_component queryString="SELECT NormalizedScore FROM KnowledgeArticleViewStat WHERE ParentId = '{!article.id}'"> <apex:repeat value="{!results}" var="result"> </apex:repeat> </c:Query_component> </td> </tr> </knowledge:articleList> </table> </apex:page> </code></pre> <p>I put the Visualforce Page into a tab. When I view the page, all the information about the knowledge articles show up except for the information about the most viewed stat. How do I see this stat?</p> |
27,961,400 | 0 | three.js raycaster with dynamic canvas position <p>i currently have a three.js scene in a twitter bootstrap environment, so the renderer.domelement can resize and change its position dependent on screen resolution, browser window size and so on.</p> <p>Now i have problems using the three.js raycaster to intersect objects in this scene. When the page loads and the scene is shown on the screen the raycaster works fine, but when i scroll the browser window and/or resize it so that the scene is at a different position in the browser window, the intersection of objects doesn't work anymore.</p> <p>i have no idea how to fix this issue...does someone have an idea how i can fix this?</p> <p>This is how my Raycaser aktually looks like:</p> <pre><code>var container = document.getElementById( 'view' ); ///Raycaster/// var projector = new THREE.Projector(); function onDocumentMouseDown(event) { var mouseX = ( ( event.clientX - container.offsetLeft ) / container.clientWidth ) * 2 - 1; var mouseY = - ( ( event.clientY - container.offsetTop ) / container.clientHeight ) * 2 + 1; var vector = new THREE.Vector3(mouseX, mouseY, 0.5); projector.unprojectVector(vector, camera); var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); var intersects = raycaster.intersectObjects(objects); if (intersects.length > 0) { // do something var origin = raycaster.ray.origin.clone(); console.log(origin); } } } </code></pre> |
40,215,971 | 0 | <p>There is no reason to choose between <code>putIfAbsent</code> and <code>computeIfPresent</code>. Most notably, <code>computeIfPresent</code> in entirely inappropriate as it, as its name suggests, only computes a new value, when there is already an old one, and <code>(k,v)->v</code> even makes this computation a no-op.</p> <p>There are several options</p> <ol> <li><p><code>containsKey</code>, <code>put</code> and <code>get</code>. This is the most popular pre-Java 8 one, though its the most inefficient of this list, as it incorporates up to three hash lookups for the same key</p> <pre><code>String key=str.substring(i, j); if(!map.containsKey(key)) map.put(key, new HashSet<>()); map.get(key).add(str); </code></pre></li> <li><p><code>get</code> and <code>put</code>. Better than the first one, though it still may incorporate two lookups. For ordinary <code>Map</code>s, this was the best choice before Java 8:</p> <pre><code>String key=str.substring(i, j); Set<String> set=map.get(key); if(set==null) map.put(key, set=new HashSet<>()); set.add(str); </code></pre></li> <li><p><code>putIfAbsent</code>. Before Java 8, this option was only available to <code>ConcurrentMap</code>s.</p> <pre><code>String key=str.substring(i, j); Set<String> set=new HashSet<>(), old=map.putIfAbsent(key, set); (old!=null? old: set).add(str); </code></pre> <p>This only bears one hash lookup, but needs the unconditional creation of a new <code>HashSet</code>, even if we don’t need it. Here, it might be worth to perform a <code>get</code> first to defer the creation, especially when using a <code>ConcurrentMap</code>, as the <code>get</code> can be performed lock-free and may make the subsequent more expensive <code>putIfAbsent</code> unnecessary.</p> <p>On the other hand, it must be emphasized, that this construct is not thread-safe, as the manipulation of the value <code>Set</code> is not guarded by anything.</p></li> <li><p><code>computeIfAbsent</code>. This Java 8 method allows the most concise and most efficient operation:</p> <pre><code>map.computeIfAbsent(str.substring(i, j), k -> new HashSet<>()).add(str); </code></pre> <p>This will only evaluate the function, if there is no old value, and unlike <code>putIfAbsent</code>, this method returns the new value, if there was no old value, in other words, it returns the right <code>Set</code> in either case, so we can directly <code>add</code> to it. Still, the <code>add</code> operation is performed outside the <code>Map</code> operation, so there’s no thread safety, even if the <code>Map</code> is thread safe. But for ordinary <code>Map</code>s, i.e. if thread safety is not a concern, this is the most efficient variant.</p></li> <li><p><code>compute</code>. This Java 8 method will always evaluate the function and can be used in two ways. The first one</p> <pre><code>map.compute(str.substring(i, j), (k,v) -> v==null? new HashSet<>(): v).add(str); </code></pre> <p>is just a more verbose variant of <code>computeIfAbsent</code>. The second</p> <pre><code>map.compute(str.substring(i, j), (k,v) -> { if(v==null) v=new HashSet<>(); v.add(str); return v; }); </code></pre> <p>will perform the <code>Set</code> update under the <code>Map</code>’s thread safety policy, so in case of <code>ConcurrentHashMap</code>, this will be a thread safe update, so using <code>compute</code> instead of <code>computeIfAbsent</code> has a valid use case when thread safety is a concern.</p></li> </ol> |
9,802,372 | 0 | stackoverflowerror when resume an activity at the second time <p>i am designing an app, it has <code>Main Activity</code> with <code>tabhost</code>. my point is that when i click on a <code>tabwidget</code> in tabhost bar, it call to <code>Activity A</code>, in <code>Activity A</code> I have a list of menu, when i click on 1 button menu it call to another activity <code>Activity B</code> (i have home button on this activity). my problem is that when i click on button for the first time and click back to <code>Activity A</code>, it run normally, but on the second time i click on it and go back, it got <code>stackoverflowerror</code>. I use this code for handle <code>go back</code></p> <p><code>View view = getLocalActivityManager() .startActivity( "Add Ring", new Intent(getApplicationContext(), ProfileView.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView(); setContentView(view);</code></p> <p>my error log</p> <pre><code>03-21 16:02:40.343: E/AndroidRuntime(2118): FATAL EXCEPTION: main 03-21 16:02:40.343: E/AndroidRuntime(2118): java.lang.StackOverflowError 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6986) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.ScrollView.draw(ScrollView.java:1409) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1862) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewRoot.draw(ViewRoot.java:1522) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewRoot.performTraversals(ViewRoot.java:1258) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859) </code></pre> <p>any solutions is appreciate!</p> |
33,299,274 | 0 | <p>This line:</p> <pre><code>temp = (cell*)realloc(temp, sizeof(cell)); </code></pre> <p>invokes <strong>undefined behaviour</strong> since <code>temp</code> is not initialized. You should initialize it with, e.g., <code>cell *temp = NULL;</code> (understand that <code>realloc</code> can either take a <code>NULL</code> pointer in which case it is equivalent to <code>malloc</code>, or a previously <code>malloced/calloced/realloced</code> pointer).</p> <p>And <strong>don't cast the return from malloc</strong>. This is C, not C++. Search this site for why casting the <code>malloc</code> return value is frowned upon in C.</p> |
25,733,564 | 0 | How can I search for documents that contain three times a special word? <p>Solr should return the documents, that contain a given word minimum three times. What is the query?</p> |
36,773,827 | 0 | Titan Warn: Query requires iterating over all vertices [(name <> null)] <p>I have used below code</p> <pre><code>mgmt = g.getManagementSystem() PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).make(); mgmt.buildIndex("name",Vertex.class).addKey(name).unique().buildCompositeIndex(); </code></pre> <p>while retrieving data from graph i am getting this warning,</p> <pre><code>TransactionalGraph tx = g.newTransaction(); Iterator vertex=tx.query().has("name").vertices.iterator(); </code></pre> <p>Entire graph is traversed to fetch the vertices instead of indexed vertices. Please suggest changes.</p> |
36,785,089 | 0 | Image galleries with <img> tag? <p>I am building a website, and I need to 'implement' a gallery on a group of photos. Since I'm using Spring MVC, my images are with 'img src..' tag and regular js and jquery addons don't work. Is there any plugin/library that can help me do this? If not, suggestions for making my way around it are also welcome. Here is the html, if it can somehow help.</p> <pre><code><div id="img-slider"> <img class="slider-img" src="/LBProperties/img/bisc.jpg"/> <img class="slider-img" src="/LBProperties/img/bisc1.jpg"/> </div> </code></pre> <p>Thank you !</p> |
20,972,745 | 0 | How to track time spent on site <p>In my rails application, I want to track the total time spent on site by individual user. I did research on it but can not get perfect solution.<br> How is it possible.</p> |
40,611,758 | 0 | Error: Type 'GearViewController' does not conform to protocol 'UIPickerViewDataSource' <p>Error:</p> <blockquote> <p>Type 'GearViewController' does not conform to protocol 'UIPickerViewDataSource'</p> </blockquote> <p>Based on <a href="https://developer.apple.com/reference/uikit/uipickerviewdatasource" rel="nofollow noreferrer">apple documentation</a> there are only 2 required methods for a UIPickerViewDataSource. Both are included in the code below. I think the syntax is correct. (but probably not)</p> <p>Class/control declaration, and init. (lots of other code removed for clarity. Full code available if needed, i'll edit. Just trying to stay brief.)</p> <pre><code>class GearViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate{ @IBOutlet weak var pickerGearCategory: UIPickerView! override func viewDidLoad() { super.viewDidLoad() pickerGearCategory.dataSource = self pickerGearCategory.delegate = self } </code></pre> <p>Delegate and datasources</p> <pre><code> let gearCategoryPickerData = CategoryRepository.allCategories() //MARK: CategoryPicker- Delegates and data sources //MARK: CategoryPicker - Data Sources //Required func numberOfComponents(in pickerGearCategory: UIPickerView) -> Int { return 1 } //Required func pickerGearCategory(pickerGearCategory: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return gearCategoryPickerData.count } func pickerGearCategory(pickerGearCategory: UIPickerView,titleForRow row: Int, forComponent component: Int) -> String? { return gearCategoryPickerData[row].name } </code></pre> |
6,142,041 | 0 | <p>Note: For url-safe version of Base64 consider using modifyed set of characters for Base64 ( <a href="http://en.wikipedia.org/wiki/Base64#URL_applications" rel="nofollow">http://en.wikipedia.org/wiki/Base64#URL_applications</a>) instead of custom Base62.</p> <p>I believe you can append 0 to the array first (will make higest byte always not to contain 1 in the highest bit) and then convert to BigInteger if you really need positive BigInteger.</p> |
187,548 | 0 | <p>From the comments to my answer I guess it is not possible to have different credentials for service authentication and http proxy.</p> <p>that suck! :(</p> |
38,318,389 | 0 | <p>I figured out a solution.</p> <p>(1) Export your Voxel Object from MagicVoxel as a .OBJ file.</p> <p>(2) This will create 3 files. Keep the .PNG and .OBJ files. </p> <p>(3) Download a program called blender here: <a href="https://www.blender.org/" rel="nofollow noreferrer">https://www.blender.org/</a></p> <p>(4) Open Blender</p> <p>(5) Go to [File] -> [Import] -> [Wavefront .OBJ] </p> <p>(6) Navigate to your .OBJ file</p> <p>(7) This will open up the .OBJ. You can rotate your object to fix any rotation problems</p> <p>(8) Go to [File] -> [Export] -> [Collada .DAE]</p> <p>(9) Save the new file and drag it into your XCode [SceneKit] Project!</p> <p>(10) Drag in the .PNG file from Step 2 into your project too</p> <p>(11) Select your .DAE file and open the right menu shown below<a href="https://i.stack.imgur.com/GdnMh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GdnMh.png" alt="s"></a></p> <p>(12) Open this <a href="https://i.stack.imgur.com/zaO60.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zaO60.png" alt="spherish thingy"></a></p> <p>(13) Drag and drop the .PNG file from your project into the dropdown menu here. <a href="https://i.stack.imgur.com/uz6Ng.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uz6Ng.png" alt="enter image description here"></a></p> <p>(14) Finished! Hope this helped!</p> |
37,335,733 | 0 | <p>I'm not sure AJAX can upload files, but you can do everything you're talking about with just PHP and HTML, but you'll need to spend some time learning PHP. I would find one of the many online PHP tutorials to start. </p> <p>As far as what you want to do, here is what you need to learn:</p> <ol> <li><p>(HTML/PHP) How to upload a file</p></li> <li><p>(PHP) How to create a directory</p></li> </ol> <p>That's it, assuming you know enough HTML to create and use forms.</p> |
10,866,319 | 0 | <p><code>String *</code> means a pointer to a <code>String</code>, if you want to do anything with the <code>String</code> itself you have to dereference it with <code>*moj</code>. What you can do instead is this:</p> <pre><code>String moj = String("Alice has a cat"); // note lack of * and new cout << moj[2]; </code></pre> <p>Also note that anything you allocate with <code>new</code> needs to be deleted after:</p> <pre><code>String *x = new String("foo"); // code delete x; </code></pre> |
27,820,436 | 0 | <p>Do not mix sub-query and join logic. Use only one of them. I prefer sub-select.</p> <pre><code>SELECT tblForumSubGroups_1.id, tblForumSubGroups_1.GroupID, tblForumSubGroups_1.SubGroupTitle, tblForumSubGroups_1.SubGroupDesc, (SELECT COUNT(*) FROM dbo.tblForumPosts WHERE dbo.tblForumSubGroups.id = dbo.tblForumPosts.SubGroupID) AS Expr1 FROM dbo.tblForumSubGroups AS tblForumSubGroups_1 </code></pre> |
4,882,030 | 0 | <blockquote> <p>What's the big deal about being able to support a new characterset.</p> </blockquote> <p>Unicode is not just "a new characterset". It's the character set that removes the need to think about character sets.</p> <p>How would you rather write a string containing the Euro sign?</p> <ul> <li><code>"\x80"</code>, <code>"\x88"</code>, <code>"\x9c"</code>, <code>"\x9f"</code>, <code>"\xa2\xe3"</code>, <code>"\xa2\xe6"</code>, <code>"\xa3\xe1"</code>, <code>"\xa4"</code>, <code>"\xa9\xa1"</code>, <code>"\xd9\xe6"</code>, <code>"\xdb"</code>, or <code>"\xff"</code> depending upon the encoding.</li> <li><code>"\u20AC"</code>, in every locale, on every OS.</li> </ul> |
8,344,520 | 0 | <p>The post-fix notation is how you do the math in, say, a HP calculator.</p> <p>Keep a stack, whenever you get a number add it to the top. Whenever you get an operator consume inputs from the top and then add the result to the top</p> <pre><code>token stack *empty* 3 3 //push numbers... 4 3 4 2 3 4 2 * 3 8 //remove 4 and 2, add 4*2=8 1 3 8 1 5 3 8 1 5 - 3 8 -4 2 3 8 -4 2 3 3 8 -4 2 3 ^ 3 8 -4 8 ... ... </code></pre> |
29,248,553 | 0 | <p>It sounds like you were trying to used nested loops, but you in fact had one loop at the beginning which closed out and then you loop through the rest. You need to move your closing curly brace marked below:</p> <pre><code>for($i=0; $i<count($_FILES['upload']['name']); $i++) { $filut = basename($_FILES['upload']['name'][$i]); } <<<<<<<<<=========== This curly brace closes the "for loop" if(isset($_POST['subi'])) { $data1 = $_POST['answers']; foreach($data1) as $postValues) { $sql4 = 'INSERT INTO db_image (text, image) VALUES("'.$postValues.'","'.$filut.'")'; $my->query($sql4); } } ??? <<<<<======== For a nested loop you should close it here </code></pre> <p>or perhaps you were trying to assign <code>$filut</code> as an array in which case the starting <code>for...</code> loop needs to look like this:</p> <pre><code>for($i=0; $i<count($_FILES['upload']['name']); $i++) { $filut[] = basename($_FILES['upload']['name'][$i]); } </code></pre> <p>(Note the addition of <code>[]</code> after <code>$filut</code>.)</p> <p>However, if this is what you were intending (to make $filut into an array) then you need to do something different down below in order to access just one element of the array. This is where a nested <code>foreach</code> would solve the problem - maybe this is how you intended to finish it off:</p> <pre><code>if(isset($_POST['subi'])) { $data1 = $_POST['answers']; foreach($data1 as $postValues) { foreach ($filut as $f) { $sql4 = 'INSERT INTO db_image (text, image) VALUES("'.$postValues.'","'.$f.'")'; $my->query($sql4); } } } </code></pre> <p>This will insert a row for every value in $filut for every value in $_POST['answers']. Is that what you wanted? Or are $filut and $_POST['answers'] in parallel and you want a 1-1 correlation on the insert?</p> <p>Finally I'm going to suggest that you use prepare and bind since you are getting your data from the user. This example copied/modified from <a href="http://php.net/manual/en/mysqli-stmt.execute.php" rel="nofollow">here</a>:</p> <pre><code><?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Prepare an insert statement */ $query = "INSERT INTO db_image (text, image) VALUES (?,?)"; $stmt = $my->prepare($query); #### NOTE THE USE OF YOUR VARIABLES HERE IN THE BIND - the "ss" means they are strings $stmt->bind_param("ss", $postValues, $f); #### HERE IS WHERE YOUR CODE IS GETTING INSERTED foreach($data1 as $postValues) { foreach ($filut as $f) { /* Execute the statement */ $stmt->execute(); } } /* close statement */ $stmt->close(); /* close connection */ $my->close(); ?> </code></pre> <p>I can't guarantee that I got all the variables changed to match your code, but hopefully it's close enough to give you an idea. This solution (1) protects you from SQL Injection (which is a serious flaw in your code otherwise) and (2) will be much faster by means of the prepare/execute cycle.</p> <p><em>Do note the careful indentation in my examples where everything lines up perfectly with 3 or more spaces per indent - I can't tell you how many times I have seen sloppy (or too little) indentation make people miss problems which would be otherwise obvious.</em></p> |
31,245,436 | 0 | <p>The '&' characters needs to be encoded in XML as '<code>&amp;</code>'.</p> |
38,696,106 | 0 | <p>There is a typo in the <a href="https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/api/org/springframework/boot/context/embedded/ErrorPage.html" rel="nofollow">docs</a>, they actually meant "in favor of the superclass, <a href="https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/api/org/springframework/boot/web/servlet/ErrorPage.html" rel="nofollow">org.springframework.boot.web.<strong>servlet</strong>.ErrorPage</a>", which is located in the same artifact, <code>org.springframework.boot:spring-boot</code>.</p> |
23,364,919 | 0 | Connect different points with line in matlab <p>I have matrix of 2 column (x and y) and 100 rows, and each row make one point like (x1,y1). </p> <p>I need to draw a line consecutively between them, like point (x1,y1) to (x2,y2) and (x2,y2) to (x3,y3) and so on till (x100,y100).</p> <p>I have written this code and it's working properly. The problem is, it takes too long as I have to do this for 55000 matrix.</p> <pre><code> figure; for j=1:length(data); % data = 55000 different matrices which should draw in the same figure for i=1:length(data(j).x); x= (data(j).x(i)); y= (data(j).y(i)); if i == length(data(j).x); break; end x1= (data(j).x(i+1)); y1= (data(j).y(i+1)); line([x,x1],[y,y1]); end end </code></pre> <p>Is there any more efficient and quicker way to do that?</p> |
23,074,589 | 0 | Launch Company Specific apps on iTunes App Store <p>We have an app to launch on App Store. This App is for a company users(free to download) not for publicly use. Our client has purchased the iOS developer program instead of Enterprise account. So is there any way to launch the App on AppStore using developer program. (like Custom B2B). </p> <p>Please suggest your ideas. So I can proceed to right way.</p> <p>Thanks in Advance.</p> |
35,780,494 | 0 | <pre><code>any(x in message for x in myArray) </code></pre> <p>Evaluates to <code>True</code> if <strong><em>at least one</em></strong> string in <code>myArray</code> is found in <code>message</code>.</p> <pre><code>sum(x in message for x in myArray) == 1 </code></pre> <p>Evaluates to <code>True</code> if <strong><em>exactly one</em></strong> string in <code>myArray</code> is found in <code>message</code>.</p> |
20,129,501 | 0 | JQuery Sortable Preview <p>I need help with Sortable JQuery UI. My requirement is whenever I move the 1st div (portlet 1) with 5th div (portlet 5) 5th and 1st should get swapped and before releasing the mouse the preview should be the same (portlet 5 should be in the first place). Please help me. Please find the fiddle: <a href="http://jsfiddle.net/R_S/3TqTU/2/" rel="nofollow">http://jsfiddle.net/R_S/3TqTU/2/</a></p> <pre><code><div class="dropme"> <div class="rpt 1 row1"><span class="heading">Portlet 1</span></div> <div class="rpt 2 row1"><span class="heading">Portlet 2</span></div> <div class="rpt 3 row1"><span class="heading">Portlet 3</span></div> <div class="rpt 4 row2"><span class="heading">Portlet 4</span></div> <div class="rpt 5 row2"><span class="heading">Portlet 5</span></div> <div class="rpt 6 row2"><span class="heading">Portlet 6</span></div> <div class="rpt 7 row3"><span class="heading">Portlet 7</span></div> <div class="rpt 8 row3"><span class="heading">Portlet 8</span></div> <div class="rpt 9 row3"><span class="heading">Portlet 9</span></div> </div> $('.rpt').draggable({ cursor: 'pointer', connectWith: '.rpt', connectToSortable:'.dropme' helper: 'clone' }); $('.dropme').sortable({ connectWith: '.dropme', cursor: 'pointer' }); </code></pre> |
5,800,357 | 0 | <p>Adjust <a href="http://doc.trolltech.com/4.7/qwidget.html#minimumHeight-prop" rel="nofollow">QToolBar::setMinimumHeight()</a> or <a href="http://doc.trolltech.com/4.7/qwidget.html#minimumSize-prop" rel="nofollow">QToolBar::setMinimumSize()</a> to your needs.</p> <p>And don't forget to use appropriate icon sizes then.</p> |
3,764 | 0 | <p>Second the recommendation on file paths. I've worked on a couple of projects that needed to manage large-ish asset collections, and any attempts to store things directly in the DB resulted in pain and frustration long-term.</p> <p>The only real "pro" I can think of regarding storing them in the DB is the potential for easy of individual image assets. If there are no file paths to use, and all images are streamed straight out of the DB, there's no danger of a user finding files they shouldn't have access to.</p> <p>That seems like it would be better solved with an intermediary script pulling data from a web-inaccessible file store, though. So the DB storage isn't REALLY necessary.</p> |
14,624,832 | 0 | <p>The question is really, whether you need the CSR format immediately after the insertion, or you can rather have more insertions first in a more insertion friendly format and convert then to CSR.</p> <p>You may have a look at <a href="http://www-users.cs.umn.edu/~saad/software/SPARSKIT/" rel="nofollow">sparskit</a> and its linked list storage format, or you may create yourself some linked list for the new elements, and once you finished insertion, you could build up a new CSR formatted matrix, sparing a lot of reshuffling the data.</p> |
33,147,774 | 0 | <p>You have to enable early bound entities by calling</p> <pre><code>_serviceProxy.EnableProxyTypes(); </code></pre> <p>on your OrganizationServiceProxy instance.</p> <pre><code>var cred = new ClientCredentials(); cred.UserName.UserName = "your username"; cred.UserName.Password = "your password"; using (var _serviceProxy = new OrganizationServiceProxy(new Uri("https://[your organization service url here]"), null, cred, null)) { _serviceProxy.EnableProxyTypes(); // Will throw error on save changes if not here var context = new CrmServiceContext(_serviceProxy); context.AddObject(new Opportunity() { Name = "My opportunity" }); context.SaveChanges(); } </code></pre> |
11,045,515 | 0 | How to Implement shared preference concept in tabhost on android eclipse <p>I am self- learner to android,</p> <p>Assume an android program is going to display some result on a textview.can any one tell me how to show that answer on first tab of the tab host's on the next screen.How to achieve this?</p> <p>As per my knowledge i googled and found "Shared preference" concept will be helpful to this problem. Was i right?</p> <p>And i found some samples but they are not making me clear,can any one give me some examples with screen images.</p> <p>Thanks for your precious time!.</p> |
10,885,092 | 0 | <p>It looks like you're using a listbox in your template, but lists are meant to go straight down. You can do things inside the listbox items that make them look a certain way, but the list box will always create a straight up and down list of items.</p> <p>If you want a grid pattern, use the grid control and the Grid.RowDefinitions and Grid.ColumnDefinitions to make the correct pattern.</p> |
7,066,185 | 0 | <p>Depending on your distribution, install the <code>unzip</code> package. Then simply issue </p> <pre><code>unzip -p YOUR_FILE.jar META-INF/MANIFEST.MF </code></pre> <p>This will dump the contents to STDOUT.</p> <p>HTH</p> |
39,340,387 | 0 | <pre><code>def count_dups(L): ans = [] if not L: return ans running_count = 1 for i in range(len(L)-1): if L[i] == L[i+1]: running_count += 1 else: ans.append(running_count) running_count = 1 ans.append(running_count) return ans </code></pre> |
25,343,201 | 0 | <p>Whoever first wrote that code was either</p> <p>a) Being very defensive against future use. b) Didn't understand how <code>attr</code> works.</p> <p>The method <code>attr</code> (or the underlying call of <code>getAttribute</code> will return either</p> <ul> <li>A string value, of the attribute is found</li> <li><code>null</code>, if it is not.</li> </ul> <p>Importantly, should there have been a <code>0</code> value, it would be a <em>string</em> <code>0</code>, <strike>and thus not caught in the test below</strike> -- caught against the <code>price == 0</code> test because the system would have automatically converted it to a number as part of the <code>==</code> compare.</p> <pre><code>if(price=="" || price==0 || price==null || price==undefined ) </code></pre> <p>And, due to the way that conversions work internally, those tests don't work as intended. <code>==</code> and <code>===</code> are different. It should be:</p> <pre><code>if(price === "" || price === 0 || price === null || price === undefined ) </code></pre> <p>All of which can easily be reduced to simply "price" due how how <a href="http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/" rel="nofollow">coercion to boolean work</a>:</p> <pre><code>if (!price) </code></pre> <p>Or, if you want to catch <code>"0"</code> values</p> <pre><code>if (!price || +price === 0) </code></pre> <p>(the +price forces price to be a number, so we catch <code>0</code> <code>0.00</code> and other variations.)</p> |
33,511,823 | 0 | Local notification "schedule" and "trigger" methods are executing multiple times <p>Hi I'm new on ionic and I'm using (katzer/cordova-plugin-local-notifications), I have a problem and I don't know what is happening.</p> <p>When I click in a link, I'm generating a new notification. But I don't know for what when I click for the second time in the notification, the alert inside of "schedule" and "trigger" is executed two times, and when I click for the third time in the notification, the alert inside of "schedule" and "trigger" is executed three times, and so..</p> <p>This is my code, it's very simple:</p> <p>$scope.addNotification = function (){</p> <pre><code>var idaudio = Math.round(Math.random() * 10000); var date = Date.now(); cordova.plugins.notification.local.schedule({ id: idaudio, title: 'Remember', text: 'New Remember', at: date }); cordova.plugins.notification.local.on("schedule", function(notification) { alert("scheduled: " + notification.id); }); cordova.plugins.notification.local.on('trigger', function (notification) { alert("trigger" + notification.id) }); </code></pre> <p>}</p> <p>I need that when I click in a notification only one alert print the related notification id. </p> <p>Can anyone help me please?</p> <p>Thanks in advance.</p> |
3,253,800 | 0 | <p>How about using a utility enumerable method:</p> <pre><code> static IEnumerable<int> RandomNumbersBetween(int min, int max) { int availableNumbers = (max - min) + 1 ; int yieldedNumbers = 0; Random rand = new Random(); Dictionary<int, object> used = new Dictionary<int, object>(); while (true) { int n = rand.Next(min, max+1); //Random.Next max value is exclusive, so add one if (!used.ContainsKey(n)) { yield return n; used.Add(n, null); if (++yieldedNumbers == availableNumbers) yield break; } } } </code></pre> <p>Because it returns IEnumerable, you can use it with LINQ and IEnumerable extension methods:</p> <pre><code>RandomNumbersBetween(0, 20).Take(10) </code></pre> <p>Or maybe take odd numbers only:</p> <pre><code>RandomNumbersBetween(1, 1000).Where(i => i%2 == 1).Take(100) </code></pre> <p>Et cetera.</p> <p><strong>Edit:</strong></p> <p>Note that this solution has terrible performance characteristics if you are trying to generate a full set of random numbers between <code>min</code> and <code>max</code>. </p> <p>However it works efficiently if you want to generate, say 10 random numbers between 0 and 20, or even better, between 0 and 1000.</p> <p>In worst-case scenario it can also take <code>(max - min)</code> space.</p> |
34,802,923 | 0 | <p>You need to use <code>{}</code> around js expressions:</p> <pre><code><List columns={['one', 'two', 'three', 'four']} /> </code></pre> |
9,205,063 | 0 | ProcessBuilder debugging <p>I created an executable jar and executed it using process builder from another java program. Here's my code -</p> <pre><code>public class SomeClass { public static void main(String[] args) { Process p = null; ProcessBuilder pb = new ProcessBuilder("java", "-jar", "src.jar"); pb.directory(new File("/Users/vivek/servers/azkaban-0.10/TestApp/src")); try { p = pb.start(); } catch(Exception ex) { ex.printStackTrace(); } } </code></pre> <p>}</p> <p>I'm trying to now debug the src.jar from eclipse. I provided the project src as external project in my debug configuration, but it still never hits any of my break points. Is there a way to set up a debug environment for something like this?</p> |
26,716,758 | 0 | <p>Not sure if it's causing the problem, but <code>head</code> and <code>body</code> should be inside the <code>html</code> tag.</p> <pre><code>!!! = surround '<!--[if !IE]> -->'.html_safe, '<!-- <![endif]-->'.html_safe do %html.no-js{:lang => 'en'} %head %body </code></pre> <p>Could be confusing the <code>surround</code> method by having multiple tags appended instead of nested... Worth a try!</p> |
22,226,407 | 0 | Comparing similarity matrices over time <p>I've computed 4 different similarity matrices for same items but in different time periods and I'd like to compare how similarity between items changes over time. The problem is that order of items i.e. matrix columns is different for every matrix. How can I reorder columns in matrices so all my matrices become comparable?</p> |
24,241,335 | 0 | WAITING at sun.misc.Unsafe.park(Native Method) <p>One of my applications hangs under some period of running under load, does anyone know what could cause such output in jstack:</p> <pre><code>"scheduler-5" prio=10 tid=0x00007f49481d0000 nid=0x2061 waiting on condition [0x00007f494e8d0000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x00000006ee117310> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186) at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043) at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1085) at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:807) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) </code></pre> <p>I am seeing this a lot in jstack output when it hangs.</p> <p>I heavily using Spring @Async & maps, synchronized maps & ehcache.</p> <p>What is interesting this only happens on one of app instances. Two others are running perfectly fine. What else I could investigate to get more details in such case?</p> <p>I found this post <a href="http://stackoverflow.com/questions/23992787/parking-to-wait-for-0xd8cf0070-a-java-util-concurrent-locks-abstractqueueds">- parking to wait for <0xd8cf0070> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)</a> but it is not very useful in my case.</p> |
14,384,546 | 0 | Download windows phone sdk 8 offline <p>I just installed Visual Studio 2012 express edition on my Windows 8 machine.</p> <p>Now I wanted to install the Windows 8 Phone's SDK, I know it can be downloaded from here : <a href="http://dev.windowsphone.com/en-us/downloadsdk">http://dev.windowsphone.com/en-us/downloadsdk</a></p> <p>But this link only download a setup which in turns downloads the files, I wanted to know if there is any full sdk download available which I can download and use.</p> <p>I am planning to use my office connection to download these files and then install it on my home PC.</p> <p>Any thoughts ?</p> |
32,005,527 | 0 | <pre><code>String[] arrFUSE={"3", "true", "0", "FUSE"}; String[] arrPLACE={ "2", "true", "7", "PLACE"}; List<List<String>> arrLIST = new ArrayList<List<String>>(); arrLIST.add( Arrays.asList(arrFUSE) ); arrLIST.add( Arrays.asList(arrPLACE) ); </code></pre> <p>Don't use <code>{</code> on the line you create a new instance of the <code>ArrayList</code>. If you do you will be writing your own implementation of <code>ArrayList</code> on the lines below it. In stead you just want to use the standard <code>ArrayList</code> so terminate that line and start a new one.</p> <p>I also changed <code>ArrayList<ArrayList<String>></code> to <code>List<List<String>></code> because you want to be able to put any <code>List</code> in there, not just <code>ArrayLists</code>. In fact what <code>Arrays.asList</code> creates is not an <code>ArrayList</code> so it wouldn't fit otherwise.</p> |
2,088,904 | 0 | Able to include file in ASP.NET, but not check if it exists <p>I want to include certain files in my page. I'm not always sure if they exists, so I have to check if they do. (Otherwise the page crashes, as you probably know)</p> <pre><code><%@ Page Language="C#" %> <html> <body> <% bool exists; exists = System.IO.File.Exists("/extra/file/test.txt"); %> Test include:<br> <!--#include file="/extra/file/test.txt"--> </body> </html> </html> </code></pre> <p>While the include works, the code checking if the file exists does not.</p> <p>If I remove this code:</p> <pre><code><% bool exists; exists = System.IO.File.Exists("/extra/file/test.txt"); %> </code></pre> <p>Everything runs fine. I also tried putting it in a <code><script runat="server"></code> block, but it still failed.</p> |
18,092,036 | 0 | Why is the GUI not working, is the code correct? <p>So Im trying to create 3 panels. The first panel has the layout set (e.g. the radio buttons and next button) I`m now adding two new panels which have different background colors. But when I execute the code I get an error of Null point exception. How do I fix that? </p> <p>Here is the code:</p> <pre><code>import java.awt.Color;import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.CardLayout; import javax.swing.*; public class Wizard { private JLabel lblPicture; private JRadioButton btLdap, btKerbegos, btSpnego, btSaml2; private JButton btNext; private JPanel panel; private JPanel panelFirst; private JPanel panelSecond; CardLayout c1 = new CardLayout(); public static void main(String[] args) { new Wizard(); } public Wizard() { JFrame frame = new JFrame("Wizard"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600,360); frame.setVisible(true); MyPanel(); RadioButtons(); Button(); Image(); groupButton(); panel.setLayout(c1); panelFirst.setBackground(Color.BLUE); panelSecond.setBackground(Color.GREEN); panel.add(panelFirst,"1"); panel.add(panelSecond,"2"); c1.show(panel,"panel"); frame.add(panel); frame.pack(); frame.setVisible(true); } public void MyPanel() { panel = new JPanel(); panel.setLayout(null); } public void RadioButtons() { btLdap = new JRadioButton ("Ldap"); btLdap.setBounds(60,85,100,20); panel.add(btLdap); btKerbegos = new JRadioButton ("Kerbegos"); btKerbegos.setBounds(60,115,100,20); panel.add(btKerbegos); btSpnego =new JRadioButton("Spnego"); btSpnego.setBounds(60,145,100,20); panel.add(btSpnego); btSaml2 = new JRadioButton("Saml2"); btSaml2.setBounds(60,175,100,20); panel.add(btSaml2); } public void Button() { btNext = new JButton ("Next"); btNext.setBounds(400,260,100,20); panel.add(btNext); btNext.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { c1.show(panel, "2"); } }); } public void Image() { ImageIcon image = new ImageIcon("image.jpg"); lblPicture = new JLabel(image); lblPicture.setBounds(200,20, 330, 270); panel.add(lblPicture); } private void groupButton() { ButtonGroup bg1 = new ButtonGroup( ); bg1.add(btLdap); bg1.add(btKerbegos); bg1.add(btSpnego); bg1.add(btSaml2); } } </code></pre> |
34,552,278 | 1 | Can't see debug print statements using Google App Engine with python <p>I am new to both Google App Engine and Python. When things go wrong I'd like to see variable values and such, but print statements don't seem to be output anywhere. I would have expected them to appear in the same window where I started dev_appserver, but the only time I can see them is if a server error is imminent, then they appear in the output as I'd expect, right before the server error. Otherwise I don't see them.</p> <p>I'm sure I'm missing something very fundamental... it seems everyone else can see their print statements just fine. I have tried using the logger functionality, but best I can tell it is intended for deployed apps. At any rate I can't see any output from those either. A simple example:</p> <pre><code>class PageHandler(BaseHandler): def get(self): // the page renders just fine, but no print statement to be found print "rendering the page!" self.render("page.html") </code></pre> <p>Am I just looking in the wrong spot for the print output? Do I need to be doing something to redirect output before printing? Very confused why the print statements work only when an error is about to occur.</p> |
16,725,188 | 0 | <p>For those for whom the solution provided by cpowers and WonderGrub also didn't work, you should check out the following SO question, because for me this question was actually the answer to my occurence of this problem! <a href="http://stackoverflow.com/questions/7204840/rss20feedformatter-ignores-textsyndicationcontent-type-for-syndicationitem-summa">Rss20FeedFormatter Ignores TextSyndicationContent type for SyndicationItem.Summary</a></p> <p>Judging from the positive answer from <code>thelsdj</code> and <code>Andy Rose</code> and then later the 'negative' response from <code>TimLeung</code> and the alternative offered by <code>WonderGrub</code> I would estimate that the fix offered by cpowers stopped working in some later version of ASP.NET or something.</p> <p>In any case the solution in the above SO article (derived from David Whitney's code) solved the problem with unwanted HTML encoding in CDATA blocks in an RSS 2.0 feed for me. I used it in an ASP.NET 4.0 WebForms application.</p> |
7,778,918 | 0 | Creating a clean unified border around an li and its ul with CSS <p>Within my <code>#header</code> <code>#nav</code>, I have a <code><ul></code> within an <code><li></code> that displays on <code>li:hover</code>. I want to put a border around everything but for some reason adding a border around the main <code><li></code> makes the <code><ul></code> within it fall out of alignment by one px on the left. </p> <p>Here's a jsFiddle to show what I'm doing:</p> <p><a href="http://jsfiddle.net/Mh3Hg/" rel="nofollow">http://jsfiddle.net/Mh3Hg/</a></p> <p>Here is my HTML:</p> <pre><code><div id="header"> <div id="nav"> <ul> <li id="thisli"><a href="#">Main Element</a> <ul id="children"> <li><a href="#">First Child</a></li> <li><a href="#">Second Child</a></li> </ul> </li> </ul> </div><!-- end nav --> </div> </code></pre> <p>The border that throws it off is the <code>border-left:1px solid #99B3FF</code> applied to <code>li#thisli</code>. Can anyone help me figure out what's wrong?</p> |
9,131,892 | 0 | <p>Duplicate of <a href="http://stackoverflow.com/questions/3314953/load-time-weaving-in-aspectj-using-aop-xml">Load time weaving in AspectJ using aop.xml</a>.</p> <p>Furthermore, the <a href="http://www.eclipse.org/aspectj/doc/next/devguide/ltw-configuration.html" rel="nofollow">AspectJ documentation</a> says:</p> <blockquote> <p>When several configuration files are visible from a given weaving class loader their contents are conceptually merged.</p> </blockquote> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.