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
46,710,747
Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"'
<p>I get the following error in my application (npm 5.4.2, react 15.4, typescript 2.5.3, webpack 2.2.1, webpack-dev-server 2.4.1).</p> <p>This will work:</p> <pre><code>&lt;div style={{position: 'absolute'}}&gt;working&lt;/div&gt; </code></pre> <p>This will not compile:</p> <pre><code>const mystyle = { position: 'absolute' } &lt;div style={mystyle}&gt;not working&lt;/div&gt; </code></pre> <p>The compile error is:</p> <pre><code>ERROR in ./src/components/Resource.tsx (61,18): error TS2322: Type '{ style: { position: string; }; children: string; }' is not assignable to type 'DetailedHTMLProps&lt;HTMLAttributes&lt;HTMLDivElement&gt;, HTMLDivElement&gt;'. Type '{ style: { position: string; }; children: string; }' is not assignable to type 'HTMLAttributes&lt;HTMLDivElement&gt;'. Types of property 'style' are incompatible. Type '{ position: string; }' is not assignable to type 'CSSProperties'. Types of property 'position' are incompatible. Type 'string' is not assignable to type '"inherit" | "initial" | "unset" | "fixed" | "absolute" | "static" | "relative" | "sticky"'. webpack: Failed to compile. </code></pre> <p>But what't the difference? I can fix it with: </p> <pre><code>const mystyle = { position: 'absolute' as 'absolute' } </code></pre> <p>but is this a good solution? </p> <p>I don't have this problem with other style/css properties.</p> <p>I found a similar problem on github: <a href="https://github.com/Microsoft/TypeScript/issues/11465" rel="noreferrer">https://github.com/Microsoft/TypeScript/issues/11465</a> but if understand it right, it was a typescript bug in an ealier version. </p> <p>Any help appreciated.</p>
46,711,592
5
1
null
2017-10-12 13:21:15.597 UTC
11
2022-01-17 17:16:25.347 UTC
null
null
null
null
1,472,223
null
1
76
reactjs|typescript|webpack
46,937
<p>This is a workaround, but it is alright. Some other solution is:</p> <pre><code>const mystyles = { position: 'absolute', } as React.CSSProperties; </code></pre> <p>You can check back when this <a href="https://github.com/Microsoft/TypeScript/issues/16457" rel="noreferrer">issue</a> will be solved. Around TS 2.6 i guess, judging by milestones.</p>
8,874,987
Symfony2/Doctrine QueryBuilder using andwhere()
<p>I am using following method in a repository class to look for certain tags in my database:</p> <pre><code>public function getItemsByTag($tag, $limit = null) { $tag = '%'.$tag.'%'; $qb = $this-&gt;createQueryBuilder('c'); $qb-&gt;select('c') -&gt;where($qb-&gt;expr()-&gt;like('c.tags', '?1')) -&gt;setParameter(1, $tag) -&gt;addOrderBy('c.clicks', 'DESC'); if (false === is_null($limit)) $qb-&gt;setMaxResults($limit); return $qb-&gt;getQuery()-&gt;getResult(); } </code></pre> <p>This works just nice.. But: How can I add 2 additional variables (where: reviewed = 1, enabled = 1)? I tried andwhere() but I couldn't figure it out.</p> <p>I also found out that something like this:</p> <pre><code>public function getItems($limit = null) { $qb = $this-&gt;createQueryBuilder('b') -&gt;select('b') -&gt;add('where', 'b.reviewed = 1') -&gt;add('where', 'b.enabled = 1') -&gt;addOrderBy('b.name', 'ASC'); // ... } </code></pre> <p>won't work either...</p> <p>Any hints?</p>
8,876,905
2
0
null
2012-01-16 01:42:14.153 UTC
5
2013-09-26 14:26:31.573 UTC
null
null
null
null
804,670
null
1
12
doctrine|symfony
47,647
<p>I would write it like this:</p> <pre class="lang-php prettyprint-override"><code>$qb = $this -&gt;createQueryBuilder('c') -&gt;where('c.tags LIKE :tag') -&gt;andWhere('c.reviewed = 1') -&gt;andWhere('c.enabled = 1') -&gt;setParameter('tag', "%{$tag}%") -&gt;orderBy('c.clicks', 'DESC') -&gt;addOrderBy('b.name', 'ASC'); if ($limit) { $qb-&gt;setMaxResults($limit); } return $qb-&gt;getQuery()-&gt;getResult(); </code></pre> <p>You could also unite those <code>where</code> conditions:</p> <pre class="lang-php prettyprint-override"><code>-&gt;where('c.tags LIKE :tag AND c.reviewed = 1 AND c.enabled = 1') </code></pre>
9,010,734
Why do I need to nest a component with rendered="#{some}" in another component when I want to ajax-update it?
<p>So I've found a few answers close to this, and I've found enough to fix the problem I had. But even so, I'm curious as to understand the workings around this. Let me illustrate with an example :</p> <p>I have a facelet <code>.xhtml</code> page that looks like this (shortned).</p> <pre class="lang-xml prettyprint-override"><code>&lt;h:form id="resultForm"&gt; &lt;h:panelGroup class="search_form" layout="block"&gt; &lt;h:inputText id="lastname" value="#{search.lastname}"/&gt; &lt;h:commandButton action="#{search.find}" value="Find"&gt; &lt;f:ajax execute="lastname" render="resultDisplay"/&gt; &lt;/h:commandButton&gt; &lt;/h:panelGroup&gt; &lt;h:dataTable value="#{search.searchResults}" var="results" id="resultDisplay" rendered="#{!empty search.searchResults}"&gt; &lt;h:column&gt; #{results.field} &lt;/h:column&gt; &lt;/h:dataTable&gt; &lt;/h:form&gt; </code></pre> <p>Now, for the sake of breivity, I will not post all the backing bean code, but I have something of this sort :</p> <pre class="lang-java prettyprint-override"><code>public void find() { searchResults = setResults(true); } </code></pre> <p>Where <code>searchResults</code> is an <code>ArrayList&lt;Objects&gt;</code>. After a search, it is not null - checked in multiple tests (can be null, but not in the testing I am doing).</p> <p>Now. This does NOT work.</p> <p>But if I nest the <code>dataTable</code> inside another, let's say <code>panelGroup</code>, it will work.</p> <pre class="lang-xml prettyprint-override"><code>&lt;h:panelGroup id="resultDisplay"&gt; &lt;h:dataTable value="#{search.searchResults}" var="results" rendered="#{!empty search.searchResults}"&gt; &lt;h:column&gt; #{results.field} &lt;/h:column&gt; &lt;/h:dataTable&gt; &lt;/h:panelGroup&gt; </code></pre> <p>Now, this changes allows everything to work fine. I'd be okay with this... but I guess I am seeking a bit of understanding as well. Any insight as to why I have to nest these components? I am surely missing something!</p>
9,010,771
1
0
null
2012-01-25 21:41:30.763 UTC
27
2016-02-10 08:58:01.893 UTC
2016-02-10 08:58:01.893 UTC
null
157,882
null
686,036
null
1
35
jsf|jsf-2|facelets|conditional-rendering|ajax-update
22,012
<p>Ajax updating is performed by JavaScript language in the client side. All which JavaScript has access to is the HTML DOM tree. If JSF does not render any component to the HTML output, then there's nothing in the HTML DOM tree which can be obtained by JavaScript upon Ajax update. JavaScript cannot get the desired element by its ID.</p> <p>It will only work if you wrap the conditionally JSF-rendered component in another component which is <em>always</em> rendered to the HTML output and thus <em>always</em> present in the HTML DOM tree and thus <em>always</em> obtainable by JavaScript. Reference that wrapper component instead during ajax render/update.</p> <h3>See also:</h3> <ul> <li><a href="http://balusc.blogspot.com/2011/09/communication-in-jsf-20.html#AjaxRenderingOfContentWhichIsByItselfConditionallyRendered" rel="noreferrer">Communication in JSF2 - Ajax rendering of content which is by itself conditionally rendered</a></li> </ul>
27,244,132
What benefits does dictionary initializers add over collection initializers?
<p>In a recent past there has been a lot of talk about whats new in C# 6.0<br> One of the most talked about feature is using <code>Dictionary</code> initializers in C# 6.0<br> But wait we have been using collection initializers to initialize the collections and can very well initialize a <code>Dictionary</code> also in .NET 4.0 and .NET 4.5 (Don't know about old version) like</p> <pre><code>Dictionary&lt;int, string&gt; myDict = new Dictionary&lt;int, string&gt;() { { 1,"Pankaj"}, { 2,"Pankaj"}, { 3,"Pankaj"} }; </code></pre> <p>So what is there new in C# 6.0, What Dictionary Initializer they are talking about in C# 6.0</p>
27,244,282
3
1
null
2014-12-02 07:37:24.837 UTC
1
2020-03-06 13:06:50.867 UTC
2017-09-15 09:24:29.697 UTC
null
158,074
null
2,568,925
null
1
51
c#|dictionary|collections|c#-6.0|collection-initializer
17,702
<p>While you <em>could</em> initialize a dictionary with collection initializers, it's quite cumbersome. Especially for something that's supposed to be syntactic sugar.</p> <p>Dictionary initializers are much cleaner:</p> <pre><code>var myDict = new Dictionary&lt;int, string&gt; { [1] = "Pankaj", [2] = "Pankaj", [3] = "Pankaj" }; </code></pre> <p>More importantly these initializers aren't just for dictionaries, they can be used for <strong>any object supporting an indexer</strong>, for example <code>List&lt;T&gt;</code>:</p> <pre><code>var array = new[] { 1, 2, 3 }; var list = new List&lt;int&gt;(array) { [1] = 5 }; foreach (var item in list) { Console.WriteLine(item); } </code></pre> <p>Output:</p> <pre><code>1 5 3 </code></pre>
749,209
How do I Display Code Samples On Web Pages With Nice Syntax Styling Like Stack Overflow Does?
<p>I would like to be able to pull some code samples out of a database and/or have the text embedded into the website and then have the sample formatted in a code like fashion on the screen. While the text alone on the screen is great, the format will make it more user friendly. How is this done?</p> <p><strong>I want this:</strong><br><br> &nbsp;public string MyString = "The Sample Text"; <hr> <strong>To look like:</strong></p> <pre><code>public string MyString = "The Sample Text"; </code></pre> <p><hr> <strong>EDIT WITH ANSWER</strong><br> I took <a href="https://stackoverflow.com/questions/749209/display-code-samples-on-web-like-stackoverflow/749229#749229">Gortok's</a> suggestion and looked into <a href="http://code.google.com/p/google-code-prettify/" rel="nofollow noreferrer">Prettify.js</a> and its doing just what I had hoped. Here is how this is implemented.</p> <pre><code>&lt;head runat="server"&gt; &lt;script src="Scripts/prettify.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="Scripts/jquery-1.3.2.js" type="text/javascript"&gt;&lt;/script&gt; &lt;link href="Scripts/prettify.css" rel="stylesheet" type="text/css"&gt;&lt;/link&gt; &lt;/head&gt; &lt;body&gt; &lt;code class="prettyprint"&gt; public String HelloString = "New String"; &lt;/code&gt; &lt;script language="javascript"&gt; $().ready(function() { prettyPrint(); }); &lt;/script&gt; &lt;/body&gt; </code></pre>
749,229
3
0
null
2009-04-14 20:21:49.083 UTC
17
2015-01-05 23:48:14.787 UTC
2017-05-23 12:07:10.757 UTC
null
-1
null
55,747
null
1
11
asp.net|javascript|html|css
1,923
<p>Stack Overflow uses <a href="http://code.google.com/p/google-code-prettify/" rel="noreferrer">prettify.js</a> from Google.</p>
588,918
ImageMagick/Imagick convert PDF to JPG using native PHP API
<p>I’m attempting to convert PDF files into PNGs. It works great from the command line (I do have GhostScript 8.64 installed). But from PHP I’m having a problem:</p> <p>code:</p> <pre><code>$im = new Imagick($pdf_file); // this is where it throws the exception below </code></pre> <p>output:</p> <pre><code>Fatal error: Uncaught exception ‘ImagickException’ with message ‘Postscript delegate failed `23_1235606503.pdf’: No such file or directory @ pdf.c/ReadPDFImage/612′ in get_thumbnail.php:93 Stack trace: \#0 get_thumbnail.php(93): Imagick-&gt;__construct(’…’) </code></pre> <p>etc. etc.</p> <p>I'm not sure what I'm doing wrong here, but I suspect it has something to do with my server configuration somewhere. I'm running: Apache 2.2.11 PHP 5.2.8 ImageMagick 6.4.8-9 GhostScript 8.64</p>
591,466
3
0
null
2009-02-26 02:54:10.23 UTC
9
2016-12-21 22:46:32.323 UTC
2009-02-26 03:29:49.753 UTC
Norman Ramsey
41,661
matt
63,567
null
1
12
php|image|pdf|pdf-generation|ghostscript
25,760
<p>Finally figured this out. The GhostScript executable (<code>gs</code>) wasn't in Apache's environment path. It was in <code>/usr/local/bin</code>. Though I tried several ways to add <code>/usr/local/bin</code> to the path, I did not succeed. I ended up putting a symlink for <code>gs</code> in the <code>/usr/bin directory</code>. Now everything works perfectly.</p>
538,435
AES interoperability between .Net and iPhone?
<p>I need to encrypt a string on the iPhone and send it to a .Net web service for decryption. I am able to encrypt/decrypt on the iPhone and with .Net, but the encrypted strings from the iPhone cannot be decrypted by .Net. The error I get is "Padding is invalid and cannot be removed."</p> <p>The .Net code is from: <a href="http://blog.realcoderscoding.com/index.php/2008/07/dot-net-encryption-simple-aes-wrapper/" rel="noreferrer">http://blog.realcoderscoding.com/index.php/2008/07/dot-net-encryption-simple-aes-wrapper/</a></p> <p>The iPhone code uses the sample code from: <a href="http://nootech.wordpress.com/2009/01/17/symmetric-encryption-with-the-iphone-sdk/" rel="noreferrer">http://nootech.wordpress.com/2009/01/17/symmetric-encryption-with-the-iphone-sdk/</a></p> <p>AFAIK my key settings are the same:</p> <pre><code>result.BlockSize = 128; // iPhone: kCCBlockSizeAES128 result.KeySize = 128; // kCCBlockSizeAES128 result.Mode = CipherMode.CBC; result.Padding = PaddingMode.PKCS7; // kCCOptionPKCS7Padding </code></pre> <p>I tried different ways of generating ciphertext. hello/hello is:</p> <p>e0PnmbTg/3cT3W+92CDw1Q== in .Net </p> <p>yrKe5Z7p7MNqx9+CbBvNqQ== on iPhone</p> <p>and "openssl enc -aes-128-cbc -nosalt -a -in hello.txt -pass pass:hello" generates: QA+Ul+r6Zmr7yHipMcHSbQ==</p> <p>Update: <a href="http://dotmac.rationalmind.net/2009/02/aes-interoperability-between-net-and-iphone/" rel="noreferrer">I've posted the working code for this here</a>.</p>
539,928
3
3
null
2009-02-11 19:40:33.643 UTC
27
2016-02-03 14:01:44.647 UTC
2009-02-12 20:28:19.807 UTC
HeroicLife
65,244
HeroicLife
65,244
null
1
23
.net|iphone|encryption|aes
16,296
<p>At the very least, you are using differing initialization vectors (IV).</p> <ul> <li><p>The .Net code uses the key for IV.</p> <pre><code>private static AesCryptoServiceProvider GetProvider(byte[] key) { //Set up the encryption objects AesCryptoServiceProvider result = new AesCryptoServiceProvider(); byte[] RealKey = Encryptor.GetKey(key, result); result.Key = RealKey; result.IV = RealKey; return result; }</code></pre> <p>and </p> <pre><code>private static byte[] GetKey(byte[] suggestedKey, AesCryptoServiceProvider p) { byte[] kRaw = suggestedKey; List kList = new List(); for (int i = 0; i &lt; p.LegalKeySizes[0].MinSize; i += 8 ) { kList.Add(kRaw[i % kRaw.Length]); } byte[] k = kList.ToArray(); return k; }</code></pre> <p>which should probably be: <code>kList.Add(kRaw[(i / 8) % kRaw.Length]);</code>. Otherwise a key whose length % 8 == 0 will use the same letter repeatedly, doh!</p> <p>Thus the IV (and key) used by .Net is: <code>hleolhleolhleolh</code>. This is not part of the API, but rather due to the wrapper code that you pointed at (which has a serious bug in it...).</p></li> <li><p>The iPhone code uses 0 for IV.</p> <pre><code>// Initialization vector; dummy in this case 0's. uint8_t iv[kChosenCipherBlockSize]; memset((void *) iv, 0x0, (size_t) sizeof(iv));</code></pre></li> <li><p>openssl by default prepends a randomly generated salt (which is why the output is longer!).</p></li> </ul> <p>The openssl output is more secure since it is prepending a random initialization vector. It looks like the first few bytes of the base64 decoded string is "Salted__". You can also ask openssl to not use a salt (-nosalt) and / or provide an IV (-iv).</p> <p>Essentially, openssl, .Net, and the iPhone are using the same encryption, you just need to be careful how you initialize the APIs with the encryption key and the initialization vector.</p>
22,348,705
Best way to store DB config in Node.Js / Express app
<p>What would be the best way to store DB config (username, password) in an open source app that runs on node.js / Express? Two specific questions:</p> <ol> <li><p>Shall I put it into a separate config.js file in <code>/lib</code> folder, for example, and never include it into the master repository that is publicly available on GitHub?</p></li> <li><p>To inlcude the config, is it as simple as <code>require('./config.js')</code> from the file that needs it or is there a better way of doing it?</p></li> </ol> <p>PS sorry if the questions seem a bit simple or not so well formulated, but I'm just starting :)</p>
22,348,862
7
0
null
2014-03-12 10:33:14.77 UTC
35
2022-04-19 06:29:44.577 UTC
2017-02-24 12:23:37.203 UTC
null
2,360,798
null
712,347
null
1
77
javascript|node.js|express|config
70,082
<p>Not sure whether this is the best practice, but personally I have a <code>config.json</code> file where I store my db connection information. Then I do the following:</p> <pre><code>// options.js var fs = require('fs'), configPath = './config.json'; var parsed = JSON.parse(fs.readFileSync(configPath, 'UTF-8')); exports.storageConfig= parsed; </code></pre> <p>Then from a different file I do the following:</p> <pre><code>var options = require('./options'); var loginData = { host: options.storageConfig.HOST, user: options.storageConfig.user, password: options.storageConfig.password }; </code></pre>
20,383,647
Pandas selecting by label sometimes return Series, sometimes returns DataFrame
<p>In Pandas, when I select a label that only has one entry in the index I get back a Series, but when I select an entry that has more then one entry I get back a data frame.</p> <p>Why is that? Is there a way to ensure I always get back a data frame?</p> <pre><code>In [1]: import pandas as pd In [2]: df = pd.DataFrame(data=range(5), index=[1, 2, 3, 3, 3]) In [3]: type(df.loc[3]) Out[3]: pandas.core.frame.DataFrame In [4]: type(df.loc[1]) Out[4]: pandas.core.series.Series </code></pre>
20,384,317
8
0
null
2013-12-04 19:01:40.187 UTC
36
2022-05-06 18:44:56.377 UTC
2019-07-20 23:26:07.897 UTC
null
202,229
null
2,752,242
null
1
129
python|pandas|dataframe|slice|series
56,764
<p>Granted that the behavior is inconsistent, but I think it's easy to imagine cases where this is convenient. Anyway, to get a DataFrame every time, just pass a list to <code>loc</code>. There are other ways, but in my opinion this is the cleanest.</p> <pre><code>In [2]: type(df.loc[[3]]) Out[2]: pandas.core.frame.DataFrame In [3]: type(df.loc[[1]]) Out[3]: pandas.core.frame.DataFrame </code></pre>
24,041,220
Sending message to a specific ID in Socket.IO 1.0
<p>I want to sent data to one specific socket ID. </p> <p>We used to be able to do this in the older versions:</p> <pre><code>io.sockets.socket(socketid).emit('message', 'for your eyes only'); </code></pre> <p>How would I go about doing something similar in Socket.IO 1.0?</p>
24,224,146
7
0
null
2014-06-04 15:12:50.31 UTC
38
2021-10-15 13:48:28.93 UTC
null
null
null
user2283026
null
null
1
89
socket.io|socket.io-1.0
93,078
<p>In socket.io 1.0 they provide a better way for this. Each socket automatically joins a default room by self id. Check documents: <a href="http://socket.io/docs/rooms-and-namespaces/#default-room">http://socket.io/docs/rooms-and-namespaces/#default-room</a></p> <p>So you can emit to a socket by id with following code:</p> <pre><code>io.to(socketid).emit('message', 'for your eyes only'); </code></pre>
41,606,853
Error in commiting to git saying stCommitMsg file not found
<p>While I am trying to make a commit to my local git branch I got this error</p> <blockquote> <p>fatal: could not read '/Users/&lt;username&gt;/.stCommitMsg': No such file or directory</p> </blockquote> <p>I am able to commit using</p> <pre><code>git commit -m "commit message" </code></pre> <p>but I am unable to commit using</p> <pre><code>git commit </code></pre> <p>I am using macOS Sierra, and git version 2.10.1 (Apple Git-78)</p>
41,607,044
2
0
null
2017-01-12 06:53:16.893 UTC
4
2021-07-22 10:10:11.22 UTC
2017-01-12 07:28:28.123 UTC
null
7,256,199
null
5,077,507
null
1
30
git
9,678
<p>When run <code>git commit</code>, git will read from configure variable commit.template to find commit message template and load it to editor for you to write commit message.</p> <p>For your error, it seems that it try to find a template file of <code>'/Users/&lt;username&gt;/.stCommitMsg</code>. please create it for you or edit ~/.gitconfig to delete commit.template item.</p> <p>By the way, you can check your configuration by <code>git config --get commit.template</code></p>
20,190,668
Multiprocessing a for loop?
<p>I have an array (called <code>data_inputs</code>) containing the names of hundreds of astronomy images files. These images are then manipulated. My code works and takes a few seconds to process each image. However, it can only do one image at a time because I'm running the array through a <code>for</code> loop:</p> <pre><code>for name in data_inputs: sci=fits.open(name+'.fits') #image is manipulated </code></pre> <p>There is no reason why I have to modify an image before any other, so is it possible to utilise all 4 cores on my machine with each core running through the for loop on a different image?</p> <p>I've read about the <code>multiprocessing</code> module but I'm unsure how to implement it in my case. I'm keen to get <code>multiprocessing</code> to work because eventually I'll have to run this on 10,000+ images.</p>
20,192,251
4
0
null
2013-11-25 11:09:12.46 UTC
48
2022-04-17 02:44:32.877 UTC
2018-05-13 16:24:19.063 UTC
null
355,230
null
2,952,205
null
1
120
python|multiprocessing
191,859
<p>You can simply use <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool" rel="noreferrer"><code>multiprocessing.Pool</code></a>:</p> <pre><code>from multiprocessing import Pool def process_image(name): sci=fits.open('{}.fits'.format(name)) &lt;process&gt; if __name__ == '__main__': pool = Pool() # Create a multiprocessing Pool pool.map(process_image, data_inputs) # process data_inputs iterable with pool </code></pre>
20,011,138
PHPStorm - Run Filewatcher on existing files?
<p>I've installed the nodejs plugin in PHPStorm and setup the yuicompressor npm for minifying css/js. </p> <p>I got the file watcher working so that .min.css files are produced automatically whenever i make changes to .css/.js files in the project, but notice the file watcher only kicks in on existing files if I make a change to the file. </p> <p>So, if .css/.js files already exist in a project which do not require any changes, the newly defined file watcher doesn't run on them unless you go in and make a change on each file you want minified (or touched some other external way). </p> <p>Assuming you have an existing project with existing .css/.js files which don't require changes, is there an easy way to run PHPStorm File Watchers without having to change the files first? </p>
20,012,655
1
0
null
2013-11-15 21:44:48.753 UTC
13
2014-04-02 16:19:51.103 UTC
null
null
null
null
1,930,687
null
1
21
phpstorm
9,619
<ol> <li>Select such file(s)/folder(s) in Project View panel</li> <li><strong>"Help | Find Action"</strong> (<kbd>Ctrl + Shift + A</kbd>), activate check box for better results</li> <li>Search for "<code>run file w</code>" (without quotes, obviously) and choose <strong>Run File Watchers</strong> entry</li> </ol> <hr> <p><strong>Alternatively:</strong></p> <ol> <li><strong>"Settings | Keymap"</strong></li> <li>Find that <strong>Run File Watchers</strong> action (under "Plugins | File Watchers" branch)</li> <li>Assign some custom shortcut</li> <li>Select desired file(s)/folder(s) in Project View panel</li> <li>Use that shortcut from step 3</li> </ol> <hr> <p><strong>Alternatively:</strong></p> <ol> <li><strong>"Settings | Menus and Toolbars"</strong></li> <li>"Project View Popup Menu" branch</li> <li>Find desired location and click on "Add After..." button</li> <li>Locate <strong>Run File Watchers</strong> action (it's under "Plugins | File Watcher" branch) and click on "OK" button</li> <li>The action is now accessible via content menu in Project View panel and can be used on desired files and folders.</li> </ol>
5,683,793
Emoji (Emoticons) on Blackberry and Android App. How to support?
<p>I wonder how whatsapp gives support for that. I could use emojis on iPhone because it is natively supported. I'm not developing for bb neither android but I need to help a coder with this stuff. <br><br> The bb guy told me that he can add a font as a project resource (ttf), but since emojis are colored graphics, I'm not sure if i can create a ttf. I do not know anything about fonts either. <br><br> As you can see, my unknowledge is huge on this. I just need some tips that point me to the right way to research.<br><br> Thanks!</p>
5,698,761
3
3
null
2011-04-16 01:10:21.427 UTC
8
2013-10-08 13:39:35.54 UTC
2011-10-22 17:55:24.467 UTC
null
67,407
null
463,675
null
1
9
android|blackberry|fonts|emoticons|emoji
68,652
<p>On <strong>Android</strong> you can make a <a href="http://en.wikipedia.org/wiki/Computer_font#Bitmap_fonts" rel="noreferrer">BitMap font</a> with the tutorial i <a href="http://obviam.net/index.php/using-bitmap-fonts-in-android/" rel="noreferrer">found here</a>. Then you can embed all your Emoji into that font.</p> <p>For making this on the <strong>BlackBerry</strong> you can use the <a href="http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/ui/FontFamily.html" rel="noreferrer">FontFamily</a> class. <br>Here is a <a href="http://www.blackberryforums.com/developer-forum/100107-using-custom-fonts.html" rel="noreferrer">tutorial</a> that explains how this works.</p> <p>Have fun! :-)</p>
5,694,923
In Clojure how to choose a value if nil
<p>In Clojure what is the idiomatic way to test for nil and if something is nil then to substitute a value? </p> <p>For example I do this a lot:</p> <pre><code> let [ val (if input-argument input-argument "use default argument")] </code></pre> <p>: but I find it repetitive having to use "input-argument" twice.</p>
5,695,731
3
1
null
2011-04-17 16:56:28.967 UTC
8
2018-08-10 11:06:55.187 UTC
2018-08-10 11:06:55.187 UTC
null
2,311,567
null
190,822
null
1
29
clojure
16,629
<p>Alex's suggestion of "or" is indeed the idiomatic way to rewrite your example code, but note that it will not <em>only</em> replace <code>nil</code> values, but also those which are <code>false</code>.</p> <p>If you want to keep the value <code>false</code> but discard <code>nil</code>, you need:</p> <pre><code>(let [val (if (nil? input-argument) "use default argument" input-argument)] ...) </code></pre>
5,893,349
Java, How to add library files in netbeans?
<p>I am new to the Netbeans IDE and Java. I have a java project that shows lot of compilation errors: </p> <pre><code>can not import "org.apache.commons.logging.Log" </code></pre> <p>Can somebody please help me with these errors, How do I add library files in Netbeans IDE?</p>
5,893,518
4
0
null
2011-05-05 06:09:03.62 UTC
5
2020-11-09 03:36:30.39 UTC
2015-07-27 13:03:22.093 UTC
null
660,143
null
199,675
null
1
23
java|include-path|netbeans-6.9
167,716
<p>Quick solution in NetBeans 6.8.</p> <p>In the Projects window right-click on the name of the project that lacks library -> Properties -> The Project Properties window opens. In Categories tree select "Libraries" node -> On the right side of the Project Properties window press button "Add JAR/Folder" -> Select jars you need.</p> <p>You also can see my short <a href="http://youtu.be/vqhQY7U9Rlc" rel="noreferrer">Video How-To</a>.</p>
6,209,903
How to exclude dependencies from maven assembly plugin : jar-with-dependencies?
<p>Maven's assembly plugin enables the creation of a big jar including all dependencies with descriptorRef <code>jar-with-dependencies</code>.</p> <p>How can one exclude some of these dependencies? It seems like it does not have such a configuration? Is there another solution?</p>
6,210,532
4
1
null
2011-06-02 02:51:37.153 UTC
9
2022-04-12 22:00:16.337 UTC
2015-08-28 12:27:41.393 UTC
null
1,743,880
null
520,957
null
1
40
java|maven|jar|maven-assembly-plugin
42,241
<p>This <a href="http://maven.apache.org/plugins/maven-assembly-plugin/examples/single/including-and-excluding-artifacts.html" rel="nofollow noreferrer">example</a> indicates one way to do this:</p> <pre><code> &lt;dependencySets&gt; &lt;dependencySet&gt; .... &lt;excludes&gt; &lt;exclude&gt;commons-lang:commons-lang&lt;/exclude&gt; &lt;exclude&gt;log4j:log4j&lt;/exclude&gt; &lt;/excludes&gt; &lt;/dependencySet&gt; .... &lt;/dependencySets&gt; </code></pre> <p>Essentially we would use the <code>excludes</code> option available in <code>dependencySet</code>.</p> <p>See also: <a href="https://maven.apache.org/plugins/maven-assembly-plugin/assembly-component.html" rel="nofollow noreferrer">https://maven.apache.org/plugins/maven-assembly-plugin/assembly-component.html</a></p>
1,783,540
Spring JTA configuration - how to set TransactionManager?
<p>We configure our Spring transaction in Spring config as:</p> <pre><code>&lt;tx:jta-transaction-manager/&gt; </code></pre> <p>I gather this means that Spring will automatically discover the underlying JTA implementation. So when we start up JBoss we see these messages while Spring searches:</p> <pre><code>[JtaTransactionManager] [ ] No JTA TransactionManager found at fallback JNDI location [java:comp/Tran sactionManager] javax.naming.NameNotFoundException: TransactionManager not bound &lt;&lt;Big stack trace&gt;&gt; &lt;&lt;More of the same&gt;&gt; </code></pre> <p>And then eventually see:</p> <pre><code>[JtaTransactionManager] [ ] JTA TransactionManager found at fallback JNDI location [java:/Transaction Manager] [JtaTransactionManager] [ ] Using JTA UserTransaction: org.jboss.tm.usertx.client.ServerVMClientUserT ransaction@1f78dde </code></pre> <p>Question is - how can we edit our <code>&lt;tx:jta-transaction-manager/&gt;</code> tag to explicitly configure the <code>java:/Transaction Manager</code> JTA implementation so we avoid all these stack traces in the logs? (I'd prefer not to just change the Log4J logging levels)</p> <hr> <p><strong>Update</strong>: I replaced <code>&lt;tx:jta-transaction-manager/&gt;</code> with the below config and it seems to work.. i'm guessing this is alright?</p> <pre><code>&lt;bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"&gt; &lt;property name="transactionManagerName" value="java:/TransactionManager"/&gt; &lt;/bean&gt; </code></pre>
1,784,044
2
1
null
2009-11-23 14:41:42.433 UTC
10
2015-08-12 19:38:47.843 UTC
2009-11-23 16:06:00.783 UTC
null
7,034
null
47,281
null
1
13
java|spring|jboss|jta|spring-transactions
47,358
<p>Yes, that's alright. The stack trace you were seeing was also alright: <code>&lt;tx:jta-transaction-manager/&gt;</code> tries to acquire the transaction manager from a number of different standard locations; for every failed JNDI lookup, you'll see the <code>javax.naming.NameNotFoundException</code>.</p> <p><code>java:/TransactionManager</code> is where JBoss binds to by default; other servlet containers will default to <code>java:/comp/TransactionManager</code>, which I think is supposed to be the "standard" location for the TM.</p> <p>From the <a href="http://static.springsource.org/spring/docs/2.5.x/reference/transaction.html#transaction-application-server-integration" rel="noreferrer">Spring reference documentation</a>:</p> <blockquote> <p>For standard scenarios, including WebLogic, WebSphere and OC4J, consider using the convenient <code>&lt;tx:jta-transaction-manager/&gt;</code> configuration element. This will automatically detect the underlying server and choose the best transaction manager available for the platform. This means that you won't have to configure server-specific adapter classes (as discussed in the following sections) explicitly; they will rather be chosen automatically, with the standard <code>JtaTransactionManager</code> as default fallback.</p> </blockquote>
6,016,000
How to open phones gallery through code
<p>I wanna to open phones gallery through a button click.<br> In my activity I have a button, I want to open the gallery through that button click.</p>
6,016,352
5
1
null
2011-05-16 10:24:58.77 UTC
8
2021-03-31 15:01:11.89 UTC
2011-05-16 10:37:07.633 UTC
null
246,342
null
1,147,007
null
1
22
android
90,661
<p>Here is sample code for open gallery from app.</p> <pre><code>Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_IMAGE); </code></pre> <p>OnActivityResult for get image.</p> <pre><code>public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SELECT_IMAGE) { if (resultCode == Activity.RESULT_OK) { if (data != null) { try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData()); } catch (IOException e) { e.printStackTrace(); } } } else if (resultCode == Activity.RESULT_CANCELED) { Toast.makeText(getActivity(), "Canceled", Toast.LENGTH_SHORT).show(); } } } </code></pre>
6,069,368
Aggregate Function on Uniqueidentifier (GUID)
<p>Let's say I have the following table:</p> <pre><code>category | guid ---------+----------------------- A | 5BC2... A | 6A1C... B | 92A2... </code></pre> <p>Basically, I want to do the following SQL:</p> <pre><code>SELECT category, MIN(guid) FROM myTable GROUP BY category </code></pre> <p>It doesn't necessarily have to be MIN. I just want to return <em>one</em> GUID of each category. I don't care which one. Unfortunately, SQL Server does not allow MIN or MAX on GUIDs.</p> <p>Of course, I could convert the guid into a varchar, or create some nested TOP 1 SQL, but that seems like an ugly workaround. Is there some elegant solution that I've missed? </p>
6,069,422
5
2
null
2011-05-20 08:33:15.603 UTC
7
2015-03-03 11:10:42.123 UTC
null
null
null
null
87,698
null
1
48
sql|sql-server|guid|aggregate|uniqueidentifier
29,987
<p>Assuming you're using SQL Server 2005 or later:</p> <pre><code>;with Numbered as ( select category,guid,ROW_NUMBER() OVER (PARTITION BY category ORDER BY guid) rn from myTable ) select * from Numbered where rn=1 </code></pre>
6,039,050
difference between text file and binary file
<p>Why should we distinguish between text file and binary files when transmitting them? Why there are some channels designed only for textual data? At the bottom level, they are all bits.</p>
6,039,058
5
0
null
2011-05-18 01:49:24.393 UTC
20
2019-12-29 22:16:41.887 UTC
null
null
null
null
660,496
null
1
51
text-files|binaryfiles|file-type
31,826
<p>At the bottom level, they are all bits... true. However, some transmission channels have seven bits per byte, and other transmission channels have eight bits per byte. If you transmit ASCII text over a seven-bit channel, then all is fine. Binary data gets mangled.</p> <p>Additionally, different systems use different conventions for line endings: LF and CRLF are common, but some systems use CR or NEL. A text transmission mode will convert line endings automatically, which will damage binary files.</p> <p>However, this is all mostly of historical interest these days. Most transmission channels are eight bit (such as HTTP) and most users are fine with whatever line ending they get.</p> <p><strong>Some examples of 7-bit channels:</strong> SMTP (nominally, without extensions), SMS, Telnet, some serial connections. The internet wasn't always built on TCP/IP, and it shows.</p> <p>Additionally, the HTTP spec states that,</p> <blockquote> <p>When in canonical form, media subtypes of the "text" type use CRLF as the text line break. HTTP relaxes this requirement and allows the transport of text media with plain CR or LF alone representing a line break when it is done consistently for an entire entity-body.</p> </blockquote>
5,816,960
How to check is timezone identifier valid from code?
<p>I'll try to explain what's the problem here.</p> <p>According to <a href="http://php.net/manual/en/timezones.php">list of supported timezones</a> from PHP manual, I can see all valid TZ identifiers in PHP.</p> <p>My first question is how to get that list from code but that's not what I really need.</p> <p>My final goal is to write function <code>isValidTimezoneId()</code> that returns <strong>TRUE</strong> if timezone is valid, otherwise it should return <strong>FALSE</strong>.</p> <pre><code>function isValidTimezoneId($timezoneId) { # ...function body... return ?; # TRUE or FALSE } </code></pre> <p>So, when I pass TZ identifier using <code>$timezoneId</code> (string) in function I need boolean result.</p> <p>Well, what I have so far...</p> <h2>1) Solution using @ operator</h2> <p>First solution I've got is something like this:</p> <pre><code>function isValidTimezoneId($timezoneId) { $savedZone = date_default_timezone_get(); # save current zone $res = $savedZone == $timezoneId; # it's TRUE if param matches current zone if (!$res) { # 0r... @date_default_timezone_set($timezoneId); # try to set new timezone $res = date_default_timezone_get() == $timezoneId; # it's true if new timezone set matches param string. } date_default_timezone_set($savedZone); # restore back old timezone return $res; # set result } </code></pre> <p>That works perfectly, but I want another solution (to avoid trying to set wrong timezone)</p> <h2>2) Solution using <a href="http://www.php.net/manual/en/function.timezone-identifiers-list.php">timezone_identifiers_list()</a></h2> <p>Then, I was trying to get list of valid timezone identifiers and check it against parameter using <a href="http://php.net/manual/en/function.in-array.php">in_array()</a> function. So I've tried to use <a href="http://www.php.net/manual/en/function.timezone-identifiers-list.php">timezone_identifiers_list()</a>, but that was not so good because a lot of timezones was missing in array returned by this function (alias of <a href="http://www.php.net/manual/en/datetimezone.listidentifiers.php">DateTimeZone::listIdentifiers()</a>). At first sight that was exactly what I was looking for.</p> <pre><code>function isValidTimezoneId($timezoneId) { $zoneList = timezone_identifiers_list(); # list of (all) valid timezones return in_array($timezoneId, $zoneList); # set result } </code></pre> <p>This code looks nice and easy but than I've found that <code>$zoneList</code> array contains ~400 elements. According to my calculations it should return 550+ elements. 150+ elements are missing... So that's not good enough as solution for my problem.</p> <h2>3) Solution based on <a href="http://php.net/manual/en/datetimezone.listabbreviations.php">DateTimeZone::listAbbreviations()</a></h2> <p>This is last step on my way trying to find perfect solution. Using array returned by this method I can extract <strong>all</strong> timezone identifiers supported by PHP.</p> <pre><code>function createTZlist() { $tza = DateTimeZone::listAbbreviations(); $tzlist = array(); foreach ($tza as $zone) foreach ($zone as $item) if (is_string($item['timezone_id']) &amp;&amp; $item['timezone_id'] != '') $tzlist[] = $item['timezone_id']; $tzlist = array_unique($tzlist); asort($tzlist); return array_values($tzlist); } </code></pre> <p>This function returns 563 elements (in <code>Example #2</code> I've got <strong>just 407</strong>).</p> <p>I've tried to find differences between those two arrays:</p> <pre><code>$a1 = timezone_identifiers_list(); $a2 = createTZlist(); print_r(array_values(array_diff($a2, $a1))); </code></pre> <p>Result is:</p> <pre><code>Array ( [0] =&gt; Africa/Asmera [1] =&gt; Africa/Timbuktu [2] =&gt; America/Argentina/ComodRivadavia [3] =&gt; America/Atka [4] =&gt; America/Buenos_Aires [5] =&gt; America/Catamarca [6] =&gt; America/Coral_Harbour [7] =&gt; America/Cordoba [8] =&gt; America/Ensenada [9] =&gt; America/Fort_Wayne [10] =&gt; America/Indianapolis [11] =&gt; America/Jujuy [12] =&gt; America/Knox_IN [13] =&gt; America/Louisville [14] =&gt; America/Mendoza [15] =&gt; America/Porto_Acre [16] =&gt; America/Rosario [17] =&gt; America/Virgin [18] =&gt; Asia/Ashkhabad [19] =&gt; Asia/Calcutta [20] =&gt; Asia/Chungking [21] =&gt; Asia/Dacca [22] =&gt; Asia/Istanbul [23] =&gt; Asia/Katmandu [24] =&gt; Asia/Macao [25] =&gt; Asia/Saigon [26] =&gt; Asia/Tel_Aviv [27] =&gt; Asia/Thimbu [28] =&gt; Asia/Ujung_Pandang [29] =&gt; Asia/Ulan_Bator [30] =&gt; Atlantic/Faeroe [31] =&gt; Atlantic/Jan_Mayen [32] =&gt; Australia/ACT [33] =&gt; Australia/Canberra [34] =&gt; Australia/LHI [35] =&gt; Australia/NSW [36] =&gt; Australia/North [37] =&gt; Australia/Queensland [38] =&gt; Australia/South [39] =&gt; Australia/Tasmania [40] =&gt; Australia/Victoria [41] =&gt; Australia/West [42] =&gt; Australia/Yancowinna [43] =&gt; Brazil/Acre [44] =&gt; Brazil/DeNoronha [45] =&gt; Brazil/East [46] =&gt; Brazil/West [47] =&gt; CET [48] =&gt; CST6CDT [49] =&gt; Canada/Atlantic [50] =&gt; Canada/Central [51] =&gt; Canada/East-Saskatchewan [52] =&gt; Canada/Eastern [53] =&gt; Canada/Mountain [54] =&gt; Canada/Newfoundland [55] =&gt; Canada/Pacific [56] =&gt; Canada/Saskatchewan [57] =&gt; Canada/Yukon [58] =&gt; Chile/Continental [59] =&gt; Chile/EasterIsland [60] =&gt; Cuba [61] =&gt; EET [62] =&gt; EST [63] =&gt; EST5EDT [64] =&gt; Egypt [65] =&gt; Eire [66] =&gt; Etc/GMT [67] =&gt; Etc/GMT+0 [68] =&gt; Etc/GMT+1 [69] =&gt; Etc/GMT+10 [70] =&gt; Etc/GMT+11 [71] =&gt; Etc/GMT+12 [72] =&gt; Etc/GMT+2 [73] =&gt; Etc/GMT+3 [74] =&gt; Etc/GMT+4 [75] =&gt; Etc/GMT+5 [76] =&gt; Etc/GMT+6 [77] =&gt; Etc/GMT+7 [78] =&gt; Etc/GMT+8 [79] =&gt; Etc/GMT+9 [80] =&gt; Etc/GMT-0 [81] =&gt; Etc/GMT-1 [82] =&gt; Etc/GMT-10 [83] =&gt; Etc/GMT-11 [84] =&gt; Etc/GMT-12 [85] =&gt; Etc/GMT-13 [86] =&gt; Etc/GMT-14 [87] =&gt; Etc/GMT-2 [88] =&gt; Etc/GMT-3 [89] =&gt; Etc/GMT-4 [90] =&gt; Etc/GMT-5 [91] =&gt; Etc/GMT-6 [92] =&gt; Etc/GMT-7 [93] =&gt; Etc/GMT-8 [94] =&gt; Etc/GMT-9 [95] =&gt; Etc/GMT0 [96] =&gt; Etc/Greenwich [97] =&gt; Etc/UCT [98] =&gt; Etc/UTC [99] =&gt; Etc/Universal [100] =&gt; Etc/Zulu [101] =&gt; Europe/Belfast [102] =&gt; Europe/Nicosia [103] =&gt; Europe/Tiraspol [104] =&gt; Factory [105] =&gt; GB [106] =&gt; GB-Eire [107] =&gt; GMT [108] =&gt; GMT+0 [109] =&gt; GMT-0 [110] =&gt; GMT0 [111] =&gt; Greenwich [112] =&gt; HST [113] =&gt; Hongkong [114] =&gt; Iceland [115] =&gt; Iran [116] =&gt; Israel [117] =&gt; Jamaica [118] =&gt; Japan [119] =&gt; Kwajalein [120] =&gt; Libya [121] =&gt; MET [122] =&gt; MST [123] =&gt; MST7MDT [124] =&gt; Mexico/BajaNorte [125] =&gt; Mexico/BajaSur [126] =&gt; Mexico/General [127] =&gt; NZ [128] =&gt; NZ-CHAT [129] =&gt; Navajo [130] =&gt; PRC [131] =&gt; PST8PDT [132] =&gt; Pacific/Ponape [133] =&gt; Pacific/Samoa [134] =&gt; Pacific/Truk [135] =&gt; Pacific/Yap [136] =&gt; Poland [137] =&gt; Portugal [138] =&gt; ROC [139] =&gt; ROK [140] =&gt; Singapore [141] =&gt; Turkey [142] =&gt; UCT [143] =&gt; US/Alaska [144] =&gt; US/Aleutian [145] =&gt; US/Arizona [146] =&gt; US/Central [147] =&gt; US/East-Indiana [148] =&gt; US/Eastern [149] =&gt; US/Hawaii [150] =&gt; US/Indiana-Starke [151] =&gt; US/Michigan [152] =&gt; US/Mountain [153] =&gt; US/Pacific [154] =&gt; US/Pacific-New [155] =&gt; US/Samoa [156] =&gt; Universal [157] =&gt; W-SU [158] =&gt; WET [159] =&gt; Zulu ) </code></pre> <p>This list contains all valid TZ identifiers that <code>Example #2</code> failed to match.</p> <p>There's four TZ identifiers more (part of <code>$a1</code>):</p> <pre><code>print_r(array_values(array_diff($a1, $a2))); </code></pre> <p>Output</p> <pre><code>Array ( [0] =&gt; America/Bahia_Banderas [1] =&gt; Antarctica/Macquarie [2] =&gt; Pacific/Chuuk [3] =&gt; Pacific/Pohnpei ) </code></pre> <p>So now, I have almost perfect solution...</p> <pre><code>function isValidTimezoneId($timezoneId) { $zoneList = createTZlist(); # list of all valid timezones (last 4 are not included) return in_array($timezoneId, $zoneList); # set result } </code></pre> <p>That's my solution and I can use it. Of course, I use this function as part of class so I don't need to generate <code>$zoneList</code> on every methods call.</p> <h2>What I really need here?</h2> <p>I'm wondering, is there any easier (quicker) solution to get list of all valid timezone identifiers as array (I want to avoid extracting that list from <code>DateTimeZone::listAbbreviations()</code> if that's possible)? Or if you know another way how to check <strong>is timezone parameter valid</strong>, please let me know (I repeat, <code>@</code> operator can't be part of solution).</p> <p><hr> P.S. If you need more details and examples, let me know. I guess you don't.</p> <p>I'm using <code>PHP 5.3.5</code> (think that's not important).</p> <hr> <h2>Update</h2> <p>Any part of code that throws exception on invalid timezone string (hidden using <code>@</code> or caught using <code>try..catch</code> block) is not solution I'm looking for.</p> <p><hr></p> <h2>Another update</h2> <p><strong>I've put small bounty on this question!</strong></p> <p>Now I'm looking for the easiest way how to extract list of <strong>all</strong> timezone identifiers in PHP array.</p>
5,878,722
8
0
null
2011-04-28 10:09:57.39 UTC
9
2020-10-05 09:52:12.403 UTC
2011-05-03 14:03:11.113 UTC
null
679,733
null
679,733
null
1
39
php|validation|datetime|time|timezone
18,455
<p>You solution works fine, so if it's speed you're looking for I would look more closely at what you're doing with your arrays. I've timed a few thousand trials to get reasonable average times, and these are the results:</p> <pre><code>createTZlist : 20,713 microseconds per run createTZlist2 : 13,848 microseconds per run </code></pre> <p>Here's the faster function:</p> <pre><code>function createTZList2() { $out = array(); $tza = timezone_abbreviations_list(); foreach ($tza as $zone) { foreach ($zone as $item) { $out[$item['timezone_id']] = 1; } } unset($out['']); ksort($out); return array_keys($out); } </code></pre> <p>The <code>if</code> test is faster if you reduce it to just <code>if ($item['timezone_id'])</code>, but rather than running it 489 times to catch a single case, it's quicker to unset the empty key afterwards.</p> <p>Setting hash keys allows us the skip the <code>array_unique()</code> call which is more expensive. Sorting the keys and then extracting them is a tiny bit faster than extracting them and then sorting the extracted list.</p> <p>If you drop the sorting (which is not needed unless you're comparing the list), it gets down to 12,339 microseconds.</p> <p>But really, you don't need to return the keys anyway. Looking at the holistic <code>isValidTimezoneId()</code>, you'd be better off doing this:</p> <pre><code>function isValidTimezoneId2($tzid) { $valid = array(); $tza = timezone_abbreviations_list(); foreach ($tza as $zone) { foreach ($zone as $item) { $valid[$item['timezone_id']] = true; } } unset($valid['']); return !!$valid[$tzid]; } </code></pre> <p>That is, assuming you only need to test once per execution, otherwise you'd want to save <code>$valid</code> after the first run. This approach avoids having to do a sort or converting the keys to values, key lookups are faster than in_array() searches and there's no extra function call. Setting the array values to <code>true</code> instead of <code>1</code> also removes a single cast when the result is true.</p> <p>This brings it reliably down to under 12ms on my test machine, almost half the time of your example. A fun experiment in micro-optimizations!</p>
5,731,234
How to get the start time of a long-running Linux process?
<p>Is it possible to get the start time of an old running process? It seems that <code>ps</code> will report the date (not the time) if it wasn't started today, and only the year if it wasn't started this year. Is the precision lost forever for old processes?</p>
5,731,337
8
12
null
2011-04-20 13:38:27.93 UTC
84
2021-10-18 16:16:21.33 UTC
null
null
null
null
512,652
null
1
333
linux|bash|process
273,554
<p>You can specify a formatter and use <code>lstart</code>, like this command:</p> <pre><code>ps -eo pid,lstart,cmd </code></pre> <p>The above command will output all processes, with formatters to get PID, command run, and date+time started.</p> <p>Example (from Debian/Jessie command line)</p> <pre><code>$ ps -eo pid,lstart,cmd PID CMD STARTED 1 Tue Jun 7 01:29:38 2016 /sbin/init 2 Tue Jun 7 01:29:38 2016 [kthreadd] 3 Tue Jun 7 01:29:38 2016 [ksoftirqd/0] 5 Tue Jun 7 01:29:38 2016 [kworker/0:0H] 7 Tue Jun 7 01:29:38 2016 [rcu_sched] 8 Tue Jun 7 01:29:38 2016 [rcu_bh] 9 Tue Jun 7 01:29:38 2016 [migration/0] 10 Tue Jun 7 01:29:38 2016 [kdevtmpfs] 11 Tue Jun 7 01:29:38 2016 [netns] 277 Tue Jun 7 01:29:38 2016 [writeback] 279 Tue Jun 7 01:29:38 2016 [crypto] ... </code></pre> <p>You can read <code>ps</code>'s manpage or <a href="http://pubs.opengroup.org/onlinepubs/9699919799/" rel="noreferrer">check Opengroup's page</a> for the other formatters.</p>
5,742,543
An invalid XML character (Unicode: 0xc) was found
<p>Parsing an XML file using the Java DOM parser results in:</p> <pre><code>[Fatal Error] os__flag_8c.xml:103:135: An invalid XML character (Unicode: 0xc) was found in the element content of the document. org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0xc) was found in the element content of the document. at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at javax.xml.parsers.DocumentBuilder.parse(Unknown Source) </code></pre>
5,742,563
10
0
null
2011-04-21 10:05:44.45 UTC
18
2021-11-29 16:47:54.997 UTC
2015-05-06 16:47:42.527 UTC
null
2,777,965
null
644,474
null
1
45
java|xml|dom|xml-parsing
189,666
<p>There are a few characters that are dissallowed in XML documents, even when you encapsulate data in CDATA-blocks.</p> <p>If you generated the document you will need to <strike>entity encode it or</strike> strip it out. If you have an errorneous document, you should strip away these characters before trying to parse it.</p> <p>See dolmens answer in this thread: <a href="https://stackoverflow.com/questions/730133/invalid-characters-in-xml">Invalid Characters in XML</a></p> <p>Where he links to this article: <a href="http://www.w3.org/TR/xml/#charsets" rel="noreferrer">http://www.w3.org/TR/xml/#charsets</a></p> <p>Basically, all characters below 0x20 is disallowed, except 0x9 (TAB), 0xA (CR?), 0xD (LF?) </p>
55,606,800
Create Pull Request Button is disabled
<p>I would like to make a pull request from my fork repo to the upstream repository.</p> <p>As always I was following these steps <a href="https://help.github.com/en/articles/creating-a-pull-request-from-a-fork" rel="noreferrer">here</a> from <strong>the guidance from Github.</strong></p> <p>But this time I can not make a pull request, as the button is <em>disabled.</em></p> <p>The branches can be automatically merged.</p> <p>I do have changes in my forked repo and I can see commits made. Base repo and head repo are indicated correctly.</p>
55,633,299
9
6
null
2019-04-10 07:17:16.773 UTC
4
2022-07-21 14:39:55.893 UTC
2021-11-10 13:43:58.957 UTC
null
1,201,863
null
11,257,110
null
1
46
github|pull-request
27,029
<p>From Github Developer Support:</p> <blockquote> <p>Also, I know this might seem strange, but could you try selecting the base repo/branch from the drop down list (even if this already seems selected), and give this another go. It could that, for whatever reason, the pull request creation flow isn't picking this up implicitly.</p> </blockquote> <p>I have also logged out and logged in again.</p> <p>After that, everything was fine!</p>
46,257,633
iOS 11 - Is in app purchase testing using a sandbox user keeps asking to sign in for anyone else too? Forever loop?
<p>I am testing a non-consumable IAP on an iPhone 6s running iOS 11 GM. Whenever I tap my "Buy" button, it asks me to sign in. I tap "Sign in with existing apple ID" and enter my sandbox user details (which worked fine as of a few days ago on iOS 10).</p> <p>After entering, it just goes back to the same "Sign in" screen. I tried entering a few more times and it just goes back to the same screen again. Keeps looping forever.</p> <p>Is this down for anyone else?</p>
46,364,900
5
2
null
2017-09-16 19:22:16.667 UTC
8
2020-03-17 11:28:48.387 UTC
2017-10-13 16:45:14.85 UTC
null
7,506,896
null
1,634,905
null
1
38
ios|iphone|in-app-purchase|app-store-connect|ios11
8,202
<p>The same thing happens for me, for three separate sandbox users which were created before iOS 11 release. (The problem seems prevalent on iOS 11, there are posts on reddit and apple forums reporting this issue) </p> <p>It seems creating new fresh sandbox user is the way to go. Sandbox users created after iOS 11 release work, while those created before the release cause "Sign in/Create Apple id" alert loop.</p>
19,779,483
PL/SQL ORA-01422: exact fetch returns more than requested number of rows
<p>I get keep getting this error I can't figure out what is wrong.</p> <blockquote> <p>DECLARE<br> *<br> ERROR at line 1:<br> ORA-01422: exact fetch returns more than requested number of rows<br> ORA-06512: at line 11</p> </blockquote> <p>Here is my code.</p> <pre><code>DECLARE rec_ENAME EMPLOYEE.ENAME%TYPE; rec_JOB EMPLOYEE.DESIGNATION%TYPE; rec_SAL EMPLOYEE.SALARY%TYPE; rec_DEP DEPARTMENT.DEPT_NAME%TYPE; BEGIN SELECT EMPLOYEE.EMPID, EMPLOYEE.ENAME, EMPLOYEE.DESIGNATION, EMPLOYEE.SALARY, DEPARTMENT.DEPT_NAME INTO rec_EMPID, rec_ENAME, rec_JOB, rec_SAL, rec_DEP FROM EMPLOYEE, DEPARTMENT WHERE EMPLOYEE.SALARY &gt; 3000; DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec_EMPID); DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------'); DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec_ENAME); DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------'); DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec_JOB); DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------'); DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec_SAL); DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------'); DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec_DEP); END; / </code></pre>
19,779,546
1
0
null
2013-11-04 23:46:08.427 UTC
10
2021-02-08 19:28:06.357 UTC
2017-08-20 18:11:51.077 UTC
null
146,325
null
2,954,433
null
1
30
oracle|plsql|oracle11g|sqlplus
199,977
<p>A <code>SELECT INTO</code> statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a <code>no_data_found</code> exception. If it returns more than 1 row, you'll get a <code>too_many_rows</code> exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a <code>SELECT INTO</code> statement here.</p> <p>Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a <code>departmentID</code> column in both tables)</p> <pre><code>BEGIN FOR rec IN (SELECT EMPLOYEE.EMPID, EMPLOYEE.ENAME, EMPLOYEE.DESIGNATION, EMPLOYEE.SALARY, DEPARTMENT.DEPT_NAME FROM EMPLOYEE, DEPARTMENT WHERE employee.departmentID = department.departmentID AND EMPLOYEE.SALARY &gt; 3000) LOOP DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID); DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------'); DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME); DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------'); DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION); DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------'); DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY); DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------'); DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME); END LOOP; END; </code></pre> <p>I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use <code>dbms_output</code> like this and would not depend on anyone seeing data that you write to the <code>dbms_output</code> buffer.</p>
39,690,094
Spring-boot default profile for integration tests
<p>Spring-boot utilizes <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html" rel="noreferrer">Spring profiles</a> which allow for instance to have separate config for different environments. One way I use this feature is to configure test database to be used by integration tests. I wonder however is it necessary to create my own profile 'test' and explicitly activate this profile in each test file? Right now I do it in the following way:</p> <ol> <li><p>Create application-test.properties inside src/main/resources</p> </li> <li><p>Write test specific config there (just the database name for now)</p> </li> <li><p>In every test file include:</p> <pre><code>@ActiveProfiles(&quot;test&quot;) </code></pre> </li> </ol> <p>Is there a smarter / more concise way? For instance a default test profile?</p> <p>Edit 1: This question pertains to Spring-Boot 1.4.1</p>
39,690,595
14
0
null
2016-09-25 18:05:54.963 UTC
29
2022-08-12 20:10:48.203 UTC
2021-04-30 20:30:56.73 UTC
null
254,477
null
854,603
null
1
133
java|spring|spring-boot
178,213
<p>As far as I know there is nothing directly addressing your request - but I can suggest a proposal that could help:</p> <p>You could use your own test annotation that is a <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-meta-annotations" rel="noreferrer">meta annotation</a> comprising <code>@SpringBootTest</code> and <code>@ActiveProfiles("test")</code>. So you still need the dedicated profile but avoid scattering the profile definition across all your test.</p> <p>This annotation will default to the profile <code>test</code> and you can override the profile using the meta annotation.</p> <pre><code>@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @SpringBootTest @ActiveProfiles public @interface MyApplicationTest { @AliasFor(annotation = ActiveProfiles.class, attribute = "profiles") String[] activeProfiles() default {"test"}; } </code></pre>
33,355,444
R - when trying to install package: InternetOpenUrl failed
<p>Since I've updated both R (to 3.2.2) and RStudio (to 0.99.486) in Win 7, I'm experiencing problems downloading packages.</p> <p>I'm aware of the questions asked <a href="https://stackoverflow.com/questions/25599943/unable-to-install-packages-in-latest-version-of-rstudio-and-r-version-3-1-1">here</a> but neither</p> <pre><code>setInternet2(TRUE) </code></pre> <p>nor changing the CRAN mirror helped. The "Tools -> Global Options -> Packages -> "Use Internet Explorer library/proxy for HTTP" was also already unchecked and I made sure that my Firefox uses no proxy.</p> <p>I tried </p> <pre><code>setRepositories() </code></pre> <p>as well as manually installing the package with</p> <pre><code>install.packages('dplyr', repos='https://cran.uni-muenster.de/') </code></pre> <p>but I still get the message:</p> <pre><code>Warning in install.packages : InternetOpenUrl failed: 'Der Servername oder die Serveradresse konnte nicht verarbeitet werden.' Warning in install.packages : InternetOpenUrl failed: 'Der Servername oder die Serveradresse konnte nicht verarbeitet werden.' Warning in install.packages : unable to access index for repository https://R-Forge.R-project.org/src/contrib Warning in install.packages : InternetOpenUrl failed: 'Der Servername oder die Serveradresse konnte nicht verarbeitet werden.' Warning in install.packages : InternetOpenUrl failed: 'Der Servername oder die Serveradresse konnte nicht verarbeitet werden.' Warning in install.packages : unable to access index for repository https://cran.uni-muenster.de/src/contrib Installing package into ‘C:/Users/me/Documents/R/win-library/3.2’ (as ‘lib’ is unspecified) Warning in install.packages : InternetOpenUrl failed: 'Der Servername oder die Serveradresse konnte nicht verarbeitet werden.' Warning in install.packages : InternetOpenUrl failed: 'Der Servername oder die Serveradresse konnte nicht verarbeitet werden.' Warning in install.packages : unable to access index for repository https://cran.uni-muenster.de/src/contrib Warning in install.packages : package ‘dplyr’ is not available (for R version 3.2.2) Warning in install.packages : InternetOpenUrl failed: 'Der Servername oder die Serveradresse konnte nicht verarbeitet werden.' Warning in install.packages : InternetOpenUrl failed: 'Der Servername oder die Serveradresse konnte nicht verarbeitet werden.' Warning in install.packages : unable to access index for repository https://cran.uni-muenster.de/bin/windows/contrib/3.2 </code></pre> <p>Could anyone please help? Thank you!</p>
33,372,798
4
0
null
2015-10-26 20:55:22.503 UTC
9
2018-10-06 12:31:37.22 UTC
2017-05-23 12:10:24.4 UTC
null
-1
null
4,126,224
null
1
22
r|installation|package|install.packages
28,203
<p>The problem might be a failure to handle <code>https</code> properly by the underlying method used by R for downloading files. This can be verified by trying</p> <pre><code>fname &lt;- tempfile() download.file("https://cran.uni-muenster.de/", destfile=fname) file.remove(fname) </code></pre> <p>If that does not work but replacing <code>https</code> with <code>http</code> does, this most likely means that the method used by R's <code>download.file</code> cannot deal with <code>https</code> at all or fails verifying SSL certificates.</p> <p>You can try</p> <ul> <li>using regular <code>http</code> mirrors instead of <code>https</code></li> <li>update your CA certificate bundle to allow proper certificate validation</li> <li><p>setting the default download method to <code>"libcurl"</code> and see if that helps:</p> <pre><code>options(download.file.method="libcurl") </code></pre></li> </ul>
69,207,368
Constant FILTER_SANITIZE_STRING is deprecated
<p>I have installed PHP 8.1 and I started testing my old project. I have used the filter <code>FILTER_SANITIZE_STRING</code> like so:</p> <pre><code>$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); </code></pre> <p>Now I get this error:</p> <blockquote> <p>Deprecated: Constant FILTER_SANITIZE_STRING is deprecated</p> </blockquote> <p>The same happens when I use <code>FILTER_SANITIZE_STRIPPED</code>:</p> <blockquote> <p>Deprecated: Constant FILTER_SANITIZE_STRIPPED is deprecated</p> </blockquote> <p>What can I replace it with?</p>
69,207,369
5
0
null
2021-09-16 11:10:25.95 UTC
5
2022-09-02 16:05:12.643 UTC
2021-09-24 19:59:38.917 UTC
null
1,839,439
null
1,839,439
null
1
34
php|filter|sanitization|php-8.1
23,693
<p>This filter had an unclear purpose. It's difficult to say what exactly it was meant to accomplish or when it should be used. It was also confused with the default string filter, due to its name, when in reality the default string filter is called <code>FILTER_UNSAFE_RAW</code>. The PHP community decided that the usage of this filter should not be supported anymore.</p> <p>The behaviour of this filter was very unintuitive. It removed everything between <code>&lt;</code> and the end of the string or until the next <code>&gt;</code>. It also removed all <code>NUL</code> bytes. Finally, it encoded <code>'</code> and <code>&quot;</code> into their HTML entities.</p> <p>If you want to replace it, you have a couple of options:</p> <ol> <li><p>Use the default string filter <code>FILTER_UNSAFE_RAW</code> that doesn't do any filtering. This should be used if you had no idea about the behaviour of <code>FILTER_SANITIZE_STRING</code> and you just want to use a default filter that will give you the string value.</p> </li> <li><p>If you used this filter to protect against XSS vulnerabilities, then replace its usage with <a href="https://www.php.net/manual/en/function.htmlspecialchars.php" rel="noreferrer"><code>htmlspecialchars()</code></a>. Don't call this function on the input data. To protect against XSS you need to encode the output!</p> </li> <li><p>If you knew exactly what that filter does and you want to create a polyfill, you can do that easily with regex.</p> <pre><code>function filter_string_polyfill(string $string): string { $str = preg_replace('/\x00|&lt;[^&gt;]*&gt;?/', '', $string); return str_replace([&quot;'&quot;, '&quot;'], ['&amp;#39;', '&amp;#34;'], $str); } </code></pre> </li> </ol> <p><a href="https://benhoyt.com/writings/dont-sanitize-do-escape/" rel="noreferrer">Don’t try to sanitize input. Escape output.</a></p>
20,327,937
ValueError: unconverted data remains: 02:05
<p>I have some dates in a json files, and I am searching for those who corresponds to today's date :</p> <pre><code>import os import time from datetime import datetime from pytz import timezone input_file = file(FILE, "r") j = json.loads(input_file.read().decode("utf-8-sig")) os.environ['TZ'] = 'CET' for item in j: lt = time.strftime('%A %d %B') st = item['start'] st = datetime.strptime(st, '%A %d %B') if st == lt : item['start'] = datetime.strptime(st,'%H:%M') </code></pre> <p>I had an error like this : </p> <pre><code>File "/home/--/--/--/app/route.py", line 35, in file.py st = datetime.strptime(st, '%A %d %B') File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime data_string[found.end():]) ValueError: unconverted data remains: 02:05 </code></pre> <p>Do you have any suggestions ? </p>
20,328,136
6
0
null
2013-12-02 12:07:31.577 UTC
8
2022-09-06 12:38:19.153 UTC
null
null
null
null
2,899,642
null
1
46
python|date|datetime|python-2.7
189,756
<p>The value of <code>st</code> at <code>st = datetime.strptime(st, '%A %d %B')</code> line something like <code>01 01 2013 02:05</code> and the <code>strptime</code> can't parse this. Indeed, you get an hour in addition of the date... You need to add <code>%H:%M</code> at your strptime.</p>
30,033,096
What is `lr_policy` in Caffe?
<p>I just try to find out how I can use <a href="http://caffe.berkeleyvision.org/">Caffe</a>. To do so, I just took a look at the different <code>.prototxt</code> files in the examples folder. There is one option I don't understand:</p> <pre><code># The learning rate policy lr_policy: "inv" </code></pre> <p>Possible values seem to be:</p> <ul> <li><code>"fixed"</code></li> <li><code>"inv"</code></li> <li><code>"step"</code></li> <li><code>"multistep"</code></li> <li><code>"stepearly"</code></li> <li><code>"poly"</code> </li> </ul> <p>Could somebody please explain those options?</p>
33,711,600
2
0
null
2015-05-04 14:47:04.15 UTC
18
2018-03-22 06:46:36.26 UTC
2018-03-22 06:46:36.26 UTC
null
1,714,410
null
562,769
null
1
37
machine-learning|neural-network|deep-learning|caffe|gradient-descent
33,958
<p>If you look inside the <code>/caffe-master/src/caffe/proto/caffe.proto</code> file (you can find it online <a href="https://github.com/BVLC/caffe/blob/master/src/caffe/proto/caffe.proto#L157-L172">here</a>) you will see the following descriptions:</p> <pre><code>// The learning rate decay policy. The currently implemented learning rate // policies are as follows: // - fixed: always return base_lr. // - step: return base_lr * gamma ^ (floor(iter / step)) // - exp: return base_lr * gamma ^ iter // - inv: return base_lr * (1 + gamma * iter) ^ (- power) // - multistep: similar to step but it allows non uniform steps defined by // stepvalue // - poly: the effective learning rate follows a polynomial decay, to be // zero by the max_iter. return base_lr (1 - iter/max_iter) ^ (power) // - sigmoid: the effective learning rate follows a sigmod decay // return base_lr ( 1/(1 + exp(-gamma * (iter - stepsize)))) // // where base_lr, max_iter, gamma, step, stepvalue and power are defined // in the solver parameter protocol buffer, and iter is the current iteration. </code></pre>
36,840,396
fetch gives an empty response body
<p>I have a react/redux application and I'm trying to do a simple GET request to a sever: </p> <pre><code>fetch('http://example.com/api/node', { mode: "no-cors", method: "GET", headers: { "Accept": "application/json" } }).then((response) =&gt; { console.log(response.body); // null return dispatch({ type: "GET_CALL", response: response }); }) .catch(error =&gt; { console.log('request failed', error); }); </code></pre> <p>The problem is that the response body is empty in the <code>.then()</code> function and I'm not sure why. I checked examples online and it looks like my code should work so I'm obviously missing something here. The thing is, if I check the network tab in Chrome's dev tools, the request is made and I receive the data I'm looking for.</p> <p>Can anybody shine a light on this one?</p> <p><strong>EDIT:</strong></p> <p>I tried converting the reponse.</p> <p>using <code>.text()</code>:</p> <pre><code>fetch('http://example.com/api/node', { mode: "no-cors", method: "GET", headers: { "Accept": "application/json" } }) .then(response =&gt; response.text()) .then((response) =&gt; { console.log(response); // returns empty string return dispatch({ type: "GET_CALL", response: response }); }) .catch(error =&gt; { console.log('request failed', error); }); </code></pre> <p>and with <code>.json()</code>:</p> <pre><code>fetch('http://example.com/api/node', { mode: "no-cors", method: "GET", headers: { "Accept": "application/json" } }) .then(response =&gt; response.json()) .then((response) =&gt; { console.log(response.body); return dispatch({ type: "GET_CALL", response: response.body }); }) .catch(error =&gt; { console.log('request failed', error); }); // Syntax error: unexpected end of input </code></pre> <p>Looking in the chrome dev tools:</p> <p><a href="https://i.stack.imgur.com/K8XSY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/K8XSY.png" alt="enter image description here"></a></p>
40,427,882
9
0
null
2016-04-25 12:20:01.607 UTC
23
2022-06-03 15:33:38.223 UTC
2019-08-24 03:42:59.02 UTC
null
3,578,997
null
2,828,229
null
1
109
javascript|fetch-api
176,977
<p>I just ran into this. As mentioned in this <a href="https://stackoverflow.com/a/35291777/2800482">answer</a>, using <code>mode: "no-cors"</code> will give you an <code>opaque response</code>, which doesn't seem to return data in the body.</p> <blockquote> <p>opaque: Response for “no-cors” request to cross-origin resource. <a href="https://fetch.spec.whatwg.org/#concept-filtered-response-opaque" rel="noreferrer">Severely restricted</a>.</p> </blockquote> <p>In my case I was using <code>Express</code>. After I installed <a href="https://github.com/expressjs/cors" rel="noreferrer">cors for Express</a> and configured it and removed <code>mode: "no-cors"</code>, I was returned a promise. The response data will be in the promise, e.g.</p> <pre><code>fetch('http://example.com/api/node', { // mode: 'no-cors', method: 'GET', headers: { Accept: 'application/json', }, }, ).then(response =&gt; { if (response.ok) { response.json().then(json =&gt; { console.log(json); }); } }); </code></pre>
18,955,397
Update the selected dates of date range picker for Twitter Bootstrap
<p>I'm using the <a href="https://github.com/dangrossman/bootstrap-daterangepicker" rel="noreferrer">date range picker</a> for Twitter Bootstrap, by <a href="http://www.dangrossman.info/2012/08/20/a-date-range-picker-for-twitter-bootstrap/" rel="noreferrer">Dan Grossman</a>.</p> <p>When initialized, it's possible to set pre-defined values like startDate and endDate. Is it possible to update the values manually later on in a similar way?</p> <p>What I want to do is to "load" the date range picker with filters I have saved, which includes a start and end date (not by defining pre-defined ranges). Just updating the field of the date range picker through jQuery won't update the actual selection of the calendar. </p> <p>I guess I should do something like this when initializing the date range picker:</p> <pre><code>var reportrange = $('#reportrange').daterangepicker(), DateRangePicker = reportrange.data('daterangepicker'); </code></pre> <p>But then, how to use DateRangePicker to update the date range picker and calendar with new selected dates manually?</p>
21,391,074
5
0
null
2013-09-23 09:02:42.523 UTC
1
2019-12-21 10:22:50.05 UTC
2017-01-14 12:02:28.677 UTC
null
6,106,614
null
2,417,844
null
1
11
javascript|jquery|twitter-bootstrap|daterangepicker
47,888
<p>The latest version of this component provides methods for updating the start/end date:</p> <pre><code>$("#reportrange").data('daterangepicker').setStartDate(startDate); $("#reportrange").data('daterangepicker').setEndDate(endDate); </code></pre> <p>You don't have to call the update methods yourself as these will handle all that.</p>
19,177,732
What is the difference between ng-if and ng-show/ng-hide
<p>I'm trying to understand the difference between <code>ng-if</code> and <code>ng-show</code>/<code>ng-hide</code>, but they look the same to me.</p> <p>Is there a difference that I should keep in mind choosing to use one or the other?</p>
19,177,773
12
0
null
2013-10-04 09:26:14.98 UTC
115
2019-05-07 06:48:50 UTC
2019-05-07 06:48:50 UTC
null
1,033,581
null
356,440
null
1
429
angularjs|angularjs-ng-show|angularjs-ng-if
320,805
<h2>ngIf</h2> <p>The <code>ngIf</code> directive <strong>removes or recreates</strong> a portion of the DOM tree based on an expression. If the expression assigned to <code>ngIf</code> evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.</p> <pre><code>&lt;!-- when $scope.myValue is truthy (element is restored) --&gt; &lt;div ng-if="1"&gt;&lt;/div&gt; &lt;!-- when $scope.myValue is falsy (element is removed) --&gt; &lt;div ng-if="0"&gt;&lt;/div&gt; </code></pre> <p>When an element is removed using <code>ngIf</code> its scope is destroyed and a new scope is created when the element is restored. The scope created within <code>ngIf</code> inherits from its parent scope using prototypal inheritance.</p> <p>If <code>ngModel</code> is used within <code>ngIf</code> to bind to a JavaScript primitive defined in the parent scope, any modifications made to the variable within the child scope will not affect the value in the parent scope, e.g.</p> <pre><code>&lt;input type="text" ng-model="data"&gt; &lt;div ng-if="true"&gt; &lt;input type="text" ng-model="data"&gt; &lt;/div&gt; </code></pre> <p>To get around this situation and update the model in the parent scope from inside the child scope, use an object:</p> <pre><code>&lt;input type="text" ng-model="data.input"&gt; &lt;div ng-if="true"&gt; &lt;input type="text" ng-model="data.input"&gt; &lt;/div&gt; </code></pre> <p>Or, <code>$parent</code> variable to reference the parent scope object:</p> <pre><code>&lt;input type="text" ng-model="data"&gt; &lt;div ng-if="true"&gt; &lt;input type="text" ng-model="$parent.data"&gt; &lt;/div&gt; </code></pre> <h2>ngShow</h2> <p>The <code>ngShow</code> directive <strong>shows or hides</strong> the given HTML element based on the expression provided to the <code>ngShow</code> attribute. The element is shown or hidden by removing or adding the <code>ng-hide</code> CSS class onto the element. The <code>.ng-hide</code> CSS class is predefined in AngularJS and sets the display style to none (using an <code>!important</code> flag).</p> <pre><code>&lt;!-- when $scope.myValue is truthy (element is visible) --&gt; &lt;div ng-show="1"&gt;&lt;/div&gt; &lt;!-- when $scope.myValue is falsy (element is hidden) --&gt; &lt;div ng-show="0" class="ng-hide"&gt;&lt;/div&gt; </code></pre> <p>When the <code>ngShow</code> expression evaluates to <code>false</code> then the <code>ng-hide</code> CSS class is added to the <code>class</code> attribute on the element causing it to become hidden. When <code>true</code>, the <code>ng-hide</code> CSS class is removed from the element causing the element not to appear hidden.</p>
26,893,792
How to change an endpoint address with XML Transformation in web.config?
<p>I need change the address of this configuration in a web.config:</p> <pre><code>&lt;client&gt; &lt;endpoint address="OLD_ADDRESS" binding="basicHttpBinding" contract="Service.IService" name="BasicHttpBinding_IService" /&gt; &lt;/client&gt; </code></pre> <p>to this:</p> <pre><code>&lt;client&gt; &lt;endpoint address="NEW_ADDRESS" binding="basicHttpBinding" contract="Service.IService" name="BasicHttpBinding_IService" /&gt; &lt;/client&gt; </code></pre> <p>In my XML-Transformation file (it's working, it changes another <code>add key value</code>)<br> I have this:</p> <pre><code>&lt;configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"&gt; &lt;client&gt; &lt;endpoint name="BasicHttpBinding_IService" address="NEW_ADDRESS" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/&gt; &lt;/client&gt; </code></pre> <p>but it doesn't work. I don't understand why it doesn't change, if I locate by name. Any help/tip will be preciated. Thanks</p>
26,894,625
1
0
null
2014-11-12 18:19:09.427 UTC
5
2014-11-12 19:07:12.02 UTC
2014-11-12 18:32:38.887 UTC
null
888,472
null
888,472
null
1
30
c#|xml|wcf|xslt
13,320
<p>Does the structure of your transformation file match your web.config? Specifically, are you missing a systems.serviceModel element? </p> <pre><code>&lt;configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"&gt; &lt;system.serviceModel&gt; &lt;client&gt; &lt;endpoint name="BasicHttpBinding_IService" address="NEW_ADDRESS" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre>
51,527,489
Change the default width of a VuetifyJS DataTable cell
<p>I'm using the <a href="https://vuetifyjs.com/en/components/data-tables#introduction" rel="nofollow noreferrer">VuetifyJS Data Table</a> and I need to move the entries of each header cell as close as possible to each other. I tried to add a <em>width</em> to each header but that didn't work - it seems there is a predefined width one can't go below.</p> <p>Update: This is how it should look like - the margin between each row should be fixed at 10px: <a href="https://i.stack.imgur.com/tLGSV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tLGSV.png" alt="enter image description here" /></a></p> <p>Here is a CodePen <a href="https://%20https://codepen.io/anon/pen/ejEpKZ?&amp;editors=101" rel="nofollow noreferrer">example</a>.</p> <pre><code> &lt;div id=&quot;app&quot;&gt; &lt;v-app id=&quot;inspire&quot;&gt; &lt;v-data-table :headers=&quot;headers&quot; :items=&quot;desserts&quot; class=&quot;elevation-1&quot; &gt; &lt;template slot=&quot;headerCell&quot; slot-scope=&quot;props&quot;&gt; &lt;v-tooltip bottom&gt; &lt;span slot=&quot;activator&quot;&gt; {{ props.header.text }} &lt;/span&gt; &lt;span&gt; {{ props.header.text }} &lt;/span&gt; &lt;/v-tooltip&gt; &lt;/template&gt; &lt;template slot=&quot;items&quot; slot-scope=&quot;props&quot;&gt; &lt;td&gt;{{ props.item.name }}&lt;/td&gt; &lt;td class=&quot;text-xs-right&quot;&gt;{{ props.item.calories }}&lt;/td&gt; &lt;td class=&quot;text-xs-right&quot;&gt;{{ props.item.fat }}&lt;/td&gt; &lt;td class=&quot;text-xs-right&quot;&gt;{{ props.item.carbs }}&lt;/td&gt; &lt;td class=&quot;text-xs-right&quot;&gt;{{ props.item.protein }}&lt;/td&gt; &lt;td class=&quot;text-xs-right&quot;&gt;{{ props.item.iron }}&lt;/td&gt; &lt;/template&gt; &lt;/v-data-table&gt; &lt;/v-app&gt; &lt;/div&gt; </code></pre> <p>How to get them close together?</p>
51,569,928
5
1
null
2018-07-25 20:53:55.907 UTC
2
2022-09-10 05:07:20.673 UTC
2022-05-27 14:51:40.443 UTC
null
6,000,966
null
974,925
null
1
32
javascript|vue.js|datatable|vuetify.js
84,698
<p>You can add another empty header and set <code>width</code> of every column to min value(1%), except empty to make it fill all free space. Also you need to add empty <code>td</code> to table body template to make grey row dividers visible.</p> <p>See codepen: <a href="https://codepen.io/anon/pen/WKXwOR" rel="noreferrer">https://codepen.io/anon/pen/WKXwOR</a></p>
33,308,121
Can you bind 'this' in an arrow function?
<p>I've been experimenting with ES6 for a while now, and I've just come to a slight problem.</p> <p>I really like using arrow functions, and whenever I can, I use them.</p> <p>However, it would appear that you can't bind them!</p> <p>Here is the function:</p> <pre><code>var f = () =&gt; console.log(this); </code></pre> <p>Here is the object I want to bind the function to:</p> <pre><code>var o = {'a': 42}; </code></pre> <p>And here is how I would bind <code>f</code> to <code>o</code>:</p> <pre><code>var fBound = f.bind(o); </code></pre> <p>And then I can just call <code>fBound</code>:</p> <pre><code>fBound(); </code></pre> <p>Which will output this (the <code>o</code> object):</p> <pre><code>{'a': 42} </code></pre> <p>Cool! Lovely! Except that it doesn't work. Instead of outputting the <code>o</code> object, it outputs the <code>window</code> object.</p> <p>So I'd like to know: can you bind arrow functions? (And if so, how?)</p> <hr> <p>I've tested the code above in Google Chrome 48 and Firefox 43, and the result is the same.</p>
33,308,151
14
1
null
2015-10-23 17:22:36.373 UTC
36
2022-08-15 21:40:48.773 UTC
2019-11-23 16:01:50.883 UTC
null
2,051,454
null
4,633,828
null
1
178
javascript|function|ecmascript-6
100,471
<p>You cannot <em>rebind</em> <code>this</code> in an arrow function. It will always be defined as the context in which it was defined. If you require <code>this</code> to be meaningful you should use a normal function.</p> <p>From the <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-arrow-function-definitions-runtime-semantics-evaluation" rel="noreferrer">ECMAScript 2015 Spec</a>:</p> <blockquote> <p>Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.</p> </blockquote>
9,174,966
Example of ´instanceof´
<pre><code>public class TableModel2 extends TableModel1 { ... } TableModel2 tableModel = new TableModel2(); boolean t1 = tableModel instanceof TableModel1; boolean t2 = tableModel instanceof TableModel2; </code></pre> <p>In the above example, <code>t1</code> and <code>t2</code> are <code>true</code>. So, how could I differentiate between <code>TableModel1</code> and <code>TableModel2</code> using <code>instanceof</code>?</p>
9,175,054
7
0
null
2012-02-07 10:54:15.18 UTC
6
2012-02-07 11:23:10.453 UTC
2012-02-07 10:58:48.147 UTC
null
1,122,645
null
1,089,623
null
1
21
java|instanceof
66,453
<pre><code>boolean t2 = tableModel.getClass().equals(TableModel1.class); //False boolean t2 = tableModel.getClass().equals(TableModel2.class); //True </code></pre>
9,522,897
Groovy, how to iterate a list with an index
<p>With all the shorthand ways of doing things in Groovy, there's got to be an easier way to iterate a list while having access to an iteration index.</p> <pre><code>for(i in 0 .. list.size()-1) { println list.get(i) } </code></pre> <p>Is there no implicit index in a basic <code>for</code> loop?</p> <pre><code>for( item in list){ println item println index } </code></pre>
9,522,992
2
0
null
2012-03-01 19:46:38.547 UTC
4
2016-01-07 20:54:46.897 UTC
2013-03-12 20:59:26.453 UTC
null
791,406
null
791,406
null
1
55
arrays|list|groovy|loops
102,352
<p>You can use <a href="http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Object.html#eachWithIndex(groovy.lang.Closure)" rel="noreferrer"><code>eachWithIndex</code></a>:</p> <pre><code>list.eachWithIndex { item, index -&gt; println item println index } </code></pre> <p>With Groovy 2.4 and newer, you can also use the <a href="http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Iterable.html#indexed()" rel="noreferrer"><code>indexed()</code></a> method. This can be handy to access the index with methods like <code>collect</code>:</p> <pre><code>def result = list.indexed().collect { index, item -&gt; "$index: $item" } println result </code></pre>
30,149,493
Redis AUTH command in Python
<p>I'm using <a href="https://github.com/andymccurdy/redis-py" rel="noreferrer">redis-py</a> binding in Python 2 to connect to my Redis server. The server requires a password. I don't know how to <code>AUTH</code> after making the connection in Python.</p> <p>The following code does not work:</p> <pre><code>import redis r = redis.StrictRedis() r.auth('pass') </code></pre> <p>It says:</p> <blockquote> <p>'StrictRedis' object has no attribute 'auth'</p> </blockquote> <p>Also,</p> <pre><code>r = redis.StrictRedis(auth='pass') </code></pre> <p>does not work either. No such keyword argument.</p> <p>I've used Redis binding in other languages before, and usually the method name coincides with the Redis command. So I would guess <code>r.auth</code> will send <code>AUTH</code>, but unfortunately it does not have this method.</p> <p>So what is the standard way of <code>AUTH</code>? Also, why call this <code>StrictRedis</code>? What does <code>Strict</code> mean here?</p>
30,153,367
4
3
null
2015-05-10 08:51:50.403 UTC
10
2022-03-24 15:38:59.963 UTC
null
null
null
null
1,595,430
null
1
29
python|redis
38,874
<p>Thanks to the hints from the comments. I found the answer from <a href="https://redis-py.readthedocs.org/en/latest/" rel="noreferrer">https://redis-py.readthedocs.org/en/latest/</a>.</p> <p>It says</p> <pre><code>class redis.StrictRedis(host='localhost', port=6379, db=0, password=None, socket_timeout=None, connection_pool=None, charset='utf-8', errors='strict', unix_socket_path=None) </code></pre> <p>So <code>AUTH</code> is in fact <code>password</code> passed by keyword argument.</p>
30,818,694
Test if dict contained in dict
<p>Testing for equality works fine like this for python dicts:</p> <pre><code>first = {"one":"un", "two":"deux", "three":"trois"} second = {"one":"un", "two":"deux", "three":"trois"} print(first == second) # Result: True </code></pre> <p>But now my second dict contains some additional keys I want to ignore:</p> <pre><code>first = {"one":"un", "two":"deux", "three":"trois"} second = {"one":"un", "two":"deux", "three":"trois", "foo":"bar"} </code></pre> <p><strong>Is there a simple way to test if the first dict is part of the second dict, with all its keys and values?</strong></p> <p><strong>EDIT 1:</strong></p> <p>This question is suspected to be a duplicate of <a href="https://stackoverflow.com/questions/3415347/how-to-test-if-a-dictionary-contains-certain-keys">How to test if a dictionary contains certain <em>keys</em></a>, but I'm interested in testing keys <em>and their values</em>. Just containing the same keys does not make two dicts equal.</p> <p><strong>EDIT 2:</strong></p> <p>OK, I got some answers now using four different methods, and proved all of them working. As I need a fast process, I tested each for execution time. I created three identical dicts with 1000 items, keys and values were random strings of length 10. The <code>second</code> and <code>third</code> got some extra key-value pairs, and the last non-extra key of the <code>third</code> got a new value. So, <code>first</code> is a subset of <code>second</code>, but not of <code>third</code>. Using module <code>timeit</code> with 10000 repetitions, I got:</p> <pre><code>Method Time [s] first.viewitems() &lt;=second.viewitems() 0.9 set(first.items()).issubset(second.items()) 7.3 len(set(first.items()) &amp; set(second.items())) == len(first) 8.5 all(first[key] == second.get(key, sentinel) for key in first) 6.0 </code></pre> <p>I guessed the last method is the slowest, but it's on place 2. But method 1 beats them all.</p> <p>Thanks for your answers!</p>
30,818,799
4
2
null
2015-06-13 12:30:35.833 UTC
11
2015-06-14 18:47:17.867 UTC
2017-05-23 12:10:47.363 UTC
null
-1
null
4,099,181
null
1
42
python|dictionary
24,722
<p>You can use a <a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects">dictionary view</a>:</p> <pre><code># Python 2 if first.viewitems() &lt;= second.viewitems(): # true only if `first` is a subset of `second` # Python 3 if first.items() &lt;= second.items(): # true only if `first` is a subset of `second` </code></pre> <p>Dictionary views are the <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects">standard in Python 3</a>, in Python 2 you need to prefix the standard methods with <code>view</code>. They act like sets, and <code>&lt;=</code> tests if one of those is a subset of (or is equal to) another.</p> <p>Demo in Python 3:</p> <pre><code>&gt;&gt;&gt; first = {"one":"un", "two":"deux", "three":"trois"} &gt;&gt;&gt; second = {"one":"un", "two":"deux", "three":"trois", "foo":"bar"} &gt;&gt;&gt; first.items() &lt;= second.items() True &gt;&gt;&gt; first['four'] = 'quatre' &gt;&gt;&gt; first.items() &lt;= second.items() False </code></pre> <p>This works for <em>non-hashable values too</em>, as the keys make the key-value pairs unique already. The documentation is a little confusing on this point, but even with mutable values (say, lists) this works:</p> <pre><code>&gt;&gt;&gt; first_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei']} &gt;&gt;&gt; second_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei'], 'three': ['trois', 'drie', 'drei']} &gt;&gt;&gt; first_mutable.items() &lt;= second_mutable.items() True &gt;&gt;&gt; first_mutable['one'].append('ichi') &gt;&gt;&gt; first_mutable.items() &lt;= second_mutable.items() False </code></pre> <p>You could also use the <a href="https://docs.python.org/2/library/functions.html#all"><code>all()</code> function</a> with a generator expression; use <code>object()</code> as a sentinel to detect missing values concisely:</p> <pre><code>sentinel = object() if all(first[key] == second.get(key, sentinel) for key in first): # true only if `first` is a subset of `second` </code></pre> <p>but this isn't as readable and expressive as using dictionary views.</p>
10,620,131
Running liquibase within Java code
<p>For some reason there's no documentation on running liquibase inside Java code. I want to generate tables for Unit tests.</p> <p>How would I run it directly in Java?</p> <p>e.g.</p> <pre><code>Liquibase liquibase = new Liquibase() liquibase.runUpdates() ? </code></pre>
10,626,847
4
1
null
2012-05-16 13:57:11.42 UTC
17
2022-05-14 19:26:51.517 UTC
null
null
null
null
53,069
null
1
38
java|liquibase
35,466
<p>It should be something like (taken from liquibase.integration.spring.SpringLiquibase source):</p> <pre><code>java.sql.Connection c = YOUR_CONNECTION; Liquibase liquibase = null; try { Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c)) liquibase = new Liquibase(YOUR_CHANGELOG, new FileSystemResourceAccessor(), database); liquibase.update(); } catch (SQLException e) { throw new DatabaseException(e); } finally { if (c != null) { try { c.rollback(); c.close(); } catch (SQLException e) { //nothing to do } } } </code></pre> <p>There are multiple implementation of ResourceAccessor depending on how your changelog files should be found.</p>
22,673,111
Required XML attribute "adSize" was missing
<p>I get a "Required XML attribute "adSize" was missing" when I launch my app. This is written on the screen of my smartphone instead of my banner. </p> <p>I tried the different solutions founded on stack (like <code>xmlns:ads="http://schemas.android.com/apk/res-auto"</code> instead of <code>xmlns:ads="http://schemas.android.com/apk/libs/com.google.ads"</code> or instead of <code>xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"</code>) but it doesn't work.</p> <p>Here's my java code (a simple Hello World just to try to implement a banner):</p> <pre><code>package com.example.publicite; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } </code></pre> <p>Here's my xml file:</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:ads="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" &gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /&gt; &lt;com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/libs/com.google.ads" android:id="@+id/adView" android:layout_width="fill_parent" android:layout_height="wrap_content" ads:adSize="BANNER" ads:adUnitId="MyAdUnitId" ads:loadAdOnCreate="true" ads:testDevices="TEST_EMULATOR" /&gt; &lt;Button android:id="@+id/votrescore" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="..." /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>and here's my manifest:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.publicite" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="13" android:targetSdkVersion="13" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/&gt; &lt;activity android:name="com.example.publicite.MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER"/&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" /&gt; &lt;/application&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; &lt;/manifest&gt; </code></pre> <p>I use the google play service lib.</p>
34,531,612
18
2
null
2014-03-26 21:09:51.563 UTC
3
2021-11-16 13:32:42.993 UTC
2017-10-20 09:50:27.34 UTC
null
4,720,935
null
3,464,273
null
1
22
android|admob
43,044
<p>Here is a weird answer. I just restarted my eclipse and it stared working. This might help some one.</p> <p>Just restart eclipse, android studio or IntelliJ IDE</p>
7,540,329
NSPredicate compare with Integer
<p>How can I compare two NSNumbers or a NSNumber and an Integer in an NSPredicate?</p> <p>I tried:</p> <pre><code>NSNumber *stdUserNumber = [NSNumber numberWithInteger:[[NSUserDefaults standardUserDefaults] integerForKey:@&quot;standardUser&quot;]]; fetchRequest.predicate = [NSPredicate predicateWithFormat:@&quot;userID == %@&quot;, stdUserNumber]; </code></pre> <p>Well, this doesn't work ... anyone has an idea how to do it? I'm sure it's pretty easy but I wasn't able to find anything ...</p>
7,540,395
2
0
null
2011-09-24 16:37:32.4 UTC
9
2020-09-25 11:52:38.453 UTC
2020-09-25 11:52:38.453 UTC
null
8,642,838
null
265,551
null
1
44
ios|objective-c|core-data|nspredicate
39,677
<p><code>NSNumber</code> is an object type. Unlike <code>NSString</code>, the actual value of <em>NSNumber</em> is not substitued when used with <code>%@</code> format. You have to get the actual value using the predefined methods, like <code>intValue</code> which returns the integer value. And use the format substituer as <code>%d</code> as we are going to substitute an integer value.</p> <p>The predicate should be,</p> <pre><code>predicateWithFormat:@"userID == %d", [stdUserNumber intValue]]; </code></pre>
18,866,745
remove all options from select jquery but only one
<p>I have a select that contain this values: </p> <pre><code>&lt;select id="lstCities" class="valid" name="City"&gt; &lt;option value="OSNY"&gt;OSNY&lt;/option&gt; &lt;option value="dd"&gt;dd&lt;/option&gt; &lt;option value="OSffNY"&gt;OSffNY&lt;/option&gt; &lt;option value="ANTONY"&gt;ANTONY&lt;/option&gt; &lt;option value="0"&gt;Autre...&lt;/option&gt; &lt;/select&gt; </code></pre> <p>How can I delete all options but i would like to keep only </p> <pre><code> &lt;option value="0"&gt;Autre...&lt;/option&gt; </code></pre> <p>My problem is my list is dynamic sometimes I have 3,5,7,.... select + the last one <code>&lt;option value="0"&gt;Autre...&lt;/option&gt;</code></p>
18,866,808
5
1
null
2013-09-18 07:56:57.35 UTC
3
2017-10-17 03:30:25.86 UTC
null
null
null
null
1,428,798
null
1
14
javascript|jquery|removeall
55,537
<p>select all options, then exclude the one with that value :</p> <pre><code>$('#lstCities option[value!="0"]').remove(); </code></pre> <p><a href="http://jsfiddle.net/9dgV5/2/"><strong>FIDDLE</strong></a></p>
17,736,967
Python: how to add text inside a canvas?
<p>I have tried many times to add text to my canvas but it only adds it with a click of a button or on the outside of my canvas. Or it pops up in a separate box. Using the code below-</p> <pre><code>def text(): canvas.create_text(100,10,fill="darkblue",font="Times 20 italic bold",text="Click the bubbles that are multiples of two.") canvas.update </code></pre> <p>It never worked. So my question is how do I add text in my canvas to start of my game?</p>
17,737,103
2
0
null
2013-07-19 01:58:18.293 UTC
4
2020-02-12 12:39:51.823 UTC
2013-07-22 03:35:44.157 UTC
null
2,589,457
null
2,589,457
null
1
16
text|python-3.x|tkinter
85,823
<p>For one, the first snippet of code doesn't work because you don't have a variable named <code>canvas</code>. You have one called <code>self.canvas</code>, however. And when I use <code>self.canvas</code> in the first bit of code and add it to the working program, the text shows up just fine.</p> <p>Also, in that first bit of code you do <code>canvas.update</code>. That has absolutely zero effect because you don't have the trailing parenthesis. If you fix that it will work, but it's really useless. The text will show up as soon as the event loop is entered.</p> <p>All you need to do is add one line right after you create the canvas:</p> <pre><code>self.canvas = Canvas(root, width=800, height=650, bg = '#afeeee') self.canvas.create_text(100,10,fill="darkblue",font="Times 20 italic bold", text="Click the bubbles that are multiples of two.") </code></pre>
18,128,895
Replace spaces, tabs and carriage returns
<p>I am working with SQL developer with Oracle 11g. I have a query that looks something along the lines of this;</p> <pre><code>SELECT [column], [column], [column],...... rs.notes FROM [table], [table], [table]............ return_sku rs WHERE [conditions] AND [conditions] AND [conditions] </code></pre> <p>In the <code>return_sku</code> column there are tabs, spaces, and newlines (I believe this is a carriage return?) I need to make all of these spaces, carriage returns and tabs disappear when I run my query.</p> <p>I am fairly new to SQL, but the most popular search result I found is the REPLACE function. I have absolutely no idea how to use this, as I've tried this in many different ways with no result. I've tried the following;</p> <pre><code>SELECT [column], [column], [column],...... REPLACE(rs.notes, Char(10), '') FROM [table], [table], [table]............ return_sku rs WHERE [conditions] AND [conditions] AND [conditions] </code></pre> <p>This gives the error message:</p> <pre><code>ORA-00904: "RS"."NOTES": invalid identifier 00904. 00000 - "%s: invalid identifier" *Cause: *Action: Error at Line: 3 Column: 531 </code></pre> <p>How do I use this function correctly?</p>
18,129,100
2
1
null
2013-08-08 14:38:26.017 UTC
1
2013-08-08 15:07:33.963 UTC
2013-08-08 14:48:30.493 UTC
null
1,464,444
null
2,664,815
null
1
3
sql|oracle|select|replace
59,728
<p>In Oracle if you just want to remove a character you can omit the third argument of the replace call and the function for character codes is chr(), not char().</p> <p>So your line would be <code>SELECT ... replace(rs.notes,chr(10)) ...</code></p>
3,589,573
PHP function flags, how?
<p>I'm attempting to create a function with flags as its arguments but the output is always different with what's expected :</p> <pre><code>define("FLAG_A", 1); define("FLAG_B", 4); define("FLAG_C", 7); function test_flags($flags) { if($flags &amp; FLAG_A) echo "A"; if($flags &amp; FLAG_B) echo "B"; if($flags &amp; FLAG_C) echo "C"; } test_flags(FLAG_B | FLAG_C); # Output is always ABC, not BC </code></pre> <p>How can I fix this problem?</p>
3,589,579
1
0
null
2010-08-28 05:16:09.957 UTC
10
2015-06-15 00:04:22.027 UTC
2011-06-30 18:23:24.54 UTC
null
236,247
null
433,531
null
1
21
php|function|bit-manipulation|flags
15,244
<p>Flags must be powers of 2 in order to bitwise-or together properly.</p> <pre><code>define("FLAG_A", 0x1); define("FLAG_B", 0x2); define("FLAG_C", 0x4); function test_flags($flags) { if ($flags &amp; FLAG_A) echo "A"; if ($flags &amp; FLAG_B) echo "B"; if ($flags &amp; FLAG_C) echo "C"; } test_flags(FLAG_B | FLAG_C); # Now the output will be BC </code></pre> <p>Using hexadecimal notation for the constant values makes no difference to the behavior of the program, but is one idiomatic way of emphasizing to programmers that the values compose a <a href="http://en.wikipedia.org/wiki/Bit_field" rel="noreferrer">bit field</a>. Another would be to use shifts: <code>1&lt;&lt;0</code>, <code>1&lt;&lt;1</code>, <code>1&lt;&lt;2</code>, &amp;c.</p>
28,354,217
how can you record your screen in a gif?
<p><img src="https://i.stack.imgur.com/lfdUs.gif" alt="enter image description here"></p> <p>This is the example i am talking about, how can you do this?</p>
28,354,334
2
2
null
2015-02-05 21:20:13.62 UTC
12
2018-03-27 21:26:42.12 UTC
2015-02-06 00:43:26.51 UTC
null
2,166,798
null
97,893
null
1
25
macos|gif
41,316
<p>I usually, on Mac, do this task with <a href="https://www.cockos.com/licecap/" rel="noreferrer">https://www.cockos.com/licecap/</a> (source: <a href="https://github.com/justinfrankel/licecap" rel="noreferrer">https://github.com/justinfrankel/licecap</a>). It also runs on Windows. </p> <blockquote> <p>LICEcap can capture an area of your desktop and save it directly to .GIF (for viewing in web browsers, etc).</p> </blockquote> <p>GUI is simple but effective, and it's really easy to select just the area you want to capture.</p> <p><strong>Demo</strong></p> <p><img src="https://www.cockos.com/licecap/how_to_licecap.gif" alt=""></p> <p><strong>Output</strong></p> <p><img src="https://www.cockos.com/licecap/demo2.gif" alt=""></p>
8,955,332
What is signing ClickOnce manifests for?
<p>According to <a href="http://msdn.microsoft.com/en-us/library/zfz60ccf%28v=vs.90%29.aspx" rel="noreferrer">Microsoft</a>, you <em>must</em> sign your ClickOnce application. But it seems to me that it works just fine when I publish it without signing it (by turning off the 'Sign the ClickOnce manifests' option).</p> <p>I really didn't care and kept the default values (I think I was using a test certificate) until I changed computer and started getting a message telling me that 'The application is signed with a different key than the existing application on the server', which <a href="http://msdn.microsoft.com/en-us/library/ms228673%28v=vs.90%29.aspx" rel="noreferrer">seems</a> will cause my users to stop getting automatic updates. Apparently, VS uses my computer's name to create the key.</p> <p>So, should I just stop signing my ClickOnce manifests to prevent this kind of error, or is there any benefit from singing it. Also, are these certificates the ones that would cause the 'Publisher: Unknown Publisher' message when installing the application to show my company name instead, or would I need to purchase two different kind of certificates?</p>
9,053,248
1
1
null
2012-01-21 18:08:22.45 UTC
3
2012-01-29 16:33:52.893 UTC
2012-01-28 05:39:27.4 UTC
null
1,336
null
1,219,414
null
1
39
.net|clickonce|manifest|code-signing
22,675
<p>It's a security feature that allows your users to verify that any updates really originated from the publisher of the version you installed before. This is a basic property of Public Key encryption. On top of that you can have your certificate authorized by a trusted peer so that the details of the publisher supplied are also verified. (Having the same publisher as before doesn't have to mean the original information about the publisher is correct. That's the advantage of a bought one.)</p> <p>So summary:</p> <ol> <li>No certificate puts your users at a gamble where the software came from.</li> <li>Self-signed certificates give the user certainty that updates at least came from the same publisher as their original install. But still don't know where this original came from.</li> <li>Purchased certificates give users a degree of certainty that the information about the publisher is verified by a 3rd (and trusted) party. As well as any following updates.</li> </ol>
26,993,853
ViewPager inside fragment, how to retain state?
<p>In my application the fragment activity holds two fragments, Fragment A and Fragment B. Fragment B is a view pager that contains 3 fragments.</p> <p><img src="https://i.stack.imgur.com/1zKEm.png" alt="enter image description here"></p> <p>In my activity, to prevent that the fragment is recreated on config changes:</p> <pre><code>if(getSupportFragmentManager().findFragmentByTag(MAIN_TAB_FRAGMENT) == null) { getSupportFragmentManager().beginTransaction().replace(R.id.container, new MainTabFragment(), MAIN_TAB_FRAGMENT).commit(); } </code></pre> <p>Code for Fragment B:</p> <pre><code>public class MainTabFragment extends Fragment { private PagerSlidingTabStrip mSlidingTabLayout; private LfPagerAdapter adapter; private ViewPager mViewPager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_tab, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { this.adapter = new LfPagerAdapter(getChildFragmentManager()); this.mViewPager = (ViewPager) view.findViewById(R.id.viewpager); this.mViewPager.setAdapter(adapter); this.mSlidingTabLayout = (PagerSlidingTabStrip) view.findViewById(R.id.sliding_tabs); this.mSlidingTabLayout.setViewPager(this.mViewPager); } } </code></pre> <p>Code for the adapter:</p> <pre><code>public class LfPagerAdapter extends FragmentPagerAdapter { private static final int NUM_ITEMS = 3; private FragmentManager fragmentManager; public LfPagerAdapter(FragmentManager fm) { super(fm); this.fragmentManager = fm; } @Override public int getCount() { return NUM_ITEMS; } @Override public Fragment getItem(int position) { Log.d("TEST","TEST"); switch (position) { case 1: return FragmentC.newInstance(); case 2: return FragmentD.newInstance(); default: return FragmentE.newInstance(); } } } </code></pre> <p>My problem is that I am not able to retain the state of the view pager an its child fragments on orientation changes.</p> <p>Obviously this is called on every rotation:</p> <pre><code>this.adapter = new LfPagerAdapter(getChildFragmentManager()); </code></pre> <p>which will cause the whole pager to be recreated, right? As a result </p> <pre><code>getItem(int position) </code></pre> <p>will be called on every rotation and the fragment will be created from scratch and losing his state:</p> <pre><code>return FragmentC.newInstance(); </code></pre> <p>I tried solving this with:</p> <pre><code>if(this.adapter == null) this.adapter = new LfPagerAdapter(getChildFragmentManager()); </code></pre> <p>in <code>onViewCreated</code> but the result was that on rotation the fragments inside the pager where removed.</p> <p>Any ideas how to correctly retain the state inside the pager?</p>
27,316,052
2
3
null
2014-11-18 12:00:04.4 UTC
12
2017-09-27 11:58:54.537 UTC
2014-11-18 12:50:24.843 UTC
null
401,025
null
401,025
null
1
12
android|android-fragments|fragmentpageradapter
18,224
<p>You will need to do 2 things to resolve the issue:</p> <p>1) You should use <code>onCreate</code> method instead of <code>onViewCreated</code> to instantiate <code>LfPagerAdapter</code>;</p> <p>i.e.:</p> <pre><code> public class MainTabFragment extends Fragment { private PagerSlidingTabStrip mSlidingTabLayout; private LfPagerAdapter adapter; private ViewPager mViewPager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); this.adapter = new LfPagerAdapter(getChildFragmentManager()); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_tab, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { this.mViewPager = (ViewPager) view.findViewById(R.id.viewpager); this.mViewPager.setAdapter(adapter); this.mSlidingTabLayout = (PagerSlidingTabStrip) view.findViewById(R.id.sliding_tabs); this.mSlidingTabLayout.setViewPager(this.mViewPager); } } </code></pre> <p>2) You will need to extend <code>FragmentStatePagerAdapter</code> instead of <code>FragmentPagerAdapter</code></p>
19,800,939
How to initialize a constructor with that takes Strings as parameters?
<p>I am not sure that I am using the right terminology, but question is how do I properly make a constructor that takes a string in as a parameter?</p> <p>I am used to having a <code>const char *</code> in the constructor instead of strings.</p> <p>Normally I would do something like this:</p> <pre><code>Name(const char* fName, const char* lName) : firstName(0), lastName(0) { char * temp = new char [strlen(fName) + 1]; strcpy_s(temp, strlen(fName) + 1, fName); firstName = temp; char * temp2 = new char [strlen(lName) + 1]; strcpy_s(temp2, strlen(lName) + 1, lName); lastName = temp2; } </code></pre> <p>What if the constructor is this:</p> <pre><code> Name(const string fName, const string lName) { } </code></pre> <p>Do I still do base member initialization? do I still need to use string copy in the base of the constructor?</p>
19,800,969
4
0
null
2013-11-05 23:11:16.403 UTC
2
2019-06-02 08:36:26.74 UTC
2013-11-05 23:13:47.797 UTC
null
1,404,311
null
1,819,427
null
1
16
c++|string|constructor
52,461
<p>Use <a href="http://en.cppreference.com/w/cpp/string/basic_string" rel="noreferrer"><code>std::string</code></a> and initializer lists:</p> <pre><code>std::string fName, lName; Name(string fName, string lName):fName(std::move(fName)), lName(std::move(lName)) { } </code></pre> <p>In this case, you don't need to use terribly bare pointers, you don't need allocate memory, copy characters and finally de-allocate. In addition, this new code has chances to take advantages of moving rather than copying since <code>std::string</code> is movable. Also it's useful to read <a href="https://stackoverflow.com/questions/4321305/best-form-for-constructors-pass-by-value-or-reference">this</a>.</p> <p>And so on....</p>
368,766
How to pass parameters to SSRS report programmatically
<p>I'm looking for a little help on programmatically passing parameters to a SSRS report via VB.NET and ASP.NET. This seems like it should be a relatively simple thing to do, but I haven't had much luck finding help on this.</p> <p>Does anyone have any suggestions on where to go to get help with this, or perhaps even some sample code?</p> <p>Thanks.</p>
368,851
4
0
null
2008-12-15 15:47:31.93 UTC
8
2015-02-24 15:21:25.08 UTC
null
null
null
null
6,602
null
1
15
asp.net|vb.net|reporting-services
55,660
<p>You can do the following,: (it works both on local reports as in Full Blown SSRS reports. but in full mode, use the appropriate class, the parameter part remains the same)</p> <pre><code>LocalReport myReport = new LocalReport(); myReport.ReportPath = Server.MapPath("~/Path/To/Report.rdlc"); ReportParameter myParam = new ReportParameter("ParamName", "ParamValue"); myReport.SetParameters(new ReportParameter[] { myParam }); // more code here to render report </code></pre>
399,971
Sharing a folder and setting permissions in PowerShell
<p>I need a script to run on Vista Ultimate to share an external drive and assign full control to Everyone. I've got a batch file to create the share using <code>net share</code>, but there doesn't seem to be a way to change the permissions. I reckon this must be possible in PowerShell, but I have no idea where to start.</p>
400,459
4
0
null
2008-12-30 10:45:30.323 UTC
3
2017-12-07 20:37:32.453 UTC
null
null
null
harriyott
5,744
null
1
17
powershell|permissions|directory|share
55,586
<p>Two answers.</p> <p>In PowerShell, the Get-ACL cmdlet will retrieve the existing permissions. You then modify those using .NET commands, and run Set-ACL to apply it back to the folder - the help for these two cmdlets includes examples, and you can download the book examples from www.sapienpress.com for "Windows PowerShell: TFM" = the book also contains explicit examples.</p> <p>However, it is not worth your time. Practically speaking, file ACLs are a royal pain to deal with and incredibly complicated. Microsoft has already written lovely tools to do this, like Cacls, and it's far easier just to use those.</p> <p>Now that's all FILE permissions - you may also be interested in changing the permissions on the SHARE itself. The tool for that is SUBINACL, and you can download it from Microsoft. See also <a href="http://cwashington.netreach.net/depo/view.asp?Index=1127&amp;ScriptType=vbscript" rel="nofollow noreferrer">http://cwashington.netreach.net/depo/view.asp?Index=1127&amp;ScriptType=vbscript</a>. </p>
695,303
Building Amazon Affiliates links
<p>How can I generate an Amazon affiliates link (with my Tracking ID) from a regular link without using Amazon online tools ?</p>
695,912
4
1
null
2009-03-29 20:21:12.84 UTC
15
2018-11-22 17:38:44.927 UTC
null
null
null
null
41,767
null
1
19
amazon
8,510
<p>Here's an <a href="http://www.askdavetaylor.com/how_do_i_quickly_build_amazon_affiliate_links_on_my_pages.html" rel="noreferrer">easy tutorial</a> that should get you started. And <a href="https://affiliate-program.amazon.com/gp/associates/help/t5/a16" rel="noreferrer">this page</a> at Amazon should fill in some gaps about ASINs, especially the section entitled: "Is there an automated way to create Associates links if I have the 13-digit ISBN?" Here's <a href="http://crazybob.org/2008/10/how-to-create-simple-amazon-affiliate.html" rel="noreferrer">another relevant article</a>.</p> <p>You are not very specific on how you want to generate them or how many you will be generating, but there's an <a href="http://www.erobillard.com/snippets/amazonlink.aspx" rel="noreferrer">online tool</a> written by <a href="http://www.erobillard.com" rel="noreferrer">Eri Robillard</a> that uses WebForms and XML Web Services. If it's a small number of links you want to make by hand, it looks like a good tool.<br/> If you're looking to generate them programatically, you might be able to get permission from him to screenscrape his site, or maybe he'd provide you with source code. I can't find what restrictions (if any) he puts on its use.</p>
390,578
Creating instance of type without default constructor in C# using reflection
<p>Take the following class as an example:</p> <pre><code>class Sometype { int someValue; public Sometype(int someValue) { this.someValue = someValue; } } </code></pre> <p>I then want to create an instance of this type using reflection:</p> <pre><code>Type t = typeof(Sometype); object o = Activator.CreateInstance(t); </code></pre> <p>Normally this will work, however because <code>SomeType</code> has not defined a parameterless constructor, the call to <code>Activator.CreateInstance</code> will throw an exception of type <code>MissingMethodException</code> with the message "<em>No parameterless constructor defined for this object.</em>" Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.</p>
390,596
4
2
null
2008-12-24 01:34:32.407 UTC
48
2018-06-25 12:14:10.23 UTC
2013-09-27 15:57:55.463 UTC
null
661,933
Aistina
37,472
null
1
105
c#|reflection|instantiation|default-constructor
95,187
<p>I originally posted this answer <a href="https://stackoverflow.com/questions/178645/how-does-wcf-deserialization-instantiate-objects-without-calling-a-constructor#179486">here</a>, but here is a reprint since this isn't the exact same question but has the same answer:</p> <p><code>FormatterServices.GetUninitializedObject()</code> will create an instance without calling a constructor. I found this class by using <a href="http://www.red-gate.com/products/reflector/index.htm" rel="noreferrer">Reflector</a> and digging through some of the core .Net serialization classes. </p> <p>I tested it using the sample code below and it looks like it works great:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Runtime.Serialization; namespace NoConstructorThingy { class Program { static void Main(string[] args) { MyClass myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass)); //does not call ctor myClass.One = 1; Console.WriteLine(myClass.One); //write "1" Console.ReadKey(); } } public class MyClass { public MyClass() { Console.WriteLine("MyClass ctor called."); } public int One { get; set; } } } </code></pre>
1,243,614
How do I calculate the normal vector of a line segment?
<p>Suppose I have a line segment going from (x1,y1) to (x2,y2). How do I calculate the normal vector perpendicular to the line?</p> <p>I can find lots of stuff about doing this for planes in 3D, but no 2D stuff.</p> <p>Please go easy on the maths (links to worked examples, diagrams or algorithms are welcome), I'm a programmer more than I'm a mathematician ;)</p>
1,243,676
4
3
null
2009-08-07 08:35:36.627 UTC
71
2022-01-13 19:29:33.827 UTC
null
null
null
null
18,854
null
1
205
math|geometry|vector
236,536
<p>If we define <code>dx = x2 - x1</code> and <code>dy = y2 - y1</code>, then the normals are <code>(-dy, dx)</code> and <code>(dy, -dx)</code>.</p> <p>Note that no division is required, and so you're not risking dividing by zero.</p>
22,404,641
Using Sqoop to import data from MySQL to Hive
<p>I am using Sqoop (version 1.4.4) to import data from MySQL to Hive. The data will be a subset of one of tables, i.e. few columns from a table. Is it necessary to create table in Hive before hand. Or importing the data will create the name specified in the command if it is not in the Hive?</p>
22,407,835
6
1
null
2014-03-14 12:10:36.403 UTC
5
2022-01-25 15:39:18.187 UTC
2014-03-14 12:11:29.567 UTC
null
13,302
null
2,526,951
null
1
7
mysql|hadoop|hive|sqoop
63,119
<p>As mentioned in the <a href="http://sqoop.apache.org/docs/1.4.4/SqoopUserGuide.html#_importing_data_into_hive" rel="nofollow noreferrer">sqoop documentation</a>, you will not have to create any hive tables if you use the <em><code>--hive-import</code></em> argument in your command</p> <p>example:</p> <pre><code>sqoop import \ --connect jdbc:mysql://mysql_server:3306/db_name \ --username mysql_user \ --password mysql_pass \ --table table_name \ --hive-import </code></pre> <p>Also... consider the <em><code>--hive-overwrite</code></em> argument if you want to schedule a full data import, on a daily base for example</p>
23,522,130
JavaBean wrapping with JavaFX Properties
<p>I want to use JavaFX properties for UI binding, but I don't want them in my model classes (see <a href="https://stackoverflow.com/questions/23187989/using-javafx-beans-properties-in-model-classes">Using javafx.beans properties in model classes</a>). My model classes have getters and setters, and I want to create properties based on those. For example, assuming an instance <code>bean</code> with methods <code>String getName()</code> and <code>setName(String name)</code>, I would write</p> <pre><code> SimpleStringProperty property = new SimpleStringProperty(bean, "name") </code></pre> <p>expecting that <code>property.set("Foobar")</code> would trigger a call to <code>bean.setName</code>. But this doesn't seem to work. What am I missing?</p>
23,524,537
1
1
null
2014-05-07 15:32:38.213 UTC
8
2017-02-11 22:25:15.413 UTC
2017-05-23 12:34:45.273 UTC
null
-1
null
1,829,158
null
1
22
java|model-view-controller|javafx|model|javabeans
10,341
<p>The <code>Simple*Property</code> classes are full, standalone implementations of their corresponding <code>Property</code> abstract classes, and do not rely on any other object. So, for example, <code>SimpleStringProperty</code> contains a (private) <code>String</code> field itself which holds the current value of the property. </p> <p>The parameters to the constructor you showed:</p> <pre><code>new SimpleStringProperty(bean, "name") </code></pre> <p>are:</p> <ul> <li><code>bean</code>: the bean to which the property belongs, if any</li> <li><code>name</code>: the name of the property</li> </ul> <p>The <code>bean</code> can be useful in a <code>ChangeListener</code>'s <code>changed(...)</code> method as you can retrieve the "owning bean" of the property that changed from the property itself. The <code>name</code> can be used similarly (if you have the same listener registered with multiple properties, you can figure out which property changed: though I never use this pattern).</p> <p>So a typical use of a <code>SimpleStringProperty</code> as an observable property of an object looks like:</p> <pre><code>public class Person { private final StringProperty firstName = new SimpleStringProperty(this, "firstName"); public final String getFirstName() { return firstName.get(); } public final void setFirstName(String firstName) { this.firstName.set(firstName); } public StringProperty firstNameProperty() { return firstName ; } // ... other properties, etc } </code></pre> <p>The functionality you are looking for: to wrap an existing Java Bean style property in a JavaFX observable property is implemented by classes in the <code>javafx.beans.property.adapter</code> package. So, for example, you could do</p> <pre><code>StringProperty nameProperty = new JavaBeanStringPropertyBuilder() .bean(bean) .name("name") .build(); </code></pre> <p>Calling </p> <pre><code>nameProperty.set("James"); </code></pre> <p>with this setup will effectively cause a call to </p> <pre><code>bean.setName("James"); </code></pre> <p>If the bean supports <code>PropertyChangeListener</code>s, the <code>JavaBeanStringProperty</code> will register a <code>PropertyChangeListener</code> with the bean. Any changes to the <code>name</code> property of the Java Bean will be translated by the <code>JavaBeanStringProperty</code> into JavaFX property changes. Consequently, if the underlying JavaBean supports <code>PropertyChangeListener</code>s, then changes to the bean via</p> <pre><code>bean.setName(...); </code></pre> <p>will result in any <code>ChangeListener</code>s (or <code>InvalidationListener</code>s) registered with the <code>JavaBeanStringProperty</code> being notified of the change.</p> <p>So, for example, if the Bean class is</p> <pre><code>import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; public class Bean { private String name ; private final PropertyChangeSupport propertySupport ; public Bean(String name) { this.name = name ; this.propertySupport = new PropertyChangeSupport(this); } public Bean() { this(""); } public String getName() { return name ; } public String setName(String name) { String oldName = this.name ; this.name = name ; propertySupport.firePropertyChange("name", oldName, name); } public void addPropertyChangeListener(PropertyChangeListener listener) { propertySupport.addPropertyChangeListener(listener); } } </code></pre> <p>Then the following code:</p> <pre><code>Bean bean = new Bean(); StringProperty nameProperty() = new JavaBeanStringPropertyBuilder() .bean(bean) .name("name") .build(); nameProperty().addListener((obs, oldName, newName) -&gt; System.out.println("name changed from "+oldName+" to "+newName)); bean.setName("James"); System.out.println(nameProperty().get()); </code></pre> <p>will produce the output:</p> <pre><code>name changed from to James James </code></pre> <p>If the JavaBean does not support <code>PropertyChangeListener</code>s, then changes to the bean via <code>bean.setName(...)</code> will not propagate to <code>ChangeListener</code>s or <code>InvalidationListener</code>s registered with the <code>JavaBeanStringProperty</code>.</p> <p>So if the bean is simply</p> <pre><code>public class Bean { public Bean() { this(""); } public Bean(String name) { this.name = name ; } private String name ; public String getName() { return name ; } public void setName(String name) { this.name = name ; } } </code></pre> <p>The JavaBeanStringProperty would have no way to observe the change, so the change listener would never be invoked by a call to <code>bean.setName()</code>. So the test code above would simply output</p> <pre><code>James </code></pre>
48,218,065
ProgrammingError: SQLite objects created in a thread can only be used in that same thread
<p>i'm fairly new to programming. I've tried MySQL before, but now it's my first time using SQLite in a python flask website. So maybe I'm using MySQL syntax instead of SQLite, but I can't seem to find the problem.</p> <pre><code>Piece of my code: @app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm(request.form) if request.method=='POST' and form.validate(): name = form.name.data email = form.email.data username = form.username.data password = sha256_crypt.encrypt(str(form.password.data)) c.execute("INSERT INTO users(name,email,username,password) VALUES(?,?,?,?)", (name, email, username, password)) conn.commit conn.close() The error: File "C:\Users\app.py", line 59, in register c.execute("INSERT INTO users(name,email,username,password) VALUES(?,?,?,?)", (name, email, username, password)) ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 23508 and this is thread id 22640 </code></pre> <p>Does this mean I can't use the name, email username &amp; password in an HTML file? How do I solve this? </p> <p>Thank you.</p>
48,218,213
9
1
null
2018-01-12 00:52:17.887 UTC
21
2022-05-14 03:22:34.567 UTC
null
null
null
null
9,136,764
null
1
105
python|mysql|sqlite|flask
111,715
<p>Your cursor 'c' is not created in the same thread; it was probably initialized when the Flask app was run.</p> <p>You probably want to generate SQLite objects (the conneciton, and the cursor) in the same method, such as:</p> <pre><code> @app.route('/') def dostuff(): with sql.connect("database.db") as con: name = "bob" cur = con.cursor() cur.execute("INSERT INTO students (name) VALUES (?)",(name)) con.commit() msg = "Done" </code></pre>
29,477,393
Is middleware neeeded to redirect to HTTPS in ASP.net and C#?
<p>What is the recommend way to redirect to HTTPS all incoming requests that are not secure. Do I need to write a middleware component? If so, I couldn't figure out how to get the server name.</p> <pre><code>public class RedirectHttpMiddleware { RequestDelegate _next; public RedirectHttpMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { if (context.Request.IsSecure) await _next(context); else { var server = ""; // How do I get the server name? context.Response.Redirect("https://" + server + context.Request.Path); } } } </code></pre>
29,477,556
12
2
null
2015-04-06 18:39:07.053 UTC
17
2021-12-14 16:48:18.843 UTC
2021-12-14 16:48:18.843 UTC
null
1,145,388
null
3,151,470
null
1
36
c#|redirect|https|asp.net-core|middleware
21,533
<p>You can use your own middleware class, but typically I just do something like this in my Startup configuration:</p> <pre><code>app.Use(async (context, next) =&gt; { if (context.Request.IsHttps) { await next(); } else { var withHttps = Uri.UriSchemeHttps + Uri.SchemeDelimiter + context.Request.Uri.GetComponents(UriComponents.AbsoluteUri &amp; ~UriComponents.Scheme, UriFormat.SafeUnescaped); context.Response.Redirect(withHttps); } }); </code></pre> <p>What this does is just grab the entire URL, query string and all, and use <code>GetComponents</code> to get everything <em>except</em> the scheme in the URL. Then the HTTPS scheme gets prepended to the components URL.</p> <p>This will work with the full .NET Framework, for ASP.NET Core, you can do something like this:</p> <pre><code>app.Use(async (context, next) =&gt; { if (context.Request.IsHttps) { await next(); } else { var withHttps = "https://" + context.Request.Host + context.Request.Path; context.Response.Redirect(withHttps); } }); </code></pre> <p>This appends the host and the path to the HTTPS scheme. You may want to add other components such as the query and hash, too.</p>
29,576,063
How to attach navbar only on certain pages using ui-router?
<p>How to display a navbar on every page except landingpage, so that not have to attach a navbar file on each of needed pages? Now I have enclosed navbar on main app layout, how it should be handled to keep it DRY?</p> <p>Demo (with navbar on each page):</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var App = angular.module('app', ['ui.router']); App.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/home', templateUrl: 'home.html' }) .state('about', { url: '/about', templateUrl: 'about.html' }).state('landingpage', { url: '/landingpage', templateUrl: 'landingpage.html' }); $urlRouterProvider.otherwise('/home'); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"&gt;&lt;/script&gt; &lt;link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" /&gt; &lt;div ng-app="app"&gt; &lt;div ng-include="'navbar.html'"&gt;&lt;/div&gt; &lt;div class="container"&gt; &lt;div ui-view&gt;&lt;/div&gt; &lt;/div&gt; &lt;script type="text/ng-template" id="navbar.html"&gt; &lt;nav class="navbar navbar-inverse" role="navigation"&gt; &lt;div class="navbar-header"&gt; &lt;a class="navbar-brand" ui-sref="landingpage"&gt;LandingPage&lt;/a&gt; &lt;/div&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a ui-sref="home"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a ui-sref="about"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li ng-hide="signedIn()"&gt;&lt;a href="/login"&gt;Log In&lt;/a&gt;&lt;/li&gt; &lt;li ng-show="signedIn()"&gt;&lt;a ng-click="logout()"&gt;Log Out&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/script&gt; &lt;script type="text/ng-template" id="home.html"&gt; &lt;h1&gt;The Homey Page&lt;/h1&gt; &lt;/script&gt; &lt;script type="text/ng-template" id="about.html"&gt; &lt;h1&gt;The About Page&lt;/h1&gt; &lt;/script&gt; &lt;script type="text/ng-template" id="landingpage.html"&gt; &lt;h1&gt;Landing Page&lt;/h1&gt; &lt;a ui-sref="home"&gt;Home&lt;/a&gt; &lt;/script&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
29,577,344
1
2
null
2015-04-11 09:06:53.103 UTC
12
2015-04-11 11:28:08.973 UTC
2015-04-11 10:47:29.97 UTC
null
171,456
null
707,729
null
1
15
javascript|angularjs|twitter-bootstrap|angular-ui-router|angularjs-ng-include
9,094
<p>Created named views like <code>&lt;div ui-view name="nav"&gt;&lt;/div&gt;</code> and set the templateUrl by view by state. For the <code>landingpage</code> state, just don't provide a templateUrl for the <code>nav</code> view and it won't render the navbar.</p> <p><strong>Update</strong>: hide on <code>landingpage</code> not <code>home</code> state.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var App = angular.module('app', ['ui.router']); App.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/home', views: { nav: { templateUrl: 'navbar.html' }, content: { templateUrl: 'home.html' } } }) .state('about', { url: '/about', views: { nav: { templateUrl: 'navbar.html' }, content: { templateUrl: 'about.html' } } }).state('landingpage', { url: '/landingpage', views: { content: { templateUrl: 'landingpage.html' } } }); $urlRouterProvider.otherwise('/home'); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"&gt;&lt;/script&gt; &lt;link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css" /&gt; &lt;div ng-app="app"&gt; &lt;div ui-view name="nav"&gt;&lt;/div&gt; &lt;div class="container"&gt; &lt;div ui-view name="content"&gt;&lt;/div&gt; &lt;/div&gt; &lt;script type="text/ng-template" id="navbar.html"&gt; &lt;nav class="navbar navbar-inverse" role="navigation"&gt; &lt;div class="navbar-header"&gt; &lt;a class="navbar-brand" ui-sref="landingpage"&gt;LandingPage&lt;/a&gt; &lt;/div&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a ui-sref="home"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a ui-sref="about"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li ng-hide="signedIn()"&gt;&lt;a href="/login"&gt;Log In&lt;/a&gt;&lt;/li&gt; &lt;li ng-show="signedIn()"&gt;&lt;a ng-click="logout()"&gt;Log Out&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/script&gt; &lt;script type="text/ng-template" id="home.html"&gt; &lt;h1&gt;The Homey Page&lt;/h1&gt; &lt;/script&gt; &lt;script type="text/ng-template" id="about.html"&gt; &lt;h1&gt;The About Page&lt;/h1&gt; &lt;/script&gt; &lt;script type="text/ng-template" id="landingpage.html"&gt; &lt;h1&gt;Landing Page&lt;/h1&gt; &lt;a ui-sref="home"&gt;Home&lt;/a&gt; &lt;/script&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
36,580,963
Can you, or should you use localStorage in Redux's initial state?
<p>For example... </p> <pre><code>export const user = (state = { id: localStorage.getItem('id'), name: localStorage.getItem('name'), loggedInAt: null }, action) =&gt; { case types.LOGIN: localStorage.setItem('name', action.payload.user.name); localStorage.setItem('id', action.payload.user.id); return { ...state, ...action.payload.user } default: return { ...state, loggedInAt: Date.now() } } </code></pre> <p>That's a scaled down version of what I'm doing, default returns the state from localStorage as expected. However the state of my application is actually blank once I refresh the page. </p>
36,581,186
1
3
null
2016-04-12 18:10:07.013 UTC
8
2019-02-28 22:20:33.843 UTC
null
null
null
null
1,541,609
null
1
30
javascript|reactjs|ecmascript-6|redux|flux
16,271
<p>Redux <a href="http://redux.js.org/docs/api/createStore.html" rel="noreferrer"><code>createStore</code></a> 2nd param is intended for store initialization:</p> <pre><code>createStore(reducer, [initialState], [enhancer]) </code></pre> <p>So you can do something like this:</p> <pre><code>const initialState = { id: localStorage.getItem('id'), name: localStorage.getItem('name'), loggedInAt: null }; const store = createStore(mainReducer, initialState); </code></pre> <p>Since reducers should be pure functions (i.e. no side effects) and <code>localStorage.setItem</code> is a side effect, you should avoid saving to localStorage in a reducer.</p> <p>Instead you can:</p> <pre><code>store.subscribe(() =&gt; { const { id, name } = store.getState(); localStorage.setItem('name', name); localStorage.setItem('id', id); }); </code></pre> <p>This will happen whenever the state changes, so it might affect performance.</p> <p>Another option is to save the state only when the page is closed (refresh counts) using <code>onBeforeUnload</code>:</p> <pre><code>window.onbeforeunload = () =&gt; { const { id, name } = store.getState(); localStorage.setItem('name', name); localStorage.setItem('id', id); }; </code></pre>
4,366,177
Static block on home page in Magento
<p>I am trying to add a static block to the home page of a Magento site using the layout XML file.</p> <p>I can see how to add and remove block inside a reference, but I am struggling to see how to add it for a specific page, i.e. the home page.</p> <pre><code>&lt;block type="cms/block" name="home-page-block"&gt; &lt;action method="setBlockId"&gt;&lt;block_id&gt;home-page-block&lt;/block_id&gt;&lt;/action&gt; &lt;/block&gt; </code></pre> <p>How would I wrap this code in the <code>page.xml</code> file for it to be only used on the homepage?<br> Or is there a better way? Should the home page be a new template?</p>
4,366,398
1
0
null
2010-12-06 12:02:40.57 UTC
9
2017-03-29 05:34:38.727 UTC
2012-07-07 06:14:39.42 UTC
null
635,608
null
347,180
null
1
15
xml|magento
37,225
<p>In any layout file used by your theme add the following.</p> <pre><code>&lt;cms_index_index&gt; &lt;reference name="content"&gt; &lt;block type="cms/block" name="home-page-block"&gt; &lt;action method="setBlockId"&gt;&lt;block_id&gt;home-page-block&lt;/block_id&gt;&lt;/action&gt; &lt;/block&gt; &lt;/reference&gt; &lt;/cms_index_index&gt; </code></pre> <p><code>cms_index_index</code> is specific to the home page.</p>
39,526,595
EntityFramework Core automatic migrations
<p>Is there any code to perform automatic migration in <code>Entity Framework core</code> <code>code first</code> in asp.net core project?</p> <p>I do it simply in MVC4/5 by adding</p> <pre><code>Database.SetInitializer(new MigrateDatabaseToLatestVersion&lt;AppDbContext, MyProject.Migrations.Configuration&gt;()); public Configuration() { AutomaticMigrationsEnabled = true; } </code></pre> <p>This saves time when entities changed</p>
39,526,807
10
1
null
2016-09-16 08:07:57.807 UTC
9
2022-04-12 14:26:03.987 UTC
2016-09-16 10:41:26.773 UTC
null
1,077,309
null
4,404,269
null
1
50
entity-framework|asp.net-core|entity-framework-core
72,631
<p>You can call <code>context.Database.Migrate()</code>in your <code>Startup.cs</code></p> <p>eg:</p> <pre><code>using (var context = new MyContext(...)) { context.Database.Migrate(); } </code></pre>
39,414,692
A javascript 'let' global variable is not a property of 'window' unlike a global 'var'
<p>I used to check if a global <code>var</code> has been defined with:</p> <pre><code>if (window['myvar']==null) ... </code></pre> <p>or</p> <pre><code>if (window.myvar==null) ... </code></pre> <p>It works with <code>var myvar</code></p> <p>Now that I am trying to switch to let, this does not work anymore.</p> <pre><code>var myvar='a'; console.log(window.myvar); // gives me a let mylet='b'; console.log(window.mylet); // gives me undefined </code></pre> <p>Question: With a global <code>let</code>, is there any place I can look if something has been defined like I could with <code>var</code> from the <code>window</code> object?</p> <p><b>More generally</b>:<br> Is <code>var myvar='a'</code> equivalent to <code>window.myvar='a'</code>?<br> I hear people say that at the global level, <code>let</code> and <code>var</code> are/behave the same, but this is not what I am seeing.</p>
39,414,995
1
6
null
2016-09-09 15:10:39.147 UTC
12
2018-07-12 15:03:20.74 UTC
null
null
null
null
1,413,206
null
1
16
javascript|var|let
16,207
<blockquote> <p>I hear people say that at the global level, let and var are/behave the same, but this is not what I am seeing.</p> </blockquote> <p>Eh, yes and no. To answer your question, in the large majority of cases <code>let</code> and <code>var</code> are the same when declared globally, but there are some differences.</p> <p>To explain: A <strong>global environment record</strong> is where JS keeps all the logic and memory values for the code in play. However, this global environment record is really a composite encapsulating an <strong>object environment record</strong> and a <strong>declarative environment record</strong>.</p> <p>Some more explanation:</p> <p>A <strong>declarative environment record</strong> stores the bindings in an internal data structure. It's impossible to get a hold of that data structure in any way (think about function scope).</p> <p>An <strong>object environment record</strong> uses an actual JS object as data structure. Every property of the object becomes a binding and vice versa. The global environment has an object environment record whose "binding object" is the global object. This would be the <em>Realm</em>, which in most cases is the <code>window</code> object. </p> <p>So, per the ECMA spec, only <em>FunctionDeclarations</em>, <em>GeneratorDeclarations</em>, and <em>VariableStatements</em> create bindings in the <strong>global</strong> environment's object environment record.</p> <p>All other declarations (i.e <code>const</code> and <code>let</code>) are stored in the global environment's <strong>declarative</strong> environment record, which is not based on the global object. They still declare a variable, but are not a <em>VariableStatement</em>.</p> <p><strong>TL;DR: Both are still global, but <code>var</code>s are stored in the <code>window</code> object, while <code>let</code>s are stored in a declarative environment that you can't see (just like you can't access a variable in a function scope from outside of the function). When declared globally, both statements are pretty much identical in use.</strong></p>
19,965,197
Change column values in an R dataframe
<p>I have a data frame formatted like this in R:</p> <p><img src="https://i.stack.imgur.com/FSQvT.png" alt="dataframe"></p> <p>How could I call up all the HEIGHT values where GROUP is equal to B and change them? I.e. from cm to mm. </p>
19,965,337
2
1
null
2013-11-13 21:55:39.54 UTC
null
2021-06-11 16:40:14.66 UTC
2015-12-02 23:59:13.223 UTC
null
4,370,109
null
1,658,170
null
1
2
r|dataframe
54,086
<pre><code>data = data.frame( group = rep(c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;), each = 4), height = c(259, 243, 253, 235, 23.5, 23.6, 23.5, 24.1, 235, 234, 235, 220) ) data #shows your data #from cm to mm data$height[data$group == &quot;B&quot;] &lt;- data$height[data$group == &quot;B&quot;] * 10 </code></pre>
7,511,353
Change iPhone splash screen time
<p>How would I make the splash screen stay for longer, 5 seconds, for example?</p>
7,511,511
4
7
null
2011-09-22 07:48:53.537 UTC
10
2016-11-24 11:50:23.983 UTC
null
null
null
null
948,163
null
1
7
iphone|ios|xcode|splash-screen
33,968
<p>You need to create a view controller for displaying the splash screen as done below. </p> <pre><code> - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self generateRandomSplashScreen]; [self performSelector:@selector(removeSplashScreen) withObject:nil afterDelay:SPLASHSCREEN_DELAY]; [self otherViewControllerLoad]; // the other view controller [self.window makeKeyAndVisible]; return YES; } -(void) generateRandomSplashScreen { splashScreenViewController = [[SplashScreenController alloc] initWithNibName:@"SplashScreenController" bundle:[NSBundle mainBundle]]; [self.window addSubview:self.splashScreenViewController.view]; } -(void) removeSplashScreen { [splashScreenViewController.view removeFromSuperview]; self.window.rootViewController = self.tabBarController; [splashScreenViewController release]; } </code></pre>
7,397,988
Android GridView with categories?
<p>Is it possible to use categories or some sort of headers with a <code>GridView</code> in Android?</p> <p>I put together a quick illustration of what I was thinking about:</p> <p><img src="https://i.stack.imgur.com/09tNQ.jpg" alt="enter image description here"></p> <p>Thanks a lot.</p>
15,547,863
4
8
null
2011-09-13 07:01:59.43 UTC
7
2016-08-30 12:42:03.82 UTC
null
null
null
null
762,442
null
1
33
android|gridview|android-3.0-honeycomb
21,097
<p>You can use <a href="http://tonicartos.github.com/StickyGridHeaders/">Stickygridheaders</a> library directly or as a model to create your own widget.</p>
7,335,920
What specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX?
<p>I can take a guess based on the names, but what specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX?</p> <p>Is user-cpu time the amount of time spent executing user-code while kernel-cpu time the amount of time spent in the kernel due to the need of privileged operations (like IO to disk)?</p> <p>What unit of time is this measurement in?</p> <p>And is wall-clock time really the number of seconds the process has spent on the CPU or is the name just misleading?</p>
7,335,965
4
1
null
2011-09-07 14:50:01.247 UTC
69
2021-03-09 13:33:10.81 UTC
2021-03-09 13:33:10.81 UTC
null
3,924,118
null
857,994
null
1
190
unix|operating-system
105,516
<p>Wall-clock time is the time that a clock on the wall (or a stopwatch in hand) would measure as having elapsed between the start of the process and 'now'.</p> <p>The user-cpu time and system-cpu time are pretty much as you said - the amount of time spent in user code and the amount of time spent in kernel code.</p> <p>The units are seconds (and subseconds, which might be microseconds or nanoseconds).</p> <p>The wall-clock time is not the number of seconds that the process has spent on the CPU; it is the elapsed time, including time spent waiting for its turn on the CPU (while other processes get to run).</p>
24,441,178
Recommended Minimum Android App SDK
<p>I am making an android app, and am wondering what the industry's thoughts are on supporting older android versions like GingerBread and FroYo. Should a developer like me take the extra step to make my app compatible with those older versions, or are they obsolete? I am speaking in terms of the market in 2014.</p> <p>Increasing my minimum SDK version opens up some more APIs, so which option should I pick, compatibility or APIs and features?</p>
24,441,258
8
1
null
2014-06-26 22:21:58.777 UTC
8
2022-08-02 08:51:51.733 UTC
null
null
null
null
2,518,263
null
1
47
android|sdk
65,019
<p>Most of the Android devices are above the Gingerbread level. But there are still a decent number of those devices out there. You, as a developer, must decide if the number of users who would potentially download your app for those versions of Android is worth the level of effort in developing the app for those versions. For the past year, both companies I've worked at have begun to work on 4.0 and above only and have forsaken the lower versions.</p> <p>To get the current information on what the ecosystem looks like for Android, check out <a href="https://developer.android.com/about/dashboards/" rel="noreferrer">Google's dashboard</a></p> <p>As I write this comment, Gingerbread and below is around 15% of the total population.</p> <p><strong>2019 UPDATE:</strong> <a href="https://developer.android.com/about/dashboards/" rel="noreferrer">Google's dashboard</a> states that only 0.2% of Android users are running Gingerbread (Android 2.3). Around 3% are using Jelly Bean (Android 4.1/4.2/4.3), and 7.6% are running KitKat (Android 4.4).</p> <p>Generally, companies target a minimum version of KitKat, or SDK 19, for new endeavors. For personal projects, we usually choose Lollipop, or SDK 21, as it brings a number of improvements to the table, such as improved build times.</p>
1,435,012
switch statement in Jquery and List
<p>I would like to know if my approach is efficient and correct. my code is not working though, I don't know why.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { function HotelQuery(HotelName) { switch (HotelName) { case 'TimelessHotel': var strHotelName = 'Timeless Hotel'; var strHotelDesc = 'Hotel Description Timeless Hotel'; var strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00']; var strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person']; ; //end Timeless Hotel case 'ParadiseInn': var strHotelName = 'Paradise Inn'; var strHotelDesc = 'Hotel Description Paradise Inn'; var strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00']; var strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person']; ; //end Paradise Inn case 'TetrisHotel': var strHotelName = 'Tetris Hotel'; var strHotelDesc = 'Hotel Description Tetris Hotel'; var strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00']; var strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person']; ; //end Tetris Hotel case 'JamstoneInn': var strHotelName = 'Jamstone Inn'; var strHotelDesc = 'Hotel Description Jamstone Inn'; var strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00']; var strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person']; ; //end Jamstone Inn } }; }); &lt;/script&gt; &lt;title&gt;hotel query&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#" onclick="javascript: HotelQuery('TetrisHotel'); alert: (strHotelName, strHotelDesc, strHotelPrice);"&gt;Tetris Hotel Query&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1,435,074
4
0
null
2009-09-16 19:30:24.003 UTC
3
2012-12-20 14:22:37.48 UTC
2009-09-16 19:34:08.08 UTC
null
1,831
null
173,072
null
1
8
javascript|jquery|switch-statement|conditional-statements
74,256
<p>You code doesn't work because the variables are scoped to the function <code>HotelQuery</code>. I think what you might want to do is return an object with properties from the function, and also use the unobtrusive JavaScript approach to bind an click event handler to the <code>&lt;a&gt;</code> element.</p> <p>Something like</p> <pre><code>$(function() { $('a').click(function() { var hotel = HotelQuery('TetrisHotel'); alert(hotel.name) // alerts 'Tetris Hotel' }); }); function HotelQuery(HotelName) { var strHotelName; var strHotelDesc; var strHotelPrice; var strHotelRoomType; switch (HotelName) { case 'TimelessHotel': strHotelName = 'Timeless Hotel'; strHotelDesc = 'Hotel Description Timeless Hotel'; strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00']; strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person']; break; //end Timeless Hotel case 'ParadiseInn': strHotelName = 'Paradise Inn'; strHotelDesc = 'Hotel Description Paradise Inn'; strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00']; strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person']; break; //end Paradise Inn case 'TetrisHotel': strHotelName = 'Tetris Hotel'; strHotelDesc = 'Hotel Description Tetris Hotel'; strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00']; strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person']; break; //end Tetris Hotel case 'JamstoneInn': strHotelName = 'Jamstone Inn'; strHotelDesc = 'Hotel Description Jamstone Inn'; strHotelPrice = ['980.00', '1,300.00', '1,600.00', '1,500.00', '1,800.00', '300.00', '150.00', '200.00']; strHotelRoomType = ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person']; break; //end Jamstone Inn } return { name: strHotelName, desc: strHotelDesc, price: strHotelPrice, roomType: strHotelRoomType } }; </code></pre> <p>Just noticed that you're also returning the same values other than the hotel name and description each time <em>(you might have done this just as an example, I'm not sure)</em>. You could just assign all variables their value on declaration (or assign the values as properties of the returned object), other than the hotel name and description, which you could assign from the value of the argument for parameter <code>HotelName</code>. Something like</p> <pre><code>function hotelQuery(hotelName) { return { name: hotelName, desc: 'Hotel Desciption' + hotelName, // Keep prices as numbers and have a function to display them // in the culture specific way. Numbers for prices will be easier to deal with price: [980, 1300, 1600, 1500, 1800, 300, 150, 200], roomType: ['Single Room', 'Delux Room','Twin Room', 'Matrimonial Room', 'Presidential Suites', 'Extra Bed', 'Free Breakfast', 'Extra Person'] } } </code></pre>
42,593,975
Make front- and backend (Angular 2 and Spring) Maven Multimodule Project
<p>How do I create a Maven multimodule project with a Spring backend and Angular2 front-end? Using spring initializr (<a href="https://start.spring.io" rel="noreferrer">https://start.spring.io</a>) and angular cli separately seems to be straightforward, but how do I organize that as a multi-module Maven project with linked but separate pom-files? With what values and in what order should I create and initialize those? I can use Intellij IDEA if it makes things easier, but i am also fine with CMD (I'm on windows).</p> <p>The only tutorial I found on this is here: <a href="https://blog.jdriven.com/2016/12/angular2-spring-boot-getting-started/" rel="noreferrer">https://blog.jdriven.com/2016/12/angular2-spring-boot-getting-started/</a> but the guy uses some self-written "frontend-maven-plugin" which I do not want. Can someone explain the steps or link me to a tutorial that doesn't use third-party-resources but just clean Spring and Angular2, please?</p> <blockquote> <p>EDIT: when I posted this question, WebDevelopment was for the most part new to me. The below solution worked at the beginning, but for better scalability we decided to make separate projects later on: one FE project containing multiple Angular apps and many FE-libs (check out <a href="https://github.com/nrwl/nx" rel="noreferrer">NRWL's NX</a> for that). And one project for each BE-Microservice, each deployable separately in the CI-Pipelines. Google themselves go with the approach of one project for all the FEs and BEs, but they do have special requirements (all libs have to work with each other in the latest version) and they use the ABC-stack (Angular + Bazel + Closure) stack for that, which is not yet fully available for the public, but is worth keeping an eye on: <a href="https://github.com/angular/angular/issues/19058" rel="noreferrer">https://github.com/angular/angular/issues/19058</a></p> </blockquote>
43,032,863
1
9
null
2017-03-04 08:44:44.347 UTC
12
2018-06-13 13:09:31.453 UTC
2018-06-13 13:09:31.453 UTC
null
4,125,622
null
4,125,622
null
1
15
spring|maven|angular|spring-boot|angular-cli
16,079
<p>The recommended way to build an Angular 2 application is to make use of Angular CLI tool. Similarly when you work with Java EE projects you typically use Maven as the build tool.</p> <p>To get the best of both worlds you can develop a multi module project as you already figured.</p> <p>If you would like then just clone this sample:</p> <p>git clone <a href="https://github.com/prashantpro/ng-jee.git" rel="noreferrer">https://github.com/prashantpro/ng-jee.git</a></p> <p>Given the frontend/UI project will be Angular 2 application. Backend project can be Spring or purely Java EE application (Any web app).</p> <p>We want to take the Angular 2 output (<strong>dist</strong> directory) and map it into the web application project for the UI part.</p> <p>Here's how you can do it without any fancy third party plugins. Lets take this Multi module project structure as an example:</p> <p><strong>cd ng-jee</strong> (This is your parent POM project)</p> <pre><code>. ├── pom.xml ├── ngdemo │   ├── pom.xml --- maven pom for angular module │   ├── dist --- This will be Angular output │   ├── e2e │   ├── karma.conf.js │   ├── node_modules │   ├── package.json │   ├── protractor.conf.js │   ├── README.md │   ├── src │   ├── tsconfig.json │   └── tslint.json └── webdemo ├── pom.xml └── src </code></pre> <p>The parent pom.xml needs to list both modules. The <strong>first</strong> module should be the UI (Angular 2) module followed by the Java/Spring module.</p> <p>The important section is shown below for <strong>ng-jee/pom.xml</strong></p> <pre><code>&lt;packaging&gt;pom&lt;/packaging&gt; &lt;modules&gt; &lt;module&gt;ngdemo&lt;/module&gt; &lt;module&gt;webdemo&lt;/module&gt; &lt;/modules&gt; </code></pre> <p>Next, if you have created your angular app using CLI like this:</p> <p>ng new ngdemo</p> <p>Then you need to place a pom.xml in that same directory <strong>ngdemo/pom.xml</strong> Having the below build plugins: (This will build the Angular CLI project and generate output in its <strong>dist</strong> folder.</p> <pre><code> &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-clean-plugin&lt;/artifactId&gt; &lt;version&gt;3.0.0&lt;/version&gt; &lt;configuration&gt; &lt;failOnError&gt;false&lt;/failOnError&gt; &lt;filesets&gt; &lt;fileset&gt; &lt;directory&gt;.&lt;/directory&gt; &lt;includes&gt; &lt;include&gt;dist/**/*.*&lt;/include&gt; &lt;/includes&gt; &lt;followSymlinks&gt;false&lt;/followSymlinks&gt; &lt;/fileset&gt; &lt;/filesets&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.5.0&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;angular-cli build&lt;/id&gt; &lt;configuration&gt; &lt;workingDirectory&gt;.&lt;/workingDirectory&gt; &lt;executable&gt;ng&lt;/executable&gt; &lt;arguments&gt; &lt;argument&gt;build&lt;/argument&gt; &lt;argument&gt;--prod&lt;/argument&gt; &lt;argument&gt;--base-href&lt;/argument&gt; &lt;argument&gt;"/ngdemo/"&lt;/argument&gt; &lt;/arguments&gt; &lt;/configuration&gt; &lt;phase&gt;generate-resources&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;exec&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>The last piece of the puzzle is to reference this <strong>ngdemo/dist</strong> folder so we can copy the output into our WAR file.</p> <p>So, here's what needs to be done in <strong>webdemo/pom.xml</strong></p> <pre><code>&lt;build&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;src/main/resources&lt;/directory&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;configuration&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;webResources&gt; &lt;resource&gt; &lt;!-- this is relative to the pom.xml directory --&gt; &lt;directory&gt;../ngdemo/dist/&lt;/directory&gt; &lt;/resource&gt; &lt;/webResources&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>Now, if you build the project from the parent directory <strong>ng-jee</strong></p> <p><code>mvn clean install</code></p> <p>Then you will see that first it builds the Angular project then Web Project, while doing the build for the latter it also copies the Angular dist contents into the Web projects root. </p> <p>So you get something like the below in the WAR/Web project target directory:</p> <p>/ng-jee/webdemo/target/webdemo-1.0-SNAPSHOT.war</p> <pre><code>. ├── favicon.ico ├── index.html ├── inline.d72284a6a83444350a39.bundle.js ├── main.e088c8ce83e51568eb21.bundle.js ├── META-INF ├── polyfills.f52c146b4f7d1751829e.bundle.js ├── styles.d41d8cd98f00b204e980.bundle.css ├── vendor.fb5e0f38fc8dca20e0ec.bundle.js └── WEB-INF └── classes </code></pre> <p>That's it. I will be doing a series on few of these aspects and more here <a href="http://www.prashantp.org/blog/angular/2017/02/19/angular2-building-project.html" rel="noreferrer">Angular and JEE</a></p> <p>Till then hope this helps!</p>
49,530,465
Lombok plugin incompatible with 2018.1 Intellij Idea
<p>Right now I have seen Intellij Idea update window with the notion: </p> <blockquote> <p>Plugin incompatible with new build found: Lombok Plugin</p> </blockquote> <p><a href="https://i.stack.imgur.com/8u7Pi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8u7Pi.png" alt="enter image description here"></a></p> <p>Is there a way to solve the problem or I should wait till lombok plugin team resolved the compatibility issues?</p>
49,531,561
4
3
null
2018-03-28 09:11:51.747 UTC
2
2018-03-28 10:06:33.383 UTC
null
null
null
null
723,845
null
1
59
intellij-idea|lombok|intellij-lombok-plugin
19,964
<p>The following is a solution works for me:</p> <ol> <li>Update intellij idea (I use the community release zip package)</li> <li>Run Idea and open settings</li> <li>Select lombok plugin and reload list of plugins <a href="https://i.stack.imgur.com/dyitm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dyitm.png" alt="enter image description here"></a></li> <li>Then there will button <kbd>Update</kbd> instead of <kbd>Uninstall</kbd>. Press it and after updating restart Idea</li> </ol> <p>Have a look at <a href="https://github.com/mplushnikov/lombok-intellij-plugin/issues/465" rel="noreferrer">link</a> for more information.</p>
10,299,811
Creating new database from a backup of another Database on the same server?
<p>I am trying to create a new database from an old backup of database on the same server. When using <em>SQL server management studio</em> and trying to restore to the new DB from the backup I get this error</p> <pre><code>System.Data.SqlClient.SqlError: The backup set holds a backup of a database other than the existing 'test' database. (Microsoft.SqlServer.Smo) </code></pre> <p>after googling around I found this piece of code</p> <pre><code> RESTORE DATABASE myDB FROM DISK = 'C:\myDB.bak' WITH MOVE 'myDB_Data' TO 'C:\DATA\myDB.mdf', MOVE 'myDB_Log' TO 'C:\DATA\myDB_log.mdf' GO </code></pre> <p>I was wondering will the move statements mess with the database that the backup came from on that server?</p> <p>Thanks, all help appreciated.</p>
10,300,030
5
2
null
2012-04-24 14:16:29.38 UTC
16
2021-10-16 17:25:21.043 UTC
2013-09-11 07:52:36.373 UTC
null
1,989,820
null
1,353,886
null
1
85
sql|database|sql-server-2008
151,139
<h1>What I should to do:</h1> <ul> <li>Click on 'Restore Database ...' float menu that appears right clicking the &quot;Databases&quot; node on SQL Server Management Studio.</li> <li>Fill wizard with the database to restore and the new name.</li> <li><strong>Important</strong> If database still exists change the &quot;Restore As&quot; file names in the &quot;Files&quot; tab to avoid &quot;files already in use, cannot overwrite&quot; error message.</li> </ul> <h1>What I do</h1> <p>IDk why I prefer to do this:</p> <ul> <li>I create a blank target database with my favorite params.</li> <li>Then, in &quot;SQL Server Management Studio&quot; restore wizard, I look for the option to overwrite target database. It is in the 'Options' tab and is called <strong>'Overwrite the existing database (WITH REPLACE)'</strong>. Check it.</li> <li>Remember to select target files in 'Files' page.</li> </ul> <p>You can change 'tabs' at left side of the wizard (General, Files, Options)</p>
7,621,373
How do I change the date format of a DataBinder.Eval in asp.net?
<p>I'm trying to figure out how to change the datetime format so just the date will show up.</p> <pre><code> &lt;asp:Repeater ID="RepeaterActions" runat="server"&gt; &lt;ItemTemplate&gt; &lt;li&gt; &lt;span class="historyDate"&gt;&lt;%#DataBinder.Eval(Container.DataItem, "ActionListDate")%&gt;&lt;/span&gt; &lt;span class="historyName"&gt;&lt;%#DataBinder.Eval(Container.DataItem, "LeadActionName")%&gt;&lt;/span&gt;&lt;br /&gt; &lt;span class="historyNotes"&gt;&lt;%#DataBinder.Eval(Container.DataItem, "ActionListNote")%&gt;&lt;/span&gt; &lt;/li&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre> <p>I'm guessing it's something in between the &lt;% %>, but I'm not sure.</p> <p>My code behind is:</p> <pre><code>&lt;pre&gt; protected void RepeaterActionsFill() { string sql = @" select a.ActionListDate, a.LeadListID, a.ActionListNote, l.LeadActionName from ActionLists as a INNER JOIN LeadActions as l ON a.LeadActionID = l.LeadActionID where a.LeadListID = " + Convert.ToInt32(Request["id"].ToString()); RepeaterActions.DataSource = DBUtil.FillDataReader(sql); RepeaterActions.DataBind(); } &lt;/pre&gt; </code></pre> <p>Currently, it comes accross looking like this:</p> <p><img src="https://i.stack.imgur.com/BwRgb.png" alt="HTML View"></p> <p>And what I'm looking for is for the time stamp to be gone there.</p> <p>Any help is appreciated.</p> <p>EDIT:</p> <p>Here is what I was looking for:</p> <pre><code> &lt;asp:Repeater ID="RepeaterActions" runat="server"&gt; &lt;ItemTemplate&gt; &lt;li&gt; &lt;span class="historyDate"&gt;&lt;%#DataBinder.Eval(Container.DataItem, "ActionListDate", "{0:M/d/yy}")%&gt;&lt;/span&gt; &lt;span class="historyName"&gt;&lt;%#DataBinder.Eval(Container.DataItem, "LeadActionName")%&gt;&lt;/span&gt;&lt;br /&gt; &lt;span class="historyNotes"&gt;&lt;%#DataBinder.Eval(Container.DataItem, "ActionListNote")%&gt;&lt;/span&gt; &lt;/li&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre>
7,621,648
5
0
null
2011-10-01 16:09:09.767 UTC
5
2019-01-03 08:52:55.867 UTC
2011-10-01 17:20:17.52 UTC
null
957,627
null
957,627
null
1
40
c#|asp.net|sql-server
82,896
<p>give the format e.g: </p> <pre><code>&lt;%# DataBinder.Eval(Container.DataItem, "ActionListDate", "{0:d/M/yyyy hh:mm:ss tt}") %&gt; </code></pre>
13,903,257
HTML5 canvas, scale image after drawing it
<p>I'm trying to scale an image that has already been draw into canvas. This is the code:</p> <pre><code> var canvas = document.getElementById('splash-container'); var context = canvas.getContext('2d'); var imageObj = new Image(); imageObj.onload = function() { // draw image at its original size context.drawImage(imageObj, 0, 0); }; imageObj.src = 'images/mine.jpeg'; // Now let's scale the image. // something like... imageObj.scale(0.3, 0.3); </code></pre> <p>How should I do?</p>
13,903,654
2
0
null
2012-12-16 16:32:17.617 UTC
1
2014-03-18 01:46:07.81 UTC
null
null
null
null
1,200,252
null
1
13
image|html|canvas|scale
40,934
<p>You're thinking about it wrong. Once you've drawn the image onto the <code>canvas</code> it has no relationship to the <code>imageObj</code> object. Nothing you do to <code>imageObj</code> will affect what's already drawn. If you want to scale the image, do in the <a href="https://developer.mozilla.org/docs/Web/Guide/HTML/Canvas_tutorial/Using_images"><code>drawImage</code> function</a>:</p> <pre><code>drawImage(imgObj, 0, 0, imgObj.width * 0.3, imgObj.height * 0.3) </code></pre> <p>If you want to animate the scaling or are looking to achieve some other effect which requires you to draw the image at full size initially you'll have to first <a href="http://tutorials.jenkov.com/html5-canvas/clearrect.html">clear it</a> before drawing the scaled down image.</p>
13,933,077
Android AlertDialog setOnDismissListener for API lower than 17
<p>I created an AlertDialog:</p> <pre><code>private CharSequence[] _items = { "item1", "item2", "item3", "item4", "item5", "item6", "item7" }; AlertDialog.Builder daysBuilder = new AlertDialog.Builder(this); daysBuilder.setTitle("SomeCaption"); daysBuilder.setMultiChoiceItems(_items,new Boolean[] { false, true, false, false false false, true }, SetListener); daysBuilder.setPositiveButton("OK", OKListener); daysBuilder.setNegativeButton("Cancel", CancelListener); AlertDialog alert = daysBuilder.create(); alert.show();` </code></pre> <p>Through the statement "<code>new Boolean[] { false, true, false false false false, true }</code>" the items in the dialog get checked/unchecked by default.</p> <p>When I open the dialog, change the selection of the items but then dismiss (by pressing cancel or the back-button of the device) the dialog gets dismissed. So far so good.</p> <p>But when I reopen the dialog, the items have the checked/unchecked state of the previous changes from the last opening of the dialog.</p> <p>But when the dialog was dismissed at the first opening, I want to have the items checked/unchecked state like when I created the dialog (<code>new Boolean[] { false, true, false false false false, true }</code>).</p> <p>So basically I need an opportunity to get notified when the dialog gets dissmissed so I can then reset the state of the items.</p> <p>I tried it with the setOnDismissListener for the dialog object. Unfortunately this is just available in API 17.</p> <p>setOnDismissListener worked perfect for me (exactly what I need) in the emulator (API 17) but not on my device (Android 4.1 => API 16)</p> <p>Is there something similar in API 16?</p>
13,935,676
1
2
null
2012-12-18 12:31:29.64 UTC
3
2017-07-16 06:23:26.383 UTC
2017-07-16 06:23:26.383 UTC
null
5,250,273
null
1,900,916
null
1
30
java|android|dialog
6,105
<p>The problem is you are using <code>setOnDismissListener</code> of <code>AlertDialog.Builder</code>. This was introduced in Api level 17, <code>setOnDismissListener</code> of <code>AlertDialog</code> itself has been since api level 1.</p> <pre><code>AlertDialog alert = daysBuilder.create(); alert.setOndismissListener(yourdismisslistener); alert.show();` </code></pre>
13,881,292
What information does GCC Profile Guided Optimization (PGO) collect and which optimizations use it?
<p>Which information does GCC collect when I enable <code>-fprofile-generate</code> and which optimization does in fact uses the collected information (when setting the <code>-fprofile-use</code> flag) ?</p> <p>I need citations here. I've searched for a while but didn't found anything documented.</p> <p>Information regarding link-time optimization (LTO) would be a plus! =D</p>
13,881,504
2
0
null
2012-12-14 15:10:25.5 UTC
12
2017-10-29 01:09:36.897 UTC
2017-10-29 01:09:36.897 UTC
null
895,245
null
973,795
null
1
48
c++|gcc|pgo|lto
26,256
<p><code>-fprofile-generate</code> enables <code>-fprofile-arcs</code>, <code>-fprofile-values</code> and <code>-fvpt</code>.</p> <p><code>-fprofile-use</code> enables <code>-fbranch-probabilities</code>, <code>-fvpt</code>, <code>-funroll-loops</code>, <code>-fpeel-loops</code> and <code>-ftracer</code></p> <p>Source: <a href="http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Optimize-Options.html#Optimize-Options" rel="noreferrer">http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Optimize-Options.html#Optimize-Options</a></p> <p>PS. Information about LTO also on that page.</p>
13,793,060
`respond_to?` vs. `respond_to_missing?`
<p>What is the point of defining <code>respond_to_missing?</code> as opposed to defining <code>respond_to?</code>? What goes wrong if you redefine <code>respond_to?</code> for some class?</p>
13,793,573
2
0
null
2012-12-09 23:37:53.233 UTC
14
2019-11-06 14:28:49.813 UTC
null
null
null
null
314,166
null
1
54
ruby|metaprogramming
12,745
<p>Without <a href="http://ruby-doc.org/core/Object.html#method-i-respond_to_missing-3F" rel="noreferrer"><code>respond_to_missing?</code></a> defined, trying to get the method via <a href="http://ruby-doc.org/core/Object.html#method-i-method" rel="noreferrer"><code>method</code></a> will fail:</p> <pre><code>class Foo def method_missing name, *args p args end def respond_to? name, include_private = false true end end f = Foo.new f.bar #=&gt; [] f.respond_to? :bar #=&gt; true f.method :bar # NameError: undefined method `bar' for class `Foo' class Foo def respond_to? *args; super; end # “Reverting” previous redefinition def respond_to_missing? *args true end end f.method :bar #=&gt; #&lt;Method: Foo#bar&gt; </code></pre> <p><a href="https://stackoverflow.com/users/8279/marc-andre-lafortune">Marc-André</a> (a Ruby core committer) has a good <a href="http://blog.marc-andre.ca/2010/11/methodmissing-politely.html" rel="noreferrer">blog post on <code>respond_to_missing?</code></a>.</p>
14,178,264
C++11: Correct std::array initialization?
<p>If I initialize a std::array as follows, the compiler gives me a warning about missing braces </p> <pre><code>std::array&lt;int, 4&gt; a = {1, 2, 3, 4}; </code></pre> <p>This fixes the problem:</p> <pre><code>std::array&lt;int, 4&gt; a = {{1, 2, 3, 4}}; </code></pre> <p>This is the warning message:</p> <pre><code>missing braces around initializer for 'std::array&lt;int, 4u&gt;::value_type [4] {aka int [4]}' [-Wmissing-braces] </code></pre> <p>Is this just a bug in my version of gcc, or is it done intentionally? If so, why?</p>
14,178,283
5
8
null
2013-01-06 01:10:32.19 UTC
12
2022-07-21 21:22:56.453 UTC
2018-07-30 08:25:20.913 UTC
null
706,055
null
1,392,142
null
1
82
c++|arrays|c++11|initialization|c++14
103,767
<p>This is the bare implementation of <code>std::array</code>: </p> <pre><code>template&lt;typename T, std::size_t N&gt; struct array { T __array_impl[N]; }; </code></pre> <p>It's an aggregate struct whose only data member is a traditional array, such that the inner <code>{}</code> is used to initialize the inner array.</p> <p>Brace elision is allowed in certain cases with aggregate initialization (but usually not recommended) and so only one brace can be used in this case. See here: <a href="https://stackoverflow.com/questions/6041459/c-vector-of-arrays">C++ vector of arrays</a></p>
29,203,312
How can I retain the scroll position of a scrollable area when pressing back button?
<p>I have a long list of links inside a big scrollable div. Each time when a user click on a link then click the back button, it starts at the very top of the div. It is not user friendly to our users. Any ways to let the browser scroll to the previous position when pressing the back button? </p> <p>Thank you very much!</p>
29,203,427
8
2
null
2015-03-23 04:33:07.527 UTC
17
2022-04-21 05:31:07.74 UTC
null
null
null
null
2,335,065
null
1
29
javascript|jquery|html|google-chrome|browser
50,813
<p>During page unload, get the scroll position and store it in local storage. Then during page load, check local storage and set that scroll position. Assuming you have a div element with id <code>element</code>. In case it's for the page, please change the selector :)</p> <pre><code>$(function() { $(window).unload(function() { var scrollPosition = $("div#element").scrollTop(); localStorage.setItem("scrollPosition", scrollPosition); }); if(localStorage.scrollPosition) { $("div#element").scrollTop(localStorage.getItem("scrollPosition")); } }); </code></pre>
43,291,165
How to append multi dimensional array using for loop in python
<p>I am trying to <code>append</code> to a multi-dimensional array.</p> <p>This is what I have done so far:</p> <pre><code>arr=[[]] for i in range(10): for j in range(5): arr[i].append(i*j) print i,i*j print arr </code></pre> <p>This is my expected output:</p> <blockquote> <p><code>[[0,0,0,0,0],[0,1,2,3,4],[0,2,4,6,8],[0,3,6,9,12],[0,4,8,12,16],[0,5,10,15,20],[0,6,12,18,24],[0,7,14,21,28],[0,8,16,24,32],[0,9,18,27,36]]</code></p> </blockquote> <p>However, I am getting this error:</p> <blockquote> <p><code>IndexError</code>: list index out of range</p> </blockquote>
43,291,200
4
1
null
2017-04-08 06:59:23.53 UTC
2
2020-12-14 17:53:22.7 UTC
2017-04-08 07:11:47.427 UTC
null
7,256,039
null
996,366
null
1
6
python|arrays
46,565
<p>You're forgetting to append the empty list beforehand. Thus why you get a, <code>IndexError</code> when you try to do <code>arr[i]</code>.</p> <pre><code>arr = [] for i in range(10): arr.append([]) for j in range(5): arr[i].append(i*j) </code></pre>
9,095,748
Method Area and PermGen
<p>I was trying to understand the memory structure of HotSpot JVM and got confused with the two terms <strong>"Method Area"</strong> and <strong>"PermGen"</strong> space. The docs I referred to say that Method Area contains the definition of classes and methods including the byte code. Some other docs say that they are stored in the PermGen space. </p> <p>So can I conclude that these two memory areas are <strong>same</strong>?</p>
9,095,858
4
1
null
2012-02-01 12:24:14.017 UTC
12
2020-10-18 07:52:51.47 UTC
2019-03-14 10:02:54.11 UTC
null
2,361,308
null
830,753
null
1
20
java|memory-management|jvm|jvm-hotspot|permgen
19,246
<p>You should take a look at <a href="http://javapapers.com/core-java/java-jvm-memory-types/" rel="noreferrer">Java Memory Types</a> and optionally at this doc about the <a href="http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html" rel="noreferrer">Garbage Collection</a> in Java. The latter is very verbose and both are useful.</p> <p>Actually the Method area is a part of the Permanent Generation: </p> <blockquote> <p>A third generation closely related to the tenured generation is the permanent generation. The permanent generation is special because it holds data needed by the virtual machine to describe objects that do not have an equivalence at the Java language level. For example objects describing classes and methods are stored in the permanent generation.</p> </blockquote>
19,696,153
Difference between qt qml and qt quick
<p>I'm confused with QML, QtQuick 1.0 and QtQuick 2.0. What's the difference between them?</p> <p>I use QtCreator 2.8.1 based on Qt 5.1.1. I want to develop a desktop program, which technology should I use?</p>
19,706,567
2
2
null
2013-10-31 00:06:48.703 UTC
23
2019-04-03 09:15:21.55 UTC
2019-04-03 09:15:21.55 UTC
null
10,239,789
null
1,424,014
null
1
77
qt|qml|qt-quick|qtquick2
34,761
<p><strong>EDIT: Please refer to @TheBootroo for a better answer</strong></p> <p>Although my answer was accepted by the OP, I want to revise (or even) remove my answer.</p> <p>My answer was based on personal experiences with respect to Qt 5.2 in 2013 some of which is no longer valid today:</p> <ul> <li>QML is Qt Meta Language or Qt Modelling Language is a user interface markup language.</li> <li>QtQuick (both QtQuick 1.x and QtQuick 2.x) uses QML as a declarative language for designing user interface–centric applications.</li> </ul> <p>Back at Qt 5.2 when you built a Qt Quick Application a significant question was whether the app was QtQuick 1.x or a QtQuick 2.x. Not only did this affect the components that were available, but, it altered how the application was rendered.</p> <p>Back in 2013:</p> <ul> <li><p>QtQuick 1.x applications was often chosen if you had to target older operating systems (e.g. Windows XP) or older hardware (e.g. OLPC) because the QML UI components such as Buttons were rendered by components native to your OS. However, this meant you were targeting a lowest common denominator set of UI components and that your UI experience may vary from platform to platform.</p></li> <li><p>QtQuick 2.x application was chosen for a more consistent cross platform look, but, it required that your platform implemented OpenGLES sufficiently else, your application may fail to load. This, unfortunately, restricted your application to only the newest computer and devices that implemented OpenGLES.</p></li> </ul> <p>When I wrote my original answer, this lead me to recommend QtQuick 1.x in some scenarios over QtQuick 2.x.</p> <p>However, since then, Qt 5+ now allows you to target ANGLE on Windows which brings high performance OpenGL compatibility to Windows desktops by translating calls to Direct3D, which has much better driver support.</p>
45,086,480
.Net Core Model Binding JSON Post To Web API
<p>Just started a new project using .NET Core. Added my Web API controller and related method. Using Postman I created a JSON object and posted it to my controller method. Bear in mind the JSON object matches the Object param in the controller method exactly.</p> <p>In debug mode I can see the object, it is not null, the properties are there, HOWEVER the prop values are defaulted to their representatives types, <code>0</code> for <code>int</code>, etc.</p> <p>I've never seen this behavior before… so I took exactly the same code and object and replicated in a MVC project with a Web API 2 controller and it works perfectly.</p> <p>What am I missing, can I not POST JSON and model bind in .NET Core?</p> <p>Reading this article it seems I cannot unless I send as form POST or as querystring vars which by the way works fine.</p> <p><a href="https://lbadri.wordpress.com/2014/11/23/web-api-model-binding-in-asp-net-mvc-6-asp-net-5/" rel="noreferrer">https://lbadri.wordpress.com/2014/11/23/web-api-model-binding-in-asp-net-mvc-6-asp-net-5/</a></p> <p>JSON:</p> <pre><code>{ "id": "4", "userId": "3" "dateOfTest": "7/13/2017" } </code></pre> <p>Method:</p> <pre><code>[HttpPost] [Route("test1")] [AllowAnonymous] public IActionResult Test(Class1 data) { return Ok(); } </code></pre>
45,086,673
6
1
null
2017-07-13 16:35:06.217 UTC
2
2021-10-25 21:36:16.2 UTC
2017-10-24 14:26:26.917 UTC
null
1,548,895
null
2,237,982
null
1
18
c#|asp.net-core|asp.net-web-api2|model-binding|asp.net-core-webapi
45,219
<p><strong>NOTE: If you are using aspnet core 3.0, the solution can be found <a href="https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-3.1" rel="noreferrer">here</a>. For other versions, keep reading.</strong></p> <p>You need to mark your parameter as coming from the body with the <code>FromBody</code> attribute like this:</p> <pre><code>[HttpPost] [Route(&quot;test1&quot;)] [AllowAnonymous] public IActionResult Test([FromBody] Class1 data) { return Ok(); } </code></pre> <p>You need to make sure you're using <code>application/json</code> as your content type from Postman:</p> <p><a href="https://i.stack.imgur.com/197UW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/197UW.png" alt="Postman application/json" /></a></p> <p>Resulting in:</p> <p><a href="https://i.stack.imgur.com/n4cca.png" rel="noreferrer"><img src="https://i.stack.imgur.com/n4cca.png" alt="json POST action" /></a></p> <p>Make sure your property setters are public as well:</p> <pre><code>public class Person { public String Name; public Int32 Age; } </code></pre>
711,884
Python naming conventions for modules
<p>I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?</p>
711,892
5
0
null
2009-04-02 22:31:35.687 UTC
14
2019-08-13 07:09:29.003 UTC
null
null
null
cool-RR
76,701
null
1
125
python|naming-conventions
126,639
<p>Just nib. Name the class Nib, with a capital N. For more on naming conventions and other style advice, see <a href="https://www.python.org/dev/peps/pep-0008/#package-and-module-names" rel="noreferrer">PEP 8</a>, the Python style guide.</p>
224,689
Transactions in .net
<p>What are the best practices to do transactions in C# .Net 2.0. What are the classes that should be used? What are the pitfalls to look out for etc. All that commit and rollback stuff. I'm just starting a project where I might need to do some transactions while inserting data into the DB. Any responses or links for even basic stuff about transactions are welcome. </p>
224,702
5
2
null
2008-10-22 06:41:02.257 UTC
90
2016-09-13 13:29:03.043 UTC
2008-10-22 07:23:40.343 UTC
Xardas
1,688,440
Xardas
1,688,440
null
1
150
c#|.net|transactions
192,274
<p>There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):</p> <pre><code>using (IDbTransaction tran = conn.BeginTransaction()) { try { // your code tran.Commit(); } catch { tran.Rollback(); throw; } } </code></pre> <p>Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.</p> <p>The alternative is an ambient transaction; new in .NET 2.0, the <a href="http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx" rel="noreferrer">TransactionScope</a> object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).</p> <p>For example:</p> <pre><code>using(TransactionScope tran = new TransactionScope()) { CallAMethodThatDoesSomeWork(); CallAMethodThatDoesSomeMoreWork(); tran.Complete(); } </code></pre> <p>Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.</p> <p>If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.</p> <p>The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).</p> <p>All in all, a very, very useful object.</p> <p>Some caveats:</p> <ul> <li>On SQL Server 2000, a TransactionScope will go to DTC immediately; this is fixed in SQL Server 2005 and above, it can use the LTM (much less overhead) until you talk to 2 sources etc, when it is elevated to DTC.</li> <li>There is a <a href="https://stackoverflow.com/questions/195420/transactionscope-bug-in-net-more-information#195427">glitch</a> that means you might need to tweak your connection string</li> </ul>
104,953
Position an element relative to its container
<p>I'm trying to create a horizontal 100% stacked bar graph using HTML and CSS. I'd like to create the bars using <code>DIVs</code> with background colors and percentage widths depending on the values I want to graph. I also want to have a grid lines to mark an arbitrary position along the graph.</p> <p>In my experimentation, I've already gotten the bars to stack horizontally by assigning the CSS property <code>float: left</code>. However, I'd like to avoid that, as it really seems to mess with the layout in confusing ways. Also, the grid lines don't seem to work very well when the bars are floated.</p> <p>I think that CSS positioning should be able to handle this, but I don't yet know how to do it. I want to be able to specify the position of several elements relative to the top-left corner of their container. I run into this sort of issue regularly (even outside of this particular graph project), so I'd like a method that's:</p> <ol> <li>Cross-browser (ideally without too many browser hacks)</li> <li>Runs in Quirks mode</li> <li>As clear/clean as possible, to facilitate customizations</li> <li>Done without JavaScript if possible.</li> </ol>
105,035
5
1
null
2008-09-19 19:48:22.937 UTC
80
2020-03-30 22:38:30.827 UTC
2020-03-30 22:38:30.827 UTC
null
3,488
Kanook
3,488
null
1
196
html|css|positioning
246,220
<p>You are right that CSS positioning is the way to go. Here's a quick run down:</p> <p><code>position: relative</code> will layout an element relative to <em>itself.</em> In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).</p> <p>However, you're most likely interested in <code>position: absolute</code> which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has <code>position: relative</code> or <code>position: absolute</code> set on it, then it will act as the parent for positioning coordinates for its children.</p> <p>To demonstrate:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#container { position: relative; border: 1px solid red; height: 100px; } #box { position: absolute; top: 50px; left: 20px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="container"&gt; &lt;div id="box"&gt;absolute&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>In that example, the top left corner of <code>#box</code> would be 100px down and 50px left of the top left corner of <code>#container</code>. If <code>#container</code> did not have <code>position: relative</code> set, the coordinates of <code>#box</code> would be relative to the top left corner of the browser view port.</p>
940,707
How do I programmatically get the version of a DLL or EXE file?
<p>I need to get the product version and file version for a DLL or EXE file using Win32 native APIs in C or C++. I'm <em>not</em> looking for the Windows version, but the version numbers that you see by right-clicking on a DLL file, selecting "Properties", then looking at the "Details" tab. This is usually a four-part dotted version number x.x.x.x.</p>
940,743
6
4
null
2009-06-02 17:04:57.13 UTC
19
2017-06-13 21:15:04 UTC
2017-03-23 16:00:38.48 UTC
null
1,033,581
null
8,078
null
1
83
c++|winapi|dll|version|exe
96,826
<p>You would use the <a href="http://msdn.microsoft.com/en-us/library/ms647003.aspx" rel="noreferrer">GetFileVersionInfo</a> API.</p> <p>See <a href="http://msdn.microsoft.com/en-us/library/ms646985(VS.85).aspx" rel="noreferrer">Using Version Information</a> on the MSDN site.</p> <p>Sample:</p> <pre><code>DWORD verHandle = 0; UINT size = 0; LPBYTE lpBuffer = NULL; DWORD verSize = GetFileVersionInfoSize( szVersionFile, &amp;verHandle); if (verSize != NULL) { LPSTR verData = new char[verSize]; if (GetFileVersionInfo( szVersionFile, verHandle, verSize, verData)) { if (VerQueryValue(verData,"\\",(VOID FAR* FAR*)&amp;lpBuffer,&amp;size)) { if (size) { VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)lpBuffer; if (verInfo-&gt;dwSignature == 0xfeef04bd) { // Doesn't matter if you are on 32 bit or 64 bit, // DWORD is always 32 bits, so first two revision numbers // come from dwFileVersionMS, last two come from dwFileVersionLS TRACE( "File Version: %d.%d.%d.%d\n", ( verInfo-&gt;dwFileVersionMS &gt;&gt; 16 ) &amp; 0xffff, ( verInfo-&gt;dwFileVersionMS &gt;&gt; 0 ) &amp; 0xffff, ( verInfo-&gt;dwFileVersionLS &gt;&gt; 16 ) &amp; 0xffff, ( verInfo-&gt;dwFileVersionLS &gt;&gt; 0 ) &amp; 0xffff ); } } } } delete[] verData; } </code></pre>
17,483,726
Hide and show div when page load
<p>i have a div :</p> <pre><code>&lt;div id="postreply"&gt; &lt;asp:Label ID="lbStatus" CssClass="input-large1" runat="server" Text="Close" Width="600px"&gt;&lt;/asp:Label&gt; &lt;/div&gt; </code></pre> <p>i try to hide div when page load :</p> <pre><code>&lt;script type="text/javascript"&gt; window.onload = function() { var x = document.getElementById('lbStatus').innerText; if(x == "Close"){ $("#postreply").hide(); } }&lt;/script&gt; </code></pre> <p>anyone help me hide this div with lbStatus.Text = Close</p>
17,483,867
5
7
null
2013-07-05 07:47:59.47 UTC
1
2013-07-05 08:15:20.027 UTC
2013-07-05 07:50:31.68 UTC
null
1,563,422
null
2,514,731
null
1
2
javascript|jquery
51,434
<p>Try this, once with <code>$(document).ready</code>, it executes when HTML-Document is loaded and DOM is ready where as <code>window.onload</code> executes when complete page is fully loaded, including all frames, objects and images</p> <pre><code>$(document).ready(function() { if($("#lbStatus").val() == "Close"){ $("#postreply").hide(); } }); </code></pre> <p>As you are using <code>Asp.Net</code> try to use <code>ClientId</code> property</p> <pre><code>$(document).ready(function() { if($("#&lt;%=lbStatus.ClientID%&gt;").val() == "Close"){ $("#postreply").hide(); } }); </code></pre> <p>Changed <code>&lt;%=lbStatus.ClientID%&gt;</code> instead of <code>lbStatus</code></p> <p>Reference: <a href="http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/" rel="nofollow">http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/</a></p>
38,017,016
"async Task then await Task" vs "Task then return task"
<p>Quick question..</p> <p>In order to get some solid base understanding about Asynchronous Programming and the <code>await</code> I would like to know what the difference is between these two code snippets when it comes to multi threading and the execution sequence and time:</p> <p><strong>This</strong>:</p> <pre><code>public Task CloseApp() { return Task.Run( ()=&gt;{ // save database // turn off some lights // shutdown application }); } </code></pre> <p><strong>Versus this:</strong></p> <pre><code>public async Task CloseApp() { await Task.Run( ()=&gt;{ // save database // turn off some lights // shutdown application }); } </code></pre> <p>if I am calling it in this routine:</p> <pre><code>private async void closeButtonTask() { // Some Task 1 // .. await CloseApp(); // Some Task 2 // .. } </code></pre>
38,017,167
2
4
null
2016-06-24 15:30:53.113 UTC
16
2019-12-10 10:07:39.97 UTC
2019-12-10 10:07:39.97 UTC
null
2,063,755
null
5,890,227
null
1
95
c#|multithreading|asynchronous
28,193
<p>It is almost the same (in terms of threads etc.). But for the second one (using <code>await</code>) a lot more overhead will be created by the compiler.</p> <p>Methods declared as <code>async</code> and using <code>await</code> are converted into a <em>state machine</em> by the compiler. So when you hit the <code>await</code>, the control flow is returned to the calling method and execution of your <code>async</code> method is resumed after the <code>await</code> when the awaited <code>Task</code> has finished.</p> <p>As there is no more code after your <code>await</code>, there is no need to use <code>await</code> anyway. Simply return the <code>Task</code> is enough.</p>
21,359,130
Should 3.4 enums use UPPER_CASE_WITH_UNDERSCORES?
<p>As the documentation says, an enumeration is a set of symbolic names (members) bound to unique, <strong>constant</strong> values. The <a href="http://www.python.org/dev/peps/pep-0008/#constants">PEP8</a> says that constants are usually named as <code>UPPER_CASE</code>, should I use this notation in Python 3.4 <a href="http://docs.python.org/3.4/library/enum.html">enums</a>? If yes, why the examples in the docs are using <code>lower_case</code>?</p>
21,359,677
3
4
null
2014-01-26 03:04:13.773 UTC
5
2019-06-12 14:01:03.86 UTC
2014-01-26 03:09:12.293 UTC
null
1,212,596
null
2,116,607
null
1
41
python|python-3.x|enums|python-3.4
13,956
<p><strong>Update</strong></p> <p>The BDFL (Benevolent Dictator For Life) <a href="https://mail.python.org/pipermail/python-ideas/2016-September/042340.html" rel="noreferrer">has spoken</a>, and the <a href="https://docs.python.org/3/library/enum.html#creating-an-enum" rel="noreferrer"><code>Enum documentation</code></a> has changed to reflect all upper-case member names.</p> <hr> <p>The examples in the [previous] docs are lower-case primarily because one of the preexisting modules that Enum was based on used lower-case (or at least its author did ;).</p> <p>My usage of enum has usually been something along the lines of:</p> <pre><code>class SomeEnum(Enum): ... = 1 ... = 2 ... = 3 globals().update(SomeEnum.__members__) </code></pre> <p>which effectively puts all the members in the module namespace.</p> <p>So I would say whichever style feels more comfortable to you -- but pick a style and be consistent.</p>
20,968,562
how to convert a bs4.element.ResultSet to strings? Python
<p>I have a simple code like: </p> <pre><code> p = soup.find_all("p") paragraphs = [] for x in p: paragraphs.append(str(x)) </code></pre> <p>I am trying to convert a list I obtained from xml and convert it to string. I want to keep it with it's original tag so I can reuse some text, thus the reason why I am appending it like this. But the list contains over 6000 observations, thus an recursion error occurs because of the str:</p> <p>"RuntimeError: maximum recursion depth exceeded while calling a Python object"</p> <p>I read that you can change the max recursion but it's not wise to do so. My next idea was to split the conversion to strings into batches of 500, but I am sure that there has to be a better way to do this. Does anyone have any advice?</p>
20,969,389
2
6
null
2014-01-07 09:54:36.587 UTC
4
2017-02-05 00:36:39.517 UTC
null
null
null
null
2,774,210
null
1
17
python|beautifulsoup|runtime-error
83,479
<p>The problem here is probably that some of the binary graphic data at the bottom of <a href="http://www.sec.gov/Archives/edgar/data/1547063/000119312513465948/0001193125-13-465948.txt" rel="noreferrer">the document</a> contains the sequence of characters <code>&lt;P</code>, which Beautiful Soup is trying to repair into an actual HTML tag. I haven't managed to pinpoint which text is causing the "recursion depth exceeded" error, but it's somewhere in there. It's <code>p[6053]</code> for me, but since you seem to have modified the file a bit (or maybe you're using a different parser for Beautiful Soup), it'll be different for you, I imagine. </p> <p>Assuming you don't need the binary data at the bottom of the document to extract whatever you need from the <em>actual</em> <code>&lt;p&gt;</code> tags, try this:</p> <pre><code># boot out the last `&lt;document&gt;`, which contains the binary data soup.find_all('document')[-1].extract() p = soup.find_all('p') paragraphs = [] for x in p: paragraphs.append(str(x)) </code></pre>
17,973,357
What are the valid characters in PHP variable, method, class, etc names?
<p>What are the valid characters you can use in PHP names for variables, constants, functions, methods, classes, ...?</p> <p>The manual has <a href="http://php.net/manual/en/language.oop5.basic.php">some</a> <a href="http://www.php.net/manual/en/language.variables.basics.php">mentions</a> of the regular expression <code>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*</code>. When does this restriction apply and when does it not?</p>
17,973,365
2
0
null
2013-07-31 14:36:03.67 UTC
15
2022-01-31 14:48:52.05 UTC
null
null
null
null
385,378
null
1
36
php
14,847
<p>The <code>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*</code> regex only applies when the name is used directly in some special syntactical element. Some examples:</p> <pre><code>$varName // &lt;-- varName needs to satisfy the regex $foo-&gt;propertyName // &lt;-- propertyName needs to satisfy the regex class ClassName {} // &lt;-- ClassName needs to satisfy the regex // and can't be a reserved keyword </code></pre> <p>Note that this regex is applied byte-per-byte, without consideration for encoding. That's why it also <a href="https://stackoverflow.com/questions/3417180/exotic-names-for-methods-constants-variables-and-fields-bug-or-feature">allows many weird Unicode names</a>.</p> <p>But the regex restricts <em>only</em> these "direct" uses of names. Through various dynamic features PHP provides it's possible to use virtually arbitrary names.</p> <p>In general you <strong>should make no assumptions</strong> about which characters names in PHP can contain. To the most parts they are just arbitrary strings. Doing things like "validating if something is a valid class name" is just meaningless in PHP.</p> <p>In the following I will provide examples of how you can create weird names for the different categories.</p> <h3>Variables</h3> <p>Variable names can be arbitrary strings:</p> <pre><code>${''} = 'foo'; echo ${''}; // foo ${"\0"} = 'bar'; echo ${"\0"}; // bar </code></pre> <h3>Constants</h3> <p>Global constants can also be arbitrary strings:</p> <pre><code>define('', 'foo'); echo constant(''); // foo define("\0", 'bar'); echo constant("\0"); // bar </code></pre> <p>There is no way to dynamically define class constants that I'm aware of, so those can not be arbitrary. Only way to create weird class constants seems to be via extension code.</p> <h3>Properties</h3> <p>Properties can not be the empty string and can not start with a NUL byte, but apart from this they are arbitrary:</p> <pre><code>$obj = new stdClass; $obj-&gt;{''} = 'foo'; // Fatal error: Cannot access empty property $obj-&gt;{"\0"} = 'foo'; // Fatal error: Cannot access property started with '\0' $obj-&gt;{'*'} = 'foo'; echo $obj-&gt;{'*'}; // foo </code></pre> <h3>Methods</h3> <p>Method names are arbitrary and can be handled by <code>__call</code> magic:</p> <pre><code>class Test { public function __call($method, $args) { echo "Called method \"$method\""; } } $obj = new Test; $obj-&gt;{''}(); // Called method "" $obj-&gt;{"\0"}(); // Called method "\0" </code></pre> <h3>Classes</h3> <p>Arbitrary class names can be created using <code>class_alias</code> with the exception of the empty string:</p> <pre><code>class Test {} class_alias('Test', ''); $className = ''; $obj = new $className; // Fatal error: Class '' not found class_alias('Test', "\0"); $className = "\0"; $obj = new $className; // Works! </code></pre> <h3>Functions</h3> <p>I'm not aware of a way to create arbitrary function names from userland, but there are still some occasions where internal code produces "weird" names:</p> <pre><code>var_dump(create_function('','')); // string(9) "\0lambda_1" </code></pre>
17,804,674
How to check whether a text box is empty or not?
<p>I want to check whether a text box contains a name or not. If not then an alert should be popped up displaying a message after pressing a submit button and the page should not submit the blank value. If it contains value then the value should be submitted.</p> <p>I am using the below code. When I leave the text box empty and click the submit button, it displays the alert as expected, but it also submits the empty value after dismissing the alert.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function check() { if (!frm1.FileName.value) { alert ("Please Enter a File Name"); return (false); } return (true); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form name="frm1" id="frm1" action="/cgi-bin/page.pl" method="POST"&gt; &lt;input type="text" name="FileName" id="FileName"&gt; &lt;input type="submit" value="send" name="btn_move" id="btn_move" onclick="check()"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What is the problem in the code?</p>
17,804,700
3
1
null
2013-07-23 08:06:24.04 UTC
1
2013-07-23 08:30:47.673 UTC
2013-07-23 08:17:25.457 UTC
null
218,196
null
2,122,220
null
1
2
javascript|javascript-events
65,047
<p>You need to do <code>onclick="return check();"</code></p>
46,705,101
mat-form-field must contain a MatFormFieldControl
<p>We are trying to build our own form-field-Components at our Company. We are trying to wrap material design's Components like this:</p> <p>field:</p> <pre class="lang-html prettyprint-override"><code>&lt;mat-form-field&gt; &lt;ng-content&gt;&lt;/ng-content&gt; &lt;mat-hint align="start"&gt;&lt;strong&gt;{{hint}}&lt;/strong&gt; &lt;/mat-hint&gt; &lt;mat-hint align="end"&gt;{{message.value.length}} / 256&lt;/mat-hint&gt; &lt;mat-error&gt;This field is required&lt;/mat-error&gt; &lt;/mat-form-field&gt; </code></pre> <p>textbox:</p> <pre class="lang-html prettyprint-override"><code>&lt;field hint="hint"&gt; &lt;input matInput [placeholder]="placeholder" [value]="value" (change)="onChange($event)" (keydown)="onKeydown($event)" (keyup)="onKeyup($event)" (keypress)="onKeypress($event)"&gt; &lt;/field&gt; </code></pre> <p>Usage:</p> <pre class="lang-html prettyprint-override"><code>&lt;textbox value="test" hint="my hint"&gt;&lt;/textbox&gt; </code></pre> <p>This results in approximately this:</p> <pre class="lang-html prettyprint-override"><code> &lt;textbox placeholder="Personnummer/samordningsnummer" value="" ng-reflect-placeholder="Personnummer/samordningsnummer"&gt; &lt;field&gt; &lt;mat-form-field class="mat-input-container mat-form-field&gt; &lt;div class="mat-input-wrapper mat-form-field-wrapper"&gt; &lt;div class="mat-input-flex mat-form-field-flex"&gt; &lt;div class="mat-input-infix mat-form-field-infix"&gt; &lt;input _ngcontent-c4="" class="mat-input-element mat-form-field-autofill-control" matinput="" ng-reflect-placeholder="Personnummer/samordningsnummer" ng-reflect-value="" id="mat-input-2" placeholder="Personnummer/samordningsnummer" aria-invalid="false"&gt; &lt;span class="mat-input-placeholder-wrapper mat-form-field-placeholder-wrapper"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="mat-input-underline mat-form-field-underline"&gt; &lt;span class="mat-input-ripple mat-form-field-ripple"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div class="mat-input-subscript-wrapper mat-form-field-subscript-wrapper"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/mat-form-field&gt; &lt;/field&gt; &lt;/textbox&gt; </code></pre> <p>But I'm getting <i><b>"mat-form-field must contain a MatFormFieldControl"</b></i> in the console. I guess this has to do with mat-form-field not directly containing a matInput-field. But it is containing it, it's just withing the ng-content projection.</p> <p>Here is a blitz: <a href="https://stackblitz.com/edit/angular-xpvwzf" rel="noreferrer">https://stackblitz.com/edit/angular-xpvwzf</a></p>
49,658,335
41
8
null
2017-10-12 08:42:28.923 UTC
34
2022-08-27 06:54:35.467 UTC
2022-06-02 11:49:33.94 UTC
null
1,791,913
null
479,045
null
1
418
angular|typescript|angular-material
550,408
<p>Import MatInputModule in your module.ts file and it will solve the problem.</p> <pre><code>import { MatInputModule } from '@angular/material/input'; </code></pre> <p>The statement after it is the old answer.</p> <p>Unfortunately content projection into <code>mat-form-field</code> is not supported yet. Please track the following <a href="https://github.com/angular/material2/issues/9411" rel="noreferrer">github issue</a> to get the latest news about it.</p> <p>By now the only solution for you is either place your content directly into <code>mat-form-field</code> component or implement a <code>MatFormFieldControl</code> class thus creating a custom form field component.</p>
1,625,158
iphone SDK detect Wifi and Carrier network
<p>my app accesses the internet and i just want to detect whether there is a connection either via wifi or via carrier data network or not</p> <p>apple has made an example for that "Reachability"</p> <p><a href="https://developer.apple.com/iphone/library/samplecode/Reachability/" rel="nofollow noreferrer">https://developer.apple.com/iphone/library/samplecode/Reachability/</a></p> <p>i think it just detects the wifi and not the carrier network</p> <p>can anyone tell me, whats the best to be done to detect if there's a connection ( any type of connection )</p> <p>Appreciate ur help!</p>
1,625,206
5
1
null
2009-10-26 14:32:12.65 UTC
15
2015-11-20 20:37:50.65 UTC
2015-11-20 20:37:50.65 UTC
null
1,505,120
null
169,656
null
1
11
iphone|networking|wifi|detect
24,198
<p>That sample is exactly what you need.</p> <p>Look at Reachability.m. it'll tell you whether you have any connection, and then tell you what kind of connection you have.</p>
1,526,409
Dynamically create text in dialog box
<p>How can I dynamically set the text of the dialog box that I'm opening? I've tried a few different things but they all respond with an empty dialog box.</p> <p>Here is my current try:</p> <pre> $('#dialog').text('Click on the link to download the file:<br />'.data); $('#dialog').dialog("open"); </pre>
1,526,821
5
1
null
2009-10-06 15:37:48.06 UTC
2
2015-12-02 23:18:28.937 UTC
2015-06-09 12:28:34.397 UTC
null
319,741
null
183,231
null
1
14
jquery|jquery-ui|dialog
58,642
<p>For best practice, try putting a div inside your dialog div and appending text to that instead. </p> <pre><code>&lt;div id="myDialog"&gt;&lt;div id="myDialogText"&gt;&lt;/div&gt;&lt;/div&gt; </code></pre> <p>and then setting the text of the internal Div. This make for better separation, so you have</p> <ul> <li>a div for dialog manipulation</li> <li>and a div for text display</li> </ul> <p>You can then set the text with</p> <pre><code>jQuery("#myDialogText").text("your text here"); </code></pre>