id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
βŒ€
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
βŒ€
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
βŒ€
last_editor_display_name
stringlengths
2
29
βŒ€
last_editor_user_id
int64
-1
20M
βŒ€
owner_display_name
stringlengths
1
29
βŒ€
owner_user_id
int64
1
20M
βŒ€
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
8,570,824
submit a rails remote form with javascript
<p>In my rails app I have a remote form that looks something like this for example:</p> <pre><code>&lt;%= form_tag some_path, :method =&gt; :get, :id =&gt; 'my-form', :remote =&gt; true do %&gt; &lt;%= text_field_tag :search, params[:search], :id =&gt; 'search-field' %&gt; &lt;%= submit_tag 'Go' %&gt; &lt;% end %&gt; </code></pre> <p>Now i would like to submit this form via javascript and trigger all rails remote form callbacks. So far i have tried a few things but nothing seems to be working. </p> <p>Things i have tried:</p> <pre><code>$('#my-form').trigger('onsubmit') $.rails.callFormSubmitBindings( $('#search-form') ) </code></pre> <p>but no luck so far. Any ideas?</p>
8,570,856
9
1
null
2011-12-20 04:31:14.467 UTC
9
2021-02-25 22:36:24.13 UTC
null
null
null
null
818,091
null
1
40
jquery|ruby-on-rails|unobtrusive-javascript
34,749
<p>You can just use .submit();</p> <pre><code>$("#my-form").submit(); </code></pre>
19,670,798
Why should I use LabelFor in MVC?
<p>Why should I use <code>LabelFor</code> instead of <code>&lt;label&gt;</code>?</p> <p>eg.</p> <pre><code>@Html.LabelFor(model =&gt; model.FirstName) @Html.DisplayFor(model =&gt; model.FirstName) </code></pre> <p>vs</p> <pre><code>&lt;label for="FirstName"&gt;First Name&lt;/label&gt; @Html.DisplayFor(model =&gt; model.FirstName) </code></pre> <p>Further to the above, @p.s.w.g has covered the DRY aspect of this question. I would also like to know if it helps with localization. ie. Different labels based on the current language setting.</p>
19,670,832
2
0
null
2013-10-29 23:04:41.39 UTC
null
2013-11-08 12:14:49.083 UTC
2013-11-08 12:14:49.083 UTC
null
727,208
null
2,833,389
null
1
38
asp.net-mvc|html-helper|html.labelfor
44,281
<p>Well, if you've decorated your models with the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.displaynameattribute.aspx"><code>DisplayNameAttribute</code></a> like this:</p> <pre><code>[DisplayName("First Name")] string FirstName { get; set; } </code></pre> <p>Then you only specify what the text of the label would be in one place. You might have to create a similar label in number of places, and if you ever needed to change the label's text it would be convenient to only do it once. </p> <p>This is even more important if you want to localize your application for different languages, which you can do with the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx"><code>DisplayAttribute</code></a>:</p> <pre><code>[Display(Name = "FirstNameLabel", ResourceType = typeof(MyResources))] string FirstName { get; set; } </code></pre> <p>It also means you'll have more strongly-typed views. It's easy to fat-finger a string like <code>"FirstName"</code> if you have to type it a lot, but using the helper method will allow the compiler to catch such mistakes most of the time.</p>
19,358,487
Guice: How to change injection on runtime based on a (dynamic web property)
<p>The following is an approximation of the problem I'm facing.</p> <p>Think we have a password validator with some rules.</p> <pre><code>public interface RuleChecker{ //Checks for a password strenght, returns 10 //for strong or 0 for soft password. int check(String pass); } </code></pre> <p>And then we have several implementations, our service will only accept the password if it is over 8 score.</p> <pre><code>public class NoCheck implements RuleChecker { public int check(String pass){return 10;} } public class LengthCheck implements RuleChecker{ ... } public class AlphanumericCheck implements RuleChecker{ ... } public class AlphaAndLenghtCheckAdapter implements RuleChecker{ ... } </code></pre> <p>But for testing purposes, we want to implement a webservice within the application where we can "admin" those rules, and select which ones to have.</p> <pre><code>public class PasswordCheckService{ private RuleChecker checker; @Inject public PasswordCheckService(final RuleChecker checker){ this.checker = checker; } public boolean checkPassword(String password){ return checker.check(password) &gt; 8; } } </code></pre> <p>So, is there any way in Guice, to change at runtime, the injection a service has?</p> <p>Example:</p> <p>We started the application and by default LengthCheck is selected and injected on the application, at the website we select the NoCheck checkbox and save options, which is stored into the database, can I configure Guice to automatically change the bean the service had injected before? so from now and on there will be no checks on new passwords?</p> <p>--</p> <p>As for now, I have found those topics </p> <p><a href="https://stackoverflow.com/questions/7651980/google-guice-and-varying-injections-at-runtime">Google Guice and varying injections at runtime</a> But i dont know if that kind of providers fits my problem.</p> <p><a href="https://stackoverflow.com/questions/7641565/guice-runtime-dependency-parameters-reinjection">Guice runtime dependency parameters reinjection</a> That nice question is talking something similar, but not what I'm looking form.</p> <p><a href="https://stackoverflow.com/questions/7663618/guice-runtime-injection-binding-at-command-line">guice: runtime injection/binding at command line</a> This is the closest to my problem but he only does on starting "runtime" and does not change it over the time.</p> <p>Any helps?</p> <p>Thank you!</p> <p>Using the tip of the first comment I implemented this POC but still does not works, if you change select another button the service bean is not updated. <a href="https://bitbucket.org/ramonboza/guicedynamicconfig" rel="nofollow noreferrer">https://bitbucket.org/ramonboza/guicedynamicconfig</a></p>
19,359,146
1
1
null
2013-10-14 10:44:25.327 UTC
8
2013-10-14 13:54:44.34 UTC
2017-05-23 11:54:12.947 UTC
null
-1
null
334,279
null
1
12
java|dependency-injection|inversion-of-control|guice
25,925
<p>Create a provider for each field type (login, password, birth date...), with a parameter to change the implementation to return.</p> <pre><code>public class MyModule extends AbstractModule { public void configure() { bind(RuleChecker.class).annotatedWith(named("password")).toProvider(PasswordRuleCheckerProvider.class); bind(RuleChecker.class).annotatedWith(named("login")).toProvider(LoginRuleCheckerProvider.class); } } public static class PasswordRuleCheckerProvider implements Provider&lt;RuleChecker&gt; { private static CheckType type = CheckType.ALPHANUMERIC; // static type setter. public RuleChecker get() { // it would even be better if you could use singletons here. switch(type) { case LENGTH: return new LengthCheck(); case ALPHANUMERIC: return new AlphanumericCheck(); case ALPHALENGTH: return new AlphaAndLenghtCheckAdapter(); case NONE: default: return NoCheck(); } } } // Almost same provider for your LoginRuleCheckerProvider. You could do something generic. </code></pre> <p>In your admin section you change "type" value, so your rules will change. It can affect a limited set of fields, thanks to the annotations. For instance : <code>PasswordRuleCheckerProvider.setType(CheckType.LENGTH);</code>. Will only affect fields with <code>@Named('password')</code>.</p> <p>You have to declare your fields and services like this :</p> <pre><code>public abstract class DynamicService { protected void updateService() { // Reinject with the new implementations the members. App.getInjector().injectMembers(this); } } public class PasswordCheckService extends DynamicService { @Inject @Named("password") private RuleChecker passwordChecker; public void changePasswordCheckType(CheckType type) { PasswordRuleCheckerProvider.setType(type); // Reinject, so you have your new implementation. updateService(); } // [...] } </code></pre>
849,396
Java BBCode library
<p>Has anybody used a good Java implementation of BBCode? I am looking at</p> <ol> <li><a href="https://javabbcode.dev.java.net/" rel="noreferrer">javabbcode</a> : nothing to see</li> <li><a href="http://sourceforge.net/projects/kefir-bb/" rel="noreferrer">kefir-bb</a> : Listed as alpha</li> <li>BBcode parser in JBoss source code.</li> </ol> <p>Are there any better options?</p>
3,722,236
4
2
null
2009-05-11 18:26:02.527 UTC
11
2014-07-31 18:54:56.563 UTC
2009-05-11 18:34:00.36 UTC
null
59,501
null
16,071
null
1
17
java|parsing|bbcode
14,148
<p><strong>The current version of KefirBB 0.6 is not listed as beta anymore. I find the KefirBB parser very easy to configure and extend with my own tags:</strong> </p> <p><a href="http://kefir-bb.sourceforge.net/" rel="noreferrer">kefir-bb.sourceforge.net</a></p> <p><em>(This is the best <a href="http://en.wikipedia.org/wiki/BBCode" rel="noreferrer">BBCode</a> parser I've found so far)</em></p> <p>I also found this code at <a href="http://fyhao.com/2010/06/computer-and-it/java/simple-java-bbcode-implementation/" rel="noreferrer">fyhao.com</a>, but it does protect you against incorrectly nested tags (thus not suitable for parsing user entered input):</p> <pre><code> public static String bbcode(String text) { String html = text; Map&lt;String,String&gt; bbMap = new HashMap&lt;String , String&gt;(); bbMap.put("(\r\n|\r|\n|\n\r)", "&lt;br/&gt;"); bbMap.put("\\[b\\](.+?)\\[/b\\]", "&lt;strong&gt;$1&lt;/strong&gt;"); bbMap.put("\\[i\\](.+?)\\[/i\\]", "&lt;span style='font-style:italic;'&gt;$1&lt;/span&gt;"); bbMap.put("\\[u\\](.+?)\\[/u\\]", "&lt;span style='text-decoration:underline;'&gt;$1&lt;/span&gt;"); bbMap.put("\\[h1\\](.+?)\\[/h1\\]", "&lt;h1&gt;$1&lt;/h1&gt;"); bbMap.put("\\[h2\\](.+?)\\[/h2\\]", "&lt;h2&gt;$1&lt;/h2&gt;"); bbMap.put("\\[h3\\](.+?)\\[/h3\\]", "&lt;h3&gt;$1&lt;/h3&gt;"); bbMap.put("\\[h4\\](.+?)\\[/h4\\]", "&lt;h4&gt;$1&lt;/h4&gt;"); bbMap.put("\\[h5\\](.+?)\\[/h5\\]", "&lt;h5&gt;$1&lt;/h5&gt;"); bbMap.put("\\[h6\\](.+?)\\[/h6\\]", "&lt;h6&gt;$1&lt;/h6&gt;"); bbMap.put("\\[quote\\](.+?)\\[/quote\\]", "&lt;blockquote&gt;$1&lt;/blockquote&gt;"); bbMap.put("\\[p\\](.+?)\\[/p\\]", "&lt;p&gt;$1&lt;/p&gt;"); bbMap.put("\\[p=(.+?),(.+?)\\](.+?)\\[/p\\]", "&lt;p style='text-indent:$1px;line-height:$2%;'&gt;$3&lt;/p&gt;"); bbMap.put("\\[center\\](.+?)\\[/center\\]", "&lt;div align='center'&gt;$1"); bbMap.put("\\[align=(.+?)\\](.+?)\\[/align\\]", "&lt;div align='$1'&gt;$2"); bbMap.put("\\[color=(.+?)\\](.+?)\\[/color\\]", "&lt;span style='color:$1;'&gt;$2&lt;/span&gt;"); bbMap.put("\\[size=(.+?)\\](.+?)\\[/size\\]", "&lt;span style='font-size:$1;'&gt;$2&lt;/span&gt;"); bbMap.put("\\[img\\](.+?)\\[/img\\]", "&lt;img src='$1' /&gt;"); bbMap.put("\\[img=(.+?),(.+?)\\](.+?)\\[/img\\]", "&lt;img width='$1' height='$2' src='$3' /&gt;"); bbMap.put("\\[email\\](.+?)\\[/email\\]", "&lt;a href='mailto:$1'&gt;$1&lt;/a&gt;"); bbMap.put("\\[email=(.+?)\\](.+?)\\[/email\\]", "&lt;a href='mailto:$1'&gt;$2&lt;/a&gt;"); bbMap.put("\\[url\\](.+?)\\[/url\\]", "&lt;a href='$1'&gt;$1&lt;/a&gt;"); bbMap.put("\\[url=(.+?)\\](.+?)\\[/url\\]", "&lt;a href='$1'&gt;$2&lt;/a&gt;"); bbMap.put("\\[youtube\\](.+?)\\[/youtube\\]", "&lt;object width='640' height='380'&gt;&lt;param name='movie' value='http://www.youtube.com/v/$1'&gt;&lt;/param&gt;&lt;embed src='http://www.youtube.com/v/$1' type='application/x-shockwave-flash' width='640' height='380'&gt;&lt;/embed&gt;&lt;/object&gt;"); bbMap.put("\\[video\\](.+?)\\[/video\\]", "&lt;video src='$1' /&gt;"); for (Map.Entry entry: bbMap.entrySet()) { html = html.replaceAll(entry.getKey().toString(), entry.getValue().toString()); } return html; } </code></pre> <p>BTW javaBBcode is part of opensource project: <a href="http://www.javabb.org/" rel="noreferrer">JavaBB</a>.</p>
22,012,071
Django nested transactions - β€œwith transaction.atomic()”
<p>I would like to know if I have something like this:</p> <pre><code>def functionA(): with transaction.atomic(): #save something functionB() def functionB(): with transaction.atomic(): #save another thing </code></pre> <p>Someone knows what will happen? If functionB fails, functionA will rollback too?</p> <p>Thank you!</p>
22,012,361
2
1
null
2014-02-25 10:57:07.107 UTC
2
2021-09-10 05:38:11.97 UTC
2014-08-22 14:04:56.65 UTC
null
3,350,765
null
3,350,765
null
1
50
django|transactions|nested|atomic
19,856
<p>Yes, it will. Regardless of nesting, if an atomic block is exited by an exception <a href="https://docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.atomic" rel="noreferrer">it will roll back</a>:</p> <blockquote> <p>If the block of code is successfully completed, the changes are committed to the database. If there is an exception, the changes are rolled back.</p> </blockquote> <p>Note also that an exception in an outer block will cause the inner block to roll back, and that an exception in an inner block can be caught to prevent the outer block from rolling back. The documentation addresses these issues. (Or see <a href="https://stackoverflow.com/q/48835309/2395796">here</a> for a more comprehensive follow-up question on nested transactions).</p>
19,452,887
org.glassfish.jersey.internal.RuntimeDelegateImpl NOT FOUND
<p>I am using jersey for my project and tring to parse a URI from a string.</p> <pre><code>UriBuilder.fromUri("http://localhost:8000").build(); </code></pre> <p>The code is simple, but I get a error below</p> <pre><code>java.lang.ClassNotFoundException: org.glassfish.jersey.internal.RuntimeDelegateImpl </code></pre> <p>It seems the program can not find the delegate. I already imported <code>javax.ws.rs.core.UriBuilder</code> and have <code>jersey-common 2.0</code> that should contain the delegate in my build path. But I still get this error.</p> <p>Does someone know how to fix it? Thanks!</p>
20,258,438
7
0
null
2013-10-18 15:03:17.973 UTC
4
2022-06-09 17:02:23.87 UTC
2016-03-24 17:08:40.663 UTC
null
294,317
null
2,525,185
null
1
45
java|rest|glassfish|jersey|jax-rs
65,163
<p>If you're using Maven, use the following dependency:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.glassfish.jersey.core&lt;/groupId&gt; &lt;artifactId&gt;jersey-common&lt;/artifactId&gt; &lt;version&gt;2.22.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>For Gradle, the following will work:</p> <pre><code>testImplementation 'org.glassfish.jersey.core:jersey-common:2.22.2' </code></pre>
19,483,511
UIRefreshControl with UICollectionView in iOS7
<p>In my application I use refresh control with collection view.</p> <pre><code>UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds]; collectionView.alwaysBounceVertical = YES; ... [self.view addSubview:collectionView]; UIRefreshControl *refreshControl = [UIRefreshControl new]; [collectionView addSubview:refreshControl]; </code></pre> <p>iOS7 has some nasty bug that when you pull collection view down and don't release your finger when refreshing begins, vertical <code>contentOffset</code> shifts for 20-30 points down which results in ugly scroll jump.</p> <p>Tables have this problem too if you use them with refresh control outside of <code>UITableViewController</code>. But for them it could be easily solved by assigning your <code>UIRefreshControl</code> instance to <code>UITableView</code>'s private property called <code>_refreshControl</code>:</p> <pre><code>@interface UITableView () - (void)_setRefreshControl:(UIRefreshControl *)refreshControl; @end ... UITableView *tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds]; [self.view addSubview:tableView]; UIRefreshControl *refreshControl = [UIRefreshControl new]; [tableView addSubview:refreshControl]; [tableView _setRefreshControl:refreshControl]; </code></pre> <p>But <code>UICollectionView</code> does not have such property so there must be some way to deal with it manually.</p>
19,926,917
2
0
null
2013-10-20 22:13:28.563 UTC
22
2019-03-22 11:09:39.97 UTC
null
null
null
null
825,882
null
1
31
ios|objective-c|uitableview|uicollectionview|uirefreshcontrol
12,685
<p>Having the same problem and found a workaround that seems to fix it.</p> <p>This seems to be happening because the <code>UIScrollView</code> is slowing down the tracking of the pan gesture when you pull past the edge of the scrollview. However, <code>UIScrollView</code> is not accounting for changes to contentInset during tracking. <code>UIRefreshControl</code> changes contentInset when it activates, and this change is causing the jump.</p> <p>Overriding <code>setContentInset</code> on your <code>UICollectionView</code> and accounting for this case seems to help:</p> <pre><code>- (void)setContentInset:(UIEdgeInsets)contentInset { if (self.tracking) { CGFloat diff = contentInset.top - self.contentInset.top; CGPoint translation = [self.panGestureRecognizer translationInView:self]; translation.y -= diff * 3.0 / 2.0; [self.panGestureRecognizer setTranslation:translation inView:self]; } [super setContentInset:contentInset]; } </code></pre> <p>Interestingly, <code>UITableView</code> accounts for this by NOT slowing down tracking until you pull PAST the refresh control. However, I don't see a way that this behavior is exposed.</p>
53,306,131
Difference between "gcloud auth application-default login" and "gcloud auth login"
<p>What is the difference between <code>gcloud auth application-default login</code> vs <code>gcloud auth login</code>?</p> <p>Despite the definitions below, it is still hard to differentiate them.</p> <p><strong>gcloud auth application-default login</strong> :</p> <ul> <li><code>acquire new user credentials to use for Application Default Credentials</code></li> </ul> <p><strong>gcloud auth login</strong> :</p> <ul> <li><code>authorize gcloud to access the Cloud Platform with Google user credentials </code></li> </ul> <p>When should I use one over the other?</p>
53,307,505
2
0
null
2018-11-14 17:53:07.21 UTC
24
2021-06-16 18:14:15.79 UTC
2020-05-08 15:34:35.63 UTC
null
320,399
null
6,066,490
null
1
56
google-cloud-platform|gcloud
31,407
<p>The difference is the use cases:</p> <p><strong>As a developer, I want to interact with GCP via gcloud.</strong><br /> <code>gcloud auth login</code><br /> This obtains your credentials and stores them in <code>~/.config/gcloud/</code>. Now you can run <code>gcloud</code> commands from your terminal and it will find your credentials automatically. Any code/SDK will <strong>not</strong> automatically pick up your creds in this case.</p> <p>Reference: <a href="https://cloud.google.com/sdk/gcloud/reference/auth/login" rel="noreferrer">https://cloud.google.com/sdk/gcloud/reference/auth/login</a></p> <p><strong>As a developer, I want my code to interact with GCP via SDK.</strong><br /> <code>gcloud auth application-default login</code><br /> This obtains your credentials via a web flow and stores them in <em>'the well-known location for Application Default Credentials'</em>. Now any code/SDK you run will be able to find the credentials automatically. This is a good stand-in when you want to locally test code which would normally run on a server and use a server-side credentials file.</p> <p>Reference: <a href="https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login" rel="noreferrer">https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login</a></p> <p><strong>Edit (09/19/2019):</strong><br /> As Kent contributed in his comment below, <em>'the well-known location for Application Default Credentials'</em> is a file named <code>application_default_credentials.json</code> located in your local <code>~/.config/gcloud/</code> directory. I've added an additional link below to an article by <strong>Theodore Sui</strong> and <strong>Daniel De Leo</strong> which goes into greater detail about the different authentication methods.</p> <p>Article: <a href="https://medium.com/google-cloud/local-remote-authentication-with-google-cloud-platform-afe3aa017b95" rel="noreferrer">https://medium.com/google-cloud/local-remote-authentication-with-google-cloud-platform-afe3aa017b95</a></p>
48,589,821
Firebase hosting: How to prevent caching for the index.html of an SPA
<p>I'm hosting an SPA on firebase where almost all paths get rewritten to <code>index.html</code>. I'm using webpack hash based cache busting, so I want to always prevent caching of my <code>index.html</code> but not any other files. I'm finding it surprisingly difficult to do so. Specifically, my file layout looks like this</p> <pre><code>/ β”œβ”€β”€ index.html β”œβ”€β”€ login.html β”œβ”€β”€ js β”‚ β”œβ”€β”€ login.ba22ef2579d744b26c65.bundle.js β”‚ └── main.6d0ef60e45ae7a11063c.bundle.js └── public └── favicon-16x16.ico </code></pre> <p>I started naively with <code>"sources": "index.html"</code> before reading this quote from the docs.</p> <blockquote> <p>Each definition must have a source key that is matched against the original request path regardless of any rewrite rules using <a href="https://firebase.google.com/docs/hosting/full-config#section-glob" rel="noreferrer">glob notation</a>. </p> </blockquote> <p>Ok, so instead of a simple glob that specifies the files I want these headers on, I guess I need one on paths. Since most paths redirect to index.html, I need a glob that excludes all the paths I do not want to put these headers on.</p> <p>For reference, my <code>firebase.json</code> hosting section looks like this:</p> <pre><code>{ "hosting": { "public": "dist", "rewrites": [ { "source": "**", "destination": "/index.html" } ], "cleanUrls": true, "trailingSlash": false, "headers": [ { "source": &lt;&lt;&lt;WHAT-GOES-HERE?&gt;&gt;&gt;, "headers": [ { "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" }, { "key": "Pragma", "value": "no-cache" }, { "key": "Expires", "value": "0" } ] } ] } } </code></pre> <p>So, to give some examples that redirect to index.html and should not be cached</p> <pre><code>mysite.com mysite.com/ mysite.com/foo/bar/baz mysite.com/index.html </code></pre> <p><em>Note: I could live if that last one got cached since it doesn't get used in practice.</em></p> <p>And the things that do not redirect to index.html and should not be cached</p> <pre><code>**/*.* (ideally excluding index.html) mysite.com/login </code></pre> <p>The closest I've gotten on my own is <code>**/!(login|*.*)</code> which works for almost everything listed above, but inexplicably does not work on <code>mysite.com</code> or <code>mysite.com/</code>. Those 2 pages are not getting matched by this glob and I cannot figure out why.</p>
48,738,828
3
2
null
2018-02-02 19:42:42.313 UTC
22
2022-06-03 19:54:40.213 UTC
2018-02-02 21:09:49.163 UTC
null
2,012,396
null
2,012,396
null
1
47
firebase|single-page-application|cache-control|firebase-hosting
19,487
<p>Here is the config that I'm using. The logic is to use cache for all static files like <code>images, css, js</code> etc.. For all others, i.e <code>"source": "/**"</code> set cache as no-cache. So for all other files, that maybe <em>example.com, example.com/index.html, example.com/about-us, example.com/about-us.html</em> cache will not be applied. </p> <pre><code>{ "hosting": { "public": "dist", "headers": [ { "source": "/**", "headers": [ { "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" } ] }, { "source": "**/*.@(jpg|jpeg|gif|png|svg|webp|js|css|eot|otf|ttf|ttc|woff|woff2|font.css)", "headers": [ { "key": "Cache-Control", "value": "max-age=604800" } ] } ], "ignore": ["firebase.json", "**/.*", "**/node_modules/**"] } } </code></pre>
39,674,850
Send a notification when the app is closed
<p>How is it possible to send a notification programmatically, when the App got completely closed? </p> <p>Example: The User closed the App, also in the Android Taskmanager, and waits. The App should send a notification after X Seconds or when the App check for Updates.</p> <p>I tried to work with these code examples but:</p> <ul> <li><a href="https://stackoverflow.com/questions/37906371/pushing-notifications-when-app-is-closed">Pushing notifications when app is closed</a> - too many Activities/doesn't work</li> <li><a href="https://stackoverflow.com/questions/24002188/how-do-i-get-my-app-to-send-a-notification-when-it-is-closed">How do I get my app to send a notification when it is closed?</a> - much information, but I don't know how to deal with it</li> <li><a href="https://stackoverflow.com/questions/24327453/how-to-send-local-notification-android-when-app-is-closed">How to send local notification android when app is closed?</a> - much information, but I don't know how to deal with it</li> </ul> <p>If you can, try to explain it at an example, because beginners (like me) can easier learn it this way.</p>
39,675,175
3
0
null
2016-09-24 09:37:45.41 UTC
16
2022-03-16 05:29:58.303 UTC
2017-05-23 12:33:37.303 UTC
null
-1
null
6,382,125
null
1
29
android|notifications
42,130
<p>You can use this service all you need to do is Start this service onStop() in your activity lifecycle. With this code: <code>startService(new Intent(this, NotificationService.class));</code> then you can create a new Java Class and paste this code in it:</p> <pre><code>public class NotificationService extends Service { Timer timer; TimerTask timerTask; String TAG = "Timers"; int Your_X_SECS = 5; @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand"); super.onStartCommand(intent, flags, startId); startTimer(); return START_STICKY; } @Override public void onCreate() { Log.e(TAG, "onCreate"); } @Override public void onDestroy() { Log.e(TAG, "onDestroy"); stoptimertask(); super.onDestroy(); } //we are going to use a handler to be able to run in our TimerTask final Handler handler = new Handler(); public void startTimer() { //set a new Timer timer = new Timer(); //initialize the TimerTask's job initializeTimerTask(); //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms timer.schedule(timerTask, 5000, Your_X_SECS * 1000); // //timer.schedule(timerTask, 5000,1000); // } public void stoptimertask() { //stop the timer, if it's not already null if (timer != null) { timer.cancel(); timer = null; } } public void initializeTimerTask() { timerTask = new TimerTask() { public void run() { //use a handler to run a toast that shows the current timestamp handler.post(new Runnable() { public void run() { //TODO CALL NOTIFICATION FUNC YOURNOTIFICATIONFUNCTION(); } }); } }; } } </code></pre> <p>After this you only need to combine the service with the manifest.xml:</p> <pre><code>&lt;service android:name=".NotificationService" android:label="@string/app_name"&gt; &lt;intent-filter&gt; &lt;action android:name="your.app.domain.NotificationService" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/service&gt; </code></pre>
48,437,189
Python enumerate() tqdm progress-bar when reading a file?
<p>I can't see the tqdm progress bar when I use this code to iterate my opened file:</p> <pre><code> with open(file_path, 'r') as f: for i, line in enumerate(tqdm(f)): if i &gt;= start and i &lt;= end: print("line #: %s" % i) for i in tqdm(range(0, line_size, batch_size)): # pause if find a file naed pause at the currend dir re_batch = {} for j in range(batch_size): re_batch[j] = re.search(line, last_span) </code></pre> <p>what's the right way to use tqdm here?</p>
49,281,428
5
2
null
2018-01-25 06:54:23.833 UTC
8
2022-09-18 18:10:51.417 UTC
2021-02-14 05:39:08.02 UTC
null
202,229
null
5,301,692
null
1
65
python|progress-bar|enumerate|tqdm
89,561
<p>You're on the right track. You're using tqdm correctly, but stop short of printing each line inside the loop when using tqdm. You'll also want to use tqdm on your first for loop and not on others, like so: </p> <pre><code>with open(file_path, 'r') as f: for i, line in enumerate(tqdm(f)): if i &gt;= start and i &lt;= end: for i in range(0, line_size, batch_size): # pause if find a file naed pause at the currend dir re_batch = {} for j in range(batch_size): re_batch[j] = re.search(line, last_span) </code></pre> <p>Some notes on using <em>enumerate</em> and its usage in tqdm <a href="https://pypi.python.org/pypi/tqdm#faq-and-known-issues" rel="noreferrer">here</a>. </p>
25,491,847
Extract The Second Word In A Line From A Text File
<p>I am currently in need to extract the second word (CRISTOBAL) in a line in a text file.</p> <pre><code> * CRISTOBAL AL042014 08/05/14 12 UTC * </code></pre> <p>The second word in the line "CRISTOBAL" will vary from day to day so, I just need to find a way to extract JUST the second word/character from the line.</p>
25,491,964
4
1
null
2014-08-25 18:07:04.597 UTC
3
2022-02-15 15:32:34.873 UTC
null
null
null
null
2,888,846
null
1
25
bash|unix|awk|sed|cut
60,184
<p><strong>2nd word</strong></p> <pre><code>echo '* CRISTOBAL AL042014 08/05/14 12 UTC *' | awk '{print $2}' </code></pre> <p>will give you <code>CRISTOBAL</code></p> <pre><code>echo 'testing only' | awk '{print $2}' </code></pre> <p>will give you <code>only</code></p> <p>You may have to modify this if the structure of the line changes. </p> <p><strong>2nd word from lines in a text file</strong></p> <p>If your text file contains the following two sentences </p> <pre><code>this is a test * CRISTOBAL AL042014 08/05/14 12 UTC * </code></pre> <p>running <code>awk '{print $2}' filename.txt</code> will return</p> <pre><code>is CRISTOBAL </code></pre> <p><strong>2nd character</strong> </p> <pre><code>echo 'testing only' | cut -c 2 </code></pre> <p>This will give you <code>e</code>, which is the 2nd character, and you may have to modify this so suit your needs also.</p>
30,474,614
Multiple Select limit number of selection
<p>I want user to select maximum of only three options from multiple select options. I tried this code so far:</p> <pre><code>&lt;select id="userRequest_activity" required name="activity[]" class="multiselect form-control" multiple="multiple"&gt; &lt;option value="2"&gt;Bungee Jumping&lt;/option&gt; &lt;option value="3"&gt;Camping&lt;/option&gt; &lt;option value="5"&gt;Mountain Biking&lt;/option&gt; &lt;option value="6"&gt;Rappelling&lt;/option&gt; &lt;option value="7"&gt;Rock Climbing / Bouldering&lt;/option&gt; &lt;option value="8"&gt;Skiing&lt;/option&gt; &lt;option value="10"&gt;Wild Life (Safari)&lt;/option&gt; &lt;option value="11"&gt;Canoeing &amp;amp; Kayaking&lt;/option&gt; &lt;option value="12"&gt;Rafting&lt;/option&gt; &lt;option value="13"&gt;Sailing&lt;/option&gt; &lt;option value="14"&gt;Scuba Diving&lt;/option&gt; &lt;option value="15"&gt;Snorkeling&lt;/option&gt; &lt;option value="16"&gt;Surfing&lt;/option&gt; &lt;option value="18"&gt;Hang Gliding&lt;/option&gt; &lt;option value="19"&gt;Hot-air Ballooning&lt;/option&gt; &lt;option value="20"&gt;Micro-light Aircrafts&lt;/option&gt; &lt;option value="21"&gt;Paragliding&lt;/option&gt; &lt;option value="22"&gt;Paramotoring&lt;/option&gt; &lt;option value="23"&gt;Parasailing&lt;/option&gt; &lt;option value="24"&gt;Skydiving / Parachuting&lt;/option&gt; &lt;option value="25"&gt;Zip-line / Flying Fox&lt;/option&gt; &lt;option value="26"&gt;Caving&lt;/option&gt; &lt;option value="27"&gt;Cycling&lt;/option&gt; &lt;option value="28"&gt;Fishing &amp;amp; Angling&lt;/option&gt; &lt;option value="29"&gt;Motorbike trips&lt;/option&gt; &lt;option value="30"&gt;Nature Walks&lt;/option&gt; &lt;option value="31"&gt;Road Trips&lt;/option&gt; &lt;option value="32"&gt;Zorbing&lt;/option&gt; &lt;option value="33"&gt;Trekking Hiking and Mountaineering&lt;/option&gt; &lt;option value="34"&gt;Backpacking&lt;/option&gt; &lt;option value="61"&gt;Water&lt;/option&gt; &lt;/select&gt; </code></pre> <p>The javascript code:</p> <pre><code>&lt;script type="text/javascript"&gt; $("select").change(function() { if ($("select option:selected").length &gt; 3) { $(this).removeAttr("selected"); alert('You can select upto 3 options only'); } }); &lt;/script&gt; </code></pre> <p>This code shows the alert box when selected more than 3 options but still allow access to select the 4th, 5th, 6th and so on selections with the alert box appearing. How to validate this?</p>
30,475,067
6
1
null
2015-05-27 06:21:55.367 UTC
14
2022-01-23 22:55:24.04 UTC
2015-05-27 06:22:57.717 UTC
null
2,025,923
null
4,622,552
null
1
18
javascript|jquery|html
72,542
<p>Try this...</p> <p>Check length and deselect after reach maximum select</p> <pre><code>&lt;select id="userRequest_activity" required name="activity[]" class="multiselect form-control" multiple="multiple"&gt; &lt;option value="2"&gt;Bungee Jumping&lt;/option&gt; &lt;option value="3"&gt;Camping&lt;/option&gt; &lt;option value="5"&gt;Mountain Biking&lt;/option&gt; &lt;option value="6"&gt;Rappelling&lt;/option&gt; &lt;option value="7"&gt;Rock Climbing / Bouldering&lt;/option&gt; &lt;option value="8"&gt;Skiing&lt;/option&gt; &lt;option value="10"&gt;Wild Life (Safari)&lt;/option&gt; &lt;option value="11"&gt;Canoeing &amp;amp; Kayaking&lt;/option&gt; &lt;option value="12"&gt;Rafting&lt;/option&gt; &lt;option value="13"&gt;Sailing&lt;/option&gt; &lt;option value="14"&gt;Scuba Diving&lt;/option&gt; &lt;option value="15"&gt;Snorkeling&lt;/option&gt; &lt;option value="16"&gt;Surfing&lt;/option&gt; &lt;option value="18"&gt;Hang Gliding&lt;/option&gt; &lt;option value="19"&gt;Hot-air Ballooning&lt;/option&gt; &lt;option value="20"&gt;Micro-light Aircrafts&lt;/option&gt; &lt;option value="21"&gt;Paragliding&lt;/option&gt; &lt;option value="22"&gt;Paramotoring&lt;/option&gt; &lt;option value="23"&gt;Parasailing&lt;/option&gt; &lt;option value="24"&gt;Skydiving / Parachuting&lt;/option&gt; &lt;option value="25"&gt;Zip-line / Flying Fox&lt;/option&gt; &lt;option value="26"&gt;Caving&lt;/option&gt; &lt;option value="27"&gt;Cycling&lt;/option&gt; &lt;option value="28"&gt;Fishing &amp;amp; Angling&lt;/option&gt; &lt;option value="29"&gt;Motorbike trips&lt;/option&gt; &lt;option value="30"&gt;Nature Walks&lt;/option&gt; &lt;option value="31"&gt;Road Trips&lt;/option&gt; &lt;option value="32"&gt;Zorbing&lt;/option&gt; &lt;option value="33"&gt;Trekking Hiking and Mountaineering&lt;/option&gt; &lt;option value="34"&gt;Backpacking&lt;/option&gt; &lt;option value="61"&gt;Water&lt;/option&gt; &lt;/select&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { var last_valid_selection = null; $('#userRequest_activity').change(function(event) { if ($(this).val().length &gt; 3) { $(this).val(last_valid_selection); } else { last_valid_selection = $(this).val(); } }); }); &lt;/script&gt; </code></pre> <p><strong>DEMO:</strong><a href="http://jsfiddle.net/9c3sevuv/" rel="noreferrer">http://jsfiddle.net/9c3sevuv/</a></p>
20,634,868
Put icon inside input element in a form (not as background image!)
<p>I want to do exactly what was asked here:</p> <p><a href="https://stackoverflow.com/questions/917610/put-icon-inside-input-element-in-a-form">Put icon inside input element in a form</a></p> <p>Except that I want the icons to be right-aligned.</p> <p>The "background" workaround won't work, since those images have to be clickable! So it must be an IMG.</p> <p>How can I do this?</p>
20,635,049
3
1
null
2013-12-17 13:00:14.27 UTC
8
2018-03-08 22:44:44.827 UTC
2017-05-23 12:26:15.373 UTC
null
-1
null
1,043,342
null
1
28
html|css|forms|input|icons
99,722
<p>A solution without background-images:</p> <p><a href="http://jsfiddle.net/2pbtB/573/" rel="noreferrer">JSFiddle.</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#input_container { position:relative; padding:0; margin:0; } #input { height:20px; margin:0; padding-left:30px; } #input_img { position:absolute; bottom:8px; left:10px; width:10px; height:10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="input_container"&gt; &lt;input type="text" id="input" value&gt; &lt;img src="https://cdn1.iconfinder.com/data/icons/CornerStone/PNG/arrow%20right.png" id="input_img"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
15,638,550
finding sum of two dimensional array java
<p>I am working on a project where I have to read a file and enter the content into a 2D array. Then I have to sum each row, each column, and the perimeter of the matrix. I have everything working so far except the perimeter. I am trying to create separate for loops for the top row, bottom row, and middle of the two outside columns. </p> <p>The matrix file looks like this:</p> <pre><code>1 2 3 4 2 4 6 8 2 4 6 8 3 2 3 4 </code></pre> <p>Therefore the perimeter should add up to 42. Right now I can successfully add the first row and the last row to equal 22. However, when I add the columns to that total I get 32. </p> <p>Here is the code:</p> <pre><code>import java.util.*; // Scanner class import java.io.*; // File class public class Lab10 { static public void main( String [ ] args ) throws Exception { if ( args.length != 1 ) { System.out.println("Error -- usage is: java Lab10 matdataN.txt"); System.exit( 0 ); } //Requirement #1: first int value: # of rows, second int value: # of cols File newFile = new File(args[0]); Scanner in = new Scanner(newFile); int numRows = in.nextInt(); int numCols = in.nextInt(); //Requirement #2: declare two-d array of ints int[][] matrix; matrix = new int[numRows][numCols]; //Requirement #3 &amp; 4: read file one line at a time (nested for loops //and nextInt()) and print for (int i = 0; i &lt; numRows; i++) { for (int j = 0; j &lt; numCols; j++) { matrix[i][j] = in.nextInt(); System.out.print(matrix[i][j]+ " "); } System.out.println(); } //Requirement #5: traverse each row and sum the values and display the sums int rowTotal = 0; for (int i = 0; i &lt; numRows; i++) { rowTotal = 0; for (int j = 0; j &lt; numCols; j++) { rowTotal += matrix[i][j]; } System.out.println("Sum for row = " + rowTotal); } //Requirement #6: traverse each column and sum the values and display the sums int colTotal = 0; for (int i = 0; i &lt; numRows; i++) { colTotal = 0; for (int j = 0; j &lt; numCols; j++) { colTotal += matrix[j][i]; } System.out.println("Sum for col = " + colTotal); } //Requirement #7: traverse the perimeter and sum the values and display the sum //sum bottom row matrix int perTotal = 0; for (int i = (numRows-1); i &lt; numRows; i++) { perTotal = 0; for (int j = 0; j &lt; numCols; j++) { perTotal += matrix[i][j]; } } //sum + top row matrix for (int i = 0; i &lt; numRows - (numRows-1); i++) { for (int j = 0; j &lt; numCols; j++) { perTotal += matrix[i][j]; } System.out.println("Sum of perimeter = " + perTotal); } // sum + first col middle for (int i = 1; i &lt; (numRows-1); i++) { for (int j = 0; j &lt; numCols - (numCols-1); j++) { perTotal += matrix[j][i]; } System.out.println("Sum = " + perTotal); } // sum + last col middle for (int i = 1; i &lt; (numRows-1); i++) { for (int j = (numCols-1); j &lt; numCols; j++) { perTotal += matrix[j][i]; } System.out.println(perTotal); } } </code></pre> <p>I would be hugeeeeeely appreciative if anyone could help me total the middle of the first and last column (should be 2+2 and 8+8). Or if you have an altogether better way of finding the perimeter. Thanks in advance!</p>
15,638,828
9
1
null
2013-03-26 13:41:28.427 UTC
null
2021-04-15 02:17:50.227 UTC
2013-03-26 13:44:38.667 UTC
null
1,749,753
null
2,211,761
null
1
2
java|matrix|multidimensional-array
59,271
<p>I reccomend you do it this way:</p> <pre><code>int perTotal = 0; // top and bottom row for (int c = 0; c &lt; numCols; c++) perTotal += matrix[0][c] + matrix[numRows-1][c]; // left and right column for (int r = 1; r &lt; numRows-1; r++) perTotal += matrix[r][0] + matrix[r][numCols-1]; // output System.out.println("Perimeter=" + perTotal); </code></pre>
26,503,455
ASP.NET Web API Login method
<p>I'm wanting to build a RESTful web service using ASP.NET Web API that third-party developers will use to access my application's data. </p> <p>In Visual Studio I decided to create a new ASP.NET project. I followed this <a href="http://www.asp.net/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider" rel="noreferrer">tutorial</a> but I choose a different template: Web API template. I use a MySQL database with the standard user role tables as explained in the tutorial.</p> <p>The template come with many very interesting methods to register a new user but there is no default Login request. I wrote this without understanding what I'm doing:</p> <pre><code> // POST api/Account/Login [Route("Login")] public IHttpActionResult Login(LoginBindingModel model) { ClaimsIdentity ci = new ClaimsIdentity(); // ... // ... Authentication.SignIn(ci); return Ok(); } </code></pre> <p>I've read quite a lot about security without finding a good sample with documentation explaining how it works. It seems to be incredibly difficult to implement a simple login method in Web API.</p> <p>Could you explain me why there is no login method in this template. Do you have an sample of login method. And what should I sent back to the client application to authenticate the request. Is this working with a token ?</p>
26,503,795
4
2
null
2014-10-22 08:41:52.323 UTC
5
2018-01-06 02:34:17.813 UTC
2016-06-06 21:09:21.577 UTC
null
1,664,443
null
196,526
null
1
20
c#|asp.net|asp.net-web-api
91,150
<p>Usually what you do is implement the login logic in that method, and return a token which will be then validated on each call to your api.</p> <p>You can read this for more information</p> <p><a href="http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/" rel="noreferrer">http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/</a></p>
19,972,965
Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists
<p>I am trying to convert <code>DateTime?</code> to <code>DateTime</code> but I get this Error:</p> <blockquote> <p>Error 7 Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists</p> </blockquote> <p>Here is my code:</p> <pre><code>public string ConvertToPersianToShow(DateTime? datetime) { DateTime dt; string date; dt = datetime; string year = Convert.ToString(persian_date.GetYear(dt)); string month = Convert.ToString(persian_date.GetMonth(dt)); string day = Convert.ToString(persian_date.GetDayOfMonth(dt)); if (month.Length == 1) { month = &quot;0&quot; + Convert.ToString(persian_date.GetMonth(dt)); } if (day.Length == 1) { day = &quot;0&quot; + Convert.ToString(persian_date.GetDayOfMonth(dt)); } //date = Convert.ToString(persian_date.GetYear(dt)) + &quot;/&quot; + Convert.ToString(persian_date.GetMonth(dt)) + &quot;/&quot; + //Convert.ToString(persian_date.GetDayOfMonth(dt)); date = year + &quot;/&quot; + month + &quot;/&quot; + day+&quot;(&quot;+dt.Hour+&quot;:&quot;+dt.Minute+&quot;)&quot;; return date; } </code></pre>
19,972,995
4
1
null
2013-11-14 08:36:42.71 UTC
8
2021-08-05 08:28:06.557 UTC
2021-08-05 08:28:06.557 UTC
null
11,455,105
user2796487
null
null
1
49
c#|.net|linq|datetime|type-conversion
137,271
<p>You have 3 options:</p> <p>1) Get default value</p> <pre><code>dt = datetime??DateTime.Now; </code></pre> <p>it will assign <code>DateTime.Now</code> (or any other value which you want) if <code>datetime</code> is null</p> <p>2) Check if datetime contains value and if not return empty string</p> <pre><code>if(!datetime.HasValue) return ""; dt = datetime.Value; </code></pre> <p>3) Change signature of method to </p> <pre><code>public string ConvertToPersianToShow(DateTime datetime) </code></pre> <p>It's all because <code>DateTime?</code> means it's nullable <code>DateTime</code> so before assigning it to <code>DateTime</code> you need to check if it contains value and only then assign.</p>
24,346,068
Set up a Stomp client in android with Spring framework in server side
<p>I am developing an android application that exchanges data with a jetty server configured in Spring. To obtain a more dynamic android application, i am trying to use WebSocket protocol with Stomp messages.</p> <p>In order to realize this stuff, i config a web socket message broker in spring :</p> <pre><code>@Configuration //@EnableScheduling @ComponentScan( basePackages="project.web", excludeFilters = @ComponentScan.Filter(type= FilterType.ANNOTATION, value = Configuration.class) ) @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/message"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/client"); } } </code></pre> <p>and a <code>SimpMessageSendingOperations</code> in Spring controller to send message from server to client :</p> <pre><code>@Controller public class MessageAddController { private final Log log = LogFactory.getLog(MessageAddController.class); private SimpMessageSendingOperations messagingTemplate; private UserManager userManager; private MessageManager messageManager; @Autowired public MessageAddController(SimpMessageSendingOperations messagingTemplate, UserManager userManager, MessageManager messageManager){ this.messagingTemplate = messagingTemplate; this.userManager = userManager; this.messageManager = messageManager; } @RequestMapping("/Message/Add") @ResponseBody public SimpleMessage addFriendship( @RequestParam String content, @RequestParam Long otherUser_id ){ if(log.isInfoEnabled()) log.info("Execute MessageAdd action"); SimpleMessage simpleMessage; try{ User curentUser = userManager.getCurrentUser(); User otherUser = userManager.findUser(otherUser_id); Message message = new Message(); message.setContent(content); message.setUserSender(curentUser); message.setUserReceiver(otherUser); messageManager.createMessage(message); Message newMessage = messageManager.findLastMessageCreated(); messagingTemplate.convertAndSend( "/message/add", newMessage);//send message through websocket simpleMessage = new SimpleMessage(null, newMessage); } catch (Exception e) { if(log.isErrorEnabled()) log.error("A problem of type : " + e.getClass() + " has occured, with message : " + e.getMessage()); simpleMessage = new SimpleMessage( new SimpleException(e.getClass(), e.getMessage()), null); } return simpleMessage; } } </code></pre> <p>When i test this configuration in a web browser with stomp.js, I haven't any problem : messages are perfectly exchanged between web browser and Jetty server. The JavaScript code using for web browser test :</p> <pre><code> var stompClient = null; function setConnected(connected) { document.getElementById('connect').disabled = connected; document.getElementById('disconnect').disabled = !connected; document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden'; document.getElementById('response').innerHTML = ''; } function connect() { stompClient = Stomp.client("ws://YOUR_IP/client"); stompClient.connect({}, function(frame) { setConnected(true); stompClient.subscribe('/message/add', function(message){ showMessage(JSON.parse(message.body).content); }); }); } function disconnect() { stompClient.disconnect(); setConnected(false); console.log("Disconnected"); } function showMessage(message) { var response = document.getElementById('response'); var p = document.createElement('p'); p.style.wordWrap = 'break-word'; p.appendChild(document.createTextNode(message)); response.appendChild(p); } </code></pre> <p>Problems occur when i try to use stomp in Android with libraries like gozirra, activemq-stomp or others : most of time, connection with server doesn't work. My app stop to run and, after a few minutes, i have the following message in logcat : <code>java.net.UnknownHostException: Unable to resolve host "ws://192.168.1.39/client": No address associated with hostname</code>, and i don't understand why. Code using Gozzira library which manages the stomp appeal in my android activity :</p> <pre><code>private void stomp_test() { String ip = "ws://192.172.6.39/client"; int port = 8080; String channel = "/message/add"; Client c; try { c = new Client( ip, port, "", "" ); Log.i("Stomp", "Connection established"); c.subscribe( channel, new Listener() { public void message( Map header, String message ) { Log.i("Stomp", "Message received!!!"); } }); } catch (IOException ex) { Log.e("Stomp", ex.getMessage()); ex.printStackTrace(); } catch (LoginException ex) { Log.e("Stomp", ex.getMessage()); ex.printStackTrace(); } catch (Exception ex) { Log.e("Stomp", ex.getMessage()); ex.printStackTrace(); } } </code></pre> <p>After some research, i found that most persons who want to use stomp over websocket with Java Client use ActiveMQ server, like in this <a href="http://aredko.blogspot.fr/2013/06/easy-messaging-with-stomp-over.html" rel="noreferrer">site</a>. But spring tools are very simple to use and it will be cool if i could keep my server layer as is it now. Someone would know how to use stomp java (Android) in client side with Spring configuration in server side?</p>
24,627,888
4
1
null
2014-06-21 21:35:49.217 UTC
11
2020-02-11 11:40:55.707 UTC
2015-02-10 09:46:35.6 UTC
null
3,706,184
null
3,706,184
null
1
9
android|spring|websocket|stomp
28,224
<p>I achieve to use stomp over web socket with Android and spring server. </p> <p>To do such a thing, i used a web socket library : werbench (follow this <a href="https://github.com/pelotoncycle/weberknecht" rel="noreferrer">link</a> to download it). To install, I used the maven command <code>mvn install</code> and i got back the jar in my local repository. Then, I need to add a stomp layer on the basic web socket one, but i couldn't find any stomp library in java which could manage stomp over web socket (I had to give up gozzira). So I create my own one (with stomp.js like model). Don't hesitate to ask me if you want take a look at it, but i realized it very quickly so it can not manage as much as stomp.js. Then, i need to realize an authentication with my spring server. To achieve it, i followed the indication of <a href="http://blogs.burnsidedigital.com/2012/11/how-to-use-ssl-and-session-cookies-with-spring-for-android/" rel="noreferrer">this site</a>. when i get back the JSESSIONID cookie, I had just need to declare an header with this cookie in the instantiation of a werbench web socket in my stomp "library".</p> <p>EDIT : this is the main class in this library, the one which manage the stomp over web socket connection :</p> <pre><code>import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import android.util.Log; import de.roderick.weberknecht.WebSocket; import de.roderick.weberknecht.WebSocketEventHandler; import de.roderick.weberknecht.WebSocketMessage; public class Stomp { private static final String TAG = Stomp.class.getSimpleName(); public static final int CONNECTED = 1;//Connection completely established public static final int NOT_AGAIN_CONNECTED = 2;//Connection process is ongoing public static final int DECONNECTED_FROM_OTHER = 3;//Error, no more internet connection, etc. public static final int DECONNECTED_FROM_APP = 4;//application explicitely ask for shut down the connection private static final String PREFIX_ID_SUBSCIPTION = "sub-"; private static final String ACCEPT_VERSION_NAME = "accept-version"; private static final String ACCEPT_VERSION = "1.1,1.0"; private static final String COMMAND_CONNECT = "CONNECT"; private static final String COMMAND_CONNECTED = "CONNECTED"; private static final String COMMAND_MESSAGE = "MESSAGE"; private static final String COMMAND_RECEIPT = "RECEIPT"; private static final String COMMAND_ERROR = "ERROR"; private static final String COMMAND_DISCONNECT = "DISCONNECT"; private static final String COMMAND_SEND = "SEND"; private static final String COMMAND_SUBSCRIBE = "SUBSCRIBE"; private static final String COMMAND_UNSUBSCRIBE = "UNSUBSCRIBE"; private static final String SUBSCRIPTION_ID = "id"; private static final String SUBSCRIPTION_DESTINATION = "destination"; private static final String SUBSCRIPTION_SUBSCRIPTION = "subscription"; private static final Set&lt;String&gt; VERSIONS = new HashSet&lt;String&gt;(); static { VERSIONS.add("V1.0"); VERSIONS.add("V1.1"); VERSIONS.add("V1.2"); } private WebSocket websocket; private int counter; private int connection; private Map&lt;String, String&gt; headers; private int maxWebSocketFrameSize; private Map&lt;String, Subscription&gt; subscriptions; private ListenerWSNetwork networkListener; /** * Constructor of a stomp object. Only url used to set up a connection with a server can be instantiate * * @param url * the url of the server to connect with */ public Stomp(String url, Map&lt;String,String&gt; headersSetup, ListenerWSNetwork stompStates){ try { this.websocket = new WebSocket(new URI(url), null, headersSetup); this.counter = 0; this.headers = new HashMap&lt;String, String&gt;(); this.maxWebSocketFrameSize = 16 * 1024; this.connection = NOT_AGAIN_CONNECTED; this.networkListener = stompStates; this.networkListener.onState(NOT_AGAIN_CONNECTED); this.subscriptions = new HashMap&lt;String, Subscription&gt;(); this.websocket.setEventHandler(new WebSocketEventHandler() { @Override public void onOpen(){ if(Stomp.this.headers != null){ Stomp.this.headers.put(ACCEPT_VERSION_NAME, ACCEPT_VERSION); transmit(COMMAND_CONNECT, Stomp.this.headers, null); Log.d(TAG, "...Web Socket Openned"); } } @Override public void onMessage(WebSocketMessage message) { Log.d(TAG, "&lt;&lt;&lt; " + message.getText()); Frame frame = Frame.fromString(message.getText()); boolean isMessageConnected = false; if(frame.getCommand().equals(COMMAND_CONNECTED)){ Stomp.this.connection = CONNECTED; Stomp.this.networkListener.onState(CONNECTED); Log.d(TAG, "connected to server : " + frame.getHeaders().get("server")); isMessageConnected = true; } else if(frame.getCommand().equals(COMMAND_MESSAGE)){ String subscription = frame.getHeaders().get(SUBSCRIPTION_SUBSCRIPTION); ListenerSubscription onReceive = Stomp.this.subscriptions.get(subscription).getCallback(); if(onReceive != null){ onReceive.onMessage(frame.getHeaders(), frame.getBody()); } else{ Log.e(TAG, "Error : Subscription with id = " + subscription + " had not been subscribed"); //ACTION TO DETERMINE TO MANAGE SUBCRIPTION ERROR } } else if(frame.getCommand().equals(COMMAND_RECEIPT)){ //I DON'T KNOW WHAT A RECEIPT STOMP MESSAGE IS } else if(frame.getCommand().equals(COMMAND_ERROR)){ Log.e(TAG, "Error : Headers = " + frame.getHeaders() + ", Body = " + frame.getBody()); //ACTION TO DETERMINE TO MANAGE ERROR MESSAGE } else { } if(isMessageConnected) Stomp.this.subscribe(); } @Override public void onClose(){ if(connection == DECONNECTED_FROM_APP){ Log.d(TAG, "Web Socket disconnected"); disconnectFromApp(); } else{ Log.w(TAG, "Problem : Web Socket disconnected whereas Stomp disconnect method has never " + "been called."); disconnectFromServer(); } } @Override public void onPing() { } @Override public void onPong() { } @Override public void onError(IOException e) { Log.e(TAG, "Error : " + e.getMessage()); } }); } catch (URISyntaxException e) { e.printStackTrace(); } } /** * Send a message to server thanks to websocket * * @param command * one of a frame property, see {@link Frame} for more details * @param headers * one of a frame property, see {@link Frame} for more details * @param body * one of a frame property, see {@link Frame} for more details */ private void transmit(String command, Map&lt;String, String&gt; headers, String body){ String out = Frame.marshall(command, headers, body); Log.d(TAG, "&gt;&gt;&gt; " + out); while (true) { if (out.length() &gt; this.maxWebSocketFrameSize) { this.websocket.send(out.substring(0, this.maxWebSocketFrameSize)); out = out.substring(this.maxWebSocketFrameSize); } else { this.websocket.send(out); break; } } } /** * Set up a web socket connection with a server */ public void connect(){ if(this.connection != CONNECTED){ Log.d(TAG, "Opening Web Socket..."); try{ this.websocket.connect(); } catch (Exception e){ Log.w(TAG, "Impossible to establish a connection : " + e.getClass() + ":" + e.getMessage()); } } } /** * disconnection come from the server, without any intervention of client side. Operations order is very important */ private void disconnectFromServer(){ if(this.connection == CONNECTED){ this.connection = DECONNECTED_FROM_OTHER; this.websocket.close(); this.networkListener.onState(this.connection); } } /** * disconnection come from the app, because the public method disconnect was called */ private void disconnectFromApp(){ if(this.connection == DECONNECTED_FROM_APP){ this.websocket.close(); this.networkListener.onState(this.connection); } } /** * Close the web socket connection with the server. Operations order is very important */ public void disconnect(){ if(this.connection == CONNECTED){ this.connection = DECONNECTED_FROM_APP; transmit(COMMAND_DISCONNECT, null, null); } } /** * Send a simple message to the server thanks to the body parameter * * * @param destination * The destination through a Stomp message will be send to the server * @param headers * headers of the message * @param body * body of a message */ public void send(String destination, Map&lt;String,String&gt; headers, String body){ if(this.connection == CONNECTED){ if(headers == null) headers = new HashMap&lt;String, String&gt;(); if(body == null) body = ""; headers.put(SUBSCRIPTION_DESTINATION, destination); transmit(COMMAND_SEND, headers, body); } } /** * Allow a client to send a subscription message to the server independently of the initialization of the web socket. * If connection have not been already done, just save the subscription * * @param subscription * a subscription object */ public void subscribe(Subscription subscription){ subscription.setId(PREFIX_ID_SUBSCIPTION + this.counter++); this.subscriptions.put(subscription.getId(), subscription); if(this.connection == CONNECTED){ Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(SUBSCRIPTION_ID, subscription.getId()); headers.put(SUBSCRIPTION_DESTINATION, subscription.getDestination()); subscribe(headers); } } /** * Subscribe to a Stomp channel, through messages will be send and received. A message send from a determine channel * can not be receive in an another. * */ private void subscribe(){ if(this.connection == CONNECTED){ for(Subscription subscription : this.subscriptions.values()){ Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(SUBSCRIPTION_ID, subscription.getId()); headers.put(SUBSCRIPTION_DESTINATION, subscription.getDestination()); subscribe(headers); } } } /** * Send the subscribe to the server with an header * @param headers * header of a subscribe STOMP message */ private void subscribe(Map&lt;String, String&gt; headers){ transmit(COMMAND_SUBSCRIBE, headers, null); } /** * Destroy a subscription with its id * * @param id * the id of the subscription. This id is automatically setting up in the subscribe method */ public void unsubscribe(String id){ if(this.connection == CONNECTED){ Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); headers.put(SUBSCRIPTION_ID, id); this.subscriptions.remove(id); this.transmit(COMMAND_UNSUBSCRIBE, headers, null); } } } </code></pre> <p>This one is the Frame of a Stomp message :</p> <pre><code>import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Frame { // private final static String CONTENT_LENGTH = "content-length"; private String command; private Map&lt;String, String&gt; headers; private String body; /** * Constructor of a Frame object. All parameters of a frame can be instantiate * * @param command * @param headers * @param body */ public Frame(String command, Map&lt;String, String&gt; headers, String body){ this.command = command; this.headers = headers != null ? headers : new HashMap&lt;String, String&gt;(); this.body = body != null ? body : ""; } public String getCommand(){ return command; } public Map&lt;String, String&gt; getHeaders(){ return headers; } public String getBody(){ return body; } /** * Transform a frame object into a String. This method is copied on the objective C one, in the MMPReactiveStompClient * library * @return a frame object convert in a String */ private String toStringg(){ String strLines = this.command; strLines += Byte.LF; for(String key : this.headers.keySet()){ strLines += key + ":" + this.headers.get(key); strLines += Byte.LF; } strLines += Byte.LF; strLines += this.body; strLines += Byte.NULL; return strLines; } /** * Create a frame from a received message. This method is copied on the objective C one, in the MMPReactiveStompClient * library * * @param data * a part of the message received from network, which represented a frame * @return * An object frame */ public static Frame fromString(String data){ List&lt;String&gt; contents = new ArrayList&lt;String&gt;(Arrays.asList(data.split(Byte.LF))); while(contents.size() &gt; 0 &amp;&amp; contents.get(0).equals("")){ contents.remove(0); } String command = contents.get(0); Map&lt;String, String&gt; headers = new HashMap&lt;String, String&gt;(); String body = ""; contents.remove(0); boolean hasHeaders = false; for(String line : contents){ if(hasHeaders){ for(int i=0; i &lt; line.length(); i++){ Character c = line.charAt(i); if(!c.equals('\0')) body += c; } } else{ if(line.equals("")){ hasHeaders = true; } else { String[] header = line.split(":"); headers.put(header[0], header[1]); } } } return new Frame(command, headers, body); } // No need this method, a single frame will be always be send because body of the message will never be excessive // /** // * Transform a message received from server in a Set of objects, named frame, manageable by java // * // * @param datas // * message received from network // * @return // * a Set of Frame // */ // public static Set&lt;Frame&gt; unmarshall(String datas){ // String data; // String[] ref = datas.split(Byte.NULL + Byte.LF + "*");//NEED TO VERIFY THIS PARAMETER // Set&lt;Frame&gt; results = new HashSet&lt;Frame&gt;(); // // for (int i = 0, len = ref.length; i &lt; len; i++) { // data = ref[i]; // // if ((data != null ? data.length() : 0) &gt; 0){ // results.add(unmarshallSingle(data));//"unmarshallSingle" is the old name method for "fromString" // } // } // return results; // } /** * Create a frame with based fame component and convert them into a string * * @param command * @param headers * @param body * @return a frame object convert in a String, thanks to &lt;code&gt;toStringg()&lt;/code&gt; method */ public static String marshall(String command, Map&lt;String, String&gt; headers, String body){ Frame frame = new Frame(command, headers, body); return frame.toStringg(); } private class Byte { public static final String LF = "\n"; public static final String NULL = "\0"; } } </code></pre> <p>This one is an object used to establish a subscription via the stomp protocol :</p> <pre><code>public class Subscription { private String id; private String destination; private ListenerSubscription callback; public Subscription(String destination, ListenerSubscription callback){ this.destination = destination; this.callback = callback; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDestination() { return destination; } public ListenerSubscription getCallback() { return callback; } } </code></pre> <p>At least, there are two interfaces used as the "Run" java class, to listen web socket network and a given subscription canal</p> <pre><code>public interface ListenerWSNetwork { public void onState(int state); } import java.util.Map; public interface ListenerSubscription { public void onMessage(Map&lt;String, String&gt; headers, String body); } </code></pre> <p>For more information, don't hesitate to ask me.</p>
1,413,753
creating an image in php, display works, saving to file does not
<p>I am creating an image via a php script using imagepng. This works fine and displays well on the website. even saving-as gives me a valid .png file</p> <pre><code>header( "Content-type: image/png" ); imagepng($my_img); $save = "../sigs/". strtolower($name) .".png"; //imagepng($my_img, $save, 0, NULL); imagepng($my_img, $save); </code></pre> <p>This is the end part of the code I use to generate the file and return it as picture on the website. but both options (tried the one marked out as well) dont save the file to the webserver for later use. The folder where the file is written is even set to chmod 777 at the moment to rule out any issues on that front. the $name is for sure a valid string without spaces.</p>
1,414,097
4
2
null
2009-09-11 23:44:16.913 UTC
4
2017-03-01 19:05:20.01 UTC
2009-09-11 23:59:23.493 UTC
null
9,314
null
156,455
null
1
15
php|image
53,798
<p>Make sure that PHP has permissions to write files to that folder. chmod probably only affects FTP users or particular users.</p> <p>And try one at a time. i.e.:</p> <pre><code>header( "Content-type: image/png" ); imagepng($my_img); </code></pre> <p>then</p> <pre><code>$save = "../sigs/". strtolower($name) .".png"; imagepng($my_img, $save); </code></pre> <p>So that you can isolate errors.</p> <p>Attempt saving in the same folder as the script first, see if there's any problem.</p> <pre><code>$save = strtolower($name) .".png"; imagepng($my_img, $save); </code></pre>
10,484,607
PHP sort array alphabetically using a subarray value
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php">How can I sort arrays and data in PHP?</a><br> <a href="https://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php">How do I sort a multidimensional array in php</a><br> <a href="https://stackoverflow.com/questions/2477496/php-sort-array-by-subarray-value">PHP Sort Array By SubArray Value</a><br> <a href="https://stackoverflow.com/questions/2699086/php-sort-multidimensional-array-by-value">PHP sort multidimensional array by value</a> </p> </blockquote> <p>My array looks like:</p> <pre><code>Array( [0] =&gt; Array( [name] =&gt; Bill [age] =&gt; 15 ), [1] =&gt; Array( [name] =&gt; Nina [age] =&gt; 21 ), [2] =&gt; Array( [name] =&gt; Peter [age] =&gt; 17 ) ); </code></pre> <p>I would like to sort them in alphabetic order based on their name. I saw <a href="https://stackoverflow.com/questions/2477496/php-sort-array-by-subarray-value">PHP Sort Array By SubArray Value</a> but it didn't help much. Any ideas how to do this?</p>
10,484,863
2
2
null
2012-05-07 15:17:41.62 UTC
11
2018-02-28 13:36:41.783 UTC
2018-02-28 13:36:41.783 UTC
null
476
null
1,405,450
null
1
74
php|arrays
84,257
<p>Here is your answer and it works 100%, I've tested it.</p> <pre><code>&lt;?php $a = Array( 1 =&gt; Array( 'name' =&gt; 'Peter', 'age' =&gt; 17 ), 0 =&gt; Array( 'name' =&gt; 'Nina', 'age' =&gt; 21 ), 2 =&gt; Array( 'name' =&gt; 'Bill', 'age' =&gt; 15 ), ); function compareByName($a, $b) { return strcmp($a["name"], $b["name"]); } usort($a, 'compareByName'); /* The next line is used for debugging, comment or delete it after testing */ print_r($a); </code></pre>
10,822,464
Access denied for enabled xp_cmdshell for the admin user
<p>I'm using xp_cmdshell within a database trigger to launch a exe file. </p> <p>xp_cmdshell is enabled(it can execute simple cmd command like 'echo'). But when I try to launch the exe through xp_cmdshell, the access is denied. </p> <p>I am the database administrator. And I can launch the exe through cmd directly. Anyone know why I get denied and how to fix it?</p>
10,822,577
7
3
null
2012-05-30 18:53:10.16 UTC
1
2021-12-14 16:15:20.207 UTC
2012-05-30 19:18:57.617 UTC
null
935,730
null
935,730
null
1
6
sql-server|windows|sql-server-2008|permissions|xp-cmdshell
50,721
<p>Likely insufficient NTFS permissions. Make sure the 'user account' that the SQL Server is running as, has permission (Read+Execute) to the *.EXE (and any dependent files)</p>
36,376,146
_reactDom2.default.render is not a function
<p>consider the following react code</p> <p>the main.js file is:</p> <pre><code>import React from 'react'; import ReactDOM from 'react-dom'; import Maincontainner from './maincontainner'; ReactDOM.render( &lt;div&gt; &lt;h1&gt;News&lt;/h1&gt; &lt;Maincontainner/&gt; &lt;/div&gt;, document.getElementById('content') ); </code></pre> <p>and the component is:</p> <pre><code>import React from 'react'; export default class Maincontainner extends React.Component{ render() { console.log("I am here"); return (&lt;dev&gt; Salman is here &lt;/dev&gt;); } } </code></pre> <p>the problem is, when i run the application, i face with following error in my console:</p> <pre><code>Uncaught TypeError: _reactDom2.default.render is not a function </code></pre> <p>and here is the dependencies</p> <pre><code>"dependencies": { "webpack": "^1.12.14", "webpack-dev-server": "^1.14.1", "react" : "^0.14.7", "react-dom" : "^0.14.7", "babel-cli": "^6.5.1", "babel-preset-es2015": "^6.5.0", "babel-loader": "^6.2.1", "babel-preset-react": "^6.3.13", "babelify": "^7.2.0" } </code></pre> <p>Update: webpack.config.json</p> <pre><code>module.exports={ entry: './js/main.js', output:{ filename: 'bundle.js' }, module: { loaders: [ { test: /.js?$/, loader: 'babel', exclude: /node_modules/, query: { presets: ['es2015', 'react'] } } ] }, devServer:{ port:3000 } }; </code></pre> <p>I have also 1 .babelrc file</p> <pre><code>{ "presets": ["es2015", "react"] } </code></pre>
39,157,549
9
14
null
2016-04-02 16:56:42.41 UTC
5
2022-04-28 08:50:05.097 UTC
2016-04-02 17:53:10.253 UTC
null
1,953,504
null
1,953,504
null
1
44
reactjs
62,108
<p>You can change something in your <code>Maincontainner</code> component.</p> <ol> <li>Add it top: <code>import ReactDOM from 'react-dom';</code></li> <li>Change <code>render</code> to <code>ReactDOM.render</code></li> </ol>
49,069,363
AWS Lambda - How to stop retries when there is a failure
<p>I know that when a Lambda function fails (for example when there is a time out), it tries to run the function 3 more times again. Is there any way to avoid this behavior? I' have been reading the documentation, but didn't find anyting about this.</p> <p>Thanks!</p>
50,627,455
9
3
null
2018-03-02 12:42:17.143 UTC
9
2020-07-02 13:14:24.013 UTC
null
null
null
null
6,833,121
null
1
39
amazon-web-services|aws-lambda
39,239
<p><strong>EDITED</strong>: It's now possible to change the lambda settings to disable retries (see <a href="https://aws.amazon.com/about-aws/whats-new/2019/11/aws-lambda-supports-max-retry-attempts-event-age-asynchronous-invocations/?nc1=h_ls" rel="noreferrer">announcement</a>)</p> <hr /> <p><strong>Original answer</strong>:</p> <p>There isn't a way to disable retry behavior of Lambda functions. I suggest two options to deal with that:</p> <ol> <li>Make your Lambda able to handle retry cases correctly. You can use context.AwsRequestId (or corresponding field) that will be the same when a Lambda is retried.</li> <li>Put your Lambda inside a state machine (using AWS Step Functions). You can only then disable retries. <a href="https://epsagon.com/blog/how-to-handle-aws-lambda-errors-like-a-pro" rel="noreferrer">This blog post</a> I've written gives a more general explanation.</li> </ol>
7,344,309
Concatenating strings with `if` statements in JavaScript
<p>I'm attempting to set up a script to concatenate some variables inside a string <em>if they exist</em>, in order to place the appropriate metadata tags into a rendered HTML document.</p> <p>My concatenation code is:</p> <pre class="lang-js prettyprint-override"><code>data = "&lt;html&gt;\n&lt;head&gt;\n" + "&lt;/head&gt;\n&lt;body&gt;\n\n" + paras.join("\n\n") + "\n\n&lt;/body&gt;\n&lt;/html&gt;"; </code></pre> <p>I'm trying to add <code>if</code> statements like the following into it (between the first and second items):</p> <pre class="lang-js prettyprint-override"><code>if (typeof metadata_title !== "undefined") { "&lt;title&gt;" + metadata_title + "&lt;/title&gt;\n" } if (typeof metadata_author !== "undefined") { "&lt;meta name=\"author\" content=\"" + metadata_author + "\"&gt;&lt;/meta&gt;\n" } if (typeof metadata_date !== "undefined") { "&lt;meta name=\"date\" content=\"" + metadata_date + "\"&gt;&lt;/meta&gt;\n" } </code></pre> <p>But I can't add any of these statements directly into the concatenation code (it throws an error: <code>Unexpected token (</code>).</p> <p>How best would I go about adding statements such as these into my concatenation string?</p>
7,344,366
5
0
null
2011-09-08 07:01:48.87 UTC
5
2019-12-11 10:18:54.987 UTC
2019-12-11 10:18:54.987 UTC
null
421,749
null
365,975
null
1
29
javascript|string|concatenation|string-concatenation
49,961
<p>I'd use a <a href="http://en.wikipedia.org/wiki/Ternary_operation" rel="noreferrer">ternary operator</a>:</p> <pre><code>data = "&lt;html&gt;\n" + "&lt;head&gt;\n" + ( typeof metadata_title !== "undefined" ? "&lt;title&gt;" + metadata_title + "&lt;/title&gt;\n" : "" ) + ( typeof metadata_author !== "undefined" ? "&lt;meta name=\"author\" content=\"" + metadata_author + "\"&gt;&lt;/meta&gt;\n" : "" ) + ( typeof metadata_date !== "undefined" ? "&lt;meta name=\"date\" content=\"" + metadata_date + "\"&gt;&lt;/meta&gt;\n" : "" ) + "&lt;/head&gt;\n" + "&lt;body&gt;\n" + "\n" + paras.join("\n\n") + "\n" + "\n" + "&lt;/body&gt;\n" + "&lt;/html&gt;" ; </code></pre>
7,221,833
How can I call a method on each element of a List?
<p>Suppose that I have a list of cars :</p> <pre><code>public class Car { private String brand; private String name; private String color; public Car() { // ... } public getName() { return name; } // ... } </code></pre> <hr> <pre><code>// Suppose that I have already init the list of car List&lt;Car&gt; cars = //... List&lt;String&gt; names = new ArrayList&lt;String&gt;(); for (Car c : cars ) { names.add(c.getName()); } </code></pre> <p>How can I shorten the code above ? In a nutshell, How can I call a method on each element of a List ?</p> <p>For example, in Python :</p> <pre><code>[car.name for car in cars] </code></pre>
7,222,256
6
0
null
2011-08-28 15:24:02.39 UTC
6
2020-09-06 07:38:10.387 UTC
null
null
null
null
259,576
null
1
53
java|list|list-comprehension
104,455
<p><strong>UPDATE:</strong></p> <p>See aaiezza's <a href="https://stackoverflow.com/a/20684006/697449">answer</a> for a Java 8 solution using a lambda expression.</p> <p><strong>Original pre-Java 8 answer:</strong></p> <p>The effect can be achieved with Guava, the <code>Function</code> implementation is already more verbose than what you have:</p> <pre><code>List&lt;Car&gt; cars = //... Function&lt;Car, String&gt; carsToNames = new Function&lt;Car, String&gt;() { @Override public String apply(Car car) { return car.getName(); } } List&lt;String&gt; names = Lists.transform(cars, carsToNames); </code></pre> <p>(Keep in mind that <a href="https://google.github.io/guava/releases/22.0/api/docs/com/google/common/collect/Lists.html#transform-java.util.List-com.google.common.base.Function-" rel="noreferrer"><code>Lists.transform</code></a> returns a view that will apply the function lazily - if you want an immediate copy, you need to copy the returned list into a new list.)</p> <p>So this doesn't help you shorten your code, but it's an example of how verbose it is to achieve your desired affect in Java.</p> <p><strong>Edit:</strong> You might have a look at <a href="http://code.google.com/p/lambdaj/" rel="noreferrer">lambdaj</a>, a library that seems to approach what you're looking for. I haven't tried this out myself, but the homepage shows this example:</p> <pre><code>List&lt;Person&gt; personInFamily = asList(new Person("Domenico"), new Person("Mario"), new Person("Irma")); forEach(personInFamily).setLastName("Fusco"); </code></pre>
7,279,887
What is the use of a private static variable in Java?
<p>If a variable is declared as <code>public static varName;</code>, then I can access it from anywhere as <code>ClassName.varName</code>. I am also aware that static members are shared by all instances of a class and are not reallocated in each instance.</p> <p>Is declaring a variable as <code>private static varName;</code> any different from declaring a variable <code>private varName;</code>?</p> <p>In both cases it cannot be accessed as <code>ClassName.varName</code> or as <code>ClassInstance.varName</code> from any other class.</p> <p>Does declaring the variable as static give it other special properties?</p>
7,279,918
19
1
null
2011-09-02 06:24:14.547 UTC
79
2020-10-26 16:05:49.087 UTC
2016-06-09 22:29:01.613 UTC
null
2,446,208
null
703,851
null
1
180
java|variables|static|private
374,324
<p>Of course it can be accessed as <code>ClassName.var_name</code>, but only from inside the class in which it is defined - that's because it is defined as <code>private</code>.</p> <p><code>public static</code> or <code>private static</code> variables are often used for constants. For example, many people don't like to "hard-code" constants in their code; they like to make a <code>public static</code> or <code>private static</code> variable with a meaningful name and use that in their code, which should make the code more readable. (You should also make such constants <code>final</code>).</p> <p>For example:</p> <pre><code>public class Example { private final static String JDBC_URL = "jdbc:mysql://localhost/shopdb"; private final static String JDBC_USERNAME = "username"; private final static String JDBC_PASSWORD = "password"; public static void main(String[] args) { Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD); // ... } } </code></pre> <p>Whether you make it <code>public</code> or <code>private</code> depends on whether you want the variables to be visible outside the class or not.</p>
14,297,079
Why are Clojure stacktraces so long?
<p>I've written some toy interpreters/compilers in the past, so I associate stacktraces referencing lines in compiler source files with compiler bugs.</p> <p>If I add the following bad function definition to my compojure project:</p> <pre><code>(defn dodgy-map [] {:1 :2 :3}) </code></pre> <p>Lein refuses to start:</p> <pre><code>$ lein ring server-headless Exception in thread "main" java.lang.RuntimeException: Map literal must contain an even number of forms, compiling:(one_man_wiki/views.clj:19) at clojure.lang.Compiler.load(Compiler.java:6958) at clojure.lang.RT.loadResourceScript(RT.java:359) at clojure.lang.RT.loadResourceScript(RT.java:350) at clojure.lang.RT.load(RT.java:429) at clojure.lang.RT.load(RT.java:400) at clojure.core$load$fn__4890.invoke(core.clj:5415) at clojure.core$load.doInvoke(core.clj:5414) at clojure.lang.RestFn.invoke(RestFn.java:408) at clojure.core$load_one.invoke(core.clj:5227) at clojure.core$load_lib.doInvoke(core.clj:5264) at clojure.lang.RestFn.applyTo(RestFn.java:142) at clojure.core$apply.invoke(core.clj:603) at clojure.core$load_libs.doInvoke(core.clj:5298) at clojure.lang.RestFn.applyTo(RestFn.java:137) at clojure.core$apply.invoke(core.clj:603) at clojure.core$require.doInvoke(core.clj:5381) at clojure.lang.RestFn.invoke(RestFn.java:457) at one_man_wiki.handler$eval1564$loading__4784__auto____1565.invoke(handler.clj:1) at one_man_wiki.handler$eval1564.invoke(handler.clj:1) at clojure.lang.Compiler.eval(Compiler.java:6511) at clojure.lang.Compiler.eval(Compiler.java:6501) at clojure.lang.Compiler.load(Compiler.java:6952) at clojure.lang.RT.loadResourceScript(RT.java:359) at clojure.lang.RT.loadResourceScript(RT.java:350) at clojure.lang.RT.load(RT.java:429) at clojure.lang.RT.load(RT.java:400) at clojure.core$load$fn__4890.invoke(core.clj:5415) at clojure.core$load.doInvoke(core.clj:5414) at clojure.lang.RestFn.invoke(RestFn.java:408) at clojure.core$load_one.invoke(core.clj:5227) at clojure.core$load_lib.doInvoke(core.clj:5264) at clojure.lang.RestFn.applyTo(RestFn.java:142) at clojure.core$apply.invoke(core.clj:603) at clojure.core$load_libs.doInvoke(core.clj:5298) at clojure.lang.RestFn.applyTo(RestFn.java:137) at clojure.core$apply.invoke(core.clj:603) at clojure.core$require.doInvoke(core.clj:5381) at clojure.lang.RestFn.invoke(RestFn.java:421) at user$eval1.invoke(NO_SOURCE_FILE:1) at clojure.lang.Compiler.eval(Compiler.java:6511) at clojure.lang.Compiler.eval(Compiler.java:6500) at clojure.lang.Compiler.eval(Compiler.java:6477) at clojure.core$eval.invoke(core.clj:2797) at clojure.main$eval_opt.invoke(main.clj:297) at clojure.main$initialize.invoke(main.clj:316) at clojure.main$null_opt.invoke(main.clj:349) at clojure.main$main.doInvoke(main.clj:427) at clojure.lang.RestFn.invoke(RestFn.java:421) at clojure.lang.Var.invoke(Var.java:419) at clojure.lang.AFn.applyToHelper(AFn.java:163) at clojure.lang.Var.applyTo(Var.java:532) at clojure.main.main(main.java:37) Caused by: java.lang.RuntimeException: Map literal must contain an even number of forms at clojure.lang.Util.runtimeException(Util.java:170) at clojure.lang.LispReader$MapReader.invoke(LispReader.java:1071) at clojure.lang.LispReader.readDelimitedList(LispReader.java:1126) at clojure.lang.LispReader$ListReader.invoke(LispReader.java:962) at clojure.lang.LispReader.read(LispReader.java:180) at clojure.lang.Compiler.load(Compiler.java:6949) ... 51 more </code></pre> <p>If I reference a variable that doesn't exist:</p> <pre><code>(defn no-such-variable [] i-dont-exist) </code></pre> <p>I get an equally ginormous traceback:</p> <pre><code>Exception in thread "main" java.lang.RuntimeException: Unable to resolve symbol: i-dont-exist in this context, compiling:(one_man_wiki/views.clj:18) at clojure.lang.Compiler.analyze(Compiler.java:6281) at clojure.lang.Compiler.analyze(Compiler.java:6223) at clojure.lang.Compiler$BodyExpr$Parser.parse(Compiler.java:5618) at clojure.lang.Compiler$FnMethod.parse(Compiler.java:5054) at clojure.lang.Compiler$FnExpr.parse(Compiler.java:3674) at clojure.lang.Compiler.analyzeSeq(Compiler.java:6453) at clojure.lang.Compiler.analyze(Compiler.java:6262) at clojure.lang.Compiler.analyzeSeq(Compiler.java:6443) at clojure.lang.Compiler.analyze(Compiler.java:6262) at clojure.lang.Compiler.access$100(Compiler.java:37) at clojure.lang.Compiler$DefExpr$Parser.parse(Compiler.java:518) at clojure.lang.Compiler.analyzeSeq(Compiler.java:6455) at clojure.lang.Compiler.analyze(Compiler.java:6262) at clojure.lang.Compiler.analyze(Compiler.java:6223) at clojure.lang.Compiler.eval(Compiler.java:6515) at clojure.lang.Compiler.load(Compiler.java:6952) at clojure.lang.RT.loadResourceScript(RT.java:359) at clojure.lang.RT.loadResourceScript(RT.java:350) at clojure.lang.RT.load(RT.java:429) at clojure.lang.RT.load(RT.java:400) at clojure.core$load$fn__4890.invoke(core.clj:5415) at clojure.core$load.doInvoke(core.clj:5414) at clojure.lang.RestFn.invoke(RestFn.java:408) at clojure.core$load_one.invoke(core.clj:5227) at clojure.core$load_lib.doInvoke(core.clj:5264) at clojure.lang.RestFn.applyTo(RestFn.java:142) at clojure.core$apply.invoke(core.clj:603) at clojure.core$load_libs.doInvoke(core.clj:5298) at clojure.lang.RestFn.applyTo(RestFn.java:137) at clojure.core$apply.invoke(core.clj:603) at clojure.core$require.doInvoke(core.clj:5381) at clojure.lang.RestFn.invoke(RestFn.java:457) at one_man_wiki.handler$eval1564$loading__4784__auto____1565.invoke(handler.clj:1) at one_man_wiki.handler$eval1564.invoke(handler.clj:1) at clojure.lang.Compiler.eval(Compiler.java:6511) at clojure.lang.Compiler.eval(Compiler.java:6501) at clojure.lang.Compiler.load(Compiler.java:6952) at clojure.lang.RT.loadResourceScript(RT.java:359) at clojure.lang.RT.loadResourceScript(RT.java:350) at clojure.lang.RT.load(RT.java:429) at clojure.lang.RT.load(RT.java:400) at clojure.core$load$fn__4890.invoke(core.clj:5415) at clojure.core$load.doInvoke(core.clj:5414) at clojure.lang.RestFn.invoke(RestFn.java:408) at clojure.core$load_one.invoke(core.clj:5227) at clojure.core$load_lib.doInvoke(core.clj:5264) at clojure.lang.RestFn.applyTo(RestFn.java:142) at clojure.core$apply.invoke(core.clj:603) at clojure.core$load_libs.doInvoke(core.clj:5298) at clojure.lang.RestFn.applyTo(RestFn.java:137) at clojure.core$apply.invoke(core.clj:603) at clojure.core$require.doInvoke(core.clj:5381) at clojure.lang.RestFn.invoke(RestFn.java:421) at user$eval1.invoke(NO_SOURCE_FILE:1) at clojure.lang.Compiler.eval(Compiler.java:6511) at clojure.lang.Compiler.eval(Compiler.java:6500) at clojure.lang.Compiler.eval(Compiler.java:6477) at clojure.core$eval.invoke(core.clj:2797) at clojure.main$eval_opt.invoke(main.clj:297) at clojure.main$initialize.invoke(main.clj:316) at clojure.main$null_opt.invoke(main.clj:349) at clojure.main$main.doInvoke(main.clj:427) at clojure.lang.RestFn.invoke(RestFn.java:421) at clojure.lang.Var.invoke(Var.java:419) at clojure.lang.AFn.applyToHelper(AFn.java:163) at clojure.lang.Var.applyTo(Var.java:532) at clojure.main.main(main.java:37) Caused by: java.lang.RuntimeException: Unable to resolve symbol: i-dont-exist in this context at clojure.lang.Util.runtimeException(Util.java:170) at clojure.lang.Compiler.resolveIn(Compiler.java:6766) at clojure.lang.Compiler.resolve(Compiler.java:6710) at clojure.lang.Compiler.analyzeSymbol(Compiler.java:6671) at clojure.lang.Compiler.analyze(Compiler.java:6244) ... 66 more </code></pre> <p>Why doesn't the Clojure compiler raise a <code>ClojureSyntaxError</code> and a <code>ClojureNameError</code> that could be caught at the top level and a simple error shown? These are common developer errors during development.</p> <p>If the long tracebacks are useful in some circumstances, why are they truncated?</p> <p><strong>Edit</strong>: What I'm looking for in an answer:</p> <ol> <li>Are there situations (some metaprogramming with Java interop perhaps?) when getting a traceback referencing clojure.lang is useful?</li> <li>(Related) Are there any technical constraints preventing adding a <code>ClojureSyntaxError</code> as I described above? Is it worth me opening an issue on the Clojure bug tracker? (update: I've <a href="http://dev.clojure.org/jira/browse/CLJ-1155" rel="noreferrer">opened CLJ-1155</a>)</li> <li>How do experience Clojure programmers read these tracebacks? Are there tools to help? Does everyone use clj-stacktrace?</li> </ol>
14,298,576
2
4
null
2013-01-12 19:27:31.79 UTC
4
2015-07-10 08:09:49.66 UTC
2013-11-05 12:03:21.733 UTC
null
509,706
null
509,706
null
1
33
clojure
1,920
<p>Replying to your numbered points,</p> <ol> <li><p>it is idiomatic in Clojure to interoperate directly with Java libraries, so getting the full Java stacktrace can be helpful if you are calling into Java objects in some unexpected or unsupported way.</p></li> <li><p>Sounds like a good idea; I've often at least wished for a settable option which would allow me to see only the parts of stacktraces originating in my own code, suppressing all the underlying language layers.</p></li> <li><p>I usually just do it the hard way and pore over the stacktrace to get the line in my program that barfed, tuning out the <code>clojure.*</code> parts (and I usually test each minute change so I have a pretty good idea what change caused the problem). Some of the Emacs and Eclipse tools I've used show you only the actual error and not the whole stacktrace; I generally find this to be more helpful. </p> <p>At Clojure/west in 2012, @chouser gave <a href="https://github.com/strangeloop/clojurewest2012-slides/blob/master/StackTraces-Longbottom-Chouser.pdf" rel="noreferrer">a nice talk</a> [PDF] on the anatomy of stacktraces, explained how to read them, and introduced a promising-looking tool, which apparently still has not seen the light of day yet.</p></li> </ol> <p>Compared with, say, Python, whose stacktraces I find pretty user-friendly, I think stacktraces are a rough edge in Clojure, particularly for beginners. This is partly due to the "hosted" nature of the language, though I expect there are improvements which could be made without adding incidental complexity.</p>
13,965,877
The shortcut key to open console in Sublime Text 2 does not work
<p>I'm using Sublime Text 2 (version 2.0.1) on Windows 7, and I haven't installed any plugins for this software. I can use menu to open the console, but I cannot open console via <kbd>ctrl</kbd> + <kbd>`</kbd> shortcut. How to fix this problem?</p>
15,644,431
20
8
null
2012-12-20 05:27:49.207 UTC
13
2020-05-04 09:59:48.467 UTC
2014-04-28 18:06:07.54 UTC
null
1,696,030
null
1,396,077
null
1
51
sublimetext2
87,177
<h1>Magic Keyboard - US English - Apple</h1> <p>The title itself causes this answer to show up in Google search results for any operating system. So even though the details ask about Windows 7, I am including picture of the shortcut to the Mac because it will save some people a lot of time.<br /> <img src="https://i.stack.imgur.com/3md8M.jpg" alt="enter image description here" /></p>
14,347,611
jQuery + client-side template = "Syntax error, unrecognized expression"
<p>I just updated jQuery from 1.8.3 to 1.9, and it started crashing all of a sudden.</p> <p>This is my template:</p> <pre><code>&lt;script type="text/template" id="modal_template"&gt; &lt;div&gt;hello&lt;/div&gt; &lt;/script&gt; </code></pre> <p>This is how I read it:</p> <pre><code>modal_template_html = $("#modal_template").html(); </code></pre> <p>This is how I transform it into jQuery object (I need to use jQuery methods on it):</p> <pre><code>template = $(modal_template_html); </code></pre> <p>... and jQuery crashes!</p> <p>Error: Syntax error, unrecognized expression: &lt;div&gt;hello&lt;/div&gt;</p> <p>slice.call( docElem.childNodes, 0 )[0].nodeType;</p> <p>jquery-1.9.0.js (line 3811)</p> <p>However, if I declare template as a plain text variable, it starts working again:</p> <pre><code>var modal_template_html = '&lt;div&gt;hello&lt;/div&gt;'; </code></pre> <p>Can anyone help me to figure this out?</p> <p><strong>UPDATE</strong>: Jquery team heard and <a href="http://blog.jquery.com/2013/05/09/jquery-1-10-beta-1-released/">changed</a> things back to normal in 1.10:</p> <blockquote> <p>The biggest change you’re likely to see is that we’ve loosened up the criteria for HTML processing in $(), allowing leading spaces and newlines as we did before version 1.9</p> </blockquote>
14,349,083
6
5
null
2013-01-15 21:53:22.213 UTC
12
2017-06-20 08:52:03.103 UTC
2014-05-29 00:12:06.707 UTC
null
1,189,546
null
1,189,546
null
1
59
javascript|jquery|mustache
121,905
<p>Turns out string starting with a newline (or anything other than "&lt;") is not considered HTML string in jQuery 1.9</p> <p><a href="http://stage.jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring" rel="noreferrer">http://stage.jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring</a></p>
14,030,337
What's the difference between Void and no parameter?
<p>I have a class which defines two overloaded methods</p> <pre><code>public void handle(Void e) protected void handle() </code></pre> <p>Obviously they are different, especially <code>handle(Void e)</code> is <code>public</code>.</p> <p><br/> What's the difference between those two? </p> <p>How to call the first method? I am using <code>handle(null)</code> - is this correct?</p>
14,030,360
4
6
null
2012-12-25 11:45:42.563 UTC
14
2017-07-10 11:09:02.79 UTC
2013-01-20 13:25:03.65 UTC
null
256,196
null
1,136,700
null
1
67
java|void
24,671
<p>The first function is a function of a single argument, which must be provided and can only validly take the value <code>null</code>. Any value other than null will not compile. The second function doesn't take any argument and passing <code>null</code> to it would not compile.</p>
13,806,299
How can I create a self-signed certificate using C#?
<p>I need to create a self-signed certificate (for local encryption - it's not used to secure communications), using C#. </p> <p>I've seen some implementations that use <a href="http://www.daveamenta.com/2008-05/what-is-pinvoke-pinvoke/" rel="noreferrer">P/Invoke</a> with <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa379884%28v=vs.85%29.aspx" rel="noreferrer">Crypt32.dll</a>, but they are complicated and it's hard to update the parameters - and I would also like to avoid P/Invoke if at all possible.</p> <p>I don't need something that is cross platform - running only on Windows is good enough for me.</p> <p>Ideally, the result would be an X509Certificate2 object that I can use to insert into the Windows certificate store or export to a <a href="https://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions" rel="noreferrer">PFX</a> file.</p>
13,806,300
7
4
null
2012-12-10 17:46:24.083 UTC
57
2021-07-23 06:37:32.84 UTC
2019-11-19 11:44:58.163 UTC
null
63,550
null
53,538
null
1
91
c#|.net|certificate|self-signed
116,173
<p>This implementation uses the <code>CX509CertificateRequestCertificate</code> COM object (and friends - <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa377124%28v=vs.85%29.aspx" rel="noreferrer">MSDN doc</a>) from <code>certenroll.dll</code> to create a self signed certificate request and sign it. </p> <p>The example below is pretty straight forward (if you ignore the bits of COM stuff that goes on here) and there are a few parts of the code that are really optional (such as EKU) which are none-the-less useful and easy to adapt to your use.</p> <pre><code>public static X509Certificate2 CreateSelfSignedCertificate(string subjectName) { // create DN for subject and issuer var dn = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); // create a new private key for the certificate CX509PrivateKey privateKey = new CX509PrivateKey(); privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0"; privateKey.MachineContext = true; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG; privateKey.Create(); // Use the stronger SHA512 hashing algorithm var hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA512"); // add extended key usage if you want - look at MSDN for a list of possible OIDs var oid = new CObjectId(); oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server var oidlist = new CObjectIds(); oidlist.Add(oid); var eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.Subject = dn; cert.Issuer = dn; // the issuer and the subject are the same cert.NotBefore = DateTime.Now; // this cert expires immediately. Change to whatever makes sense for you cert.NotAfter = DateTime.Now; cert.X509Extensions.Add((CX509Extension)eku); // add the EKU cert.HashAlgorithm = hashobj; // Specify the hashing algorithm cert.Encode(); // encode the certificate // Do the final enrollment process var enroll = new CX509Enrollment(); enroll.InitializeFromRequest(cert); // load the certificate enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 // and install it back as the response enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption PFXExportOptions.PFXExportChainWithRoot); // instantiate the target class with the PKCS#12 data (and the empty password) return new System.Security.Cryptography.X509Certificates.X509Certificate2( System.Convert.FromBase64String(base64encoded), "", // mark the private key as exportable (this is usually what you want to do) System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable ); } </code></pre> <p>The result can be added to a certificate store using <code>X509Store</code> or exported using the <code>X509Certificate2</code> methods.</p> <p>For a fully managed and not tied to Microsoft's platform, and if you're OK with Mono's licensing, then you can look at <a href="http://code.ohloh.net/file?fid=hlZXds9VgYcE3MIgdWJfVBrCE-o&amp;cid=oX7t2cSLUiM&amp;s=X509CertificateBuilder&amp;mp=1&amp;ml=1&amp;me=1&amp;md=1&amp;browser=Default#L2" rel="noreferrer">X509CertificateBuilder</a> from <a href="http://www.mono-project.com/Cryptography#Assembly:_Mono.Security" rel="noreferrer">Mono.Security</a>. Mono.Security is standalone from Mono, in that it doesn't need the rest of Mono to run and can be used in any compliant .Net environment (e.g. Microsoft's implementation).</p>
30,174,042
How to switch themes (night mode) without restarting the activity?
<p>I have made a few apps that support multiple themes, but I always had to restart the app when user switches theme, because <code>setTheme()</code> needs to be called before <code>setContentView()</code>.</p> <p>I was okay with it, until I discovered this app. It can seamlessly switch between two themes, and with transitions/animations too!</p> <p><img src="https://i.stack.imgur.com/gHMpn.gif" alt="enter image description here"></p> <p>Please give me some hints on how this was implemented (and animations too). Thanks!</p>
41,301,512
6
5
null
2015-05-11 17:33:01.49 UTC
33
2021-08-24 17:31:44.22 UTC
2015-05-11 18:38:10.737 UTC
null
1,332,549
null
1,032,613
null
1
72
android|android-theme
30,067
<p>@Alexander Hanssen's answer basically has answered this... Don't know why it was not accepted... Maybe because of the finish()/startActivity(). I voted for it and I tried to comment but cannot...</p> <p>Anyway, I would do exactly what he described in terms of styles.</p> <pre><code>&lt;style name=&quot;AppThemeLight&quot; parent=&quot;Theme.AppCompat.Light&quot;&gt; &lt;!-- Customize your theme here. --&gt; &lt;item name=&quot;android:windowAnimationStyle&quot;&gt;@style/WindowAnimationTransition&lt;/item&gt; &lt;/style&gt; &lt;style name=&quot;AppThemeDark&quot; parent=&quot;Theme.AppCompat&quot;&gt; &lt;!-- Customize your theme here. --&gt; &lt;item name=&quot;android:windowAnimationStyle&quot;&gt;@style/WindowAnimationTransition&lt;/item&gt; &lt;/style&gt; &lt;!-- This will set the fade in animation on all your activities by default --&gt; &lt;style name=&quot;WindowAnimationTransition&quot;&gt; &lt;item name=&quot;android:windowEnterAnimation&quot;&gt;@android:anim/fade_in&lt;/item&gt; &lt;item name=&quot;android:windowExitAnimation&quot;&gt;@android:anim/fade_out&lt;/item&gt; &lt;/style&gt; </code></pre> <p>But instead of finish/start with new intent:</p> <pre><code>Intent intent = new Intent(this, &lt;yourclass&gt;.class); startActivity(intent); finish(); </code></pre> <p>I would do:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { // MUST do this before super call or setContentView(...) // pick which theme DAY or NIGHT from settings setTheme(someSettings.get(PREFFERED_THEME) ? R.style.AppThemeLight : R.style.AppThemeDark); super.onCreate(savedInstanceState); } // Somewhere in your activity where the button switches the theme btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // decide which theme to use DAY or NIGHT and save it someSettings.save(PREFFERED_THEME, isDay()); Activity.this.recreate(); } }); </code></pre> <p>The effect is as shown in the video...</p>
30,222,572
How to install QtDesigner?
<p>I just installed Qt 5.4.1 on Windows 7. And there is no QtDesigner. Also there is no QtDesigner in MaintenanceTool.<br> How can I install it?</p>
43,229,814
9
5
null
2015-05-13 18:26:21.017 UTC
14
2022-09-19 20:45:30.58 UTC
null
null
null
null
1,034,253
null
1
22
qt|qt-designer
108,203
<p>You can install and find QT Designer as follows (Windows environment):</p> <ul> <li>Install latest QT (I'm using 5.8) from <a href="https://www.qt.io/" rel="noreferrer">QT main site</a></li> <li>Make sure you include "Qt 5.8 MinGW" component</li> <li>QT Designer will be installed in <code>C:\Qt\5.8\mingw53_32\bin\designer.exe</code></li> <li>Note that the executable is named "designer.exe"</li> </ul> <p><strong>UPDATE</strong> - there is an easier way to install QT Designer without downloading GB's of data from QT:</p> <ul> <li><p>Install the latest version of "<strong>pyqt5-tools</strong>" using <code>pip install pyqt5-tools --pre</code></p></li> <li><p>The "designer.exe" will be installed in <code>...Lib\site-packages\pyqt5_tools</code></p></li> </ul>
9,224,773
Check if date is less than 1 hour ago?
<p>Is there a way to check if a date is less than 1 hour ago like this?</p> <pre class="lang-js prettyprint-override"><code>// old date var olddate = new Date(&quot;February 9, 2012, 12:15&quot;); // current date var currentdate = new Date(); if (olddate &gt;= currentdate - 1 hour) { alert(&quot;newer than 1 hour&quot;); else { alert(&quot;older than 1 hour&quot;); } </code></pre> <p>Also, different question - is there a way to add hours to a date like this?</p> <pre class="lang-js prettyprint-override"><code>var olddate = new Date(&quot;February 9, 2012, 12:15&quot;) + 15 HOURS; // output: February 10, 2012, 3:15 </code></pre>
9,224,799
7
1
null
2012-02-10 08:23:34.95 UTC
17
2022-06-09 06:08:26.76 UTC
2021-12-07 16:15:50.553 UTC
null
1,366,033
null
960,462
null
1
120
javascript|datetime
118,731
<p>Define</p> <pre><code>var ONE_HOUR = 60 * 60 * 1000; /* ms */ </code></pre> <p>then you can do</p> <pre><code>((new Date) - myDate) &lt; ONE_HOUR </code></pre> <p>To get one hour from a date, try</p> <pre><code>new Date(myDate.getTime() + ONE_HOUR) </code></pre>
49,716,583
How to temporarily switch profiles for AWS CLI?
<p>Updated answer (7/10/2021): For AWS CLI v1, do this:</p> <pre class="lang-sh prettyprint-override"><code>export AWS_DEFAULT_PROFILE=user2 </code></pre> <p>For AWS CLI v2, the following will work:</p> <pre class="lang-sh prettyprint-override"><code>export AWS_PROFILE=user2 </code></pre> <p>The full question is below for context:</p> <hr /> <p>(1.) After successfully configuring a second profile for the AWS CLI, I unsuccessfully tried to set the profile to user2 in my bash session with the following command:</p> <pre><code>export AWS_PROFILE=user2 </code></pre> <p>... per the advice here: <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html" rel="noreferrer">https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html</a></p> <p>(2.) The following command works:</p> <pre class="lang-sh prettyprint-override"><code>aws s3 ls --profile user2 </code></pre> <p>So I know that the AWS CLI and the user2 profile are both working on my computer.</p> <p>(3.) However, when I subsequently (that is, after entering &quot;export AWS_PROFILE=user2&quot;) try something like:</p> <pre class="lang-sh prettyprint-override"><code>aws s3 ls </code></pre> <p>... AWS's response assumes that I want to query it as the default user (NOT user2)</p> <p>(4.) So the only way I can use the user2 profile from the command line is by continuing to append &quot;--profile user2&quot; to every single command, which is tedious.</p> <p>(5.)</p> <pre class="lang-sh prettyprint-override"><code>echo $AWS_PROFILE </code></pre> <p>yields:</p> <pre class="lang-sh prettyprint-override"><code>&gt;&gt; user2 </code></pre> <p>, as expected.</p> <p>Any idea what's going on here? I'm sure I'm making some dumb mistake somewhere.</p>
49,748,262
8
11
null
2018-04-08 09:49:19.337 UTC
14
2022-04-02 02:09:19.427 UTC
2021-07-23 07:12:53.633 UTC
null
830,841
null
830,841
null
1
74
bash|shell|amazon-web-services|command-line|aws-cli
58,850
<p>For AWS CLI v1, the cleanest solution is:</p> <pre class="lang-sh prettyprint-override"><code>export AWS_DEFAULT_PROFILE=user2 </code></pre> <p>Afterward, commands like:</p> <pre><code>aws s3 ls </code></pre> <p>... are handled from the appropriate account.</p> <p>For AWS CLI v2, the following will work:</p> <pre class="lang-sh prettyprint-override"><code>export AWS_PROFILE=user2 </code></pre>
32,798,816
UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexException: Multiple dex files define
<p>When I add the configurations for <a href="https://developers.google.com/analytics/devguides/collection/android/v4/">google analytics</a> to my Android project and build the project I get the following error:</p> <pre><code>:app:transformClassesWithDexForDebug UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexException: Multiple dex files define Ljavax/inject/Inject; at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596) at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554) at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171) at com.android.dx.merge.DexMerger.merge(DexMerger.java:189) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:502) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334) at com.android.dx.command.dexer.Main.run(Main.java:277) at com.android.dx.command.dexer.Main.main(Main.java:245) at com.android.dx.command.Main.main(Main.java:106) FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:transformClassesWithDexForDebug'. &gt; com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2 * Try: Run with --info or --debug option to get more log output. * Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88) at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23) at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68) at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55) at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149) at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106) at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86) at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90) at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:54) at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28) at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:49) at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74) at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72) at org.gradle.util.Swapper.swap(Swapper.java:38) at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66) at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71) at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41) at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120) at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50) at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54) at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40) Caused by: org.gradle.internal.UncheckedException: com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2 at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:45) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:78) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:243) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:230) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61) ... 57 more Caused by: com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2 at com.android.build.gradle.internal.transforms.DexTransform.transform(DexTransform.java:411) at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:112) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75) ... 63 more Caused by: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2 at com.android.build.gradle.internal.process.GradleProcessResult.assertNormalExitValue(GradleProcessResult.java:42) at com.android.builder.core.AndroidBuilder.convertByteCode(AndroidBuilder.java:1325) at com.android.build.gradle.internal.transforms.DexTransform.transform(DexTransform.java:396) ... 65 more Caused by: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2 at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:365) at com.android.build.gradle.internal.process.GradleProcessResult.assertNormalExitValue(GradleProcessResult.java:40) ... 67 more </code></pre> <p><strong>What does this mean and how can I prevent this error?</strong></p>
33,786,747
13
4
null
2015-09-26 15:32:05.863 UTC
13
2019-07-22 10:07:04.197 UTC
2015-09-26 15:40:46.443 UTC
null
1,055,664
null
1,055,664
null
1
45
java|android|android-studio|gradle|google-analytics
72,336
<p>A little late to the game here but this is <strong>most likely</strong> a problem with the dependencies you have listed in your <code>build.gradle</code> file for you app. </p> <p>After lots of testing i successfully chased down my problem and believe it could be of help to others.</p> <p>Things I do not recommend:</p> <blockquote> <p>Unless you have an absolute <strong>need</strong> to enable multiDex in your build.gradle <strong>DO NOT DO IT</strong>, this is just stepping over the underlying problem in your app and not getting to the root of it. You are also unnecessarily increasing the size of your apk, and there could be unexpected crashes when there is a conflicting method in your dex file.</p> </blockquote> <p>Things to look out for:</p> <blockquote> <p>Check all your dependencies in your build.gradle file. Are you referencing a dependency that also includes a dependency you have already included? For example, if your including appcompat-v7 there is no need to include appcompat-v4 since v7 includes all features from v4.</p> </blockquote> <p><strong>WHAT I ACTUALLY FOUND (MY ISSUE causing my app to exceed method limit in my dex file) ----> GOOGLE PLAY SERVICES</strong></p> <blockquote> <p>If you do not need all the google play services library dependencies <strong>STAY AWAY</strong> from this line in your build.gradle <code>compile 'com.google.android.gms:play-services:8.3.0'</code> and instead just use what you need!!</p> </blockquote> <p>Google has a comprehensive list of the libraries for selectively compiling <strong><a href="https://developers.google.com/android/guides/setup">here</a></strong></p> <p>With all that said you probably only need to include this one line in gradle for your Google Analytics:</p> <pre><code> dependencies{ compile 'com.google.android.gms:play-services-analytics:8.3.0' } </code></pre> <p><strong>EDIT</strong></p> <p>Also, you can view the dependency tree by going to the root of your project (or using terminal in Android studio) and running:</p> <pre><code>./gradlew app:dependencies </code></pre> <p>Good Luck and happy coding!</p> <p><strong>Update</strong></p> <p>Now as of Android Studio 2.2 you no longer need to trial and error whether you need to use multi-dex in your application. Use the <a href="https://developer.android.com/studio/build/apk-analyzer.html#view_dex_files">Apk Analyzer</a> to see if its really needed!</p>
24,598,140
java.io.FileNotFoundException: class path resource [WEB-INF/classes/library.properties] cannot be opened because it does not exist
<p>In my Spring application, I have a simple properties file located in folder <code>WEB-INF\classes</code> so that it, the <code>DispatcherServlet</code> and various other config files are in the <code>classpath</code>.</p> <p>The props file is defined in the <code>DispatcherServlet</code> as:</p> <pre><code>&lt;bean id="propertiesFactory" class="org.springframework.beans.factory.config.PropertiesFactoryBean"&gt; &lt;property name="location"&gt; &lt;value&gt;/WEB-INF/classes/library.properties&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>The <code>propertiesFactory</code> bean is injected into a controller:</p> <pre><code>@Autowired private Properties propertiesFactory; </code></pre> <p>And used in a one of the controller's methods as:</p> <pre><code>if (adminPassword.equals(propertiesFactory.getProperty("adminPassword"))) { </code></pre> <p>This all works perfectly, except for a test program as follows which has line:</p> <pre><code>ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("library-servlet.xml"); </code></pre> <p>Which throws a <code>BeanCreationException</code>: </p> <pre><code>Injection of autowired dependencies failed </code></pre> <p>Because of:</p> <pre><code>java.io.FileNotFoundException: class path resource [WEB-INF/classes/library.properties] cannot be opened because it does not exist </code></pre> <p>But if the whole application can see the props file, why not this one program?</p>
24,598,145
1
3
null
2014-07-06 16:51:25.387 UTC
null
2014-07-06 16:52:39.697 UTC
null
null
null
null
953,331
null
1
4
java|spring|dependency-injection|properties-file
46,181
<p>Everything in <code>WEB-INF/classes</code> is added to the root of the classpath. As such, you need to refer to your resource simply as</p> <pre><code>library.properties </code></pre> <p>or better yet</p> <pre><code>classpath:library.properties </code></pre> <p>in</p> <pre><code>&lt;property name="location"&gt; &lt;value&gt;classpath:library.properties&lt;/value&gt; &lt;/property&gt; </code></pre> <p>You may find it useful to run</p> <pre><code>System.out.println(System.getProperty("java.class.path")); </code></pre> <p>and see what was used as classpath entries.</p>
1,320,374
Is there any way to find unused CSS in a website?
<p>Is there any way to find unused CSS in a website? </p> <p>I'm trying to clean up a project I just inherited.</p>
1,320,381
5
0
null
2009-08-24 03:37:21.25 UTC
13
2018-03-24 05:33:31.153 UTC
2012-08-23 18:26:43.867 UTC
null
63,550
null
4,653
null
1
17
css|code-cleanup
1,250
<p><a href="https://addons.mozilla.org/en-US/firefox/addon/dust-me-selectors/" rel="nofollow noreferrer">Dust-me Selectors</a> is a Firefox plugin that finds unused selectors.</p>
315,717
How do I check if Windows Installer 3.1 or higher is installed?
<p>I need to know this since this is a pre-req for .NET 3.5 and if I'm including the .NET bootstrapper, I should also see if Windows Installer 3.1 is needed.</p> <p>Right now I'm checking for the registry key:</p> <pre><code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows XP\SP3\KB893803v2 </code></pre> <p>Which will check for Windows Installer 3.1 but I suspect it doesn't check for higher versions. (Haven't been able to confirm or deny that)</p> <p>What registry key should I look at to find this information?</p> <p>Edit: I need to check this in Inno Setup which is what I'm using as my bootstrapper, and I'm not sure how to check a dll version in there.</p>
371,818
5
2
null
2008-11-24 22:22:14.743 UTC
1
2015-11-24 12:44:51.09 UTC
2013-10-24 10:50:31.703 UTC
Davy8
266,487
Davy8
23,822
null
1
21
windows-installer
88,181
<p>locate the installer msi.dll with this registry path: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer</p> <p>value: InstallerLocation</p> <p>then get the version information from that file.</p> <p>update: the way above is old! new way to detect the version is documented here: <a href="http://msdn.microsoft.com/en-us/library/aa368280%28VS.85%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa368280%28VS.85%29.aspx</a></p>
661,862
C++ Memory Management for Texture Streaming in Videogames
<p>this is a "hard" question. I've found nothing interesting over the web.</p> <p>I'm developing a Memory Management module for my company. We develop games for next-gen consoles (Xbox 360, PS3 and PC... we consider PC a console!).</p> <p>We'll need in future, for our next games, to handle texture streaming for large game worlds that cannot be loaded all in main console memory (not talking about PC for now).</p> <p>We are going to stream at the beginning hi-res mipmaps of textures (that is about 70% of the size of world data). Maybe in the future we'll have to stream also geometry, smaller mipmaps, audio, etc.</p> <p>I'm developing a Memory Manager for that issue, focused on X360 (because over PS3 we can use host memory and the associated, auto-defragmenting GMM allocator).</p> <p>The problem I'm facing is the following: We have decided to reserve a specific Memory Area for texture streaming (for example 64 Megabytes) and we want to handle all allocations and deallocations in that area. We have allocated the area at the beginning of the application and the area is Physically guaranteed to be contiguous (not just virtually, cause we need to store textures there).</p> <p>I've implemented an auto defragmenting allocator, using handles instead of pointers. Time is not an issue, the problem is memory fragmentation. In game we continuously load and unload streaming targets, so we'd like to use the maximum amount of our buffer (64 Megabytes).</p> <p>With this allocator we can use all of the allocated space but the defragmentation routine works in an unaccettable time (sometimes 60 milliseconds, more than a frames!) while the algorithm is not too bad... there are just too meny unevitable memcpy!</p> <p>I'm looking for a solution to solve this issue. I'd like to find at least a good paper, or a post-mortem, or someone who have faced the same problem of mine.</p> <p>Now I'm choosing between two strategies: 1) move the defragmentation routine on a dedicated thread (good for X360 with 6 hw threads, bad for PS3 with just a hw thread... and don't tell me to use SPU's!) with all multithreading problems of locking regions, of accessing a region who is being moved,... 2) find an "incremental" solution to defragmentation problem: we can give each frame a time budget (for example up to 1 millisecond) for defragmentation and the Memory Manager will do what it can do in the budget each frame.</p> <p>Can someone tell me his experience about?</p>
661,983
5
0
null
2009-03-19 11:35:07.187 UTC
10
2011-04-17 09:51:21.53 UTC
null
null
null
ugasoft
10,120
null
1
21
c++|memory-management|defragmentation
6,872
<p>I did a lot of study recently regarding memory management and this is the most informative and helpful article I found on the net.</p> <p><a href="http://www.ibm.com/developerworks/linux/library/l-memory/" rel="noreferrer">http://www.ibm.com/developerworks/linux/library/l-memory/</a></p> <p>Based on that paper the best and fastest result you will get is to divide your 64 MB into equal sized chunks. The size of chunks will depend on your object size. And allocate or deallocate a full chunk at a time. It's</p> <ol> <li>Faster than incremental garbage collection.</li> <li>Simpler.</li> <li>And solves that "too much fragmantation" problem by some amount.</li> </ol> <p>Read it, you will find excellent information on every possible solution there is and merits and demerits for each.</p>
512,516
How to copy a resource or another in Maven depending on the target environment?
<p>I have to create test war and production war, which will have a different <code>log4j.properties</code> file in the <code>WEB-INF</code> directory. I have these files <code>log4j.properties</code> (test war) and <code>dev.log4j.properties</code> (for production enivorment).</p> <p>How to copy the <code>dev.log4j.properties</code> file into <code>log4j.properties</code> file for production war?</p>
549,813
5
0
null
2009-02-04 17:51:29.463 UTC
20
2018-04-10 20:46:43.85 UTC
2012-04-27 15:50:03.23 UTC
null
270,349
null
62,534
null
1
33
maven-2|resources
47,983
<ul> <li>Use Maven profiles (<a href="http://maven.apache.org/guides/introduction/introduction-to-profiles.html" rel="noreferrer">http://maven.apache.org/guides/introduction/introduction-to-profiles.html</a>)</li> <li><p>Create a "dev" and "prod" profile, selecting an alternate set of resources for each profile. Make Dev active by default.</p> <pre><code>&lt;profiles&gt; &lt;profile&gt; &lt;id&gt;dev&lt;/id&gt; &lt;activation&gt; &lt;activeByDefault&gt;true&lt;/activeByDefault&gt; &lt;/activation&gt; &lt;build&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;src/main/resources/dev&lt;/directory&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;/build&gt; &lt;/profile&gt; &lt;profile&gt; &lt;id&gt;prod&lt;/id&gt; &lt;build&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;src/main/resources/prod&lt;/directory&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;/build&gt; &lt;/profile&gt; &lt;/profiles&gt; </code></pre></li> <li><p>Build using the desired profile via: <code>mvn install -Pdev</code> or <code>mvn install -Pprod</code></p></li> </ul>
364,825
Getting the number of rows with a GROUP BY query
<p>I have a query to the effect of</p> <pre><code>SELECT t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 WHERE (associate t1,t2, and t3 with each other) GROUP BY t3.id LIMIT 10,20 </code></pre> <p>I want to know to many total rows this query would return without the LIMIT (so I can show pagination information).</p> <p>Normally, I would use this query:</p> <pre><code>SELECT COUNT(t3.id) FROM t1, t2, t3 WHERE (associate t1,t2, and t3 with each other) GROUP BY t3.id </code></pre> <p>However the GROUP BY changes the meaning of the COUNT, and instead I get a set of rows representing the number of unique t3.id values in each group.</p> <p>Is there a way to get a count for the total number of rows when I use a GROUP BY? I'd like to avoid having to execute the entire query and just counting the number of rows, since I only need a subset of the rows because the values are paginated. I'm using MySQL 5, but I think this pretty generic.</p>
364,837
5
1
null
2008-12-13 04:14:15.967 UTC
22
2016-04-06 11:21:14.71 UTC
null
null
null
SoapBox
36,384
null
1
59
sql|mysql
93,825
<p>There is a nice solution in MySQL. </p> <p>Add the keyword SQL_CALC_FOUND_ROWS right after the keyword SELECT :</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 WHERE (associate t1,t2, and t3 with each other) GROUP BY t3.id LIMIT 10,20 </code></pre> <p>After that, run another query with the function FOUND_ROWS() :</p> <pre><code>SELECT FOUND_ROWS(); </code></pre> <p>It should return the number of rows without the LIMIT clause.</p> <p>Checkout this page for more information : <a href="http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows</a></p>
1,340,223
Calculating area enclosed by arbitrary polygon on Earth's surface
<p>Say I have an arbitrary set of latitude and longitude pairs representing points on some simple, closed curve. In Cartesian space I could easily calculate the area enclosed by such a curve using Green's Theorem. What is the analogous approach to calculating the area on the surface of a sphere? I guess what I am after is (even some approximation of) the algorithm behind <a href="http://www.mathworks.com/access/helpdesk/help/toolbox/map/index.html?/access/helpdesk/help/toolbox/map/areaint.html" rel="noreferrer">Matlab's <code>areaint</code> function</a>.</p>
1,342,709
6
0
null
2009-08-27 10:36:16.593 UTC
21
2020-04-12 19:11:41.043 UTC
2009-08-27 10:46:59.863 UTC
user142019
null
null
18,493
null
1
25
math|geometry|gis|geography
28,814
<p>There several ways to do this.</p> <p>1) Integrate the contributions from latitudinal strips. Here the area of each strip will be (Rcos(A)(B1-B0))(RdA), where A is the latitude, B1 and B0 are the starting and ending longitudes, and all angles are in radians.</p> <p>2) Break the surface into <a href="http://en.wikipedia.org/wiki/Spherical_trigonometry#Lines_on_a_sphere" rel="nofollow noreferrer">spherical triangles</a>, and calculate the area using <a href="http://en.wikipedia.org/wiki/Spherical_trigonometry#Lines_on_a_sphere" rel="nofollow noreferrer">Girard's Theorem</a>, and add these up.</p> <p>3) As suggested here by James Schek, in GIS work they use an area preserving projection onto a flat space and calculate the area in there.</p> <p>From the description of your data, in sounds like the first method might be the easiest. (Of course, there may be other easier methods I don't know of.)</p> <p><strong>Edit – comparing these two methods:</strong></p> <p>On first inspection, it may seem that the spherical triangle approach is easiest, but, in general, this is not the case. The problem is that one not only needs to break the region up into triangles, but into <em>spherical triangles</em>, that is, triangles whose sides are great circle arcs. For example, <em>latitudinal boundaries don't qualify</em>, so these boundaries need to be broken up into edges that better approximate great circle arcs. And this becomes more difficult to do for arbitrary edges where the great circles require specific combinations of spherical angles. Consider, for example, how one would break up a middle band around a sphere, say all the area between lat 0 and 45deg into spherical triangles.</p> <p>In the end, if one is to do this properly with similar errors for each method, method 2 will give fewer triangles, but they will be harder to determine. Method 1 gives more strips, but they are trivial to determine. Therefore, I suggest method 1 as the better approach.</p>
295,772
Query Microsoft Access MDB Database using LINQ and C#
<p>I have a *.MDB database file, and I am wondering if it is possible or recommended to work against it using LINQ in C#. I am also wondering what some simple examples would look like.</p> <p>I don't know a lot about LINQ, but my requirements for this task are pretty simple (I believe). The user will be passing me a file path to Microsoft Access MDB database and I would like to use LINQ to add rows to one of the tables within the database.</p>
295,801
6
2
null
2008-11-17 15:02:09.937 UTC
13
2017-10-26 03:14:20.887 UTC
2012-09-20 19:11:58.72 UTC
null
5,640
Matthew Ruston
506
null
1
37
c#|linq|ms-access
96,307
<p>What you want is a LINQ to ODBC provider, or a LINQ to JET/OLEDB provider.</p> <p>Out of the box, MS doesn't make one. There may be a 3rd party who does.</p>
32,339,617
Change the active bootstrap tab on button click
<p>I want to change the active bootstrap tab on the click of another button.</p> <p>I have tried add id's to the tabs li and write custom jquery code.</p> <pre><code>$('#emailNotify').click(function () { $('#notify').addClass('active').attr('aria-expanded','true'); $('#myacc').removeClass('active').attr('aria-expanded','false'); }); </code></pre> <p>This code works fine on first click but it doesn't change back when I tried to click My Account tab again.</p> <p><a href="https://i.stack.imgur.com/s90yN.jpg"><img src="https://i.stack.imgur.com/s90yN.jpg" alt="Image of Tabs and Button"></a></p> <p>Markup:</p> <pre><code>&lt;ul class="content-list museo_sans500"&gt; &lt;li&gt;&lt;a href="javascript:void(0)"&gt;Change Password&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id="emailNotify" data-toggle="tab"&gt;Change Email Notifications&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="javascript:void(0)"&gt;Change Profile Picture&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
32,339,934
2
5
null
2015-09-01 19:38:45.237 UTC
1
2015-09-01 19:58:37.137 UTC
2015-09-01 19:44:58.837 UTC
null
4,282,170
null
4,282,170
null
1
18
javascript|jquery|twitter-bootstrap
59,542
<p>You can change the active tab on the click event button with that:</p> <pre><code>$('#changetabbutton').click(function(e){ e.preventDefault(); $('#mytabs a[href="#second"]').tab('show'); }) </code></pre> <p>Here's a JSFiddle with an example:</p> <p><a href="http://jsfiddle.net/4ns0mdcf/">http://jsfiddle.net/4ns0mdcf/</a></p>
46,783,599
Base64 encoded image is not showing in gmail
<p>I have an embedded HTML email in which I'm using a <code>base64</code> encoded image. Image doesn't show in gmail when accessing via chrome. But it works fine when accessing same mail via mail client(Mail application on Mac). I have set headers correctly. Any idea?</p> <p>My code</p> <pre><code>&lt;html&gt; &lt;body&gt;Hi &lt;img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAREAAAALCAYAAABYrrnHAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABANpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ1dWlkOjVEMjA4OTI0OTNCRkRCMTE5MTRBODU5MEQzMTUwOEM4IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjVGMjU1MzZBQUVGQjExRTc5NUQyQTc1MzA0RERGMTVGIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjVGMjU1MzY5QUVGQjExRTc5NUQyQTc1MzA0RERGMTVGIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIElsbHVzdHJhdG9yIENDIDIwMTcgKE1hY2ludG9zaCkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0idXVpZDpiNDQ5NzVjYy00YmI1LTRmNzAtODRiZi0zMGU2NjFkYmY3ZDMiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6ZDc1MTVmZDQtMjkzZS00ZWI5LWFiMjQtOTMzYzRkZjNmOTY4Ii8+IDxkYzp0aXRsZT4gPHJkZjpBbHQ+IDxyZGY6bGkgeG1sOmxhbmc9IngtZGVmYXVsdCI+bXRrYV9hY3RpdmF0aW9uX2NhcmQ8L3JkZjpsaT4gPC9yZGY6QWx0PiA8L2RjOnRpdGxlPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pr6AOtYAAABESURBVHja7NZBDQAwCARB2tS/m6qoKIoGvswkGNjHhQgAAACAeVbdkwHoOnVXBqD9iWSmCkDblgAwIoARAYwIMNAXYACy9wSMWMVdzAAAAABJRU5ErkJggg==" width="273" height="11" alt=""&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Headers </p> <pre><code>Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: quoted-printable </code></pre>
46,789,485
2
4
null
2017-10-17 06:13:19.803 UTC
6
2021-01-19 10:25:15.173 UTC
2018-06-17 14:24:24.677 UTC
null
1,740,715
null
1,740,715
null
1
45
html|gmail|base64|html-email
56,016
<p><strong>base64 encoded images are not well supported in email.</strong> They aren't supported in most web email clients (including Gmail) and are completely blocked in Outlook. Apple Mail is one of the few clients that <em>does</em> support them, that's why you're able to see them there but not elsewhere.</p> <hr> <p>Another thing to be mindful of with base64 encoded images is email file size. Gmail App (iOS, Android) and Outlook (iOS) truncate email messages whose file size exceeds 102KB. Remotely referenced images (Eg. <code>&lt;img src="http://www.website.com/image.png"&gt;</code> do not count towards the email's file size, <strong>but base64 encoded images <em>do</em></strong> and can quickly blow out an email's file size past the 102KB limit. Just something else to consider.</p>
23,013,484
Jquery, set value of td in a table?
<p>I create dynamic a table with <code>&lt;tr&gt;</code> and <code>&lt;td&gt;</code> tags. One of the td tags gets the id "detailInfo". I have an onclick function on some button. I would like to set some value in the td "detailInfo" after pressing on the button.</p> <p>So how can I set the value of the td with id "detailInfo" ?</p> <p>This is the td:</p> <pre><code>&lt;td id="detailInfo" rowspan="2" width="300px"&gt;picture detail&lt;/td&gt; </code></pre>
23,013,521
5
3
null
2014-04-11 13:07:40.833 UTC
7
2018-12-12 09:05:12.817 UTC
2014-04-11 13:10:48.29 UTC
null
616,443
null
1,326,231
null
1
59
jquery
195,236
<p>use <code>.html()</code> along with selector to get/set HTML:</p> <pre><code> $('#detailInfo').html('changed value'); </code></pre>
2,218,093
Django, Retrieve IP location
<p>I would like to redirect my users to specific location areas in my website, by detecting their location from their IP address.</p> <p>What would be the best way to achieve this under Django 1.1.1 ?</p> <p>Thanks</p> <p><strong>Edit:</strong> I want city based locationing on europe.</p>
2,218,134
6
1
null
2010-02-07 19:57:22.51 UTC
30
2021-08-30 14:20:48.713 UTC
2010-02-07 20:28:23.943 UTC
null
151,937
null
151,937
null
1
30
django|geolocation
32,301
<p><a href="http://geodjango.org/" rel="noreferrer">GeoDjango</a> looks like it will suit your needs. I'm not sure exactly how you would want to direct users, but using the <a href="http://geodjango.org/docs/geoip.html#example" rel="noreferrer">GeoIP API</a>, you can do something like:</p> <pre><code>from django.contrib.gis.utils import GeoIP g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) if ip: city = g.city(ip)['city'] else: city = 'Rome' # default city # proceed with city </code></pre> <p>The <a href="http://geodjango.org/docs/" rel="noreferrer">Docs</a> explain things in great detail; I would take a moment to read through them thoroughly. </p>
2,331,716
How to find whether a ResultSet is empty or not in Java?
<p>How can I find that the <code>ResultSet</code>, that I have got by querying a database, is empty or not?</p>
2,331,898
6
0
null
2010-02-25 04:50:21.043 UTC
4
2018-01-29 17:25:07.477 UTC
2013-06-20 05:37:43.73 UTC
null
2,240,403
null
157,027
null
1
35
java|jdbc|resultset
115,491
<p>Immediately after your execute statement you can have an if statement. For example</p> <pre><code>ResultSet rs = statement.execute(); if (!rs.next()){ //ResultSet is empty } </code></pre>
1,882,981
Google Chrome - Alphanumeric hashes to identify extensions
<p>Google Chrome is using alpha numeric hashes as identifiers for the Chrome extensions. For eg. "ajpgkpeckebdhofmmjfgcjjiiejpodla" is the identifier for <a href="https://chrome.google.com/extensions/detail/ajpgkpeckebdhofmmjfgcjjiiejpodla" rel="noreferrer">XMarks</a> Bookmark Sync extension.</p> <p>Which algorithm is in use here to generate such strings? How are they ensuring uniqueness? </p>
1,962,064
8
0
null
2009-12-10 18:20:55.247 UTC
15
2014-10-30 09:08:54.117 UTC
2012-12-03 15:27:58.42 UTC
null
938,089
null
27,474
null
1
19
google-chrome-extension
10,012
<p>Chromium generates the id via public key. If you use the extension gallery, they handle all that for you.</p> <p>From the <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/extension.cc" rel="noreferrer">source</a>:</p> <pre><code>bool Extension::GenerateId(const std::string&amp; input, std::string* output) { CHECK(output); if (input.length() == 0) return false; const uint8* ubuf = reinterpret_cast&lt;const unsigned char*&gt;(input.data()); SHA256Context ctx; SHA256_Begin(&amp;ctx); SHA256_Update(&amp;ctx, ubuf, input.length()); uint8 hash[Extension::kIdSize]; SHA256_End(&amp;ctx, hash, NULL, sizeof(hash)); *output = StringToLowerASCII(HexEncode(hash, sizeof(hash))); ConvertHexadecimalToIDAlphabet(output); return true; } </code></pre> <p>Take a look at extension.cc file it has more detailed information such as generating the .pem file exncoding/decoding, etc.</p>
1,434,144
Compiling Python
<p>How can I compile and run a python file (*.py extension)?</p>
1,434,155
8
5
null
2009-09-16 16:42:51.203 UTC
5
2015-03-12 19:28:23.007 UTC
2009-09-16 17:26:54.143 UTC
null
52,963
null
161,004
null
1
48
python|compiler-construction
60,294
<p><code>python yourfile.py</code></p> <p>You have to have python installed first. It will automatically compile your file into a .pyc binary, and then run it for you. It will automatically recompile any time your file changes.</p> <p><a href="http://www.python.org/download/" rel="noreferrer">http://www.python.org/download/</a></p>
1,645,174
jquery: using appendTo in second to last row of table
<p>I have a piece of the DOM that I'd like to insert into my page. Currently I'm just blindly using:</p> <pre><code>$(myblob).appendTo(someotherblob); </code></pre> <p>How do I do the same thing, but append myblob to the second to last row that is within someotherblob. someotherblob in this case is a table and I want to inject a row above the second to last one.</p>
1,645,218
9
0
null
2009-10-29 17:02:38.6 UTC
5
2017-12-09 08:34:20.083 UTC
null
null
null
null
175,836
null
1
25
javascript|jquery
40,577
<pre><code>$('#mytable tr:last').before("&lt;tr&gt;&lt;td&gt;new row&lt;/td&gt;&lt;/tr&gt;") </code></pre>
2,251,839
Login failed for user 'NT AUTHORITY\NETWORK SERVICE'
<p>I been strugling with this for 2 days now without comming any closer to solution. I have read 20-30 threads alteast and stil can not resolve this.</p> <p>Please help me out.</p> <p>I have disable anonymous authentication, enable asp.net impersonation.</p> <p>I have added <code>&lt;identity impersonate = "true" /&gt;</code></p> <p>I have added the a user to the security logins that is connected to the database I try to connect to</p> <p>This is the connectionstring I use:</p> <pre><code>Data Source=IPTOSERVER;Initial Catalog=Phaeton;User Id=User;Password=Password; </code></pre> <p>errormessage:</p> <blockquote> <p>Cannot open database "Phaeton.mdf" requested by the login. The login failed.</p> <p>Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.</p> </blockquote>
2,253,178
9
5
null
2010-02-12 12:47:07.937 UTC
12
2020-09-25 08:50:49.463 UTC
2010-02-12 12:52:02.087 UTC
null
88,558
null
148,601
null
1
33
asp.net|sql-server-2008|iis-7|web-config|connection-string
132,268
<p>The error message you are receiving is telling you that the application failed to connect to the sqlexpress db, and not sql server. I will just change the name of the db in sql server and then update the connectionstring accordingly and try it again.</p> <p>Your error message states the following:</p> <pre><code>Cannot open database "Phaeton.mdf" requested by the login. The login failed. </code></pre> <p>It looks to me you are still trying to connect to the file based database, the name "Phaeton.mdf" does not match with your new sql database name "Phaeton".</p> <p>Hope this helps.</p>
2,034,799
How to truncate long matching lines returned by grep or ack
<p>I want to run ack or grep on HTML files that often have very long lines. I don't want to see very long lines that wrap repeatedly. But I do want to see just that portion of a long line that surrounds a string that matches the regular expression. How can I get this using any combination of Unix tools?</p>
2,034,806
10
6
null
2010-01-09 20:19:50.19 UTC
19
2021-06-24 11:42:12.47 UTC
2017-07-27 01:43:27.82 UTC
null
3,266,847
null
232,417
null
1
112
grep|unix|ack
50,398
<p>You could use the grep option <code>-o</code>, possibly in combination with changing your pattern to <code>".{0,10}&lt;original pattern&gt;.{0,10}"</code> in order to see some context around it:</p> <pre> -o, --only-matching Show only the part of a matching line that matches PATTERN. </pre> <p>..or <code>-c</code>:</p> <pre> -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see below), count non-matching lines. </pre>
1,550,688
Rails: How do I create a default value for attributes in Rails activerecord's model?
<p>I want to create a default value for an attribute by defining it in ActiveRecord. By default everytime the record is created, I want to have a default value for attribute <code>:status</code>. I tried to do this:</p> <pre><code>class Task &lt; ActiveRecord::Base def status=(status) status = 'P' write_attribute(:status, status) end end </code></pre> <p>But upon creation I still retrieve this error from the database:</p> <pre><code>ActiveRecord::StatementInvalid: Mysql::Error: Column 'status' cannot be null </code></pre> <p>Therefore I presume the value was not applied to the attribute. </p> <p>What would be the elegant way to do this in Rails?</p> <p>Many thanks.</p>
1,551,430
10
1
null
2009-10-11 13:24:11.957 UTC
48
2022-03-04 07:56:49.967 UTC
2020-06-23 15:02:14.2 UTC
null
10,907,864
null
141,186
null
1
206
ruby-on-rails|activerecord
225,728
<p>You can set a default option for the column in the migration</p> <pre><code>.... add_column :status, :string, :default =&gt; &quot;P&quot; .... </code></pre> <p>OR</p> <p>You can use a callback, <code>before_save</code></p> <pre><code>class Task &lt; ActiveRecord::Base before_save :default_values def default_values self.status ||= 'P' # note self.status = 'P' if self.status.nil? might better for boolean fields (per @frontendbeauty) end end </code></pre>
2,158,868
How do I efficiently cache objects in Java using available RAM?
<p>I need to cache objects in Java using a proportion of whatever RAM is available. I'm aware that others have asked this question, but none of the responses meet my requirements.</p> <p>My requirements are:</p> <ul> <li>Simple and lightweight</li> <li>Not dramatically slower than a plain HashMap</li> <li>Use LRU, or some deletion policy that approximates LRU</li> </ul> <p>I tried LinkedHashMap, however it requires you to specify a maximum number of elements, and I don't know how many elements it will take to fill up available RAM (their sizes will vary significantly).</p> <p>My current approach is to use Google Collection's MapMaker as follows:</p> <pre><code>Map&lt;String, Object&gt; cache = new MapMaker().softKeys().makeMap(); </code></pre> <p>This seemed attractive as it should automatically delete elements when it needs more RAM, however there is a serious problem: its behavior is to fill up all available RAM, at which point the GC begins to thrash and the whole app's performance deteriorates dramatically.</p> <p>I've heard of stuff like EHCache, but it seems quite heavy-weight for what I need, and I'm not sure if it is fast enough for my application (remembering that the solution can't be dramatically slower than a HashMap).</p>
3,852,113
12
4
null
2010-01-28 23:45:03.977 UTC
14
2020-07-13 10:13:27.433 UTC
2010-01-29 19:25:38.18 UTC
null
202,214
null
16,050
null
1
26
java|caching|guava|soft-references
11,005
<p>I've got similar requirements to you - concurrency (on 2 hexacore CPUs) and LRU or similar - and also tried Guava MapMaker. I found softValues() much slower than weakValues(), but both made my app excruciatingly slow when memory filled up.</p> <p>I tried WeakHashMap and it was less problematic, oddly even faster than using LinkedHashMap as an LRU cache via its removeEldestEntry() method.</p> <p>But by the fastest for me is <a href="http://concurrentlinkedhashmap.googlecode.com/svn/wiki/release-1.0-LRU/index.html" rel="noreferrer">ConcurrentLinkedHashMap</a> which has made my app 3-4 (!!) times faster than any other cache I tried. Joy, after days of frustration! It's apparently been incorporated into Guava's MapMaker, but the LRU feature isn't in Guava r07 at any rate. Hope it works for you.</p>
8,753,206
Split shape defined by path into sub-paths
<p>I am attempting to split a closed path to sub-paths, the image is of a tree and I want to be able to easily manipulate branches by dividing them from the path between two nodes and then recombining later.<br><br>I have tried "Break apart" and "Cut Path" but neither work predictably (annoyingly, it worked for one branch but can't get to to work for others!).<br><br> Ideally, I want to cut the path at the base of a branch by selecting the nodes on either side at the base of the branch so that I can rotate and translate that branch independently.</p> <p><img src="https://i.stack.imgur.com/NYzxo.jpg" alt="branch nodes"></p>
9,237,528
1
2
null
2012-01-06 04:02:32.247 UTC
9
2012-12-05 10:18:12.357 UTC
2012-12-05 10:18:12.357 UTC
null
944,657
null
924,551
null
1
47
inkscape
53,074
<p>Try this: </p> <ol> <li>Select the two nodes at each side of the base of the branch (as shown in your image).</li> <li>Use the "Break path at selected nodes"-button. It's located in the upper toolbar visible when you press F2.</li> <li>Now you have two connected paths which you can separate using Path->"Break Apart".</li> </ol>
8,686,725
What is the difference between std::set and std::vector?
<p>I am learning STL now. I read about <code>set</code> container. I have question when you want to use <code>set</code>? After reading <a href="http://www.cplusplus.com/reference/stl/set/">description of set</a> it looks like it is useless because we can substitute it by <code>vector</code>. Could you say pros and cos for <code>vector</code> vs <code>set</code> containers. Thanks</p>
8,686,825
5
2
null
2011-12-31 06:24:42.307 UTC
40
2020-02-19 05:50:26.177 UTC
2011-12-31 10:24:33.33 UTC
null
554,075
null
1,082,727
null
1
80
c++|stl
99,296
<p>A <code>set</code> is ordered. It is <em>guaranteed</em> to remain in a specific ordering, according to a functor that you provide. No matter what elements you add or remove (unless you add a duplicate, which is not allowed in a <code>set</code>), it will always be ordered.</p> <p>A <code>vector</code> has exactly and <em>only</em> the ordering you explicitly give it. Items in a <code>vector</code> are where you put them. If you put them in out of order, then they're out of order; you now need to <code>sort</code> the container to put them back in order.</p> <p>Admittedly, <code>set</code> has relatively limited use. With proper discipline, one could insert items into a <code>vector</code> and keep it ordered. However, if you are constantly inserting and removing items from the container, <code>vector</code> will run into many issues. It will be doing a lot of copying/moving of elements and so forth, since it is effectively just an array.</p> <p>The time it takes to insert an item into a <code>vector</code> is proportional to the number of items already in the <code>vector</code>. The time it takes to insert an item into a <code>set</code> is proportional to the <em>logβ‚‚</em> of the number of items. If the number of items is large, that's a huge difference. logβ‚‚(100,000) is ~16; that's a major speed improvement. The same goes for removal.</p> <p>However, if you do all of your insertions at once, at initialization time, then there's no problem. You can insert everything into the <code>vector</code>, sort it (paying that price once), and then use standard algorithms for sorted <code>vectors</code> to find elements and iterate over the sorted list. And while iteration over the elements of a <code>set</code> isn't exactly slow, iterating over a <code>vector</code> is faster.</p> <p>So there are cases where a sorted <code>vector</code> beats a <code>set</code>. That being said, you really shouldn't bother with the expense of this kind of optimization unless you know that it is necessary. So use a <code>set</code> unless you have experience with the kind of system you're writing (and thus know that you need that performance) or have profiling data in hand that tells you that you need a <code>vector</code> and not a <code>set</code>.</p>
18,134,318
Extracting contents from specific meta tags that are not closed using BeautifulSoup
<p>I'm trying to parse out content from specific meta tags. Here's the structure of the meta tags. The first two are closed with a backslash, but the rest don't have any closing tags. As soon as I get the 3rd meta tag, the entire contents between the <code>&lt;head&gt;</code> tags are returned. I've also tried <code>soup.findAll(text=re.compile('keyword'))</code> but that does not return anything since keyword is an attribute of the meta tag.</p> <pre><code>&lt;meta name="csrf-param" content="authenticity_token"/&gt; &lt;meta name="csrf-token" content="OrpXIt/y9zdAFHWzJXY2EccDi1zNSucxcCOu8+6Mc9c="/&gt; &lt;meta content='text/html; charset=UTF-8' http-equiv='Content-Type'&gt; &lt;meta content='en_US' http-equiv='Content-Language'&gt; &lt;meta content='c2y_K2CiLmGeet7GUQc9e3RVGp_gCOxUC4IdJg_RBVo' name='google-site- verification'&gt; &lt;meta content='initial-scale=1.0,maximum-scale=1.0,width=device-width' name='viewport'&gt; &lt;meta content='notranslate' name='google'&gt; &lt;meta content="Learn about Uber's product, founders, investors and team. Everyone's Private Driver - Request a car from any mobile phoneβ€”text message, iPhone and Android apps. Within minutes, a professional driver in a sleek black car will arrive curbside. Automatically charged to your credit card on file, tip included." name='description'&gt; </code></pre> <p>Here's the code:</p> <pre><code>import csv import re import sys from bs4 import BeautifulSoup from urllib.request import Request, urlopen req3 = Request("https://angel.co/uber", headers={'User-Agent': 'Mozilla/5.0') page3 = urlopen(req3).read() soup3 = BeautifulSoup(page3) ## This returns the entire web page since the META tags are not closed desc = soup3.findAll(attrs={"name":"description"}) </code></pre>
18,135,015
6
2
null
2013-08-08 19:20:31.65 UTC
8
2019-10-29 21:52:34.173 UTC
null
null
null
null
675,740
null
1
11
python|beautifulsoup
24,295
<p>Edited: Added regex for case sensitivity as suggested by @Albert Chen.</p> <p>Python 3 Edit:</p> <pre><code>from bs4 import BeautifulSoup import re import urllib.request page3 = urllib.request.urlopen("https://angel.co/uber").read() soup3 = BeautifulSoup(page3) desc = soup3.findAll(attrs={"name": re.compile(r"description", re.I)}) print(desc[0]['content']) </code></pre> <p>Although I'm not sure it will work for every page: </p> <pre><code>from bs4 import BeautifulSoup import re import urllib page3 = urllib.urlopen("https://angel.co/uber").read() soup3 = BeautifulSoup(page3) desc = soup3.findAll(attrs={"name": re.compile(r"description", re.I)}) print(desc[0]['content'].encode('utf-8')) </code></pre> <p>Yields:</p> <pre><code>Learn about Uber's product, founders, investors and team. Everyone's Private Dri ver - Request a car from any mobile phoneΓÇâtext message, iPhone and Android app s. Within minutes, a professional driver in a sleek black car will arrive curbsi de. Automatically charged to your credit card on file, tip included. </code></pre>
6,498,487
What's the point of "var t = Object(this)" in the official implementation of forEach?
<p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach">According to the MDC</a>, the ECMA-262, 5th edition gives the implementation of forEach as:</p> <pre><code>if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun /*, thisp */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length &gt;&gt;&gt; 0; if (typeof fun !== "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i &lt; len; i++) { if (i in t) fun.call(thisp, t[i], i, t); } }; } </code></pre> <p>Can anyone tell me what the line "var t = Object(this)" is doing? How does Object(this) differ from plain this? And what work is that difference doing here?</p>
6,498,638
3
9
null
2011-06-27 20:21:40.823 UTC
12
2014-09-19 15:11:52.38 UTC
null
null
null
null
629,474
null
1
13
javascript
1,562
<p>The Mozilla implementations just try to emulate exactly the steps that are described in the specification, <code>Object(this);</code> emulates the <em>first step</em>, calling the <a href="http://es5.github.com/#x9.9" rel="noreferrer"><code>ToObject</code></a> internal method:</p> <p>From <code>Array.prototype.forEach</code> <a href="http://es5.github.com/#x15.4.4.18" rel="noreferrer">15.4.4.18</a>:</p> <blockquote> <p>....</p> <p>When the forEach method is called with one or two arguments, the following steps are taken:</p> <ol> <li><p>Let O be the result of calling ToObject passing the this value as the argument.</p></li> <li><p>Let lenValue be the result of calling the [[Get]] internal method of O with the argument "length".</p></li> <li><p>Let len be ToUint32(lenValue).</p></li> </ol> <p>....</p> </blockquote> <p>Calling <a href="http://es5.github.com/#x15.2.1" rel="noreferrer">the Object constructor as a function</a> behind the scenes it performs type conversion, internally as described in <a href="http://es5.github.com/#x15.2.1.1" rel="noreferrer">15.2.1.1</a> the <code>ToObject</code> method is called.</p> <p>There are more things like this if you look carefully, for example, the line:</p> <pre><code>var len = t.length &gt;&gt;&gt; 0; </code></pre> <p>They are emulating a call to the <a href="http://es5.github.com/#x9.6" rel="noreferrer">ToUint32</a> internal method, as described in the step 3, using the unsigned right shift operator (<a href="http://es5.github.com/#x11.7.3" rel="noreferrer"><code>&gt;&gt;&gt;</code></a>). </p> <p><strong>Edit:</strong> The previous lines answer <em>why</em> the Mozilla implementation does it in this way.</p> <p>You might wonder why the ECMAScript spec. needs to call <code>ToObject</code>, check back the <em>Step 2</em>, and it will start to seem obvious:</p> <blockquote> <ol start="2"> <li>Let lenValue be the result of calling the [[Get]] internal method of O with the argument "length".</li> </ol> </blockquote> <p>The spec. needs to ensure that the <code>this</code> value used when the function is called is <em>an object</em>, because primitive values don't have any internal methods, an as you can see on the step 2, the <code>[[Get]](P)</code> internal method is needed, to get the value of the <code>length</code> property.</p> <p>This is done because for <em>strict functions</em> (and also for built-in functions), you can set <em>primitive values</em> as the function's <code>this</code> value, e.g.:</p> <pre><code>(function () {"use strict"; return typeof this; }).call(5); // "number" </code></pre> <p>While for non-strict functions, the <code>this</code> value is always converted to Object:</p> <pre><code>(function () { return typeof this; }).call(5); // "object" </code></pre>
6,355,482
Scroll to a specific position on a page using Javascript / Jquery
<p>It is possible to move to a certain position on a page using <code>#elementId</code>. How can I do the same thing using Javascript / Jquery. When a JS function is called, I want to scroll to the specific position on that page.</p>
6,368,093
4
0
null
2011-06-15 09:13:17.01 UTC
1
2016-10-06 13:11:58.803 UTC
2016-10-06 13:11:58.803 UTC
null
542,251
null
733,984
null
1
30
javascript|jquery
48,205
<p>After much googling I found that you just need to do this:</p> <pre><code>location.hash = "elementId" </code></pre>
36,026,904
How to automate OTP using selenium web driver?
<p>I am doing automation for registration in a website but the problem is that it sends an OTP once i enter mobile no. after enter otp it will ask for password and than i am able to do registration.</p> <p>Is there any way to get the OTP code once i enter mobile no ? or Can we automate OTP using selenium webdriver ? </p>
36,058,605
2
3
null
2016-03-16 04:39:02.68 UTC
8
2022-05-02 10:39:12.02 UTC
null
null
null
null
5,097,027
null
1
16
selenium|selenium-webdriver
49,798
<p>You may try any one of them:</p> <p><b>Solution 1:</b></p> <p>Step 1: Connect the Phone/Dongle to the COM Port via USB.</p> <p>Step 2: Call the code for fetching sms via smslib.jar</p> <p>Sample Code to fetch sms:</p> <pre><code>public void sendSMS() throws Exception{ OutboundNotification outboundNotification = new OutboundNotification(); SerialModemGateway gateway = new SerialModemGateway("modem.com5", "COM5", 9600, "ZTE", "COM5"); gateway.setInbound(true); gateway.setOutbound(true); gateway.setSmscNumber("+91XXXXXXXXXX"); // 10-digit Mobile Number Service.getInstance().setOutboundMessageNotification(outboundNotification); Service.getInstance().addGateway(gateway); Service.getInstance().startService(); OutboundMessage msg = new OutboundMessage(ExcelConnect.strSMSTo, ExcelConnect.strSMSText); Service.getInstance().sendMessage(msg); System.out.println(msg); System.out.println(ExcelConnect.strSMSTo + "-" + ExcelConnect.strSMSText); Service.getInstance().stopService(); Service.getInstance().removeGateway(gateway); } </code></pre> <p>Step 3: Parse sms to get the <strong>OTP</strong> from the fetched list by latest received sms</p> <p>.</p> <p><b>Solution 2:</b></p> <p>Step 1: Connect the android phone / iphone.</p> <p>Step 2: Automate the SMS App in either of the phone, if its android - automate SMS app via appium(or any other automating app) or if its iphone - automate its SMS app feature, </p> <p>to get the SMS and parse it to get the OTP</p> <p>.</p> <p><strong>Solution 3:</strong></p> <p>Step 1: Register for the HTTP SMS Gateway(Most of them provide paid API Call with <b>very few free API</b> Calls for testing).</p> <p>Step 2: Call the method to fetch SMS.</p> <p>Step 3: Parse the message(after sorting it by latest received sms) to get the OTP</p> <p>.</p> <p>These three ways you can get the OTP and then you can send it to you Web Application.</p> <p>.</p> <p><strong>Solution 4:</strong></p> <p>Get the OTP from DB, if its in-house application or if it can be accessed.</p> <p>.</p> <p>'<b>Solution 3 and Solution 4</b>' being most efficient and it doesn't have any dependency on sms receiving platforms.</p> <p>.</p> <p>Solutions consolidated below:</p> <p><a href="https://i.stack.imgur.com/MbIxW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MbIxW.png" alt="enter image description here"></a></p>
39,947,314
Write a query that displays the names of cities and their countries when the capital city is the largest of all cities listed for that country
<p>I have a database called <code>world</code>. This database has two tables: <code>city</code> and <code>country</code>.</p> <p><code>city</code>'s columns are: <code>name</code>, <code>ID</code>, <code>Population</code>, <code>countryCode</code>.</p> <p><code>country</code>'s columns are: <code>Code</code>, <code>name</code>, <code>countryPopulation</code>, <code>Capital</code>.</p> <ul> <li><code>countryCode</code> in <code>city</code> table = <code>Code</code> in <code>country</code> table</li> <li><code>ID</code> in <code>city</code> table = <code>capital</code> in <code>country</code> table</li> </ul> <p>Write a query that displays the names of cities and their countries when the capital city is the largest of all cities listed for that country.</p> <p>Here is the code that displays the largest cities list:</p> <pre><code>SELECT MAX(c.Population) AS Population, c.Name AS City, cou.Name AS Country FROM city c, country cou WHERE c.CountryCode = cou.Code GROUP BY cou.Name </code></pre> <p>Suppose I have that information from previous code:</p> <pre><code>Population City Country 1000000 Washington DC USA 993943210 Sao Paulo Brazil 1911919 Dubai UAE </code></pre> <p>My query should show all cities in the USA because Washington DC is the capital of USA and all cities in the UAE because Dubai is the capital of UAE but should not show cities in Brazil because Sao Paulo is not the capital of Brazil.</p>
39,948,193
2
5
null
2016-10-09 18:54:34.617 UTC
1
2019-12-01 09:56:53.753 UTC
2016-10-11 04:50:54.647 UTC
null
6,101,269
null
6,101,269
null
1
-1
mysql|sql|database|relational-database
50,444
<p>You can use this query:</p> <pre><code>SELECT c.name AS city_name, cou.name AS country_name FROM city c LEFT JOIN country cou ON c.countrycode = cou.code LEFT JOIN city c2 ON cou.capital = c2.id LEFT JOIN (SELECT countrycode, MAX(population) AS max_pop FROM city GROUP BY countrycode) t ON cou.code = t.countrycode WHERE c2.population = t.max_pop </code></pre> <p>The second <code>LEFT JOIN</code> allows to get the population of the country's capital (<code>c2.population</code>).</p> <p>The third <code>LEFT JOIN</code> allows to get the population of the country's biggest city (<code>t.max_pop</code>).</p> <p>And we keep only the cities where these two numbers are equal.</p>
34,024,805
C++ sizeof Vector is 24?
<p>I was just messing around and learning about vectors as well as structs, and at one point, I tried outputting the size of a vector in bytes. Here's the code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; struct Foo{ std::vector&lt;int&gt; a; }; int main() { using std::cout; using std::endl; Foo* f1 = new Foo; f1-&gt;a.push_back(5); cout &lt;&lt; sizeof(f1-&gt;a) &lt;&lt; endl; cout &lt;&lt; sizeof(f1-&gt;a[0]) &lt;&lt; endl; delete[] f1; } </code></pre> <p>The output is <code>24</code> and <code>4</code>.</p> <p>Obviously the second line printed 4, because that is the size of an int. But why exactly is the other value 24? Does a vector take up 24 bytes of memory? Thanks!</p>
34,024,896
1
7
null
2015-12-01 16:10:17.187 UTC
10
2015-12-01 16:15:31.533 UTC
null
null
null
null
5,361,456
null
1
34
c++|vector
17,344
<p>While the public interface of <code>std::vector</code> is defined by the standard, there can be different <em>implementations</em>: in other words, what's under the hood of <code>std::vector</code> can change from implementation to implementation.</p> <p>Even in the same implementation (for example: the STL implementation that comes with a given version of Visual C++), the internals of <code>std::vector</code> can change from release builds and debug builds.</p> <p>The 24 size you see can be explained as 3 pointers (each pointer is 8 bytes in size on 64-bit architectures; so you have 3 x 8 = 24 bytes). These pointers can be:</p> <ul> <li>begin of vector</li> <li>end of vector</li> <li>end of reserved memory for vector (i.e. vector's <em>capacity</em>)</li> </ul>
34,012,099
"TypeError: Cannot read property 'apply' of undefined"
<p>Using node, express, socket.io, jade and angular. Getting the error: <code>TypeError: Cannot read property 'apply' of undefined</code>. Any suggestions?</p> <p>index.js:</p> <pre><code>module.exports = function(app, res) { res.render('index', { title: 'Express' }); var io = app.get('io'); io.on('connection', function(socket){ }); }; </code></pre> <p>index.jade:</p> <pre><code>extends layout block content script. var app = angular.module('hackigur', []); var socket = io.connect(); var refreshTimer = 10; app.controller('UpdateController', function($scope){ //socket.on('update', function(msg){ //$scope.refreshTimer = msg; //$scope.$apply(); //}); setInterval(secondTick,1000); function secondTick() { if(refreshTimer != 0) { refreshTimer -= 1; } $scope.refreshTimer = refreshTimer; $scope.$apply(); }; }); h1= title p Welcome to #{title} div(ng-controller="UpdateController") p(ng-bind="refreshTimer") </code></pre> <p>layout.jade:</p> <pre> doctype html html(ng-app="hackigur") head title= title script(src = "/socket.io/socket.io.js") script(src = "/js/angular/angular.min.js") body block content </pre> <p>Full error:</p> <pre> Server listening on port 3000 TypeError: Cannot read property 'apply' of undefined at Server.(anonymous function) [as on] (D:\Projects\hackigur\node_modules\so cket.io\lib\index.js:364:15) at module.exports (D:\Projects\hackigur\server\api\index.js:30:8) at ... </pre>
34,026,662
1
8
null
2015-12-01 03:31:11.343 UTC
1
2017-04-25 10:08:24.807 UTC
2015-12-01 05:09:50.193 UTC
null
2,050,455
null
5,606,877
null
1
12
javascript|angularjs|node.js|express
62,733
<p>My <code>router</code> which called my <code>index.js</code> passed <code>app</code> in the <code>module.export</code> as such:</p> <pre><code>module.export = function (app) { app.get( ... , function(..., res) { require(index.js)(app)(res); }; </code></pre> <p>I needed to declare a variable for <code>app</code> external to my <code>module.export</code>:</p> <pre><code>var x; module.export = function (app) { x = app; app.get( ... , function(..., res) { require(index.js)(x)(res); }; </code></pre> <p>Don't fully understand why it worked, but it seemed to pass the correct <code>app</code> object to <code>app.get</code> by applying the above.</p>
27,474,921
Compare two columns using pandas
<p>Using this as a starting point:</p> <pre><code>a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']] df = pd.DataFrame(a, columns=['one', 'two', 'three']) Out[8]: one two three 0 10 1.2 4.2 1 15 70 0.03 2 8 5 0 </code></pre> <p>I want to use something like an <code>if</code> statement within pandas. </p> <pre><code>if df['one'] &gt;= df['two'] and df['one'] &lt;= df['three']: df['que'] = df['one'] </code></pre> <p>Basically, check each row via the <code>if</code> statement, create new column. </p> <p>The docs say to use <code>.all</code> but there is no example...</p>
27,475,514
10
3
null
2014-12-14 22:33:45.89 UTC
82
2021-11-07 20:34:31.693 UTC
2017-01-02 11:29:33.82 UTC
null
3,923,281
null
428,862
null
1
160
python|pandas|if-statement|dataframe
551,628
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer">np.where</a>. If <code>cond</code> is a boolean array, and <code>A</code> and <code>B</code> are arrays, then</p> <pre><code>C = np.where(cond, A, B) </code></pre> <p>defines C to be equal to <code>A</code> where <code>cond</code> is True, and <code>B</code> where <code>cond</code> is False.</p> <pre><code>import numpy as np import pandas as pd a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']] df = pd.DataFrame(a, columns=['one', 'two', 'three']) df['que'] = np.where((df['one'] &gt;= df['two']) &amp; (df['one'] &lt;= df['three']) , df['one'], np.nan) </code></pre> <p>yields</p> <pre><code> one two three que 0 10 1.2 4.2 10 1 15 70 0.03 NaN 2 8 5 0 NaN </code></pre> <hr> <p>If you have more than one condition, then you could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.select.html" rel="noreferrer">np.select</a> instead. For example, if you wish <code>df['que']</code> to equal <code>df['two']</code> when <code>df['one'] &lt; df['two']</code>, then</p> <pre><code>conditions = [ (df['one'] &gt;= df['two']) &amp; (df['one'] &lt;= df['three']), df['one'] &lt; df['two']] choices = [df['one'], df['two']] df['que'] = np.select(conditions, choices, default=np.nan) </code></pre> <p>yields</p> <pre><code> one two three que 0 10 1.2 4.2 10 1 15 70 0.03 70 2 8 5 0 NaN </code></pre> <p>If we can assume that <code>df['one'] &gt;= df['two']</code> when <code>df['one'] &lt; df['two']</code> is False, then the conditions and choices could be simplified to</p> <pre><code>conditions = [ df['one'] &lt; df['two'], df['one'] &lt;= df['three']] choices = [df['two'], df['one']] </code></pre> <p>(The assumption may not be true if <code>df['one']</code> or <code>df['two']</code> contain NaNs.)</p> <hr> <p>Note that </p> <pre><code>a = [['10', '1.2', '4.2'], ['15', '70', '0.03'], ['8', '5', '0']] df = pd.DataFrame(a, columns=['one', 'two', 'three']) </code></pre> <p>defines a DataFrame with string values. Since they look numeric, you might be better off converting those strings to floats:</p> <pre><code>df2 = df.astype(float) </code></pre> <p>This changes the results, however, since strings compare character-by-character, while floats are compared numerically.</p> <pre><code>In [61]: '10' &lt;= '4.2' Out[61]: True In [62]: 10 &lt;= 4.2 Out[62]: False </code></pre>
662,439
What are some refactoring methods to reduce size of compiled code?
<p>I have a legacy firmware application that requires new functionality. The size of the application was already near the limited flash capacity of the device and the few new functions and variables pushed it over the edge. Turning on compiler optimization does the trick, but the customer is wary of doing so because they have caused failures in the past. So, what are some common things to look for when refactoring C code to produce smaller output?</p>
662,452
7
4
null
2009-03-19 14:33:50.503 UTC
16
2019-04-09 23:04:47.817 UTC
2009-03-19 17:42:29.37 UTC
monjardin
1,491
monjardin
1,491
null
1
17
c|optimization|memory|embedded|size
24,018
<ul> <li>Use generation functions instead of data tables where possible</li> <li>Disable inline functions</li> <li>Turn frequently used macros into functions</li> <li>Reduce resolution for variables larger than the native machine size (ie, 8 bit micro, try to get rid of 16 and 32 bit variables - doubles and quadruples some code sequences)</li> <li>If the micro has a smaller instruction set (Arm thumb) enable it in the compiler</li> <li>If the memory is segmented (ie, paged or nonlinear) then <ul> <li>Rearrange code so that fewer global calls (larger call instructions) need to be used</li> <li>Rearrange code and variable usage to eliminate global memory calls</li> <li>Re-evaluate global memory usage - if it can be placed on the stack then so much the better</li> </ul></li> <li>Make sure you're compiling with debug turned off - on some processors it makes a big difference</li> <li>Compress data that can't be generated on the fly - then decompress into ram at startup for fast access</li> <li>Delve into the compiler options - it may be that every call is automatically global, but you might be able to safely disable that on a file by file basis to reduce size (sometimes significantly)</li> </ul> <p>If you still need more space than with <code>compile with optimizations</code> turned on, then look at the generated assembly versus unoptimized code. Then re-write the code where the biggest changes took place so that the compiler generates the same optimizations based on tricky C re-writes with optimization turned off.</p> <p>For instance, you may have several 'if' statements that make similar comparisons:</p> <pre><code>if(A &amp;&amp; B &amp;&amp; (C || D)){} if(A &amp;&amp; !B &amp;&amp; (C || D)){} if(!A &amp;&amp; B &amp;&amp; (C || D)){} </code></pre> <p>Then creating anew variable and making some comparisons in advance will save the compiler from duplicating code:</p> <pre><code>E = (C || D); if(A &amp;&amp; B &amp;&amp; E){} if(A &amp;&amp; !B &amp;&amp; E){} if(!A &amp;&amp; B &amp;&amp; E){} </code></pre> <p>This is one of the optimizations the compiler does for you automatically if you turn it on. There are many, many others, and you might consider reading a bit of compiler theory if you want to learn how to do this by hand in the C code.</p>
1,271,768
What HTTP traffic monitor would you recommend for Windows?
<p>I need the sniffer to test network traffic of applications developed by me for Windows and Facebook.</p> <p>Basic requirements:</p> <ul> <li>display request and response</li> <li>display HTTP headers</li> <li>display the time it took to complete HTTP request</li> </ul> <p>Now I'm using HTTP Analyzer. A very good tool, but it terminates with some error after 10-15 min running on Vista.</p>
1,271,789
7
1
null
2009-08-13 12:49:44.05 UTC
26
2018-08-09 09:07:05.25 UTC
2018-06-25 18:12:49.45 UTC
null
3,357,935
null
139,412
null
1
76
windows|http|traffic|sniffer
170,733
<p><a href="http://www.wireshark.org/" rel="noreferrer">Wireshark</a> if you want to see everything going on in the network.</p> <p><a href="http://fiddler2.com/" rel="noreferrer">Fiddler</a> if you want to just monitor HTTP/s traffic.</p> <p><a href="https://addons.mozilla.org/en-US/firefox/addon/live-http-headers/" rel="noreferrer">Live HTTP Headers</a> if you're in Firefox and want a quick plugin just to see the headers.</p> <p>Also <a href="http://getfirebug.com/" rel="noreferrer">FireBug</a> can get you that information too and provides a nice interface when your working on a single page during development. I've used it to monitor AJAX transactions.</p>
135,782
Generic logging of function parameters in exception handling
<p>A lot of my C# code follows this pattern:</p> <pre><code>void foo(string param1, string param2, string param3) { try { // do something... } catch(Exception ex) { LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message)); } } </code></pre> <p>Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string? OR Do you have a more generic / better way of doing this?</p>
136,041
8
3
null
2008-09-25 20:20:45.54 UTC
10
2022-02-09 11:41:59.45 UTC
null
null
null
Guy
1,463
null
1
31
c#|.net
27,445
<p>You could use Reflection and the convention that you must pass the parameters to the LogError with the right order:</p> <pre><code>private static void MyMethod(string s, int x, int y) { try { throw new NotImplementedException(); } catch (Exception ex) { LogError(MethodBase.GetCurrentMethod(), ex, s, x, y); } } private static void LogError(MethodBase method, Exception ex, params object[] values) { ParameterInfo[] parms = method.GetParameters(); object[] namevalues = new object[2 * parms.Length]; string msg = "Error in " + method.Name + "("; for (int i = 0, j = 0; i &lt; parms.Length; i++, j += 2) { msg += "{" + j + "}={" + (j + 1) + "}, "; namevalues[j] = parms[i].Name; if (i &lt; values.Length) namevalues[j + 1] = values[i]; } msg += "exception=" + ex.Message + ")"; Console.WriteLine(string.Format(msg, namevalues)); } </code></pre>
1,207,404
How to pass a null variable to a SQL Stored Procedure from C#.net code
<p>Im calling a SQL stored procedure from a piece of C#.net code:</p> <pre><code>SqlHelper.ExecuteDataset(sqlConnection, CommandType.StoredProcedure, STORED_PROC_NAME, sqlParameters); </code></pre> <p>where the <code>sqlParameters</code> variable is defined as:</p> <pre><code> SqlParameter[] sqlParameters = new SqlParameter[SQL_NUMBER_PARAMETERS]; Log.Logger.Debug(string.Format("Running proc: {0} ", STORED_PROC_NAME)); SqlParameters[0] = new SqlParameter("fieldID", SqlDbType.BigInt ); SqlParameters[0].Value = fieldID; SqlParameters[0].Direction = ParameterDirection.Input; </code></pre> <p>I need to now pass in another two parameters to this Stored Proc, (both are of type <code>SqlDateTime</code>), which are going to <em>NULL</em> in this case.</p> <p>Thanks,</p> <p>IN</p>
1,207,438
8
0
null
2009-07-30 15:36:39.62 UTC
10
2017-06-26 22:10:05.387 UTC
2009-07-31 16:38:44.483 UTC
null
13,302
null
81,324
null
1
73
c#|sql|sql-server|stored-procedures
158,848
<pre><code>SqlParameters[1] = new SqlParameter("Date1", SqlDbType.SqlDateTime); SqlParameters[1].Value = DBNull.Value; SqlParameters[1].Direction = ParameterDirection.Input; </code></pre> <p>...then copy for the second.</p>
1,046,477
Is there any reason to use the 'auto' keyword in C++03?
<blockquote> <p><strong>Note</strong> this question was originally posted in 2009, before C++11 was ratified and before the meaning of the <code>auto</code> keyword was drastically changed. The answers provided pertain <em>only</em> to the C++03 meaning of <code>auto</code> -- that being a storage class specified -- and not the C++11 meaning of <code>auto</code> -- that being automatic type deduction. If you are looking for advice about when to use the C++11 <code>auto</code>, this question is not relevant to that question.</p> </blockquote> <p>For the longest time I thought there was no reason to use the <code>static</code> keyword in C, because variables declared outside of block-scope were implicitly global. Then I discovered that declaring a variable as <code>static</code> within block-scope would give it permanent duration, and declaring it outside of block-scope (in program-scope) would give it file-scope (can only be accessed in that compilation unit).</p> <p>So this leaves me with only one keyword that I (maybe) don't yet fully understand: The <code>auto</code> keyword. Is there some other meaning to it other than 'local variable?' Anything it does that isn't implicitly done for you wherever you may want to use it? How does an <code>auto</code> variable behave in program scope? What of a <code>static auto</code> variable in file-scope? Does this keyword have any purpose other than <em>just existing for completeness</em>?</p>
1,046,503
10
0
null
2009-06-25 22:05:04.033 UTC
32
2018-10-26 08:00:28.337 UTC
2017-01-03 07:11:25.18 UTC
null
711,006
null
84,478
null
1
85
c++|keyword|c++03
71,034
<p><code>auto</code> is a storage class specifier, <code>static</code>, <code>register</code> and <code>extern</code> too. You can only use one of these four in a declaration. </p> <p>Local variables (without <code>static</code>) have automatic storage duration, which means they live from the start of their definition until the end of their block. Putting auto in front of them is redundant since that is the default anyway. </p> <p>I don't know of any reason to use it in C++. In old C versions that have the implicit int rule, you could use it to declare a variable, like in:</p> <pre><code>int main(void) { auto i = 1; } </code></pre> <p>To make it valid syntax or disambiguate from an assignment expression in case <code>i</code> is in scope. But this doesn't work in C++ anyway (you have to specify a type). Funny enough, the C++ Standard writes:</p> <blockquote> <p>An object declared without a storage-class-specifier at block scope or declared as a function parameter has automatic storage duration by default. [Note: hence, the auto specifier is almost always redundant and not often used; one use of auto is to distinguish a declaration-statement from an expression-statement (6.8) explicitly. β€” end note]</p> </blockquote> <p>which refers to the following scenario, which could be either a cast of <code>a</code> to <code>int</code> or the declaration of a variable <code>a</code> of type <code>int</code> having redundant parentheses around <code>a</code>. It is always taken to be a declaration, so <code>auto</code> wouldn't add anything useful here, but would for the human, instead. But then again, the human would be better off removing the redundant parentheses around <code>a</code>, I would say:</p> <pre><code>int(a); </code></pre> <p>With the new meaning of <code>auto</code> arriving with C++0x, I would discourage using it with C++03's meaning in code. </p>
1,313,373
jQuery same click event for multiple elements
<p>Is there any way to execute same code for different elements on the page?</p> <pre><code>$('.class1').click(function() { some_function(); }); $('.class2').click(function() { some_function(); }); </code></pre> <p>instead to do something like:</p> <pre><code>$('.class1').$('.class2').click(function() { some_function(); }); </code></pre> <p>Thanks</p>
1,313,404
10
0
null
2009-08-21 17:59:15.877 UTC
84
2020-09-05 13:05:32.687 UTC
2015-12-11 20:31:00.15 UTC
null
814,702
null
136,530
null
1
501
jquery|events
519,609
<pre><code>$('.class1, .class2').on('click', some_function); </code></pre> <p>Or:</p> <pre><code>$('.class1').add('.class2').on('click', some_function); </code></pre> <p>This also works with existing objects:</p> <pre><code>const $class1 = $('.class1'); const $class2 = $('.class2'); $class1.add($class2).on('click', some_function); </code></pre>
302,820
.NET 3.5 chart controls exception: Error executing child request for ChartImg.axd
<p>Anyone getting this error when using the new free chart controls MS bought from Dundas?</p> <p>"Error executing child request for ChartImg.axd"</p> <p>On the MSDN forum they suggested it was my web.config: <a href="http://social.msdn.microsoft.com/Forums/en-US/MSWinWebChart/thread/1dc4b352-c9a5-49dc-8f35-9b176509faa1/" rel="noreferrer">MSDN forum post</a></p> <p>So far that hasn't fixed the problem though. Any other ideas?</p>
438,251
12
0
null
2008-11-19 18:09:47.733 UTC
13
2016-05-02 19:30:25.337 UTC
2009-06-09 19:39:18.197 UTC
null
3,043
Scott Anderson
5,115
null
1
40
.net|.net-3.5|charts
49,917
<p>I encountered the same problem: the chart would work on one page but not on the next. Turns out if the chart is initialized for the first time in a POST (i.e. a postback) the error is thrown because the handler is configured incorrectly. To fix the issue modify the httpHandler configuration that user LaptopHeaven referred to in this topic by adding the POST verb:</p> <pre class="lang-xml prettyprint-override"><code>&lt;add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" /&gt; </code></pre> <p>I've written a more thorough explanation of why this error occurs in the MSDN forum post that Scott Anderson referred to in his opening post of this topic. </p>
309,149
Generate distinctly different RGB colors in graphs
<p>When generating graphs and showing different sets of data it usually a good idea to difference the sets by color. So one line is red and the next is green and so on. The problem is then that when the number of datasets is unknown one needs to randomly generate these colors and often they end up very close to each other (green, light green for example). </p> <p>Any ideas on how this could be solved and how it would be possibler to generate distinctly different colors? </p> <p>I'd be great if any examples (feel free to just discuss the problem and solution without examples if you find that easier) were in C# and RGB based colors.</p>
309,193
12
1
null
2008-11-21 15:43:06.407 UTC
54
2019-07-02 08:42:14.197 UTC
2017-08-27 16:53:10.967 UTC
Richard Hallgren
815,724
Richard Hallgren
298
null
1
93
c#|random|graph|colors
80,334
<p>You have three colour channels 0 to 255 R, G and B.</p> <p>First go through</p> <pre><code>0, 0, 255 0, 255, 0 255, 0, 0 </code></pre> <p>Then go through</p> <pre><code>0, 255, 255 255, 0, 255 255, 255, 0 </code></pre> <p>Then divide by 2 => 128 and start again:</p> <pre><code>0, 0, 128 0, 128, 0 128, 0, 0 0, 128, 128 128, 0, 128 128, 128, 0 </code></pre> <p>Divide by 2 => 64</p> <p>Next time add 64 to 128 => 192</p> <p>follow the pattern.</p> <p>Straightforward to program and gives you fairly distinct colours.</p> <p><strong>EDIT: Request for code sample</strong></p> <p>Also - adding in the additional pattern as below if gray is an acceptable colour:</p> <pre><code>255, 255, 255 128, 128, 128 </code></pre> <p>There are a number of ways you can handle generating these in code. </p> <h1>The Easy Way</h1> <p>If you can guarantee that you will never need more than a fixed number of colours, just generate an array of colours following this pattern and use those:</p> <pre><code> static string[] ColourValues = new string[] { "FF0000", "00FF00", "0000FF", "FFFF00", "FF00FF", "00FFFF", "000000", "800000", "008000", "000080", "808000", "800080", "008080", "808080", "C00000", "00C000", "0000C0", "C0C000", "C000C0", "00C0C0", "C0C0C0", "400000", "004000", "000040", "404000", "400040", "004040", "404040", "200000", "002000", "000020", "202000", "200020", "002020", "202020", "600000", "006000", "000060", "606000", "600060", "006060", "606060", "A00000", "00A000", "0000A0", "A0A000", "A000A0", "00A0A0", "A0A0A0", "E00000", "00E000", "0000E0", "E0E000", "E000E0", "00E0E0", "E0E0E0", }; </code></pre> <h1>The Hard Way</h1> <p>If you don't know how many colours you are going to need, the code below will generate up to 896 colours using this pattern. (896 = 256 * 7 / 2) 256 is the colour space per channel, we have 7 patterns and we stop before we get to colours separated by only 1 colour value.</p> <p>I've probably made harder work of this code than I needed to. First, there is an intensity generator which starts at 255, then generates the values as per the pattern described above. The pattern generator just loops through the seven colour patterns.</p> <pre><code>using System; class Program { static void Main(string[] args) { ColourGenerator generator = new ColourGenerator(); for (int i = 0; i &lt; 896; i++) { Console.WriteLine(string.Format("{0}: {1}", i, generator.NextColour())); } } } public class ColourGenerator { private int index = 0; private IntensityGenerator intensityGenerator = new IntensityGenerator(); public string NextColour() { string colour = string.Format(PatternGenerator.NextPattern(index), intensityGenerator.NextIntensity(index)); index++; return colour; } } public class PatternGenerator { public static string NextPattern(int index) { switch (index % 7) { case 0: return "{0}0000"; case 1: return "00{0}00"; case 2: return "0000{0}"; case 3: return "{0}{0}00"; case 4: return "{0}00{0}"; case 5: return "00{0}{0}"; case 6: return "{0}{0}{0}"; default: throw new Exception("Math error"); } } } public class IntensityGenerator { private IntensityValueWalker walker; private int current; public string NextIntensity(int index) { if (index == 0) { current = 255; } else if (index % 7 == 0) { if (walker == null) { walker = new IntensityValueWalker(); } else { walker.MoveNext(); } current = walker.Current.Value; } string currentText = current.ToString("X"); if (currentText.Length == 1) currentText = "0" + currentText; return currentText; } } public class IntensityValue { private IntensityValue mChildA; private IntensityValue mChildB; public IntensityValue(IntensityValue parent, int value, int level) { if (level &gt; 7) throw new Exception("There are no more colours left"); Value = value; Parent = parent; Level = level; } public int Level { get; set; } public int Value { get; set; } public IntensityValue Parent { get; set; } public IntensityValue ChildA { get { return mChildA ?? (mChildA = new IntensityValue(this, this.Value - (1&lt;&lt;(7-Level)), Level+1)); } } public IntensityValue ChildB { get { return mChildB ?? (mChildB = new IntensityValue(this, Value + (1&lt;&lt;(7-Level)), Level+1)); } } } public class IntensityValueWalker { public IntensityValueWalker() { Current = new IntensityValue(null, 1&lt;&lt;7, 1); } public IntensityValue Current { get; set; } public void MoveNext() { if (Current.Parent == null) { Current = Current.ChildA; } else if (Current.Parent.ChildA == Current) { Current = Current.Parent.ChildB; } else { int levelsUp = 1; Current = Current.Parent; while (Current.Parent != null &amp;&amp; Current == Current.Parent.ChildB) { Current = Current.Parent; levelsUp++; } if (Current.Parent != null) { Current = Current.Parent.ChildB; } else { levelsUp++; } for (int i = 0; i &lt; levelsUp; i++) { Current = Current.ChildA; } } } } </code></pre>
128,636
.Net Data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?
<p>.NET has a lot of complex data structures. Unfortunately, some of them are quite similar and I'm not always sure when to use one and when to use another. Most of my C# and VB books talk about them to a certain extent, but they never really go into any real detail.</p> <p>What's the difference between Array, ArrayList, List, Hashtable, Dictionary, SortedList, and SortedDictionary?</p> <p>Which ones are enumerable (IList -- can do 'foreach' loops)? Which ones use key/value pairs (IDict)?</p> <p>What about memory footprint? Insertion speed? Retrieval speed?</p> <p>Are there any other data structures worth mentioning?</p> <p>I'm still searching for more details on memory usage and speed (Big-O notation)</p>
128,754
12
6
null
2008-09-24 17:47:27.897 UTC
111
2022-01-06 16:41:21.393 UTC
2021-07-07 17:52:58.48 UTC
null
21,244
null
21,244
null
1
222
c#|.net|vb.net|arrays|data-structures
169,807
<p>Off the top of my head:</p> <ul> <li><p><code>Array</code>* - represents an old-school memory array - kind of like a alias for a normal <code>type[]</code> array. Can enumerate. Can't grow automatically. I would assume very fast insert and retrival speed.</p></li> <li><p><code>ArrayList</code> - automatically growing array. Adds more overhead. Can enum., probably slower than a normal array but still pretty fast. These are used a lot in .NET</p></li> <li><p><code>List</code> - one of my favs - can be used with generics, so you can have a strongly typed array, e.g. <code>List&lt;string&gt;</code>. Other than that, acts very much like <code>ArrayList</code></p></li> <li><p><code>Hashtable</code> - plain old hashtable. O(1) to O(n) worst case. Can enumerate the value and keys properties, and do key/val pairs</p></li> <li><p><code>Dictionary</code> - same as above only strongly typed via generics, such as <code>Dictionary&lt;string, string&gt;</code></p></li> <li><p><code>SortedList</code> - a sorted generic list. Slowed on insertion since it has to figure out where to put things. Can enum., probably the same on retrieval since it doesn't have to resort, but deletion will be slower than a plain old list.</p></li> </ul> <p>I tend to use <code>List</code> and <code>Dictionary</code> all the time - once you start using them strongly typed with generics, its really hard to go back to the standard non-generic ones.</p> <p>There are lots of other data structures too - there's <code>KeyValuePair</code> which you can use to do some interesting things, there's a <code>SortedDictionary</code> which can be useful as well.</p>
183,791
How would you do a "not in" query with LINQ?
<p>I have two collections which have property <code>Email</code> in both collections. I need to get a list of the items in the first list where <code>Email</code> does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done?</p> <p>So far I have a join, like...</p> <pre><code>var matches = from item1 in list1 join item2 in list2 on item1.Email equals item2.Email select new { Email = list1.Email }; </code></pre> <p>But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet.</p>
183,804
16
1
null
2008-10-08 17:01:40.93 UTC
77
2021-10-27 05:06:39.557 UTC
2015-03-06 20:25:00.807 UTC
null
63,550
Brennan
10,366
null
1
339
c#|linq
372,436
<p>I don't know if this will help you but..</p> <pre><code>NorthwindDataContext dc = new NorthwindDataContext(); dc.Log = Console.Out; var query = from c in dc.Customers where !(from o in dc.Orders select o.CustomerID) .Contains(c.CustomerID) select c; foreach (var c in query) Console.WriteLine( c ); </code></pre> <p>from <a href="https://web.archive.org/web/20120321161927/https://www.programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx" rel="noreferrer">The NOT IN clause in LINQ to SQL</a> by <a href="https://web.archive.org/web/20110805143247/http://introducinglinq.com/blogs/marcorusso/default.aspx" rel="noreferrer">Marco Russo</a></p>
607,863
Do you find java.util.logging sufficient?
<p>Per the title, do you find the default Java logging framework sufficient for your needs?</p> <p>Do you use alternative logging services such as <a href="http://logging.apache.org/log4j/" rel="noreferrer">log4j</a> or others? If so, why? I'd like to hear any advice you have regarding logging requirements in different types of projects, and when integrating frameworks is actually necessary and/or useful.</p>
608,184
17
2
null
2009-03-03 19:51:37.417 UTC
14
2012-07-27 22:47:45.717 UTC
null
null
null
Yuval A
24,545
null
1
42
java|logging|frameworks
11,109
<h3>Logging Dependencies with Third Party Libraries</h3> <p>Java JDK logging in most cases is not insufficient by itself. However, if you have a large project that uses multiple open-source third party libraries, you will quickly discover that many of them have disparate logging dependencies.</p> <p>It is in these cases where the need to abstract your logging API from your logging implementation become important. I recommend using <a href="http://www.slf4j.org/" rel="noreferrer">slf4j</a> or <a href="http://logback.qos.ch/" rel="noreferrer">logback</a> (uses the slf4j API) as your API and if you want to stick with Java JDK logging, you still can! Slf4j can output to many different logger implementations with no problems.</p> <p>A concrete example of its usefulness happened during a recent project: we needed to use third-party libs that needed log4j, but we did not want to run two logging frameworks side by side, so we used the slf4j log4j api wrapper libs and the problem was solved.</p> <p>In summary, Java JDK logging is fine, but a standardized API that is used in my third party libraries will save you time in the long run. Just try to imagine refactoring every logging statement!</p>
1,099,133
What is the purpose of a dedicated "Build Server"?
<p>I haven't worked for very large organizations and I've never worked for a company that had a &quot;Build Server&quot;.</p> <p>What is their purpose?<br /> Why aren't the developers building the project on their local machines, or are they?<br /> Are some projects so large that more powerful machines are needed to build it in a reasonable amount of time?</p> <p>The only place I see a Build Server being useful is for continuous integration with the build server constantly building what is committed to the repository. Is it I have just not worked on projects large enough?</p> <p>Someone, please enlighten me: What is the purpose of a build server?</p>
1,099,146
18
0
null
2009-07-08 16:24:51.657 UTC
38
2021-10-08 15:30:52.763 UTC
2021-10-08 15:30:52.763 UTC
user1228
8,014,824
null
64,878
null
1
106
build|continuous-integration|agile|build-server
59,302
<p>The reason given is actually a huge benefit. Builds that go to QA should only ever come from a system that builds only from the repository. This way build packages are reproducible and traceable. Developers manually building code for anything except their own testing is dangerous. Too much risk of stuff not getting checked in, being out of date with other people's changes, etc. etc.</p> <p><a href="http://www.joelonsoftware.com/articles/fog0000000023.html" rel="noreferrer">Joel Spolsky on this matter.</a></p>
779,929
ID, id, or Id?
<p>I use <code>camelCase</code> in my code and database field names, etc, but with fields that have <code>Id</code> at the end, it always ends up being hard to read. For example, <code>itemId</code>, <code>teacherId</code>, <code>unitId</code>, etc. In these cases I consider breaking convention and writing <code>itemID, teacherID, or unitID</code> just for improved readability.</p> <p>What do you do and what's a general, best practice of dealing with this issue?</p>
779,933
20
0
null
2009-04-23 01:13:35.337 UTC
4
2020-04-13 21:57:01.837 UTC
2009-04-23 04:56:48.683 UTC
null
811
null
49,153
null
1
34
variables|naming-conventions
20,729
<p>I do what I feel like. In general, your best practice is to err in favor of readability vs. compliance with some abstract standard. </p> <p>Just be consistent.</p>
34,648,186
Split at last occurrence of character then join
<p>I would like to split an <code>attribute</code> at the last occurrence of a character, then add a string and join the array back together. Here is a simplified <strong><a href="https://jsfiddle.net/Ldjoqtk1/1/" rel="noreferrer">demo</a></strong>.</p> <p>In the demo I would like to split the <code>src</code> attribute at the last occurrence of the <code>.</code> and then add <code>-fx</code> to the <code>src</code> path.</p> <p><strong>original <code>src</code> attributes</strong></p> <p><code>src="extension.jpg"</code> <code>src="ext.ension.jpg"</code></p> <p><strong>what I am hoping to get</strong></p> <p><code>src="extension-fx.jpg"</code> <code>src="ext.ension-fx.jpg"</code></p> <p>To be more specific, the issue is that if I <code>split('.')</code> and the path has multiple <code>.</code> problems arise (<code>-fx</code> not added properly).</p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('img').each(function(){ var a = $(this).attr('src'); var b = a.split('.') var c = b[0] + '-fx' + '.' + b[1]; console.log(c); $(this).attr('src', c); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>img { height: 100px; width: 100px; background: red; } img[src*="-fx.jpg"] { background: blue; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;img src="extension.jpg"&gt; &lt;img src="ext.ension.jpg"&gt;</code></pre> </div> </div> </p>
34,648,267
4
5
null
2016-01-07 05:50:18.81 UTC
2
2022-02-16 08:59:27.78 UTC
2016-01-07 05:52:31.07 UTC
null
3,126,477
null
3,126,477
null
1
26
javascript|jquery|css|regex
39,882
<p>You can use <a href="http://api.jquery.com/attr/#attr-attributeName-function" rel="noreferrer"><code>.attr( attributeName, function )</code></a> with callback function to update the attribute value of respective element. To add the string <code>-fx</code> in the src attribute, <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf" rel="noreferrer"><code>String#lastIndexOf</code></a> and <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/substring" rel="noreferrer"><code>String#substring</code></a> can be used.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Get the src attribute value of image one by one $('img').attr('src', function(i, src) { // Get the index of the last . var lastIndex = src.lastIndexOf('.'); // Add the string before the last . // Return updated string, this will update the src attribute value return src.substr(0, lastIndex) + '-fx' + src.substr(lastIndex); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>img { height: 100px; width: 100px; background: red; } img[src$="-fx.jpg"] { background: blue; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;img src="extension.jpg" /&gt; &lt;img src="ext.ension.jpg" /&gt;</code></pre> </div> </div> </p> <p><strong>Note:</strong> The selector used <code>img[src*="-fx.jpg"]</code> will select all the images whose <code>src</code> attribute value contains the given string anywhere. To select images whose <code>src</code> value ends with given string, use <code>$=</code> selector.</p> <pre><code>img[src$="-fx.jpg"] ^ </code></pre> <hr> <p>If you want to use regex, following regex can be used.</p> <pre><code>(\.(?:jpe?g|png|gif))$/ </code></pre> <p><a href="https://regex101.com/r/cC8nI7/2" rel="noreferrer"><strong>Demo</strong></a></p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Get the src attribute value of image one by one $('img').attr('src', function(i, src) { return src.replace(/(\.(?:jpe?g|png|gif))$/, "-fx$1"); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>img { height: 100px; width: 100px; background: red; } img[src$="-fx.jpg"] { background: blue; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;img src="extension.jpg" /&gt; &lt;img src="ext.ension.jpg" /&gt;</code></pre> </div> </div> </p>
6,351,823
How to check if a column exists before adding it to an existing table in PL/SQL?
<p>How do I add a simple check before adding a column to a table for an oracle db? I've included the SQL that I'm using to add the column.</p> <pre><code>ALTER TABLE db.tablename ADD columnname NVARCHAR2(30); </code></pre>
6,352,261
4
0
null
2011-06-15 00:48:04.64 UTC
11
2021-03-11 10:27:50.93 UTC
2011-06-15 03:26:54.69 UTC
null
135,152
null
123,451
null
1
71
sql|oracle|plsql
163,821
<p>All the metadata about the columns in Oracle Database is accessible using one of the following views.</p> <p><a href="http://download.oracle.com/docs/cd/E11882_01/server.112/e17110/statviews_5465.htm#REFRN26276" rel="noreferrer">user_tab_cols</a>; -- For all tables owned by the user</p> <p><a href="http://download.oracle.com/docs/cd/E11882_01/server.112/e17110/statviews_2102.htm#I1020276" rel="noreferrer">all_tab_cols</a> ; -- For all tables accessible to the user</p> <p><a href="http://download.oracle.com/docs/cd/E11882_01/server.112/e17110/statviews_5043.htm#REFRN23276" rel="noreferrer">dba_tab_cols</a>; -- For all tables in the Database.</p> <p>So, if you are looking for a column like ADD_TMS in SCOTT.EMP Table and add the column only if it does not exist, the PL/SQL Code would be along these lines..</p> <pre><code>DECLARE v_column_exists number := 0; BEGIN Select count(*) into v_column_exists from user_tab_cols where upper(column_name) = 'ADD_TMS' and upper(table_name) = 'EMP'; --and owner = 'SCOTT --*might be required if you are using all/dba views if (v_column_exists = 0) then execute immediate 'alter table emp add (ADD_TMS date)'; end if; end; / </code></pre> <p>If you are planning to run this as a script (not part of a procedure), the easiest way would be to include the alter command in the script and see the errors at the end of the script, assuming you have no Begin-End for the script..</p> <p>If you have file1.sql</p> <pre><code>alter table t1 add col1 date; alter table t1 add col2 date; alter table t1 add col3 date; </code></pre> <p>And col2 is present,when the script is run, the other two columns would be added to the table and the log would show the error saying "col2" already exists, so you should be ok.</p>
6,625,849
Compare these products for PDF generation with Java given requirements inside: iText, Apache PDFBox or FOP?
<p>There were questions on that but not recently and technology must have gone ahead since then. </p> <p>Requirements:</p> <ul> <li>generating pdf documents based on predefined template (I can use either pdf forms or xsl-fo)</li> <li>being able to fill textual data</li> <li>being able to fill graphical data (generated bar codes)</li> <li>being able to alter pdf template in production environment without patching (recompiling)</li> <li>generating pdf file to be saved in the database (as blob) and/or printed</li> <li>open source/free</li> </ul> <p>The options assumed are iText, PDFBox, FOP, anything else? What are recommendations based on the requirements above?</p>
6,626,008
7
5
null
2011-07-08 14:23:30.877 UTC
21
2021-07-19 12:09:24.243 UTC
2021-07-19 12:09:24.243 UTC
null
5,024,726
null
59,470
null
1
42
java|itext|pdf-generation|apache-fop|openpdf
66,007
<ol> <li>iText; nowadays iText is a commercial library, the latest version is not for free anymore (a fork of an older version remains under MIT license: <a href="https://github.com/LibrePDF/OpenPDF" rel="nofollow noreferrer">OpenPDF</a>)</li> <li>FOP; I worked a lot with FOP. It's fairly resource intensive (Java > XML > XSLT > PDF) and complex PDFs become a nightmare ( may result in XSLTs with 20k+ LoC)</li> <li>PDFBox; it seems to be the best alternative although I did not work with it in large projects</li> <li>Did not check Flying Saucer yet</li> </ol> <p>To conclude, I'd give PDFBox a try. Depending on your bar code requirements you may need to inline your barcode (font) into the PDF or distribute the font to your clients - take care of those issues.</p>
6,624,819
C++ vector of objects vs. vector of pointers to objects
<p>I am writing an application using openFrameworks, but my question is not specific to just oF; rather, it is a general question about C++ vectors in general.</p> <p>I wanted to create a class that contains multiple instances of another class, but also provides an intuitive interface for interacting with those objects. Internally, my class used a vector of the class, but when I tried to manipulate an object using vector.at(), the program would compile but not work properly (in my case, it would not display a video).</p> <pre><code>// instantiate object dynamically, do something, then append to vector vector&lt;ofVideoPlayer&gt; videos; ofVideoPlayer *video = new ofVideoPlayer; video-&gt;loadMovie(filename); videos.push_back(*video); // access object in vector and do something; compiles but does not work properly // without going into specific openFrameworks details, the problem was that the video would // not draw to screen videos.at(0)-&gt;draw(); </code></pre> <p>Somewhere, it was suggested that I make a vector of pointers to objects of that class instead of a vector of those objects themselves. I implemented this and indeed it worked like a charm.</p> <pre><code>vector&lt;ofVideoPlayer*&gt; videos; ofVideoPlayer * video = new ofVideoPlayer; video-&gt;loadMovie(filename); videos.push_back(video); // now dereference pointer to object and call draw videos.at(0)-&gt;draw(); </code></pre> <p>I was allocating memory for the objects dynamically, i.e. <code>ofVideoPlayer = new ofVideoPlayer;</code></p> <p>My question is simple: why did using a vector of pointers work, and when would you create a vector of objects versus a vector of pointers to those objects?</p>
6,625,042
7
3
null
2011-07-08 13:03:55.633 UTC
30
2021-08-26 17:35:15.467 UTC
2013-07-26 17:11:18.59 UTC
null
1,009,479
null
565,911
null
1
47
c++|pointers|vector
48,276
<blockquote> <p>My question is simple: why did using a vector of pointers work, and when would you create a vector of objects versus a vector of pointers to those objects?</p> </blockquote> <p><code>std::vector</code> is like a raw array allocated with new and reallocated when you try to push in more elements than its current size.</p> <p>So, if it contains <code>A</code> pointers, it's like if you were manipulating an array of <code>A*</code>. When it needs to resize (you <code>push_back()</code> an element while it's already filled to its current capacity), it will create another <code>A*</code> array and copy in the array of <code>A*</code> from the previous vector.</p> <p>If it contains <code>A</code> objects, then it's like you were manipulating an array of <code>A</code>, so <code>A</code> should be default-constructible if there are automatic reallocations occuring. In this case, the whole <code>A</code> objects get copied too in another array.</p> <p>See the difference? <strong>The <code>A</code> objects in <code>std::vector&lt;A&gt;</code> can change address if you do some manipulations that requires the resizing of the internal array.</strong> That's where most problems with containing objects in <code>std::vector</code> comes from.</p> <p>A way to use <code>std::vector</code> without having such problems is to allocate a large enough array from the start. <strong>The keyword here is "capacity".</strong> The <code>std::vector</code> capacity is the <em>real</em> size of the memory buffer in which it will put the objects. So, to setup the capacity, you have two choices: </p> <p>1) size your <code>std::vector</code> on construction to build all the object from the start , with maximum number of objects - that will call constructors of each objects. </p> <p>2) once the <code>std::vector</code> is constructed (but has nothing in it), <strong>use its <code>reserve()</code> function</strong> : the vector will then allocate a large enough buffer (you provide the maximum size of the vector). <strong>The vector</strong> will set the capacity. If you <code>push_back()</code> objects in this vector or <code>resize()</code> under the limit of the size you've provided in the <code>reserve()</code> call, it will never reallocate the internal buffer and your objects will not change location in memory, making pointers to those objects always valid (some assertions to check that change of capacity never occurs is an excellent practice).</p>
6,614,228
C# get all elements of array
<p>Using <code>array.ElementAt(0);</code> we can get the element at index 0 of the array. Is there a method to get all the elements in an array?</p> <pre><code>string[] arr1 = {'abc', 'def', 'ghi'} Library.Results["TEST_ACTUALVALUE"] = "The results are: " + arr1; </code></pre> <p>TEST_ACTUALVALUE is a column in my report.xls file. The above writes System.string[] in my excel file.</p>
6,614,252
10
4
null
2011-07-07 16:55:02.787 UTC
2
2017-08-23 05:16:29.593 UTC
2011-07-07 17:05:25.73 UTC
null
749,097
null
749,097
null
1
6
c#|arrays
85,912
<p>You already have all of the elements in the array...the array itself. </p> <p>The simple answer is iterate over them:</p> <pre><code>foreach(var item in array) { // work with item here } </code></pre> <p>Or if you'd rather deal with indexes:</p> <pre><code>for(var i = 0; i &lt; array.Length; i++) { var item = array[i]; // work with item here } </code></pre>
38,086,542
Break long dependencies in Makefile into several lines
<p><code>target: TargetA ../DirB/FileB.cpp ../DirC/FileC.o ../DirD/FileD.o ...</code></p> <p>This is a long line in a make file. Is it possible to break this into several lines?</p>
38,104,673
2
1
null
2016-06-28 21:23:03.223 UTC
1
2016-06-29 15:58:37.817 UTC
null
null
null
null
5,302,241
null
1
28
makefile
15,098
<p>There are a couple ways of doing this. One simple way:</p> <pre><code>target: targetA targetB target: targetC targetD target: @echo $@ is dependent on $? </code></pre> <p>Note that this will not work with pattern rules through (rules with <code>%</code> in the targets/dependencies). If you are using pattern rules (and even if you're not), you can consider doing something like:</p> <pre><code>TARGET_DEPS := targetA targetB TARGET_DEPS += targetC TARGET_DEPS += targetD target: $(TARGET_DEPS) @echo $@ is dependent on $? </code></pre> <p>While it's possible to use the backslash, I personally find this makes the makefiles harder to read as the meaning of the indentation becomes unclear.</p>
10,683,773
What is "undefined x 1" in JavaScript?
<p>I'm doing some small experiments based on <a href="http://perfectionkills.com/understanding-delete/" rel="noreferrer"><strong><em>this blog entry</em></strong></a>.</p> <p>I am doing this research in Google Chrome's debugger and here comes the hard part.</p> <p><img src="https://i.stack.imgur.com/asltc.jpg" alt="What the heck is this?!"></p> <p>I get the fact that I can't delete local variables (since they are not object attributes). I get that I can 'read out' all of the parameters passed to a function from the array called 'arguments'. I even get it that I can't delete and array's element, only achieve to have <strong><code>array[0]</code></strong> have a value of undefined.</p> <p>Can somebody explain to me what <strong><code>undefined x 1</code></strong> means on the embedded image?</p> <p>And when I overwrite the function <strong><code>foo</code></strong> to return the <strong><code>arguments[0]</code></strong>, then I get the usual and 'normal' undefined.</p> <p>This is only an experiment, but seems interresting, does anybody know what <strong><code>undefined x 1</code></strong> refers to?</p>
10,683,811
5
6
null
2012-05-21 10:43:38.01 UTC
3
2018-10-31 16:23:46.44 UTC
2012-05-21 10:54:29.293 UTC
null
218,196
null
819,194
null
1
29
javascript|arrays|oop|arguments
12,809
<p>That seems to be Chrome's new way of displaying uninitialized indexes in arrays (and <em>array-like</em> objects):</p> <pre><code>&gt; Array(100) [undefined Γ— 100] </code></pre> <p>Which is certainly better than printing <code>[undefined, undefined, undefined,...]</code> or however it was before.</p> <p>Although, if there is only one <code>undefined</code> value, they could drop the <code>x 1</code>.</p>
25,245,088
Swipe Refresh Layout in Android Fragment
<p>Im trying to implement SwipeRefreshLayout on a Fragment.</p> <p>I already solved it to implement it on an Activity, but when I implement it on Fragment: java.lang.NoClassDefFoundError: com...</p> <p>Does anyone has an idea? Thanks!</p> <p>Similar post without answers/solution: <a href="https://stackoverflow.com/questions/24495952/swipe-refresh-layout-class-not-found">Swipe Refresh Layout - Class not found</a></p> <p>My code:</p> <pre><code>public class Principal extends Fragment implements OnRefreshListener { SwipeRefreshLayout swipeLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.principal, container, false); swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container); swipeLayout.setOnRefreshListener(this); swipeLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); return view; } } </code></pre> <p>And my layout:</p> <pre><code>&lt;android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swipe_container" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;com.enhancedListView.EnhancedListView android:id="@+id/listaNoticias" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="6dp" android:layout_marginRight="6dp" android:layout_marginTop="5dp" &gt; &lt;/com.enhancedListView.EnhancedListView&gt; &lt;/android.support.v4.widget.SwipeRefreshLayout&gt; </code></pre> <p>Full stack trace</p> <pre><code>08-13 11:36:19.292: E/AndroidRuntime(31572): FATAL EXCEPTION: main 08-13 11:36:19.292: E/AndroidRuntime(31572): Process: com.xxx.xx, PID: 31572 08-13 11:36:19.292: E/AndroidRuntime(31572): java.lang.NoClassDefFoundError: com.xxx.fragments.Principal 08-13 11:36:19.292: E/AndroidRuntime(31572): at com.xxx.hem.activities.MainActivity.CargarPrincipal(MainActivity.java:676) 08-13 11:36:19.292: E/AndroidRuntime(31572): at com.xxx.hem.activities.MainActivity.onCreate(MainActivity.java:297) 08-13 11:36:19.292: E/AndroidRuntime(31572): at android.app.Activity.performCreate(Activity.java:5231) 08-13 11:36:19.292: E/AndroidRuntime(31572): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 08-13 11:36:19.292: E/AndroidRuntime(31572): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148) 08-13 11:36:19.292: E/AndroidRuntime(31572): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 08-13 11:36:19.292: E/AndroidRuntime(31572): at android.app.ActivityThread.access$800(ActivityThread.java:135) 08-13 11:36:19.292: E/AndroidRuntime(31572): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 08-13 11:36:19.292: E/AndroidRuntime(31572): at android.os.Handler.dispatchMessage(Handler.java:102) 08-13 11:36:19.292: E/AndroidRuntime(31572): at android.os.Looper.loop(Looper.java:136) 08-13 11:36:19.292: E/AndroidRuntime(31572): at android.app.ActivityThread.main(ActivityThread.java:5001) 08-13 11:36:19.292: E/AndroidRuntime(31572): at java.lang.reflect.Method.invoke(Native Method) 08-13 11:36:19.292: E/AndroidRuntime(31572): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 08-13 11:36:19.292: E/AndroidRuntime(31572): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) </code></pre>
25,370,382
3
4
null
2014-08-11 13:58:44.757 UTC
6
2019-12-12 14:56:18.903 UTC
2016-08-04 11:07:39.607 UTC
null
1,276,636
null
2,855,036
null
1
14
android|android-fragments|noclassdeffounderror
38,318
<p>Solved it :)</p> <p>My XML</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swipe_container" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;com.enhancedListView.EnhancedListView android:id="@+id/listaNoticias" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="6dp" android:layout_marginRight="6dp" android:layout_marginTop="5dp" &gt; &lt;/com.enhancedListView.EnhancedListView&gt; &lt;/android.support.v4.widget.SwipeRefreshLayout&gt; </code></pre> <p>My Fragment</p> <pre><code>public class Principal extends Fragment implements OnRefreshListener { SwipeRefreshLayout swipeLayout; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.principal, container, false); swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container); swipeLayout.setOnRefreshListener(this); swipeLayout.setColorSchemeColors(android.R.color.holo_green_dark, android.R.color.holo_red_dark, android.R.color.holo_blue_dark, android.R.color.holo_orange_dark); (...) @Override public void onRefresh() { new myTask().execute(); } </code></pre>
4,806,322
Connection string to Oracle 10g DB using VB.net
<p>Hey all i am VERY new to a Oracle DB and i am trying to connect to it via VB.net 2010. I have been trying the following:</p> <pre><code>Dim myConnection As OleDbConnection Dim myCommand As OleDbCommand Dim dr As OleDbDataReader myConnection = New OleDbConnection("Provider=MSDAORA.1;UserID=xxxx;password=xxxx; database=xxxx") 'MSDORA is the provider when working with Oracle Try myConnection.Open() 'opening the connection myCommand = New OleDbCommand("Select * from emp", myConnection) 'executing the command and assigning it to connection dr = myCommand.ExecuteReader() While dr.Read() 'reading from the datareader MessageBox.Show("EmpNo" &amp; dr(0)) MessageBox.Show("EName" &amp; dr(1)) MessageBox.Show("Job" &amp; dr(2)) MessageBox.Show("Mgr" &amp; dr(3)) MessageBox.Show("HireDate" &amp; dr(4)) 'displaying data from the table End While dr.Close() myConnection.Close() Catch ee As Exception End Try </code></pre> <p>And i get the error on the Catch ee As Exception line: <strong>ORA-12560: TNS:protocol adapter error</strong></p> <p>I also have a tnsnames.ora file on my computer but i am unsure if i need to use that when connecting (or really, how too in the first place)? Is it needed for the code above?</p> <p>I am trying to use a DNS-Less connection to the DB. Not sure if that is what it is doing in this or not?</p> <p>Any help would be great!!! :o)</p> <p>David</p>
4,806,400
2
0
null
2011-01-26 15:26:59.217 UTC
2
2011-04-01 16:55:17.643 UTC
2011-04-01 16:55:17.643 UTC
null
135,152
null
277,480
null
1
2
vb.net|oracle|visual-studio-2010|connection-string|ora-12560
39,240
<p>There are many ways: the one I use almost every time that doesn't require an entry in TNSNAMES.ORA is this:</p> <pre><code>Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword; </code></pre> <p>And if you don't need an OleDb connection I think you should use System.Data.OracleClient or any other free provider (like <a href="http://www.devart.com/dotconnect/oracle/" rel="nofollow">DevArt dotConnect for Oracle Express</a>)</p> <p>Source: <a href="http://www.connectionstrings.com/oracle" rel="nofollow">http://www.connectionstrings.com/oracle</a></p>
53,248,736
ListAdapter submitList() - How to scroll to beginning
<p>I have an issue with my RecyclerView and ListAdapter.</p> <p>Through an API, I receive items in a ascending order from older to newer.</p> <p>My list is then being refreshed by calling the submitList(items) method.</p> <p>However, since everything is asynchronous, after receiving the first item, the RecyclerView remains on the position of the first item received and showed. Since in the ListAdapter class there is no callback when the submitList() method completed, I cannot find a way to scroll after the updates to one of the new items that has been added.</p> <p>Is there a way to intercept when ListAdapter has been updated ?</p>
55,054,002
4
6
null
2018-11-11 12:24:58.23 UTC
3
2021-09-02 10:43:04.73 UTC
2019-03-14 08:35:26.353 UTC
null
9,799,857
null
5,292,951
null
1
48
android|android-recyclerview|listadapter
9,810
<p>Not specific to ListAdapter, but it should work nonetheless:</p> <p>Just use <a href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#registerAdapterDataObserver(android.support.v7.widget.RecyclerView.AdapterDataObserver)" rel="noreferrer"><code>adapter.registerAdapterDataObserver(RecyclerView.AdapterDataObserver)</code></a> and override the relevant onItemXXX method to tell your RecyclerView to scroll to whatever position.</p> <p>As an example:</p> <pre><code> adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { (recycler_view.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(positionStart, 0) } }) </code></pre>
13,558,159
sprintf not declared in scope?
<p>I have a small snippet of code here from something I designed but I keep getting the error :</p> <pre><code>sprintf not declared in scope </code></pre> <p>Do I include something in the #includes or how can I get this working? I was working on it on VS at my mom's but came home and I can't get it on code blocks</p> <pre class="lang-cpp prettyprint-override"><code>if (tmp2 &lt;= B_dest[hr - 6]) { sprintf(name, &quot;B%d&quot;, tmp3); }else{ sprintf(name, &quot;A%d&quot;, tmp3); } </code></pre>
13,558,186
3
1
null
2012-11-26 03:07:19.043 UTC
3
2021-04-25 05:30:32.503 UTC
2021-04-25 05:30:32.503 UTC
null
11,573,842
null
330,396
null
1
16
c++
45,995
<p>You need to include <code>stdio.h</code>. </p> <pre><code>#include&lt;stdio.h&gt; </code></pre> <p>The <code>stdio.h</code> declares the function <code>sprintf</code>, Without the header the compiler has no way of understand what <code>sprintf</code> means and hence it gives you the error.</p> <p>In C++ Note that, </p> <p>Including <code>cstdio</code> imports the symbol names in <code>std</code> namespace and <em>possibly</em> in Global namespace.<br> Including <code>stdio.h</code> imports the symbol names in Global namespace and <em>possibly</em> in <code>std</code> namespace. </p> <p>The same applies for all c-styled headers.</p>
13,600,480
Extract data from XML Clob using SQL from Oracle Database
<p>I want to extract the value of Decision using sql from table TRAPTABCLOB having column testclob with XML stored as clob. </p> <p>Sample XML as below.</p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;DCResponse&gt; &lt;Status&gt;Success&lt;/Status&gt; &lt;Authentication&gt; &lt;Status&gt;Success&lt;/Status&gt; &lt;/Authentication&gt; &lt;ResponseInfo&gt; &lt;ApplicationId&gt;5701200&lt;/ApplicationId&gt; &lt;SolutionSetInstanceId&gt; 63a5c214-b5b5-4c45-9f1e-b839a0409c24 &lt;/SolutionSetInstanceId&gt; &lt;CurrentQueue /&gt; &lt;/ResponseInfo&gt; &lt;ContextData&gt; &lt;!--Decision Details Start--&gt; &lt;Field key="SoftDecision"&gt;A&lt;/Field&gt; &lt;Field key="**Decision**"&gt;1&lt;/Field&gt; &lt;Field key="NodeNo"&gt;402&lt;/Field&gt; &lt;Field key="NodeDescription" /&gt; &lt;!--Decision Details End--&gt; &lt;!--Error Details Start--&gt; &lt;Field key="ErrorResponse"&gt; &lt;Response&gt; &lt;Status&gt;[STATUS]&lt;/Status&gt; &lt;ErrorCode&gt;[ERRORCODE]&lt;/ErrorCode&gt; &lt;ErrorDescription&gt;[ERRORDESCRIPTION]&lt;/ErrorDescription&gt; &lt;Segment&gt;[SEGMENT]&lt;/Segment&gt; &lt;/Response&gt; &lt;/Field&gt; &lt;Field key="ErrorCode"&gt;0&lt;/Field&gt; &lt;Field key="ErrorDescription" /&gt; &lt;/ContextData&gt; &lt;/DCResponse&gt; </code></pre>
13,601,681
2
0
null
2012-11-28 08:04:07.403 UTC
7
2015-06-22 13:12:17.65 UTC
2012-11-28 08:54:10.467 UTC
null
1,138,658
null
1,859,050
null
1
19
sql|xml|oracle|parsing|clob
115,513
<p>Try</p> <pre><code>SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]') FROM traptabclob; </code></pre> <p><a href="http://www.sqlfiddle.com/#!4/cc513/4" rel="noreferrer">Here</a> is a sqlfiddle demo</p>
13,755,163
What do I need to add into OnModelCreating(DbModelBuilder modelBuilder) function to define relations between Person and Role?
<p>I'm using EntityFramework version 5.0 in WinForms project, .net 4.5.</p> <p>I have created 2 for me important Entities</p> <pre class="lang-cs prettyprint-override"><code> public class Role { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Name { get; set; } public bool StockPermission { get; set; } public bool ItemPermission { get; set; } public bool OrderPermission { get; set; } public bool PersonPermission { get; set; } public bool StatisticPermission { get; set; } } public class Person { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public String Name { get; set; } public String Nickname { get; set; } public String Contact { get; set; } public System.DateTime Created { get; set; } public String Pincode { get; set; } public virtual ICollection&lt;Role&gt; Role { get; set; } public virtual Person Creator { get; set; } } </code></pre> <p>and dbContext class:</p> <pre class="lang-cs prettyprint-override"><code> public class SusibarDbContext : DbContext { public DbSet&lt;Entity.Role&gt; Roles { get; set; } public DbSet&lt;Entity.Person&gt; Persons { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //base.OnModelCreating(modelBuilder); } } </code></pre> <p>please, can you help me what I need to add into <code>OnModelCreating(DbModelBuilder modelBuilder)</code> function to define relations between Person and Role?</p> <p>Person can have many Role(s) (but can't be null), different Persons can have same Role(s).</p> <p>Person can have one "creator" Person (can be null), different Persons can have same "creator"</p> <p>If you could be so kind, just advise me solution :-(</p>
13,776,006
3
1
null
2012-12-07 00:36:33.157 UTC
8
2015-07-15 00:10:11.77 UTC
2015-07-15 00:10:11.77 UTC
null
1,664,443
null
1,176,409
null
1
20
c#|entity-framework|entity-framework-5|dbcontext
71,344
<p>If you want to use Fluent API for it, look at <a href="http://msdn.microsoft.com/en-US/data/jj591620" rel="noreferrer">this topic</a> from MSDN. You should use Many-to-Many relationship and EF will create a table required for case when Person can have many Roles and Role have many Persons. Something like this:</p> <pre><code>modelBuilder.Entity&lt;Person&gt;().HasMany(x =&gt; x.Roles).WithMany(); </code></pre> <p>Also you can create this relationship without using Fluent API. You should create navigation property <code>ICollection&lt;Person&gt; Persons</code> in Role class and EF will create appropriate table and relationship as well.</p>
13,505,562
getting "index" of set element via iterator
<p>This question applies to both <code>std::set</code> and <code>std::unsorted_set</code>.</p> <p>I have an iterator to an element in a set. I'd like to use the iterator to get an "index" for the element based on its location in the set.</p> <p>For example, the indices for my set would be as follows:</p> <pre><code>int index = 0; for(MySetType::iterator begin = mySet.begin(); begin != mySet.end(); begin++) { cout &lt;&lt; "The index for this element is " &lt;&lt; index; index++; } </code></pre> <p>I have tried doing arithmetic using iterators but it doesn't work:</p> <pre><code>int index = mySetIterator - mySet.begin(); </code></pre> <p>Is there any way to use the iterator to get an index value like this based on its location in the set?</p>
13,505,578
3
1
null
2012-11-22 03:40:50.373 UTC
4
2020-11-14 12:51:13.673 UTC
null
null
null
null
974,967
null
1
23
c++|stl|iterator
49,131
<p>Use <a href="https://en.cppreference.com/w/cpp/iterator/distance" rel="noreferrer">STL distance</a>, namely <code>std::distance(set.begin(), mySetIterator)</code></p> <p>Please note that:</p> <blockquote> <p>Returns the number of elements between first and last. The <strong>behavior is undefined</strong> if last is not reachable from first by (possibly repeatedly) incrementing first.</p> </blockquote> <p>Remark : Complexity is linear;</p> <blockquote> <p>However, if InputIt additionally meets the requirements of LegacyRandomAccessIterator, complexity is constant.</p> </blockquote>
13,698,779
timezone with DST handling by PHP
<p>I am working on a calendar application. In this users from different time-zones create/view events. I am thinking to follow below method to save event time in UTC and display them in user's local time. Note: user has their preferred timezone setting.</p> <p><strong>To save event start time as UTC timestamp:</strong></p> <pre><code>$timezone = new DateTimeZone( $user_timezone_name ); $utcOffset = $timezone-&gt;getOffset( new DateTime( $event_start_time_string_local ) ); $event_start_timestamp_local = maketime( $event_start_time_string_local ); //Now add/subtract $utcOffset to/from $event_start_timestamp_local to get event's start //time timestamp in UTC and save this result in DB. </code></pre> <p><strong>To get event start time in user's timezone:</strong></p> <pre><code>date_default_timezone_set( $user_timezone_name ); $eventTimeLocalTime = date("Y-m-d H:i:s", $event_start_timestamp_in_UTC ); </code></pre> <p>Where:</p> <pre><code>user_timezone_name is user's timezone setting. event_start_time_string_local is event's start time string in local/civil time. event_start_timestamp_in_UTC is event's start time timestamp in UTC. </code></pre> <p><strong>My questions:</strong> </p> <ul> <li>Whether the PHP APIs used above take care of DST for all regions?</li> <li>The DST time itself changes in different years, how does PHP gets information about this? do we need to upgrade PHP? If so do we need to upgrade all or particular PHP library?</li> </ul> <p>References: - <a href="https://stackoverflow.com/questions/7660240/does-phps-date-default-timezone-set-adjust-to-daylight-saving?rq=1">does-phps-date-default-timezone-set-adjust-to-daylight-saving</a> - <a href="https://stackoverflow.com/questions/3910500/get-timezone-offset-for-a-given-location?rq=1">get-timezone-offset-for-a-given-location</a></p>
13,698,860
2
0
null
2012-12-04 08:30:34.847 UTC
9
2019-10-22 04:30:25.787 UTC
2017-05-23 11:47:18.267 UTC
null
-1
null
1,060,044
null
1
25
php|datetime|utc|dst|timezone-offset
34,131
<p>You're way too overcomplicating this. To convert between two timezones using <code>DateTime</code>, do this:</p> <pre><code>date_default_timezone_set('Asia/Kolkata'); // YOUR timezone, of the server $date = new DateTime($input, new DateTimeZone('Asia/Tokyo')); // USER's timezone $date-&gt;setTimezone(new DateTimeZone('UTC')); echo $date-&gt;format('Y-m-d H:i:s'); </code></pre> <p>This converts from a user's local timezone to UTC. To go the other way around, to display the time in the user's local time, swap the two timezones.</p> <p>Yes, PHP takes care of DST. The necessary conversion rules are part of the PHP installation. You can keep them up to date by updating PHP, or by updating the <a href="https://pecl.php.net/package/timezonedb." rel="noreferrer">timezonedb</a>.</p>
13,624,097
Change directory and execute file in one command
<p>When I want to execute a file, it seems that I always have to first 'cd' into that file's directory before executing it, unless it fails on a can't-find-my-dataz type error. </p> <p>How can I get around typing two commands to just execute a program?</p> <p>Example: </p> <pre><code>cd /usr/local/bin/minecraft/ java -Xms512M -Xmx2048M -jar minecraft.jar </code></pre> <p>How can I make that into one line, so as I can put it as my Exec=<em>_</em> line when creating a custom launcher in Gnome3?</p>
13,624,172
3
0
null
2012-11-29 10:50:39.543 UTC
6
2022-06-28 01:49:03.103 UTC
null
null
null
null
1,239,186
null
1
34
linux|bash|fedora|launcher|gnome-3
43,346
<p><code>cd /usr/local/bin/minecraft/ &amp;&amp; java -Xms512M -Xmx2048M -jar minecraft.jar</code> should do it</p>
13,780,153
UICollectionView: Animate cell size change on selection
<p>What I want to do is change the size of an UICollectionViewCell, and to animate that change, when the cell is selected. I already managed to do that unanimated by marking a cell as selected in <code>collectionView: didSelectItemAtIndexPath:</code> and then calling <code>reloadData</code> on my UICollectionView, displaying the selected cell with a different size.</p> <p>Nevertheless, this happens all at once, and I have no clue how to get that change in size animated. Any ideas?</p> <p>I already found <a href="https://stackoverflow.com/questions/12885003/animate-uicollectionview-cells-on-selection">Animate uicollectionview cells on selection</a>, but the answer was to unspecific for me and I didn't figure out yet if it could also help me in my case.</p>
13,780,259
10
0
null
2012-12-08 17:51:08.893 UTC
49
2021-11-09 22:11:52.517 UTC
2018-10-09 15:53:12.007 UTC
null
8,372,062
null
1,279,298
null
1
66
ios|swift|uicollectionview
86,897
<pre><code>[UIView transitionWithView:collectionView duration:.5 options:UIViewAnimationOptionTransitionCurlUp animations:^{ //any animatable attribute here. cell.frame = CGRectMake(3, 14, 100, 100); } completion:^(BOOL finished) { //whatever you want to do upon completion }]; </code></pre> <p>Play around with something along those lines inside your <code>didselectItemAtIndexPath</code> method.</p>
13,270,491
How do I get the intersection between two arrays as a new array?
<p>I faced this problem many times during various situations. It is generic to all programming languages although I am comfortable with C or Java.</p> <p>Let us consider two arrays (or collections):</p> <pre><code>char[] A = {'a', 'b', 'c', 'd'}; char[] B = {'c', 'd', 'e', 'f'}; </code></pre> <p>How do I get the common elements between the two arrays as a new array? In this case, the intersection of array A and B is <code>char[] c = {'c', 'd'}</code>.</p> <p>I want to avoid the repeated iteration of one array inside the other array which will increase the execution time by (length of A times length of B) which is too much in the case of huge arrays.</p> <p>Is there any way we could do a single pass in each array to get the common elements?</p>
13,270,836
22
14
null
2012-11-07 13:11:01.43 UTC
33
2018-05-23 09:22:03.18 UTC
2016-09-22 15:50:23.79 UTC
null
2,756,409
null
1,314,439
null
1
72
java|c++|c|algorithm
83,501
<p>Since this looks to me like a string algorithm, I'll assume for a moment that its not possible to sort this sequence (hence string) then you can use <a href="http://en.wikipedia.org/wiki/Longest_common_subsequence_problem">Longest Common Sequence algorithm (LCS)</a></p> <p>Assuming the input size is constant, then the problem has a complexity of O(nxm), (length of the two inputs)</p>
24,148,723
undefined method 'devise' for User
<p>I have been looking to get to grips with devise and its workings and have kind of fallen at the first hurdle. I have looked in a few places but cannot seem to find someone with this error exactly.</p> <p>So I have created a simple Home controller with an index view and added root 'home#index' and also ensured the default url options are setup in the development.rb file. I then simply typed:</p> <pre><code>rails generate devise User </code></pre> <p>This created my user.rb file in models with the following:</p> <pre><code>class User &lt; ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end </code></pre> <p>Pretty straightforward so far, I have the following Gemfile:</p> <pre><code>source 'https://rubygems.org' gem 'rails', '4.0.5' gem 'sqlite3' gem 'sass-rails', '~&gt; 4.0.2' gem 'devise' gem 'uglifier', '&gt;= 1.3.0' gem 'coffee-rails', '~&gt; 4.0.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~&gt; 1.2' group :doc do gem 'sdoc', require: false end gem 'bcrypt' </code></pre> <p>And when I run either rake db:migrate I get the following error:</p> <pre><code>rake aborted! NoMethodError: undefined method `devise' for User (call 'User.connection' to establish a connection):Class /home/jonlee/.rvm/gems/ruby-2.1.1@railstutorial_rails_4_0/gems/activerecord-4.0.5/lib/active_record/dynamic_matchers.rb:22:in `method_missing' /home/jonlee/Projects/rails/userauth/app/models/user.rb:4:in `&lt;class:User&gt;' /home/jonlee/Projects/rails/userauth/app/models/user.rb:1:in `&lt;top (required)&gt;' </code></pre> <p>Im at a loss as to why the User model cannot find the 'devise' method when as far as I can see it is definitely there.</p> <p>I get similar errors with rake routes, rails server and rails console.</p> <p>For further info I am using ruby 2.1.1 if that helps?</p>
24,148,983
13
3
null
2014-06-10 18:50:36.18 UTC
8
2022-09-02 23:02:18.58 UTC
2014-06-10 18:56:23.62 UTC
null
3,646,872
null
3,646,872
null
1
50
ruby-on-rails|ruby|devise
52,554
<p>Add <code>devise</code> to your application <code>Gemfile</code> and install it by running <code>bundle install</code>. After this, you should run the following generator command:</p> <pre><code>rails generate devise:install </code></pre> <p>This generator will install an initializer <code>your_application/config/initializers/devise.rb</code> which consists of all the Devise's configuration options. </p> <p>You missed the above mentioned step which is why the devise configurations are not set and you receive <code>undefined method 'devise' for User</code> error in your model class <code>User</code>.</p>
4,022,604
JAVA: how to obtain keystore file for a certification (crt) file
<p>HI All,</p> <p>I have a .crt file and I need to get the associated keystore file. How to do so?</p> <p>Is <code>keytool</code> is helpful in that?</p> <p>Thanks.</p>
12,155,652
2
0
null
2010-10-26 10:04:14.457 UTC
10
2019-03-15 13:15:16.897 UTC
null
null
null
null
171,950
null
1
23
java|keystore|crt|keytool
47,645
<p><strong>In JDK8 or higher:</strong></p> <p>Command below creates empty store and imports your certificate into the keystore:</p> <pre><code>keytool -import -alias alias -file cert_file.crt -keypass keypass -keystore yourkeystore.jks -storepass Hello1 </code></pre> <p><strong>In JDK7:</strong></p> <p>Older versions of JDK7 create non-empty keystore which then needs to be cleared. Below is how you do that.</p> <p>Create store with temporary key inside: </p> <pre><code>keytool -genkey -alias temp -keystore yourkeystore.jks -storepass Hello1 </code></pre> <p>Then delete existing entry: </p> <pre><code>keytool -delete -alias temp -keystore yourkeystore.jks -storepass Hello1 </code></pre> <p>Now you've got empty store. You can check that it's empty: </p> <pre><code>keytool -list -keystore yourkeystore.jks -storepass Hello1 </code></pre> <p>Then import your certificate to the store:</p> <pre><code>keytool -import -alias alias -file cert_file.crt -keypass keypass -keystore yourkeystore.jks -storepass Hello1 </code></pre> <p>And off you go!</p>
28,436,066
Retargeting All Projects in a Solution to .NET 4.5.2
<p>I have a solution in Visual Studio 2012 with 170 C# projects in it. I need to retarget all of the projects from .NET Framework 4.0 to 4.5.2.</p> <p>I prefer to let Visual Studio handle this by going into the properties of each project, changing the targeted framework, and letting Visual Studio make any necessary changes to the .csproj files.</p> <p>I noticed that these changes include adding a few new XML tags to the .csproj, depending on some attributes of the current project.</p> <p>How can I batch retarget all 170 C# projects without just using a replace text tool to replace the targeted version number? I want Visual Studio to make all the necessary tag modifications and additions and replace alone will not permit that to happen.</p>
28,436,255
6
5
null
2015-02-10 15:56:36.057 UTC
9
2020-03-02 17:44:01.6 UTC
null
null
null
null
1,504,964
null
1
106
c#|visual-studio|visual-studio-2012|solution
85,290
<p>The MSDN documentation "<a href="https://msdn.microsoft.com/en-us/library/ff657133(v=vs.110).aspx" rel="noreferrer">Migration Guide to the .NET Framework 4.5</a>" and "<a href="https://msdn.microsoft.com/en-us/library/jj152935(v=vs.110).aspx" rel="noreferrer">How to Configure an App to Support .NET Framework 4 or 4.5</a>" only discusses modifying projects. There's no details on applying changes to the entire solution at once, nor have I seen a function in VS that supports it.</p> <p>However, there's a (well-rated) extension called <a href="https://visualstudiogallery.msdn.microsoft.com/47bded90-80d8-42af-bc35-4736fdd8cd13" rel="noreferrer">Target Framework Migrator</a> available in the Visual Studio gallery, which supports upgrading to 4.5.2 (as well as newer versions**) and looks like it'll do exactly what you want. The source code is available on <a href="https://github.com/VHQLabs/TargetFrameworkMigrator" rel="noreferrer">GitHub</a>, if you're interested.</p> <p>Note that the lack of such a feature may be intentional (and not just an omission). I'm just guessing, but maybe MS figures only projects that <em>need</em> the new Frameworks will be upgraded. FWIW, if you end up upgrading some projects that are shared with other solutions, those solutions may fail to build until <em>they're</em> upgraded too.</p> <p>That being said, if you're in a small shop with just one (or a few) solutions and you're looking to upgrade everything in one go, then perhaps the above tool will work for you.</p> <hr> <blockquote> <p><strong>There's been no development on this for years</strong>, and apparently the developer has no plans to <a href="https://github.com/VHQLabs/TargetFrameworkMigrator/issues/51" rel="noreferrer">pass the baton</a> to anyone else.</p> </blockquote> <p>If you're unable to get it to work with a newer .NET Framework version, check the existing <a href="https://github.com/VHQLabs/TargetFrameworkMigrator/pulls" rel="noreferrer">PRs</a> and <a href="https://github.com/VHQLabs/TargetFrameworkMigrator/issues" rel="noreferrer">Issues</a> for fixes, but you may have to apply them yourself. For example, someone posted a <a href="https://github.com/VHQLabs/TargetFrameworkMigrator/pull/43" rel="noreferrer">fix for .NET Framework v 4.7.1</a>. Hopefully these will get merged, but I wouldn't hold my breath.</p> <p>If anyone else is seeing the same error as Anas (in the comments), <a href="https://github.com/VHQLabs/TargetFrameworkMigrator/issues/47" rel="noreferrer">here's a GitHub issue</a> from a couple weeks ago, and <a href="https://github.com/VHQLabs/TargetFrameworkMigrator/issues/36" rel="noreferrer">another possibly related issue</a> from 2017. Consider thumbs upping them and adding more details if you're having the same problem.</p>