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
34,860,814
Basic Authentication Using JavaScript
<p>I am building an application that consumes the <a href="http://howto.caspio.com/integration/web-services-api/rest-api/authenticating-rest/" rel="noreferrer">Caspio API</a>. I am having some trouble authenticating against their API. I have spent 2-3 days trying to figure this out but it may be due to some understanding on my end. I have read countless articles on stackoverflow post and otherwise but have not solved the issue. Below is a code example of my solution based on what i have looked at and i am getting a 400 Status code message; What am i doing wrong here? (Please provide well commented code example and i would prefer to <strong>NOT</strong> have links posted here referencing other material as i have looked at these extensively. Thanks!):</p> <p>Some references i have looked at:</p> <p>1) <a href="https://stackoverflow.com/questions/491914/pure-javascript-code-for-http-basic-authentication">Pure JavaScript code for HTTP Basic Authentication?</a> </p> <p>2) <a href="https://stackoverflow.com/questions/22413921/how-to-make-http-authentication-in-rest-api-call-from-javascript?rq=1">How to make http authentication in REST API call from javascript</a></p> <p>I would like to use this authentication method as described by caspio below: </p> <p>As an alternative to including credentials in the request body, a client can use the HTTP Basic authentication scheme. In this case, authentication request will be setup in the following way:</p> <p><strong><em>Method:</em></strong> POST</p> <p><strong><em>URL:</em></strong> Your token endpoint</p> <p><strong><em>Body:</em></strong> grant_type=client_credentials</p> <p><strong><em>Header parameter:</em></strong></p> <p><strong><em>Authorization:</em></strong> Basic Basic authentication realm</p> <p>Below are my Javascript and HTML code.</p> <p><strong>JavaScript:</strong></p> <pre><code>var userName = "clientID"; var passWord = "secretKey"; function authenticateUser(user, password) { var token = user + ":" + password; // Should i be encoding this value????? does it matter??? // Base64 Encoding -&gt; btoa var hash = btoa(token); return "Basic " + hash; } function CallWebAPI() { // New XMLHTTPRequest var request = new XMLHttpRequest(); request.open("POST", "https://xxx123.caspio.com/oauth/token", false); request.setRequestHeader("Authorization", authenticateUser(userName, passWord)); request.send(); // view request status alert(request.status); response.innerHTML = request.responseText; } </code></pre> <p><strong>HTML:</strong></p> <pre><code>&lt;div&gt; &lt;div id="response"&gt; &lt;/div&gt; &lt;input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" /&gt; </code></pre> <p></p>
35,043,887
4
0
null
2016-01-18 17:38:49.98 UTC
14
2021-07-04 20:48:41.133 UTC
2017-05-23 11:47:08.953 UTC
null
-1
null
1,294,193
null
1
23
javascript|authentication|xmlhttprequest
170,452
<p>After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future: </p> <pre><code>var token_ // variable will store the token var userName = "clientID"; // app clientID var passWord = "secretKey"; // app clientSecret var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint var request = new XMLHttpRequest(); function getToken(url, clientID, clientSecret) { var key; request.open("POST", url, true); request.setRequestHeader("Content-type", "application/json"); request.send("grant_type=client_credentials&amp;client_id="+clientID+"&amp;"+"client_secret="+clientSecret); // specify the credentials to receive the token on request request.onreadystatechange = function () { if (request.readyState == request.DONE) { var response = request.responseText; var obj = JSON.parse(response); key = obj.access_token; //store the value of the accesstoken token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function } } } // Get the token getToken(caspioTokenUrl, userName, passWord); </code></pre> <p>If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue; </p> <p>NOTE: encodedParams is NOT used in this example but was used in my solution. </p> <p>Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application </p> <pre><code>function CallWebAPI() { var request_ = new XMLHttpRequest(); var encodedParams = encodeURIComponent(params); request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true); request_.setRequestHeader("Authorization", "Bearer "+ token_); request_.send(); request_.onreadystatechange = function () { if (request_.readyState == 4 &amp;&amp; request_.status == 200) { var response = request_.responseText; var obj = JSON.parse(response); // handle data as needed... } } } </code></pre> <p>This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...</p>
47,683,591
React Native: Different styles applied on orientation change
<p>I'm developing a <strong>React Native</strong> application to be deployed as a native application on iOS and Android (and Windows, if possible).</p> <p>The problem is that we want the layout to be different <strong>depending on screen dimensions and its orientation.</strong></p> <p>I've made some functions that return the <strong>styles object</strong> and are called on every component render's function, so I am able to apply different styles at application startup, but if the orientation (or screen's size) changes once the app has been initialized, they aren't recalculated nor reapplied.</p> <p>I've added listeners to the top rendered so it updates its state on orientation change (and it forces a render for the rest of the application), but the subcomponents are not rerendering (because, in fact, <strong>they have not been changed</strong>).</p> <p>So, <strong>my question is:</strong> how can I make to have styles that may be <strong>completely different</strong> based on screen size and orientation, just as with <strong>CSS Media Queries</strong> (which are rendered on the fly)?</p> <p><em>I've already tried <a href="https://github.com/adbayb/react-native-responsive" rel="noreferrer">react-native-responsive</a> module without luck.</em></p> <p>Thank you!</p>
47,773,142
16
1
null
2017-12-06 21:17:32.473 UTC
14
2022-08-16 08:17:55.133 UTC
null
null
null
null
1,047,814
null
1
50
css|reactjs|screen-orientation|react-native
65,413
<p>Finally, I've been able to do so. Don't know the performance issues it can carry, but they should not be a problem since it's only called on resizing or orientation change.</p> <p>I've made a global controller where I have a function which receives the component (the container, the view) and adds an event listener to it:</p> <pre><code>const getScreenInfo = () =&gt; { const dim = Dimensions.get('window'); return dim; } const bindScreenDimensionsUpdate = (component) =&gt; { Dimensions.addEventListener('change', () =&gt; { try{ component.setState({ orientation: isPortrait() ? 'portrait' : 'landscape', screenWidth: getScreenInfo().width, screenHeight: getScreenInfo().height }); }catch(e){ // Fail silently } }); } </code></pre> <p>With this, I force to rerender the component when there's a change on orientation, or on window resizing.</p> <p>Then, on every component constructor:</p> <pre><code>import ScreenMetrics from './globalFunctionContainer'; export default class UserList extends Component { constructor(props){ super(props); this.state = {}; ScreenMetrics.bindScreenDimensionsUpdate(this); } } </code></pre> <p>This way, it gets rerendered everytime there's a window resize or an orientation change.</p> <p><strong>You should note</strong>, however, that this must be applied to every component which we want to listen to orientation changes, since if the parent container is updated but the <code>state</code> (or <code>props</code>) of the children do not update, they won't be rerendered, so <strong>it can be a performance kill</strong> if we have a big children tree listening to it.</p> <p>Hope it helps someone!</p>
38,835,747
Type erasing type erasure, `any` questions?
<p>So, suppose I want to type erase using type erasure.</p> <p>I can create pseudo-methods for variants that enable a natural:</p> <pre><code>pseudo_method print = [](auto&amp;&amp; self, auto&amp;&amp; os){ os &lt;&lt; self; }; std::variant&lt;A,B,C&gt; var = // create a variant of type A B or C (var-&gt;*print)(std::cout); // print it out without knowing what it is </code></pre> <p>My question is, how do I extend this to a <code>std::any</code>?</p> <p>It cannot be done "in the raw". But at the point where we assign to/construct a <code>std::any</code> we have the type information we need.</p> <p>So, in theory, an augmented <code>any</code>:</p> <pre><code>template&lt;class...OperationsToTypeErase&gt; struct super_any { std::any data; // or some transformation of OperationsToTypeErase? std::tuple&lt;OperationsToTypeErase...&gt; operations; // ?? what for ctor/assign/etc? }; </code></pre> <p>could somehow automatically rebind some code such that the above type of syntax would work.</p> <p>Ideally it would be as terse in use as the variant case is.</p> <pre><code>template&lt;class...Ops, class Op, // SFINAE filter that an op matches: std::enable_if_t&lt; std::disjunction&lt; std::is_same&lt;Ops, Op&gt;... &gt;{}, int&gt;* =nullptr &gt; decltype(auto) operator-&gt;*( super_any&lt;Ops...&gt;&amp; a, any_method&lt;Op&gt; ) { return std::get&lt;Op&gt;(a.operations)(a.data); } </code></pre> <p>Now can I keep this to a <em>type</em>, yet reasonably use the lambda syntax to keep things simple?</p> <p>Ideally I want:</p> <pre><code>any_method&lt;void(std::ostream&amp;)&gt; print = [](auto&amp;&amp; self, auto&amp;&amp; os){ os &lt;&lt; self; }; using printable_any = make_super_any&lt;&amp;print&gt;; printable_any bob = 7; // sets up the printing data attached to the any int main() { (bob-&gt;*print)(std::cout); // prints 7 bob = 3.14159; (bob-&gt;*print)(std::cout); // prints 3.14159 } </code></pre> <p>or similar syntax. Is this impossible? Infeasible? Easy?</p>
38,865,269
2
13
null
2016-08-08 18:04:45.543 UTC
19
2017-09-24 18:37:07.49 UTC
2017-09-24 18:34:24.42 UTC
null
15,168
null
1,774,667
null
1
24
c++|type-erasure|c++17|stdany
3,110
<p>Here's my solution. It looks shorter than Yakk's, and it does not use <code>std::aligned_storage</code> and placement new. It additionally supports stateful and local functors (which implies that it might never be possible to write <code>super_any&lt;&amp;print&gt;</code>, since <code>print</code> could be a local variable). </p> <p>any_method:</p> <pre><code>template&lt;class F, class Sig&gt; struct any_method; template&lt;class F, class Ret, class... Args&gt; struct any_method&lt;F,Ret(Args...)&gt; { F f; template&lt;class T&gt; static Ret invoker(any_method&amp; self, boost::any&amp; data, Args... args) { return self.f(boost::any_cast&lt;T&amp;&gt;(data), std::forward&lt;Args&gt;(args)...); } using invoker_type = Ret (any_method&amp;, boost::any&amp;, Args...); }; </code></pre> <p>make_any_method:</p> <pre><code>template&lt;class Sig, class F&gt; any_method&lt;std::decay_t&lt;F&gt;,Sig&gt; make_any_method(F&amp;&amp; f) { return { std::forward&lt;F&gt;(f) }; } </code></pre> <p>super_any:</p> <pre><code>template&lt;class...OperationsToTypeErase&gt; struct super_any { boost::any data; std::tuple&lt;typename OperationsToTypeErase::invoker_type*...&gt; operations = {}; template&lt;class T, class ContainedType = std::decay_t&lt;T&gt;&gt; super_any(T&amp;&amp; t) : data(std::forward&lt;T&gt;(t)) , operations((OperationsToTypeErase::template invoker&lt;ContainedType&gt;)...) {} template&lt;class T, class ContainedType = std::decay_t&lt;T&gt;&gt; super_any&amp; operator=(T&amp;&amp; t) { data = std::forward&lt;T&gt;(t); operations = { (OperationsToTypeErase::template invoker&lt;ContainedType&gt;)... }; return *this; } }; </code></pre> <p>operator->*:</p> <pre><code>template&lt;class...Ops, class F, class Sig, // SFINAE filter that an op matches: std::enable_if_t&lt; std::disjunction&lt; std::is_same&lt;Ops, any_method&lt;F,Sig&gt;&gt;... &gt;{}, int&gt; = 0 &gt; auto operator-&gt;*( super_any&lt;Ops...&gt;&amp; a, any_method&lt;F,Sig&gt; f) { auto fptr = std::get&lt;typename any_method&lt;F,Sig&gt;::invoker_type*&gt;(a.operations); return [fptr,f, &amp;a](auto&amp;&amp;... args) mutable { return fptr(f, a.data, std::forward&lt;decltype(args)&gt;(args)...); }; } </code></pre> <p>Usage:</p> <pre><code>#include &lt;iostream&gt; auto print = make_any_method&lt;void(std::ostream&amp;)&gt;( [](auto&amp;&amp; self, auto&amp;&amp; os){ os &lt;&lt; self; } ); using printable_any = super_any&lt;decltype(print)&gt;; printable_any bob = 7; // sets up the printing data attached to the any int main() { (bob-&gt;*print)(std::cout); // prints 7 bob = 3.14159; (bob-&gt;*print)(std::cout); // prints 3.14159 } </code></pre> <p><a href="http://melpon.org/wandbox/permlink/llv3Va7aGQVuIe0P" rel="noreferrer">Live</a></p>
38,597,274
Why does printf("%f",0); give undefined behavior?
<p>The statement</p> <pre><code>printf("%f\n",0.0f); </code></pre> <p>prints 0.</p> <p>However, the statement</p> <pre><code>printf("%f\n",0); </code></pre> <p>prints random values. </p> <p>I realize I'm exhibiting some kind of undefined behaviour, but I can't figure out why specifically. </p> <p>A floating point value in which all the bits are 0 is still a valid <code>float</code> with value of 0.<br> <code>float</code> and <code>int</code> are the same size on my machine (if that is even relevant). </p> <p>Why does using an integer literal instead of a floating point literal in <code>printf</code> cause this behavior?</p> <p>P.S. the same behaviour can be seen if I use</p> <pre><code>int i = 0; printf("%f\n", i); </code></pre>
38,597,324
10
25
null
2016-07-26 18:23:10.583 UTC
11
2020-01-29 20:52:02.173 UTC
2017-12-21 14:26:53.003 UTC
null
918,959
null
908,939
null
1
89
c++|c|printf|implicit-conversion|undefined-behavior
8,073
<p>The <code>"%f"</code> format requires an argument of type <code>double</code>. You're giving it an argument of type <code>int</code>. That's why the behavior is undefined.</p> <p>The standard does not guarantee that all-bits-zero is a valid representation of <code>0.0</code> (though it often is), or of any <code>double</code> value, or that <code>int</code> and <code>double</code> are the same size (remember it's <code>double</code>, not <code>float</code>), or, even if they are the same size, that they're passed as arguments to a variadic function in the same way.</p> <p>It might happen to "work" on your system. That's the worst possible symptom of undefined behavior, because it makes it difficult to diagnose the error.</p> <p><a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="nofollow noreferrer">N1570</a> 7.21.6.1 paragraph 9:</p> <blockquote> <p>... If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.</p> </blockquote> <p>Arguments of type <code>float</code> are promoted to <code>double</code>, which is why <code>printf("%f\n",0.0f)</code> works. Arguments of integer types narrower than <code>int</code> are promoted to <code>int</code> or to <code>unsigned int</code>. These promotion rules (specified by N1570 6.5.2.2 paragraph 6) do not help in the case of <code>printf("%f\n", 0)</code>.</p> <p>Note that if you pass a constant <code>0</code> to a non-variadic function that expects a <code>double</code> argument, the behavior is well defined, assuming the function's prototype is visible. For example, <code>sqrt(0)</code> (after <code>#include &lt;math.h&gt;</code>) implicitly converts the argument <code>0</code> from <code>int</code> to <code>double</code> -- because the compiler can see from the declaration of <code>sqrt</code> that it expects a <code>double</code> argument. It has no such information for <code>printf</code>. Variadic functions like <code>printf</code> are special, and require more care in writing calls to them.</p>
7,031,395
Implementing tags in Rails: How to reference multiple items with one tag?
<p>I'm writing a blog engine in rails, and have set up a tag model and a post model which have a have_and_belongs_to_many relationship. Tag addition works fine, the problem comes when looking for all posts with a specific tag:</p> <p>If I add tag "test" to Post A, then add tag "test" to post B, there are two tag objects, both with name "test" but with different IDs, both referencing different posts. Now if I have a controller action indexTagPosts which takes the parameter "tag" and finds all posts with that tag, it will only return one post, since the other tag has a different ID and is not really associated. Should I be somehow restricting the addition of new tags, or should I be manipulating the way I pull all relevant tags differently?</p> <p>Here is the controller action which is supposed to grab all relevant posts based on the parameter 'tag':</p> <pre><code>def indexTagPosts @tag = Tag.find(params[:tag]) @posts = @tag.posts.all end </code></pre> <p>And here is the action to save a tag:</p> <pre><code>def create @post = Post.find(params[:post_id]) @tag = @post.tags.create(params[:tag]) respond_to do |format| if @tag.save format.html { redirect_to edit_post_path(@post),:notice =&gt; "Success" } end end end </code></pre> <p>Thanks in advance and apologies for redundancy or bad wording.</p>
7,031,485
1
0
null
2011-08-11 19:04:49.337 UTC
9
2012-01-15 15:15:03.773 UTC
null
null
null
null
757,806
null
1
5
ruby-on-rails|tags|has-and-belongs-to-many
4,016
<p>I wish I knew where everyone got the idea to use <code>has_and_belongs_to_many</code> because it's a really difficult thing to manage, even if it seems simple at the start. The better approach is to have a <code>has_many ..., :through</code> type relationship because you can manage the individual links and add meta-data to them easily.</p> <p>For instance, here is a simple two way join with an intermediate model, a pattern you'll find occurs quite often:</p> <pre><code>class Post &lt; ActiveRecord::Base has_many :post_tags has_many :tags, :through =&gt; :post_tags end class Tag &lt; ActiveRecord::Base has_many :post_tags has_many :posts, :through =&gt; :post_tags end class PostTag &lt; ActiveRecord::Base belongs_to :post belongs_to :tag end </code></pre> <p>Adding and removing Tag links at this point is trivial:</p> <pre><code>@post = Post.find(params[:post_id]) if (params[:tags].present?) @post.tags = Tag.where(:name =&gt; params[:tags].split(/\s*,\s*/)) else @post.tags = [ ] end </code></pre> <p>The <code>has_many</code> relationship manager will create, update, or destroy the <code>PostTag</code> association models as required.</p> <p>Generally you'll evolve the Post model to include a utility method for retrieving and assigning the tags using whatever separator you like:</p> <pre><code> class Post def tags_used self.tags.collect(&amp;:name).join(',') end def tags_used=(list) self.tags = list.present? ? Tag.where(:name =&gt; list.split(/\s*,\s*/)) : [ ] end end </code></pre>
3,136,059
Getting one value from a tuple
<p>Is there a way to get one value from a tuple in Python using expressions?</p> <pre><code>def tup(): return (3, "hello") i = 5 + tup() # I want to add just the three </code></pre> <p>I know I can do this:</p> <pre><code>(j, _) = tup() i = 5 + j </code></pre> <p>But that would add a few dozen lines to my function, doubling its length.</p>
3,136,069
3
1
null
2010-06-28 20:55:35.387 UTC
18
2022-02-27 14:21:22.55 UTC
2020-02-02 12:20:24.937 UTC
null
7,851,470
null
1,343
null
1
194
python|tuples
487,556
<p>You can write</p> <pre><code>i = 5 + tup()[0] </code></pre> <p>Tuples can be indexed just like lists.</p> <p>The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.</p>
3,018,891
How would I go about licensing a WPF windows application
<p>I have developed a small application that I would like to try and sell but I am unfamiliar with how best to go about this. </p> <ol> <li><p>How would I go about locking the program down for trial use1.</p></li> <li><p>How would I go about dealing with accepting payments?</p></li> </ol> <p>Bearing in mind that I am a one man band with not a lot of money, I was hoping for a solution that would be free or a low cost, effective, secure and simple to implement and maintain. This is not something that I have a lot of experience with as I have typically developed for the public sector where they buy a solution as a whole and we have never licensed it.</p> <p>Any help would really be appreciated. Thanks,</p> <p>B</p>
3,019,019
4
0
null
2010-06-10 22:05:47.95 UTC
30
2019-12-19 08:28:56.217 UTC
2019-12-19 08:28:56.217 UTC
null
3,382,549
null
76,439
null
1
21
.net|wpf|licensing|software-distribution
12,683
<p>I can tell you how I do it. Disclaimer: your mileage may vary. This is for the case of preventing casual piracy of a simple WinForms or WPF or other desktop app. It's not particularly robust or secure against sophisticated cracking, but it does a great job of preventing casual piracy.</p> <ol> <li><p>For licensing, I tried several 3rd party solutions. They're all fairly easy to use for the nominal case of <em>preventing casual piracy</em>, which of course if the only piracy you should really be concerned about.</p></li> <li><p>What I found was that none of the licensing providers were really compatible with the existing payment processors / gateways. There are a few "all-in-one" solutions but the level of technical debt there was unacceptable to me (a freelancer and sole developer). I was looking for a simple way to go from a "Buy Now" link on a website to unlocking the desktop software after purchase. Some of the existing "all-in-one" solutions are overkill for this purpose, some ignore the "purchase" aspect entirely.</p></li> <li><p>I ended up using <a href="http://msdn.microsoft.com/en-us/library/ms229745.aspx" rel="noreferrer">Xml Digital Signatures</a> to sign license files with the application's private key, which is never distributed to users. The result: you have a .LIC or .LICX file on the target machine that users can read (it's plain text, except for the enveloped signature) but not modify. (Or rather, they can't modify it without you <em>knowing</em> they've modified it.) This little file is the key to the whole system.</p></li> <li><p>When the application loads, it verifies that the XML signature is valid (using the application's public key, which <em>is</em> distributed with the app) and if it's valid, it reads the information from the license file, and enables/disables certain features based on that. For example, your license file could contain a product expiration date, or a couple pieces of unique machine info (be careful, always, not to inconvenience your legit users with this...you don't want them to have to reapply for license keys every time they change out a hard drive).</p></li> <li><p>As an additional (and slightly more invasive) step, you can have the app connect to your server, though this gets you into server downtime issues and so forth and so on. Some devs are willing to put up with this, others aren't.</p></li> <li><p>Now for the purchase part, there are many many options. Paypal is far and away the easiest. You may or may not like their rate plans, but it's an absolute cinch to get up and running with Paypal.</p></li> <li><p>For that you want a Premier or Business account, not a Personal account. Note: in the Paypal docs it sometimes says you need a Paypal Business account. Whenever they say that, they actually mean, "a Paypal Business or Premier account".</p></li> <li><p>Now get yourself a product website and customize your Buy Now buttons etc. When the user makes a purchase, your website will receive a ping from <a href="https://www.paypal.com/ipn" rel="noreferrer">Paypal IPN</a>, which is their notification service. This ping is just a call to a defined HTTP endpoint on your website, and it contains all the information you'll want about the purchase. Mainly, the user's email...</p></li> <li><p>(Okay, I feel like I should mention: Paypal along with most other legit processors have a "sandbox" where you can test all this out before going live. Does wonders towards giving you the warm fuzzy about actually going live, with money on the line.)</p></li> <li><p>Which you'll use to auto-send the user an Activation Code after purchase, so they don't have to wait 24 hours for you to manually send them a code. Store this activation code (which under this scenario can be any unique, difficult-to-guess number, such as a GUID, prettified or not) in the DB with a usage count which you'll track to detect duplicate codes.</p></li> <li><p>The user enters the Activation Code into the software, via a screen you provide.</p></li> <li><p>The software contacts the server over https (this is a one-time thing that happens only when the software is unlocked), and says, "hey, is this license code the user just gave me valid?"</p></li> <li><p>If the supplied activation code matches the code stored in the database at the time of sale, and that activation code hasn't yet been confirmed, then Success!</p></li> <li><p>The server then needs to build the license file, which is an extremely simple XML or text file containing "what this copy of the software is allowed to do". There's no standard for what it should contain, only a few conventions.</p></li> <li><p>The server <strong>signs the license file with the application's private key</strong> and returns it as a data stream to your application...</p></li> <li><p>Which saves it as a .LIC or .LICX (or whatever extension you want) file, which it then checks on load time as per Step 3.</p></li> </ol> <p>This has worked really well for me, and it's a cinch to implement. The key to the whole thing is simply: trust those XML DSigs. When the LIC file is missing, you default to trial mode. When the sig is modified, you switch to trial mode. Only when the LIC file is present, validly signed, and contains the right information, do you then (in code) open up access to "full" functionality.</p> <p>Also, interperse more than one license-check point in your code. I do one at app startup, another at idle, and another just before entering key functional areas. So if someone does reverse the code, and they can, they'll at least have to do a bit of searching to gut all the license checks. Of course, nothing you can do can prevent people from patching their way around those checks. You just want to make it a bit more difficult.</p>
2,738,641
Testing Python Decorators?
<p>I'm writing some unit tests for a Django project, and I was wondering if its possible (or necessary?) to test some of the decorators that I wrote for it. </p> <p>Here is an example of a decorator that I wrote:</p> <pre><code>class login_required(object): def __init__(self, f): self.f = f def __call__(self, *args): request = args[0] if request.user and request.user.is_authenticated(): return self.f(*args) return redirect('/login') </code></pre>
2,743,646
4
4
null
2010-04-29 15:35:56.167 UTC
8
2020-02-12 16:06:38.387 UTC
2010-04-29 15:45:54.947 UTC
null
1,694
null
177,972
null
1
29
python|django|unit-testing|decorator|python-unittest
19,437
<p>Simply:</p> <pre><code>from nose.tools import assert_equal from mock import Mock class TestLoginRequired(object): def test_no_user(self): func = Mock() decorated_func = login_required(func) request = prepare_request_without_user() response = decorated_func(request) assert not func.called # assert response is redirect def test_bad_user(self): func = Mock() decorated_func = login_required(func) request = prepare_request_with_non_authenticated_user() response = decorated_func(request) assert not func.called # assert response is redirect def test_ok(self): func = Mock(return_value='my response') decorated_func = login_required(func) request = prepare_request_with_ok_user() response = decorated_func(request) func.assert_called_with(request) assert_equal(response, 'my response') </code></pre> <p>The <a href="http://www.voidspace.org.uk/python/mock/index.html" rel="noreferrer">mock</a> library helps here.</p>
38,511,444
Python: download files from google drive using url
<p>I am trying to download files from google drive and all I have is the drive's URL.</p> <p>I have read about google API that talks about some <code>drive_service</code> and <code>MedioIO</code>, which also requires some credentials( mainly JSON <code>file/OAuth</code>). But I am unable to get any idea about how it is working.</p> <p>Also, tried <code>urllib2.urlretrieve</code>, but my case is to get files from the drive. Tried <code>wget</code> too but no use.</p> <p>Tried <code>PyDrive</code> library. It has good upload functions to drive but no download options.</p> <p>Any help will be appreciated. Thanks.</p>
39,225,272
11
0
null
2016-07-21 18:09:36.003 UTC
39
2022-05-04 21:55:53.94 UTC
2020-06-30 11:08:24.77 UTC
null
7,001,213
null
3,218,127
null
1
92
python|download|google-drive-api|urllib2|pydrive
158,535
<p>If by "drive's url" you mean the <strong>shareable link</strong> of a file on Google Drive, then the following might help:</p> <pre><code>import requests def download_file_from_google_drive(id, destination): URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(URL, params = { 'id' : id }, stream = True) token = get_confirm_token(response) if token: params = { 'id' : id, 'confirm' : token } response = session.get(URL, params = params, stream = True) save_response_content(response, destination) def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None def save_response_content(response, destination): CHUNK_SIZE = 32768 with open(destination, "wb") as f: for chunk in response.iter_content(CHUNK_SIZE): if chunk: # filter out keep-alive new chunks f.write(chunk) if __name__ == "__main__": file_id = 'TAKE ID FROM SHAREABLE LINK' destination = 'DESTINATION FILE ON YOUR DISK' download_file_from_google_drive(file_id, destination) </code></pre> <p>The snipped does not use <em>pydrive</em>, nor the Google Drive SDK, though. It uses the <a href="http://docs.python-requests.org" rel="noreferrer">requests</a> module (which is, somehow, an alternative to <em>urllib2</em>).</p> <p>When downloading large files from Google Drive, a single GET request is not sufficient. A second one is needed - see <a href="https://stackoverflow.com/a/39225039/6770522">wget/curl large file from google drive</a>.</p>
38,672,900
How to manage database connection pool in spring jpa?
<p>I am using spring-boot in my web application and use spring-jpa to read/write from/to my database. It works very well but I want to understand how to manage the database connections. Below is my properties configuration for database:</p> <pre><code>spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8 spring.datasource.username=user spring.datasource.password=pwd spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.max-active=500 </code></pre> <p>I have set the maximum connections to 500. When a user makes a request on my spring application, a database connection will be opened for him. After finishing the request, will spring jpa close this connection? If not, when will it close the unused connections?</p> <p>I have read through the spring jpa reference document from <a href="http://docs.spring.io/spring-data/jpa/docs/current/reference/html/" rel="noreferrer">http://docs.spring.io/spring-data/jpa/docs/current/reference/html/</a>. But it doesn't mention anything about the connections. </p>
38,672,966
2
0
null
2016-07-30 10:32:10.723 UTC
7
2018-05-23 04:39:24.517 UTC
2018-05-23 04:39:24.517 UTC
null
66,686
null
5,421,539
null
1
24
java|spring|hibernate|spring-data-jpa|spring-jdbc
86,858
<p>When using DB connection pooling, a call to <code>sqlconnection.close()</code> will not necessarily close the heavyweight connection to the database, instead most often will just release the connection as re-usable in the pool. That's why it is advisable to invoke the <code>close()</code> on connection as soon as possible when leveraging a client side connection pool.</p> <p>In your configuration, the pool will contain a maximum number of 500 connections ( it would be also good to configure <code>maxIdle</code>, <code>minIdle</code>, and <code>minEvictableIdleTimeMillis</code> to tune the number of ready-to-use connections and how often to release them when not used).</p> <p>Some more doc <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html" rel="noreferrer">here</a></p>
33,640,327
How to pass optional elements to a component as a prop in reactjs
<p>I am trying to figure out the proper "react" way to pass in an optional prop that is an Element to a container component, that is handled differently from the children of that component. </p> <p>For a simple example, I have a Panel component, which renders its children, that also has an optional "title" prop (which is an element rather than a string, for the sake of the example) that gets specially rendered (put in a special spot, with special behaviors in while maintaining the abstraction.</p> <p>One option is to have a component which is pulled out of the children and rendered specially:</p> <pre><code>&lt;Panel&gt; &lt;Title&gt; some stuff&lt;/Title&gt; &lt;div&gt; some other stuff&lt;/div&gt; &lt;/Panel&gt; </code></pre> <p>But it seems wierd to have the children pulled out and handled separately like that.</p> <p>How is this normally handled in react, and am I even thinking about this the right way</p>
33,640,433
4
0
null
2015-11-10 21:52:18.563 UTC
2
2019-06-09 09:25:47.923 UTC
null
null
null
null
497,868
null
1
16
javascript|reactjs|components
43,855
<p>You don't need to do anything special. Just pass the title component as a prop, and then use <code>{this.props.title}</code> wherever you want it to be rendered:</p> <pre><code>class Panel extends React.Component { render() { return &lt;div&gt; {this.props.title} &lt;div&gt;Some other stuff...&lt;/div&gt; &lt;/div&gt;; } } class App extends React.Component { render() { var title = &lt;Title&gt;My Title&lt;/Title&gt;; return &lt;Panel title={title}/&gt;; } } </code></pre> <p>If you don't pass any value for the <code>title</code> prop (or if the value is <code>false</code>, <code>null</code>, or <code>undefined</code>) then nothing will be rendered there.</p> <p>This is a fairly common pattern in React.</p>
59,359,280
React app error: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS
<p>I am deploying a React app but am getting a strange error when I visit the page over https.</p> <p>When I visit the page over https I receive the following error:</p> <p>SecurityError: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.</p> <p>But when I go to the page over http it works perfectly. </p> <p>The problem is I'm not using websockets as far as I can tell. I searched through the code to see if there is a request to http that should be to https or to ws: instead of wss: but I don't see anything.</p> <p>Has anyone run into this before?</p> <p>I am including a copy of the package.json file. Let me know if you need me to upload any other parts of code to help debug.</p> <p>Thanks in advance.</p> <pre><code>{ "name": "client", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "baffle": "^0.3.6", "cross-env": "^6.0.3", "react": "^16.12.0", "react-dom": "^16.12.0", "react-player": "^1.14.2", "react-router-dom": "^5.1.2", "react-scripts": "3.3.0", "react-typist": "^2.0.5", "webpack-hot-dev-clients": "^2.0.2" }, "scripts": { "start": "cross-env react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ "&gt;0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } </code></pre>
59,697,522
9
0
null
2019-12-16 15:06:14.673 UTC
7
2022-06-04 09:49:36.9 UTC
2020-01-04 18:09:08.703 UTC
null
10,508,753
null
10,508,753
null
1
42
node.js|reactjs
45,064
<p>A lot of answers here do actually solve the issue but the simplest way I have found since I asked this question is to add npm package <a href="https://www.npmjs.com/package/serve" rel="noreferrer">serve</a> to your dependencies.</p> <p><code>yarn add serve</code> or <code>npm i serve</code></p> <p>and then replace your start script with the following:</p> <pre><code>"scripts": { "start": "serve -s build", } </code></pre> <p>This is actually straight out of the create-react-app <a href="https://create-react-app.dev/docs/deployment" rel="noreferrer">docs</a></p>
42,848,130
Why I can't access remote Jupyter Notebook server?
<p>I have started a Jupyter Notebook server on my centos6.5 server.And jupyter is running like</p> <pre><code>[I 17:40:59.649 NotebookApp] Serving notebooks from local directory: /root [I 17:40:59.649 NotebookApp] 0 active kernels [I 17:40:59.649 NotebookApp] The Jupyter Notebook is running at:https://[all ip addresses on your system]:8045/ [I 17:40:59.649 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). </code></pre> <p>When I want to access Jupyter remotely in the same local area network, say open <code>http://192.168.1.111:8045/</code>, I can't open a Jupyter page at all. By the way, I can access remote centos server successfully.</p> <p>What's the possible reason?</p>
43,500,232
19
0
null
2017-03-17 02:23:49.123 UTC
66
2022-02-08 11:46:14.37 UTC
2018-05-11 17:19:48.023 UTC
null
1,007,939
null
4,481,660
null
1
126
jupyter-notebook
172,825
<p>Have you configured the <em>jupyter_notebook_config.py</em> file to allow external connections?</p> <p>By default, Jupyter Notebook only accepts connections from localhost (eg, from the same computer that its running on). By modifying the <em>NotebookApp.allow_origin</em> option from the default ' ' to '*', you allow Jupyter to be accessed externally.</p> <p><code>c.NotebookApp.allow_origin = '*' #allow all origins</code></p> <p>You'll also need to change the IPs that the notebook will listen on:</p> <p><code>c.NotebookApp.ip = '0.0.0.0' # listen on all IPs </code></p> <br> <p>Also see the details in a <a href="https://stackoverflow.com/a/54063685/2827162">subsequent answer</a> in this thread. <br></p> <p><a href="http://jupyter-notebook.readthedocs.io/en/latest/config.html" rel="noreferrer">Documentation on the Jupyter Notebook config file.</a></p>
44,796,433
Centre code in Android Studio/IntelliJ IDEA editor
<p>I would like to centre my code in the Android Studio's/IntelliJ's editor, like as it is done in the Distraction Free Mode.</p> <p>Right now, it is always aligned on the left side of the editor, but I want to have it in the centre of the window. I could not find any option for this in the settings. Is this possible <strong>without</strong> entering the Distraction Free Mode?</p>
44,802,228
2
0
null
2017-06-28 07:42:52.93 UTC
11
2021-05-01 19:59:32.563 UTC
2021-02-26 01:07:20.353 UTC
null
1,402,846
null
1,031,556
null
1
36
android-studio|intellij-idea
6,709
<p>Add <code>-Deditor.distraction.free.mode=true</code> in <code>Help</code> | <strong>Edit Custom VM Options</strong> and restart the IDE. This will center the editor without the other features of the distraction free mode (like hidden tool windows).</p>
39,355,241
Compute HMAC-SHA512 with secret key in java
<p>I want to exactly build a function which produces a HMAC with a secret key like this site provides:</p> <p><a href="http://www.freeformatter.com/hmac-generator.html" rel="noreferrer">http://www.freeformatter.com/hmac-generator.html</a></p> <p>The Java 8 lib only provides MessageDigest and KeyGenerator which both only support up to SH256.</p> <p>Also, Google doesn't give me any result for an implementation to generate a HMAC.</p> <p>Does someone know a implementation?</p> <p>I have this code to generate an ordinary SH256 but I guess this doesn't help me much:</p> <pre><code> public static String get_SHA_512_SecurePassword(String passwordToHash) throws Exception { String generatedPassword = null; MessageDigest md = MessageDigest.getInstance(&quot;SHA-512&quot;); byte[] bytes = md.digest(passwordToHash.getBytes(&quot;UTF-8&quot;)); StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; bytes.length; i++) { sb.append(Integer.toString((bytes[i] &amp; 0xff) + 0x100, 16).substring(1)); } generatedPassword = sb.toString(); System.out.println(generatedPassword); return generatedPassword; } </code></pre>
39,356,436
4
0
null
2016-09-06 18:05:48.303 UTC
14
2021-04-27 15:01:16.22 UTC
2021-04-27 15:01:16.22 UTC
null
3,964,927
null
4,945,303
null
1
36
java|hmac
61,803
<p>Hope this helps:</p> <pre><code>import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class Test1 { private static final String HMAC_SHA512 = "HmacSHA512"; public static void main(String[] args) { Mac sha512Hmac; String result; final String key = "Welcome1"; try { final byte[] byteKey = key.getBytes(StandardCharsets.UTF_8); sha512Hmac = Mac.getInstance(HMAC_SHA512); SecretKeySpec keySpec = new SecretKeySpec(byteKey, HMAC_SHA512); sha512Hmac.init(keySpec); byte[] macData = sha512Hmac.doFinal("My message".getBytes(StandardCharsets.UTF_8)); // Can either base64 encode or put it right into hex result = Base64.getEncoder().encodeToString(macData); //result = bytesToHex(macData); } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) { e.printStackTrace(); } finally { // Put any cleanup here System.out.println("Done"); } } } </code></pre> <p>For converting from byte array to hex refer this stackoverflow answer : <a href="https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java">here</a></p>
2,896,833
How to stretch a table over multiple pages
<p>I have a Table (multiple rows, multiple columns, see below ) that is longer than one page. How can I tell LaTeX to continue on the next page. </p> <ul> <li>Adding a \newpage didn't work</li> <li><p>Manually 'ending' and 'reopening' the table works, but is very tedious, since the table will be many pages long.</p> <pre><code>\begin{tabular}{lp{13cm}} AAAAAAAAAA &amp; FOOBAR FOOBAR FOOBAR FOOBAR FOOBAR\\ BBBBBBBBBB &amp; FOOBAR FOOBAR FOOBAR FOOBAR FOOBAR\\ CCCCCCCCCC &amp; FOOBAR FOOBAR FOOBAR FOOBAR FOOBAR\\ ... ZZZZZZZZZ &amp; FOOBAR FOOBAR FOOBAR FOOBAR FOOBAR\\ \end{tabular} </code></pre></li> </ul>
2,896,850
1
1
null
2010-05-24 12:07:18.72 UTC
8
2017-01-14 23:25:25.413 UTC
2017-01-14 23:25:25.413 UTC
null
4,370,109
null
31,472
null
1
53
pagination|latex
156,703
<p>You should <code>\usepackage{longtable}</code>.</p> <ul> <li>PDF Documentation of the package: <a href="ftp://ftp.tex.ac.uk/tex-archive/macros/latex/required/tools/longtable.pdf" rel="noreferrer">ftp://ftp.tex.ac.uk/tex-archive/macros/latex/required/tools/longtable.pdf</a></li> <li>Tutorial with examples can be found <a href="http://users.sdsc.edu/~ssmallen/latex/longtable.html" rel="noreferrer">here</a>.</li> </ul>
38,626,649
How to "Show my current location on google maps, when I open the ViewController?" in Swift?
<p>I am using Google maps sdk of iOS(Swift).</p> <p>Has anyone know how to "Show my current location on google maps, when I open the ViewController"?</p> <p>Actually it just like Google Maps App. When you open the Google Maps, the blue spot will show your current location. You don't need press the "myLocationButton" in first time.</p> <p>So this is the code:</p> <pre><code>import UIKit import CoreLocation import GoogleMaps class GoogleMapsViewer: UIViewController { @IBOutlet weak var mapView: GMSMapView! let locationManager = CLLocationManager() let didFindMyLocation = false override func viewDidLoad() { super.viewDidLoad() let camera = GMSCameraPosition.cameraWithLatitude(23.931735,longitude: 121.082711, zoom: 7) let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera) mapView.myLocationEnabled = true self.view = mapView // GOOGLE MAPS SDK: BORDER let mapInsets = UIEdgeInsets(top: 80.0, left: 0.0, bottom: 45.0, right: 0.0) mapView.padding = mapInsets locationManager.distanceFilter = 100 locationManager.delegate = self locationManager.requestWhenInUseAuthorization() // GOOGLE MAPS SDK: COMPASS mapView.settings.compassButton = true // GOOGLE MAPS SDK: USER'S LOCATION mapView.myLocationEnabled = true mapView.settings.myLocationButton = true } } // MARK: - CLLocationManagerDelegate extension GoogleMapsViewer: CLLocationManagerDelegate { func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .AuthorizedWhenInUse { locationManager.startUpdatingLocation() mapView.myLocationEnabled = true mapView.settings.myLocationButton = true } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 20, bearing: 0, viewingAngle: 0) locationManager.stopUpdatingLocation() } } } </code></pre> <p>Anyone help? Thank you so much!</p>
38,627,279
8
2
null
2016-07-28 03:34:05.45 UTC
7
2021-06-03 06:54:43.86 UTC
2017-06-03 09:19:31.793 UTC
null
3,908,884
null
6,645,375
null
1
30
ios|swift|google-maps
89,651
<blockquote> <p>For <strong>Swift 3.x</strong> solution, please check this <a href="https://stackoverflow.com/a/40058423/2545465">Answer</a></p> </blockquote> <p>First all of you have to enter a key in Info.plist file <code>NSLocationWhenInUseUsageDescription</code></p> <p><a href="https://i.stack.imgur.com/sJ2VB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sJ2VB.png" alt="enter image description here"></a></p> <p>After adding this key just make a <code>CLLocationManager</code> variable and do the following</p> <pre><code>@IBOutlet weak var mapView: GMSMapView! var locationManager = CLLocationManager() class YourControllerClass: UIViewController,CLLocationManagerDelegate { //Your map initiation code let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera) self.view = mapView self.mapView?.myLocationEnabled = true //Location Manager code to fetch current location self.locationManager.delegate = self self.locationManager.startUpdatingLocation() } //Location Manager delegates func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last let camera = GMSCameraPosition.cameraWithLatitude((location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0) self.mapView?.animateToCameraPosition(camera) //Finally stop updating location otherwise it will come again and again in this delegate self.locationManager.stopUpdatingLocation() } </code></pre> <p>When you run the code you will get a pop up of Allow and Don't Allow for location. Just click on Allow and you will see your current location.</p> <p>Make sure to do this on a <strong>device</strong> rather than simulator. If you are using simulator, you have to choose some custom location and then only you will be able to see the blue dot.</p> <p><a href="https://i.stack.imgur.com/LeKTn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LeKTn.png" alt="enter image description here"></a></p>
41,989,526
Android - Firebase jobdispatcher
<p>I would like to know if it's possible to use Firebase jobdispatcher to schedule an url hit and get the response in order to update the db. I would like it to run once per day at night. Does anyone know if this is possible? </p> <p>I can't find any good example of doing this. I already read android documentation and <a href="https://github.com/firebase/firebase-jobdispatcher-android#user-content-firebase-jobdispatcher-" rel="noreferrer">https://github.com/firebase/firebase-jobdispatcher-android#user-content-firebase-jobdispatcher-</a> .</p> <p>I need to use Firebase jobdispatcher because I'm targeting API 16. </p> <p>Thanks in advance.</p> <p><strong>UPDATE</strong> </p> <p>This is what I did to schedule it once per day. </p> <pre><code>final int periodicity = (int) TimeUnit.HOURS.toSeconds(24); final int toleranceInterval = (int) TimeUnit.HOURS.toSeconds(1); FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this)); Job job = dispatcher.newJobBuilder() .setService(UpdateTVJobService.class) .setTag(JOB_TAG) .setTrigger(Trigger.executionWindow(periodicity, periodicity + toleranceInterval)) .setLifetime(Lifetime.FOREVER) .setRecurring(true) .setReplaceCurrent(true) .build(); int result = dispatcher.schedule(job); if (result != FirebaseJobDispatcher.SCHEDULE_RESULT_SUCCESS) { Log.d("JOB_TAG", "ERROR ON SCHEDULE"); } </code></pre>
42,111,723
2
0
null
2017-02-01 20:51:21.57 UTC
8
2017-02-10 15:34:54.95 UTC
2017-02-10 15:34:54.95 UTC
null
6,347,069
null
6,347,069
null
1
13
android|firebase|android-service|firebase-job-dispatcher
6,984
<p>You can schedule recurring jobs using Firebase JobDispatcher.As per your requirement,you need to create a service extending JobService that get response from url and update the db . Then you can schedule this service using Firebase JobDispatcher .In executionWindow you have to specify the earliest and latest time that job should run in ideal circumstances.</p> <p>If you want to schedule job after every 24 hours you can use execution window (60*60*24,60*60*24+60).Then if you want that it should run every night then you have to make sure that it is initially scheduled at night.For that you can initially use AlarmManager to be fired at night(only once) when app is installed and schedule a recurring job using job dispatcher OR another way is that based on difference from now and the desired execution time you can schedule a non recursive job using jobdispatcher which will run at night and inside that job service you can schedule recurring job using job dispatcher .</p> <p>ExecutionWindow specifies approximate time. It's not guaranteed it would run at the given window. If it misses the window the job will run at earliest time later under ideal circumstances.For recurring jobs once the job has finished next job will calculate execution window time from the time job last run.</p> <pre><code>Job myJob = dispatcher.newJobBuilder() .setTag("my-unique-tag") .setRecurring(true) .setLifetime(Lifetime.FOREVER) .setService(MyJobService.class) .setTrigger(Trigger.executionWindow(60*60*24,60*60*24+60)) .setReplaceCurrent(false) .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL) .setConstraints(Constraint.ON_ANY_NETWORK) .setExtras(myExtrasBundle) .build(); dispatcher.mustSchedule(myJob); </code></pre>
6,297,404
Multi-threaded use of SQLAlchemy
<p>I want to make a Database Application Programming Interface written in Python and using SQLAlchemy (or any other database connectors if it is told that using SQLAlchemy for this kind of task is not the good way to go). The setup is a MySQL server running on Linux or BSD and a the Python software running on a Linux or BSD machine (Either foreign or local).</p> <p>Basically what I want to do is spawn a new thread for each connections and the protocol would be custom and quite simple, although for each requests I would like to open a new transaction (or session as I have read) and then I need to commit the session. The problem I am facing right now is that there is high probability that another sessions happen at the same time from another connection.</p> <p>My question here is what should I do to handle this situation?</p> <ul> <li>Should I use a lock so only a single session can run at the same time?</li> <li>Are sessions actually thread-safe and I am wrong about thinking that they are not?</li> <li>Is there a better way to handle this situation?</li> <li>Is threading the way not-to-go?</li> </ul>
18,265,238
1
0
null
2011-06-09 18:20:19.363 UTC
27
2019-08-29 08:35:10.423 UTC
2014-03-19 14:01:04.383 UTC
null
742,082
null
451,938
null
1
70
python|multithreading|sqlalchemy
60,883
<p>Session objects are <strong>not</strong> thread-safe, but are <strong>thread-local</strong>. <a href="http://docs.sqlalchemy.org/en/latest/orm/contextual.html" rel="noreferrer">From the docs:</a></p> <blockquote> <p>&quot;The <code>Session</code> object is entirely designed to be used in a <strong>non-concurrent</strong> fashion, which in terms of multithreading means &quot;only in one thread at a time&quot; .. some process needs to be in place such that mutltiple calls across many threads don’t actually get a handle to the same session. We call this notion <strong>thread local storage</strong>.&quot;</p> </blockquote> <p>If you don't want to do the work of managing threads and sessions yourself, SQLAlchemy has the <code>ScopedSession</code> object to take care of this for you:</p> <blockquote> <p>The <code>ScopedSession</code> object by default uses <a href="https://docs.python.org/3/library/threading.html#threading.local" rel="noreferrer">threading.local()</a> as storage, so that a single <code>Session</code> is maintained for all who call upon the <code>ScopedSession</code> registry, but only within the scope of a single thread. Callers who call upon the registry in a different thread get a Session instance that is local to that other thread.</p> <p>Using this technique, the <code>ScopedSession</code> provides a quick and relatively simple way of providing a single, global object in an application that is safe to be called upon from multiple threads.</p> </blockquote> <p>See the examples in <a href="http://docs.sqlalchemy.org/en/latest/orm/contextual.html" rel="noreferrer">Contextual/Thread-local Sessions</a> for setting up your own thread-safe sessions:</p> <pre><code># set up a scoped_session from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker session_factory = sessionmaker(bind=some_engine) Session = scoped_session(session_factory) # now all calls to Session() will create a thread-local session some_session = Session() # you can now use some_session to run multiple queries, etc. # remember to close it when you're finished! Session.remove() </code></pre>
24,463,473
Add more text after using a filter in ng-bind in angularjs
<p>So I want to put a variable through a filter inthe ng-bind directive</p> <pre><code>ng-bind="input | filter" </code></pre> <p>but I want to insert more text </p> <pre><code>ng-bind="input | filter + 'more' " </code></pre> <p>but this isn't working. Is there a way to add more text in ng-bind, like you could if you were simply using <code>{{}}</code>:</p> <pre><code>{{input | filter}} more </code></pre>
24,463,770
2
0
null
2014-06-28 04:06:25 UTC
8
2018-01-17 09:45:07.797 UTC
null
null
null
null
1,266,650
null
1
62
angularjs|ng-bind|angular-filters
54,301
<p>Instead of interpolating(using <code>{{}}</code>) something in the <code>ng-bind</code> directive you can simply enclose the filtered value with a parenthesis and append your text.</p> <pre><code>&lt;h1 ng-bind="(input | filter) + ' more stuff'"&gt;&lt;/h1&gt; </code></pre> <p>furthermore, if the text you want to add is not in any way dynamic then I suggest you append another element to bind the filtered value and then add the text after that element.</p> <p>e.g.</p> <pre><code>&lt;h1&gt;&lt;span ng-bind="(input | filter)"&gt;&lt;/span&gt; more stuff&lt;/h1&gt; </code></pre> <p>This saves you one concatenation process.</p> <p><strong><a href="http://plnkr.co/edit/UNEwVBUL9zwAraiUYIBh?p=preview" rel="noreferrer">Example here</a></strong></p>
54,438,473
How to execute file.py on HTML button press using Django?
<p>My goal is to click an HTML button on my Django web page and this will execute a local python script.</p> <p>I am creating a local web application as an interface to a project. This will not be hosted and will always just run on my local machine. My project is run with a python script (which carries out numerous tests specific to my project). All I need is for a button in my web interface to execute this script on my machine.</p> <p>I have a template index.html where the whole web page is located. I presume I need to call some form of views function possibly when the button is pressed?</p> <p><a href="https://stackoverflow.com/questions/26299492/how-to-execute-python-code-by-django-html-button">How to execute python code by django html button?</a></p> <p>This question suggests:</p> <pre><code>def index(request): if request.method == 'GET': return render(request, 'yourapp/index.html', {'output': ''}) elif request.method == 'POST': py_obj = mycode.test_code(10) return render(request, 'yourapp/output.html', {'output': py_obj.a}) </code></pre> <p>I tried this just as a test but nothing happened when I went to the URL (located in the appropriate views.py):</p> <pre><code>def runtest(request): print("Hello World") Popen(['gnome-terminal', '-e', 'echo "Hello World"'], stdout=PIPE) return </code></pre> <p>However I don't quite understand if this achieves what I need it to, I am struggling to understand what the answer is suggesting.</p> <p>Where in the Django framework can I specify a call to a local python script when a button is pressed?</p> <p>(I have very limited experience with web applications, this is simply just meant to be a simple interface with some buttons to run tests)</p>
54,451,774
2
0
null
2019-01-30 10:33:00.403 UTC
9
2020-01-28 08:14:04.267 UTC
2019-01-30 11:59:08.03 UTC
null
5,631,940
null
5,631,940
null
1
9
javascript|python|html|django
17,222
<p>what you're going to want to try and do is submit a form on the button click. You can then import the functions you want to run from the script and call them in your view. You then redirect to the same page.</p> <p>I hope this helps!</p> <p><strong>index.html</strong></p> <pre><code>&lt;form method="post"&gt; {% csrf_token %} &lt;button type="submit" name="run_script"&gt;Run script&lt;/button&gt; &lt;/form&gt; </code></pre> <p><strong>views.py</strong></p> <pre><code>if request.method == 'POST' and 'run_script' in request.POST: # import function to run from path_to_script import function_to_run # call function function_to_run() # return user to required page return HttpResponseRedirect(reverse(app_name:view_name) </code></pre>
1,050,043
LDAP query for all users in sub OUs within a particular OU
<p>The active directory I have to deal with is laid out as such: the domain contains many OUs. One of these OUs is named "Primary OU". Within this OU are several OUs named with location of global offices (ie "Chicago" "Paris"). </p> <p>Any user account that is an actual flesh and bone person is put into the OU named for the office they work in as their primary OU. Any user account that is an alias, generic account, or otherwise not directly tied to a real person, has the "Primary OU" OU set as their primary OU.</p> <p>Data-wise, this primary OU distinction is the only thing that indicates which users are real people, and which users are not. There is no group that contains only real people, no indicator in any field that they are real people or not, and making any changes to active directory or any user accounts is strictly forbidden.</p> <p>My task is writing a query that will only get all actual flesh and bone people.</p> <p>Unfortunately LDAP is not exactly my strong suit and the only way I've come up with is searching each of these office sub OUs individually and putting all the results together, but there are a lot of offices and it would require a change to the query if any offices were added, which I need to avoid.</p> <p>Is there a way to query all users within a particular OU's "sub" OUs, but not return any users directly in the parent OU?</p>
1,050,055
2
2
null
2009-06-26 16:27:16.627 UTC
1
2012-08-06 19:13:12.207 UTC
null
null
null
null
108,971
null
1
10
active-directory|ldap
43,405
<p>Yes, sure - you would need to:</p> <p>1) Bind to the particular OU</p> <pre><code>DirectoryEntry myOU = new DirectoryEntry("LDAP://OU=MyOU,......,DC=MyCompany,DC=com"); </code></pre> <p>2) Enumerate all its sub-OU's</p> <pre><code>DirectorySearcher subOUsearcher = new DirectorySearcher(myOU); subOUsearcher.SearchScope = SearchScope.OneLevel; // don't recurse down subOUsearcher.Filter = "(objectClass=organizationalUnit)"; foreach(SearchResult subOU in subOUsearcher.FindAll()) { // stick those Sub OU's into a list and then handle them } </code></pre> <p>3) One-by-one enumerate all the users in each of the sub-OU's and stick them into a global list of users</p> <pre><code>DirectorySearcher userSearcher = new DirectorySearcher(myCurrentSubOu); userSearcher.SearchScope = SearchScope.OneLevel; // don't recurse down userSearcher.Filter = "(objectClass=user)"; foreach(SearchResult user in userSearcher.FindAll()) { // stick those users into a list being built up } </code></pre> <p>4) Return that list</p> <p>Marc</p>
257,605
OCaml: Match expression inside another one?
<p>I'm currently working on a small project with OCaml; a simple mathematical expression simplifier. I'm supposed to find certain patterns inside an expression, and simplify them so the number of parenthesis inside the expression decreases. So far I've been able to implement most rules except two, for which I've decided to create a recursive, pattern-matching "filter" function. The two rules I need to implement are:</p> <p>-Turn all expressions of the form a - (b + c) or similar into a - b - c</p> <p>-Turn all expressions of the form a / (b * c) or similar into a / b / c</p> <p>...which I suspect would be fairly simple, and once I've managed to implement one, I can implement the other easily. However, I'm having trouble with the recursive pattern-matching function. My type expression is this:</p> <pre><code>type expr = | Var of string (* variable *) | Sum of expr * expr (* sum *) | Diff of expr * expr (* difference *) | Prod of expr * expr (* product *) | Quot of expr * expr (* quotient *) ;; </code></pre> <p>And what I'm mainly having trouble on, is in the match expression. For example, I'm trying something like this:</p> <pre><code>let rec filter exp = match exp with | Var v -&gt; Var v | Sum(e1, e2) -&gt; Sum(e1, e2) | Prod(e1, e2) -&gt; Prod(e1, e2) | Diff(e1, e2) -&gt; match e2 with | Sum(e3, e4) -&gt; filter (diffRule e2) | Diff(e3, e4) -&gt; filter (diffRule e2) | _ -&gt; filter e2 | Quot(e1, e2) -&gt; ***this line*** match e2 with | Quot(e3, e4) -&gt; filter (quotRule e2) | Prod(e3, e4) -&gt; filter (quotRule e2) | _ -&gt; filter e2 ;; </code></pre> <p>However, it seems that the match expression on the marked line is being recognized as being part of the previous "inner match" instead of the "principal match", so all "Quot(...)" expressions are never recognized. Is it even possible to have match expressions inside other match expressions like this? And what would be the correct way to end the inner match so I can continue matching the other possibilities?</p> <p>Ignore the logic, since it's pretty much what I came up with first, it's just that I haven't been able to try it since I have to deal with this "match" error first, although any recommendation on how to handle the recursiveness or the logic would be welcome.</p>
257,627
2
0
null
2008-11-02 23:56:11.167 UTC
11
2021-12-20 09:59:47.013 UTC
2018-12-04 21:41:42.557 UTC
ypnos
1,371,329
Fireblend
9,506
null
1
52
pattern-matching|ocaml
40,242
<p><strong>Quick Solution</strong></p> <p>You just need to add parentheses, or <code>begin</code>/<code>end</code>, around the inner match:</p> <pre class="lang-ml prettyprint-override"><code>let rec filter exp = match exp with | Var v -&gt; Var v | Sum (e1, e2) -&gt; Sum (e1, e2) | Prod (e1, e2) -&gt; Prod (e1, e2) | Diff (e1, e2) -&gt; (match e2 with | Sum (e3, e4) -&gt; filter (diffRule e2) | Diff (e3, e4) -&gt; filter (diffRule e2) | _ -&gt; filter e2) | Quot (e1, e2) -&gt; (match e2 with | Quot (e3, e4) -&gt; filter (quotRule e2) | Prod (e3, e4) -&gt; filter (quotRule e2) | _ -&gt; filter e2) ;; </code></pre> <p><strong>Simplifications</strong></p> <p>In your particular case there is no need for a nested match. You can just use bigger patterns. You can also eliminate the duplication in the nested rules using &quot;<code>|</code>&quot; (&quot;or&quot;) patterns:</p> <pre><code>let rec filter exp = match exp with | Var v -> Var v | Sum (e1, e2) -> Sum (e1, e2) | Prod (e1, e2) -> Prod (e1, e2) | Diff (e1, (Sum (e3, e4) | Diff (e3, e4) as e2)) -> filter (diffRule e2) | Diff (e1, e2) -> filter e2 | Quot (e1, (Quot (e3, e4) | Prod (e3, e4) as e2)) -> filter (quotRule e2) | Quot (e1, e2) -> filter e2 ;; </code></pre> <p>You can make it even more readable by replacing unused pattern variables with <code>_</code> (underscore). This also works for whole sub patterns such as the <code>(e3,e4)</code> tuple:</p> <pre><code>let rec filter exp = match exp with | Var v -> Var v | Sum (e1, e2) -> Sum (e1, e2) | Prod (e1, e2) -> Prod (e1, e2) | Diff (_, (Sum _ | Diff _ as e2)) -> filter (diffRule e2) | Diff (_, e2) -> filter e2 | Quot (_, (Quot _ | Prod _ as e2)) -> filter (quotRule e2) | Quot (_, e2) -> filter e2 ;; </code></pre> <p>In the same way, you can proceed simplifying. For example, the first three cases (<code>Var</code>, <code>Sum</code>, <code>Prod</code>) are returned unmodified, which you can express directly:</p> <pre><code>let rec filter exp = match exp with | Var _ | Sum _ | Prod _ as e -> e | Diff (_, (Sum _ | Diff _ as e2)) -> filter (diffRule e2) | Diff (_, e2) -> filter e2 | Quot (_, (Quot _ | Prod _ as e2)) -> filter (quotRule e2) | Quot (_, e2) -> filter e2 ;; </code></pre> <p>Finally, you can replace <code>e2</code> by <code>e</code> and replace <code>match</code> with the <code>function</code> shortcut:</p> <pre><code>let rec filter = function | Var _ | Sum _ | Prod _ as e -> e | Diff (_, (Sum _ | Diff _ as e)) -> filter (diffRule e) | Diff (_, e) -> filter e | Quot (_, (Quot _ | Prod _ as e)) -> filter (quotRule e) | Quot (_, e) -> filter e ;; </code></pre> <p>OCaml's pattern syntax is nice, isn't it?</p>
2,393,847
How can I get an Android TableLayout to fill the screen?
<p>I'm battling with Android's awful layout system. I'm trying to get a table to fill the screen (simple right?) but it's ridiculously hard.</p> <p>I got it to work somehow in XML like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent"&gt; &lt;TableRow android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"&gt; &lt;Button android:text="A" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/&gt; &lt;Button android:text="B" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/&gt; &lt;/TableRow&gt; &lt;TableRow android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"&gt; &lt;Button android:text="C" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/&gt; &lt;Button android:text="D" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/&gt; &lt;/TableRow&gt; </code></pre> <p>However I can not get it to work in Java. I've tried a million combinations of the LayoutParams, but nothing ever works. This is the best result I have which only fills the width of the screen, not the height:</p> <pre><code> table = new TableLayout(this); // Java. You suck. TableLayout.LayoutParams lp = new TableLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); table.setLayoutParams(lp); // This line has no effect! WHYYYY?! table.setStretchAllColumns(true); for (int r = 0; r &lt; 2; ++r) { TableRow row = new TableRow(this); for (int c = 0; c &lt; 2; ++c) { Button btn = new Button(this); btn.setText("A"); row.addView(btn); } table.addView(row); } </code></pre> <p>Obviously the Android documentation is no help. Anyone have any ideas?</p>
2,481,381
5
3
null
2010-03-06 19:39:23.367 UTC
9
2018-08-09 00:05:15.473 UTC
2015-07-16 08:57:24.99 UTC
null
402,884
null
265,521
null
1
28
java|xml|android|layout|tablelayout
42,240
<p>Finally worked out how to do this. Gave up on <code>TableLayout</code> and just used horizontal <code>LinearLayout</code>s inside a vertical one. The critical key is to set the weight. If you specify <code>FILL_PARENT</code> but with the default weight, it doesn't work:</p> <pre><code>LinearLayout buttonsView = new LinearLayout(this); buttonsView.setOrientation(LinearLayout.VERTICAL); for (int r = 0; r &lt; 6; ++r) { LinearLayout row = new LinearLayout(this); row.setOrientation(LinearLayout.HORIZONTAL); for (int c = 0; c &lt; 4; ++c) { Button btn = new Button(this); btn.setText("A"); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); lp.weight = 1.0f; row.addView(btn, lp); } LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); lp.weight = 1.0f; buttonsView.addView(row, lp); } ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); setContentView(buttonsView, lp); </code></pre>
2,419,353
make ArrayList Read only
<p>In Java, how can you make an <code>ArrayList</code> read-only (so that no one can add elements, edit, or delete elements) after initialization?</p>
2,419,365
5
0
null
2010-03-10 18:08:21.047 UTC
7
2022-03-04 16:43:30.873 UTC
2013-03-05 02:27:36.817 UTC
null
737,040
null
238,052
null
1
70
java|collections|jakarta-ee|arraylist
47,606
<p>Pass the <code>ArrayList</code> into <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#unmodifiableList(java.util.List)" rel="noreferrer"><code>Collections.unmodifiableList()</code></a>. It returns an unmodifiable view of the specified list. Only use this returned <code>List</code>, and never the original <code>ArrayList</code>.</p>
2,663,912
Ruby on Rails: debugging rake tasks
<p>When I write <code>debugger</code> it does not start:</p> <pre><code>NoMethodError: undefined method `run_init_script' for Debugger:Module from /usr/local/lib/ruby/gems/1.8/gems/ruby-debug-base-0.10.3/lib/ruby-debug-base.rb:239:in `debugger' from (irb):4 </code></pre> <p>If I run <code>rake my:task --debugger</code>,it returns me to console immediately. How is it possible to debug rake tasks?</p>
2,663,970
6
1
null
2010-04-18 20:53:10.063 UTC
8
2016-10-22 07:31:40.183 UTC
2014-06-23 22:07:49.633 UTC
null
1,277,538
null
222,380
null
1
43
ruby-on-rails|ruby|debugging|rake|ruby-debug
31,885
<p>I found the solution.</p> <pre><code>$ gem install ruby-debug $ ruby-debug rake my:task </code></pre> <p>or on some systems</p> <pre><code>$ rdebug rake my:task </code></pre>
2,627,650
Why JavaScript getTime() is not a function?
<p>I used the following function:</p> <pre><code>function datediff() { var dat1 = document.getElementById('date1').value; alert(dat1);//i get 2010-04-01 var dat2 = document.getElementById('date2').value; alert(dat2);// i get 2010-04-13 var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds var diffDays = Math.abs((dat1.getTime() - dat2.getTime())/(oneDay)); alert(diffDays); } </code></pre> <p>I get the error:</p> <blockquote> <pre><code>dat1.getTime()` is not a function </code></pre> </blockquote>
2,627,664
6
0
null
2010-04-13 07:12:39.837 UTC
7
2022-09-08 08:15:14.94 UTC
2021-04-02 10:33:52.563 UTC
null
9,193,372
null
241,853
null
1
57
javascript|function|date|gettime
185,332
<p>That's because your <code>dat1</code> and <code>dat2</code> variables are just strings.</p> <p>You should parse them to get a <code>Date</code> object, for that format I always use the following function:</p> <pre><code>// parse a date in yyyy-mm-dd format function parseDate(input) { var parts = input.match(/(\d+)/g); // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]]) return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based } </code></pre> <p>I use this function because the <a href="http://bclary.com/2004/11/07/#a-15.9.4.2" rel="noreferrer"><code>Date.parse(string)</code></a> (or <code>new Date(string)</code>) method is <em>implementation dependent</em>, and the <em>yyyy-MM-dd</em> format will work on modern browser but <em>not</em> on IE, so I prefer doing it manually.</p>
2,352,623
Is there an online code coloring service?
<p>I would like to know if there is an online service where we paste the code and it generates back the colored HTML source code for that code. It could be PHP, HTML, CSS, JavaScript, C, and Java.</p> <p>The idea is that once I have the colored HTML code, I could easily put that in my wordpress.com blog. I know about <code>[sourcecode language=&quot;whatever&quot;]</code>, but I just wanted to know an online service that supports multiple languages. The <strong>benefit</strong> is that, I can choose any color style/theme from that online service for my code.</p>
2,352,641
7
0
null
2010-02-28 20:52:39.35 UTC
14
2020-09-05 22:37:30.76 UTC
2020-09-05 22:34:38.957 UTC
null
63,550
null
139,459
null
1
37
c#|php|javascript|wordpress
7,681
<p>Also you can use <a href="http://tohtml.com/html/" rel="noreferrer">http://tohtml.com/html/</a> or <a href="http://qbnz.com/highlighter/demo.php" rel="noreferrer">GeSHi</a></p>
2,536,692
A simple scenario using wait() and notify() in java
<p>Can I get a complete simple scenario i.e. tutorial that suggest how this should be used, specifically with a Queue?</p>
2,537,117
7
0
null
2010-03-29 08:47:17.307 UTC
114
2022-02-20 23:07:08.087 UTC
2013-08-15 14:58:41.893 UTC
user1228
null
null
445,584
null
1
202
java|wait|notify
243,852
<p>The <code>wait()</code> and <code>notify()</code> methods are designed to provide a mechanism to allow a thread to block until a specific condition is met. For this I assume you're wanting to write a blocking queue implementation, where you have some fixed size backing-store of elements.</p> <p>The first thing you have to do is to identify the conditions that you want the methods to wait for. In this case, you will want the <code>put()</code> method to block until there is free space in the store, and you will want the <code>take()</code> method to block until there is some element to return.</p> <pre><code>public class BlockingQueue&lt;T&gt; { private Queue&lt;T&gt; queue = new LinkedList&lt;T&gt;(); private int capacity; public BlockingQueue(int capacity) { this.capacity = capacity; } public synchronized void put(T element) throws InterruptedException { while(queue.size() == capacity) { wait(); } queue.add(element); notify(); // notifyAll() for multiple producer/consumer threads } public synchronized T take() throws InterruptedException { while(queue.isEmpty()) { wait(); } T item = queue.remove(); notify(); // notifyAll() for multiple producer/consumer threads return item; } } </code></pre> <p>There are a few things to note about the way in which you must use the wait and notify mechanisms. </p> <p>Firstly, you need to ensure that any calls to <code>wait()</code> or <code>notify()</code> are within a synchronized region of code (with the <code>wait()</code> and <code>notify()</code> calls being synchronized on the same object). The reason for this (other than the standard thread safety concerns) is due to something known as a missed signal. </p> <p>An example of this, is that a thread may call <code>put()</code> when the queue happens to be full, it then checks the condition, sees that the queue is full, however before it can block another thread is scheduled. This second thread then <code>take()</code>'s an element from the queue, and notifies the waiting threads that the queue is no longer full. Because the first thread has already checked the condition however, it will simply call <code>wait()</code> after being re-scheduled, even though it could make progress.</p> <p>By synchronizing on a shared object, you can ensure that this problem does not occur, as the second thread's <code>take()</code> call will not be able to make progress until the first thread has actually blocked.</p> <p>Secondly, you need to put the condition you are checking in a while loop, rather than an if statement, due to a problem known as spurious wake-ups. This is where a waiting thread can sometimes be re-activated without <code>notify()</code> being called. Putting this check in a while loop will ensure that if a spurious wake-up occurs, the condition will be re-checked, and the thread will call <code>wait()</code> again.</p> <hr> <p>As some of the other answers have mentioned, Java 1.5 introduced a new concurrency library (in the <code>java.util.concurrent</code> package) which was designed to provide a higher level abstraction over the wait/notify mechanism. Using these new features, you could rewrite the original example like so:</p> <pre><code>public class BlockingQueue&lt;T&gt; { private Queue&lt;T&gt; queue = new LinkedList&lt;T&gt;(); private int capacity; private Lock lock = new ReentrantLock(); private Condition notFull = lock.newCondition(); private Condition notEmpty = lock.newCondition(); public BlockingQueue(int capacity) { this.capacity = capacity; } public void put(T element) throws InterruptedException { lock.lock(); try { while(queue.size() == capacity) { notFull.await(); } queue.add(element); notEmpty.signal(); } finally { lock.unlock(); } } public T take() throws InterruptedException { lock.lock(); try { while(queue.isEmpty()) { notEmpty.await(); } T item = queue.remove(); notFull.signal(); return item; } finally { lock.unlock(); } } } </code></pre> <hr> <p>Of course if you actually need a blocking queue, then you should use an implementation of the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html" rel="noreferrer">BlockingQueue</a> interface.</p> <p>Also, for stuff like this I'd highly recommend <a href="http://www.amazon.co.uk/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601" rel="noreferrer">Java Concurrency in Practice</a>, as it covers everything you could want to know about concurrency related problems and solutions.</p>
2,705,719
jqGrid trigger "Loading..." overlay
<p>Does anyone know how to trigger the stock jqGrid "Loading..." overlay that gets displayed when the grid is loading? I know that I can use a jquery plugin without much effort but I'd like to be able to keep the look-n-feel of my application consistent with that of what is already used in jqGrid.</p> <p>The closes thing I've found is this:</p> <p><a href="https://stackoverflow.com/questions/2614643/jqgrid-display-default-loading-message-when-updating-a-table-on-custom-update">jqGrid display default &quot;loading&quot; message when updating a table / on custom update</a></p> <ul> <li>n8</li> </ul>
2,706,447
10
0
null
2010-04-24 18:47:50.52 UTC
5
2021-12-03 13:02:04.23 UTC
2017-05-23 12:07:08.61 UTC
null
-1
null
319,969
null
1
13
jqgrid|overlay|loading
43,275
<p>If you are searching for something like <code>DisplayLoadingMessage()</code> function. It does not exist in jqGrid. You can only set the <em>loadui</em> option of jqGrid to <em>enable</em> (default), <em>disable</em> or <em>block</em>. I personally prefer <em>block</em>. (see <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options" rel="nofollow noreferrer">http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options</a>). But I think it is not what you wanted.</p> <p>The only thing which you can do, if you like the "Loading..." message from jqGrid, is to make the same one. I'll explain here what jqGrid does to display this message: Two hidden divs will be created. If you have a grid with id=list, this divs will look like following:</p> <pre class="lang-html prettyprint-override"><code>&lt;div style="display: none" id="lui_list" class="ui-widget-overlay jqgrid-overlay"&gt;&lt;/div&gt; &lt;div style="display: none" id="load_list" class="loading ui-state-default ui-state-active"&gt;Loading...&lt;/div&gt; </code></pre> <p>where the text "Loading..." or "Lädt..." (in German) comes from <code>$.jgrid.defaults.loadtext</code>. The ids of divs will be constructed from the "lui_" or "load_" prefix and grid id ("list"). Before sending ajax request jqGrid makes one or two of this divs visible. It calls <code>jQuery.show()</code> function for the second div (id="load_list") if <em>loadui</em> option is <em>enable</em>. If <em>loadui</em> option is <em>block</em>, however, then both divs (id="lui_list" and id="load_list") will be shown with respect of <code>.show()</code> function. After the end of ajax request <code>.hide()</code> jQuery function will be called for one or two divs. It's all.</p> <p>You will find the definition of all css classes in <code>ui.jqgrid.css</code> or <code>jquery-ui-1.8.custom.css</code>.</p> <p>Now you have enough information to reproduce jqGrid "Loading..." message, but if I were you I would think one more time whether you really want to do this or whether the <a href="http://malsup.com/jquery/block/" rel="nofollow noreferrer">jQuery blockUI plugin</a> is better for your goals.</p>
3,011,179
Django - The included urlconf doesn't have any patterns in it
<p>My website, which was working before, suddenly started breaking with the error</p> <blockquote> <p>ImproperlyConfigured at / The included urlconf resume.urls doesn't have any patterns in it</p> </blockquote> <p>The project base is called resume. In settings.py I have set</p> <pre><code>ROOT_URLCONF = 'resume.urls' </code></pre> <p>Here's my resume.urls, which sits in the project root directory. </p> <pre><code>from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^resume/', include('resume.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^accounts/login/$', 'django.contrib.auth.views.login'), #(r'^employer/', include(students.urls)), (r'^ajax/', include('urls.ajax')), (r'^student/', include('students.urls')), (r'^club/(?P&lt;object_id&gt;\d+)/$', 'resume.students.views.club_detail'), (r'^company/(?P&lt;object_id&gt;\d+)/$', 'resume.students.views.company_detail'), (r'^program/(?P&lt;object_id&gt;\d+)/$', 'resume.students.views.program_detail'), (r'^course/(?P&lt;object_id&gt;\d+)/$', 'resume.students.views.course_detail'), (r'^career/(?P&lt;object_id&gt;\d+)/$', 'resume.students.views.career_detail'), (r'^site_media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': 'C:/code/django/resume/media'}), ) </code></pre> <p>I have a folder called urls and a file ajax.py inside. (I also created a blank <strong>init</strong>.py in the same folder so that urls would be recognized.) This is ajax.py.</p> <pre><code>from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^star/(?P&lt;object_id&gt;\d+)$', 'resume.students.ajax-calls.star'), ) </code></pre> <p>Anyone know what's wrong? This is driving me crazy.</p> <p>Thanks,</p>
3,011,196
11
0
null
2010-06-10 02:03:14.967 UTC
12
2021-12-25 15:23:00.523 UTC
2019-08-28 15:53:25.23 UTC
null
8,686,588
null
146,478
null
1
54
python|django
71,949
<p>Check your patterns for include statements that point to non-existent modules or modules that do not have a <code>urlpatterns</code> member. I see that you have an <code>include('urls.ajax')</code> which may not be correct. Should it be <code>ajax.urls</code>?</p>
2,625,707
Split a string into an array of strings based on a delimiter
<p>I'm trying to find a Delphi function that will split an input string into an array of strings based on a delimiter. I've found a lot from searching the web, but all seem to have their own issues and I haven't been able to get any of them to work.</p> <p>I just need to split a string like: <code>&quot;word:doc,txt,docx&quot;</code> into an array based on ':'. The result would be <code>['word', 'doc,txt,docx']</code>. How can I do that?</p>
2,625,799
20
0
null
2010-04-12 21:49:38.19 UTC
26
2021-08-07 08:37:27.26 UTC
2021-08-07 08:37:27.26 UTC
null
472,495
null
294,120
null
1
89
delphi|string|split|delimiter
299,104
<p>you can use the TStrings.DelimitedText property for split an string</p> <p>check this sample</p> <pre><code>program Project28; {$APPTYPE CONSOLE} uses Classes, SysUtils; procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ; begin ListOfStrings.Clear; ListOfStrings.Delimiter := Delimiter; ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer. ListOfStrings.DelimitedText := Str; end; var OutPutList: TStringList; begin OutPutList := TStringList.Create; try Split(':', 'word:doc,txt,docx', OutPutList) ; Writeln(OutPutList.Text); Readln; finally OutPutList.Free; end; end. </code></pre> <p>UPDATE</p> <p>See this <a href="https://stackoverflow.com/questions/1335027/delphi-stringlist-delimiter-is-always-a-space-character-even-if-delimiter-is-set">link</a> for an explanation of <code>StrictDelimiter</code>.</p>
39,979,880
kubectl exec into container of a multi container pod
<p>I have problem login into one container of a multi-container pod. I get the container id from the <code>kubectl describe pod &lt;pod-name&gt;</code></p> <pre><code>kubectl describe pod ipengine-net-benchmark-488656591-gjrpc -c &lt;container id&gt; </code></pre> <p>When i try: </p> <pre><code>kubectl exec -ti ipengine-net-benchmark-488656591-gjrpc -c 70761432854f /bin/bash </code></pre> <p>It says: Error from server: container 70761432854f is not valid for pod ipengine-net-benchmark-488656591-gjrpc</p>
39,979,989
1
0
null
2016-10-11 14:40:05.817 UTC
7
2022-03-04 08:48:11.457 UTC
2020-12-18 13:47:38.203 UTC
null
1,898,534
null
1,898,534
null
1
64
kubernetes
47,320
<p>ah once more detailed reading the man page of kubectl exec :</p> <p>Flags:</p> <pre><code> -c, --container=&quot;&quot;: Container name. If omitted, the first container in the pod will be chosen -p, --pod=&quot;&quot;: Pod name -i, --stdin[=false]: Pass stdin to the container -t, --tty[=false]: Stdin is a TTY </code></pre> <p>So i just used the container name from my manifest.yaml and it worked like charm. Hope this helps others ...</p> <p><code>Name of the container: ipengine-net-benchmark-iperf-server</code></p> <pre><code>kubectl exec -ti ipengine-net-benchmark-488656591-gjrpc -c ipengine-net-benchmark-iperf-server /bin/bash </code></pre>
10,449,917
Android change color of ImageView / Bitmap
<p>I need to find a way to change the color of bitmap in Android. I need to replace/change colors of oval image smoothly in my application depending on <code>int</code> value. I need something like if <code>myValue=5</code> than change my image's color to <code>RED</code> and if <code>myValue=322</code> change color to <code>BLUE</code>. The only way which I find I can do this was using xml file which looks like this :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" android:padding="10dp"&gt; &lt;!-- you can use any color you want I used here gray color--&gt; &lt;solid android:color="#cccccc"/&gt; &lt;corners android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp" android:topLeftRadius="10dp" android:topRightRadius="10dp"/&gt; &lt;/shape&gt; </code></pre> <p>and after that when <code>myValue</code> is changing to set my <code>ImageView</code> image resource. But in this way I have to create 35 different xml files...which I don't think is a good idea.</p> <p>So anyone who can suggest better solution to do this?</p>
10,483,733
6
0
null
2012-05-04 13:34:12.373 UTC
3
2021-10-07 09:34:05.857 UTC
null
null
null
null
917,586
null
1
8
android|bitmap|android-imageview
39,075
<p>This is how I solved this issue :</p> <ol> <li>Declare an <code>ImageView</code> with <code>src="@drawable/button"</code></li> <li>Create a <code>Drawable</code> and set <code>ColorFilter</code> to it and after that use it as src to your declared <code>ImageView</code> like this :</li> </ol> <p>></p> <pre><code>Drawable myIcon = getResources().getDrawable( R.drawable.button ); ColorFilter filter = new LightingColorFilter( Color.BLUE, Color.BLUE ); myIcon.setColorFilter(filter); color.setImageDrawable(myIcon); </code></pre>
10,385,452
Location of spring-context.xml
<p>When I run my application on tomcat the spring-context.xml file is located at </p> <blockquote> <p>/WEB-inf/spring-context.xml</p> </blockquote> <p>This is ok. But running a junit test I have to supply it with the location of my spring-test-context.xml like this: </p> <pre><code>@ContextConfiguration(locations={"classpath:/spring-test-context.xml"}) </code></pre> <p>The only way this works is if the file is located in </p> <blockquote> <p>/src/spring-context.xml</p> </blockquote> <p>How can I get my application to find my spring-context files in the same location? So that it works with junit testes and deployed on tomcat?</p> <p>I tried this and it gave me alot of errors about not finding any beans, but it didn't say it couldn't find the file..</p> <pre><code>classpath:/WEB-INF/spring-test-context.xml </code></pre>
10,522,417
2
0
null
2012-04-30 14:33:41.593 UTC
11
2016-01-27 08:19:01.41 UTC
2015-10-07 17:16:22.86 UTC
null
826,983
null
142,824
null
1
21
java|spring|junit
77,640
<p>As duffymo hinted at, the Spring TestContext Framework (TCF) assumes that string locations are in the classpath by default. For details, see the JavaDoc for <a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/test/context/ContextConfiguration.html" rel="noreferrer">ContextConfiguration</a>.</p> <p>Note, however, that you can also specify resources in the file system with either an absolute or relative path using Spring's resource abstraction (i.e., by using the "file:" prefix). You can find details on that in the JavaDoc for the <a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/test/context/support/AbstractContextLoader.html#modifyLocations%28java.lang.Class,%20java.lang.String...%29" rel="noreferrer">modifyLocations()</a> method in Spring's <code>AbstractContextLoader</code>.</p> <p>So for example, if your XML configuration file is located in <code>"src/main/webapp/WEB-INF/spring-config.xml"</code> in your project folder, you could specify the location as a relative file system path as follows:</p> <pre><code>@ContextConfiguration("file:src/main/webapp/WEB-INF/spring-config.xml") </code></pre> <p>As an alternative, you could store your Spring configuration files in the classpath (e.g., <code>src/main/resources</code>) and then reference them via the classpath in your Spring MVC configuration -- for example:</p> <pre class="lang-xml prettyprint-override"><code>&lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;classpath:/spring-config.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; </code></pre> <p>With this approach, your test configuration would simply look like this (note the leading slash that denotes that the resource is in the root of the classpath):</p> <pre><code>@ContextConfiguration("/spring-config.xml") </code></pre> <p>You might also find the <a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#testcontext-ctx-management-xml" rel="noreferrer">Context configuration with XML resources</a> section of the reference manual useful.</p> <p>Regards,</p> <p>Sam</p> <p><em>(author of the Spring TestContext Framework)</em></p>
10,416,424
Underscore.js: create a map out of list of objects using a key found in the object
<p>I am using the excellent <a href="http://underscorejs.org/">Underscore.js</a> library. I have a specific task which I can do fine using JavaScript or jQuery but was wondering if there was some sort of abstraction avaialable in Underscore that I was missing out on.</p> <p>Essentially I have an object like so - </p> <pre><code>var some_object_array = [{id: "a", val: 55}, {id: "b", val: 1}, {id: "c", val: 45}]; </code></pre> <p>I want to convert this into -</p> <pre><code>var some_map = {"a": {id: "a", val: 55}, "b": {id: "b", val: 1}, "c": {id: "c", val: 45}}; </code></pre> <p>I know that I can use <code>_.groupBy(some_object_array, "id")</code>. But this returns a map like so -</p> <pre><code>var some_grouped_map = {"a": [{id: "a", val: 55}], "b": [{id: "b", val: 1}], "c": [{id: "c", val: 45}]}; </code></pre> <p>Note that this does what it is advertised to do. But I was hoping to get <code>some_map</code> without iterating over the objects myself.</p> <p>Any help appreciated.</p>
12,852,042
6
0
null
2012-05-02 15:04:16.45 UTC
6
2019-05-15 05:01:11.443 UTC
2015-09-01 13:11:36.717 UTC
null
3,335,966
null
131,315
null
1
60
javascript|underscore.js|javascript-objects
59,450
<p>For what it's worth, since underscore.js you can now use <a href="http://underscorejs.org/#object" rel="nofollow noreferrer"><code>_.object()</code></a></p> <pre><code>var some_map = _.object(_.map(some_object_array, function(item) { return [item.id, item] })); </code></pre>
19,533,019
Is it safe to delete the journal file of mongodb?
<p>If I delete the 3.1G journal file, <code>sudo service mongodb restart</code> will fail. However, this file is taking too much space. How can I solve this problem? How can I remove it?</p> <pre class="lang-none prettyprint-override"><code>bash$ du -sh /var/lib/mongodb/* 4.0K _tmp 65M auction_development.0 128M auction_development.1 17M auction_development.ns 3.1G journal 4.0K mongod.lock </code></pre>
19,535,463
3
0
null
2013-10-23 04:49:28.433 UTC
24
2017-10-10 06:48:01.3 UTC
2017-03-12 02:06:12.977 UTC
null
1,253,312
null
2,797,018
null
1
72
linux|mongodb|disk
50,647
<p>TL;DR: You have two options. Use the <code>--smallfiles</code> startup option when starting MongoDB to <a href="http://docs.mongodb.org/manual/core/journaling/#journal-files">limit the size of the journal files</a> to 128MB, or turn off journalling using the <code>--nojournal</code> option. Using <code>--nojournal</code> in production is usually a bad idea, and it often makes sense to use different write concerns also in development so you don't have different code in dev and prod.</p> <p><strong>The long answer</strong>: No, deleting the journal file isn't safe. The idea of journalling is this:</p> <p>A write comes in. Now, to make that write persistent (and the database durable), the write must somehow go to the disk.</p> <p>Unfortunately, writes to the disk take eons <a href="https://gist.github.com/hellerbarde/2843375">compared to writes to the RAM</a>, so the database is in a dilemma: not writing to the disk is risky, because an unexpected shutdown would cause data loss. But writing to the disk for every single write operation will decrease the database's performance so badly that it becomes unusable for practical purposes.</p> <p>Now instead of writing to the data files themselves, and instead of doing it for every request, the database will simply append to a journal file where it stores all the operations that haven't been committed to the actual data files yet. This is a lot faster, because the file is already 'hot' since it's read and written to all the time, and it's only one file, not a bunch of files, and lastly, because it writes all pending operations in a batch every 100ms by default. Deleting this file in the middle of something wreaks havoc.</p>
21,223,894
Manage Connection Pooling in multi-tenant web app with Spring, Hibernate and C3P0
<p>I'm trying to setup a multi-tenant web application, with (ideally) possibility for both Database-separated and Schema-separated approach at the same time. Although I'm going to start with Schema separation. We're currently using: </p> <ul> <li>Spring 4.0.0</li> <li>Hibernate 4.2.8</li> <li>Hibernate-c3p0 4.2.8 (which uses c3p0-0.9.2.1)</li> <li>and PostgreSQL 9.3 (which I doubt it really matters for the overall architecture)</li> </ul> <p>Mostly I followed <a href="http://forum.spring.io/forum/spring-projects/data/114116-sessionfactory-configured-for-multi-tenancy-but-no-tenant-identifier-specified" rel="noreferrer">this thread</a> (because of the solution for <code>@Transactional</code>). But I'm kinda lost in implementing <code>MultiTenantContextConnectionProvider</code>. There is also <a href="https://stackoverflow.com/questions/12351724/implement-an-abstractmultitenantconnectionprovider">this similar question</a> asked here on SO, but there are some aspects that I can't figure out: </p> <p>1) What happens to Connection Pooling? I mean, is it managed by Spring or Hibernate? I guess with <code>ConnectionProviderBuilder</code> - or as suggested - any of its implementation, Hibernate is the guy who manages it.<br> 2) Is it a good approach that Spring does not manage Connection Pooling? or Is it even possible that Spring does manage it?<br> 3) Is this the right path for future implementing of both Database and Schema separation?</p> <p>Any comments or descriptions are totally appreciated.</p> <p><strong>application-context.xml</strong></p> <pre><code>&lt;beans&gt; ... &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy"&gt; &lt;property name="targetDataSource" ref="c3p0DataSource" /&gt; &lt;/bean&gt; &lt;bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"&gt; &lt;property name="driverClass" value="org.postgresql.Driver" /&gt; ... other C3P0 related config &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt; &lt;property name="packagesToScan" value="com.webapp.domain.model" /&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.PostgreSQLDialect&lt;/prop&gt; &lt;prop key="hibernate.default_schema"&gt;public&lt;/prop&gt; &lt;prop key="hibernate.multiTenancy"&gt;SCHEMA&lt;/prop&gt; &lt;prop key="hibernate.tenant_identifier_resolver"&gt;com.webapp.persistence.utility.CurrentTenantContextIdentifierResolver&lt;/prop&gt; &lt;prop key="hibernate.multi_tenant_connection_provider"&gt;com.webapp.persistence.utility.MultiTenantContextConnectionProvider&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt; &lt;property name="autodetectDataSource" value="false" /&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; ... &lt;/beans&gt; </code></pre> <p><strong>CurrentTenantContextIdentifierResolver.java</strong></p> <pre><code>public class CurrentTenantContextIdentifierResolver implements CurrentTenantIdentifierResolver { @Override public String resolveCurrentTenantIdentifier() { return CurrentTenantIdentifier; // e.g.: public, tid130, tid456, ... } @Override public boolean validateExistingCurrentSessions() { return true; } } </code></pre> <p><strong>MultiTenantContextConnectionProvider.java</strong></p> <pre><code>public class MultiTenantContextConnectionProvider extends AbstractMultiTenantConnectionProvider { // Do I need this and its configuratrion? //private C3P0ConnectionProvider connectionProvider = null; @Override public ConnectionProvider getAnyConnectionProvider() { // the main question is here. } @Override public ConnectionProvider selectConnectionProvider(String tenantIdentifier) { // and of course here. } } </code></pre> <p><br /></p> <hr> <p><strong>Edit</strong> </p> <p>Regarding <a href="https://stackoverflow.com/questions/21223894/manage-connection-pooling-in-multi-tenant-web-app-with-spring-hibernate-and-c3p/21364219#21364219">the answer</a> of @ben75: </p> <p>This is a new implementation of <code>MultiTenantContextConnectionProvider</code>. It no longer extends <code>AbstractMultiTenantConnectionProvider</code>. It rather implements <code>MultiTenantConnectionProvider</code>, to be able to return <code>[Connection][4]</code> instead of <code>[ConnectionProvider][5]</code></p> <pre><code>public class MultiTenantContextConnectionProvider implements MultiTenantConnectionProvider, ServiceRegistryAwareService { private DataSource lazyDatasource;; @Override public void injectServices(ServiceRegistryImplementor serviceRegistry) { Map lSettings = serviceRegistry.getService(ConfigurationService.class).getSettings(); lazyDatasource = (DataSource) lSettings.get( Environment.DATASOURCE ); } @Override public Connection getAnyConnection() throws SQLException { return lazyDatasource.getConnection(); } @Override public Connection getConnection(String tenantIdentifier) throws SQLException { final Connection connection = getAnyConnection(); try { connection.createStatement().execute("SET SCHEMA '" + tenantIdentifier + "'"); } catch (SQLException e) { throw new HibernateException("Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", e); } return connection; } } </code></pre>
21,364,219
2
2
null
2014-01-19 23:09:15.023 UTC
28
2017-12-07 21:27:11.477 UTC
2017-05-23 12:09:52.84 UTC
null
-1
null
493,615
null
1
31
spring|hibernate|postgresql|multi-tenant|c3p0
24,634
<p>You can choose between 3 different strategies that will impact connection polling. In any case you have to provide an implementation of <a href="http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/service/jdbc/connections/spi/MultiTenantConnectionProvider.html" rel="noreferrer"><code>MultiTenantConnectionProvider</code></a>. The strategy you choose will of course impact your implementation.</p> <p><strong>General remark about <code>MultiTenantConnectionProvider.getAnyConnection()</code></strong></p> <p><a href="http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/service/jdbc/connections/spi/MultiTenantConnectionProvider.html#getAnyConnection%28%29" rel="noreferrer"><code>getAnyConnection()</code></a> is required by hibernate to collect metadata and setup the SessionFactory. Usually in a multi-tenant architecture you have a special/master database (or schema) not used by any tenant. It's a kind of template database (or schema). It's ok if this method returns a connection to this database (or schema).</p> <p><strong>Strategy 1 : each tenant have it's own database.</strong> (and so it's own connection pool)</p> <p>In this case, each tenant have it's own connection pool managed by C3PO and you can provide an implementation of <a href="http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/service/jdbc/connections/spi/MultiTenantConnectionProvider.html" rel="noreferrer"><code>MultiTenantConnectionProvider</code></a> based on <a href="http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/service/jdbc/connections/spi/AbstractMultiTenantConnectionProvider.html" rel="noreferrer"><code>AbstractMultiTenantConnectionProvider</code></a></p> <p>Every tenant have it's own <a href="http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.html" rel="noreferrer"><code>C3P0ConnectionProvider</code></a>, so all you have to do in <a href="http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/service/jdbc/connections/spi/AbstractMultiTenantConnectionProvider.html#selectConnectionProvider%28java.lang.String%29" rel="noreferrer"><code>selectConnectionProvider(tenantIdentifier)</code></a> is to return the correct one. You can keep a Map to cache them and you can lazy-initialize a C3POConnectionProvider with something like :</p> <pre><code>private ConnectionProvider lazyInit(String tenantIdentifier){ C3P0ConnectionProvider connectionProvider = new C3P0ConnectionProvider(); connectionProvider.configure(getC3POProperties(tenantIdentifier)); return connectionProvider; } private Map getC3POProperties(String tenantIdentifier){ // here you have to get the default hibernate and c3po config properties // from a file or from Spring application context (there are good chances // that those default properties point to the special/master database) // and alter them so that the datasource point to the tenant database // i.e. : change the property hibernate.connection.url // (and any other tenant specific property in your architecture like : // hibernate.connection.username=tenantIdentifier // hibernate.connection.password=... // ...) } </code></pre> <p><strong>Strategy 2 : each tenant have it's own schema and it's own connection pool in a single database</strong></p> <p>This case is very similar to the first strategy regarding <code>ConnectionProvider</code> implementation since you can also use <a href="http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/service/jdbc/connections/spi/AbstractMultiTenantConnectionProvider.html" rel="noreferrer"><code>AbstractMultiTenantConnectionProvider</code></a> as base class to implement your <a href="http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/service/jdbc/connections/spi/MultiTenantConnectionProvider.html" rel="noreferrer"><code>MultiTenantConnectionProvider</code></a></p> <p>The implementation is very similar to the suggested implementation for Strategy 1 except that you must alter the schema instead of the database in the c3po configuration</p> <p><strong>Strategy 3 : each tenant have it's own schema in a single database but use a shared connection pool</strong></p> <p>This case is slightly different since every tenant will use the same connection provider (and so the connection pool will be shared). In the case : the connection provider must set the schema to use prior to any usage of the connection. i.e. You must implement <code>MultiTenantConnectionProvider.getConnection(String tenantIdentifier)</code> (i.e. the default implementation provided by <code>AbstractMultiTenantConnectionProvider</code> won't work).</p> <p>With <a href="http://www.postgresql.org/docs/9.1/static/sql-set.html" rel="noreferrer">postgresql</a> you can do it with :</p> <pre><code> SET search_path to &lt;schema_name_for_tenant&gt;; </code></pre> <p>or using the alias</p> <pre><code> SET schema &lt;schema_name_for_tenant&gt;; </code></pre> <p>So here is what your <code>getConnection(tenant_identifier);</code> will look like:</p> <pre><code>@Override public Connection getConnection(String tenantIdentifier) throws SQLException { final Connection connection = getAnyConnection(); try { connection.createStatement().execute( "SET search_path TO " + tenanantIdentifier ); } catch ( SQLException e ) { throw new HibernateException( "Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]", e ); } return connection; } </code></pre> <p>Useful reference is <a href="https://docs.jboss.org/hibernate/core/4.2/devguide/en-US/html/ch16.html#d5e4755" rel="noreferrer">here</a> (official doc)</p> <p>Other useful link <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.hibernate/hibernate-c3p0/4.2.6.Final/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java/" rel="noreferrer">C3POConnectionProvider.java</a></p> <hr> <p>You can combine strategy 1 and strategy 2 in your implementation. You just need a way to find the correct connection properties/connection url for the current tenant.</p> <hr> <p><strong>EDIT</strong></p> <p>I think that the choice between strategy 2 or 3 depends on the traffic and the number of tenants on your app. With separate connection pools : the amount of connections available for one tenant will be much lower and so: if for some legitime reason one tenant need suddenly many connections the performance seen by this particular tenant will drastically decrease (while the other tenant won't be impacted).</p> <p>On the other hand, with strategy 3, if for some legitime reason one tenant need suddenly many connections: the performance seen by every tenant will decrease.</p> <p>In general , I think that strategy 2 is more flexible and safe : every tenant cannot consume more than a given amount of connection (and this amount can be configured per tenant if you need it)</p>
21,487,066
Get URL(link) of a public S3 object programmatically
<p>I am storing one public object in AWS S3 bucket using given java API in my server Now i need to return back the public URL of the S3 object to my client</p> <p>Till now i have'nt found any API call that can return the public URL(or link field) of a S3 object</p> <p>Is there any way to get the URL??</p>
33,569,459
7
0
null
2014-01-31 18:08:51.127 UTC
5
2021-09-15 19:07:44.17 UTC
null
null
null
null
2,786,065
null
1
25
java|amazon-web-services|amazon-s3
39,079
<p><strong>For Java SDK 2</strong></p> <pre><code>s3Client.utilities().getUrl(builder -&gt; builder.bucket(AWS_BUCKET).key(s3RelativeFilePath)).toExternalForm(); </code></pre> <p>Reference - <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Utilities.html#getUrl-java.util.function.Consumer-" rel="noreferrer">https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Utilities.html#getUrl-java.util.function.Consumer-</a></p> <p><strong>older versions had:</strong></p> <pre><code>s3Client.getResourceUrl(bucket, s3RelativeToBucketPath); </code></pre>
19,070,615
python - os.getenv and os.environ don't see environment variables of my bash shell
<p>I am on ubuntu 13.04, bash, python2.7.4</p> <p><strong>The interpreter doesn't see variables I set.</strong></p> <p>Here is an example:</p> <pre><code>$ echo $A 5 $ python -c 'import os; print os.getenv( "A" )' None $ python -c 'import os; print os.environ[ "A" ]' Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__ raise KeyError(key) KeyError: 'A' </code></pre> <p>But everything works fine with the <code>PATH</code> variable:</p> <pre><code>$ echo $PATH /usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games $ python -c 'import os; print os.getenv("PATH")' /usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games </code></pre> <p>And it notices changes in <code>PATH</code>:</p> <pre><code>$ PATH="/home/alex/tests/:$PATH" $ echo $PATH /home/alex/tests/:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games $ python -c 'import os; print os.getenv("PATH")' /home/alex/tests/:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games </code></pre> <p>What could be wrong?</p> <p>PS the problem comes when using <code>$PYTHONPATH</code>:</p> <pre><code>$ python -c 'import os; print os.getenv("PYTHONPATH")' None </code></pre>
19,070,674
2
0
null
2013-09-28 19:02:30.02 UTC
16
2021-10-18 21:28:09.55 UTC
null
null
null
null
1,420,489
null
1
61
python|bash|environment-variables|pythonpath
76,728
<p>Aha! the solution is simple!</p> <p>I was setting variables with plain <code>$ A=5</code> command; when you use <code>$ export B=&quot;foo&quot;</code> everything is fine.</p> <p>That is <a href="https://stackoverflow.com/questions/1158091/bash-defining-a-variable-with-or-without-export">beca</a><a href="https://www.gnu.org/software/bash/manual/html_node/Environment.html#Environment" rel="noreferrer">use</a> <code>export</code> makes the variable available to sub-processes:</p> <ul> <li>it creates a variable in the shell</li> <li>and <em>exports</em> it into the environment of the shell</li> <li>the environment is passed to sub-processes of the shell.</li> </ul> <p>Plain <code>$ A=&quot;foo&quot;</code> just creates variables in the shell and doesn't do anything with the environment.</p> <p>The interpreter called from the shell obtains its environment from the parent -- the shell. So really the variable should be exported into the environment before.</p>
25,621,496
How shouldChangeCharactersInRange works in Swift?
<p>I'm using <em>shouldChangeCharactersInRange</em> as a way of using on-the-fly type search.</p> <p>However I'm having a problem, <em>shouldChangeCharactersInRange</em> gets called before the text field actually updates:</p> <p>In Objective C, I solved this using using below:</p> <pre><code>-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string]; return YES; } </code></pre> <p>However, I've tried writing this in Swift:</p> <pre><code>func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -&gt; Bool { let txtAfterUpdate:NSString = self.projectSearchTxtFld.text as NSString txtAfterUpdate.stringByReplacingCharactersInRange(range, withString: string) self.callMyMethod(txtAfterUpdate) return true } </code></pre> <p>The method still gets called before I get a value?</p>
48,585,517
9
0
null
2014-09-02 10:43:36.27 UTC
18
2022-05-07 16:39:00.317 UTC
2014-11-06 12:50:00.39 UTC
null
239,219
null
2,794,594
null
1
89
ios|objective-c|swift|uitextfielddelegate|nsrange
89,002
<p><strong>Swift 4, Swift 5</strong></p> <p>This method doesn't use <code>NSString</code></p> <pre><code>// MARK: - UITextFieldDelegate extension MyViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -&gt; Bool { if let text = textField.text, let textRange = Range(range, in: text) { let updatedText = text.replacingCharacters(in: textRange, with: string) myvalidator(text: updatedText) } return true } } </code></pre> <p>Note. Be careful when you use a secured text field. </p>
25,742,913
java.net.BindException: Address already in use: JVM_Bind <null>:80
<p>I am getting binding exception while starting the Tomcat server. I tried to kill the process that which is using '80' as couple of processes are using it.</p> <p>Getting error, while killing process id is '0':</p> <blockquote> <p>ERROR: The process with PID 0 could not be terminated. Reason: This is critical system process. Taskkill cannot end this process.</p> </blockquote> <p>How to fix this?</p> <p>I don't need to use another port to run the tomcat server.</p>
25,743,238
13
0
null
2014-09-09 10:58:56.34 UTC
1
2019-08-14 13:59:30.597 UTC
2017-07-20 08:53:13.297 UTC
null
55,075
null
717,584
null
1
9
java|tomcat|exception-handling
130,512
<p>Setting Tomcat to listen to port 80 is <strong>WRONG</strong> , for development the 8080 is a good port to use. For production use, just set up an apache that shall forward your requests to your tomcat. <a href="http://www.ntu.edu.sg/home/ehchua/programming/howto/ApachePlusTomcat_HowTo.html" rel="noreferrer">Here</a> is a how to. </p>
48,700,350
LINQ OrderBy is not sorting correctly
<p>I hope someone can prove me wrong here :)</p> <p>If I do this:</p> <pre><code>List&lt;string&gt; a = new List&lt;string&gt; { "b", "c", "a", "aa" }; var b = a.OrderBy(o =&gt; o).ToList(); </code></pre> <p>I would expect the result of 'b' to be:</p> <pre><code>a aa b c </code></pre> <p>Instead, the result I get is:</p> <pre><code>a b c aa </code></pre> <p>How can I get OrderBy to do a "correct" alphabetical sort? Am I just plain wrong? :)</p>
48,700,441
2
2
null
2018-02-09 07:02:19.6 UTC
5
2018-02-09 16:19:38.13 UTC
null
null
null
null
766,069
null
1
51
c#|linq
4,190
<p>You’re in the Danish culture, which treats <code>aa</code> as <code>å</code> and puts it after <code>ø</code> accordingly. You can pass a string comparer that acts differently to <code>OrderBy</code> to change that:</p> <pre><code>var b = a.OrderBy(o =&gt; o, StringComparer.InvariantCulture).ToList(); </code></pre>
8,558,763
XElement => Add children nodes at run time
<p>So let's assume this is what i want to achieve:</p> <pre><code>&lt;root&gt; &lt;name&gt;AAAA&lt;/name&gt; &lt;last&gt;BBBB&lt;/last&gt; &lt;children&gt; &lt;child&gt; &lt;name&gt;XXX&lt;/name&gt; &lt;last&gt;TTT&lt;/last&gt; &lt;/child&gt; &lt;child&gt; &lt;name&gt;OOO&lt;/name&gt; &lt;last&gt;PPP&lt;/last&gt; &lt;/child&gt; &lt;/children&gt; &lt;/root&gt; </code></pre> <p><strong>Not sure if using XElement is the simplest way</strong><br> but this is what I have so far: </p> <pre><code> XElement x = new XElement("root", new XElement("name", "AAA"), new XElement("last", "BBB")); </code></pre> <p>Now I have to add the "children" based on some data i have.<br> There could be 1,2,3,4 ...</p> <p>so I need to iterate thru my list to get every single child</p> <pre><code>foreach (Children c in family) { x.Add(new XElement("child", new XElement("name", "XXX"), new XElement("last", "TTT")); } </code></pre> <h1><strong>PROBLEM:</strong></h1> <p>Doing this way I will be missing the "CHILDREN Parent node". If I just add it before the foreach, it will be rendered as a closed node</p> <pre><code>&lt;children/&gt; </code></pre> <p>and that's NOT what we want.</p> <h1><strong>QUESTION:</strong></h1> <p>How can I add to the 1st part a parent node and as many as my list has?</p>
8,558,800
3
0
null
2011-12-19 08:32:05.803 UTC
9
2012-12-11 17:11:31.017 UTC
2012-12-11 17:11:31.017 UTC
null
897,326
null
486,818
null
1
36
c#|xml|linq-to-xml|xelement
59,506
<p>Try this:</p> <pre><code>var x = new XElement("root", new XElement("name", "AAA"), new XElement("last", "BBB"), new XElement("children", from c in family select new XElement("child", new XElement("name", "XXX"), new XElement("last", "TTT") ) ) ); </code></pre>
47,804,813
How do you keep SourceTree/SSH from forgetting your SSH keys? (I have to manually re-run 'ssh-add' to get it to work again!)
<h2>UPDATE - It happened AGAIN!!!</h2> <p>Ok, so this just happened <em>AGAIN</em>! MAN is this frustrating!!! But this time I dug a little deeper and found that for some reason, my private keys were unloaded.</p> <p>Specifically, when I call this...</p> <pre><code>ssh-add -l -E md5 </code></pre> <p>I get this...</p> <pre><code>The agent has no identities. </code></pre> <p>However, if I then run this...</p> <pre><code>ssh-add /Users/[username]/.ssh/[private key] </code></pre> <p>Everything works again! SourceTree connects just as it's supposed to.</p> <p>The question is <strong><em>why do I have to keep running the 'ssh-add' command?! Why does it keep forgetting my keys?!</em></strong></p> <p>As mentioned elsewhere, not sure if this makes a difference, but I'm running a MacBook Pro with High Sierra, although this happens on Sierra too.</p> <h2>Original Post:</h2> <p>This one has me both stumped, and annoyed as heck!! SourceTree (or ssh or something!) keeps forgetting/not applying/ignoring my SSH keys every day! I don't know why.</p> <blockquote> <p><strong>Note: Updated to use BitBucket's info instead of GitHub.</strong></p> </blockquote> <p>Here's the relevant portion of my current <code>config</code> file</p> <pre><code># --- Sourcetree Generated --- Host MarqueIV-Bitbucket HostName bitbucket.org User MarqueIV PreferredAuthentications publickey IdentityFile /Users/MarqueIV/.ssh/MarqueIV-Bitbucket UseKeychain yes AddKeysToAgent yes # ---------------------------- </code></pre> <p>Here's a 'ls' of my ~/.ssh folder (truncated)</p> <pre><code>-rw-r--r--@ 1 MarqueIV staff 421 Dec 14 11:25 config -rw-r--r--@ 1 MarqueIV staff 1808 Dec 9 14:20 known_hosts -rw------- 1 MarqueIV staff 3243 Dec 6 23:33 MarqueIV-Bitbucket -rw-r--r-- 1 MarqueIV staff 781 Dec 6 23:33 MarqueIV-Bitbucket.pub </code></pre> <p>Here's my <code>known_hosts</code> file (keys redacted)</p> <pre><code>bitbucket.org,104.192.143.3 ssh-rsa [redacted] bitbucket.com,104.192.143.9 ssh-rsa [redacted] 104.192.143.2 ssh-rsa [redacted] </code></pre> <blockquote> <p>Note: Not sure if this matters, but you can see lines 1 and 2 seem to be duplicates.</p> </blockquote> <p>And here's the output of <code>ssh -Tv [email protected]</code></p> <pre><code>OpenSSH_7.6p1, LibreSSL 2.6.2 debug1: Reading configuration data /Users/MarqueIV/.ssh/config debug1: Reading configuration data /etc/ssh/ssh_config debug1: /etc/ssh/ssh_config line 48: Applying options for * debug1: Connecting to bitbucket.org port 22. debug1: Connection established. debug1: key_load_public: No such file or directory debug1: identity file /Users/MarqueIV/.ssh/id_rsa type -1 debug1: key_load_public: No such file or directory debug1: identity file /Users/MarqueIV/.ssh/id_rsa-cert type -1 debug1: key_load_public: No such file or directory debug1: identity file /Users/MarqueIV/.ssh/id_dsa type -1 debug1: key_load_public: No such file or directory debug1: identity file /Users/MarqueIV/.ssh/id_dsa-cert type -1 debug1: key_load_public: No such file or directory debug1: identity file /Users/MarqueIV/.ssh/id_ecdsa type -1 debug1: key_load_public: No such file or directory debug1: identity file /Users/MarqueIV/.ssh/id_ecdsa-cert type -1 debug1: key_load_public: No such file or directory debug1: identity file /Users/MarqueIV/.ssh/id_ed25519 type -1 debug1: key_load_public: No such file or directory debug1: identity file /Users/MarqueIV/.ssh/id_ed25519-cert type -1 debug1: Local version string SSH-2.0-OpenSSH_7.6 debug1: Remote protocol version 2.0, remote software version conker_1.0.315-a08d059 app-153 debug1: no match: conker_1.0.315-a08d059 app-153 debug1: Authenticating to bitbucket.org:22 as 'git' debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: algorithm: [email protected] debug1: kex: host key algorithm: ssh-rsa debug1: kex: server-&gt;client cipher: aes128-ctr MAC: [email protected] compression: none debug1: kex: client-&gt;server cipher: aes128-ctr MAC: [email protected] compression: none debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug1: Server host key: ssh-rsa SHA256:zzXQOXSRBEiUtuE8AikJYKwbHaxvSc0ojez9YXaGp1A debug1: Host 'bitbucket.org' is known and matches the RSA host key. debug1: Found key in /Users/MarqueIV/.ssh/known_hosts:1 debug1: rekey after 4294967296 blocks debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: rekey after 4294967296 blocks debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey debug1: Next authentication method: publickey debug1: Offering public key: RSA SHA256:h+6zCXg32Uw4fYxSUMwYst3zee8RFb9Z47H1QUTz58E /Users/MarqueIV/.ssh/MarqueIV-GitHub debug1: Authentications that can continue: publickey debug1: Trying private key: /Users/MarqueIV/.ssh/id_rsa debug1: Trying private key: /Users/MarqueIV/.ssh/id_dsa debug1: Trying private key: /Users/MarqueIV/.ssh/id_ecdsa debug1: Trying private key: /Users/MarqueIV/.ssh/id_ed25519 debug1: No more authentication methods to try. [email protected]: Permission denied (publickey). </code></pre> <p>See how it doesn't appear to be applying the key defined in <code>config</code> and <code>known_hosts</code>? Seems like that would be a problem, no?</p> <blockquote> <p>Note: I'm using macOS Sierra, and I have updated my path to include <code>/usr/bin</code> before <code>/usr/local/bin</code> as outlined <a href="https://apple.stackexchange.com/a/276023">here</a>. If I don't do that, I get an error saying ssh doesn't recognize <code>UseKeychain yes</code> in the config.</p> </blockquote> <p>As a result, almost daily here's the routine I have to go through. I'll use GitHub as my example.</p> <ol> <li><p>I open SourceTree and try to pull the latest from GitHub. It fails with a '[email protected]: Permission denied (publickey).' message.</p></li> <li><p>I remove my GitHub account from SourceTree.</p></li> <li><p>I delete both the public and private keys for GitHub from the .ssh folder on my machine.</p></li> <li><p>I go to GitHub and delete my old public key from my account.</p></li> <li><p>Back in SourceTree, I log into GitHub again using my username and password.</p></li> <li><p>Once logged in, using SourceTree, I generate a new SSH key-pair for GitHub.</p></li> <li><p>I copy my public key to the SSH area in my GitHub account. (Sometimes I notice it adds it for me, but I like to be safe and double-check.)</p></li> <li><p>Now I can push and pull again just fine.</p></li> </ol> <p>I go home for the day and log on at home. It fails again. Repeat all of the steps above.</p> <p>How do I get SourceTree/ssh/whatever to remember my da*n keys so I don't have to keep doing this every time I change locations?! What step am I missing???</p> <p>So can anyone offer suggestions on how to make my SSH keys 'stick'?</p>
48,668,358
3
2
null
2017-12-14 01:59:39.81 UTC
9
2022-05-08 18:33:29.52 UTC
2018-02-07 05:54:31.473 UTC
null
168,179
null
168,179
null
1
12
github|ssh|bitbucket|atlassian-sourcetree
6,550
<p>Ok, I think I have all the parts figured out.</p> <p>To help people get what they're after, here's the solution right up front:</p> <ol> <li>Make sure the keys you want to work with are secured with a password or else they will not add to Keychain.</li> <li>Make sure the keys you want to auto-load are configured in your <code>config</code> file and have the <code>UseKeychain</code> and <code>AddKeysToAgent</code> set</li> <li>Make sure to connect to those config-defined hosts <em><strong>from terminal!!</strong></em></li> <li>Create a LaunchAgent to run <code>ssh-add -A</code> to automatically reload your Keychain-stored keys</li> </ol> <p>Ok now that you know what to do, here's the 'why'.</p> <h2>The Meat</h2> <p>As explained in my question, lately, whenever I rebooted, I (incorrectly) thought the system was losing my private keys. It wasn't losing them, it was just ignoring them. This was because of a bunch of things that all came together in a perfect storm of confusion for someone like me who never uses the terminal for GIT.</p> <ol> <li>In the latest versions of macOS, Apple changed how it's implemented SSH so that It better matches the implementation of OpenSSH</li> <li>As a result of #1, <code>ssh-add -K [privateKey]</code> no longer stores the keys in the keychain (it essentially ignores the <code>-K</code>.) While they do get added to ssh for that session--and thus your connections will work again--as soon as you reboot, they will no longer work. (This is what's been driving me mad!)</li> <li>Even for keys that <em>are</em> in the Keychain, Apple no longer loads them automatically meaning you manually have to call <code>ssh-add -A</code> from the terminal to reload them every time you reboot.</li> <li>However, as stated above, <code>ssh-add -K [privateKey]</code> no longer adds the keys to keychain, so <code>ssh-add -A</code> is pointless anyway for keys added that way. (They can be added to Keychain another way. More on that in a minute.)</li> </ol> <p>Because of the above, any keys manually added with the <code>-K</code> option prior to upgrading your OS will still be in your Keychain. However, keys added after Apple's change are not.</p> <p>That said, Apple <em>does</em> still have the ability to store keys in the keychain, but not from <code>ssh-add</code> anymore. It now only works for hosts defined in your <code>config</code> file.</p> <p><em><strong>This is now the only way to get your keys in your Keychain.</strong></em></p> <p>Again, here's my config:</p> <pre><code>Host MarqueIV-Bitbucket HostName bitbucket.org User git &lt;-- Make sure this is 'git', not what SourceTree puts here PreferredAuthentications publickey IdentityFile /Users/MarqueIV/.ssh/MarqueIV-Bitbucket UseKeychain yes &lt;-- Note here AddKeysToAgent yes &lt;-- ...and here </code></pre> <p>But wait! If you look in my config file, it <em>does</em> have those values set! So why didn't it work?</p> <p>Two things.</p> <ol> <li>I don't use Terminal, ever. I use SourceTree which doesn't use the host entry in that file</li> <li>Apple technically only adds (and stores) the key on demand when that host is accessed, not when the file is (re)loaded meaning unless you explicitly access that host, nothing happens.</li> </ol> <p>In my case, adding the keys via SourceTree would add them for that initial session, but as soon as I rebooted, the keys would again not be loaded and thus all connections would fail. <code>ssh-add -A</code> wouldn't fix it either because again, they weren't in the keychain, meaning I was back to manually adding each one on the command line with <code>ssh-add [privateKey]</code>. What a pain!!</p> <p>Then it occurred to me... if that setting is in the config file, and that entry can be used from the command line, then shouldn't I be able to directly connect to that host, thus adding the keys to my keychain? Let's find out! I typed this...</p> <pre><code>ssh -T MarqueIV-BitBucket </code></pre> <p>And sure enough, not only was the key added to ssh, but it was also again added to my Keychain! I confirmed this by checking Keychain Access directly and it was there.</p> <p>To further test, I ran this...</p> <pre><code>ssh-add -D </code></pre> <p>which deleted all my keys. Sure enough, my SourceTree connections all failed again.</p> <p>Then I ran this...</p> <pre><code>ssh-add -A </code></pre> <p>and the keychain-stored keys magically came back and connections started working again! WOOT!!</p> <p>Ok, almost there, but not quite! What about reboots? Again, Apple no longer automatically loads keys from Keychain. Sure, it's just a quick jaunt now to terminal to type <code>ssh-add -A</code>, but again, I shouldn't have to do that!</p> <p><strong>Enter LaunchAgents!</strong></p> <p>LaunchAgents and LaunchDaemons are beyond the discussion of this post, but in short, they allow you to execute something on reboot, on a schedule, when changes happen to the system, etc.</p> <p>In my case, I wanted something that would run when I logged onto my mac, so a LaunchAgent was the best choice.</p> <p>Here's my plist defining how to execute <code>ssh-add -A</code> every time I logged into my account (even if I never touched Terminal):</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt; &lt;plist version=&quot;1.0&quot;&gt; &lt;dict&gt; &lt;key&gt;Label&lt;/key&gt; &lt;string&gt;ssh-add-a&lt;/string&gt; &lt;key&gt;ProgramArguments&lt;/key&gt; &lt;array&gt; &lt;string&gt;ssh-add&lt;/string&gt; &lt;string&gt;-A&lt;/string&gt; &lt;/array&gt; &lt;key&gt;RunAtLoad&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre> <p>Since I only want this for my particular user, I stored it here:</p> <pre><code>~/Library/LaunchAgents </code></pre> <blockquote> <p>Note: Make sure to change the permissions to allow it to be executed, or it won't start!</p> </blockquote> <p>Sure enough, on reboot, all my keys came back and were active! Connections all worked, children played, grown men cried, and it was a good day in the Code-dom!</p> <p>So to recap:</p> <ol> <li>Apple changed how their SSH worked</li> <li>Keys were no longer added to Keychain from the command line</li> <li>Apple also no longer auto-loaded keys that <em>were</em> stored in the keychain</li> <li>Using terminal to connect to config-defined hosts fixed #2</li> <li>Using a LaunchAgent fixed #3</li> </ol> <p>Hope this helps! Now time to go get some Icy-Hot for my sore shoulder that I've been patting myself on so hard for figuring this all out! ;)</p>
433,104
How do I get a book graphic and description from the Amazon Book API?
<p><a href="http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&amp;AWSAccessKeyId=13529AWJ97PJXSM2K1R2&amp;Operation=ItemLookup&amp;ItemId=1590599659" rel="noreferrer">This URL</a> sends an ISBN number to Amazon and gets back a small bit of XML including author, title, and publisher.</p> <p>However, I also want to get small, medium and large graphic and book descriptions of the title.</p> <p>Problem: I can find no REST URL examples/documention that work, either at Google or when logged into my "AWS Account" at Amazon Associates.</p> <p>I find a lot of examples from 2003-2005 but they are all out-of-date and give errors, it seems that Amazon's cloud web services have obfuscated their simple REST API documentation for their books.</p> <p>Can anyone point me to some documentation on how I can get detailed information about books at Amazon via REST/XML? </p> <p>Here's what I have tried so <a href="http://[http://tanguay.info/web/index.php?pg=forays&amp;id=3][2]" rel="noreferrer">far</a>.</p>
433,149
3
0
null
2009-01-11 15:51:29.933 UTC
14
2016-01-19 23:20:27.203 UTC
2016-01-07 20:31:32.73 UTC
null
247,372
Edward Tanguay
4,639
null
1
22
api|amazon
23,097
<p>So, allow me to answer my own question, from another question here I found this <a href="http://s3.amazonaws.com/awsdocs/ECS/20080819/QRC-AAWS-2008-08-19.pdf" rel="nofollow noreferrer">useful PDF</a> and the following <a href="http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&amp;Version=2005-03-23&amp;Operation=ItemLookup&amp;SubscriptionId=13529AWJ97PJXSM2K1R2&amp;AssociateTag=httpwwwcomput-20&amp;ItemId=B0002ZAILY&amp;IdType=ASIN&amp;ResponseGroup=Images" rel="nofollow noreferrer">URL</a> gets images for instance, see "ResponseGroup"</p>
836,608
Stress Testing ASP.Net application
<p>what are different ways that we can do some optimum level of stress testing for asp.net application before moving it to the production environment ?</p>
836,698
3
0
null
2009-05-07 19:40:28.837 UTC
43
2020-11-10 16:50:18.487 UTC
null
null
null
null
95,107
null
1
42
asp.net|stress-testing
34,600
<p>Here is the free tool for the stress testing in asp.net application.</p> <p><a href="https://docs.microsoft.com/en-us/archive/blogs/alikl/stress-test-asp-net-web-application-with-free-wcat-tool" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/archive/blogs/alikl/stress-test-asp-net-web-application-with-free-wcat-tool</a></p> <p>Another is called asp.net performance engineering which will tell how we can stress application.</p> <p><a href="https://docs.microsoft.com/en-us/archive/blogs/alikl/asp-net-performance-engineering-stress-test-your-architecture-design-and-code" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/archive/blogs/alikl/asp-net-performance-engineering-stress-test-your-architecture-design-and-code</a></p> <p>Also go through the following post:</p> <p><a href="https://stackoverflow.com/questions/340564/best-way-to-stress-test-a-website">Best way to stress test a website</a></p> <p>From my experience before moving to the production environment please take of following things.</p> <ol> <li><p>set debug=false into the web.config</p> </li> <li><p>set trace enabled=false into the web.config</p> </li> <li><p>Always use precompiled version of your code.</p> </li> <li><p>Compile your project into the release mode.</p> </li> <li><p>Publish your code if you are using asp.net 2.0 or higher version</p> </li> <li><p>User caching api as much as possible.</p> </li> <li><p>Decrease your html kb.</p> </li> <li><p>remove blank spaces from the asp.net html code.</p> </li> <li><p>Use stylesheet as external .css file</p> </li> <li><p>USE IIS Compression if poosible.</p> </li> <li><p>Put your javascript file in .js files</p> </li> <li><p>Use Server.Transfer instead of Response.redirect</p> </li> <li><p>Use Inproc Session State if possible.</p> </li> <li><p>Use Viewstate efficiently- Use controlstate instead of viewstate which is newer feature in asp.net 2.0</p> </li> <li><p>Avoid giving big name to controls it will increase your html kb.</p> </li> <li><p>Use Div instead of tables it will decrease your size.</p> </li> <li><p>Do IIS Performance tuning as per your requirement</p> </li> </ol> <p>Here is the good link that teaches us good way of deployment in production environment.</p> <p><a href="http://www.vbdotnetheaven.com/UploadFile/dsdaf/111222006014732AM/1.aspx" rel="nofollow noreferrer">http://www.vbdotnetheaven.com/UploadFile/dsdaf/111222006014732AM/1.aspx</a></p>
22,435,971
Request.Files.Count always 0 while uploading image in MVC 5
<p>I have a Post controller on a model with some string fields and an image. Exact identical code works on MVC4 but in MVC 5 the Request.Files.Count is always 0</p> <p>My model has byte[] for image rather than HttpPostedFileBase</p> <p>My View:</p> <pre><code>@using (Html.BeginForm("Create", "HotelManager", FormMethod.Post, new { enctype = "multipart/form-data", data_ajax = "false" })) { @Html.AntiForgeryToken() @Html.TextBoxFor(model =&gt; model.Title, new { @class = "form-control" }) @Html.TextAreaFor(model =&gt; model.Description, new { @class = "form-control", @rows = "7" }) &lt;input type="file" class="form-control filestyle"&gt; &lt;input type="submit" value="Submit" class="btn btn-block" /&gt; } </code></pre> <p>I have tried omitting data_ajax = "false" but no use.</p> <p>My Post Controller is as follows:</p> <pre><code> [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Title,Description,Image")] Hotel hotel) { if (ModelState.IsValid) { // deal with the uploaded file if (Request.Files.Count &gt; 0) { HttpPostedFileBase file = Request.Files[0]; if (file != null &amp;&amp; file.ContentLength &gt; 0) { // Code to process image, resize, etc goes here } } // Other code to add the hotel to db goes here } </code></pre> <p>In the debugger I see that the Request.Files.Count is always zero, I don't know why? I have copied over both the view and controller code from another MVC4 project where it works fine.</p> <pre><code>Key Value Request POST /HotelManager/Create HTTP/1.1 Accept text/html, application/xhtml+xml, */* Referer http://localhost:4976/HotelManager/Create Accept-Language en-US,en;q=0.5 User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; ASU2JS; rv:11.0) like Gecko Content-Type multipart/form-data; boundary=---------------------------7de207070a24 Accept-Encoding gzip, deflate Host localhost:4976 Content-Length 946 DNT 1 </code></pre> <p>And in the IE Developer window I see that the form body is empty.</p>
22,441,798
5
0
null
2014-03-16 10:59:50.207 UTC
3
2020-09-16 18:33:07.06 UTC
null
null
null
null
2,475,810
null
1
25
asp.net-mvc|http-headers|asp.net-mvc-5|asp.net-mvc-5.1|enctype
38,851
<p>I wasted so much time and it turns out that all I needed to do was to use the name attribute as well </p> <pre><code> &lt;input type="file" name="somename"&gt; </code></pre> <p>the name attribute was missing in my new project.</p>
41,992,569
Template format error: unsupported structure seen in AWS CloudFormation
<p>I am trying to validate an AWS example CloudFormation template using a command like:</p> <pre><code>▶ aws cloudformation validate-template --template-body template.yml </code></pre> <p>This leads to the following error message:</p> <pre><code>An error occurred (ValidationError) when calling the ValidateTemplate operation: Template format error: unsupported structure. </code></pre> <p>I tried this on many templates, including example templates from the AWS documentation. So I know the templates are okay.</p> <p>What am I doing wrong?</p>
41,992,779
2
2
null
2017-02-02 00:54:08.983 UTC
9
2021-10-01 07:12:42.96 UTC
2019-03-22 10:35:03.98 UTC
null
3,787,051
null
2,416,097
null
1
79
amazon-web-services|amazon-cloudformation
25,726
<p>Apparently, the very unhelpful error message comes as a result of improper formatting in the CLI command.</p> <p>The <code>--template-body</code> argument must be specified as a <a href="https://en.wikipedia.org/wiki/File_URI_scheme" rel="noreferrer">file URI</a>.</p> <p>Thus, the correct, runnable form of the command above is:</p> <pre><code>▶ aws cloudformation validate-template --template-body file://template.yml </code></pre> <p>See <a href="https://randops.org/2016/11/11/confusing-syntax-error-with-aws-cli-and-cf-templates/" rel="noreferrer">this</a> blog post for more information.</p>
20,605,888
The module has not been deployed [netbeans+glassfish]
<p>i am developping a project base on J2EE EJB JSF, database is MYsql, the project works very well last week. but today, it can't be deployed when i run it. here are some exception:</p> <pre><code> Initial deploying ECOM to C:\Users\John624\Documents\NetBeansProjects\PromoCoupon\ECOM\dist\gfdeploy\ECOM Completed initial distribution of ECOM Initializing... invalid header field name: Exception Description C:\Users\John624\Documents\NetBeansProjects\PromoCoupon\ECOM\nbproject\build-impl.xml:307: The module has not been deployed. See the server log for details. BUILD FAILED (total time: 5 seconds) </code></pre> <p><strong>Glassfish:</strong></p> <pre><code> &lt;code&gt; SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method SEVERE: Exception while invoking class org.glassfish.javaee.full.deployment.EarDeployer prepare method SEVERE: org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed. Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException Exception Description: Error encountered when building the @NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata]. Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:180) at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:431) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:356) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534) at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224) at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544) at java.lang.Thread.run(Thread.java:724) Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed. Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException Exception Description: Error encountered when building the @NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata]. Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFailedPersistenceException(EntityManagerSetupImpl.java:1950) at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1941) at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:322) at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:199) at org.glassfish.persistence.jpa.PersistenceUnitLoader.&lt;init&gt;(PersistenceUnitLoader.java:107) at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223) at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510) at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230) at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168) at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922) at org.glassfish.javaee.full.deployment.EarDeployer.prepareBundle(EarDeployer.java:307) at org.glassfish.javaee.full.deployment.EarDeployer.access$200(EarDeployer.java:88) at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:153) at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:150) at org.glassfish.javaee.full.deployment.EarDeployer.doOnBundles(EarDeployer.java:230) at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllTypedBundles(EarDeployer.java:239) at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllBundles(EarDeployer.java:265) at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:150) ... 35 more Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed. Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException Exception Description: Error encountered when building the @NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata]. Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable at org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:230) ... 53 more Caused by: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException Exception Description: Error encountered when building the @NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata]. Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable at org.eclipse.persistence.exceptions.ValidationException.errorProcessingNamedQuery(ValidationException.java:824) at org. SEVERE: Exception while preparing the app SEVERE: eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.process(NamedQueryMetadata.java:194) at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processQueries(MetadataProject.java:1628) at org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor.addNamedQueries(MetadataProcessor.java:148) at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1894) ... 51 more Caused by: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:626) at org.eclipse.persistence.jpa.jpql.parser.RangeVariableDeclaration.accept(RangeVariableDeclaration.java:98) at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:577) at org.eclipse.persistence.jpa.jpql.parser.IdentificationVariableDeclaration.accept(IdentificationVariableDeclaration.java:71) at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:566) at org.eclipse.persistence.jpa.jpql.parser.FromClause.accept(FromClause.java:48) at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver.populateImp(DeclarationResolver.java:417) at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver.populate(DeclarationResolver.java:407) at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper$DescriptorCollector.collectDescriptors(JPQLQueryHelper.java:179) at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper$DescriptorCollector.visit(JPQLQueryHelper.java:204) at org.eclipse.persistence.jpa.jpql.parser.FromClause.accept(FromClause.java:48) at org.eclipse.persistence.jpa.jpql.parser.AbstractSelectStatement.acceptChildren(AbstractSelectStatement.java:93) at org.eclipse.persistence.jpa.jpql.parser.SelectStatement.acceptChildren(SelectStatement.java:110) at org.eclipse.persistence.jpa.jpql.parser.AbstractTraverseChildrenVisitor.visit(AbstractTraverseChildrenVisitor.java:32) at org.eclipse.persistence.jpa.jpql.parser.AnonymousExpressionVisitor.visit(AnonymousExpressionVisitor.java:470) at org.eclipse.persistence.jpa.jpql.parser.SelectStatement.accept(SelectStatement.java:102) at org.eclipse.persistence.jpa.jpql.parser.JPQLExpression.acceptChildren(JPQLExpression.java:143) at org.eclipse.persistence.jpa.jpql.parser.AbstractTraverseChildrenVisitor.visit(AbstractTraverseChildrenVisitor.java:32) at org.eclipse.persistence.jpa.jpql.parser.AnonymousExpressionVisitor.visit(AnonymousExpressionVisitor.java:302) at org.eclipse.persistence.jpa.jpql.parser.JPQLExpression.accept(JPQLExpression.java:136) at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper.getClassDescriptors(JPQLQueryHelper.java:87) at org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.addJPAQuery(NamedQueryMetadata.java:105) at org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.process(NamedQueryMetadata.java:192) ... 54 more &lt;code&gt; </code></pre> <p><strong>entity bean</strong></p> <pre><code>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package entities; import java.io.Serializable; import java.util.Collection; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author John624 */ @Entity @Table(name = "Adresse") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Adresse.maxId", query = "SELECT max(idAdresse) FROM Adresse"), @NamedQuery(name = "Adresse.findAll", query = "SELECT a FROM Adresse a"), @NamedQuery(name = "Adresse.findByIdAdresse", query = "SELECT a FROM Adresse a WHERE a.idAdresse = :idAdresse"), @NamedQuery(name = "Adresse.findByNumEtRue", query = "SELECT a FROM Adresse a WHERE a.numEtRue = :numEtRue"), @NamedQuery(name = "Adresse.findByComple", query = "SELECT a FROM Adresse a WHERE a.comple = :comple"), @NamedQuery(name = "Adresse.findByCodePostale", query = "SELECT a FROM Adresse a WHERE a.codePostale = :codePostale"), @NamedQuery(name = "Adresse.findByVille", query = "SELECT a FROM Adresse a WHERE a.ville = :ville"), @NamedQuery(name = "Adresse.findByPays", query = "SELECT a FROM Adresse a WHERE a.pays = :pays"), @NamedQuery(name = "Adresse.findByDateModif", query = "SELECT a FROM Adresse a WHERE a.dateModif = :dateModif")}) public class Adresse implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "idAdresse") private Long idAdresse; @Size(max = 100) @Column(name = "numEtRue") private String numEtRue; @Size(max = 100) @Column(name = "comple") private String comple; @Size(max = 5) @Column(name = "codePostale") private String codePostale; @Size(max = 35) @Column(name = "ville") private String ville; @Size(max = 35) @Column(name = "pays") private String pays; @Column(name = "dateModif") @Temporal(TemporalType.DATE) private Date dateModif; @OneToMany(mappedBy = "adrU") private Collection&lt;Utilisateur&gt; utilisateurCollection; @OneToMany(mappedBy = "adrRecep") private Collection&lt;Livraison&gt; livraisonCollection; @OneToMany(mappedBy = "adrE") private Collection&lt;Entreprise&gt; entrepriseCollection; public Adresse() { } public Adresse(Long idAdresse) { this.idAdresse = idAdresse; } public Long getIdAdresse() { return idAdresse; } public void setIdAdresse(Long idAdresse) { this.idAdresse = idAdresse; } public String getNumEtRue() { return numEtRue; } public void setNumEtRue(String numEtRue) { this.numEtRue = numEtRue; } public String getComple() { return comple; } public void setComple(String comple) { this.comple = comple; } public String getCodePostale() { return codePostale; } public void setCodePostale(String codePostale) { this.codePostale = codePostale; } public String getVille() { return ville; } public void setVille(String ville) { this.ville = ville; } public String getPays() { return pays; } public void setPays(String pays) { this.pays = pays; } public Date getDateModif() { return dateModif; } public void setDateModif(Date dateModif) { this.dateModif = dateModif; } @XmlTransient public Collection&lt;Utilisateur&gt; getUtilisateurCollection() { return utilisateurCollection; } public void setUtilisateurCollection(Collection&lt;Utilisateur&gt; utilisateurCollection) { this.utilisateurCollection = utilisateurCollection; } @XmlTransient public Collection&lt;Livraison&gt; getLivraisonCollection() { return livraisonCollection; } public void setLivraisonCollection(Collection&lt;Livraison&gt; livraisonCollection) { this.livraisonCollection = livraisonCollection; } @XmlTransient public Collection&lt;Entreprise&gt; getEntrepriseCollection() { return entrepriseCollection; } public void setEntrepriseCollection(Collection&lt;Entreprise&gt; entrepriseCollection) { this.entrepriseCollection = entrepriseCollection; } @Override public int hashCode() { int hash = 0; hash += (idAdresse != null ? idAdresse.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Adresse)) { return false; } Adresse other = (Adresse) object; if ((this.idAdresse == null &amp;&amp; other.idAdresse != null) || (this.idAdresse != null &amp;&amp; !this.idAdresse.equals(other.idAdresse))) { return false; } return true; } @Override public String toString() { return "entities.Adresse[ idAdresse=" + idAdresse + " ]"; } } </code></pre> <p><strong>session bean</strong></p> <p>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package session;</p> <pre><code>import entities.Adresse; import java.util.List; import javax.ejb.Stateless; import javax.ejb.LocalBean; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author John624 */ @Stateless @LocalBean public class AdresseManager { @PersistenceContext(unitName = "ECOM-ejbPU") private EntityManager em; public List&lt;Adresse&gt; getAllAdresses() { Query query=em.createNamedQuery("Adresse.findAll"); return query.getResultList(); } public Adresse update(Adresse adresse) { return em.merge(adresse); } public void persist(Object object) { em.persist(object); } public Long nextId(){ Query query = em.createNamedQuery("Adresse.maxId"); long res; res = query.getResultList().indexOf(0)+1; return res; } } </code></pre> <p><strong>JSF managedbean</strong></p> <pre><code>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package managedbeans; import entities.Adresse; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import session.AdresseManager; /** * * @author John624 */ @Named(value="adresseMBean") @SessionScoped public class AdresseMBean implements Serializable{ private List&lt;Adresse&gt; adresses; private Adresse adresse; @EJB private AdresseManager adresseManager; public AdresseMBean() { adresse=new Adresse(); adresseManager = new AdresseManager(); } /** * returns customer list for display in a datatable DataTable * @return */ public List&lt;Adresse&gt; getAdresses() { if((adresses == null) || (adresses.isEmpty())) adresses = adresseManager.getAllAdresses(); return adresseManager.getAllAdresses(); } // public void refresh() { // tousLesComptes = compteBancaireFacade.findAll(); // } /** * returns details of a customer. Useful for displaying in a form a customer's details * @return */ public Adresse getDetails() { return adresse; } /** * Action handler - Called when a line in the table is clicked * @param adresse * @return */ public String showDetails(Adresse adresse) { this.adresse = adresse; return "AdresseDetails"; // will display CustomerDetails.xml JSF page } /** * Action handler - update the customer model in the database. * called when one press the update button in the form * @return */ public String update() { System.out.println("###UPDATE###"); adresse = adresseManager.update(adresse); return "AdresseList"; // will display the customer list in a table } /** * Action handler - returns to the list of customers in the table */ public String list() { System.out.println("###LIST###"); return "AdresseList"; } public void update(Adresse adrU) { System.out.println("###UPDATE###"); adresseManager.update(adrU); } } </code></pre> <p>Thanks in advance.</p>
20,623,161
3
0
null
2013-12-16 07:55:44.207 UTC
2
2013-12-16 23:35:48.06 UTC
null
null
null
null
2,084,921
null
1
9
java|jsf|jakarta-ee|jsf-2
51,102
<p>As indicated by the following exception stacktrace</p> <pre><code>Exception Description: Error encountered when building the @NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata]. </code></pre> <p>the problem is here :</p> <pre><code>@NamedQuery(name = "Adresse.maxId", query = "SELECT max(idAdresse) FROM Adresse"), </code></pre> <p>To solve the problem, try this instead:</p> <pre><code>@NamedQuery(name = "Adresse.maxId", query = "SELECT max(a.idAdresse) FROM Adresse a"), </code></pre>
20,594,936
Communication between Activity and Service
<p>I am trying to make my own MusicPlayer for android. Where i came to a problem is running some things in background. Main activity manages GUI and up to now all the songs are playing. I wanted to separate GUI and music playing classes. I want to put music managing part in Service and leave other things as they are now. </p> <p>My problem is that i can't organize communication between Activity and Service as lot of communication is happening between them including moving objects in both directions. I tried many techniques that I searched here on Stack Overflow but every time I had problems. I need Service to be able to send objects to Activity and vice versa. When I add widget i also want it to be able to communicate with Service.</p> <p>Any tips are appreciated, if you need source code place comment bellow but now in this transition it became chaotic.</p> <p>Is there any more advanced tutorial on this than calling one method that returns random number from service? :P </p> <p>EDIT: Possible solution is to use RoboGuice library and move objects with injection</p>
29,101,448
8
0
null
2013-12-15 13:14:43.143 UTC
40
2018-05-02 11:29:03.373 UTC
2016-01-22 14:20:27.753 UTC
null
1,338,333
null
1,338,333
null
1
64
android|android-activity|android-service|message-passing
103,584
<p>I have implemented communication between Activity and Service using Bind and Callbacks interface. </p> <p>For sending data to the service I used Binder which retruns the Service instace to the Activity, and then the Activity can access public methods in the Service. </p> <p>To send data back to the Activity from the Service, I used Callbacks interface like you are using when you want to communicate between Fragment and Activity. </p> <p>Here is some code samples for each: The following example shows Activity and Service bidirectional relationship: The Activity has 2 buttons: The first button will start and stop the service. The second button will start a timer which runs in the service. </p> <p>The service will update the Activity through callback with the timer progress. </p> <p>My Activity:</p> <pre><code> //Activity implements the Callbacks interface which defined in the Service public class MainActivity extends ActionBarActivity implements MyService.Callbacks{ ToggleButton toggleButton; ToggleButton tbStartTask; TextView tvServiceState; TextView tvServiceOutput; Intent serviceIntent; MyService myService; int seconds; int minutes; int hours; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); serviceIntent = new Intent(MainActivity.this, MyService.class); setViewsWidgets(); } private void setViewsWidgets() { toggleButton = (ToggleButton)findViewById(R.id.toggleButton); toggleButton.setOnClickListener(btListener); tbStartTask = (ToggleButton)findViewById(R.id.tbStartServiceTask); tbStartTask.setOnClickListener(btListener); tvServiceState = (TextView)findViewById(R.id.tvServiceState); tvServiceOutput = (TextView)findViewById(R.id.tvServiceOutput); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { Toast.makeText(MainActivity.this, "onServiceConnected called", Toast.LENGTH_SHORT).show(); // We've binded to LocalService, cast the IBinder and get LocalService instance MyService.LocalBinder binder = (MyService.LocalBinder) service; myService = binder.getServiceInstance(); //Get instance of your service! myService.registerClient(MainActivity.this); //Activity register in the service as client for callabcks! tvServiceState.setText("Connected to service..."); tbStartTask.setEnabled(true); } @Override public void onServiceDisconnected(ComponentName arg0) { Toast.makeText(MainActivity.this, "onServiceDisconnected called", Toast.LENGTH_SHORT).show(); tvServiceState.setText("Service disconnected"); tbStartTask.setEnabled(false); } }; View.OnClickListener btListener = new View.OnClickListener() { @Override public void onClick(View v) { if(v == toggleButton){ if(toggleButton.isChecked()){ startService(serviceIntent); //Starting the service bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE); //Binding to the service! Toast.makeText(MainActivity.this, "Button checked", Toast.LENGTH_SHORT).show(); }else{ unbindService(mConnection); stopService(serviceIntent); Toast.makeText(MainActivity.this, "Button unchecked", Toast.LENGTH_SHORT).show(); tvServiceState.setText("Service disconnected"); tbStartTask.setEnabled(false); } } if(v == tbStartTask){ if(tbStartTask.isChecked()){ myService.startCounter(); }else{ myService.stopCounter(); } } } }; @Override public void updateClient(long millis) { seconds = (int) (millis / 1000) % 60 ; minutes = (int) ((millis / (1000*60)) % 60); hours = (int) ((millis / (1000*60*60)) % 24); tvServiceOutput.setText((hours&gt;0 ? String.format("%d:", hours) : "") + ((this.minutes&lt;10 &amp;&amp; this.hours &gt; 0)? "0" + String.format("%d:", minutes) : String.format("%d:", minutes)) + (this.seconds&lt;10 ? "0" + this.seconds: this.seconds)); } } </code></pre> <p>And here is the service:</p> <pre><code> public class MyService extends Service { NotificationManager notificationManager; NotificationCompat.Builder mBuilder; Callbacks activity; private long startTime = 0; private long millis = 0; private final IBinder mBinder = new LocalBinder(); Handler handler = new Handler(); Runnable serviceRunnable = new Runnable() { @Override public void run() { millis = System.currentTimeMillis() - startTime; activity.updateClient(millis); //Update Activity (client) by the implementd callback handler.postDelayed(this, 1000); } }; @Override public int onStartCommand(Intent intent, int flags, int startId) { //Do what you need in onStartCommand when service has been started return START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { return mBinder; } //returns the instance of the service public class LocalBinder extends Binder{ public MyService getServiceInstance(){ return MyService.this; } } //Here Activity register to the service as Callbacks client public void registerClient(Activity activity){ this.activity = (Callbacks)activity; } public void startCounter(){ startTime = System.currentTimeMillis(); handler.postDelayed(serviceRunnable, 0); Toast.makeText(getApplicationContext(), "Counter started", Toast.LENGTH_SHORT).show(); } public void stopCounter(){ handler.removeCallbacks(serviceRunnable); } //callbacks interface for communication with service clients! public interface Callbacks{ public void updateClient(long data); } } </code></pre>
19,868,138
What is the difference between system apps and privileged apps on Android?
<p>So in 4.3 there was a concept of System applications. APKs that were placed in <code>/system/app</code> were given system privileges. As of 4.4, there is a new concept of &quot;privileged app&quot;. Privileged apps are stored in <code>/system/priv-app</code> directory and seem to be treated differently. If you look in the AOSP Source code, under <code>PackageManagerService</code>, you will see new methods such as</p> <pre><code>static boolean locationIsPrivileged(File path) { try { final String privilegedAppDir = new File(Environment.getRootDirectory(), &quot;priv-app&quot;) .getCanonicalPath(); return path.getCanonicalPath().startsWith(privilegedAppDir); } catch (IOException e) { Slog.e(TAG, &quot;Unable to access code path &quot; + path); } return false; } </code></pre> <p>So here is an example of a situation where these differ.</p> <pre><code>public final void addActivity(PackageParser.Activity a, String type) { ... if (!systemApp &amp;&amp; intent.getPriority() &gt; 0 &amp;&amp; &quot;activity&quot;.equals(type)) { intent.setPriority(0); Log.w(TAG, &quot;Package &quot; + a.info.applicationInfo.packageName + &quot; has activity &quot; + a.className + &quot; with priority &gt; 0, forcing to 0&quot;); } ... </code></pre> <p>This affects the priority of any activities that are not defined as system applications. This seems to imply you can not add an activity to the package manager whose priority is higher than 0, unless you are a system app. This does <strong>not</strong> preclude privileged apps as far as I can tell (there is a lot of logic here, I may be wrong.).</p> <p>My question is what exactly does this imply? If my app is privileged, but not system, what difference will that make? In <code>PackageManagerService</code> you can find various things that differ between system and privileged apps, they are not exactly the same. There should be some kind of ideology behind privileged apps, otherwise they would have just said:</p> <pre><code>if locationIsPrivileged: app.flags |= FLAG_SYSTEM </code></pre> <p>and been done with it. This is a new concept, and I think it would be important to know the difference between these kinds of apps for anyone who is doing AOSP development as of 4.4.</p>
20,104,400
1
0
null
2013-11-08 20:41:09.66 UTC
46
2020-08-01 23:53:53.76 UTC
2020-08-01 23:53:53.76 UTC
null
712,558
null
1,306,452
null
1
76
android|android-source
83,125
<p>So after some digging, it's clear that apps in priv-app are eligible for system permissions, the same way that old apps used to be eligible to claim system permissions by being in system-app. The only official Google documentation I could find on this came in the form of a commit message: Commit hash: ccbf84f44c9e6a5ed3c08673614826bb237afc54</p> <blockquote> <p>Some system apps are more system than others</p> <p>"signatureOrSystem" permissions are no longer available to all apps residing en the /system partition. Instead, there is a new /system/priv-app directory, and only apps whose APKs are in that directory are allowed to use signatureOrSystem permissions without sharing the platform cert. This will reduce the surface area for possible exploits of system- bundled applications to try to gain access to permission-guarded operations.</p> <p>The ApplicationInfo.FLAG_SYSTEM flag continues to mean what it is says in the documentation: it indicates that the application apk was bundled on the /system partition. A new hidden flag FLAG_PRIVILEGED has been introduced that reflects the actual right to access these permissions.</p> </blockquote> <p>Update: As of Android 8.0 priv-app has changed slightly with the addition of Privileged Permission Whitelisting. Beyond just being in priv-app, your app must also be added to a whitelist in order to gain various system permissions. Information on this can be found here: <a href="https://source.android.com/devices/tech/config/perms-whitelist" rel="noreferrer">https://source.android.com/devices/tech/config/perms-whitelist</a></p>
6,168,020
What is wikipedia pageid? how to change it into real page url?
<p>I'm studying the wikipedia API, </p> <p><a href="http://en.wikipedia.org/w/api.php?action=query&amp;generator=search&amp;gsrsearch=meaning&amp;srprop=size%7Cwordcount%7Ctimestamp%7Csnippet" rel="noreferrer">some demo api call</a></p> <p>What is the pageid? How do I change it into a real page url?</p> <p>I mean <code>&lt;page pageid="18630637" ns="0" title="Translation" /&gt;</code>, how to change <code>18630637</code> into <code>http://en.wikipedia.org/wiki/Translation</code>? </p>
6,169,156
3
0
null
2011-05-29 13:36:54.293 UTC
32
2019-02-05 09:41:03.317 UTC
2013-09-30 02:31:11.447 UTC
null
734,289
null
499,587
null
1
88
wikipedia|wikipedia-api
61,807
<p>The <code>pageid</code> is the MediaWiki's internal article ID. You can use the action API's <a href="https://www.mediawiki.org/wiki/API:Info" rel="noreferrer"><code>info</code></a> property to get the full URL from <code>pageid</code>:</p> <p><a href="https://en.wikipedia.org/w/api.php?action=query&amp;prop=info&amp;pageids=18630637&amp;inprop=url" rel="noreferrer"><code>https://en.wikipedia.org/w/api.php?action=query&amp;prop=info&amp;pageids=18630637&amp;inprop=url</code></a></p>
6,215,095
NSURLConnection download large file (>40MB)
<p>I need to download large file (i.e. > 40MB) to my application from server, this file will be ZIP or PDF. I achieved it using <strong>NSURLConnection</strong>, that works well if the file is smaller other wise it download a part of the fill and the execution has stopped. for example I tried to download 36MB PDF file, but but 16MB only downloaded. pls help me to know the reason? how to fix it? </p> <p>FYI: Implementation File</p> <pre><code>#import "ZipHandlerV1ViewController.h" @implementation ZipHandlerV1ViewController - (void)dealloc { [super dealloc]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (void)viewDidLoad { UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 400)]; [mainView setBackgroundColor:[UIColor darkGrayColor]]; UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [downloadButton setFrame:CGRectMake(50, 50, 150, 50)]; [downloadButton setTitle:@"Download File" forState:UIControlStateNormal]; [downloadButton addTarget:self action:@selector(downloadFileFromURL:) forControlEvents:UIControlEventTouchUpInside]; [mainView addSubview:downloadButton]; [self setRequestURL:@"http://www.mobileveda.com/r_d/mcps/optimized_av_allpdf.pdf"]; [self.view addSubview:mainView]; [super viewDidLoad]; } - (void)viewDidUnload { [super viewDidUnload]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } -(void) setRequestURL:(NSString*) requestURL { url = requestURL; } -(void) downloadFileFromURL:(id) sender { NSURL *reqURL = [NSURL URLWithString:url]; NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:reqURL]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection) { webData = [[NSMutableData data] retain]; } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; [alert release]; } } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [webData setLength:0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [webData appendData:data]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *fileName = [[[NSURL URLWithString:url] path] lastPathComponent]; NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *folder = [pathArr objectAtIndex:0]; NSString *filePath = [folder stringByAppendingPathComponent:fileName]; NSURL *fileURL = [NSURL fileURLWithPath:filePath]; NSError *writeError = nil; [webData writeToURL: fileURL options:0 error:&amp;writeError]; if( writeError) { NSLog(@" Error in writing file %@' : \n %@ ", filePath , writeError ); return; } NSLog(@"%@",fileURL); } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection.." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; [alert release]; } @end </code></pre> <p>Header File:</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface ZipHandlerV1ViewController : UIViewController { NSMutableData *webData; NSString *url; } -(void) setRequestURL:(NSString*) requestURL; @end </code></pre> <p>Thank you,</p> <p><strong>Updated:</strong> <em>This happens because of my downloadable file was in shared hosting which having the download limitations. After I moved that file to dedicated server that working fine. and also I tried to download some other files like videos from some other sites, that also working fine. So, if you having problem like partial download, don't only stick with the code, check the server too</em></p>
6,304,041
4
0
null
2011-06-02 13:22:18.77 UTC
10
2013-04-17 19:29:47.7 UTC
2012-06-05 09:28:34.083 UTC
null
781,181
null
781,181
null
1
17
iphone|ios|file|download
19,134
<p>This happens because of my downloadable file was in shared hosting which having the download limitations. After I moved that file to dedicated server that working fine. and also I tried to download some other files like videos from some other sites, that also working fine.</p> <p>So, if you having problem like partial download, don't only stick with the code, check the server too.</p>
52,847,979
What is <router-view :key="$route.fullPath">?
<p>I'm completely new to Vue.js and I think I have a bit of understanding of how a router works with things like:</p> <pre><code>&lt;router-link to=&quot;/&quot;&gt; </code></pre> <p>But I am not really understanding what the following line does:</p> <pre><code>&lt;router-view :key=&quot;$route.fullPath&quot;&gt;&lt;/router-view&gt; </code></pre> <p>I believe <code>router-view</code> by itself makes sure the content is displayed but what does the key part mean?</p>
52,848,095
2
1
null
2018-10-17 05:45:20.323 UTC
7
2022-07-15 19:46:38.3 UTC
2022-04-17 14:42:01.823 UTC
null
6,904,888
null
7,924,493
null
1
34
javascript|html|vue.js|vue-router
23,294
<p>See <a href="https://v2.vuejs.org/v2/api/#key" rel="nofollow noreferrer">Special Attributes - key</a></p> <blockquote> <p>It can also be used to force replacement of an element/component instead of reusing it. This can be useful when you want to:</p> </blockquote> <blockquote> <ul> <li>Properly trigger lifecycle hooks of a component</li> </ul> </blockquote> <ul> <li>Trigger transitions</li> </ul> <p><a href="https://router.vuejs.org/api/#route-object-properties" rel="nofollow noreferrer"><code>$route.fullPath</code></a> is defined as</p> <blockquote> <p>The full resolved URL including query and hash.</p> </blockquote> <p>If you bind <code>key</code> to <code>$route.fullPath</code>, it will always <em>&quot;force a replacement&quot;</em> of the <code>&lt;router-view&gt;</code> element / component every time a navigation event occurs.</p> <p>As mentioned above, this is most probably done in order to trigger a transition / animation.</p>
29,626,410
Krajee Bootstrap File Input, catching AJAX success response
<p>I'm using Krajee the Bootstrap File Input plugin to perform an upload via AJAX call.</p> <p>Here is the link to the Krajee plugin AJAX section: <a href="http://plugins.krajee.com/file-input/demo#ajax-uploads" rel="nofollow noreferrer">Krajee plugin AJAX</a></p> <p>The JS and PHP (codeigniter) codes I'm using are as following:</p> <p>JS:</p> <pre><code>&lt;script&gt; $("#file-upload").fileinput({ 'allowedFileExtensions' : ['csv'], 'maxFileSize': 5120, 'maxFileCount': 1, 'uploadUrl': 'dashboard/uploader', 'elErrorContainer': '#errorBlock', 'uploadAsync': true, 'msgInvalidFileExtension': 'Invalid extension for file "{name}". Only "{extensions}" files are supported.', 'uploadExtraData': {csrf_token_name: $("input[name=csrf_token_name]").val()} }); &lt;/script&gt; </code></pre> <p>PHP:</p> <pre><code>public function uploader(){ $config['upload_path'] = './csv_uploads/'; $config['allowed_types'] = 'csv'; $config['max_size'] = '5120'; $this-&gt;upload-&gt;initialize($config); if (!$this-&gt;upload-&gt;do_upload("file-upload")){ $data['error'] = 'The following error occured : '.$this-&gt;upload-&gt;display_errors().'Click on "Remove" and try again!'; echo json_encode($data); } else { echo json_encode("success"); } } </code></pre> <p>Right now I get a response from PHP whatever it is an error or a success as JSON, I have went through the plugin documentation and I still can't find how to catch the AJAX response and act according to that response as we do in jQuery with the ajax success function : </p> <pre><code>success: function (response) { //Deal with the server side "response" data. }, </code></pre> <p>How can I do this?</p>
29,693,125
5
0
null
2015-04-14 11:43:05.393 UTC
4
2020-05-20 10:46:43.59 UTC
2018-04-28 08:35:24.913 UTC
null
2,691,058
null
1,124,711
null
1
11
javascript|php|jquery|ajax|twitter-bootstrap
42,196
<p>You can check out a demo here <a href="http://plugins.krajee.com/file-input-ajax-demo/11" rel="nofollow noreferrer">live demo</a> </p> <p>Remember to set <strong>uploadAsync false</strong> if you want the success event fire</p> <p>Example code:</p> <p>JS</p> <pre><code>$("#input-id").fileinput({ showRemove:false, showPreview: false, uploadUrl: "../xxxx/xxxx/XXXXXX.php", // server upload action uploadAsync: false, uploadExtraData: function() { return { bdInteli: xxxx }; } }); // CATCH RESPONSE $('#input-id').on('filebatchuploaderror', function(event, data, previewId, index) { var form = data.form, files = data.files, extra = data.extra, response = data.response, reader = data.reader; }); $('#input-id').on('filebatchuploadsuccess', function(event, data, previewId, index) { var form = data.form, files = data.files, extra = data.extra, response = data.response, reader = data.reader; alert (extra.bdInteli + " " + response.uploaded); }); </code></pre> <p>PHP</p> <pre><code>$nombre = $_FILES["ficheroExcel"]["name"]; $bdInteli = $_POST['bdInteli']; if (move_uploaded_file($_FILES["ficheroExcel"]["tmp_name"], $nombre) ){ $output = array('uploaded' =&gt; 'OK' ); } else { $output = array('uploaded' =&gt; 'ERROR' ); } echo json_encode($output); </code></pre>
6,184,742
How to align my link to the right side of the page?
<p>I have a link on my index page:</p> <pre><code>&lt;div class="content"&gt; &lt;a class="buy" href="buy.html"&gt;Buy&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I would like to align it to the right side of my page, I tried:</p> <pre><code>a.buy{ color: #2da1c1; font-size: small; text-decoration: none; left: 252px; float: left; } a.buy:hover { color: #f90; text-decoration: underline; left: 252px; float: left; } </code></pre> <p>But it still located on the left side. (I have included my CSS file in my index.html, and the CSS file already take effect for other elements on the page)</p>
6,184,766
5
1
null
2011-05-31 08:16:03.903 UTC
null
2021-07-15 11:12:13.493 UTC
2021-01-23 13:31:14.027 UTC
null
8,620,333
null
740,018
null
1
14
html|css
58,106
<p>Try <code>float: right</code>:</p> <pre><code>a.buy { color: #2da1c1; font-size: small; text-decoration: none; float: right; } a.buy:hover { color: #f90; text-decoration: underline; } </code></pre> <p>Another way would be:</p> <pre><code>.content { position: relative } a.buy { color: #2da1c1; font-size: small; text-decoration: none; position: absolute; right: 0; } a.buy:hover { color: #f90; text-decoration: underline; } </code></pre>
6,199,301
Global access to Rake DSL methods is deprecated
<p>I am working through the Ruby on Rails 3 tutorial book and typed the following on the command line:</p> <pre><code>rake db:migrate </code></pre> <p>which produced the following warning.</p> <pre><code>WARNING: Global access to Rake DSL methods is deprecated. Please Include ... Rake::DSL into classes and modules which use the Rake DSL methods. WARNING: DSL method DemoApp::Application#task called at /Users/imac/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.7/lib/rails/application.rb:215:in `initialize_tasks' </code></pre> <p>I am not sure what to do about it or how to work with it. I don't know any other command for Rake.</p> <p>How can I fix this problem?</p>
6,199,917
5
0
null
2011-06-01 09:52:14.323 UTC
22
2012-07-09 14:18:35.437 UTC
2011-07-31 13:23:36.87 UTC
null
63,550
null
623,266
null
1
86
ruby-on-rails-3|rake|railstutorial.org
22,733
<p>I found this in Stack Overflow question <em><a href="https://stackoverflow.com/questions/6085610/rails-rake-problems-uninitialized-constant-rakedsl">Ruby on Rails and Rake problems: uninitialized constant Rake::DSL</a></em>. It refers to a @DHH tweet.</p> <p>Put the following in your Gemfile</p> <pre><code>gem "rake", "0.8.7" </code></pre> <p>You may see something like </p> <pre><code>rake aborted! You have already activated Rake 0.9.1 ... </code></pre> <p>I still had a copy of Rake 0.9.1 in my directory so I deleted it.</p> <p>You can "delete" Rake 0.9.1 by running the following command: </p> <pre><code>gem uninstall rake -v=0.9.1 </code></pre> <p>If you have multiple versions of the gem installed, you'll be prompted to pick a version.</p> <p>After 0.9.1 was cleaned out, I ran </p> <pre><code>bundle update rake </code></pre> <p>and was finally able to create my database files. I was using <code>rake db:create</code>, but it should work for <code>rake db:migrate</code> as well. </p> <p>I hope it helps.</p>
5,666,772
How can I render text on a WriteableBitmap on a background thread, in Windows Phone 7?
<p>I am trying to render text on a bitmap in a Windows Phone 7 application.</p> <p>Code that looks more or less like the following would work fine when it's running on the main thread:</p> <pre><code>public ImageSource RenderText(string text, double x, double y) { var canvas = new Canvas(); var textBlock = new TextBlock { Text = text }; canvas.Children.Add(textBloxk); Canvas.SetLeft(textBlock, x); Canvas.SetTop(textBlock, y); var bitmap = new WriteableBitmap(400, 400); bitmap.Render(canvas, null); bitmap.Invalidate(); return bitmap; } </code></pre> <p>Now, since I have to render several images with more complex stuff, I would like to render the bitmap on a background thread to avoid an unresponsive UI.</p> <p>When I use a <code>BackgroundWorker</code> to do so, the constructor for <code>TextBlock</code> throws an <code>UnauthorizedAccessException</code> claiming that this is an invalid cross-thread access.</p> <p>My question is: how can I render text on a bitmap without blocking the UI?</p> <ul> <li>Please don't suggest using a web service to do the rendering. I need to render a large number of images and the bandwidth cost is not acceptable for my needs, and the ability to work offline is a major requirement.</li> <li>The solution doesn't necessarily has to use <code>WriteableBitmap</code> or <code>UIElements</code>, if there is another way to render text.</li> </ul> <p><strong>EDIT</strong></p> <p>Another thought: does anyone know if it should be possible to run a UI message loop in another thread, and then have that thread do the work? (instead of using a <code>BackgroundWorker</code>)?</p> <p><strong>EDIT 2</strong></p> <p>To consider alternatives to <code>WriteableBitmap</code>, the features I need are:</p> <ul> <li>Draw a background image.</li> <li>Measure the width and height of a 1-line string, given a font familiy and size (and preferably style). No need for word wrapping.</li> <li>Draw a 1-line string, with given font family, size, style, at a given coordinate.</li> <li>Text rendering should support a transparent background. I.e. you should see the background image between the characters.</li> </ul>
5,678,587
6
4
null
2011-04-14 16:56:30.827 UTC
13
2011-09-18 14:08:15.187 UTC
2011-04-15 07:06:58.953 UTC
null
464,331
null
464,331
null
1
14
c#|multithreading|silverlight|windows-phone-7|writeablebitmap
19,603
<p>This method copies the letters from an pre-made image instead of using TextBlock, it's based on my answer to this <a href="https://stackoverflow.com/questions/3719750/best-way-to-get-a-glow-effect-windows-phone-7">question</a>. The main limitation is requiring a different image for each font and size needed. A size 20 Font needed about 150kb.</p> <p>Using <a href="http://www.nubik.com/SpriteFont/" rel="nofollow noreferrer">SpriteFont2</a> export the font and the xml metrics file in the sizes you require. The code assumes they're named "FontName FontSize".png and "FontName FontSize".xml add them to your project and set the build action to content. The code also requires <a href="http://writeablebitmapex.codeplex.com/" rel="nofollow noreferrer">WriteableBitmapEx</a>.</p> <pre><code>public static class BitmapFont { private class FontInfo { public FontInfo(WriteableBitmap image, Dictionary&lt;char, Rect&gt; metrics, int size) { this.Image = image; this.Metrics = metrics; this.Size = size; } public WriteableBitmap Image { get; private set; } public Dictionary&lt;char, Rect&gt; Metrics { get; private set; } public int Size { get; private set; } } private static Dictionary&lt;string, List&lt;FontInfo&gt;&gt; fonts = new Dictionary&lt;string, List&lt;FontInfo&gt;&gt;(); public static void RegisterFont(string name,params int[] sizes) { foreach (var size in sizes) { string fontFile = name + " " + size + ".png"; string fontMetricsFile = name + " " + size + ".xml"; BitmapImage image = new BitmapImage(); image.SetSource(App.GetResourceStream(new Uri(fontFile, UriKind.Relative)).Stream); var metrics = XDocument.Load(fontMetricsFile); var dict = (from c in metrics.Root.Elements() let key = (char) ((int) c.Attribute("key")) let rect = new Rect((int) c.Element("x"), (int) c.Element("y"), (int) c.Element("width"), (int) c.Element("height")) select new {Char = key, Metrics = rect}).ToDictionary(x =&gt; x.Char, x =&gt; x.Metrics); var fontInfo = new FontInfo(new WriteableBitmap(image), dict, size); if(fonts.ContainsKey(name)) fonts[name].Add(fontInfo); else fonts.Add(name, new List&lt;FontInfo&gt; {fontInfo}); } } private static FontInfo GetNearestFont(string fontName,int size) { return fonts[fontName].OrderBy(x =&gt; Math.Abs(x.Size - size)).First(); } public static Size MeasureString(string text,string fontName,int size) { var font = GetNearestFont(fontName, size); double scale = (double) size / font.Size; var letters = text.Select(x =&gt; font.Metrics[x]).ToArray(); return new Size(letters.Sum(x =&gt; x.Width * scale),letters.Max(x =&gt; x.Height * scale)); } public static void DrawString(this WriteableBitmap bmp,string text,int x,int y, string fontName,int size,Color color) { var font = GetNearestFont(fontName, size); var letters = text.Select(f =&gt; font.Metrics[f]).ToArray(); double scale = (double)size / font.Size; double destX = x; foreach (var letter in letters) { var destRect = new Rect(destX,y,letter.Width * scale,letter.Height * scale); bmp.Blit(destRect, font.Image, letter, color, WriteableBitmapExtensions.BlendMode.Alpha); destX += destRect.Width; } } } </code></pre> <p>You need to call RegisterFont once to load the files then you call DrawString. It uses WriteableBitmapEx.Blit so if your font file has white text and a transparent background alpha is handled correctly and you can recolour it. The code does scale the text if you draw at a size you didn't load but the results aren't good, a better interpolation method could be used. </p> <p>I tried drawing from a different thread and this worked in the emulator, you still need to create the WriteableBitmap on the main thread. My understanding of your scenario is that you want to scroll through tiles similar to how mapping apps work, if this is the case reuse the old WriteableBitmaps instead of recreating them. If not the code could be changed to work with arrays instead.</p>
5,607,479
Git Server Frustration (Gitosis, Gitolite, etc)
<p><em>Please excuse the frustrating undertones as I have attempted to get this set up correctly multiple times to no avail (possibly and most likely due to my ignorance, but also likely due to the lack of thorough and concise documentation).</em></p> <p>I am trying to set up a git server so that I can share code amongst a small team of developers. Each developer may connect from multiple client PC's. I come from MS in the past so I am a bit spoiled in regards to development <em>toolset</em>, but it would be awesome if I could get something similar to TFS.</p> <p>When trying to set up either gitosis (I understand this is deprecated for the git community per <a href="https://serverfault.com/questions/225495/ubuntu-server-gitosis-user-naming-convention">https://serverfault.com/questions/225495/ubuntu-server-gitosis-user-naming-convention</a>) or gitolite, it seems as though as soon as I set it up I have to be extremely careful because it seems everything is balancing on toothpicks.</p> <p>My latest attempt to set up a git server included moving my public key (benny.pub) from my laptop to the server, setting everything using that public key and pulling down the config to set up a repo and permissions. I then realized I want to develop on another PC so I created a new key ([email protected]) and renamed benny.pub to [email protected] which screwed things up obviously. This is where I know I was dumb by changing the name.</p> <p>My question after a long-winded description is this: how can I set up a sturdy self-hosted git server with the ability to have multiple developers log in from multiple machines while maintaining security, etc? There has to be a proven technique (gitolite describes maybe 4-5 different ways...also frustrating) to do this as I'm sure I'm not the only one trying to do this exact same thing. Maybe git isn't right for my team?</p> <p>Any help is greatly appreciated!</p>
5,608,831
6
2
null
2011-04-09 19:54:02.967 UTC
10
2012-01-27 02:57:12.683 UTC
2017-04-13 12:13:40.137 UTC
null
-1
null
194,261
null
1
17
linux|git|gitosis|gitolite
13,596
<p>From my experience, all you need is a SSH server with a <em>single</em> git account/login that you are able to connect to using one of your public keys. Install gitolite using SSH (copies gitloite from your client to the server &amp; does the basic setup) and have your developers send you their public keys. Add these keys to the gitolite-admin repository in your <code>~</code> and push.</p> <p>Why does a developer need more than one keypair in the first place, even if multiple machines are used? Such cases will neither influence how SSH handles authentication nor how gitolite handles authorization: they're still SSH keys. </p> <ul> <li><p>If a developer has to use several keypairs (one for git, another for some other server), let them handle the complexity and advise them to create an entry in <code>~/.ssh/config</code> for each keypair/server combination they use.</p></li> <li><p>If a developer has a different keypair on every machine used, gitolite groups can combine several public keys:</p></li> </ul> <pre><code>@agross = agross-1 agross-2 </code></pre>
6,212,951
Endianness of Android NDK
<p>I'm working with my new app which processed captured image from cellphone camera. My phone is Nexus S, 2.3.4.</p> <p>I create a ARGB_8888 Bitmap with captured data. I know the ndk image lib, but it's only support 2.2 and above. So I pass the int[] of Bitmap to NDK and found the color byte order is little-endian.</p> <p>I searched the wiki and found arm architecture is bi-endian. <a href="http://en.wikipedia.org/wiki/Endianness#Bi-endian_hardware">http://en.wikipedia.org/wiki/Endianness#Bi-endian_hardware</a></p> <p>My question is if arm is bi-endian, how to judge the byte order in specific device? Should I test the byte order every time before access the data?</p>
6,687,977
7
3
null
2011-06-02 09:54:51.657 UTC
12
2018-11-09 15:05:39.113 UTC
null
null
null
null
531,223
null
1
63
android|android-ndk
40,666
<p>Yes most cpus bi-endian, but most end user operating systems in use today choose to use the cpus in little-endian. Along those lines, ARM can operate in both as a convenience, its actual default after ARM 3 is little-endianess which is the endian mode it starts up in. I think one can safely assume that all Android devices are little endian, otherwise it would be extra work if different android devices were a mixture of endianess.</p> <p>Because network byte order is big-endian, it can be helpful to convert any format you plan on using for data interchange to network byte order. Again, though, Mac OS X on Intel, Windows, iOS and Android are little-endian, so you might just code up structures with the native endianness and hope the next great OS you want to port data to doesn't go big-endian.</p>
5,686,755
Meaning of delta or epsilon argument of assertEquals for double values
<p>I have a question about JUnit <code>assertEquals</code> to test <code>double</code> values. Reading the <a href="https://junit.org/junit4/javadoc/latest/org/junit/Assert.html#assertEquals(double,%20double)" rel="noreferrer">API doc</a> I can see:</p> <blockquote> <pre><code>@Deprecated public static void assertEquals(double expected, double actual) </code></pre> <p><strong>Deprecated.</strong> Use <code>assertEquals(double expected, double actual, double delta)</code> instead.</p> </blockquote> <p><em>(Note: in older documentation versions, the delta parameter is called epsilon)</em></p> <p>What does the <code>delta</code> (or <code>epsilon</code>) parameter mean?</p>
5,686,764
8
0
null
2011-04-16 13:18:22.59 UTC
28
2021-09-24 12:55:54.267 UTC
2020-10-16 08:25:26.63 UTC
null
584,192
null
428,691
null
1
210
java|junit|floating-point
185,541
<p>Epsilon is the value that the 2 numbers can be off by. So it will assert to true as long as <code>Math.abs(expected - actual) &lt;= epsilon</code></p>
6,127,696
Android - local image in webview
<p>I'm trying to diplay a local image in my webview :</p> <pre><code> String data = "&lt;body&gt;" + "&lt;img src=\"file:///android_asset/large_image.png\"/&gt;&lt;/body&gt;"; webview.loadData(data, "text/html", "UTF-8"); </code></pre> <p>This code doesn't display anything, instead of :</p> <pre><code> webview.loadUrl("file:///android_asset/large_image.jpg"); </code></pre> <p>This one works, but I need to have complex web page, not just a picture.</p> <p>Any ideas ?</p>
6,134,462
11
1
null
2011-05-25 16:25:11.85 UTC
23
2020-04-28 05:32:30.363 UTC
null
null
null
null
709,863
null
1
60
android|image|webview|android-webview
92,711
<p>Load Html file in Webview and put your image in asset folder and read that image file using Html.</p> <pre><code>&lt;html&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;img src="abc.gif" width="50px" alt="Hello"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/html&gt; </code></pre> <p>Now Load that Html file in Webview</p> <pre><code>webview.loadUrl("file:///android_asset/abc.html"); </code></pre>
39,025,074
C program how to print in table format alignment
<p>The input is retrieve from text file. Which contain information of </p> <ul> <li>product ID</li> <li>product Name</li> <li>Product Quantity</li> <li><p>product Price</p> <pre><code>1 RAYBAN 1 450.000000 900 KEYBOARD 100 290.000000 78 MINERALWATER 123 345.000000 2 RAYBAN 2 450.000000 </code></pre></li> </ul> <p>After printing the output through command prompt. It was not align with the 1st item. How to make it align with the title of table. As you can see the input of line 1 and 4 almost the same. </p> <p>Here is the output. </p> <p><a href="https://i.stack.imgur.com/5MNbN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5MNbN.jpg" alt="enter image description here"></a></p> <p>Here is the full code. With <code>gotoxy</code> function. The display function is on </p> <pre><code>int displayProduct() </code></pre> <p>There is a line of code for table titles and also the printf from TXT File. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;windows.h&gt; #include &lt;ctype.h&gt; void gotoxy(int column, int line); int main(); int addProduct(); int displayProduct(); //prototype struct product { int quantity, reorder, i, id; char name[20]; float price; }; COORD coord = { 0, 0 }; void gotoxy(int x, int y) { coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); } int main() { int choice; gotoxy(17, 5); printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); gotoxy(17, 20); printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); gotoxy(22, 8); printf("1. Add Product\n\n"); gotoxy(22, 10); printf("2. Display Product\n\n"); gotoxy(22, 12); printf("3. Search Product\n\n"); gotoxy(22, 14); printf("4. Reorder Level of Product\n\n"); gotoxy(22, 16); printf("5. Update Product\n\n"); gotoxy(22, 18); printf("6. Exit\n\n"); gotoxy(22, 22); printf("Please Enter Your Choice : "); scanf(" %d", &amp;choice); switch (choice) { case 1: addProduct(); break; case 2: displayProduct(); break; case 3: searchProduct(); break; case 4: reorderProduct(); break; case 5: updateProduct(); break; case 6: break; default: system("cls"); main(); } return (0); } /*MENU CODE ENDS !*/ int addProduct() { FILE *fp; int i = 0; struct product a; system("cls"); fp = fopen("inventory.txt", "a+t"); char checker; do { system("cls"); gotoxy(17, 5); printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); gotoxy(17, 20); printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); gotoxy(22, 8); printf("Enter product ID : "); scanf(" %d", &amp;a.id); gotoxy(22, 10); printf("Enter product name : "); scanf(" %s", a.name); gotoxy(22, 12); printf("Enter product quantity : "); scanf(" %d", &amp;a.quantity); gotoxy(22, 14); printf("Enter product price : "); scanf(" %f", &amp;a.price); gotoxy(22, 17); fprintf(fp, "%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price); //SAVE TO TXT FILE LINE ! printf("Record saved!\n\n"); fclose(fp); gotoxy(22, 22); printf("Do you want to enter new product? Y / N : "); scanf(" %c", &amp;checker); checker = toupper(checker); i++; system("cls"); } while (checker=='Y'); if (checker == 'N') { main(); } else { do { system("cls"); gotoxy(17, 5); printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); gotoxy(17, 20); printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); gotoxy(18, 8); printf("&gt;&gt;&gt; Wrong Input! Please Enter Y Or N Only! &lt;&lt;&lt;"); gotoxy(19, 12); printf("Do You Want To Enter New Product? Y / N : "); scanf(" %c", &amp;checker); checker = toupper(checker); } while (checker != 'Y' &amp;&amp; checker != 'N'); if (checker == 'Y'){ addProduct(); } if (checker == 'N') { system("cls"); main(); } } return(0); } /*ADD PRODUCT LINE ENDS !*/ int displayProduct() { FILE *fp; struct product a; char true; system("cls"); fp = fopen("inventory.txt", "r"); gotoxy(17, 5); printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); gotoxy(5, 6); printf("======================================================================"); gotoxy(5, 7); printf("Product ID\t\t Product Name\t\t Quantity\t Unit Price\n"); //TABLE TITLES ! gotoxy(5, 8); printf("======================================================================"); gotoxy(5,10); while (fscanf(fp, "%d %s %d %f", &amp;a.id, a.name, &amp;a.quantity, &amp;a.price) == 4) { printf("%d\t\t\t %s\t\t\t %d\t\t %.2f\n\n", a.id, a.name, a.quantity, a.price); //PRINT FROM TXT FILE TO COMMAND PROMPT. } fclose(fp); printf("\t\t \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2"); printf("\nPress any key to return to Main Menu."); getch(); int main(); return (0); } </code></pre> <p>Updated one, changes made : </p> <pre><code>gotoxy(5,10); while(fscanf(fp, "%d %s %d %f", &amp;a.id, a.name, &amp;a.quantity, &amp;a.price)==4) { printf("%-10d\t\t %-12s\t\t %8d\t %8.2f\n\n", a.id, a.name, a.quantity, a.price); } fclose(fp); </code></pre> <p><a href="https://i.stack.imgur.com/7uLn0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7uLn0.jpg" alt="enter image description here"></a></p>
39,025,499
2
1
null
2016-08-18 18:24:11.953 UTC
6
2020-09-06 18:46:26.06 UTC
2016-09-16 17:17:15.883 UTC
null
4,370,109
null
6,713,937
null
1
3
c
52,966
<p>The code to print the inventory should use the length specifier in <code>printf</code> format like this:</p> <pre><code>gotoxy(0, 10); while (fscanf(fp, "%d %s %d %f", &amp;a.id, a.name, &amp;a.quantity, &amp;a.price) == 4) { printf(" %-10d\t\t %-12s\t\t %8d\t %8.2f\n\n", a.id, a.name, a.quantity, a.price); } </code></pre> <p>Some notes regarding the code:</p> <ul> <li><p>it is very bad style to call <code>main()</code> recursively. Use a loop instead.</p></li> <li><p>write a function that prints the header instead of duplicating the code multiple times.</p></li> <li><p>the statement <code>int main();</code> at the end of <code>displayProduct()</code> is a local declaration for function <code>main</code>, it does not generate a call.</p></li> </ul>
24,496,438
Can I take a photo in Unity using the device's camera?
<p>I'm entirely unfamiliar with Unity3D's more complex feature set and am curious if it has the capability to take a picture and then manipulate it. Specifically my desire is to have the user take a selfie and then have them trace around their face to create a PNG that would then be texture mapped onto a model. </p> <p>I know that the face mapping onto a model is simple, but I'm wondering if I need to write the photo/carving functionality into the encompassing Chrome app, or if it can all be done from within Unity. I don't need a tutorial on how to do it, just asking if it's something that is possible.</p>
24,497,723
8
1
null
2014-06-30 18:18:29.173 UTC
5
2022-03-14 09:55:48.937 UTC
2014-07-19 21:08:08.657 UTC
null
488,657
null
59,947
null
1
23
unity3d|photo
60,545
<p>Yes, this is possible. You will want to look at the <a href="http://docs.unity3d.com/ScriptReference/WebCamTexture.html" rel="nofollow noreferrer">WebCamTexture</a> functionality. </p> <p>You create a WebCamTexture and call its <a href="http://docs.unity3d.com/ScriptReference/WebCamTexture.Play.html" rel="nofollow noreferrer">Play()</a> function which starts the camera. WebCamTexture, as any Texture, allows you to get the pixels via a GetPixels() call. This allows you to take a snapshot in when you like, and you can save this in a Texture2D. A call to <a href="http://docs.unity3d.com/ScriptReference/Texture2D.EncodeToPNG.html" rel="nofollow noreferrer">EncodeToPNG()</a> and subsequent write to file should get you there. </p> <p>Do note that the code below is a quick write-up based on the documentation. I have not tested it. You might have to select a correct device if there are more than one available.</p> <pre class="lang-c# prettyprint-override"><code>using UnityEngine; using System.Collections; using System.IO; public class WebCamPhotoCamera : MonoBehaviour { WebCamTexture webCamTexture; void Start() { webCamTexture = new WebCamTexture(); GetComponent&lt;Renderer&gt;().material.mainTexture = webCamTexture; //Add Mesh Renderer to the GameObject to which this script is attached to webCamTexture.Play(); } IEnumerator TakePhoto() // Start this Coroutine on some button click { // NOTE - you almost certainly have to do this here: yield return new WaitForEndOfFrame(); // it's a rare case where the Unity doco is pretty clear, // http://docs.unity3d.com/ScriptReference/WaitForEndOfFrame.html // be sure to scroll down to the SECOND long example on that doco page Texture2D photo = new Texture2D(webCamTexture.width, webCamTexture.height); photo.SetPixels(webCamTexture.GetPixels()); photo.Apply(); //Encode to a PNG byte[] bytes = photo.EncodeToPNG(); //Write out the PNG. Of course you have to substitute your_path for something sensible File.WriteAllBytes(your_path + "photo.png", bytes); } } </code></pre>
24,872,541
Could not assemble any primary key columns for mapped table
<p>When I'm trying to create a database schema migration, I'm getting this weird error. Can you please help me to figure out what's wrong? </p> <pre><code>$ python app.py db upgrade [skipped] sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations' </code></pre> <p><strong>My model:</strong></p> <pre><code>class EssayStateAssociations(db.Model): __tablename__ = 'essay_associations' application_essay_id = db.Column( db.Integer, db.ForeignKey("application_essay.id"), primary_key=True), theme_essay_id = db.Column( db.Integer, db.ForeignKey("theme_essay.id"), primary_key=True), state = db.Column(db.String, default="pending") </code></pre>
26,029,844
5
1
null
2014-07-21 18:53:14.92 UTC
5
2021-11-27 03:09:38.657 UTC
2018-04-15 14:23:11.557 UTC
null
1,709,587
null
465,623
null
1
71
python|sqlalchemy|flask-sqlalchemy|flask-migrate
78,071
<p>You cannot have two primary keys in a table. Instead, you must use a compound primary key. This can be done by adding a <code>PrimaryKeyConstraint</code> in your model as below (remember to add a comma before closing the bracket in <code>__table_args__</code>:</p> <pre><code>from db import PrimaryKeyConstraint class EssayStateAssociations(db.Model): __tablename__ = 'essay_associations' __table_args__ = ( PrimaryKeyConstraint('application_essay_id', 'theme_essay_id'), ) application_essay_id = db.Column( db.Integer, db.ForeignKey("application_essay.id")) theme_essay_id = db.Column( db.Integer, db.ForeignKey("theme_essay.id")) state = db.Column(db.String, default="pending") </code></pre>
33,205,236
Spring security added prefix "ROLE_" to all roles name?
<p>I have this code in my Web Security Config:</p> <pre><code> @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**") .hasRole("ADMIN") .and() .httpBasic().and().csrf().disable(); } </code></pre> <p>So I added an user with "ADMIN" role in my database and I always get 403 error when I tryed loggin with this user, then I enabled log for spring and I found this line:</p> <pre><code>2015-10-18 23:13:24.112 DEBUG 4899 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /api/user/login; Attributes: [hasRole('ROLE_ADMIN')] </code></pre> <p>Why Spring Security is looking for "ROLE_ADMIN" instead "ADMIN"? </p>
33,206,127
5
1
null
2015-10-19 01:25:38.427 UTC
11
2021-02-26 13:40:55.827 UTC
null
null
null
null
2,242,903
null
1
37
java|spring|spring-mvc|spring-security|role
41,621
<p>Spring security adds the prefix "<strong>ROLE_</strong>" by default.</p> <p>If you want this removed or changed, take a look at </p> <p><a href="https://web.archive.org/web/20180201001929/http://forum.spring.io/forum/spring-projects/security/51066-how-to-change-role-from-interceptor-url" rel="noreferrer">How to change role from interceptor-url?</a></p> <p>EDIT: found this as well: <a href="https://stackoverflow.com/questions/21620076/spring-security-remove-rolevoter-prefix">Spring Security remove RoleVoter prefix</a></p>
9,338,618
How to use $(document).on("click.. on <a tag?
<p>I am new to jQuery and I am using jQuery 1.7.1 to learn Knockout JS, I was following a video demo by the author. In his example he has a tag something like </p> <pre><code>&lt;a href="#" class="button-delete"&gt;Delete&lt;/a&gt; </code></pre> <p>and in the viewmodel he has something like</p> <pre><code>$(document).on("click", ".button-delete", function() { console.log("inside"); }); </code></pre> <p>When I tried in my side when I click on the delete button I never see the console.log show up on the console window of the Chrome F12 screen. I have two part question here</p> <ol> <li>Is there something I am doing wrong which is preventing the console message to show up?</li> <li>If I do not have a class to do css, is there any other way to perform the same task in the viewmodel?</li> </ol> <p>edit: I corrected my typo, the code has proper parenthesis (I use web matrix so it take care of those issues). Here is my html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;script src="Scripts/jquery-1.7.1.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="Scripts/knockout-2.0.0.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="Scripts/ViewModel.js" type="text/javascript"&gt;&lt;/script&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;&lt;/title&gt; &lt;link href="assets/css/bootstrap.min.css" rel="stylesheet"&gt; &lt;/head&gt; &lt;body onload="init()"&gt; &lt;input data-bind="value: tagsToAdd"/&gt; &lt;button data-bind="click: addTag"&gt;Add&lt;/button&gt; &lt;ul data-bind="foreach: tags"&gt; &lt;li&gt; &lt;span data-bind="text: Name"&gt;&lt;/span&gt; &lt;div&gt; &lt;a href="#" class="btn btn-danger" &gt;Delete&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is my knockout viewmodel</p> <pre><code>/// &lt;reference file="jquery-1.7.1.js" /&gt; /// &lt;reference file="knockout-2.0.0.js" /&gt; var data = [ {Id: 1, Name: "Ball Handling" }, {Id: 2, Name: "Shooting" }, {Id: 3, Name: "Rebounding" } ]; function viewModel() { var self = this; self.tags = ko.observableArray(data); self.tagsToAdd = ko.observable(""); self.addTag = function() { self.tags.push({ Name: this.tagsToAdd() }); self.tagsToAdd(""); } } $(document).on("click", ".btn-danger", function () { console.log("inside"); }); var viewModelInstance; function init(){ this.viewModelInstance = new viewModel(); ko.applyBindings(viewModelInstance); } </code></pre>
9,354,848
4
0
null
2012-02-18 04:40:02.167 UTC
3
2012-02-20 00:38:10.887 UTC
2012-02-18 05:35:55.13 UTC
null
115,457
null
115,457
null
1
7
jquery|knockout.js
86,623
<p>Looks like you got your first answer already. On the "other ways" to bind the click event if you don;t have a class name, there are a few options. You could add an id to the tag, and call it that way. Or if you don't want to add a class nor an id, you can use the data-bind syntax with the "click" built-in binding to invoke a method on your view model (obviously this is not the jquery evnet style, so its up to you how you want to wire up your events). Like this:</p> <pre><code>&lt;button data-bind="click: someMethod"&gt;Click me&lt;/button&gt; </code></pre>
9,398,284
Creating a mock in phpunit without mocking any methods?
<p>When I'm unit-testing my php code with PHPUnit, I'm trying to figure out the right way to mock an object without mocking any of its methods.</p> <p>The problem is that if I don't call <code>getMockBuilder()-&gt;setMethods()</code>, then all methods on the object will be mocked and I can't call the method I want to test; but if I <em>do</em> call <code>setMethods()</code>, then I need to tell it what method to mock but I don't want to mock any methods at all. But I need to create the mock so I can avoid calling the constructor in my test.</p> <p>Here's a trivial example of a method I'd want to test:</p> <pre><code>class Foobar { public function __construct() { // stuff happens here ... } public function myMethod($s) { // I want to test this return (strlen($s) &gt; 3); } } </code></pre> <p>I might test <code>myMethod()</code> with:</p> <pre><code>$obj = new Foobar(); $this-&gt;assertTrue($obj-&gt;myMethod('abcd')); </code></pre> <p>But this would call Foobar's constructor, which I don't want. So instead I'd try:</p> <pre><code>$obj = $this-&gt;getMockBuilder('Foobar')-&gt;disableOriginalConstructor()-&gt;getMock(); $this-&gt;assertTrue($obj-&gt;myMethod('abcd')); </code></pre> <p>But calling <code>getMockBuilder()</code> without using <code>setMethods()</code> will result in all of its methods being mocked and returning null, so my call to <code>myMethod()</code> will return null without touching the code I intend to test.</p> <p>My workaround so far has been this:</p> <pre><code>$obj = $this-&gt;getMockBuilder('Foobar')-&gt;setMethods(array('none')) -&gt;disableOriginalConstructor()-&gt;getMock(); $this-&gt;assertTrue($obj-&gt;myMethod('abcd')); </code></pre> <p>This will mock a method named 'none', which doesn't exist, but PHPUnit doesn't care. It will leave myMethod() unmocked so that I can call it, and it will also let me disable the constructor so that I don't call it. Perfect! Except that it seems like cheating to have to specify a method name that doesn't exist - 'none', or 'blargh', or 'xyzzy'.</p> <p>What would be the right way to go about doing this?</p>
9,399,495
6
0
null
2012-02-22 15:57:18.077 UTC
6
2022-08-06 20:19:03.323 UTC
2015-03-25 23:34:54.57 UTC
null
999,942
null
548,862
null
1
41
mocking|phpunit
20,493
<p>You can pass <code>null</code> to <code>setMethods()</code> to avoid mocking any methods. Passing an empty array will mock all methods. The latter is the default value for the methods as you've found.</p> <p>That being said, I would say the need to do this might point out a flaw in the design of this class. Should this method be made static or moved to another class? If the method doesn't require a completely-constructed instance, it's a sign to me that it might be a utility method that could be made static.</p>
9,398,065
python argh/argparse: How can I pass a list as a command-line argument?
<p>I'm trying to pass a list of arguments to a python script using the argh library. Something that can take inputs like these:</p> <pre><code>./my_script.py my-func --argA blah --argB 1 2 3 4 ./my_script.py my-func --argA blah --argB 1 ./my_script.py my-func --argA blah --argB </code></pre> <p>My internal code looks like this:</p> <pre><code>import argh @argh.arg('--argA', default="bleh", help='My first arg') @argh.arg('--argB', default=[], help='A list-type arg--except it\'s not!') def my_func(args): "A function that does something" print args.argA print args.argB for b in args.argB: print int(b)*int(b) #Print the square of each number in the list print sum([int(b) for b in args.argB]) #Print the sum of the list p = argh.ArghParser() p.add_commands([my_func]) p.dispatch() </code></pre> <p>And here's how it behaves:</p> <pre><code>$ python temp.py my-func --argA blooh --argB 1 blooh ['1'] 1 1 $ python temp.py my-func --argA blooh --argB 10 blooh ['1', '0'] 1 0 1 $ python temp.py my-func --argA blooh --argB 1 2 3 usage: temp.py [-h] {my-func} ... temp.py: error: unrecognized arguments: 2 3 </code></pre> <p>The problem seems pretty straightforward: argh is only accepting the first argument, and treating it as a string. How do I make it "expect" a list of integers instead?</p> <p>I see <a href="https://stackoverflow.com/questions/2086556/specifying-a-list-as-a-command-line-argument-in-python">how this is done in optparse</a>, but what about the (not-deprecated) argparse? Or using argh's much nicer decorated syntax? These seem much more pythonic.</p>
9,398,245
2
0
null
2012-02-22 15:45:46.683 UTC
16
2022-02-19 14:44:49.587 UTC
2022-02-19 14:44:49.587 UTC
null
792,066
null
660,664
null
1
73
python|python-argh
59,521
<p>With <code>argparse</code>, you just use <code>type=int</code></p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument('-a', '--arg', nargs='+', type=int) print parser.parse_args() </code></pre> <p>Example output:</p> <pre><code>$ python test.py -a 1 2 3 Namespace(arg=[1, 2, 3]) </code></pre> <p>Edit: I'm not familiar with <code>argh</code>, but it seems to be just a wrapper around <code>argparse</code> and this worked for me:</p> <pre><code>import argh @argh.arg('-a', '--arg', nargs='+', type=int) def main(args): print args parser = argh.ArghParser() parser.add_commands([main]) parser.dispatch() </code></pre> <p>Example output:</p> <pre><code>$ python test.py main -a 1 2 3 Namespace(arg=[1, 2, 3], function=&lt;function main at 0x.......&gt;) </code></pre>
10,577,256
Numbering lines matching the pattern using sed
<p>I'm writing the script that searches for lines that match some pattern. I must use sed for this script. This works fine for searching and printing matched lines:</p> <pre><code>sed -n /PATTERN/p </code></pre> <p>However, I'd also like to print the matched lines number in front of the line itself. How can I do that using sed?</p>
10,584,999
6
1
null
2012-05-14 03:36:48.94 UTC
9
2016-10-20 16:07:27.4 UTC
2012-10-10 14:01:30.56 UTC
null
387,076
null
1,068,243
null
1
19
shell|unix|sed
30,407
<p>You can use <code>grep</code>:</p> <pre><code>grep -n pattern file </code></pre> <p>If you use <code>=</code> in <code>sed</code> the line number will be printed on a separate line and is not available in the pattern space for manipulation. However, you can pipe the output into another instance of sed to merge the line number and the line it applies to.</p> <pre><code>sed -n '/pattern/{=;p}' file | sed '{N;s/\n/ /}' </code></pre>
7,375,875
django post_save signals on update
<p>I am trying to set up some <code>post_save</code> receivers similar to the following:</p> <pre><code>@receiver(post_save, sender=Game, dispatch_uid='game_updated') def game_updated(sender, **kwargs): '''DO SOME STUFF HERE''' MyPick.objects.filter(week=game.week, team=game.home_team).update(result=home_result) MyPick.objects.filter(week=game.week, team=game.away_team).update(result=away_result) @receiver(post_save, sender=MyPick, dispatch_uid='user_pick_updated') def update_standings(sender, **kwargs): '''DO STUFF''' </code></pre> <p>The first receiver is getting called correctly after an update on the Game object, however the calls to update on the MyPick object are not causing the second receiver to be called. Does the post_save signal not work on update or am I missing something else here?</p>
7,376,491
2
0
null
2011-09-11 02:06:48.373 UTC
8
2022-06-22 14:52:18.887 UTC
2022-06-22 14:52:18.887 UTC
null
17,562,044
null
417,918
null
1
39
python|django|django-models|django-queryset|django-signals
41,333
<p><a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once" rel="noreferrer"><code>update()</code> is converted directly to an SQL statement</a>; it doesn't call <code>save()</code> on the model instances, and so the <code>pre_save</code> and <code>post_save</code> signals aren't emitted. If you want your signal receivers to be called, you should loop over the queryset, and for each model instance, make your changes and call <code>save()</code> yourself.</p>
7,021,084
How do you receive a url parameter with a spring controller mapping
<p>This issue seems trivial, but I can't get it to work properly. I'm calling my Spring controller mapping with jquery ajax. The value for someAttr is always empty string regardless of the value in the url. Please help me determine why.</p> <p>-URL called</p> <pre><code>http://localhost:8080/sitename/controllerLevelMapping/1?someAttr=6 </code></pre> <p>-Controller Mapping</p> <pre><code>@RequestMapping(value={"/{someID}"}, method=RequestMethod.GET) public @ResponseBody int getAttr(@PathVariable(value="someID") final String id, @ModelAttribute(value="someAttr") String someAttr) { //I hit some code here but the value for the ModelAttribute 'someAttr' is empty string. The value for id is correctly set to "1". } </code></pre>
7,021,883
2
0
null
2011-08-11 05:11:16.413 UTC
20
2016-09-05 14:22:04.217 UTC
2011-08-11 06:45:08.537 UTC
null
21,234
null
445,884
null
1
130
spring-mvc
220,584
<p>You should be using <code>@RequestParam</code> instead of <code>@ModelAttribute</code>, e.g.</p> <pre><code>@RequestMapping("/{someID}") public @ResponseBody int getAttr(@PathVariable(value="someID") String id, @RequestParam String someAttr) { } </code></pre> <p>You can even omit <code>@RequestParam</code> altogether if you choose, and Spring will assume that's what it is:</p> <pre><code>@RequestMapping("/{someID}") public @ResponseBody int getAttr(@PathVariable(value="someID") String id, String someAttr) { } </code></pre>
19,298,651
How does WebSocket compress messages?
<p>JSON.stringify is obviously not very space efficient. For example, [123456789,123456789] occupy 20+ bytes when it could need just around 5. Does websocket compress its JSONs before sending to stream?</p>
19,300,336
4
0
null
2013-10-10 14:31:17.53 UTC
14
2021-03-09 09:22:13.723 UTC
2013-10-24 15:38:18.737 UTC
null
775,715
null
1,031,791
null
1
27
javascript|json|websocket|socket.io
40,178
<p>WebSocket is, at its heart, just a set of framing for TEXT or BINARY data.</p> <p>It performs no compression on its own.</p> <p>However, the WebSocket spec allows for Extensions, and there have been a variety of compression extensions in the wild (the formalized specs for one of these is finalized).</p> <p>As of today (August 2018) the accepted compression spec is <code>permessage-deflate</code>.</p> <p>Some of the extensions seen in the wild:</p> <ul> <li><a href="https://www.rfc-editor.org/rfc/rfc7692" rel="nofollow noreferrer"><code>permessage-deflate</code></a> - the name of the formalized spec for using deflate to compress entire messages, regardless of the number of websocket frames.</li> <li><code>x-webkit-deflate-frame</code> - an early proposed compression that compresses each raw websocket data frame. Seen in use by Chrome and Safari. (now deprecated in Chrome and Safari)</li> <li><a href="http://tools.ietf.org/id/draft-tyoshino-hybi-websocket-perframe-deflate-05.txt" rel="nofollow noreferrer"><code>perframe-deflate</code></a> - a renamed version of the above compression. Seen in use by various websocket server implementations, and also <a href="http://www.ietf.org/mail-archive/web/hybi/current/msg09463.html" rel="nofollow noreferrer">briefly showed up in various WebKit based clients</a>. (Completely deprecated in modern browsers, but does still show up in various WebSocket client libraries)</li> </ul> <p>Of note, the <code>permessage-deflate</code> extension is the first in a line of PMCE (Per-Message Compression Extensions) that will eventually include other compression schemes (<a href="http://www.ietf.org/mail-archive/web/hybi/current/msg10109.html" rel="nofollow noreferrer">ones being discussed</a> are <code>permessage-bzip2</code>, <code>permessage-lz4</code>, and <code>permessage-snappy</code>)</p>
58,376,585
Linq methods for IAsyncEnumerable
<p>When working with an <code>IEnumerable&lt;T&gt;</code> there are the build-in extension methods from the <code>System.Linq</code> namespace such as <code>Skip</code>, <code>Where</code> and <code>Select</code> to work with. </p> <p>When Microsoft added <code>IAsyncEnumerable</code> in C#8 did they also add new Linq methods to support this?</p> <p>I could of course implement these methods myself, or maybe find some package which does that, but I'd prefer to use a language-standard method if it exists.</p>
58,376,703
1
2
null
2019-10-14 12:15:22.85 UTC
2
2021-12-21 21:16:13.817 UTC
null
null
null
null
1,383,035
null
1
38
c#|c#-8.0|iasyncenumerable
17,061
<p>LINQ for <code>IAsyncEnumerable</code> is supported by <a href="https://www.nuget.org/packages/System.Linq.Async/" rel="noreferrer"><code>System.Linq.Async</code></a> which is part of the <a href="https://github.com/dotnet/reactive" rel="noreferrer">reactive extensions for .NET</a>. The reactive extensions as a whole are split into two larger NuGet packages: <a href="https://www.nuget.org/packages/System.Reactive/" rel="noreferrer"><code>System.Reactive</code></a> and <a href="https://www.nuget.org/packages/System.Interactive/" rel="noreferrer"><code>System.Interactive</code></a>.</p> <p>While all the packages stayed the same, the extensions now live in the <code>System.Linq</code> namespace, not <code>System.Linq.Async</code> anymore (thanks Dzmitry Lahoda).</p> <p><a href="https://github.com/dotnet/corefx/issues/36545" rel="noreferrer">Relevant GitHub issue</a></p>
36,700,083
In Spyder, plot using Matplotlib with interactive zoom, etc
<p>I've recently switched from Enthought Canopy to Anaconda and am using the Spyder IDE. I've noticed that when I plot some data,</p> <pre><code>import matplotlib.pyplot as plt plt.figure() plt.plot(rigs2) plt.ion() plt.show() </code></pre> <p>It shows up as an inline figure in the IPython console:</p> <p><a href="https://i.stack.imgur.com/j1Q0Q.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/j1Q0Q.jpg" alt="Result from the plt.plot() command"></a></p> <p>However, in Enthought it used to be that the plot would show up in a separate window with zoom, back, and forward buttons. Is there any way to achieve the same in Spyder?</p>
36,700,565
4
1
null
2016-04-18 17:02:48.947 UTC
4
2019-03-11 13:37:37.267 UTC
null
null
null
null
995,862
null
1
25
python|matplotlib|plot|spyder
112,193
<p>Select from the menu <code>Tools &gt; Preferences</code>, then <code>IPython console</code> in the list of categories on the left, then the tab <code>Graphics</code> at the top, and change the <code>Graphics backend</code> from <em>Inline</em> to e.g. <em>Qt</em>.<br> For me though, the figures then always pop up in the background.<br> (I use Spyder 3.0.0dev bundled with WinPython 3.4.)</p>
35,703,005
What is the difference between target="_blank" and target="blank"?
<p>Since I approached the web programming, to open a link in a new window I always used</p> <pre><code>target=&quot;blank&quot; </code></pre> <p>but most of the time, here and in the rest of the web I have ever seen use:</p> <pre><code>target=&quot;_blank&quot; </code></pre> <p>Both forms work (of course), but I do not know the difference between the two versions and they do not know what the correct way (and why)....</p>
35,703,051
3
1
null
2016-02-29 15:14:52.023 UTC
9
2021-07-21 04:54:49.667 UTC
2021-07-21 04:54:49.667 UTC
null
12,892,553
null
3,162,975
null
1
67
html|hyperlink
46,204
<p><code>blank</code> targets an existing frame or window called "blank". A new window is created only if "blank" doesn't already exist.</p> <p><code>_blank</code> is a reserved name which targets a new, unnamed window.</p>
3,745,017
How to develop alert system like facebook using PHP and Jquery?
<p>How can I develop an alert system like Facebook's, where User A add User B, User B will get some number in Friend Request Section on the header like in the image below. How can I develop something like that? How can we get numbers like this??how can i get codes in PHP and JQuery? <br> <img src="https://i.stack.imgur.com/hu2eb.gif" alt="alt text"></p>
3,745,037
1
0
null
2010-09-19 08:25:32.883 UTC
14
2016-09-22 07:31:25.827 UTC
2010-09-19 13:09:14.073 UTC
null
404,183
null
404,183
null
1
10
php|jquery|css|notifications
14,057
<p>I presume you want a means of alerting user A, when user B 'friends' him/her without requiring a page refresh?</p> <p>This requires "AJAX". AJAX stands for Asynchronous Javascript and XML, but this is an overloaded term now-a-days with the actual exchange data structure often using JSON instead of XML. JSON is JavaScript Object Notation. Anyway, the idea is that your webpage--without being refreshed--can make periodic calls to your server to get new or updated information to update the display with. With PHP and jQuery, you'll want to first set up the AJAX call on your page like this:</p> <pre><code>$(function() { // on document ready function updateAlerts() { $.ajax({ url : "/check.php", type : "POST", data : { method : 'checkAlerts' }, success : function(data, textStatus, XMLHttpRequest) { var response = $.parseJSON(data); // Update the DOM to show the new alerts! if (response.friendRequests &gt; 0) { // update the number in the DOM and make sure it is visible... $('#unreadFriendRequestsNum').show().text(response.friendRequests); } else { // Hide the number, since there are no pending friend requests $('#unreadFriendRequestsNum').hide(); } // Do something similar for unreadMessages, if required... } }); setTimeout('updateAlerts()', 15000); // Every 15 seconds. } }); </code></pre> <p>This will, every 15 seconds, make a request to your server at the url /check.php on the same domain as the origin of the webpage. The PHP should query your database and and return the number of unread friend requests. Perhaps something like this:</p> <pre><code>&lt;?php function isValid(session) { // given the user's session object, ensure it is valid // and that there's no funny business // TO BE IMPLEMENTED } function sanitize(input) { // return CLEAN input // TO BE IMPLEMENTED } // Be sure to check that your user's session is valid before proceeding, // we don't want people checking other people's friend requests! if (!isValid(session)) { exit; } $method = sanitize($_POST['method']); switch ($method) { case 'checkAlerts' : // Check DB for number of unread friend requests and or unread messages // TO BE IMPLEMENTED $response = ['friendRequests' =&gt; $num_friend_requests, 'messages' =&gt; $num_unread_messages ]; return json_encode( $response ); exit; case 'someOtherMethodIfRequired' : // ... exit; } ?&gt; </code></pre>
21,142,923
CSS transitions with calc() do not work in IE10+
<p>I am animating a container on mouseover from right to the left with CSS transitions. This works fine in all browsers except Internet Explorer. The reason is that I am using (and need to use) calc() in my CSS left property.</p> <p><strong>I created a live demo here: <a href="http://jsfiddle.net/4MsK8/" rel="noreferrer">Live Demo</a></strong></p> <p>The CSS looks like this: </p> <pre><code>div { background: red; width: 100px; height: 100px; position: absolute; top: 100px; left: 90%; -webkit-transition: left 0.7s cubic-bezier(0.77, 0, 0.175, 1); -moz-transition: left 0.7s cubic-bezier(0.77, 0, 0.175, 1); -o-transition: left 0.7s cubic-bezier(0.77, 0, 0.175, 1); transition: left 0.7s cubic-bezier(0.77, 0, 0.175, 1); } div.translate-less { left: calc(90% - 4rem) } </code></pre> <p>I am adding the class .translate-less on mouseover with jQuery:</p> <pre><code>$(document) .on( 'mouseenter', 'div', function(){ $(this).addClass('translate-less') }) .on( 'mouseleave', 'div', function(){ $('div').removeClass('translate-less'); }) </code></pre> <p>Now I would like to have a smooth transition in Internet Explorer. For that, I would even ditch the calc() for these specific browsers and add a rule like <code>left: 85%;</code>. But IE 10 and 11 have <a href="http://blogs.msdn.com/b/ie/archive/2011/07/06/html5-parsing-in-ie10.aspx" rel="noreferrer">dropped support for conditional comments</a> and there seems to be no way to target these browsers specifically. IE 10 can be targeted with the <a href="http://www.paulirish.com/2009/browser-specific-css-hacks/" rel="noreferrer">-ms-high-contrast-hack</a>, but IE 11 cannot. I do not want to <a href="http://thebenlumley.com/how-to-target-ie-11-with-css/" rel="noreferrer">use JavaScript</a> to detect the browser because this seems even hackier than using CSS hacks.</p>
21,381,301
1
2
null
2014-01-15 16:30:49.54 UTC
7
2018-11-05 22:47:42.837 UTC
2018-11-05 22:47:42.837 UTC
null
2,756,409
null
836,005
null
1
49
css|internet-explorer|css-transitions
19,036
<p>Maybe <code>transform: translateX()</code> can provide a work-around. Depending on the circumstances, using transforms and the right property might be better: </p> <pre><code>right: 10%; transform: translateX(-4rem); </code></pre> <p>Here is a modified version of your script: <a href="http://jsfiddle.net/xV84Z/1/">http://jsfiddle.net/xV84Z/1/</a>.</p> <p>Alternatively, while you can't use <code>calc()</code> within a <code>translateX()</code> in IE (because of <a href="http://connect.microsoft.com/IE/feedback/details/762719/css3-calc-bug-inside-transition-or-transform">a bug</a>), you can apply multiple <code>translateX()</code>s in a transform:</p> <pre><code>/* This */ transform: translateX(90%) translateX(-4rem); /* is equivalent to this */ transform: translateX(calc(90% - 4rem)); </code></pre> <p>(However, 90% in this case means 90% of the target, not the parent.) </p>
21,298,190
Bluebird, promises and then()
<p>I've been only using bluebird for a few days but I want to go over all my old code and <code>promisify</code> it :)</p> <p>My problem is that I still don't fully grasp the flow of <code>then()</code> commands.</p> <p>Consider these two blocks:</p> <p>A</p> <pre><code>methodThatReturnsAPromise().then(task2).then(task3); </code></pre> <p>B</p> <pre><code>var promise = methodThatReturnsAPromise(); promise.then(task2) promise.then(task3); </code></pre> <ol> <li><p>in scenario A <code>task3</code> will get the result of <code>task2</code>? In B they all get the result of the first promise? </p></li> <li><p>How does the second one differ from running <code>Promise.all</code> from bluebird?</p></li> <li><p>How do these A/B/<code>Promise.all</code> differ when it comes to using the <code>catch</code> method (where do I put it).</p></li> </ol> <p>Sorry it's a bunch of questions in one.</p>
21,298,322
3
3
null
2014-01-23 02:27:37.593 UTC
16
2016-09-13 06:23:19.113 UTC
null
null
null
null
1,026,502
null
1
40
javascript|node.js|promise|bluebird
36,190
<p>Welcome to the wonderful world of promises.</p> <h3>How <code>then</code> works in your example</h3> <p>Your assertion in <code>1</code> is correct. We can simulate a promise resolving in Bluebird using <code>Promise.resolve</code> on a value. </p> <p>Let's show this:</p> <p>Let's get a function that returns a promise:</p> <pre><code>function foo(){ return Promise.resolve("Value"); } foo().then(alert); </code></pre> <p>This short snippet will alert <code>"Value"</code> as <a href="http://jsfiddle.net/5Ep9x/" rel="noreferrer">we can see</a>.</p> <p>Now, let's create two more promises, each that alert and return different values.</p> <pre><code>function task2(e){ alert("In two got " + e); return " Two "; } function task3(e){ alert("In three got " + e); return " Three "; } </code></pre> <p>So, as you can see in <a href="http://jsfiddle.net/4sA99/" rel="noreferrer">your first code</a> it will indeed resolve in a chain, each with the value of the previous part.</p> <p>In the second example, both task2 and task3 will get the same value and will also execute together (that is, task 3 will not wait for task 2). You can see that <a href="http://jsfiddle.net/E6pF4/" rel="noreferrer">here</a>.</p> <h3>Promise.all</h3> <p>Promise.all (or just returning an array from a <code>then</code> fulfillment handler and then using <code>.spread</code>) is used for waiting for multiple results to all complete. On your example, you're hooking on a single result in multiple parts.</p> <h3>The catch</h3> <p>You always put catch where you want the error to be caught. As you would normally in synchronous code. Just remember to always throw in a promise or in promisified code. </p>
47,806,480
What purpose do generic constructors serve in Java?
<p>As everyone knows you can have a generic class in Java by using type arguments:</p> <pre><code>class Foo&lt;T&gt; { T tee; Foo(T tee) { this.tee = tee; } } </code></pre> <p>But you can also have generic <em>constructors</em>, meaning constructors that explicitly receive their own generic type arguments, for example:</p> <pre><code>class Bar { &lt;U&gt; Bar(U you) { // Why!? } } </code></pre> <p>I'm struggling to understand the use case. What does this feature let me do?</p>
47,817,330
5
6
null
2017-12-14 05:33:27.207 UTC
7
2018-11-02 13:44:38.357 UTC
null
null
null
null
1,911,388
null
1
36
java|generics|constructor
3,769
<blockquote> <p>What does this feature let me do?</p> </blockquote> <p>There are at least <s>three</s> two things it lets you do that you could not otherwise do:</p> <ol> <li><p>express relationships between the types of the arguments, for example:</p> <pre><code>class Bar { &lt;T&gt; Bar(T object, Class&lt;T&gt; type) { // 'type' must represent a class to which 'object' is assignable, // albeit not necessarily 'object''s exact class. // ... } } </code></pre></li> <li><p>&lt;withdrawn></p></li> <li><p>As @Lino observed first, it lets you express that arguments must be compatible with a combination of two or more unrelated types (which can make sense when all but at most one are interface types). See Lino's answer for an example.</p></li> </ol>
41,012,719
How to load and display .obj file in Android with OpenGL-ES 2
<p>I am trying to load an .obj file into my Android application and display it using OpenGL 2.</p> <p>You can find the file here: <strong>EDIT: I removed the file</strong>, you can use any .obj file that contains the values mentiones below for testing.</p> <p>There are a lot of similar questions on stackoverflow but I did not find a simple solution that does not require some large library.</p> <p>The file only contains the following value types:</p> <ul> <li>g</li> <li>v</li> <li>vt</li> <li>vn</li> <li>f</li> </ul> <p>I tried libgdx, which worked ok, but it is a bit overkill for what I need.</p> <p>I tried the oObjLoader <a href="https://github.com/seanrowens/oObjLoader" rel="noreferrer">https://github.com/seanrowens/oObjLoader</a> without the LWJGL. The parsing seems to work, but how can I display the values in a simple scene?</p> <p>The next step is to attach an image as a texture to the object. But for now I would be happy to display the file as it is.</p> <p>I am open to different solutions like pre-converting the file, because it will only be this one ever within the application.</p> <p>Thanks!</p> <p><strong>Status update</strong> Basic loading and displaying works now, as shown in my own answer. </p>
41,138,223
3
1
null
2016-12-07 08:36:49.223 UTC
8
2021-07-05 20:44:22.203 UTC
2016-12-15 09:53:21.497 UTC
null
497,366
null
497,366
null
1
19
android|opengl-es|opengl-es-2.0
17,495
<p>I ended up writing a new parser, it can be used like this to build FloatBuffers to use in your Renderer:</p> <pre><code>ObjLoader objLoader = new ObjLoader(context, "Mug.obj"); numFaces = objLoader.numFaces; // Initialize the buffers. positions = ByteBuffer.allocateDirect(objLoader.positions.length * mBytesPerFloat) .order(ByteOrder.nativeOrder()).asFloatBuffer(); positions.put(objLoader.positions).position(0); normals = ByteBuffer.allocateDirect(objLoader.normals.length * mBytesPerFloat) .order(ByteOrder.nativeOrder()).asFloatBuffer(); normals.put(objLoader.normals).position(0); textureCoordinates = ByteBuffer.allocateDirect(objLoader.textureCoordinates.length * mBytesPerFloat) .order(ByteOrder.nativeOrder()).asFloatBuffer(); textureCoordinates.put(objLoader.textureCoordinates).position(0); </code></pre> <p>and here's the parser:</p> <pre><code>public final class ObjLoader { public final int numFaces; public final float[] normals; public final float[] textureCoordinates; public final float[] positions; public ObjLoader(Context context, String file) { Vector&lt;Float&gt; vertices = new Vector&lt;&gt;(); Vector&lt;Float&gt; normals = new Vector&lt;&gt;(); Vector&lt;Float&gt; textures = new Vector&lt;&gt;(); Vector&lt;String&gt; faces = new Vector&lt;&gt;(); BufferedReader reader = null; try { InputStreamReader in = new InputStreamReader(context.getAssets().open(file)); reader = new BufferedReader(in); // read file until EOF String line; while ((line = reader.readLine()) != null) { String[] parts = line.split(" "); switch (parts[0]) { case "v": // vertices vertices.add(Float.valueOf(parts[1])); vertices.add(Float.valueOf(parts[2])); vertices.add(Float.valueOf(parts[3])); break; case "vt": // textures textures.add(Float.valueOf(parts[1])); textures.add(Float.valueOf(parts[2])); break; case "vn": // normals normals.add(Float.valueOf(parts[1])); normals.add(Float.valueOf(parts[2])); normals.add(Float.valueOf(parts[3])); break; case "f": // faces: vertex/texture/normal faces.add(parts[1]); faces.add(parts[2]); faces.add(parts[3]); break; } } } catch (IOException e) { // cannot load or read file } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { //log the exception } } } numFaces = faces.size(); this.normals = new float[numFaces * 3]; textureCoordinates = new float[numFaces * 2]; positions = new float[numFaces * 3]; int positionIndex = 0; int normalIndex = 0; int textureIndex = 0; for (String face : faces) { String[] parts = face.split("/"); int index = 3 * (Short.valueOf(parts[0]) - 1); positions[positionIndex++] = vertices.get(index++); positions[positionIndex++] = vertices.get(index++); positions[positionIndex++] = vertices.get(index); index = 2 * (Short.valueOf(parts[1]) - 1); textureCoordinates[normalIndex++] = textures.get(index++); // NOTE: Bitmap gets y-inverted textureCoordinates[normalIndex++] = 1 - textures.get(index); index = 3 * (Short.valueOf(parts[2]) - 1); this.normals[textureIndex++] = normals.get(index++); this.normals[textureIndex++] = normals.get(index++); this.normals[textureIndex++] = normals.get(index); } } } </code></pre>
1,929,415
Where do you put input file in eclipse(java) in order to read it from console command?
<p>I am writing a java program in eclipse(galileo version). The program reads simple user data from input file specified at console command and process it.</p> <p>But I am not sure where I should place this input file inside eclipse workspace, so that when I run program in eclipse and type in input file name, it can be found and program can process it.</p> <p>and is there way to set file path so that I can just place input file anywhere and specified the file path at runtime?</p> <p>thanks!</p>
1,929,436
3
0
null
2009-12-18 16:47:30.057 UTC
2
2009-12-18 17:17:22.753 UTC
null
null
null
null
234,683
null
1
9
java|eclipse|console|resources|workspace
65,614
<p>The Java process is started with the project directory as the working directory by default.</p>
1,380,938
Rails view helpers in helper file
<p>I'm probably missing something obvious here but here's what I'm trying to do.</p> <p>From the view, I'm calling a custom helper function </p> <pre><code>&lt;div&gt; &lt;%=display_services%&gt; &lt;/div&gt; </code></pre> <p>In the helper file with the display_services function</p> <pre><code>def display_services html = "&lt;div&gt;" form_for @user do |f| f.text_field ... end html &lt;&lt; "&lt;/div&gt;" end </code></pre> <p>I find that form_for method and f.text_field output directly to HTML stream without the div wrapper that I like. What is the proper syntax to output all the HTML in display_services? Thanks in advance for your help.</p>
1,381,388
3
0
null
2009-09-04 18:50:57.01 UTC
9
2012-03-17 22:19:38.187 UTC
2009-09-04 20:11:08.067 UTC
null
149,002
null
149,002
null
1
17
ruby-on-rails
26,441
<p>Just a suggestion for style, I like doing something like this:</p> <p>In your view:</p> <pre><code>&lt;% display_services %&gt; </code></pre> <p>Please note that the <code>=</code> isn't needed any more. The helper then uses <code>concat()</code> to append something to your page and the putting-long-strings-together thing is obsolete too:</p> <pre><code>def display_services concat("&lt;div&gt;") form_for @user do |f| f.text_field ... end concat("&lt;/div&gt;") end </code></pre> <p>Is it nessaccary to put the <code>&lt;div&gt;</code> tag into the helper. If you need a helper for embedding something into a block you could use some yield-magic as well:</p> <pre><code>def block_helper concat("&lt;div&gt;") yield concat("&lt;/div&gt;") end </code></pre> <p>And use it like this in your view - of course with helpers too:</p> <pre><code>&lt;% block_helper do %&gt; cool block&lt;br/&gt; &lt;% display_services %&gt; &lt;% end %&gt; </code></pre>
627,865
How does the ASP.NET Cache work?
<p>I am interested in using the ASP.NET Cache to decrease load times. How do I go about this? Where do I start? And how exactly does caching work?</p>
627,875
4
0
null
2009-03-09 20:21:21.913 UTC
12
2020-02-05 13:36:16.867 UTC
2009-03-10 14:42:21.267 UTC
BtBh
6,088
ShortBus
null
null
1
19
c#|asp.net|caching
5,862
<p>As applications grow it is quite normal to leverage caching as a way to gain scalability and keep consistent server response times. Caching works by storing data in memory to drastically decrease access times. To get started I would look at ASP.NET caching. </p> <p>There are 3 types of general Caching techniques in ASP.NET web apps:</p> <ul> <li>Page Output Caching(Page Level)</li> <li>Page Partial-Page Output(Specific Elements of the page)</li> <li>Programmatic or Data Caching</li> </ul> <p><strong>Output Caching</strong></p> <p>Page level output caching caches the html of a page so that each time ASP.NET page requested it checks the output cache first. You can vary these requests by input parameters(<a href="http://msdn.microsoft.com/en-us/library/system.web.ui.outputcacheparameters.varybyparam.aspx" rel="nofollow noreferrer">VaryByParam</a>) so the the page will only be cached for users where ID=1 if a requests come in where ID=2 asp.net cache is smart enough to know it needs to re-render the page. </p> <p><strong>Partial-Page Caching</strong></p> <p>a lot of times it wont make sense to cache the entire page in these circumstances you can use partial Page caching. This is usually used with user controls and is set the same way as page level only adding the OutputCache declarative inside the usercontrol. </p> <p><strong>Data Caching</strong></p> <p>You can store objects or values that are commonly used throughout the application. It can be as easy to as:</p> <pre><code>Cache["myobject"] = person; </code></pre> <p><strong>Enterprise Level Caching</strong></p> <p>It is worth mention that there are many Enterprise level caching architectures that have come about to leverage the effectiveness caching. <a href="http://sourceforge.net/projects/memcacheddotnet/" rel="nofollow noreferrer">Memcache</a> for .net and <a href="http://msdn.microsoft.com/en-gb/windowsserver/ee695849.aspx" rel="nofollow noreferrer">Velocity(now App Fabric)</a> are a couple. </p> <p><strong>In General</strong> </p> <p>You can't really make blanket statements on what you should and shouldn't cache because every application is different. However, you can make a few generalizations that hold true <strong>MOST</strong> of time. Static elements like images and content are OK to cache. Even a dynamic page that is getting hammered is worth caching for 5-10 seconds, it will make a world of difference to your web server.</p>
423,820
Integer.Parse vs. CInt
<p>Basically, I have been using both <code>Integer.Parse</code> and <a href="https://msdn.microsoft.com/en-us/library/s2dy91zy.aspx" rel="noreferrer">CInt</a> in most of my daily programming tasks, but I'm a little bit confused of what the difference is between the two.</p> <p>What is the difference between <code>Integer.Parse</code> and <code>CInt</code> in VB.NET?</p>
423,910
4
0
null
2009-01-08 10:38:22.617 UTC
5
2022-08-16 08:45:23.66 UTC
2015-08-25 12:28:34.25 UTC
null
63,550
KG Sosa
48,581
null
1
28
vb.net
47,850
<p><code>CInt</code> does a whole lot more than <a href="https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx?cs-save-lang=1&amp;cs-lang=vb" rel="nofollow noreferrer"><code>Integer.Parse</code></a>.</p> <p><code>CInt</code> will first check to see if what it was passed is an integer, and then simply casts it and returns it. If it's a double it will try to convert it without first converting the double to a string.</p> <p>See this from the help for <code>CInt</code> and other <a href="http://msdn.microsoft.com/en-us/library/s2dy91zy.aspx" rel="nofollow noreferrer">Type Conversion Functions</a></p> <blockquote> <p>Fractional Parts. When you convert a nonintegral value to an integral type, the integer conversion functions (CByte, CInt, CLng, CSByte, CShort, CUInt, CULng, and CUShort) remove the fractional part and round the value to the closest integer.</p> <p>If the fractional part is exactly 0.5, the integer conversion functions round it to the nearest even integer. For example, 0.5 rounds to 0, and 1.5 and 2.5 both round to 2. This is sometimes called banker's rounding, and its purpose is to compensate for a bias that could accumulate when adding many such numbers together.</p> </blockquote> <p>So in short, it does much more than convert a string to an integer, e.g. applying specific rounding rules to fractions, short circuiting unnecessary conversions etc.</p> <p>If what you're doing is converting a string to an integer, use <a href="https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx?cs-save-lang=1&amp;cs-lang=vb" rel="nofollow noreferrer"><code>Integer.Parse</code></a> (or <a href="https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx" rel="nofollow noreferrer"><code>Integer.TryParse</code></a>), if you're coercing an unknown value (e.g. a <code>variant</code> or <code>object</code> from a database) to an integer, use <code>CInt</code>.</p>
280,162
Is there a way to do a C++ style compile-time assertion to determine machine's endianness?
<p>I have some low level serialization code that is templated, and I need to know the system's endianness at compiletime obviously (because the templates specializes based on the system's endianness). </p> <p>Right now I have a header with some platform defines, but I'd rather have someway to make assertions about endianness with some templated test (like a static_assert or boost_if). Reason being my code will need to be compiled and ran on a wide range of machines, of many specialized vendor, and probably devices that don't exist in 2008, so I can't really guess what might need to go into that header years down the road. And since the code-base has an expected lifetime of about 10 years. So I can't follow the code for-ever.</p> <p>Hopefully this makes my situation clear.</p> <p>So does anyone know of a compile-time test that can determine endianness, without relying on vendor specific defines?</p>
280,526
4
0
null
2008-11-11 06:29:58.92 UTC
11
2019-01-14 04:58:18.85 UTC
2009-06-17 15:38:37.56 UTC
null
49,246
Robert Gould
15,124
null
1
32
c++|templates|metaprogramming|endianness
9,216
<p>If you're using autoconf, you can use the <code>AC_C_BIGENDIAN</code> macro, which is fairly guaranteed to work (setting the <code>WORDS_BIGENDIAN</code> define by default)</p> <p>alternately, you could try something like the following (taken from autoconf) to get a test that will probably be optimized away (GCC, at least, removes the other branch)</p> <pre><code>int is_big_endian() { union { long int l; char c[sizeof (long int)]; } u; u.l = 1; if (u.c[sizeof(long int)-1] == 1) { return 1; } else return 0; } </code></pre>
51,808,160
Keyof inferring string | number when key is only a string
<p>I define an <code>AbstractModel</code> like so:</p> <pre><code>export interface AbstractModel { [key: string]: any } </code></pre> <p>Then I declare the type <code>Keys</code>:</p> <pre><code>export type Keys = keyof AbstractModel; </code></pre> <p>I would expect that anything with the Keys type would be interpreted univocally as a string, for example:</p> <pre><code>const test: Keys; test.toLowercase(); // Error: Property 'toLowerCase' does not exist on type 'string | number'. Property 'toLowerCase' does not exist on type 'number'. </code></pre> <p>Is this a bug of Typescript (2.9.2), or am I missing something?</p>
51,808,262
3
0
null
2018-08-12 11:02:18.567 UTC
17
2020-12-23 08:05:26.943 UTC
null
null
null
null
1,068,250
null
1
86
typescript|typescript-typings
33,583
<p>As defined in the Release Notes of TypeScript 2.9, if you keyof an interface with a string index signature it returns a union of string and number</p> <blockquote> <p>Given an object type X, keyof X is resolved as follows:</p> <p>If X contains a string index signature, keyof X is a union of string, number, and the literal types representing symbol-like properties, otherwise</p> <p>If X contains a numeric index signature, keyof X is a union of number and the literal types representing string-like and symbol-like properties, otherwise</p> <p>keyof X is a union of the literal types representing string-like, number-like, and symbol-like properties.</p> </blockquote> <p><a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html" rel="noreferrer">source</a></p> <p>This is because: JavaScript converts numbers to strings when indexing an object:</p> <blockquote> <p>[..] when indexing with a number, JavaScript will actually convert that to a string before indexing into an object. That means that indexing with 100 (a number) is the same thing as indexing with "100" (a string), so the two need to be consistent.</p> </blockquote> <p><a href="https://www.typescriptlang.org/docs/handbook/interfaces.html#indexable-types" rel="noreferrer">source</a></p> <p>Example:</p> <pre><code>let abc: AbstractModel = { 1: "one", }; console.log(abc[1] === abc["1"]); // true </code></pre> <p>When you only want the string keys, then you could only extract the string keys from your interface like so:</p> <pre><code>type StringKeys = Extract&lt;keyof AbstractModel, string&gt;; const test: StringKeys; test.toLowerCase(); // no error </code></pre> <p>Also the TypeScript compiler provides an option to get the pre 2.9 behavior of <code>keyof</code>:</p> <blockquote> <p>keyofStringsOnly (boolean) default <code>false</code></p> <p>Resolve <code>keyof</code> to string valued property names only (no numbers or symbols).</p> </blockquote> <p><a href="https://www.typescriptlang.org/docs/handbook/compiler-options.html" rel="noreferrer">source</a></p>
55,621,632
Firestore - How to decrement integer value atomically in database?
<p>Firestore has recently launched a new feature to increment and decrement the integer values atomically.</p> <p>I can increment the integer value using</p> <p>For instance, <code>FieldValue.increment(50)</code></p> <p>But how to decrement ?</p> <p>I tried using <code>FieldValue.decrement(50)</code> But there is no method like decrement in FieldValue.</p> <p>It's not working.</p> <p><a href="https://firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html?linkId=65365800&amp;m=1" rel="noreferrer">https://firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html?linkId=65365800&amp;m=1</a></p>
55,621,706
2
0
null
2019-04-10 21:35:26.26 UTC
6
2020-05-15 17:15:03.793 UTC
null
null
null
null
11,271,986
null
1
36
android|firebase|google-cloud-firestore
10,718
<p>To decrement the value in a field, do a negative increment. So:</p> <pre><code>FieldValue.increment(-50) </code></pre>
2,414,111
Detecting when a space changes in Spaces in Mac OS X
<p>Let's say I want to write a simple Cocoa app to make the Spaces feature of Leopard more useful. I would like to configure each space to have, say, different</p> <ul> <li>screen resolutions</li> <li>keyboard layouts</li> <li>volume (for audio)</li> </ul> <p>So there are two parts to my question:</p> <ol> <li>I suppose there are ways to modify these three things independently of Spaces, right? If so, how?</li> <li>How can I detect in my app when a space change occurs, and when that happens, determine what space the user just switched to? Does Leopard send out some distributed notifications or something?</li> </ol> <p>Update: There has to be some public API way of doing this, judging from all the Spaces-related apps on the Mac App Store.</p>
6,241,708
2
0
null
2010-03-10 02:21:39.293 UTC
13
2012-02-23 03:32:35.207 UTC
2011-06-03 07:35:07.587 UTC
null
288,444
null
288,444
null
1
13
objective-c|cocoa|macos|osx-snow-leopard|osx-leopard
4,240
<p>As Peter says, in 10.6 you can use the <code>NSWorkSpace</code> <code>NSWorkspaceActiveSpaceDidChangeNotification</code> to get a notification when the workspace changes. </p> <p>You can then determine the current space using Quartz API, the <code>kCGWindowWorkspace</code> dictionary key holds the workspace. e.g: </p> <pre><code>int currentSpace; // get an array of all the windows in the current Space CFArrayRef windowsInSpace = CGWindowListCopyWindowInfo(kCGWindowListOptionAll | kCGWindowListOptionOnScreenOnly, kCGNullWindowID); // now loop over the array looking for a window with the kCGWindowWorkspace key for (NSMutableDictionary *thisWindow in (NSArray *)windowsInSpace) { if ([thisWindow objectForKey:(id)kCGWindowWorkspace]) { currentSpace = [thisWindow objectForKey(id)kCGWindowWorkspace] intValue]; break; } } </code></pre> <p>Alternatively you can get the Space using the private API, take a look at <a href="http://www.cocoadev.com/index.pl?CoreGraphicsPrivate" rel="noreferrer">CGSPrivate.h</a> which allows you to do this:</p> <pre><code>int currentSpace = 0; CGSGetWorkspace(_CGSDefaultConnection(), &amp;currentSpace); </code></pre> <p>To change the screen resolution you'll want to look at <a href="http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/Quartz_Services_Ref/Reference/reference.html" rel="noreferrer">Quartz services</a>, for altering the volume <a href="http://www.cocoadev.com/index.pl?SoundVolume" rel="noreferrer">this may be helpful</a>.</p>
2,374,951
How can I check the last time stats was run on Oracle without using OEM
<p>I want to check the last time stats was run on my Oracle 10g server. I would normally do this via OEM, but for unrelated reasons OEM is down. Is there some way I can check this using just sqlplus? It would be extra helpful if the output was reasonably formatted.</p>
2,375,268
2
0
null
2010-03-03 21:04:40.117 UTC
6
2010-03-03 21:52:04.607 UTC
null
null
null
null
25,915
null
1
25
oracle|oracle10g|sqlplus|statistics
100,822
<p>All of the following data dictionary tables have a LAST_ANALYZED column (replace * with USER/ALL/DBA as appropriate:</p> <pre><code>*_TABLES *_TAB_PARTITIONS *_TAB_SUBPARTITIONS *_INDEXES *_IND_PARTITIONS *_IND_SUBPARTITIONS </code></pre> <p>(There's lots more in the histograms fields, but I'm not going that deep.)</p> <p>Conversely, <code>ALL_TAB_MODIFICATIONS</code> shows rows inserted/updated/deleted (or the timestamp on which a table/partition/subpartition was truncated) since it had optimizer statistics gathered.</p>
3,089,773
How to change page orientation of PDF? (Ghostscript or PostScript solution needed)
<p>Given a PDF document, how do I change individual page orientation? </p> <p>I'm using latest version of Ghostscript.</p>
3,108,179
2
0
null
2010-06-22 02:05:47.75 UTC
4
2019-04-17 22:26:08.173 UTC
2015-06-18 15:47:58.513 UTC
null
359,307
null
253,976
null
1
25
pdf|postscript|ghostscript
57,777
<p>Why do you <strong><em>require</em></strong> usage of Ghostscript? Would it be acceptable to use another Free, Open Source Software tool running on the commandline, such as <code>pdftk</code>?</p> <p>Anyway, here is how to rotate pages with Ghostscript. However, this may not work for your intentions, because you cannot <strong>force</strong> a certain orientation for an individual page only. It relies on an internal Ghostscript algorithm that tries to rotate pages automatically, depending on the flow of text inside the PDFs:<br> * <code>-dAutoRotatePages=/None</code> -- retains orientation of each page;<br> * <code>-dAutoRotatePages=/All</code> -- rotates all pages (or none) depending on a kind of "majority decision";<br> * <code>-dAutoRotatePages=/PageByPage</code> -- auto-rotates pages individually. </p> <p>Add one of these to the Ghostscript commandline you're using.</p> <p>If there is <strong><em>no</em></strong> text on a page (or if there is an automatic page rotation set to <code>/None</code>), then Ghostscript uses the <code>setpagedevice</code> settings. You can pass such <code>setpagedevice</code> parameters on the Ghostscript commandline using the <code>-c</code> switch like this:<br> * <code>-c "&lt;&lt;/Orientation 3&gt;&gt; setpagedevice"</code> -- sets <em>landscape</em> orientation;<br> * <code>-c "&lt;&lt;/Orientation 0&gt;&gt; setpagedevice"</code> -- sets <em>portrait</em> orientation;<br> * <code>-c "&lt;&lt;/Orientation 2&gt;&gt; setpagedevice"</code> -- sets <em>upside down</em> orientation;<br> * <code>-c "&lt;&lt;/Orientation 1&gt;&gt; setpagedevice"</code> -- sets <em>seascape</em> orientation. </p> <p>Probably you need to set the orientation for each page when <em>extracting</em> the pages. I don't think it would work when merging them back to the unified document (I have never tested this).</p> <p>In any case, I'd recommend to look at <code>pdftk</code> too (which is also available for Windows). It is a commandline tool that can rotate pages from PDFs, and much more. Easier to use than Ghostscript for your stated purpose, and much faster as well. Especially, it can rotate individual pages inside a PDF document, leaving the other pages untouched. <strong><em>Example:</em></strong></p> <pre><code>pdftk A=in.pdf \ cat A1-3 A4west A5-end \ output out.pdf </code></pre> <p>This command will output pages 1, 2 and 3 as well as pages 5, 6, ... last un-rotated, but will rotate page 4 by 90 degrees (so the page header faces to the "west"). <sub>(However, be aware that this command can lead to unexpected results, depending on the original orientation of your input pages: You should check the orientation of all pages of your input PDF by running <code>pdfinfo -l 1000 input.pdf</code> and then check for the value of the <code>rot</code> output: if you see values different from <code>0</code>, like <code>90</code>, <code>180</code> and <code>270</code>, these pages are already pre-rotated...)</sub></p> <p>See here for more details: <a href="http://www.accesspdf.com/pdftk/" rel="noreferrer">http://www.accesspdf.com/pdftk/</a> .</p>
59,898,874
Enable Authorize button in springdoc-openapi-ui for Bearer Token Authentication (JWT)
<p>How to enable "Authorize" button in <a href="https://springdoc.github.io/springdoc-openapi-demos/" rel="noreferrer">springdoc-openapi-ui</a> (OpenAPI 3.0 <code>/swagger-ui.html</code>) for Bearer Token Authentication, for example JWT.</p> <p>What annotations have to be added to Spring <code>@Controller</code> and <code>@Configuration</code> classes?</p> <p><a href="https://i.stack.imgur.com/lMYcw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lMYcw.png" alt="Authorize button"></a></p> <p><a href="https://i.stack.imgur.com/ZTFeG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZTFeG.png" alt="Authorize form for Bearer Token Authentication"></a></p>
59,898,875
3
0
null
2020-01-24 14:56:24.333 UTC
19
2021-09-21 06:23:53.007 UTC
2020-01-27 22:58:05.057 UTC
null
7,873,775
null
7,873,775
null
1
43
java|spring|jwt|openapi|springdoc
30,276
<p>Define a global security scheme for OpenAPI 3.0 using annotation <code>@io.swagger.v3.oas.annotations.security.SecurityScheme</code> in a <code>@Configuration</code> bean:</p> <pre><code>@Configuration @OpenAPIDefinition(info = @Info(title = "My API", version = "v1")) @SecurityScheme( name = "bearerAuth", type = SecuritySchemeType.HTTP, bearerFormat = "JWT", scheme = "bearer" ) public class OpenApi30Config { } </code></pre> <p>Annotate each <code>@RestController</code> method requiring Bearer Token Authentication (JWT) with <code>@io.swagger.v3.oas.annotations.Operation</code> referencing the defined security scheme:</p> <pre><code>@Operation(summary = "My endpoint", security = @SecurityRequirement(name = "bearerAuth")) </code></pre>
2,020,363
How to change Global Windows Proxy using C# .NET with `Immediate Effect`
<p>I'm writing a Winform's (C# .NET) app to change Windows' Global (aka Internet Explorer's) proxy settings.</p> <p>I'm using this.</p> <pre><code>RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true); registry.SetValue("ProxyEnable", 1); registry.SetValue("ProxyServer", "127.0.0.1:8080"); </code></pre> <p>But its behaving in a weird manner. I tested this using two browsers</p> <ul> <li><strong>Google Chrome:</strong></li> </ul> <p>When I change/Disable the proxy while Chrome is running. Chrome is still using the previous proxy. The change is not effecting its process. But when I <em>JUST open</em> <code>Internet Options(inetcpl.cpl) &gt; Connections &gt; LAN Settings</code>. The previous change of proxy is now considered. When I said <em>Just open</em> I really mean <em>Just open</em>. I mean, not editing or clicking any other buttons. I guess, its then the global proxy is <strong>really</strong> getting changed (by reading from registry) &amp; Google Chrome is immediately taking the effect.</p> <ul> <li><strong>Internet Explorer 8:</strong></li> </ul> <p>Case with Internet Explorer is much worse. After changing/disabling the proxy using my app while IE is running &amp; Even after going to "Internet Options(inetcpl.cpl) > Connections > Lan Settings" The running IE proxy isn't getting affected. Not even if I open a new link in a new tab. I had to restart IE for that change to be incorporated.</p> <p>The behavior I want is that whenever I change proxy settings in my app, all the browsers which are using global proxy (irrespective of whether they are running or not) should <em>instantly</em> incorporate the change in settings.</p> <p>How can I achieve this?</p>
2,025,672
1
2
null
2010-01-07 12:53:50.967 UTC
13
2019-03-06 22:09:26.963 UTC
2011-11-28 03:04:46.82 UTC
null
214,668
null
193,653
null
1
19
c#|.net|proxy
24,687
<blockquote> <p>The behavior I want is that when ever I change proxy settings in my app, all the browsers which are using global proxy (irrespective of whether they are running or not) should instantly incorporate the change in settings.</p> <p>How can I achieve this?</p> </blockquote> <p>You need to refresh your system to achieve that.</p> <p>Add these lines at the beginning of your code:</p> <pre><code>using System.Runtime.InteropServices; using Microsoft.Win32; </code></pre> <p>Add this in the beginning of your class:</p> <pre><code>[DllImport("wininet.dll")] public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength); public const int INTERNET_OPTION_SETTINGS_CHANGED = 39; public const int INTERNET_OPTION_REFRESH = 37; static bool settingsReturn, refreshReturn; </code></pre> <p>And imply the code:</p> <pre><code>RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true); registry.SetValue("ProxyEnable", 1); registry.SetValue("ProxyServer", YOURPROXY); // These lines implement the Interface in the beginning of program // They cause the OS to refresh the settings, causing IP to realy update settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0); refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0); </code></pre>
35,303,490
Uncaught TypeError: Cannot read property 'props' of null
<ul> <li>I have a react code</li> <li>this code renders various panels in the UI.</li> <li>when I click a tag, this function is called sportsCornerPanel()</li> <li>but I am getting the Uncaught TypeError how to fix it</li> <li>providing snippet code below.</li> <li>whole code you can see it in the fiddle</li> </ul> <p><strong>code snippet</strong></p> <pre><code> sportsCornerPanel() { debugger; console.log("sportsCornerPanel" console.log("this.props.sportsPanelState.size--&gt;" + this.props); if (this.props.sportsPanelState.size === 'hidden') { if (!this.props.sportsPanelState.visible) { this.props.dispatch(sportsOpenPanel()); } else { this.props.dispatch(sportsClosePanel()); } } } render() { let sportsContent, leftNavLink; if (this.props.sports-layout !== 'small') { console.log("SportsBox---page loads at bigger size"); console.log("SportsBox---page loads at ipad size"); sportsContent = &lt;SportsBox className="sports-header"/&gt;; } else { if (this.props.sportsPanelState.visible) { console.log("sportsPanelState--when it becomes small--around ipad width"); sportsContent = &lt;SportsBox className="sports-nav"/&gt;; leftNavLink = &lt;a onClick={this.sportsCornerPanel} href="javascript:;" className="header-navLink active"&gt;&lt;/a&gt;; } else { if (this.props.sports.active) { console.log("SportsBox"); sportsContent = &lt;SportsBox className="sports-nav"/&gt;; } else { console.log("leftNavLink--when it becomes small--around ipad width"); leftNavLink = &lt;a onClick={this.sportsCornerPanel} href="javascript:;" className="header-navLink"&gt;&lt;/a&gt;; } } } output Uncaught TypeError: Cannot read property 'props' of null </code></pre>
35,305,456
4
0
null
2016-02-09 22:31:50.527 UTC
15
2019-06-24 10:05:00.127 UTC
2016-02-10 21:50:01.47 UTC
user5075509
null
user5075509
null
null
1
31
javascript|json|reactjs
67,836
<p>Since you are not using <code>React.createClass</code> in class methods <code>this</code> doesn't refers to the component instance, so you should bind it manually. There are several ways: </p> <p><strong>1. Manually bind <code>this</code> in class constructor</strong></p> <pre><code>constructor(props) { super(props); this.sportsCornerPanel= this.sportsCornerPanel.bind(this); } </code></pre> <p><strong>2. Use ES7 Property initializers with arrow function</strong></p> <pre><code>sportsCornerPanel = () =&gt; { debugger; console.log("sportsCornerPanel" console.log("this.props.sportsPanelState.size--&gt;" + this.props); if (this.props.sportsPanelState.size === 'hidden') { if (!this.props.sportsPanelState.visible) { this.props.dispatch(sportsOpenPanel()); } else { this.props.dispatch(sportsClosePanel()); } } } </code></pre> <p><strong>3. Bind <code>this</code> at call-site</strong></p> <p>In <code>render()</code> method:</p> <pre><code> let sportsContent, leftNavLink; if (this.props.sports-layout !== 'small') { console.log("SportsBox---page loads at bigger size"); console.log("SportsBox---page loads at ipad size"); sportsContent = &lt;SportsBox className="sports-header"/&gt;; } else { if (this.props.sportsPanelState.visible) { console.log("sportsPanelState--when it becomes small--around ipad width"); sportsContent = &lt;SportsBox className="sports-nav"/&gt;; leftNavLink = &lt;a onClick={this.sportsCornerPanel.bind(this)} href="javascript:;" className="header-navLink active"&gt;&lt;/a&gt;; } else { if (this.props.sports.active) { console.log("SportsBox"); sportsContent = &lt;SportsBox className="sports-nav"/&gt;; } else { console.log("leftNavLink--when it becomes small--around ipad width"); leftNavLink = &lt;a onClick={this.sportsCornerPanel.bind(this)} href="javascript:;" className="header-navLink"&gt;&lt;/a&gt;; } } } </code></pre>
20,739,575
How can I get a unique array based on object property using underscore
<p>I have an array of objects and I want to get a new array from it that is unique based only on a single property, is there a simple way to achieve this?</p> <p>Eg.</p> <pre><code>[ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ] </code></pre> <p>Would result in 2 objects with name = bill removed once.</p>
20,739,664
8
0
null
2013-12-23 08:23:59.31 UTC
5
2020-07-24 12:19:44.377 UTC
2013-12-23 08:33:23.21 UTC
null
249,933
null
506,565
null
1
51
javascript|underscore.js
57,164
<p>Use the <a href="http://underscorejs.org/#uniq" rel="noreferrer">uniq</a> function</p> <pre><code>var destArray = _.uniq(sourceArray, function(x){ return x.name; }); </code></pre> <p>or single-line version</p> <pre><code>var destArray = _.uniq(sourceArray, x =&gt; x.name); </code></pre> <p>From the docs:</p> <blockquote> <p>Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iterator function.</p> </blockquote> <p>In the above example, the function uses the objects name in order to determine uniqueness.</p>
18,804,850
EntityFramework Eager Load all Navigation Properties
<p>I'm using the Repository pattern with DI and IoC.</p> <p>I have created a function in my Repository:</p> <pre><code>T EagerGetById&lt;T&gt;(Guid id, string include) where T : class { return _dbContext.Set&lt;T&gt;().Include(include).Find(id); } </code></pre> <p>This will eagerly load one navigation property in my entity right.</p> <p>But if my entity looks like this:</p> <pre><code>public class Blog : PrimaryKey { public Author Author {get;set;} public ICollection&lt;Post&gt; Posts {get;set;} } </code></pre> <p>How would I get eager loading for <code>Author</code> and <code>Posts</code>? Would I literally have to do:</p> <pre><code>_dbContext.Set&lt;T&gt;().Include("Author").Include("Posts").Find(id); </code></pre> <p>inevitably producing a function like this:</p> <pre><code>T EagerGetById&lt;T&gt;(Guid id, string include, string include2, string include3) where T : class { return _dbContext.Set&lt;T&gt;().Include(include).Include(include2).Include(include3).Find(id); } </code></pre> <p>Because that would be really inefficient for a <code>Generic</code> Repository!</p>
18,805,096
2
0
null
2013-09-14 18:07:36.907 UTC
9
2016-11-24 10:45:56.69 UTC
2016-11-24 10:45:56.69 UTC
null
271,200
null
1,330,137
null
1
16
c#|entity-framework
19,527
<p>If you don't want to use strings, you can also do the same for any N number of includes by using an expression which returns the navigation properties to be eager loaded. (original source <a href="https://github.com/tugberkugurlu/GenericRepository/blob/master/src/GenericRepository.EntityFramework/EntityRepository%272.cs">here</a>)</p> <pre><code>public IQueryable&lt;TEntity&gt; GetAllIncluding(params Expression&lt;Func&lt;TEntity, object&gt;&gt;[] includeProperties) { IQueryable&lt;TEntity&gt; queryable = GetAll();    foreach (Expression&lt;Func&lt;TEntity, object&gt;&gt; includeProperty in includeProperties) {     queryable = queryable.Include&lt;TEntity, object&gt;(includeProperty);    } return queryable; } </code></pre>
27,558,605
Java 8: Parallel FOR loop
<p>I have heard Java 8 provides a lot of utilities regarding concurrent computing. Therefore I am wondering what is the simplest way to parallelise the given for loop?</p> <pre><code>public static void main(String[] args) { Set&lt;Server&gt; servers = getServers(); Map&lt;String, String&gt; serverData = new ConcurrentHashMap&lt;&gt;(); for (Server server : servers) { String serverId = server.getIdentifier(); String data = server.fetchData(); serverData.put(serverId, data); } } </code></pre>
27,558,698
4
0
null
2014-12-19 01:39:38.65 UTC
15
2019-07-12 13:03:46.617 UTC
2014-12-19 10:49:38.867 UTC
null
3,863,500
null
3,863,500
null
1
84
java|for-loop|concurrency|java.util.concurrent|concurrent-programming
92,564
<p>Read up on <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html">streams</a>, they're all the new rage.</p> <p>Pay especially close attention to the bit about parallelism: </p> <blockquote> <p>"Processing elements with an explicit for-loop is inherently serial. Streams facilitate parallel execution by reframing the computation as a pipeline of aggregate operations, rather than as imperative operations on each individual element. All streams operations can execute either in serial or in parallel."</p> </blockquote> <p>So to recap, there are no parallel for-loops, they're inherently serial. Streams however can do the job. Take a look at the following code:</p> <pre><code> Set&lt;Server&gt; servers = getServers(); Map&lt;String, String&gt; serverData = new ConcurrentHashMap&lt;&gt;(); servers.parallelStream().forEach((server) -&gt; { serverData.put(server.getIdentifier(), server.fetchData()); }); </code></pre>
43,562,880
SpringBoot unknown property in application.properties
<p>I've generated a Spring Boot web application using Spring Initializr, using embedded Tomcat + Thymeleaf template engine.</p> <p>I put this property in my application.properties</p> <pre><code>[email protected] </code></pre> <p>I am using Spring Tool Suite Version: 3.8.4.RELEASE as a development environment, but I got this warning in the Editor <code>'default.to.address' is an unknown property.</code></p> <p>Should I put this property in another property file ?</p>
43,562,950
5
0
null
2017-04-22 18:15:43.127 UTC
1
2020-07-13 02:10:07.207 UTC
null
null
null
null
4,450,024
null
1
20
java|spring|spring-mvc|spring-boot|properties-file
51,542
<p>It's because it's being opened by the STS properties editor which validates properties amongst other things. There's no harm in having it in the application.properties file, you can even add your own meta-data for the property. </p> <p><a href="http://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html" rel="noreferrer">http://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html</a></p>
46,607,828
Moshi/Kotlin - How to serialize NULL JSON strings into empty strings instead?
<p>I'm trying to write a null-safe String adapter that will serialize this JSON <code>{"nullString": null}</code> into this: <code>Model(nullString = "")</code> so that any JSON with a 'null' value that I expect to be a String will be replaced with <code>""</code> (assuming there exists a data class like this: <code>data class Model(val nullString: String)</code>)</p> <p>I wrote a custom adapter to try and handle this:</p> <pre><code>class NullStringAdapter: JsonAdapter&lt;String&gt;() { @FromJson override fun fromJson(reader: JsonReader?): String { if (reader == null) { return "" } return if (reader.peek() == NULL) "" else reader.nextString() } @ToJson override fun toJson(writer: JsonWriter?, value: String?) { writer?.value(value) } } </code></pre> <p>...in an attempt to solve this parsing error:</p> <p><code>com.squareup.moshi.JsonDataException: Expected a name but was NULL at path $.nullString</code></p> <p>Moshi parsing code:</p> <pre><code>val json = "{\"nullString\": null}" val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .add(NullStringAdapter()) .build() val result = moshi.adapter(Model::class.java).fromJson(configStr) </code></pre> <p>What am I missing here? Still new to moshi so any help is appreciated!</p>
46,612,778
1
0
null
2017-10-06 14:15:29.227 UTC
8
2017-10-07 09:31:31.117 UTC
null
null
null
null
1,452,741
null
1
11
json|null|kotlin|moshi
8,342
<p>The immediate problem is the missing <code>reader.nextNull()</code> call to consume the null value.</p> <p>There are a couple other cleanup things you can do here, too. With <code>@FromJson</code>, implementing <code>JsonAdapter</code> is unnecessary. Also, the JsonReader and JsonWriter are not nullable.</p> <pre><code>object NULL_TO_EMPTY_STRING_ADAPTER { @FromJson fun fromJson(reader: JsonReader): String { if (reader.peek() != JsonReader.Token.NULL) { return reader.nextString() } reader.nextNull&lt;Unit&gt;() return "" } } </code></pre> <p>and use add the adapter:</p> <pre><code>val moshi = Moshi.Builder() .add(NULL_TO_EMPTY_STRING_ADAPTER) .add(KotlinJsonAdapterFactory()) .build() </code></pre>