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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,728,640 | What does "throw;" by itself do? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2999298/difference-between-throw-and-throw-new-exception">difference between throw and throw new Exception()</a> </p>
</blockquote>
<p>What would be the point of just having</p>
<pre><code>catch (Exception)
{
throw;
}
</code></pre>
<p>What does this do?</p> | 2,728,661 | 5 | 1 | null | 2010-04-28 10:33:25.587 UTC | 15 | 2017-01-13 21:53:44.117 UTC | 2017-05-23 12:26:19.87 UTC | null | -1 | null | 327,528 | null | 1 | 69 | c#|.net|exception | 21,485 | <p>By itself, the <code>throw</code> keyword simply re-raises the exception caught by the <code>catch</code> statement above. This is handy if you want to do some rudimentary exception handling (perhaps a compensating action like rolling back a transaction) and then rethrow the exception to the calling method.</p>
<p>This method has one significant advantage over catching the exception in a variable and throwing that instance: It preserves the original call stack. If you catch (Exception ex) and then throw ex, your call stack will only start at that throw statement and you lose the method/line of the original error.</p> |
3,180,456 | Java compiler/interpreter | <p>Why we do we say that Java is a compiled and interpreted language?</p>
<p>What is the advantage of this (being compiled and interpreted)?</p> | 3,180,565 | 6 | 0 | null | 2010-07-05 14:56:19.26 UTC | 21 | 2018-03-15 16:12:13.623 UTC | 2018-01-24 13:29:16.317 UTC | null | 775,954 | null | 297,115 | null | 1 | 21 | java|compiler-construction|terminology | 40,314 | <p>Java is compiled to an intermediate "byte code" at compilation time. This is in contrast to a language like C that is compiled to machine language at compilation time. The Java byte code cannot be directly executed on hardware the way that compiled C code can. Instead the byte code must be interpreted by the JVM (Java Virtual Machine) at runtime in order to be executed. The primary drawback of a language like C is that when it is compiled, that binary file will only work on one particular architecture (e.g. x86). </p>
<p>Interpreted languages like PHP are effectively system independent and rely on a system and architecture specific interpreter. This leads to much greater portability (the same PHP scripts work on Windows machines and Linux machines, etc.). However, this interpretation leads to a significant performance decrease. High-level languages like PHP require more time to interpret than machine-specific instructions that can be executed by the hardware. </p>
<p>Java seeks to find a compromise between a purely compiled language (with no portability) and a purely interpreted language (that is significantly slower). It accomplishes this by compiling the code into a form that is closer to machine language (actually, Java byte code is a machine language, simply for the Java Virtual Machine), but can still be easily transported between architectures. Because Java still requires a software layer for execution (the JVM) it is an interpreted language. However, the interpreter (the JVM) operates on an intermediate form known as byte code rather than on the raw source files. This byte code is generated at compile time by the Java compiler. Therefore, Java is also a compiled language. By operating this way, Java gets some of the benefits of compiled languages, while also getting some of the benefits of interpreted languages. However, it also inherits some limitations from both of these languages. </p>
<p>As Bozho points out, there are some strategies for increasing the performance of Java code (and other byte code languages like .Net) through the use of Just in Time (JIT) compilation. The actual process varies from implementation to implementation based on the requirements, but the end-result is that the original code is compiled into byte code at compile time, but then it is run through a compiler at runtime before it is executed. By doing this, the code can be executed at near-native speeds. Some platforms (I believe .Net does this) save the result of the JIT compilation, replacing the byte code. By doing this, all future executions of the program will execute as though the program was natively compiled from the beginning. </p> |
2,525,247 | How to extend a jquery ui widget ? (1.7) | <p>I would like to create a custom version of the sortable widget. I have been searching for documentation, but could not find something really accurate. The best information I found was : <a href="http://jqueryui.pbworks.com/Widget-factory" rel="noreferrer">http://jqueryui.pbworks.com/Widget-factory</a>.</p>
<p>I tried :</p>
<pre><code>$.widget("ui.customsortable", $.extend($.ui.sortable, {
_init: function() {
$.widget.prototype._init.apply(this, arguments);
}
}));
</code></pre>
<p>But $.widget.prototype._init is not the function I want to call I guess since it is the $.widget prototype.</p>
<p>Then, I tried something I read here and there :</p>
<pre><code>var _init = $.ui.sortable.prototype._init;
$.widget("ui.customsortable", $.extend($.ui.sortable, {
_init: function() {
_init.apply(this, arguments);
},
}));
</code></pre>
<p>But :</p>
<ul>
<li>I can't believe I have to store all methods I want to override like this, it is so ugly.</li>
<li>It throws an error ("this.refresh is not a function"), which means the refresh method does not exist. Does that mean I would have to recreate all methods I want to override ? What's the point of extending in that case ?</li>
</ul>
<p>Am I missing something here ?</p>
<p>Thanks for your help !</p> | 2,813,259 | 6 | 1 | null | 2010-03-26 17:18:04.313 UTC | 13 | 2012-10-26 17:25:04.477 UTC | null | null | null | null | 302,731 | null | 1 | 30 | javascript|jquery|jquery-ui | 17,564 | <p>After several tries, I finally found out how to do this easily :</p>
<pre><code>$.widget("ui.customsortable", $.extend({}, $.ui.sortable.prototype, {
_init: function(){
this.element.data('sortable', this.element.data('customsortable'));
return $.ui.sortable.prototype._init.apply(this, arguments);
}
// Override other methods here.
}));
$.ui.customsortable.defaults = $.extend({}, $.ui.sortable.defaults);
</code></pre>
<p>The key is to copy data from your custom widget to the original one.
Don't forget to use $.ui.sortable.prototype.[overriden method].apply(this, arguments); in each overriden method.</p>
<p>Holly crap !</p> |
2,484,079 | How can I avoid garbage collection delays in Java games? (Best Practices) | <p>I'm performance tuning interactive games in Java for the Android platform. Once in a while there is a hiccup in drawing and interaction for garbage collection. Usually it's less than one tenth of a second, but sometimes it can be as large as 200ms on very slow devices.</p>
<p>I am using the ddms profiler (part of the Android SDK) to search out where my memory allocations come from and excise them from my inner drawing and logic loops. </p>
<p>The worst offender had been short loops done like,</p>
<pre><code>for(GameObject gob : interactiveObjects)
gob.onDraw(canvas);
</code></pre>
<p>where every single time the loop was executed there was an <code>iterator</code> allocated. I'm using arrays (<code>ArrayList</code>) for my objects now. If I ever want trees or hashes in an inner loop I know that I need to be careful or even reimplement them instead of using the Java Collections framework since I can't afford the extra garbage collection. That may come up when I'm looking at priority queues.</p>
<p>I also have trouble where I want to display scores and progress using <code>Canvas.drawText</code>. This is bad,</p>
<pre><code>canvas.drawText("Your score is: " + Score.points, x, y, paint);
</code></pre>
<p>because <code>Strings</code>, <code>char</code> arrays and <code>StringBuffers</code> will be allocated all over to make it work. If you have a few text display items and run the frame 60 times a second that begins to add up and will increase your garbage collection hiccups. I think the best choice here is to keep <code>char[]</code> arrays and decode your <code>int</code> or <code>double</code> manually into it and concatenate strings onto the beginning and end. I'd like to hear if there's something cleaner.</p>
<p>I know there must be others out there dealing with this. How do you handle it and what are the pitfalls and best practices you've discovered to run interactively on Java or Android? These gc issues are enough to make me miss manual memory management, but not very much.</p> | 2,484,301 | 6 | 3 | null | 2010-03-20 17:51:40.113 UTC | 38 | 2014-06-26 07:27:34.78 UTC | 2010-03-20 18:08:23.243 UTC | null | 310,574 | null | 8,959 | null | 1 | 66 | java|android|garbage-collection|performance | 27,578 | <p>I've worked on Java mobile games... The best way to avoid GC'ing objects (which in turn <em>shall</em> trigger the GC at one point or another and <em>shall</em> kill your game's perfs) is simply to avoid creating them in your main game loop in the first place.</p>
<p>There's no "clean" way to deal with this and I'll first give an example...</p>
<p>Typically you have, say, 4 balls on screen at (50,25), (70,32), (16,18), (98,73). Well, here's your abstraction (simplified for the sake of this example):</p>
<pre><code>n = 4;
int[] { 50, 25, 70, 32, 16, 18, 98, 73 }
</code></pre>
<p>You "pop" the 2nd ball which disappears, your int[] becomes:</p>
<pre><code>n = 3
int[] { 50, 25, 98, 73, 16, 18, 98, 73 }
</code></pre>
<p>(notice how we don't even care about "cleaning" the 4th ball (98,73), we simply keep track of the number of balls we have left).</p>
<p>Manual tracking of objects, sadly. This how it's done on most current well-performing Java games that are out on mobile devices.</p>
<p>Now for strings, here's what I'd do:</p>
<ul>
<li>at game initialization, predraw using <em>drawText(...)</em> <em>only once</em> the numbers 0 to 9 that you save in a <code>BufferedImage[10]</code> array.</li>
<li>at game initialization, predraw once <em>"Your score is: "</em></li>
<li>if the <em>"Your score is: "</em> really needs to be redrawn (because, say, it's transparent), then redraw it from your pre-stored <code>BufferedImage</code></li>
<li>loop to compute the digits of the score and add, after the <em>"Your score is: "</em>, every digit manually one by one (by copying each the time the corresponding digit (0 to 9) from your <code>BufferedImage[10]</code> where you pre-stored them.</li>
</ul>
<p>This gives you best of both world: you get the reuse the <em>drawtext(...)</em> font and you created exactly zero objects during your main loop (because you <em>also</em> dodged the call to <em>drawtext(...)</em> which itself <em>may</em> very well be crappily generating, well, needless crap).</p>
<p>Another "benefit" of this <em>"zero object creation draw score"</em> is that careful image caching and reuse for the fonts is not really <em>"manual object allocation/deallocation"</em>, it's really just careful caching.</p>
<p>It's not "clean", it's not "good practice" but that's how it's done in top-notch mobile games (like, say, Uniwar).</p>
<p>And it's fast. Darn fast. Faster than <em>anything</em> involving the creation of object.</p>
<p><em>P.S: Actually if you carefully look at a few mobile games, you'll notice that often fonts are actually not system/Java fonts but pixel-perfect fonts made specifically for each game (here I just gave you an example of how to cache system/Java font but obviously you could also cache/reuse a pixel-perfect/bitmapped font).</em></p> |
2,493,404 | complex if statement in python | <p>I need to realize a <em>complex</em> if-elif-else statement in Python but I don't get it working.</p>
<p>The elif line I need has to check a variable for this conditions:</p>
<p><strong>80, 443 or 1024-65535 inclusive</strong></p>
<p>I tried </p>
<pre><code>if
...
# several checks
...
elif (var1 > 65535) or ((var1 < 1024) and (var1 != 80) and (var1 != 443)):
# fail
else
...
</code></pre> | 2,493,434 | 7 | 1 | null | 2010-03-22 15:21:27.603 UTC | 3 | 2017-05-30 07:23:22.587 UTC | 2010-03-22 15:56:02.497 UTC | null | 12,855 | null | 234,482 | null | 1 | 30 | python | 155,545 | <p>This should do it:</p>
<pre><code>elif var == 80 or var == 443 or 1024 <= var <= 65535:
</code></pre> |
2,883,887 | In JPA 2, using a CriteriaQuery, how to count results | <p>I am rather new to JPA 2 and it's CriteriaBuilder / CriteriaQuery API:</p>
<p><a href="http://java.sun.com/javaee/6/docs/api/javax/persistence/criteria/CriteriaQuery.html" rel="noreferrer"><code>CriteriaQuery</code> javadoc</a></p>
<p><a href="http://java.sun.com/javaee/6/docs/tutorial/doc/gjivm.html" rel="noreferrer"><code>CriteriaQuery</code> in the Java EE 6 tutorial</a></p>
<p>I would like to count the results of a CriteriaQuery without actually retrieving them. Is that possible, I did not find any such method, the only way would be to do this:</p>
<pre><code>CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<MyEntity> cq = cb
.createQuery(MyEntityclass);
// initialize predicates here
return entityManager.createQuery(cq).getResultList().size();
</code></pre>
<p>And that can't be the proper way to do it...</p>
<p>Is there a solution?</p> | 2,884,378 | 7 | 2 | null | 2010-05-21 16:40:58.98 UTC | 37 | 2019-10-26 10:42:39.923 UTC | 2011-05-04 14:30:46.427 UTC | null | 342,852 | null | 342,852 | null | 1 | 135 | java|jpa-2.0|criteriaquery | 177,814 | <p>A query of type <code>MyEntity</code> is going to return <code>MyEntity</code>. You want a query for a <code>Long</code>.</p>
<pre><code>CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
</code></pre>
<p>Obviously you will want to build up your expression with whatever restrictions and groupings etc you skipped in the example.</p> |
2,551,067 | Can we insert javascript into any webpage loaded in the browser | <p>I am looking into methods to inject javascript into any webpage loaded in the browser, so that I can traverse through the page's DOM. I use JQUERY for my scripting needs.
Method should work in all browsers.</p>
<p>I tried using <strong>IFRAME</strong> and adding some html into it, but I cant. Please suggest some ways.</p> | 2,551,127 | 8 | 2 | null | 2010-03-31 07:15:38.383 UTC | 8 | 2020-05-20 14:05:22.853 UTC | null | null | null | null | 140,939 | null | 1 | 20 | javascript | 81,837 | <p>Try using Greasemonkey: <a href="http://www.greasespot.net/" rel="noreferrer">http://www.greasespot.net/</a>. You can use it to execute custom scripts on page load for any website you want. You can find some basic tutorials here: <a href="http://wiki.greasespot.net/Tutorials" rel="noreferrer">http://wiki.greasespot.net/Tutorials</a>.</p> |
2,933,126 | What are good CLI tools for JSON? | <h2>General Problem</h2>
<p>Though I may be diagnosing the root cause of an event, determining how many users it affected, or distilling timing logs in order to assess the performance and throughput impact of a recent code change, my tools stay the same: <code>grep</code>, <code>awk</code>, <code>sed</code>, <code>tr</code>, <code>uniq</code>, <code>sort</code>, <code>zcat</code>, <code>tail</code>, <code>head</code>, <code>join</code>, and <code>split</code>. To glue them all together, Unix gives us pipes, and for fancier filtering we have <code>xargs</code>. If these fail me, there's always <code>perl -e</code>.</p>
<p>These tools are perfect for processing CSV files, tab-delimited files, log files with a predictable line format, or files with comma-separated key-value pairs. In other words, files where each line has next to no context.</p>
<h2>XML Analogues</h2>
<p>I recently needed to trawl through Gigabytes of XML to build a histogram of usage by user. This was easy enough with the tools I had, but for more complicated queries the normal approaches break down. Say I have files with items like this:</p>
<pre><code><foo user="me">
<baz key="zoidberg" value="squid" />
<baz key="leela" value="cyclops" />
<baz key="fry" value="rube" />
</foo>
</code></pre>
<p>And let's say I want to produce a mapping from user to average number of <code><baz></code>s per <code><foo></code>. Processing line-by-line is no longer an option: I need to know which user's <code><foo></code> I'm currently inspecting so I know whose average to update. Any sort of Unix one liner that accomplishes this task is likely to be inscrutable.</p>
<p>Fortunately in XML-land, we have wonderful technologies like XPath, XQuery, and XSLT to help us.</p>
<p>Previously, I had gotten accustomed to using the wonderful <code>XML::XPath</code> Perl module to accomplish queries like the one above, but after finding a <a href="http://ditchnet.org/xmlmate/" rel="noreferrer">TextMate Plugin that could run an XPath expression against my current window</a>, I stopped writing one-off Perl scripts to query XML. And I just found out about <a href="http://xmlstar.sourceforge.net/" rel="noreferrer">XMLStarlet</a> which is installing as I type this and which I look forward to using in the future.</p>
<h2>JSON Solutions?</h2>
<p>So this leads me to my question: are there any tools like this for JSON? It's only a matter of time before some investigation task requires me to do similar queries on JSON files, and without tools like XPath and XSLT, such a task will be a lot harder. If I had a bunch of JSON that looked like this:</p>
<pre><code>{
"firstName": "Bender",
"lastName": "Robot",
"age": 200,
"address": {
"streetAddress": "123",
"city": "New York",
"state": "NY",
"postalCode": "1729"
},
"phoneNumber": [
{ "type": "home", "number": "666 555-1234" },
{ "type": "fax", "number": "666 555-4567" }
]
}
</code></pre>
<p>And wanted to find the average number of phone numbers each person had, I could do something like this with XPath:</p>
<pre><code>fn:avg(/fn:count(phoneNumber))
</code></pre>
<h2>Questions</h2>
<ol>
<li>Are there any command-line tools
that can "query" JSON files in this
way?</li>
<li>If you have to process a bunch of
JSON files on a Unix command line,
what tools do you use?</li>
<li>Heck, is there even work being done
to make a query language like this
for JSON?</li>
<li>If you do use tools like this in
your day-to-day work, what do you
like/dislike about them? Are there
any gotchas?</li>
</ol>
<p>I'm noticing more and more data serialization is being done using JSON, so processing tools like this will be crucial when analyzing large data dumps in the future. Language libraries for JSON are very strong and it's easy enough to write scripts to do this sort of processing, but to really let people play around with the data shell tools are needed.</p>
<h3>Related Questions</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/91791/grep-and-sed-equivalent-for-xml-command-line-processing">Grep and Sed Equivalent for XML Command Line Processing</a></li>
<li><a href="https://stackoverflow.com/questions/777455/is-there-a-query-language-for-json">Is there a query language for JSON?</a></li>
<li><a href="https://stackoverflow.com/questions/859033/jsonpath-or-other-xpath-like-utility-for-json-javascript-or-jquery-json">JSONPath or other XPath like utility for JSON/Javascript; or Jquery JSON</a></li>
</ul> | 14,132,863 | 8 | 4 | null | 2010-05-28 23:34:44.037 UTC | 25 | 2022-09-08 13:01:39.277 UTC | 2017-05-23 11:47:24.983 UTC | null | -1 | null | 179,878 | null | 1 | 70 | json|xslt|command-line|xpath | 24,202 | <p>I just found this:</p>
<p><a href="http://stedolan.github.io/jq/" rel="nofollow noreferrer">http://stedolan.github.io/jq/</a></p>
<p>"jq is a lightweight and flexible command-line JSON processor."</p>
<p>2014 update:</p>
<p>@user456584 mentioned:</p>
<blockquote>
<p>There's also the 'json' command (e.g. 'jsontool'). I tend to prefer it over jq. Very UNIX-y. Here's a link to the project: github.com/trentm/json –</p>
</blockquote>
<p>in the <strong><code>json</code></strong> README at <a href="http://github.com/trentm/json" rel="nofollow noreferrer">http://github.com/trentm/json</a> there is a long list of similar things</p>
<blockquote>
<ul>
<li><strong>jq</strong>: <a href="http://stedolan.github.io/jq/" rel="nofollow noreferrer">http://stedolan.github.io/jq/</a></li>
<li><strong>json:select</strong>: <a href="http://jsonselect.org/" rel="nofollow noreferrer">http://jsonselect.org/</a></li>
<li><strong>jsonpipe</strong>: <a href="https://github.com/dvxhouse/jsonpipe" rel="nofollow noreferrer">https://github.com/dvxhouse/jsonpipe</a></li>
<li><strong>json-command</strong>: <a href="https://github.com/zpoley/json-command" rel="nofollow noreferrer">https://github.com/zpoley/json-command</a></li>
<li><strong>JSONPath</strong>: <a href="http://goessner.net/articles/JsonPath/" rel="nofollow noreferrer">http://goessner.net/articles/JsonPath/</a>, <a href="http://code.google.com/p/jsonpath/wiki/Javascript" rel="nofollow noreferrer">http://code.google.com/p/jsonpath/wiki/Javascript</a></li>
<li><strong>jsawk</strong>: <a href="https://github.com/micha/jsawk" rel="nofollow noreferrer">https://github.com/micha/jsawk</a></li>
<li><strong>jshon</strong>: <a href="http://kmkeen.com/jshon/" rel="nofollow noreferrer">http://kmkeen.com/jshon/</a></li>
<li><strong>json2</strong>: <a href="https://github.com/vi/json2" rel="nofollow noreferrer">https://github.com/vi/json2</a></li>
<li><strong>fx</strong>: <a href="https://github.com/antonmedv/fx" rel="nofollow noreferrer">https://github.com/antonmedv/fx</a></li>
</ul>
</blockquote> |
40,592,298 | Why would the character 'A' be compared with 0x41? | <p>I was looking at some C++ code and found the following construct:</p>
<pre><code>if('A' == 0x41) {
// ...
} else if('A' == 0xc1) {
// ...
} else {
// ...
}
</code></pre>
<p>I get a <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio">Visual Studio</a> warning saying:</p>
<blockquote>
<p>Warning C4127 conditional expression is constant.</p>
</blockquote>
<p>Visual Studio is clearly right - surely 'A' is defined to be 0x41. Why is the author writing this code, given that two out of the three branches are dead code?</p> | 40,592,371 | 2 | 17 | null | 2016-11-14 15:29:56.53 UTC | 13 | 2016-12-10 14:31:30.367 UTC | 2016-11-18 15:15:46.07 UTC | null | 2,474,248 | null | 1,020,773 | null | 1 | 90 | c++|string | 8,292 | <p><code>0xc1</code> is the <code>EBCDIC</code> character set code for <code>A</code>. The author is testing for such a machine.</p>
<p><a href="http://www.ibm.com/support/knowledgecenter/en/SSGH4D_15.1.3/com.ibm.xlf1513.aix.doc/language_ref/asciit.html" rel="noreferrer">http://www.ibm.com/support/knowledgecenter/en/SSGH4D_15.1.3/com.ibm.xlf1513.aix.doc/language_ref/asciit.html</a></p> |
39,954,668 | How to convert column with list of values into rows in Pandas DataFrame | <p>Hi I have a dataframe like this:</p>
<pre><code> A B
0: some value [[L1, L2]]
</code></pre>
<p>I want to change it into:</p>
<pre><code> A B
0: some value L1
1: some value L2
</code></pre>
<p>How can I do that?</p> | 39,955,283 | 6 | 0 | null | 2016-10-10 08:58:21.887 UTC | 22 | 2020-06-29 18:46:30.987 UTC | 2016-10-10 10:44:25.32 UTC | null | 3,986,879 | null | 5,893,958 | null | 1 | 54 | python|pandas|dataframe | 58,079 | <p>you can do it this way:</p>
<pre><code>In [84]: df
Out[84]:
A B
0 some value [[L1, L2]]
1 another value [[L3, L4, L5]]
In [85]: (df['B'].apply(lambda x: pd.Series(x[0]))
....: .stack()
....: .reset_index(level=1, drop=True)
....: .to_frame('B')
....: .join(df[['A']], how='left')
....: )
Out[85]:
B A
0 L1 some value
0 L2 some value
1 L3 another value
1 L4 another value
1 L5 another value
</code></pre>
<p><strong>UPDATE:</strong> <a href="https://stackoverflow.com/questions/12680754/split-explode-pandas-dataframe-string-entry-to-separate-rows/40449726#40449726">a more generic solution</a></p> |
40,248,908 | context or workdir for docker-compose | <p>I'm learning docker</p>
<p>I need to specify the working directory for a docker image, I think that'll be something like this:</p>
<pre><code>version: '2'
services:
test:
build:
context: ./dir
</code></pre>
<p>Now I want to make the image <code>python:onbuild</code> to run on the <code>./dir</code>, but I dont want to create any <code>Dockerfile</code> inside the <code>./dir</code>.</p>
<p>The <code>docker-compose</code> manual says nothing about that.</p>
<p>Is it possible? How to do that?</p> | 43,290,357 | 4 | 0 | null | 2016-10-25 20:12:57.903 UTC | 11 | 2022-09-12 07:38:30.397 UTC | null | null | null | null | 1,732,775 | null | 1 | 106 | docker|docker-compose | 146,936 | <p>I think you're looking for <code>working_dir</code>. Search for "working_dir" in the <a href="https://docs.docker.com/compose/compose-file/#domainname-hostname-ipc-mac_address-privileged-read_only-shm_size-stdin_open-tty-user-working_dir" rel="noreferrer">docker-compose reference</a>.</p> |
10,632,975 | Static class/method/property in unit test, stop it or not | <p>Should a static class/method/property be used in a unit test development environment, given that there is no way to test it without introducing a wrapper that is again not testable?</p>
<p>Another scenario is that when the static members are used within the unit tested target, the static member cannot be mocked. Thus, you have to test the static members when the unit tested target is tested. You want to isolate it when the static member performs calculation.</p> | 10,633,109 | 5 | 0 | null | 2012-05-17 09:25:53.94 UTC | 5 | 2020-07-03 01:17:08.613 UTC | 2020-07-03 01:17:08.613 UTC | null | 1,402,846 | null | 665,335 | null | 1 | 22 | c#|java|unit-testing|tdd | 43,971 | <p>Testing static method is no different than testing any other method. Having static method as a <em>dependency</em> inside another tested module raises problems (as it's been mentioned - you can't mock/stub it with free tools). But if the static method itself is unit tested you can simply <a href="https://stackoverflow.com/a/9018501/343266">treat it as working, reliable component</a>. </p>
<p>Overall, there's nothing wrong (as in, it doesn't disrupt unit testing/TDD) with static methods when:</p>
<ul>
<li>it is simple, input-output method (all kinds of <em>"calculate this given that"</em>)</li>
<li>it is <em>reliable</em>, by what we mean it's either unit tested by you or comes from 3rd party source you consider reliable (eg. <code>Math.Floor</code> might be considered reliable - using it shouldn't raise <em>"Look out, it's static!"</em> warning; one might assume Microsoft does its job)</li>
</ul>
<p>When static methods will cause problems and should be avoided? Basically only when they interact with/<strong>do something you cannot control</strong> (or mock):</p>
<ul>
<li>all kind of file system, database, network dependencies</li>
<li>other (possibly more complex) static methods called from inside</li>
<li>pretty much anything your mocking framework can't deal with on regular terms</li>
</ul>
<p><strong>Edit:</strong> <em>two examples on when static method <strong>will</strong> make unit testing hard</em></p>
<p><strong>1</strong></p>
<pre><code>public int ExtractSumFromReport(string reportPath)
{
var reportFile = File.ReadAllText(reportPath);
// ...
}
</code></pre>
<p>How do you deal with <code>File.ReadAllText</code>? This will obviously go to file system to retrieve file content, which is major no-no when unit testing. This is example of static method with external dependency. To avoid that, you usually create wrapper around file system api or simply inject it as dependency/delegate. </p>
<p><strong>2</strong></p>
<pre><code>public void SaveUser(User user)
{
var session = SessionFactory.CreateSession();
// ...
}
</code></pre>
<p>What about this? Session is <em>non-trivial</em> dependency. Sure, it might come as <code>ISession</code>, but how do force <code>SessionFactory</code> to return mock? We can't. And we can't create <em>easy to detemine</em> session object either. </p>
<p>In cases like above, it's best to avoid static methods altogether.</p> |
10,666,174 | Implement onClick only for a TextView compound drawable | <p>I need to have some text with a drawable on the left and I want to execute some code when the user clicks/touches the image (only the image, not the text), so I used a <em>LinearLayout</em> with a <em>TextView</em> and an <em>ImageView</em> which is clickable and launches an onClick event. The XML parser suggests me to replace this with a <em>TextView</em> with a <em>compound drawable</em>, which would draw the same thing with far less lines of <em>XML</em>.. My question is "can I specify I want to handle an onClick event only on the drawable of the <em>TextView</em> and not on the <em>TextView</em> itself? I've seen some solutions which involves writing your own extension of <em>TextView</em>, but I'm only interested in being able to do it within the layout resource, if possible, otherwise I'll keep the following <em>XML</em> code:</p>
<pre><code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="bottom"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="@string/home_feedback_title"
android:textColor="@android:color/primary_text_dark"
android:textStyle="bold"
android:paddingBottom="4dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/action_feedback"
android:clickable="true"
android:onClick="onClickFeedback"
android:contentDescription="@string/action_feedback_description"/>
</LinearLayout>
</code></pre> | 10,667,374 | 5 | 0 | null | 2012-05-19 14:47:20.603 UTC | 4 | 2021-12-16 19:32:34.09 UTC | null | null | null | null | 925,001 | null | 1 | 30 | android|android-layout|onclick|textview | 17,295 | <p>You can go either way. Using the compound drawable is faster though because it was intended to be an optimization. It uses less ram because you reduce 3 views into 1 and it's faster layout because you lose 1 depth.</p>
<p>If I were you I'd consider stepping back to see if both the text and the image intercepting the touch to do whatever action is possibly a good thing. In general having a larger touch region makes it easier to press. Some users may actually be inclined to touch the text instead of the image.</p>
<p>Lastly if you go that route of merging the 2 you might want to consider using a <code>Button</code> instead of a <code>TextView</code>. You can style the button to not have the rectangle around it. They call it a borderless button. It's nice because you get visual feedback that you clicked on a actionable item where as an <code>ImageView</code> or <code>TextView</code> normally aren't actionable.</p>
<p><a href="https://stackoverflow.com/questions/9167900/how-to-create-borderless-buttons-in-android">How to Create Borderless Buttons in Android</a></p> |
10,516,233 | Add a whitespace at the end of the line in Jade | <p>I have this <a href="https://github.com/visionmedia/jade" rel="noreferrer">jade</a> code:</p>
<pre><code>p
| Avatar hosted by
a(href='http://www.gravatar.com/', target='_blank') Gravatar
</code></pre>
<p>The problem is, it's rendered to</p>
<pre><code><p>Avatar hosted by<a href="http://www.gravatar.com/" target="_blank">Gravatar</a></p>
</code></pre>
<p>Which looks like: "Avatar hosted by<a href="http://www.gravatar.com/" rel="noreferrer">Gravatar</a>".</p>
<p>No matter how many spaces I added at the end of the text line, it still looks like this. The Docs couldn't help me, and I can't imagine this to be such an uncommon problem.</p> | 19,276,263 | 8 | 0 | null | 2012-05-09 12:35:53.703 UTC | 7 | 2017-04-24 20:24:38.403 UTC | 2014-02-03 22:23:37.853 UTC | null | 1,624,862 | null | 471,436 | null | 1 | 40 | node.js|express|pug | 19,757 | <p>If you don't want inline HTML or HTML entities in your code this is what you can do:</p>
<pre><code>p
| Avatar hosted by
= ' '
a(href='http://www.gravatar.com/', target='_blank') Gravatar
</code></pre>
<p>or this is is shorter</p>
<pre><code>p= 'Avatar hosted by '
a(href='http://www.gravatar.com/', target='_blank') Gravatar
</code></pre>
<p>The cleanest is probably this</p>
<pre><code>p Avatar hosted by #{''}
a(href='http://www.gravatar.com/', target='_blank') Gravatar
</code></pre> |
18,429,625 | Missing Javascript ".map" file for Underscore.js when loading ASP.NET web page | <p>I have a web page that is part of a ASP.NET web site running on Azure. It's run fine for quite a while now. Out of the blue, I am suddenly having a problem with the browser trying to download a ".map" for Underscore.js. I did some reading and apparently JQuery creates ".map" files as debugging aids for Javascript source files (".js"). However, if I look at the Scripts directory for my web site I see that this only happens for some JQuery source files and not all and I am not sure what the pattern is.</p>
<p>However, why would the browser be trying to load a "map" file for Underscore.js which is not part of JQuery? Also, why would this suddenly start happening? I added Underscore.js to the web page quite some time ago and never had this problem before. </p>
<p>The exact error I get when I look in the Chrome Debugger Console tab is:</p>
<p>GET <a href="http://myazureapp.cloudapp.net/Scripts/underscore-min.map" rel="noreferrer">http://myazureapp.cloudapp.net/Scripts/underscore-min.map</a> 404 (Not Found) Scripts/underscore-min.map:1</p> | 18,429,840 | 1 | 0 | null | 2013-08-25 13:45:58.177 UTC | 21 | 2015-07-02 17:14:29.34 UTC | 2015-07-02 17:14:29.34 UTC | null | 310,446 | null | 2,561,452 | null | 1 | 96 | javascript|asp.net|underscore.js | 50,571 | <p>What you're experiencing is <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/" rel="noreferrer">source mapping</a>. This allows you to debug with readable code in your browser's developer tools when working with minified JS files.</p>
<p>The minified version of Underscore has this line at the end of the file:</p>
<pre><code>//# sourceMappingURL=underscore-min.map
</code></pre>
<p>Your browser's developers tools will try to download <code>underscore-min.map</code> when encountering this line.</p>
<p>If you want to get rid of the error, either:</p>
<ol>
<li>Remove that line from <code>underscore-min.js</code></li>
<li>Add <a href="https://github.com/jashkenas/underscore/blob/master/underscore-min.map" rel="noreferrer">underscore-min.map</a> and <a href="https://github.com/jashkenas/underscore/blob/master/underscore.js" rel="noreferrer">underscore.js</a> to your project.</li>
</ol> |
33,387,263 | Invoke function whose name is stored in a variable in bash | <p>Let's say I have:</p>
<pre><code>function x {
echo "x"
}
call_func="x"
</code></pre>
<p>Now, I can simply use <code>eval</code> as follows:</p>
<pre><code>eval $call_func
</code></pre>
<p>but I was wondering if there was some other way of invoking the function (if it exists) whose name is stored in the variable: <code>call_func</code>.</p> | 33,387,393 | 3 | 0 | null | 2015-10-28 09:26:38.37 UTC | 5 | 2022-09-15 13:51:58.737 UTC | null | null | null | null | 1,190,388 | null | 1 | 43 | bash|shell|scripting | 27,297 | <p>You should be able to just call the function directly using</p>
<pre><code>$call_func
</code></pre>
<p>For everything else check out that answer: <a href="https://stackoverflow.com/a/17529221/3236102">https://stackoverflow.com/a/17529221/3236102</a>
It's not directly what you need, but it shows a lot of different ways of how to call commands / functions.</p>
<p>Letting the user execute any arbitrary code is bad practice though, since it can be quite dangerous. What would be better is to do it like this:</p>
<pre><code>if [ $userinput == "some_command" ];then
some_command
fi
</code></pre>
<p>This way, the user can only execute the commands that you want them to and can even output an error message if the input was incorrect.</p> |
33,303,786 | Where does Elasticsearch store its data? | <p>So I have this Elasticsearch installation, in insert data with logstash, visualize them with kibana.</p>
<p>Everything in the conf file is commented, so it's using the default folders which are relative to the elastic search folder.</p>
<pre><code>1/ I store data with logstash
2/ I look at them with kibana
3/ I close the instance of elastic seach, kibana and logstash
4/ I DELETE their folders
5/ I re-extract everything and reconfigure them
6/ I go into kibana and the data are still there
</code></pre>
<p>How is this possible?</p>
<p>This command will however delete the data : <code>curl -XDELETE 'http://127.0.0.1:9200/_all'</code></p>
<p>Thanks.</p>
<p>ps : forgot to say that I'm on windows</p> | 33,303,945 | 7 | 1 | null | 2015-10-23 13:39:27.873 UTC | 7 | 2020-07-21 04:07:22.35 UTC | 2020-07-21 04:07:22.35 UTC | null | 704,803 | null | 2,105,339 | null | 1 | 41 | elasticsearch|kibana|kibana-4 | 73,766 | <p>If you've installed ES on Linux, the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-dir-layout.html#default-paths" rel="noreferrer">default data folder</a> is in <code>/var/lib/elasticsearch</code> (CentOS) or <code>/var/lib/elasticsearch/data</code> (Ubuntu)</p>
<p>If you're on Windows or if you've simply extracted ES from the ZIP/TGZ file, then you should have a <code>data</code> sub-folder in the extraction folder.</p> |
19,737,594 | AngularJS - How to generate random value for each ng-repeat iteration | <p>I am trying to create random span sized divs(.childBox) of twitter bootstrap using AngularJS.</p>
<pre><code> <div ng-controller="HomeCtrl">
<div class="motherBox" ng-repeat="n in news">
<div class="childBox" class="col-md-{{boxSpan}} box">
<a href="#" class="thumbnail">
<img src="{{holderLink}}" height="200px" alt="100x100">
<p class="tBlock"> {{n.title}} </p>
</a>
</div>
</div>
</div>
controller('HomeCtrl', ['$scope', '$http', function($scope,$http) {
$http.get('news/abc.json').success(function(data) {
$scope.news = data;
});
$scope.holderSize = 150;
$scope.holderLink = 'http://placehold.it/'+$scope.holderSize+'x'+$scope.holderSize;
$scope.boxSpan = getRandomSpan();
function getRandomSpan(){
return Math.floor((Math.random()*6)+1);
};
}])
</code></pre>
<p>I want to create different integer value for boxSpan for each .childBox div but all .childBox have same boxSpan value. Although everytime i refresh page boxSpan creates random value.</p>
<p>How can i generate different/random value for each ng-repeat iteration?</p> | 19,737,712 | 3 | 0 | null | 2013-11-02 00:29:44.28 UTC | 3 | 2015-09-15 11:56:03.957 UTC | null | null | null | null | 1,843,210 | null | 1 | 11 | angularjs|random | 80,581 | <p>Just call add <code>getRandomSpan()</code> function to your scope and call it in your template:</p>
<pre><code>$scope.getRandomSpan = function(){
return Math.floor((Math.random()*6)+1);
}
<div ng-controller="HomeCtrl">
<div class="motherBox" ng-repeat="n in news">
<div class="childBox" class="col-md-{{getRandomSpan()}} box">
<a href="#" class="thumbnail">
<img src="{{holderLink}}" height="200px" alt="100x100">
<p class="tBlock"> {{n.title}} </p>
</a>
</div>
</div>
</div>
</code></pre> |
58,568,425 | How to fix "A JNI error has occurred, please check your installation." | <p>I have written a Java program on Eclipse and I'm able to run the program. But when I transfer it to Notepad++ and run it via command prompt. It gave me an ERROR message. Any idea on how to solve it?</p>
<p>I have attach an image of the error.</p>
<p><a href="https://i.stack.imgur.com/ehR3Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ehR3Y.png" alt=""Error Message"" /></a></p>
<pre><code>Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: Assignment_2 has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown
at java.security.SecureClassLoader.defineClass(Unknown
at java.net.URLClassLoader.defineClass(Unknown
at java.net.URLClassLoader.access$100(Unknown
at java.net.URLClassLoader$1.run(Unknown
at java.net.URLClassLoader$1.run(Unknown
at java.security.AccessController.doPrivileged(Native
at java.net.URLClassLoader.findClass(Unknown
at java.lang.ClassLoader.loadClass(Unknown
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown
at java.lang.ClassLoader.loadClass(Unknown
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
</code></pre> | 58,568,515 | 4 | 1 | null | 2019-10-26 05:54:07.697 UTC | null | 2021-09-09 03:24:34.77 UTC | 2020-10-01 07:58:38.193 UTC | null | 4,607,733 | null | 12,276,507 | null | 1 | 0 | java|command | 40,450 | <p>The error message tells you that the class version is different. In other words, the Java compiler you used in Eclipse is newer than the Java runtime you use in the command prompt. You should check which Java version you want then use only this version. To change the version you use in the command prompt you must change the <code>path</code> environment variable to contain the path to the desired version. In Eclipse you can select the used version in the settings.</p> |
21,096,436 | SSL backend error when using OpenSSL | <p>I was trying to install pycurl in a virtualenv using pip and I got this error </p>
<pre><code>ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)
</code></pre>
<p>I read some documentation saying that <em>"To fix this, you need to tell setup.py what SSL backend is used"</em> <a href="https://github.com/pycurl/pycurl">(source)</a> although I am not sure how to do this since I installed pycurl using pip.</p>
<p>How can I specify the SSL backend when installing pycurl with pip?</p>
<p>Thanks</p> | 21,099,222 | 26 | 1 | null | 2014-01-13 16:33:45.783 UTC | 21 | 2021-10-06 05:30:24.62 UTC | 2015-10-09 22:45:01.507 UTC | null | 608,639 | null | 2,192,691 | null | 1 | 89 | python|curl|virtualenv|pip|pycurl | 64,099 | <h3>for most people</h3>
<p>After reading their INSTALLATION file, I was able to solve my problem by setting an environment variable and did a reinstall</p>
<pre><code># remove existing `pycurl` installation
pip uninstall pycurl
# export variable with your link-time ssl backend (which is openssl above)
export PYCURL_SSL_LIBRARY=openssl
# then, re-install `pycurl` with **no cache**
pip install pycurl --no-cache-dir
</code></pre>
<p>There could be other solution out there but this works perfectly for me on a <code>virtualenv</code> and <code>pip</code> installation.</p>
<h3>Some people have a different error message complaining about <code>nss</code> instead of <code>openssl</code></h3>
<blockquote>
<p><code>ImportError: pycurl: libcurl link-time ssl backend (nss)</code></p>
</blockquote>
<p>(the key part is <strong><code>nss</code></strong>) so you have to do something different for this error message:</p>
<pre><code>pip uninstall pycurl
pip install --no-cache-dir --compile --compile-options="--with-nss" pycurl
</code></pre> |
21,245,545 | Ping Test Using Bat File - Trouble with errorlevel | <p>I am working on setting up a LAN ping test using a batch file. The code i have works great for websites but it acts strange for local IPs. I am running the ping test on 3 computers that i know the IPs of. No matter which one i unplug, when i run the code below, the %errorlevel% is always 0 on all three computers. It never equals to 1 like it does on a website. How can i resolve this?</p>
<pre><code>@echo off
cls
Set IPaddress=www.google.com
PING %IPaddress% -n 1
call :PingTest
Set IPaddress=www.yahoo.com
PING %IPaddress% -n 1
call :PingTest
Set IPaddress=www.unabletoping.com
PING %IPaddress% -n 1
call :PingTest
pause > null
exit
:PingTest
IF %errorlevel% EQU 1 (echo "Server is Offline") else (GOTO:EOF)
</code></pre> | 21,252,613 | 4 | 2 | null | 2014-01-20 22:33:29.74 UTC | 4 | 2021-03-28 04:14:45.61 UTC | null | null | null | null | 1,399,110 | null | 1 | 2 | batch-file|ping | 83,755 | <p>When you ping an non accesible address in your subnet, you get an "unreachable" answer, with 1 packet sent, 1 packed received, 0 packets lost. Errorlevel is not set.</p>
<p>When you ping an non accesible address out of your subnet, you get a "timeout" answer, with 1 packet sent, 0 packet received, 1 packet lost. Errorlevel is set.</p>
<p>And, you can ping an active machine, lost packets and get an errorlevel</p>
<p>And, you can ping an active/inactive machine, get TTL expired and get no errorlevel</p>
<p>Better, check for content of ping response.</p>
<pre><code>ping -n 1 192.168.1.1 | find "TTL=" >nul
if errorlevel 1 (
echo host not reachable
) else (
echo host reachable
)
</code></pre> |
18,908,708 | Installing RubyGems in Windows | <p>I'm new to ruby. I tried to install Ruby Gems on my PC by following the steps given in the site <a href="http://rubygems.org/pages/download" rel="noreferrer">http://rubygems.org/pages/download</a>.</p>
<p>I downloaded the package from the mentioned site, changed the directory to the directory in which the setup resides, and tried to run setup using the command <code>setup.rb</code> in command prompt.</p>
<p>But I get a window pop up that says "Windows can't open this file" and prompts me to select a program to open this file.</p>
<p>What should I do now? Let me know if I am doing something wrong.</p> | 18,909,228 | 7 | 0 | null | 2013-09-20 04:15:06.377 UTC | 28 | 2020-10-22 10:19:29.017 UTC | 2020-10-22 10:19:29.017 UTC | null | 5,684,184 | null | 2,797,743 | null | 1 | 107 | ruby|installation|rubygems | 226,481 | <p>I recommend you just use <a href="http://rubyinstaller.org/" rel="noreferrer">rubyinstaller</a></p>
<p>It is recommended by the official Ruby page - see <a href="https://www.ruby-lang.org/en/downloads/" rel="noreferrer">https://www.ruby-lang.org/en/downloads/</a> </p>
<blockquote>
<p>Ways of Installing Ruby</p>
<p>We have several tools on each major platform to install Ruby:</p>
<ul>
<li>On Linux/UNIX, you can use the package management system of your
distribution or third-party tools (rbenv and RVM).</li>
<li>On OS X machines, you can use third-party tools (rbenv and RVM).</li>
<li>On Windows machines, you can use RubyInstaller.</li>
</ul>
</blockquote> |
29,980,798 | Where does pip install its packages? | <p>I activated a <a href="http://pypi.python.org/pypi/virtualenv" rel="noreferrer">virtualenv</a> which has pip installed. I did</p>
<pre class="lang-none prettyprint-override"><code>pip3 install Django==1.8
</code></pre>
<p>and Django successfully downloaded. Now, I want to open up the Django folder. Where is the folder located?</p>
<p>Normally it would be in "downloads", but I'm not sure where it would be if I installed it using pip in a virtualenv.</p> | 29,980,912 | 8 | 1 | null | 2015-05-01 02:25:16.247 UTC | 135 | 2021-09-02 18:09:20.067 UTC | 2020-06-27 15:50:19.613 UTC | null | 63,550 | null | 2,719,875 | null | 1 | 616 | python|django|pip|virtualenv | 814,417 | <p><em>pip</em> when used with <em>virtualenv</em> will generally install packages in the path <code><virtualenv_name>/lib/<python_ver>/site-packages</code>.</p>
<p>For example, I created a test virtualenv named <strong>venv_test</strong> with <em>Python</em> 2.7, and the <code>django</code> folder is in <code>venv_test/lib/python2.7/site-packages/django</code>.</p> |
48,712,801 | How to correct PlantUML Line Path | <p>I created this diagram using the following code. But as you can see, the lines going from (Cancel Order) and (Place Order) to (Publisher) decide to take a terribly rounded path to get their, instead of going straight to the right and then down to publisher. I tried using manual direction commands like "-down" but none of them seemed to help. Does anybody know how to fix this?</p>
<p><img src="https://i.imgur.com/vDLTot9.png" alt=""></p>
<p>And here is my code. I appreciate any help. Thank you.</p>
<pre><code>@startUML EBook Use Case Diagram
left to right direction
Actor Customer as customer
Actor EBook as ebook
Actor Publisher as publisher
rectangle "Book Catalogue" {
together {
Actor "Book Database" as bookLog
(Retrieve Information) as getBook
customer -- getBook
getBook -- ebook
getBook -- bookLog
(Update Catalogue) as updateCatalogue
ebook -- updateCatalogue
updateCatalogue -- bookLog
}
together {
(Place Order) as order
customer -- order
order -- ebook
order--publisher
(Cancel Order) as cancelOrder
customer -- cancelOrder
cancelOrder -- ebook
cancelOrder--publisher
}
}
(Ship To EBook) as shipEBook
shipEBook -- publisher
(Ship To Customer) as shipCustomer
customer -- shipCustomer
ebook -- shipEBook
shipCustomer -- ebook
(Return to EBook) as returnCustomer
(Returnto Publisher) as returnPublisher
customer -- returnCustomer
returnCustomer -- ebook
ebook -- returnPublisher
returnPublisher -- publisher
@endUML
</code></pre> | 61,795,202 | 5 | 2 | null | 2018-02-09 19:25:44.613 UTC | 17 | 2021-12-28 07:42:09.37 UTC | 2018-02-09 21:42:05.19 UTC | null | 2,007,760 | null | 5,679,048 | null | 1 | 46 | uml|graphviz|diagram|sequence-diagram|plantuml | 38,694 | <p>To make a connection less important in the layout, use <code>[norank]</code>, e.g., <code>a -[norank]-> b</code></p> |
48,682,147 | aiohttp: rate limiting parallel requests | <p>APIs often have rate limits that users have to follow. As an example let's take 50 requests/second. Sequential requests take 0.5-1 second and thus are too slow to come close to that limit. Parallel requests with aiohttp, however, exceed the rate limit.</p>
<p>To poll the API as fast as allowed, one needs to rate limit parallel calls.</p>
<p>Examples that I found so far decorate <code>session.get</code>, approximately like so:</p>
<pre><code>session.get = rate_limited(max_calls_per_second)(session.get)
</code></pre>
<p>This works well for sequential calls. Trying to implement this in parallel calls does not work as intended.</p>
<p>Here's some code as example:</p>
<pre><code>async with aiohttp.ClientSession() as session:
session.get = rate_limited(max_calls_per_second)(session.get)
tasks = (asyncio.ensure_future(download_coroutine(
timeout, session, url)) for url in urls)
process_responses_function(await asyncio.gather(*tasks))
</code></pre>
<p>The problem with this is that it will rate-limit the <strong>queueing</strong> of the tasks. The execution with <code>gather</code> will still happen more or less at the same time. Worst of both worlds ;-).</p>
<p>Yes, I found a similar question right here <a href="https://stackoverflow.com/questions/35196974/aiohttp-set-maximum-number-of-requests-per-second">aiohttp: set maximum number of requests per second</a>, but neither replies answer the actual question of limiting the rate of requests. Also <a href="https://quentin.pradet.me/blog/how-do-you-rate-limit-calls-with-aiohttp.html" rel="noreferrer">the blog post from Quentin Pradet</a> works only on rate-limiting the queueing.</p>
<p>To wrap it up: How can one limit the <em>number of requests per second</em> for parallel <code>aiohttp</code> requests?</p> | 48,682,456 | 5 | 2 | null | 2018-02-08 09:39:49.113 UTC | 16 | 2022-08-11 17:32:44.527 UTC | null | null | null | null | 996,961 | null | 1 | 31 | python|parallel-processing|python-asyncio|aiohttp | 14,924 | <p>If I understand you well, you want to limit the number of simultaneous requests?</p>
<p>There is a object inside <code>asyncio</code> named <code>Semaphore</code>, it works like an asynchronous <code>RLock</code>.</p>
<pre><code>semaphore = asyncio.Semaphore(50)
#...
async def limit_wrap(url):
async with semaphore:
# do what you want
#...
results = asyncio.gather([limit_wrap(url) for url in urls])
</code></pre>
<h1>updated</h1>
<p>Suppose I make 50 concurrent requests, and they all finish in 2 seconds. So, it doesn't touch the limitation(only 25 requests per seconds). </p>
<p>That means I should make 100 concurrent requests, and they all finish in 2 seconds too(50 requests per seconds). But before you actually make those requests, how could you determine how long will they finish? </p>
<p>Or if you doesn't mind <strong>finished requests per second</strong> but <strong>requests made per second</strong>. You can:</p>
<pre><code>async def loop_wrap(urls):
for url in urls:
asyncio.ensure_future(download(url))
await asyncio.sleep(1/50)
asyncio.ensure_future(loop_wrap(urls))
loop.run_forever()
</code></pre>
<p>The code above will create a <code>Future</code> instance every <code>1/50</code> second.</p> |
48,674,848 | FlatList not scrolling | <p>i have created a screen where I display a component that contains a FlatList. For some reason I can't scroll through the list. Someone who can spot my mistake and point me in the right direction?</p>
<p><strong>render-function and style from my screen file:</strong></p>
<pre><code>render() {
return (
<View style={styles.container}>
<SearchBar />
<ActivityList style={styles.list} data={this.state.data} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
overflow: 'hidden',
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'flex-start',
},
list: {
flex: 1,
overflow: 'hidden',
},
});
</code></pre>
<p><strong>render function and style from my listitem component:</strong></p>
<pre><code>export default class CardItem extends React.PureComponent {
render() {
return (
<View style={styles.cardview}>
<View style={styles.imagecontainer}>
<Image
resizeMode="cover"
style={styles.cardimage}
source={{
uri: this.props.image,
}}
/>
</View>
<View style={styles.cardinfo}>
<Text style={styles.cardtitle}>{this.props.title}</Text>
<View style={styles.cardtext}>
<Text style={styles.textdate}>{this.props.date}</Text>
<Text style={styles.texthour}>{this.props.hour}</Text>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
cardview: {
flex: 1,
justifyContent: 'flex-start',
backgroundColor: 'white',
elevation: 3,
maxHeight: 200,
width: Dimensions.get('window').width - 20,
margin: 1,
marginTop: 10,
borderRadius: 4,
},
imagecontainer: {
flex: 7,
height: 140,
borderRadius: 4,
},
cardimage: {
flex: 1,
opacity: 0.8,
height: 140,
borderTopLeftRadius: 4,
borderTopRightRadius: 4,
},
cardinfo: {
flex: 2,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
padding: 10,
},
cardtitle: {
flex: 1,
fontSize: 16,
fontWeight: 'bold',
},
cardtext: {
flex: 1,
justifyContent: 'center',
alignItems: 'flex-end',
},
textdate: {
color: '#5e5e71',
},
texthour: {
color: '#5e5e71',
},
});
</code></pre>
<p><strong>render function and style from my list component:</strong></p>
<pre><code>export default class ActivityList extends React.Component {
_renderCardItem = ({ item }) => (
<CardItem
image={item.image}
title={item.title}
date={item.date}
hour={item.hour}
/>
);
_keyExtractor = item => item.id;
render() {
return (
<FlatList
data={this.props.data}
renderItem={this._renderCardItem}
contentContainerStyle={styles.cardcontainer}
keyExtractor={this._keyExtractor}
/>
);
}
}
const styles = StyleSheet.create({
cardcontainer: {
flex: 1,
overflow: 'hidden',
backgroundColor: 'white',
alignItems: 'center',
width: Dimensions.get('window').width,
borderWidth: 0,
},
});
</code></pre>
<p>my data items have all a unique id, title, date, hour.</p>
<p>Read through all available guides and docs and found no solution.</p> | 48,676,015 | 14 | 2 | null | 2018-02-07 23:10:02.85 UTC | 9 | 2022-08-16 03:08:34.707 UTC | null | null | null | null | 7,888,429 | null | 1 | 36 | javascript|css|reactjs|react-native | 75,868 | <p>Take out the <code>flex: 1</code> in your <code>styles.cardcontainer</code>, that should let you scroll. The FlatList/ScrollView <code>contentContainerStyle</code> prop wraps all the child components—what's "inside" the FlatList if you will—and should never have a defined height or flex value. If you need to set a <code>flex: 1</code> for the FlatList itself use <code>style={{flex: 1}}</code> instead. Cheers!</p> |
8,366,701 | Reading the values from OBD II Bluetooth adapter in the android application | <p>Can anyone give me an idea on how to read the values from the OBD II Bluetooth adapter in an android application.</p>
<p>I want to start with scanning for the bluetooth devices from my android application, then after bluetooth device is found, how would I interact with it and get the values from it?</p> | 8,367,944 | 4 | 0 | null | 2011-12-03 09:14:59.15 UTC | 13 | 2016-12-14 10:26:11.283 UTC | 2016-12-14 10:26:11.283 UTC | null | 773,263 | null | 384,193 | null | 1 | 8 | android|bluetooth|obd-ii | 13,825 | <p>You should start by reading this <a href="http://developer.android.com/guide/topics/wireless/bluetooth.html" rel="nofollow">http://developer.android.com/guide/topics/wireless/bluetooth.html</a>
it contains step by step procedure .</p>
<p>add required permissions,
make a bt adapter,
then find paired/unpaired devices</p> |
8,775,295 | jQuery grab a file uploaded with input type='file' | <p>I want to grab the file uploaded in a <code><input type='file'></code> tag.</p>
<p>When I do $('#inputId').val(), it only grabs the <em>name</em> of the file, not the actual file itself.</p>
<p>I'm trying to follow this: </p>
<p><a href="http://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/">http://hacks.mozilla.org/2011/03/the-shortest-image-uploader-ever/</a></p>
<pre><code>function upload(file) {
// file is from a <input> tag or from Drag'n Drop
// Is the file an image?
if (!file || !file.type.match(/image.*/)) return;
// It is!
// Let's build a FormData object
var fd = new FormData();
fd.append("image", file); // Append the file
fd.append("key", "6528448c258cff474ca9701c5bab6927");
// Get your own key: http://api.imgur.com/
// Create the XHR (Cross-Domain XHR FTW!!!)
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
xhr.onload = function() {
// Big win!
// The URL of the image is:
JSON.parse(xhr.responseText).upload.links.imgur_page;
}
// Ok, I don't handle the errors. An exercice for the reader.
// And now, we send the formdata
xhr.send(fd);
}
</code></pre> | 8,775,390 | 2 | 0 | null | 2012-01-08 04:04:11.703 UTC | 7 | 2012-06-14 06:34:39.713 UTC | null | null | null | null | 322,900 | null | 1 | 14 | javascript|jquery | 38,641 | <p>Use <code>event.target.files</code> for <code>change</code> event to retrieve the File instances.</p>
<pre><code>$('#inputId').change(function(e) {
var files = e.target.files;
for (var i = 0, file; file = files[i]; i++) {
console.log(file);
}
});
</code></pre>
<p>Have a look here for more info: <a href="http://www.html5rocks.com/en/tutorials/file/dndfiles/" rel="noreferrer">http://www.html5rocks.com/en/tutorials/file/dndfiles/</a></p>
<p>This solution uses File API which is not supported by all browser - see <a href="http://caniuse.com/#feat=fileapi" rel="noreferrer">http://caniuse.com/#feat=fileapi</a> .</p> |
8,998,612 | How to pass the value 'undefined' to a function with multiple parameters? | <p>I want to pass the value of 'undefined' on a multiple parameter function but without omitting the parameter.</p>
<p>What do I mean with <em>"without omitting the parameter"</em>. I mean that we should not just omit the <code>parm2</code> like this example:</p>
<pre><code>function myFunction (parm1, parm2) {}
myFunction("abc");
</code></pre>
<p>This will indeed make <code>parm2</code> undefined, but I am not allowed to do it this way because I will need to specify other parameters AFTER the omitted parameter, so the previous method won't work in the case I want to make <code>parm1</code> undefined BUT also want to have other parameters after this one to hold a value.</p>
<p>I have tried solving the problem with:</p>
<pre><code>myFunction( ,"abc"); //doesn't seem to work
</code></pre>
<hr>
<p><strong>Update:</strong></p>
<p><s></p>
<p>and <code>myFunction(undefined, "abc");</code></s> « this reliably works now.</p>
<p>However, it is worth mentioning that:</p>
<blockquote>
<p>Setting a variable to <code>undefined</code> is considered a bad practice, we
should be using <code>null</code> instead.</p>
</blockquote> | 8,998,692 | 12 | 0 | null | 2012-01-25 06:14:29.567 UTC | 6 | 2018-11-13 20:49:38.667 UTC | 2018-11-13 20:49:38.667 UTC | null | 908,879 | null | 908,879 | null | 1 | 49 | javascript|function|parameter-passing|undefined | 63,621 | <p><code>myFunction(undefined,"abc");</code> this way should work, what is the problem?</p>
<p>see <a href="http://jsfiddle.net/HAr3M/" rel="noreferrer">here</a></p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined" rel="noreferrer">Here is undefined documentation</a> from mozilla, supported by all browsers</p> |
27,131,165 | What is the difference between PermGen and Metaspace? | <p>Until Java 7 there was an area in JVM memory called <strong>PermGen</strong>, where JVM used to keep its classes. In <a href="http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html" rel="noreferrer">Java 8</a> it was removed and replaced by area called <strong>Metaspace</strong>. </p>
<p>What are <strong>the most important differences</strong> between PermGen and Metaspace?</p>
<p>The only difference I know is that <code>java.lang.OutOfMemoryError: PermGen space</code> can no longer be thrown and the VM parameter <code>MaxPermSize</code> is ignored. </p> | 27,144,099 | 5 | 2 | null | 2014-11-25 15:52:35.483 UTC | 63 | 2021-08-08 08:16:28.247 UTC | 2019-03-22 03:20:38.47 UTC | null | 2,361,308 | null | 3,401,555 | null | 1 | 129 | java|java-8|java-7|permgen|metaspace | 65,826 | <p>The main difference from a user perspective - which I think the previous answer does not stress enough - is that <strong>Metaspace by default auto increases</strong> its size (up to what the underlying OS provides), while PermGen always has a fixed maximum size. You can set a fixed maximum for Metaspace with JVM parameters, but you cannot make PermGen auto-increase.</p>
<p>To a large degree it is just a change of name. Back when PermGen was introduced, there was no Java EE or dynamic class(un)loading, so once a class was loaded it was stuck in memory until the JVM shut down - thus <em>Permanent</em> Generation. Nowadays classes may be loaded and unloaded during the lifespan of the JVM, so Metaspace makes more sense for the area where the metadata is kept.</p>
<p>Both of them contain the <code>java.lang.Class</code> instances and both of them suffer from <a href="http://java.jiderhamn.se/2011/12/11/classloader-leaks-i-how-to-find-classloader-leaks-with-eclipse-memory-analyser-mat/" rel="noreferrer">ClassLoader leaks</a>. Only difference is that with Metaspace default settings, it takes longer until you notice the symptoms (since it auto increases as much as it can), i.e. you just push the problem further away without solving it. OTOH I imagine the effect of running out of OS memory can be more severe than just running out of JVM PermGen, so I'm not sure it is much of an improvement.</p>
<p>Whether you're using a JVM with PermGen or with Metaspace, if you are doing dynamic class unloading, you should to take measures against classloader leaks, for example by using my <a href="https://github.com/mjiderhamn/classloader-leak-prevention" rel="noreferrer">ClassLoader Leak Prevention library</a>.</p> |
26,472,839 | Are there constructor references in Kotlin? | <p>In Java we have the <code>Class::new</code> syntax for constructor references. I know, there are callable references for methods, but how about constructors? A typical use case for me would be factories.</p> | 26,479,515 | 1 | 0 | null | 2014-10-20 18:51:39.247 UTC | 8 | 2021-11-24 15:51:47.443 UTC | 2021-11-24 15:51:47.443 UTC | null | 8,583,692 | null | 615,306 | null | 1 | 136 | kotlin|function-reference|constructor-reference | 16,747 | <p>You can get a function instance for a constructor by simply using <code>::ClassName</code>, as if it were a factory function. </p> |
26,471,225 | Spring 3.1 or Later @RequestMapping Consumes/Produces | <p>I have a question in regards to the consumes and produces part of the <code>@RequestMapping</code>. I have an endpoint that I want to accept both JSON and XML and return JSON when JSON is passed in and return XML when XML is passed in. Is there anything special that I have to do to make this work?</p>
<p>Sample code is listed below.</p>
<pre><code>@RequestMapping(value = "/something", method = PUT,
consumes = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE},
produces = {APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE})
public SomeObject updateSomeObject(SomeObject acct) {
return doStuff(acct);
}
</code></pre>
<p>Will this work the way I'm expecting or do I need two endpoints <code>updateSomeObjectXML</code> and <code>updateSomeObjectJson</code> to handle both cases?</p>
<p>Thanks,
Mike</p> | 26,472,310 | 3 | 0 | null | 2014-10-20 17:14:36.307 UTC | 11 | 2018-01-23 00:57:47.813 UTC | 2018-01-23 00:57:47.813 UTC | null | 3,641,067 | null | 1,212,443 | null | 1 | 24 | java|spring|rest|spring-mvc|media-type | 86,965 | <p>The article from the Spring blog - <a href="https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc" rel="noreferrer">Content Negotiation using Spring MVC</a> - provides details on how content negotiation works with Spring MVC, in brief if you want the same endpoint to handle XML and JSON, your mapping is correct, to summarize from the article:</p>
<ol>
<li><p>Use path extension - you can send a json to <code>/something.json</code> and xml to <code>/something.xml</code> and expect the same thing on the way back</p></li>
<li><p>Use the <code>Accept</code> header, use a value of <code>application/json</code> or <code>application/xml</code> and use <code>Content-Type</code> to specify the submitted media type.</p></li>
</ol> |
30,502,922 | A __construct on an Eloquent Laravel Model | <p>I have a custom setter that I'm running in a <code>__construct</code> method on my model. </p>
<p>This is the property I'm wanting to set.</p>
<pre><code> protected $directory;
</code></pre>
<p>My Constructor</p>
<pre><code> public function __construct()
{
$this->directory = $this->setDirectory();
}
</code></pre>
<p>The setter:</p>
<pre><code> public function setDirectory()
{
if(!is_null($this->student_id)){
return $this->student_id;
}else{
return 'applicant_' . $this->applicant_id;
}
}
</code></pre>
<p>My problem is that inside my setter the, <code>$this->student_id</code> (which is an attribute of the model being pulled from the database) is returning <code>null</code>.
When I <code>dd($this)</code> from inside my setter, I notice that my <code>#attributes:[]</code> is an empty array. <br /> So, a model's attributes aren't set until after <code>__construct()</code> is fired. How can I set my <code>$directory</code> attribute in my construct method?</p> | 30,503,372 | 2 | 0 | null | 2015-05-28 09:45:00.017 UTC | 10 | 2022-03-21 20:38:49.23 UTC | null | null | null | null | 4,010,661 | null | 1 | 39 | php|laravel|eloquent | 52,103 | <p>You need to change your constructor to:</p>
<pre><code>public function __construct(array $attributes = array())
{
parent::__construct($attributes);
$this->directory = $this->setDirectory();
}
</code></pre>
<p>The first line (<code>parent::__construct()</code>) will run the Eloquent <code>Model</code>'s own construct method before your code runs, which will set up all the attributes for you. Also the change to the constructor's method signature is to continue supporting the usage that Laravel expects: <code>$model = new Post(['id' => 5, 'title' => 'My Post']);</code></p>
<p>The rule of thumb really is to always remember, when extending a class, to check that you're not overriding an existing method so that it no longer runs (this is especially important with the magic <code>__construct</code>, <code>__get</code>, etc. methods). You can check the source of the original file to see if it includes the method you're defining.</p> |
778,252 | How to get the current directory on a class library? | <p>I've been looking around but I have not found a solution for this problem: I want to create a class library that has a configuration file under a sub-directory called Configuration. I want that class library to be deployed anywhere and I want it to find its configuration files by knowing its own location.</p>
<p>Previous attempts with <code>Assembly.GetExecutingAssembly().Location</code> did not work.<br>
It would return temp locations such as</p>
<p><code>C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\7c00e0a3\38789d63\assembly\dl3\9c0a23ff\18fb5feb_6ac3c901</code> </p>
<p>instead of the desired </p>
<p><code>bin/Configuration</code> path. </p>
<p>So: </p>
<ol>
<li>Can a class library be aware of its own location on disk? </li>
<li>How would I go about witting test scripts for this functionality since it seems that directories change based on how you run the app (debugging inside VS, deploying on IIS, etc)</li>
</ol> | 778,272 | 3 | 3 | null | 2009-04-22 17:03:56.853 UTC | 4 | 2020-11-03 18:19:13.877 UTC | 2018-06-15 10:30:44.74 UTC | null | 532,675 | null | 3,440 | null | 1 | 29 | c#|asp.net|path|filepath|configuration-files | 32,722 | <p>This should work - </p>
<pre><code>string assemblyFile = (
new System.Uri(Assembly.GetExecutingAssembly().CodeBase)
).AbsolutePath;
</code></pre> |
20,667,761 | Composer killed while updating | <p>I got a problem, I tried to install a new package to my Laravel 4 project.
But when I run <code>php composer.phar update</code> I get this:</p>
<pre><code>Loading composer repositories with package information
Updating dependencies (including require-dev)
Killed
</code></pre>
<p>I have looked for the problem in the Internet and saw that the memory is the problem, I think I don't have enough RAM available, I've checked this I have about 411mb free.
Does composer really need more RAM?</p> | 20,699,258 | 19 | 0 | null | 2013-12-18 20:29:02.443 UTC | 53 | 2022-08-20 16:29:08.653 UTC | 2019-08-27 22:14:03.143 UTC | null | 1,839,439 | null | 3,038,158 | null | 1 | 178 | php|laravel|laravel-4|composer-php | 190,854 | <p>The "Killed" message usually means your process consumed too much memory, so you may simply need to add more memory to your system if possible. At the time of writing this answer, I've had to increase my virtual machine's memory to at least 768MB in order to get <code>composer update</code> to work in some situations.</p>
<p>However, if you're doing this on a live server, you shouldn't be using <code>composer update</code> at all. What you should instead do is:</p>
<ol>
<li>Run <code>composer update</code> in a local environment (such as directly on your physical laptop/desktop, or a docker container/VM running on your laptop/desktop) where memory limitations shouldn't be as severe.</li>
<li>Upload or <code>git push</code> the composer.lock file.</li>
<li>Run <code>composer install</code> on the live server.</li>
</ol>
<p><code>composer install</code> will then read from the .lock file, fetching the exact same versions every time rather than finding the latest versions of every package. This makes your app less likely to break, and composer uses less memory.</p>
<p>Read more here: <a href="https://getcomposer.org/doc/01-basic-usage.md#installing-with-composer-lock" rel="noreferrer">https://getcomposer.org/doc/01-basic-usage.md#installing-with-composer-lock</a></p>
<p>Alternatively, you can upload the entire <code>vendor</code> directory to the server, bypassing the need to run <code>composer install</code> at all, but then you <em>should</em> run <code>composer dump-autoload --optimize</code>.</p> |
24,117,178 | Android : Typeface is changed when i apply password Type on EditText | <p>I use <strong>FloatLabel</strong> library (<a href="https://github.com/weddingparty/AndroidFloatLabel" rel="noreferrer">https://github.com/weddingparty/AndroidFloatLabel</a>) to add a little animation when user begin to write something in an EditText Android.</p>
<p>My problem is that the typeface seems to be changed when i apply the password type to my EditText. I would like to keep the same typeface as normal. (see picture 1)</p>
<p><img src="https://i.stack.imgur.com/tcD78.jpg" alt="enter image description here"></p>
<p>But when i add the following line to apply password type, the typeface of hint seems to be changed !</p>
<pre><code>pass.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
</code></pre>
<p><img src="https://i.stack.imgur.com/malFC.jpg" alt="enter image description here"></p> | 24,120,816 | 6 | 0 | null | 2014-06-09 09:20:25.593 UTC | 8 | 2020-11-07 06:56:06.96 UTC | 2014-06-09 12:38:03 UTC | null | 2,959,925 | null | 1,076,026 | null | 1 | 52 | android|android-edittext|typeface | 22,656 | <p>The following might solve it for you.</p>
<pre><code>pass.setTypeface(user.getTypeface());
</code></pre>
<p>Essentially it just passes the <code>Typeface</code> of your username field and passes it as the <code>Typeface</code> for your password field.</p>
<hr>
<p>I found an explanation of this in the <a href="http://developer.android.com/guide/topics/ui/dialogs.html">Dialogs API Guide</a>.</p>
<blockquote>
<p><strong>Tip:</strong> By default, when you set an EditText element to use the
<code>"textPassword"</code> input type, the font family is set to monospace, so you
should change its font family to <code>"sans-serif"</code> so that both text fields
use a matching font style.</p>
</blockquote>
<p>In otherwords, a fix that can be done in XML would be as follows:</p>
<pre><code><EditText
android:id="@+id/password"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:hint="@string/password"/>
</code></pre> |
35,800,795 | Number of partitions in RDD and performance in Spark | <p>In Pyspark, I can create a RDD from a list and decide how many partitions to have:</p>
<pre><code>sc = SparkContext()
sc.parallelize(xrange(0, 10), 4)
</code></pre>
<p>How does the number of partitions I decide to partition my RDD in influence the performance?
And how does this depend on the number of core my machine has?</p> | 35,802,240 | 3 | 1 | null | 2016-03-04 16:13:34.64 UTC | 23 | 2020-11-01 15:32:13.403 UTC | null | null | null | null | 2,352,319 | null | 1 | 45 | performance|apache-spark|pyspark|rdd | 48,005 | <p>The primary effect would be by specifying too few partitions or <strong><em>far</em></strong> too many partitions.</p>
<p><strong>Too few partitions</strong> You will not utilize all of the cores available in the cluster.</p>
<p><strong>Too many partitions</strong> There will be excessive overhead in managing many small tasks.</p>
<p>Between the two the first one is far more impactful on performance. Scheduling too many smalls tasks is a relatively small impact at this point for partition counts below 1000. If you have on the order of tens of thousands of partitions then spark gets <strong><em>very</em></strong> slow.</p> |
5,807,560 | Requesting iPhone location whilst in background? | <p>Simple question ... I have an application that records a users location at 30second intervals (using an NSTimer) it works perfectly until the application goes "inactive" and the NStimer stops. As a consequence I am looking for options to maintain my location interval (30secs) whilst still being able to record fairly accurate location data (within 100m accuracy).</p>
<ul>
<li><p><strong>Option_001, Brute Force:</strong> Let CLLocationManager, startUpdatingLocation run all the time using UIBackgroundModes = "location". Not recommended, drains battery. Regularity upon request, Accuracy approx. 10-65m. Might just be the only realistic option.</p></li>
<li><p><strong>Option_002, SLC:</strong> I could use Significant Location Change but the frequency of location updates is pretty poor (not to mention accuracy). This is particularly true if the application is running in a rural or wilderness area with limited numbers of cell towers. Regularity unknown, Accuracy approx. 500m</p></li>
<li><p><strong>Option_003, Hybrid:</strong> I could use Significant Location Change (SLC) in the background as an indicator of "significant" movement and then request an GPS location based on kCLLocationAccuracyBest. This would work but the SLC events are not going to arrive at anywhere near 30second intervals (particularly when walking). Regularity unknown, Accuracy approx. 10-50m.</p></li>
<li><p><strong>Option_004, Something else?</strong> any ideas would be much appreciated.</p></li>
</ul>
<hr>
<p><strong>NOTE:</strong> <em>I thought I had this working because when you press [LOCK] on an iPhone (connected via USB) applicationWillResignActive is called but NSTimers do not stop. If you try the same with the iPhone un-connected (i.e. as the phone would be in normal use) the NSTimers stop almost immediately after applicationWillResignActive is called.</em> </p> | 5,868,752 | 3 | 2 | null | 2011-04-27 16:41:46.007 UTC | 11 | 2013-06-26 10:10:46.237 UTC | 2011-04-28 08:11:48.89 UTC | null | 164,216 | null | 164,216 | null | 1 | 13 | iphone|objective-c|cocoa-touch | 5,352 | <p>First of all, don't use a timer to update the user location. Approach it from the other end:
check, when a new location is received, the interval since the last "recording" and decide if you want to record the new location or not. </p>
<p>Also, this will get around your "inactive" state problem. Just enable background location services. Info.plist > Required background modes > App registers for location updates</p>
<p>Whilst in background, when a new location is received, your app will go in a "background active" state that will allow enough time to make an API call and push the new location.</p>
<p>In a sentence, you need to design this app to work well with the new background modes.</p>
<p>Note: this solution won't work for iOS3.x </p> |
5,879,953 | Tracking API for Fedex and UPS | <p>Is there any JavaScript API available for tracking Fedex and UPS packages?</p> | 5,987,850 | 3 | 1 | null | 2011-05-04 07:25:01.533 UTC | 9 | 2021-09-22 09:56:38.14 UTC | 2019-08-11 03:30:17.753 UTC | null | 11,406,628 | null | 735,900 | null | 1 | 18 | ups|fedex | 55,812 | <p>I googled for something like this but couldn't find anything. Then I decided to do it server side in ROR.</p>
<p>Here it is how to get UPS and Fedex <code>xml</code> request and response from their test servers.</p>
<h2>For Fedex:</h2>
<pre class="lang-rb prettyprint-override"><code>track_no = '111111111111' # This is a test tracking number
# This XML Request body for fedex
xml_req =
"<TrackRequest xmlns='http://fedex.com/ws/track/v3'><WebAuthenticationDetail><UserCredential><Key>YOUR_ACC_KEY</Key>
<Password>YOUR_ACC_PASSWORD</Password></UserCredential></WebAuthenticationDetail><ClientDetail>
<AccountNumber>YOUR_ACC_NUMBER</AccountNumber><MeterNumber>YOUR_ACC_METER_NUMBER</MeterNumber></ClientDetail>
<TransactionDetail><CustomerTransactionId>ActiveShipping</CustomerTransactionId></TransactionDetail>
<Version><ServiceId>trck</ServiceId><Major>3</Major><Intermediate>0</Intermediate><Minor>0</Minor></Version>
<PackageIdentifier><Value>#{track_no}</Value><Type>TRACKING_NUMBER_OR_DOORTAG</Type></PackageIdentifier>
<IncludeDetailedScans>1</IncludeDetailedScans></TrackRequest>"
path = "https://gatewaybeta.fedex.com:443/xml"
#this url connects to the test server of fedex
# for live server url is:"https://gateway.fedex.com:443/xml"
url = URI.parse(path)
http = Net::HTTP.new(url.host,url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http.post(url.path, xml_req)
response_body = response.body
res = response_body.gsub(/<(\/)?.*?\:(.*?)>/, '<\1\2>')
hash = Hash.from_xml(res.to_s)
</code></pre>
<p>And that's it! You will get response in hash variable, I converted <code>xml</code> response in to Hash because we can easily use Hash object at our view to display response data.</p>
<h2>For UPS:</h2>
<pre class="lang-rb prettyprint-override"><code>track_no = '1Z12345E1512345676' # This is a test tracking number
# This XML Request body for UPS
xml_req =
'<?xml version="1.0"?><AccessRequest xml:lang="en-US"><AccessLicenseNumber>YOUR_ACC_LICENCE_NUMBER</AccessLicenseNumber>
<UserId>YOUR_ACC_USER_ID</UserId><Password>YOUR_ACC_PASSWORD</Password></AccessRequest>
<?xml version="1.0"?><TrackRequest xml:lang="en-US"><Request><TransactionReference>
<CustomerContext>QAST Track</CustomerContext><XpciVersion>1.0</XpciVersion></TransactionReference>
<RequestAction>Track</RequestAction><RequestOption>activity</RequestOption></Request>
<TrackingNumber>#{track_no}</TrackingNumber></TrackRequest>'
path = "https://www.ups.com/ups.app/xml/Track"
url = URI.parse(path)
http = Net::HTTP.new(url.host,url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http.post(url.path, xml_req)
response_body = response.body
hash = Hash.from_xml(response_body.to_s)
</code></pre>
<p>This hash variable contains the response of UPS Tracking Request in Hash format.</p> |
5,781,597 | Incomplete type is not allowed: stringstream | <p>Why does this line give the error <code>Error: incomplete type is not allowed</code>?</p>
<pre><code>stringstream ss;
</code></pre> | 5,781,667 | 3 | 2 | null | 2011-04-25 18:20:56.307 UTC | 15 | 2020-07-17 19:06:55.633 UTC | 2015-08-06 23:41:46.337 UTC | null | 1,505,939 | null | 1,870,451 | null | 1 | 132 | c++|types|stringstream | 218,536 | <p><code>#include <sstream></code> and use the fully qualified name i.e. <code>std::stringstream ss;</code></p> |
52,714,672 | Is there an openjdk-11-jre? | <p>For Linux distributions, there is a package openjdk-8-jre for installing just the jre part of the openjdk 8.
Is there something familiar for the latest openjdk 11 for windows?
The latest openjdk versions can be downloaded at <a href="http://jdk.java.net/11/" rel="noreferrer">http://jdk.java.net/11/</a> but I cannot find a way to download just the jre part.</p> | 52,717,729 | 3 | 2 | null | 2018-10-09 06:32:41.527 UTC | null | 2022-03-23 05:06:26.99 UTC | 2019-03-05 07:50:07.537 UTC | null | 2,664,350 | null | 1,755,381 | null | 1 | 21 | java | 60,443 | <p>We don't provide a separate JRE download with JDK 11. Instead, you can use jlink to create a custom runtime image with just the set of modules required by your application. Please see <a href="https://docs.oracle.com/en/java/javase/11/tools/jlink.html" rel="noreferrer">https://docs.oracle.com/en/java/javase/11/tools/jlink.html</a> for details.</p> |
34,619,535 | Tap on UISlider to Set the Value | <p>I created a Slider (operating as control of the video, like YouTube has at the bottom) and set the maximum (duration) and minimum values. And then used <code>SeekToTime</code> to change the currentTime. Now, the user can slide the thumb of the slider to change the value </p>
<p>What I want to achieve is letting the user tap on anywhere on the slider and set the current time of the video.</p>
<p>I got an approach from <a href="https://stackoverflow.com/questions/22717167/how-to-enable-tap-and-slide-in-a-uislider/22718266#22718266">this answer</a>, and I tried to apply it to my case, but couldn't make it work</p>
<pre><code>class ViewController: UIViewController, PlayerDelegate {
var slider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
// Setup the slider
}
func sliderTapped(gestureRecognizer: UIGestureRecognizer) {
// print("A")
let pointTapped: CGPoint = gestureRecognizer.locationInView(self.view)
let positionOfSlider: CGPoint = slider.frame.origin
let widthOfSlider: CGFloat = slider.frame.size.width
let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider)
slider.setValue(Float(newValue), animated: true)
}
}
</code></pre>
<p>I thought this should work, but no luck. Then I tried debugging with trying to printing "A" to logs, but it doesn't so apparently it doesn't go into the <code>sliderTapped()</code> function. </p>
<p>What am I doing wrong? Or is there a better way to achieve what I am trying to achieve?</p> | 34,619,780 | 7 | 1 | null | 2016-01-05 19:14:57.333 UTC | 10 | 2021-03-31 18:27:54.09 UTC | 2017-05-23 12:34:50.693 UTC | null | -1 | null | 4,705,339 | null | 1 | 26 | ios|swift|uigesturerecognizer|uislider|uitapgesturerecognizer | 18,315 | <p>Looks like you need to actually initialize the tap gesture recognizer in your viewDidLoad() per the code example above. There's a comment there, but I don't see the recognizer being created anywhere.</p>
<p><strong>Swift 2:</strong></p>
<pre><code>class ViewController: UIViewController {
var slider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
// Setup the slider
// Add a gesture recognizer to the slider
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "sliderTapped:")
self.slider.addGestureRecognizer(tapGestureRecognizer)
}
func sliderTapped(gestureRecognizer: UIGestureRecognizer) {
// print("A")
let pointTapped: CGPoint = gestureRecognizer.locationInView(self.view)
let positionOfSlider: CGPoint = slider.frame.origin
let widthOfSlider: CGFloat = slider.frame.size.width
let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider)
slider.setValue(Float(newValue), animated: true)
}
}
</code></pre>
<p><strong>Swift 3:</strong></p>
<pre><code>class ViewController: UIViewController {
var slider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
// Setup the slider
// Add a gesture recognizer to the slider
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(sliderTapped(gestureRecognizer:)))
self.slider.addGestureRecognizer(tapGestureRecognizer)
}
func sliderTapped(gestureRecognizer: UIGestureRecognizer) {
// print("A")
let pointTapped: CGPoint = gestureRecognizer.location(in: self.view)
let positionOfSlider: CGPoint = slider.frame.origin
let widthOfSlider: CGFloat = slider.frame.size.width
let newValue = ((pointTapped.x - positionOfSlider.x) * CGFloat(slider.maximumValue) / widthOfSlider)
slider.setValue(Float(newValue), animated: true)
}
}
</code></pre> |
2,039,910 | Get files in a folder | <p>In my MVC application I have the following paths;</p>
<ul>
<li>/content/images/full</li>
<li>/content/images/thumbs</li>
</ul>
<p>How would I, in my c# controller, get a list of all the files within my thumbs folder?</p>
<p><strong>Edit</strong></p>
<p>Is Server.MapPath still the best way?</p>
<p>I have this now <code>DirectoryInfo di = new DirectoryInfo(Server.MapPath("/content/images/thumbs") );</code> but feel it's not the right way.</p>
<p>is there a best practice in MVC for this or is the above still correct?</p> | 2,039,944 | 2 | 1 | null | 2010-01-11 04:26:53.05 UTC | 8 | 2012-11-12 22:13:10.27 UTC | 2010-01-11 04:42:07.31 UTC | null | 129,195 | null | 129,195 | null | 1 | 22 | asp.net-mvc|file | 48,240 | <pre><code>Directory.GetFiles("/content/images/thumbs")
</code></pre>
<p>That will get all the files in a directory into a string array.</p> |
1,721,433 | Active Record with Delegate and conditions | <p>Is it possible to use delegate in your Active Record model and use conditions like <code>:if</code> on it?</p>
<pre><code>class User < ApplicationRecord
delegate :company, :to => :master, :if => :has_master?
belongs_to :master, :class_name => "User"
def has_master?
master.present?
end
end
</code></pre> | 1,721,525 | 2 | 0 | null | 2009-11-12 10:56:32.99 UTC | 6 | 2016-11-03 01:46:37.153 UTC | 2016-11-03 01:46:37.153 UTC | null | 2,202,702 | null | 146,607 | null | 1 | 32 | ruby-on-rails|ruby|activerecord|delegates | 13,511 | <p>No, you can't, but you can pass the <code>:allow_nil => true</code> option to return nil if the master is nil.</p>
<pre><code>class User < ActiveRecord::Base
delegate :company, :to => :master, :allow_nil => true
# ...
end
user.master = nil
user.company
# => nil
user.master = <#User ...>
user.company
# => ...
</code></pre>
<p>Otherwise, you need to write your own custom method instead using the delegate macro for more complex options.</p>
<pre><code>class User < ActiveRecord::Base
# ...
def company
master.company if has_master?
end
end
</code></pre> |
53,499,361 | How do I call a method from another class component in React.js | <p>So I have to class components:<br/>
Class1: has a clickbutton<br />
Class2: has a method calling my api<br />
<br />
Basically, what I want is to call a method that sets and edits states inside one class from another class. But I keep failing.</p>
<h2>Example:</h2>
<pre><code>Class1.js
export class Class1 extends Component {
render() {
return (
<div onClick={must call Class2Method}></div>
)
}
}
Class2.js
export class Class2 extends Component {
Class2Method(){
Here I call my API, I set & call states, ...
}
render {
return (
<Class1 />
Here I return my API content
)
}
}
</code></pre>
<h2>What I tried:</h2>
<ol>
<li>I have tried to use my method and call and set my states in my App.js (parent of both class2 and class1); but then my Class2.js console says it can't find my states.</li>
<li>I also tried: < Class1 method={this.Class2Method} /> in my Class 2 and < div onClick={this.props.method} > in Class1.</li>
</ol> | 53,499,596 | 3 | 2 | null | 2018-11-27 12:08:28.127 UTC | 4 | 2018-11-27 13:02:51.347 UTC | null | null | null | null | 10,133,180 | null | 1 | 19 | reactjs|class|methods|components | 85,295 | <p>Here you go</p>
<p>Class1.js</p>
<pre><code> export class Class1 extends Component {
render() {
return (
<div onClick={this.props.callApi}></div>
)
}
}
</code></pre>
<p>Class2.js</p>
<ol>
<li>Either bind callApi function in constructor or change it to arrow function.</li>
<li><p>Passdown callApi method to class1 component as a prop and access it in the above component as this.props.callApi and pass it to onClick of div.</p>
<pre><code> export class Class2 extends Component {
callApi = () => {
Here I call my API, I set & call states, ...
}
render {
return (
<Class1 callApi={this.callApi} />
Here I return my API content
)
}
}
</code></pre></li>
</ol> |
15,124,590 | Column binding in R | <p>I am using the cbind command in R to bind many data.frames together and each data frame has the same column names so when I bind them all, R automatically changes the column names from their original names. For example, there is a column named "X" so for each binding it renames this X.1, X.2, X.3 etc. Is there a way for me to bind them without changing any of the column names and have multiple columns with the same name? </p>
<p>The reason I wish to do this is so I can sort the combined data.frame after by the column names to get all the equal named columns together in the same order they were in the combined data.frame.</p> | 15,124,674 | 1 | 2 | null | 2013-02-27 23:27:46.85 UTC | 1 | 2013-02-27 23:34:05.33 UTC | null | null | null | null | 1,836,894 | null | 1 | 1 | r|binding|dataframe | 65,852 | <p>To illustrate the points from my comment:</p>
<pre><code>> d1 <- data.frame(a = 1:5,b = 1:5)
> d2 <- data.frame(a = letters[1:5],b = letters[1:5])
> cbind(d1,d2)
a b a b
1 1 1 a a
2 2 2 b b
3 3 3 c c
4 4 4 d d
5 5 5 e e
> data.frame(cbind(d1,d2))
a b a.1 b.1
1 1 1 a a
2 2 2 b b
3 3 3 c c
4 4 4 d d
5 5 5 e e
> x <- data.frame(cbind(d1,d2))
> sort(colnames(x))
[1] "a" "a.1" "b" "b.1"
> x[,order(colnames(x))]
a a.1 b b.1
1 1 a 1 a
2 2 b 2 b
3 3 c 3 c
4 4 d 4 d
5 5 e 5 e
</code></pre> |
29,106,996 | What is a Git commit ID? | <p>How are the Git commit IDs generated to uniquely identify the commits?</p>
<p>Example: <code>521747298a3790fde1710f3aa2d03b55020575aa</code></p>
<p>How does it work? Are they only unique for each project? Or for the Git repositories globally?</p> | 29,107,504 | 2 | 1 | null | 2015-03-17 18:29:19.01 UTC | 12 | 2022-08-04 20:35:48.533 UTC | 2018-07-17 18:19:17.123 UTC | null | 63,550 | null | 1,166,505 | null | 1 | 62 | git|git-svn|uniqueidentifier|git-commit | 78,038 | <p>Here's an example of a commit object file, decompressed.</p>
<pre><code>commit 238tree 0de83a78334c64250b18b5191f6cbd6b97e77f84
parent 6270c56bec8b3cf7468b5dd94168ac410eca1e98
author Michael G. Schwern <[email protected]> 1659644787 -0700
committer Michael G. Schwern <[email protected]> 1659644787 -0700
feature: I did something cool
</code></pre>
<p>The commit ID is a <strong><a href="https://en.wikipedia.org/wiki/Cryptographic_hash_function" rel="nofollow noreferrer">SHA-1 hash</a></strong> of that.</p>
<pre><code>$ openssl zlib -d < .git/objects/81/2e8c33de3f934cb70dfe711a5354edfd4e8172 | sha1sum
812e8c33de3f934cb70dfe711a5354edfd4e8172 -
</code></pre>
<p>This includes...</p>
<ul>
<li>Full content of the commit, not just the diff, represented as a <a href="https://git-scm.com/book/en/v2/Git-Internals-Git-Objects" rel="nofollow noreferrer">tree object</a> ID.</li>
<li>The ID of the previous commit (or commits if it's a merge).</li>
<li>Commit and author date.</li>
<li>Committer and author's name and email address.</li>
<li>Log message.</li>
</ul>
<p>(The author is who originally wrote the commit, the committer is who made the commit. This is usually the same, but it can be different. For example, when you rebase or amend a commit. Or if you're committing someone else's patch they emailed to you and want to attribute the author.)</p>
<p>Change any of that and the commit ID changes. And yes, the same commit with the same properties will have the same ID on a different machine. This serves three purposes. First, it means the system can tell if a commit has been tampered with. It's baked right into the architecture.</p>
<p>Second, one can rapidly compare commits just by looking at their IDs. This makes Git's network protocols very efficient. Want to compare two commits to see if they're the same? Don't have to send the whole diff, just send the IDs.</p>
<p>Third, and this is the genius, two commits with the same IDs <em>have the same history</em>. That's why the ID of the previous commits are part of the hash. If the content of a commit is the same but the parents are different, the commit ID must be different. That means when comparing repositories (like in a push or pull) once Git finds a commit in common between the two repositories it can stop checking. This makes pushing and pulling extremely efficient. For example...</p>
<pre><code>origin
A - B - C - D - E [master]
A - B [origin/master]
</code></pre>
<p>The network conversation for <code>git fetch origin</code> goes something like this...</p>
<ul>
<li><code>local</code> Hey origin, what branches do you have?</li>
<li><code>origin</code> I have master at E.</li>
<li><code>local</code> I don't have E, I have your master at B.</li>
<li><code>origin</code> B you say? I have B and it's an ancestor of E. That checks out. Let me send you C, D and E.</li>
</ul>
<p>This is also why when you rewrite a commit with rebase, everything after it has to change. Here's an example.</p>
<pre><code>A - B - C - D - E - F - G [master]
</code></pre>
<p>Let's say you rewrite D, just to change the log message a bit. Now D can no longer be D, it has to be copied to a new commit we'll call D1.</p>
<pre><code>A - B - C - D - E - F - G [master]
\
D1
</code></pre>
<p>While D1 can have C as its parent (C is unaffected, commits do not know their children) it is disconnected from E, F and G. If we change E's parent to D1, E can't be E anymore. It has to be copied to a new commit E1.</p>
<pre><code>A - B - C - D - E - F - G [master]
\
D1 - E1
</code></pre>
<p>And so on with F to F1 and G to G1.</p>
<pre><code>A - B - C - D - E - F - G
\
D1 - E1 - F1 - G1 [master]
</code></pre>
<p>They all have the same code, just different parents (or in D1's case, a different commit message).</p> |
32,374,483 | Android DataBinding where to get context? | <p>I have <code>TextView</code> for showing time. I want to use Android's DataBinding plugin.</p>
<p>For formatting time I am using <code>DateUtils.formatDateTime(context, int, int)</code> method which takes <code>Context</code> instance. Is it possible to get context include element? Or do I have to use old school way?</p>
<p>Thanks</p> | 32,385,583 | 4 | 1 | null | 2015-09-03 11:33:25.15 UTC | 3 | 2021-09-01 07:10:49.783 UTC | 2019-05-13 03:25:10.923 UTC | null | 2,219,237 | null | 1,618,316 | null | 1 | 59 | android|data-binding|view|android-context | 23,433 | <p>Thought I should answer instead of putting in a comment. You'll have more options when rc2 is released. In rc1, you can pass the context in a variable to the Binding, then pass it as a parameter to the method. Alternatively, you can create a custom attribute for data binding:</p>
<pre><code>@BindingAdapter({"timeMillis", "dateFlags"})
public static void setDateText(TextView view, int timeMillis, int dateFlags) {
view.setText(DateUtils.formatDateTime(view.getContext(), timeMillis,
dateFlags));
}
</code></pre>
<p>And then use it in your TextView:</p>
<pre><code><TextView ... app:timeMillis="@{timeVar}" app:dateFlags="@{dateFlags}"/>
</code></pre> |
5,698,026 | Is the Service Locator pattern any different from the Abstract Factory pattern? | <p>At first glance, the Service Locator pattern looks the same as the Abstract Factory pattern to me. They both seem to have the same use (you query them to receive instances of abstract services), and they both have been mentioned when I read about Dependency Injection.</p>
<p>However, <a href="http://www.google.com/search?q=service%20locator%20anti-pattern" rel="noreferrer">I have seen the Service Locator pattern described as a poor idea</a>, but have seen <a href="http://docs.castleproject.org/Windsor.Typed-Factory-Facility-interface-based-factories.ashx" rel="noreferrer">direct support for the Abstract Factory pattern in at least one major Dependency Injection framework</a>.</p>
<p>If they aren't the same, what are the differences?</p> | 9,403,827 | 5 | 1 | null | 2011-04-18 02:43:48.903 UTC | 11 | 2021-09-01 01:58:10.39 UTC | 2011-04-18 06:17:10.25 UTC | null | 232,593 | null | 232,593 | null | 1 | 43 | design-patterns|service-locator|abstract-factory | 11,503 | <p>I have stumbled across the same question while investigating these patterns. I think the major differences can be found between a Service Locator and a Factory (whether it is abstract or not):</p>
<h3>Service Locator</h3>
<ul>
<li>'Locates' an <em>existing</em> dependency (the service). Although the service may be created during resolution, it is of no consequence to the Client because:</li>
<li>The Client of the Service Locator <em>does NOT take ownership</em> of the dependency.</li>
</ul>
<h3>Factory</h3>
<ul>
<li><em>Creates a new instance</em> of a dependency.</li>
<li>The Client of the Factory <em>takes ownership</em> of the dependency.</li>
</ul>
<h3>Abstract Factory</h3>
<ul>
<li>Same as a regular Factory except that different deployments may use different implementations of the Abstract Factory allowing different types to be instantiated in those different deployments (you could even change the implementation of the Abstract Factory at runtime but that's not usually how it's used.)</li>
</ul> |
5,801,425 | Enabling SSL with XAMPP | <p>I've been following this guide as much as I could
<a href="http://robsnotebook.com/xampp-ssl-encrypt-passwords" rel="noreferrer">http://robsnotebook.com/xampp-ssl-encrypt-passwords</a> .</p>
<p>However whenever I browse to a page starting with https the apache server replies 404 Object Not Found.</p>
<p>What setting I am missing? Thanks for any help.</p> | 5,821,003 | 7 | 1 | null | 2011-04-27 08:44:59.337 UTC | 56 | 2021-12-04 22:23:24.21 UTC | 2015-12-22 18:13:38.593 UTC | null | 1,531,473 | null | 700,735 | null | 1 | 95 | ssl|https|xampp|http-status-code-404 | 322,997 | <p>Found the answer. In the file <code>xampp\apache\conf\extra\httpd-ssl.conf</code>, under the comment <code>SSL Virtual Host Context</code> pages on port 443 meaning https is looked up under different document root. </p>
<p>Simply change the document root to the same one and problem is fixed.</p> |
6,260,383 | How to get list of changed files since last build in Jenkins/Hudson | <p>I have set up Jenkins, but I would like to find out what files were added/changed between the current build and the previous build. I'd like to run some long running tests depending on whether or not certain parts of the source tree were changed.</p>
<p>Having scoured the Internet I can find no mention of this ability within Hudson/Jenkins though suggestions were made to use SVN post-commit hooks. Maybe it's so simple that everyone (except me) knows how to do it!</p>
<p>Is this possible?</p> | 6,261,180 | 11 | 0 | null | 2011-06-07 03:43:26.727 UTC | 9 | 2019-12-23 22:44:04.107 UTC | 2018-07-21 06:18:45.51 UTC | null | 63,550 | null | 451,079 | null | 1 | 35 | hudson|jenkins | 75,779 | <p>The CI server will show you the list of changes, if you are polling for changes and using SVN update. However, you seem to want to be changing the behaviour of the build depending on which files were modified. I don't think there is any out-of-the-box way to do that with Jenkins alone.</p>
<p>A post-commit hook is a reasonable idea. You could parameterize the job, and have your hook script launch the build with the parameter value set according to the changes committed. I'm not sure how difficult that might be for you.</p>
<p>However, you may want to consider splitting this into two separate jobs - one that runs on every commit, and a separate one for the long-running tests that you don't always need. Personally I prefer to keep job behaviour consistent between executions. Otherwise traceability suffers.</p> |
39,118,528 | RGB to HSL conversion | <p>I'm creating a Color Picker tool and for the HSL slider, I need to be able to convert RGB to HSL. When I searched SO for a way to do the conversion, I found this question <a href="https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion">HSL to RGB color conversion</a>.</p>
<p>While it provides a function to do conversion from RGB to HSL, I see no explanation to what's really going on in the calculation. To understand it better, I've read the <a href="https://en.wikipedia.org/wiki/HSL_and_HSV" rel="noreferrer">HSL and HSV</a> on Wikipedia.</p>
<p>Later, I've rewritten the function from the "HSL to RGB color conversion" using the calculations from the "HSL and HSV" page.</p>
<p>I'm stuck at the calculation of hue if the R is the max value. See the calculation from the "HSL and HSV" page:</p>
<p><a href="https://i.stack.imgur.com/c6FL6.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/c6FL6.jpg" alt="enter image description here"></a></p>
<p>This is from another <a href="https://nl.wikipedia.org/wiki/HSL_(kleurruimte)#Omzetting_van_RGB_naar_HSL" rel="noreferrer">wiki page</a> that's in Dutch:</p>
<p><a href="https://i.stack.imgur.com/VJrSc.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/VJrSc.jpg" alt="enter image description here"></a></p>
<p>and this is from the <a href="https://stackoverflow.com/a/9493060/2202732">answers</a> to "HSL to RGB color conversion":</p>
<pre><code>case r: h = (g - b) / d + (g < b ? 6 : 0); break; // d = max-min = c
</code></pre>
<p>I've tested all three with a few RGB values and they seem to produce similar (if not exact) results. What I'm wondering is are they performing the same thing? Will get I different results for some specific RGB values? Which one should I be using?</p>
<pre><code>hue = (g - b) / c; // dutch wiki
hue = ((g - b) / c) % 6; // eng wiki
hue = (g - b) / c + (g < b ? 6 : 0); // SO answer
</code></pre>
<p></p>
<pre><code>function rgb2hsl(r, g, b) {
// see https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation
// convert r,g,b [0,255] range to [0,1]
r = r / 255,
g = g / 255,
b = b / 255;
// get the min and max of r,g,b
var max = Math.max(r, g, b);
var min = Math.min(r, g, b);
// lightness is the average of the largest and smallest color components
var lum = (max + min) / 2;
var hue;
var sat;
if (max == min) { // no saturation
hue = 0;
sat = 0;
} else {
var c = max - min; // chroma
// saturation is simply the chroma scaled to fill
// the interval [0, 1] for every combination of hue and lightness
sat = c / (1 - Math.abs(2 * lum - 1));
switch(max) {
case r:
// hue = (g - b) / c;
// hue = ((g - b) / c) % 6;
// hue = (g - b) / c + (g < b ? 6 : 0);
break;
case g:
hue = (b - r) / c + 2;
break;
case b:
hue = (r - g) / c + 4;
break;
}
}
hue = Math.round(hue * 60); // °
sat = Math.round(sat * 100); // %
lum = Math.round(lum * 100); // %
return [hue, sat, lum];
}
</code></pre> | 39,147,465 | 4 | 2 | null | 2016-08-24 08:45:25.09 UTC | 20 | 2021-06-27 11:27:24.2 UTC | 2018-02-15 08:40:53.723 UTC | null | 2,202,732 | null | 2,202,732 | null | 1 | 62 | colors|converter|rgb|hsl | 38,180 | <p>I've been reading several wiki pages and checking different calculations, and creating visualizations of RGB cube projection onto a hexagon. And I'd like to post my understanding of this conversion. Since I find this conversion (representations of color models using geometric shapes) interesting, I'll try to be as thorough as I can be. First, let's start with RGB.</p>
<h1>RGB</h1>
<p>Well, this doesn't really need much explanation. In its simplest form, you have 3 values, R, G, and B in the range of [0,255]. For example, <code>51,153,204</code>. We can represent it using a bar graph:</p>
<p><a href="https://i.stack.imgur.com/17UfQ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/17UfQ.jpg" alt="RGB Bar Graph"></a></p>
<h1>RGB Cube</h1>
<p>We can also represent a color in a 3D space. We have three values <code>R</code>, <code>G</code>, <code>B</code> that corresponds to <code>X</code>, <code>Y</code>, and <code>Z</code>. All three values are in the <code>[0,255]</code> range, which results in a cube. But before creating the RGB cube, let's work on 2D space first. Two combinations of R,G,B gives us: RG, RB, GB. If we were to graph these on a plane, we'd get the following:</p>
<p><a href="https://i.stack.imgur.com/xwfS7.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/xwfS7.jpg" alt="RGB 2D Graphs"></a></p>
<p>These are the first three sides of the RGB cube. If we place them on a 3D space, it results in a half cube:</p>
<p><a href="https://i.stack.imgur.com/nw2lB.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/nw2lB.jpg" alt="RGB Cube Sides"></a></p>
<p>If you check the above graph, by mixing two colors, we get a new color at (255,255), and these are Yellow, Magenta, and Cyan. Again, two combinations of these gives us: YM, YC, and MC. These are the missing sides of the cube. Once we add them, we get a complete cube:</p>
<p><a href="https://i.stack.imgur.com/qY93q.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/qY93q.jpg" alt="RGB Cube"></a></p>
<p>And the position of <code>51,153,204</code> in this cube:</p>
<p><a href="https://i.stack.imgur.com/Dh397.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Dh397.jpg" alt="RGB Cube Color Position"></a></p>
<h1>Projection of RGB Cube onto a hexagon</h1>
<p>Now that we have the RGB Cube, let's project it onto a hexagon. First, we tilt the cube by 45° on the <code>x</code>, and then 35.264° on the <code>y</code>. After the second tilt, black corner is at the bottom and the white corner is at the top, and they both pass through the <code>z</code> axis.</p>
<p><a href="https://i.stack.imgur.com/6UMZW.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/6UMZW.jpg" alt="RGB Cube Tilt"></a></p>
<p>As you can see, we get the hexagon look we want with the correct hue order when we look at the cube from the top. But we need to project this onto a real hexagon. What we do is draw a hexagon that is in the same size with the cube top view. All the corners of the hexagon corresponds to the corners of the cube and the colors, and the top corner of the cube that is white, is projected onto the center of the hexagon. Black is omitted. And if we map every color onto the hexagon, we get the look at right.</p>
<p><a href="https://i.stack.imgur.com/YXhqt.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/YXhqt.jpg" alt="Cube to Hexagon Projection"></a></p>
<p>And the position of <code>51,153,204</code> on the hexagon would be:</p>
<p><a href="https://i.stack.imgur.com/PTPwo.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/PTPwo.jpg" alt="Hue Color Position"></a></p>
<h1>Calculating the Hue</h1>
<p>Before we make the calculation, let's define what hue is. </p>
<blockquote>
<p>Hue is roughly the angle of the vector to a point in the projection, with red at 0°.</p>
</blockquote>
<p><sub></p>
<blockquote>
<p>... hue is how far around that hexagon’s edge the point lies.</p>
</blockquote>
<p>This is the calculation from the <a href="https://en.wikipedia.org/wiki/HSL_and_HSV#Hue_and_chroma" rel="noreferrer">HSL and HSV</a> wiki page. We'll be using it in this explanation.</p>
<p><a href="https://i.stack.imgur.com/c6FL6.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/c6FL6.jpg" alt="Wiki calc"></a></p>
<p>Examine the hexagon and the position of <code>51,153,204</code> on it.</p>
<p><a href="https://i.stack.imgur.com/L1pbe.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/L1pbe.jpg" alt="Hexagon basics"></a></p>
<p>First, we scale the R, G, B values to fill the [0,1] interval.</p>
<pre><code>R = R / 255 R = 51 / 255 = 0.2
G = G / 255 G = 153 / 255 = 0.6
B = B / 255 B = 204 / 255 = 0.8
</code></pre>
<p>Next, find the <code>max</code> and <code>min</code> values of <code>R, G, B</code></p>
<pre><code>M = max(R, G, B) M = max(0.2, 0.6, 0.8) = 0.8
m = min(R, G, B) m = min(0.2, 0.6, 0.8) = 0.2
</code></pre>
<p>Then, calculate <code>C</code> (chroma). Chroma is defined as:</p>
<blockquote>
<p>... chroma is roughly the distance of the point from the origin.</p>
</blockquote>
<p></sub></p>
<blockquote>
<p>Chroma is the relative size of the hexagon passing through a point ...</p>
</blockquote>
<pre><code>C = OP / OP'
C = M - m
C = 0.8- 0.2 = 0.6
</code></pre>
<p>Now, we have the <code>R</code>, <code>G</code>, <code>B</code>, and <code>C</code> values. If we check the conditions, <code>if M = B</code> returns true for <code>51,153,204</code>. So, we'll be using <code>H'= (R - G) / C + 4</code>. </p>
<p>Let's check the hexagon again. <code>(R - G) / C</code> gives us the length of <code>BP</code> segment.</p>
<pre><code>segment = (R - G) / C = (0.2 - 0.6) / 0.6 = -0.6666666666666666
</code></pre>
<p>We'll place this segment on the inner hexagon. Starting point of the hexagon is R (red) at 0°. If the segment length is positive, it should be on <code>RY</code>, if negative, it should be on <code>RM</code>. In this case, it is negative <code>-0.6666666666666666</code>, and is on the <code>RM</code> edge.</p>
<p><a href="https://i.stack.imgur.com/v8edM.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/v8edM.jpg" alt="Segment position & shift"></a></p>
<p>Next, we need to shift the position of the segment, or rather <code>P₁</code> towars the <code>B</code> (because <code>M = B</code>). Blue is at <code>240°</code>. Hexagon has 6 sides. Each side corresponds to <code>60°</code>. <code>240 / 60 = 4</code>. We need to shift (increment) the <code>P₁</code> by <code>4</code> (which is 240°). After the shift, <code>P₁</code> will be at <code>P</code> and we'll get the length of <code>RYGCP</code>.</p>
<pre><code>segment = (R - G) / C = (0.2 - 0.6) / 0.6 = -0.6666666666666666
RYGCP = segment + 4 = 3.3333333333333335
</code></pre>
<p>Circumference of the hexagon is <code>6</code> which corresponds to <code>360°</code>. <code>53,151,204</code>'s distance to <code>0°</code> is <code>3.3333333333333335</code>. If we multiply <code>3.3333333333333335</code> by <code>60</code>, we'll get its position in degrees.</p>
<pre><code>H' = 3.3333333333333335
H = H' * 60 = 200°
</code></pre>
<hr>
<p>In the case of <code>if M = R</code>, since we place one end of the segment at R (0°), we don't need to shift the segment to R if the segment length is positive. The position of <code>P₁</code> will be positive. But if the segment length is negative, we need to shift it by 6, because negative value means that the angular position is greater than 180° and we need to do a full rotation.</p>
<p>So, neither the Dutch wiki solution <code>hue = (g - b) / c;</code> nor the Eng wiki solution <code>hue = ((g - b) / c) % 6;</code> will work for negative segment length. Only the SO answer <code>hue = (g - b) / c + (g < b ? 6 : 0);</code> works for both negative and positive values.</p>
<p><a href="https://jsfiddle.net/f15dbw06/" rel="noreferrer">JSFiddle: Test all three methods for rgb(255,71,99)</a></p>
<hr>
<p><a href="https://jsfiddle.net/akinuri/2sywwz0g/" rel="noreferrer">JSFiddle: Find a color's position in RGB Cube and hue hexagon visually</a></p>
<p><strong>Working hue calculation:</strong></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-js lang-js prettyprint-override"><code>console.log(rgb2hue(51,153,204));
console.log(rgb2hue(255,71,99));
console.log(rgb2hue(255,0,0));
console.log(rgb2hue(255,128,0));
console.log(rgb2hue(124,252,0));
function rgb2hue(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
var max = Math.max(r, g, b);
var min = Math.min(r, g, b);
var c = max - min;
var hue;
if (c == 0) {
hue = 0;
} else {
switch(max) {
case r:
var segment = (g - b) / c;
var shift = 0 / 60; // R° / (360° / hex sides)
if (segment < 0) { // hue > 180, full rotation
shift = 360 / 60; // R° / (360° / hex sides)
}
hue = segment + shift;
break;
case g:
var segment = (b - r) / c;
var shift = 120 / 60; // G° / (360° / hex sides)
hue = segment + shift;
break;
case b:
var segment = (r - g) / c;
var shift = 240 / 60; // B° / (360° / hex sides)
hue = segment + shift;
break;
}
}
return hue * 60; // hue is in [0,6], scale it up
}</code></pre>
</div>
</div>
</p> |
44,025,050 | check if clob contains string oracle | <p>currently i have query with this code <code>to_char(CLOB_COLUM) like %s</code> but the following wont work for very big clob. Is there another solution to check if this column contains some string. Using oracle 11.2.0.4.0</p> | 44,025,121 | 3 | 0 | null | 2017-05-17 12:35:10.13 UTC | 3 | 2019-01-16 15:21:42.02 UTC | null | null | null | null | 6,170,711 | null | 1 | 17 | sql|oracle|clob | 46,832 | <p>You can use <a href="https://docs.oracle.com/cd/A91202_01/901_doc/appdev.901/a89852/dbms_17b.htm" rel="noreferrer"><code>DBMS_LOB.INSTR( clob_value, pattern [, offset [, occurrence]] )</code></a>:</p>
<pre><code>SELECT *
FROM your_table
WHERE DBMS_LOB.INSTR( clob_column, 'string to match' ) > 0;
</code></pre>
<p>or</p>
<pre><code>SELECT *
FROM your_table
WHERE clob_column LIKE '%string to match%';
</code></pre> |
44,136,118 | .NET Core vs ASP.NET Core | <p>What exactly is the difference between .NET Core and ASP.NET Core?</p>
<p>Are they mutually exclusive? I heard ASP.NET Core is built on .NET Core, but it can also be built on the full .NET framework.</p>
<p>So what exactly is ASP.NET Core?</p> | 44,136,528 | 5 | 1 | null | 2017-05-23 13:22:51.843 UTC | 67 | 2022-08-30 00:14:51.957 UTC | 2020-02-26 21:24:47.88 UTC | null | 63,550 | null | 3,594,365 | null | 1 | 273 | asp.net-core|.net-core | 143,426 | <p><strong>Update 2020</strong>: Do note that ASP.NET Core 3 and higher now depend on .NET Core and can no longer be used on .NET Framework. The below description is for ASP.NET Core 1.x-2.x; the layer separation still holds true for ASP.NET Core 3.0 but the ASP.NET Core layer can no longer be used on top of .NET Framework in 3.0+.</p>
<p>.NET Core is a runtime. It can execute applications that are built for it.</p>
<p>ASP.NET Core is a collection of libraries that form a Framework for building web applications.
ASP.NET Core libraries can be used on both .NET Core and the "Full .NET Framework" (which has shipped with windows for many years).</p>
<p>The confusing part is that an application using the libraries and tools of ASP.NET Core is usually referred to as "ASP.NET Core Application", which in theory doesn't say if it is built for .NET Core or .NET Framework. So an "ASP.NET Core Application" is <strong>also</strong> a ".NET Core Application" or a ".NET Framework Application".</p>
<p>This image shows the relation of the involved technologies (taken from <a href="https://www.hanselman.com/blog/ASPNET5IsDeadIntroducingASPNETCore10AndNETCore10.aspx" rel="noreferrer">this blog post</a>)
<a href="https://i.stack.imgur.com/3amI1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3amI1.png" alt=".NET Web Application Technologies"></a></p>
<p>Here you can see that ASP.NET Core is built "on top of" both .NET Framework and .NET Core, while "ASP.NET" (now often referred to as "classic ASP.NET") is .NET Framework only.</p> |
5,490,139 | Getting UndeclaredThrowableException instead of my own exception | <p>I have the following code </p>
<pre><code>public Object handlePermission(ProceedingJoinPoint joinPoint, RequirePermission permission) throws AccessException, Throwable {
System.out.println("Permission = " + permission.value());
if (user.hasPermission(permission.value())) {
System.out.println("Permission granted ");
return joinPoint.proceed();
} else {
System.out.println("No Permission");
throw new AccessException("Current user does not have required permission");
}
}
</code></pre>
<p>When I use a user that does not have permissions, I get <code>java.lang.reflect.UndeclaredThrowableException</code> instead of <code>AccessException</code>. </p> | 5,490,372 | 1 | 1 | null | 2011-03-30 17:53:15.533 UTC | 16 | 2020-07-31 17:55:56.393 UTC | 2020-07-31 17:55:56.393 UTC | null | 746,843 | null | 373,201 | null | 1 | 64 | java|aop|aspect | 80,765 | <p><code>AccessException</code> is a checked exception, but it was thrown from the method that doesn't declare it in its <code>throws</code> clause (actually - from the aspect intercepting that method). It's an abnormal condition in Java, so your exception is wrapped with <code>UndeclaredThrowableException</code>, which is unchecked.</p>
<p>To get your exception as is, you can either declare it in the <code>throws</code> clause of the method being intercepted by your aspect, or use another unchecked exception (i.e. a subclass of <code>RuntimeException</code>) instead of <code>AccessException</code>.</p> |
51,368,343 | [Angular-CLI-6]Could not determine single project for 'Serve' target | <p>I have updated my angular-cli with the help of <code>ng update @angular/cli</code> command. After that, I have got an error as <code>Could not determine single project for 'server' target</code> with following error trace.</p>
<pre><code>Could not determine a single project for the 'serve' target.
Error: Could not determine a single project for the 'serve' target.
at ServeCommand.getProjectNamesByTarget (E:\Angular\Projects\projectName\node_modules\@angular\cli\models\architect-command.js:175:19)
at ServeCommand.<anonymous> (E:\Angular\Projects\projectName\node_modules\@angular\cli\models\architect-command.js:128:51)
at Generator.next (<anonymous>)
at E:\Angular\Projects\projectName\node_modules\@angular\cli\models\architect-command.js:7:71
at new Promise (<anonymous>)
at __awaiter (E:\Angular\Projects\projectName\node_modules\@angular\cli\models\architect-command.js:3:12)
at ServeCommand.runArchitectTarget (E:\Angular\Projects\projectName\node_modules\@angular\cli\models\architect-command.js:121:16)
at ServeCommand.<anonymous> (E:\Angular\Projects\projectName\node_modules\@angular\cli\commands\serve.js:34:25)
at Generator.next (<anonymous>)
at E:\Angular\Projects\projectName\node_modules\@angular\cli\commands\serve.js:7:71
</code></pre>
<p>This behaviour is quite confusing me.
For more information i am also adding my <code>package.json</code> here.</p>
<pre><code>{
"name": "ProjectName",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^5.2.0",
"@angular/common": "^5.2.0",
"@angular/compiler": "^5.2.0",
"@angular/core": "^5.2.0",
"@angular/forms": "^5.2.0",
"@angular/http": "^5.2.0",
"@angular/platform-browser": "^5.2.0",
"@angular/platform-browser-dynamic": "^5.2.0",
"@angular/router": "^5.2.0",
"core-js": "^2.4.1",
"rxjs": "^5.5.6",
"zone.js": "^0.8.19"
},
"devDependencies": {
"@angular/cli": "~6.0.8",
"@angular/compiler-cli": "^5.2.0",
"@angular/language-service": "^5.2.0",
"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"codelyzer": "^4.0.1",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~2.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~4.1.0",
"tslint": "~5.9.1",
"typescript": "~2.5.3",
"@angular-devkit/build-angular": "~0.6.8"
}
}
</code></pre>
<p>Here, I am getting why this error is occur. Can anyone help me to resolve it?</p> | 51,368,990 | 2 | 3 | null | 2018-07-16 18:47:49.643 UTC | 5 | 2018-11-04 08:57:38.363 UTC | 2018-07-17 12:56:52.893 UTC | null | 114,900 | null | 7,560,986 | null | 1 | 13 | angular|angular5|angular-cli|angular6|angular-cli-v6 | 39,192 | <p>Did you follow all three steps of the update process?</p>
<p>The update generally follows 3 steps, and will take advantage of the new ng update tool. </p>
<p>1) Update @angular/cli:</p>
<pre><code>npm install -g @angular/cli
npm install @angular/cli
ng update @angular/cli
</code></pre>
<p>2) Update your Angular framework packages: </p>
<pre><code>ng update @angular/core
</code></pre>
<p>3) Update other dependencies</p>
<p>See toward the bottom of this post for more information: <a href="https://blog.angular.io/version-6-of-angular-now-available-cc56b0efa7a4" rel="noreferrer">https://blog.angular.io/version-6-of-angular-now-available-cc56b0efa7a4</a></p>
<p>See also this link for the set of steps: <a href="https://update.angular.io/" rel="noreferrer">https://update.angular.io/</a></p> |
9,075,030 | Shared preferences inside broadcastreceiver | <p>In my app,i want to use Shared Preferences inside a broadcast receiver...But i cant access the getPreferences() method inside...</p>
<pre><code> SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
</code></pre>
<p>I cant call with the context object...any other method???</p> | 9,075,093 | 1 | 0 | null | 2012-01-31 05:49:41.807 UTC | 7 | 2012-07-25 05:23:23.973 UTC | null | null | null | null | 986,525 | null | 1 | 48 | android|broadcastreceiver|sharedpreferences | 27,954 | <p>You can use Context from <code>onReceive(Context arg0, Intent arg1)</code> of BroadReceiver.</p>
<pre><code>@Override
public void onReceive(Context arg0, Intent arg1) {
SharedPreferences prefs = arg0.getSharedPreferences("myPrefs",
Context.MODE_PRIVATE);
}
</code></pre> |
52,397,708 | How to pass variable from beforeEach hook to tests in jest? | <pre><code>beforeEach(async () => {
const sandbox = sinon.sandbox.create()
...
})
test('/add', () => {
// how can I use sandbox here?
})
</code></pre>
<p>What I need is something like <code>t.context</code> in ava</p> | 52,409,186 | 1 | 2 | null | 2018-09-19 03:45:17.56 UTC | 4 | 2018-11-05 14:37:00.433 UTC | 2018-11-05 14:37:00.433 UTC | null | 2,071,697 | null | 325,241 | null | 1 | 80 | jestjs | 33,485 | <p>Just declare sandbox so it is available in the scope of beforeEach and test:</p>
<pre class="lang-js prettyprint-override"><code>let sandbox;
beforeEach(async () => {
sandbox = sinon.sandbox.create()
...
})
test('/add', () => {
// sandbox available for use
})
</code></pre> |
30,912,663 | Sort a string alphabetically using a function | <p>Imagine you were given a string and you had to sort that string alphabetically using a function. Example:</p>
<pre><code>sortAlphabets( 'drpoklj' ); //=> returns 'djklopr'
</code></pre>
<p>What would be the best way to do this?</p> | 30,912,718 | 3 | 1 | null | 2015-06-18 10:19:10.917 UTC | 10 | 2020-11-09 21:13:20.433 UTC | null | null | null | null | 4,357,947 | null | 1 | 56 | javascript|sorting | 100,057 | <p>You can use array <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort" rel="noreferrer"><code>sort</code></a> function:</p>
<pre><code>var sortAlphabets = function(text) {
return text.split('').sort().join('');
};
</code></pre>
<p><strong>STEPS</strong></p>
<ol>
<li>Convert <code>string</code> to <code>array</code></li>
<li>Sort <code>array</code></li>
<li>Convert back <code>array</code> to <code>string</code></li>
</ol>
<p><a href="http://jsfiddle.net/tusharj/pwzjd846/1/" rel="noreferrer"><strong>Demo</strong></a></p> |
22,483,877 | set value of input field by php variable's value | <p>I have a simple php calculator which code is:</p>
<pre><code><html>
<head>
<title>PHP calculator</title>
</head>
<body bgcolor="orange">
<h1 align="center">This is PHP Calculator</h1>
<center>
<form method="post" action="phptest.php">
Type Value 1:<br><input type="text" name="value1"><br>
Type value 2:<br><input type="text" name="value2"><br>
Operator:<br><input type="text" name="sign"><br>
Result:<br><input type"text" name="result">
<div align="center">
<input type="submit" name="submit" value="Submit">
</div>
</form>
</center>
<?php
if(isset($_POST['submit'])){
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
if($value1=='') {
echo "<script>alert('Please Enter Value 1')</script>";
exit();
}
if($value2=='') {
echo "<script>alert('Please Enter Value 2')</script>";
exit();
}
if($sign=='+') {
echo "Your answer is: " , $value1+$value2;
exit();
}
if($sign=='-') {
echo "Your answer is: " , $value1-$value2;
exit();
}
if($sign=='*') {
echo "Your answer is: " , $value1*$value2;
exit();
}
if($sign=='/') {
echo "Your answer is: " , $value1/$value2;
exit();
}
}
?>
</code></pre>
<p>All I want to do is that answer should be displayed in the result input field instead of echoing them separately. Please help? I Know it's simple but I am new in PHP.</p> | 22,484,100 | 3 | 1 | null | 2014-03-18 15:30:24.453 UTC | 1 | 2022-02-08 07:16:50.84 UTC | 2017-06-02 12:13:21.71 UTC | null | 5,076,266 | null | 2,344,353 | null | 1 | 6 | php|html|variables | 127,937 | <p>One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <code><input></code> tag.<br />
Try this - </p>
<pre><code><?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
</code></pre> |
58,139,759 | How to use class fields with System.Text.Json.JsonSerializer? | <p>I recently upgraded a solution to be all .NET Core 3 and I have a class that requires the class variables to be fields. This is a problem since the new <code>System.Text.Json.JsonSerializer</code> doesn't support serializing nor deserializing fields but only handles properties instead.</p>
<p>Is there any way to ensure that the two final classes in the example below have the same exact values?</p>
<pre><code>using System.Text.Json;
public class Car
{
public int Year { get; set; } // does serialize correctly
public string Model; // doesn't serialize correctly
}
static void Problem() {
Car car = new Car()
{
Model = "Fit",
Year = 2008,
};
string json = JsonSerializer.Serialize(car); // {"Year":2008}
Car carDeserialized = JsonSerializer.Deserialize<Car>(json);
Console.WriteLine(carDeserialized.Model); // null!
}
</code></pre> | 58,139,922 | 2 | 0 | null | 2019-09-27 18:25:58.873 UTC | 2 | 2021-08-03 02:41:53.4 UTC | 2019-11-25 23:24:48.88 UTC | null | 3,744,182 | null | 3,887,945 | null | 1 | 33 | c#|json.net|.net-core-3.0|system.text.json | 11,729 | <p>In <strong>.NET Core 3.x</strong>, System.Text.Json does not serialize fields. From the <a href="https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-core-3-1#include-fields" rel="noreferrer">docs</a>:</p>
<blockquote>
<p>Fields are not supported in System.Text.Json in .NET Core 3.1. Custom converters can provide this functionality.</p>
</blockquote>
<p>In <strong>.NET 5</strong> and later, public fields can be serialized by setting <a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializeroptions.includefields?view=net-5.0" rel="noreferrer"><code>JsonSerializerOptions.IncludeFields</code></a> to <code>true</code> or by marking the field to serialize with <a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonincludeattribute?view=net-5.0" rel="noreferrer"><code>[JsonInclude]</code></a>:</p>
<pre class="lang-cs prettyprint-override"><code>using System.Text.Json;
static void Main()
{
var car = new Car { Model = "Fit", Year = 2008 };
// Enable support
var options = new JsonSerializerOptions { IncludeFields = true };
// Pass "options"
var json = JsonSerializer.Serialize(car, options);
// Pass "options"
var carDeserialized = JsonSerializer.Deserialize<Car>(json, options);
Console.WriteLine(carDeserialized.Model); // Writes "Fit"
}
public class Car
{
public int Year { get; set; }
public string Model;
}
</code></pre>
<p>For details see:</p>
<ul>
<li><p><a href="https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0#include-fields" rel="noreferrer">How to serialize and deserialize (marshal and unmarshal) JSON in .NET: Include fields</a>.</p>
</li>
<li><p>Issues <a href="https://github.com/dotnet/runtime/issues/34558" rel="noreferrer">#34558</a> and <a href="https://github.com/dotnet/runtime/issues/876" rel="noreferrer">#876</a>.</p>
</li>
</ul> |
7,104,474 | How does Asynchronous Javascript Execution happen? and when not to use return statement? | <pre><code>// synchronous Javascript
var result = db.get('select * from table1');
console.log('I am syncronous');
// asynchronous Javascript
db.get('select * from table1', function(result){
// do something with the result
});
console.log('I am asynchronous')
</code></pre>
<p>I know in synchronous code, console.log() executes after result is fetched from db, whereas in asynchronous code console.log() executes before the db.get() fetches the result.</p>
<p>Now my question is, how does the execution happen behind the scenes for asynchronous code and why is it non-blocking?</p>
<p>I have searched the Ecmascript 5 standard to understand how asynchronous code works but could not find the word asynchronous in the entire standard.</p>
<p>And from nodebeginner.org I also found out that we should not use a return statement as it blocks the event loop. But nodejs api and third party modules contain return statements everywhere. So when should a return statement be used and when shouldn't it?</p>
<p>Can somebody throw some light on this?</p> | 7,104,633 | 2 | 1 | null | 2011-08-18 08:27:46.147 UTC | 18 | 2019-02-17 11:38:54.477 UTC | 2013-01-05 19:39:11.19 UTC | null | 825,789 | null | 900,097 | null | 1 | 37 | javascript|function|asynchronous|return|execution | 20,862 | <p>First of all, passing a function as a parameter is telling the function that you're calling that you would like it to call this function some time in the future. When exactly in the future it will get called depends upon the nature of what the function is doing.</p>
<p>If the function is doing some networking and the function is configured to be non-blocking or asychronous, then the function will execute, the networking operation will be started and the function you called will return right away and the rest of your inline javascript code after that function will execute. If you return a value from that function, it will return right away, long before the function you passed as a parameter has been called (the networking operation has not yet completed).</p>
<p>Meanwhile, the networking operation is going in the background. It's sending the request, listening for the response, then gathering the response. When the networking request has completed and the response has been collected, THEN and only then does the original function you called call the function you passed as a parameter. This may be only a few milliseconds later or it may be as long as minutes later - depending upon how long the networking operation took to complete.</p>
<p>What's important to understand is that in your example, the <code>db.get()</code> function call has long since completed and the code sequentially after it has also executed. What has not completed is the internal anonymous function that you passed as a parameter to that function. That's being held in a javascript function closure until later when the networking function finishes.</p>
<p>It's my opinion that one thing that confuses a lot of people is that the anonymous function is declared inside of your call to db.get and appears to be part of that and appears that when <code>db.get()</code> is done, this would be done too, but that is not the case. Perhaps that would look less like that if it was represented this way:</p>
<pre><code>function getCompletionfunction(result) {
// do something with the result of db.get
}
// asynchronous Javascript
db.get('select * from table1', getCompletionFunction);
</code></pre>
<p>Then, maybe it would be more obvious that the db.get will return immediately and the getCompletionFunction will get called some time in the future. I'm not suggesting you write it this way, but just showing this form as a means of illustrating what is really happening.</p>
<p>Here's a sequence worth understanding:</p>
<pre><code>console.log("a");
db.get('select * from table1', function(result){
console.log("b");
});
console.log("c");
</code></pre>
<p>What you would see in the debugger console is this:</p>
<pre><code>a
c
b
</code></pre>
<p>"a" happens first. Then, db.get() starts its operation and then immediately returns. Thus, "c" happens next. Then, when the db.get() operation actually completes some time in the future, "b" happens.</p>
<hr>
<p>For some reading on how async handling works in a browser, see <a href="https://stackoverflow.com/questions/7575589/how-does-javascript-handle-ajax-responses-in-the-background/7575649#7575649">How does JavaScript handle AJAX responses in the background?</a></p> |
7,086,220 | What does "rep; nop;" mean in x86 assembly? Is it the same as the "pause" instruction? | <ul>
<li>What does <code>rep; nop</code> mean?</li>
<li>Is it the same as <code>pause</code> instruction?</li>
<li>Is it the same as <code>rep nop</code> (without the semi-colon)?</li>
<li>What's the difference to the simple <code>nop</code> instruction?</li>
<li>Does it behave differently on AMD and Intel processors?</li>
<li>(bonus) Where is the official documentation for these instructions?</li>
</ul>
<hr>
<h3>Motivation for this question</h3>
<p>After some discussion in the comments of <a href="https://stackoverflow.com/questions/7083482/how-to-prevent-compiler-optimization-on-a-small-piece-of-code">another question</a>, I realized that I don't know what <code>rep; nop;</code> means in x86 (or x86-64) assembly. And also I couldn't find a good explanation on the web.</p>
<p>I know that <code>rep</code> is a prefix that means <em>"repeat the next instruction <code>cx</code> times"</em> (or at least it was, in old 16-bit x86 assembly). According to this <a href="http://en.wikipedia.org/wiki/X86_instruction_listings#Original_8086.2F8088_instructions" rel="noreferrer">summary table at Wikipedia</a>, it seems <code>rep</code> can only be used with <code>movs</code>, <code>stos</code>, <code>cmps</code>, <code>lods</code>, <code>scas</code> (but maybe this limitation was removed on newer processors). Thus, I would think <code>rep nop</code> (without semi-colon) would repeat a <code>nop</code> operation <code>cx</code> times.</p>
<p>However, after further searching, I got even more confused. It seems that <code>rep; nop</code> and <code>pause</code> <a href="https://stackoverflow.com/questions/2589447/is-it-necessary-that-each-machine-code-can-only-map-to-one-assembly-code/2589462#2589462">map to the exactly same opcode</a>, and <code>pause</code> has a bit different behavior than just <code>nop</code>. Some <a href="http://www.x86-64.org/pipermail/discuss/2005-March/005800.html" rel="noreferrer">old mail from 2005</a> said different things:</p>
<ul>
<li><em>"try not to burn too much power"</em></li>
<li><em>"it is equivalent to 'nop' just with 2 byte encoding."</em></li>
<li><em>"it is magic on intel. Its like 'nop but let the other HT sibling run'"</em></li>
<li><em>"it is pause on intel and fast padding on Athlon"</em></li>
</ul>
<p>With these different opinions, I couldn't understand the correct meaning.</p>
<p>It's being used in Linux kernel (on both <a href="http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/arch/um/sys-i386/asm/processor.h#L53" rel="noreferrer">i386</a> and <a href="http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/arch/um/sys-x86_64/asm/processor.h#L20" rel="noreferrer">x86_64</a>), together with this comment: <code>/* REP NOP (PAUSE) is a good thing to insert into busy-wait loops. */</code> It is also <a href="http://doc.bertos.org/2.6/attr_8h_source.html#l00096" rel="noreferrer">being used in BeRTOS</a>, with the same comment.</p> | 7,086,289 | 2 | 1 | null | 2011-08-16 23:12:25.11 UTC | 28 | 2019-10-27 05:44:11.66 UTC | 2019-10-27 05:44:11.66 UTC | null | 224,132 | null | 124,946 | null | 1 | 94 | assembly|x86|x86-64|cpu|machine-code | 28,268 | <p><code>rep; nop</code> is indeed the same as the <code>pause</code> instruction (opcode <code>F390</code>). It might be used for assemblers which don't support the <code>pause</code> instruction yet. On previous processors, this simply did nothing, just like <code>nop</code> but in two bytes. On new processors which support hyperthreading, it is used as a hint to the processor that you are executing a spinloop to increase performance. From <a href="https://software.intel.com/en-us/download/intel-64-and-ia-32-architectures-software-developers-manual-volume-2b-instruction-set-reference-m-u" rel="noreferrer">Intel's instruction reference</a>:</p>
<blockquote>
<p>Improves the performance of spin-wait loops. When executing a “spin-wait loop,” a Pentium 4 or Intel Xeon processor suffers a severe performance penalty when exiting the loop because it detects a possible memory order violation. The PAUSE instruction provides a hint to the processor that the code sequence is a spin-wait loop. The processor uses this hint to avoid the memory order violation in most situations, which greatly improves processor performance. For this reason, it is recommended that a PAUSE instruction be placed in all spin-wait loops.</p>
</blockquote> |
23,108,728 | Linux .NET remote debugging from Visual Studio | <p>I would like to remote debug a C# console application running on Linux from Visual Studio. Here's what I found so far:</p>
<p><a href="http://www.mono-project.com/Debugger" rel="noreferrer">http://www.mono-project.com/Debugger</a></p>
<blockquote>
<p>The Mono runtime implements a debugging interface that allows
debuggers and IDEs to debug managed code. This is called the Soft
Debugger and is supported by both MonoDevelop, Xamarin Studio and
Visual Studio (when the appropriate plugins are installed) as well as
the command line SDB client.</p>
<p>Mono provides an API to communicate with the debugger and create your
own debugging UIs via the Mono.Debugger.Soft.dll assembly.</p>
</blockquote>
<p>The page below discusses some issues of the current MonoVS debugger implementation, but they are all fine with me.</p>
<p><a href="http://mono-project.com/Visual_Studio_Integration" rel="noreferrer">http://mono-project.com/Visual_Studio_Integration</a></p>
<p>The page also links to the Getting started guide for MonoVS:</p>
<p><a href="http://mono-project.com/GettingStartedWithMonoVS" rel="noreferrer">http://mono-project.com/GettingStartedWithMonoVS</a></p>
<p>Which contains a download link for MonoTools:</p>
<p><a href="http://mono-tools.com/download/" rel="noreferrer">http://mono-tools.com/download/</a></p>
<p>However, the download link now redirects to:</p>
<p><a href="http://xamarin.com/download/" rel="noreferrer">http://xamarin.com/download/</a></p>
<p>Where I'm offered to download Xamarin Studio Starter Edition. Clicking the Pricing link I see that I need at least the Business edition for Visual Studio Support, at $999 per year. Well, no thank you.</p>
<p>This is where I'm stuck. Some specifics of my environment:</p>
<p>Development environment:</p>
<ul>
<li>Windows 7 64-bit</li>
<li>Visual Studio Pro 2013 (might use 2010 if that works better)</li>
</ul>
<p>Target environment:</p>
<ul>
<li>Raspberry Pi</li>
<li>Raspbian Wheezy</li>
<li>Mono 3.2.8</li>
<li>Running console application over SSH</li>
</ul> | 61,640,777 | 6 | 1 | null | 2014-04-16 11:55:38.87 UTC | 11 | 2021-09-20 12:24:47.703 UTC | 2020-05-11 06:16:38.37 UTC | null | 306,074 | null | 306,074 | null | 1 | 33 | visual-studio|mono|raspberry-pi|remote-debugging|raspbian | 18,155 | <p>I have finally found a good way to perform remote debugging of C# code running on my <a href="https://en.wikipedia.org/wiki/Raspberry_Pi" rel="nofollow noreferrer">Raspberry Pi</a>. I have switched from <a href="https://en.wikipedia.org/wiki/Mono_%28software%29" rel="nofollow noreferrer">Mono</a> to .NET Core and can now use Visual Studio to debug code running on the Raspberry Pi almost as easy as when running on my development machine.</p>
<p>The following steps were tested using Windows 10 version 1909, Visual Studio 2019 version 16.4.3, Raspbian Buster Lite version 2020-02-13 and a Raspberry Pi 2 Model B. .NET Core requires an ARMv7 CPU, so it will not run on Raspberry Pi 1 and Zero.</p>
<ol>
<li><p>Go to <a href="https://dotnet.microsoft.com/download/dotnet-core" rel="nofollow noreferrer">https://dotnet.microsoft.com/download/dotnet-core</a> and select .NET Core 3.1 (or later). Click the link for Linux ARM32 runtime binaries and copy the direct link displayed on the next page. (Do not right-click the ARM32 link and select copy link address, as you will end up with a webpage if you download that link.)</p>
<p><a href="https://i.stack.imgur.com/9iLjo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9iLjo.png" alt=".NET Core download website" /></a></p>
</li>
<li><p>Open a SSH session to the Raspberry Pi, download and install the binaries:</p>
<pre class="lang-none prettyprint-override"><code>ssh [email protected]
wget https://download.visualstudio.microsoft.com/download/pr/c11e9248-404f-4e5b-bd99-175079419d6f/83902a43e06f9fb4e45a4c6a6d5afc0b/dotnet-runtime-3.1.3-linux-arm.tar.gz
sudo mkdir /opt/dotnet
sudo tar zxf dotnet-runtime-3.1.3-linux-arm.tar.gz -C /opt/dotnet
sudo ln -s /opt/dotnet/dotnet /usr/bin/dotnet
</code></pre>
</li>
<li><p>Add the following line to <code>~/.bashrc</code>, logout and login again to activate:</p>
<pre class="lang-none prettyprint-override"><code>export DOTNET_ROOT=/opt/dotnet
</code></pre>
</li>
<li><p>Check that .NET Core has been installed correctly:</p>
<pre class="lang-none prettyprint-override"><code>dotnet --info
</code></pre>
<p><a href="https://i.stack.imgur.com/qL20p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qL20p.png" alt="Output from dotnet --info" /></a></p>
</li>
<li><p>Create a *.NET Core Console App```lang-none in Visual Studio. Set <em>Target framework = .NET Core 3.1</em> (or the version you downloaded to the Raspberry Pi). Make sure that Project → Properties → Build → Output → Advanced → Debugging information = Portable.</p>
<p><a href="https://i.stack.imgur.com/3xJVD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3xJVD.png" alt="Advanced build settings" /></a></p>
</li>
<li><p>Build the project in Visual Studio and copy all *.dll, *.pdb, *.deps.json and *.runtimeconfig.json files from the development machine to the Pi. <a href="https://www.chiark.greenend.org.uk/%7Esgtatham/putty/latest.html" rel="nofollow noreferrer">PuTTY's pscp command</a> can be used:</p>
<pre class="lang-none prettyprint-override"><code>cd bin\Debug\netcoreapp3.1
pscp -pw <password> *.dll *.pdb *.deps.json *.runtimeconfig.json [email protected]:/home/pi
</code></pre>
</li>
<li><p>Open a SSH session to the Raspberry Pi and run the program, or start it from the development machine using <a href="https://en.wikipedia.org/wiki/Secure_Shell" rel="nofollow noreferrer">SSH</a>:</p>
<pre class="lang-none prettyprint-override"><code>ssh [email protected] dotnet /home/pi/MyProgram.dll
</code></pre>
</li>
<li><p>Attach to the remote process by selecting the Debug → Attach to Process menu item in Visual Studio. Select <em>Connection type</em> = SSH and in the <em>Connection target</em> textbox, type <em>[email protected]</em> and press <kbd>Enter</kbd>.</p>
<p><a href="https://i.stack.imgur.com/4EAtl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4EAtl.png" alt="Connection target" /></a></p>
</li>
<li><p>Enter password and click the <kbd>Connect</kbd> button.</p>
<p><a href="https://i.stack.imgur.com/RMUdo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RMUdo.png" alt="Connect window" /></a></p>
</li>
<li><p>Click the <kbd>Select</kbd> button.</p>
<p><a href="https://i.stack.imgur.com/YnEEI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YnEEI.png" alt="Attach to process image" /></a></p>
</li>
<li><p>Select <em>Managed (.NET Core for Unix)</em> and click the <kbd>OK</kbd> button.</p>
<p><a href="https://i.stack.imgur.com/Tr9lW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tr9lW.png" alt="Select code type" /></a></p>
</li>
<li><p>Select the <code>dotnet MyProgram.dll</code> process and click the <kbd>Attach</kbd> button. The first connection might take several minutes, but subsequent connections are much faster.</p>
</li>
</ol>
<p>Enjoy setting breakpoints, adding watches, stepping through code and even using "Set Next Statement" - almost as fast as when debugging on the local machine. The only thing I'm missing so far is <em>Edit and Continue</em>, but not enough to investigate if it is possible to achieve.</p> |
18,885,513 | Excel Validation Drop Down list using VBA | <p>I have an array of values. I want to show those values in Excel Cell as drop down list using VBA.</p>
<p>Here is my code. It shows "<strong>Type Mismatch Error!</strong>"</p>
<pre><code>Dim xlValidateList(6) As Integer
xlValidateList(1) = 1
xlValidateList(2) = 2
xlValidateList(3) = 3
xlValidateList(4) = 4
xlValidateList(5) = 5
xlValidateList(6) = 6
With Range("A1").Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=ValidationList
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
</code></pre>
<p>The problem occurs in following line...</p>
<pre><code>.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
</code></pre>
<p>Please let me where the problem is... Thanks in advance</p> | 18,885,622 | 5 | 2 | null | 2013-09-19 02:52:04.013 UTC | 8 | 2017-07-19 14:24:39.2 UTC | null | null | null | null | 975,199 | null | 1 | 13 | vba|excel | 145,942 | <p>You are defining your array as <code>xlValidateList()</code>, so when you try to assign the type, it gets confused as to what you are trying to assign to the type.</p>
<p>Instead, try this:</p>
<pre><code>Dim MyList(5) As String
MyList(0) = 1
MyList(1) = 2
MyList(2) = 3
MyList(3) = 4
MyList(4) = 5
MyList(5) = 6
With Range("A1").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:=Join(MyList, ",")
End With
</code></pre> |
18,962,925 | What is the difference between NS_ENUM and NS_OPTIONS? | <p>I preprocessed following code with clang in Xcode5.</p>
<pre><code>typedef NS_ENUM(NSInteger, MyStyle) {
MyStyleDefault,
MyStyleCustom
};
typedef NS_OPTIONS(NSInteger, MyOption) {
MyOption1 = 1 << 0,
MyOption2 = 1 << 1,
};
</code></pre>
<p>And got this.</p>
<pre><code>typedef enum MyStyle : NSInteger MyStyle; enum MyStyle : NSInteger {
MyStyleDefault,
MyStyleCustom
};
typedef enum MyOption : NSInteger MyOption; enum MyOption : NSInteger {
MyOption1 = 1 << 0,
MyOption2 = 1 << 1,
};
</code></pre>
<p>I know NS_OPTIONS is for a bitmask, but is there any technical differences?
Or this is just for naming convention?</p>
<p><strong>EDIT</strong></p>
<p>According to the definition of NS_OPTIONS, it's probably for compiler compatibility.(especially for c++ compiler)</p>
<pre><code>// In CFAvailability.h
// Enums and Options
#if (__cplusplus && __cplusplus >= 201103L && (__has_extension(cxx_strong_enums) || __has_feature(objc_fixed_enum))) || (!__cplusplus && __has_feature(objc_fixed_enum))
#define CF_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#if (__cplusplus)
#define CF_OPTIONS(_type, _name) _type _name; enum : _type
#else
#define CF_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type
#endif
#else
#define CF_ENUM(_type, _name) _type _name; enum
#define CF_OPTIONS(_type, _name) _type _name; enum
#endif
</code></pre>
<p>__cplusplus value in clang is 199711 and I can't test what this is exactly for, though.</p> | 21,384,671 | 4 | 2 | null | 2013-09-23 15:17:23.213 UTC | 21 | 2014-12-08 02:10:14.75 UTC | 2014-07-25 01:15:43.613 UTC | null | 596,219 | null | 376,482 | null | 1 | 32 | ios|objective-c|cocoa | 22,047 | <p>There's a basic difference between an enum and a bitmask (option). You use an enum to list exclusive states. A bitmask is used when several properties can apply at the same time.</p>
<p>In both cases you use integers, but you look at them differently. With an enum you look at the numerical value, with bitmasks you look at the individual bits.</p>
<pre><code>typedef NS_ENUM(NSInteger, MyStyle) {
MyStyleDefault,
MyStyleCustom
};
</code></pre>
<p>Will only represent two states. You can simply check it by testing for equality.</p>
<pre><code>switch (style){
case MyStyleDefault:
// int is 0
break;
case MyStyleCustom:
// int is 1
break;
}
</code></pre>
<p>While the bitmask will represent more states. You check for the individual bits with logic or bitwise operators.</p>
<pre><code>typedef NS_OPTIONS(NSInteger, MyOption) {
MyOption1 = 1 << 0, // bits: 0001
MyOption2 = 1 << 1, // bits: 0010
};
if (option & MyOption1){ // last bit is 1
// bits are 0001 or 0011
}
if (option & MyOption2){ // second to last bit is 1
// bits are 0010 or 0011
}
if ((option & MyOption1) && (option & MyOption2)){ // last two bits are 1
// bits are 0011
}
</code></pre>
<p><strong>tl;dr</strong> An enum gives names to numbers. A bitmask gives names to bits.</p> |
37,721,782 | What are passive event listeners? | <p>While working around to boost performance for progressive web apps, I came across a new feature <code>Passive Event Listeners</code> and I find it hard to understand the concept.</p>
<p>What are <code>Passive Event Listeners</code> and what is the need to have it in our projects?</p> | 37,721,906 | 2 | 1 | null | 2016-06-09 09:21:04.683 UTC | 71 | 2022-04-01 16:00:36.7 UTC | 2019-12-25 00:01:51.48 UTC | null | 3,345,644 | null | 3,758,710 | null | 1 | 289 | javascript|dom-events|event-listener|passive-event-listeners | 162,962 | <blockquote>
<p>Passive event listeners are an emerging web standard, new feature
shipped in Chrome 51 that provide a major potential boost to scroll
performance. <a href="https://blog.chromium.org/2016/05/new-apis-to-help-developers-improve.html" rel="noreferrer">Chrome Release Notes.</a></p>
</blockquote>
<p>It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.</p>
<p><strong>Problem:</strong> All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any <code>touchstart</code> and <code>touchmove</code> handlers, which may prevent the scroll entirely by calling <code>preventDefault()</code> on the event.</p>
<p><strong>Solution: <code>{passive: true}</code></strong></p>
<p>By marking a touch or wheel listener as passive, the developer is promising the handler won't call <code>preventDefault</code> to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.</p>
<pre><code>document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
</code></pre>
<p><a href="https://dom.spec.whatwg.org/#dom-eventlisteneroptions-passive" rel="noreferrer">DOM Spec</a> , <a href="https://www.youtube.com/watch?v=NPM6172J22g" rel="noreferrer">Demo Video</a> , <a href="https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md" rel="noreferrer">Explainer Doc</a></p> |
17,855,846 | Using AJAX in a WordPress plugin | <p>I'm trying to create a WordPress sample plugin based in AJAX. I read a tutorial and did a plugin, but it's not working. I am new to AJAX. Here is the code I tried: </p>
<pre><code><?php
class ajaxtest {
function ajaxcontact() {
?>
<div id="feedback"></div>
<form name="myform" id="myform">
<li>
<label for fname>First Name</label><input type="text" id="fname" name="fname" value=""/>
</li>
<li>
<label for lname>Last Name</label><input type="text" id="lname" name="lname" value=""/>
</li>
<input type="submit" value="Submit" id="submit" name="submit"/>
</form>
<script type="text/javascript">
jQuery('#submit').submit(ajaxSubmit);
function ajaxSubmit() {
var newcontact = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: newcontact,
success: function(data) {
jQuery("#feedback").html(data);
}
});
return false;
}
</script>
<?php
}
function addcontact() {
$fname = $_POST['fname'];
if ($fname != "") {
echo "Your Data is" . $fname;
} else {
echo "Data you Entered is wrong";
}
die();
}
}
function jquery_add_to_contact() {
wp_enqueue_script('jquery'); // Enqueue jQuery that's already built into WordPress
}
add_action('wp_enqueue_scripts', 'jquery_add_to_contact');
add_action('wp_ajax_addcontact', array('ajaxtest', 'addcontact'));
add_action('wp_ajax_nopriv_addcontact', array('ajaxtest', 'addcontact')); // not really needed
add_shortcode('cform', array('ajaxtest', 'ajaxcontact'));
</code></pre>
<p>I used this as a shortcode, but I didn't get an output. What's the mistake?</p> | 18,614,405 | 2 | 1 | null | 2013-07-25 10:45:02.36 UTC | 11 | 2019-03-01 15:39:07.333 UTC | 2014-03-18 16:59:18.537 UTC | null | 1,287,812 | null | 1,777,480 | null | 1 | 15 | php|jquery|wordpress | 36,427 | <p><strong>WordPress environment</strong></p>
<p>First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in <code>wp_enqueue_scripts</code> action hook. In the same hook you should put <code>wp_localize_script</code> that it's used to include arbitrary JavaScript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle. </p>
<p>Please take a look to:</p>
<ol>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_register_script" rel="noreferrer">wp_register_script();</a> function</li>
<li><a href="http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts" rel="noreferrer">wp_enqueue_scripts</a> hook</li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script" rel="noreferrer">wp_enqueue_script();</a> function</li>
<li><a href="http://codex.wordpress.org/Function_Reference/wp_localize_script" rel="noreferrer">wp_localize_script();</a> function</li>
</ol>
<p>In main plugin file, add these.</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
wp_register_script(
'ajaxHandle',
plugins_url('PATH TO YOUR SCRIPT FILE/jquery.ajax.js', __FILE__),
array(),
false,
true
);
wp_enqueue_script( 'ajaxHandle' );
wp_localize_script(
'ajaxHandle',
'ajax_object',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
}
</code></pre>
<p><strong>File: jquery.ajax.js</strong></p>
<p>This file makes the AJAX call.</p>
<pre><code>jQuery(document).ready( function($){
// Some event will trigger the ajax call, you can push whatever data to the server,
// simply passing it to the "data" object in ajax call
$.ajax({
url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
type: 'POST',
data:{
action: 'myaction', // this is the function in your functions.php that will be triggered
name: 'John',
age: '38'
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
});
</code></pre>
<p>Also add below codes to plugin main file.</p>
<p>Finally, on your functions.php file, there should be the function triggered by your AJAX call.
Remember the suffixes: </p>
<ol>
<li><code>wp_ajax</code> ( allow the function only for registered users or admin panel operations )</li>
<li><code>wp_ajax_nopriv</code> ( allow the function for no privilege users )</li>
</ol>
<p>These suffixes plus the action compose the name of your action:</p>
<p><code>wp_ajax_myaction</code> or <code>wp_ajax_nopriv_myaction</code></p>
<pre><code>add_action( "wp_ajax_myaction", "so_wp_ajax_function" );
add_action( "wp_ajax_nopriv_myaction", "so_wp_ajax_function" );
function so_wp_ajax_function(){
//DO whatever you want with data posted
//To send back a response you have to echo the result!
echo $_POST['name'];
echo $_POST['age'];
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
</code></pre> |
17,683,368 | Running a command on each directory in a list using PowerShell | <p>I've got a need to make a .zip of each directory in a list in PowerShell. I for some reason cannot figure out how to change to each directory to run a command relative to that path though.</p>
<p>Here is my situation:</p>
<pre><code>$dir = Get-ChildItem d:\directory | ? {$_.PSIsContainer}
$dir | ForEach-Object {Set-Location $_.FullName;
Invoke-Expression "7z.exe A" + $_.Name + ".rar " + $_.Path + "\"}
</code></pre>
<p>The command is ugly, but due to the way that 7Zip seems to parse text, I had to go this way. I believe the command should make a ZIP file in each directory, with the name set equal to the directory name, and include all of the files in the directory.</p>
<p>It seems like I'm stuck in some PowerShell hell though where I cannot even access the values of objects for some reason.</p>
<p>For instance, if I echo $dir, I see my list of directories. However, if I try</p>
<pre><code>gci $dir[1]
</code></pre>
<p>PowerShell returns nothing. It's not actually enumerating the directory path contained within the variable property, but instead trying to list the items contained within that value, which would of course be empty.</p>
<p>What gives?! How do I do this?</p> | 18,660,336 | 2 | 2 | null | 2013-07-16 17:36:26.32 UTC | 1 | 2020-03-29 21:04:48.25 UTC | 2017-05-28 22:33:46.747 UTC | null | 63,550 | null | 1,238,413 | null | 1 | 13 | powershell|recursion | 51,083 | <p>You don't need to set the location, you just just provide paths to 7z.exe. Also, 7zip does not compress to Rar, only decompress.</p>
<pre><code>$dir = dir d:\directory | ?{$_.PSISContainer}
foreach ($d in $dir){
$name = Join-Path -Path $d.FullName -ChildPath ($d.Name + ".7z")
$path = Join-Path -Path $d.FullName -ChildPath "*"
& "C:\Program Files\7-Zip\7z.exe" a -t7z $name $path
}
</code></pre> |
17,963,348 | How to Disconnect from a database and go back to the default database in PostgreSQL? | <p>I'm using PostgreSql version : </p>
<pre><code>postgres=# select version();
version
-------------------------------------------------------------
PostgreSQL 9.2.4, compiled by Visual C++ build 1600, 64-bit
(1 row)
</code></pre>
<p>i had connected to a database from <code>postgres=#</code> to <code>newdb=#</code>....
Now i'm in <code>newdb=#</code> Database i want to disconnect it and go back to <code>postgres=#</code> database ....</p>
<p>How to do this ?</p>
<p>I have tried with <code>disconnect newdb;</code></p>
<p>but its giving erroe as::</p>
<pre><code>postgres=# create database newdb;
CREATE DATABASE
postgres=# \c newdb;
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
You are now connected to database "newdb" as user "postgres".
newdb=# disconnect newdb;
ERROR: syntax error at or near "disconnect"
LINE 1: disconnect newdb;
^
newdb=#
</code></pre>
<p>it isnt working is there any other way to do this or am i wrong in anything!!</p> | 17,964,554 | 2 | 8 | null | 2013-07-31 06:40:56.383 UTC | 18 | 2020-04-08 13:05:00.317 UTC | null | null | null | null | 2,561,626 | null | 1 | 100 | postgresql|postgresql-9.1|postgresql-9.2 | 125,344 | <p>It's easy, just look the example.</p>
<p><strong>--my databases</strong></p>
<pre><code>postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+---------+-------+---------------------------
francs | postgres | UTF8 | C | C | =Tc/postgres +
| | | | | postgres=CTc/postgres +
| | | | | francs=C*T*c*/postgres +
| | | | | select_only=c/francs
postgres | postgres | UTF8 | C | C |
source_db | postgres | UTF8 | C | C | =Tc/postgres +
| | | | | postgres=CTc/postgres +
| | | | | source_db=C*T*c*/postgres
template0 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
(5 rows)
</code></pre>
<p>--<strong>switch to db francs as role francs</strong></p>
<pre><code>postgres=# \c francs francs
You are now connected to database "francs" as user "francs".
</code></pre>
<p>--<strong>swith to db postgres as role postgres</strong></p>
<pre><code>francs=> \c postgres postgres
You are now connected to database "postgres" as user "postgres".
postgres=#
</code></pre>
<p>--<strong>disconnect from db</strong></p>
<pre><code>postgres=# \q
</code></pre> |
35,430,584 | How is the Git hash calculated? | <p>I'm trying to understand how Git calculates the hash of refs.</p>
<pre><code>$ git ls-remote https://github.com/git/git
....
29932f3915935d773dc8d52c292cadd81c81071d refs/tags/v2.4.2
9eabf5b536662000f79978c4d1b6e4eff5c8d785 refs/tags/v2.4.2^{}
....
</code></pre>
<p>Clone the repo locally. Check the <code>refs/tags/v2.4.2^{}</code> ref by sha</p>
<pre><code>$ git cat-file -p 9eabf5b536662000f79978c4d1b6e4eff5c8d785
tree 655a20f99af32926cbf6d8fab092506ddd70e49c
parent df08eb357dd7f432c3dcbe0ef4b3212a38b4aeff
author Junio C Hamano <[email protected]> 1432673399 -0700
committer Junio C Hamano <[email protected]> 1432673399 -0700
Git 2.4.2
Signed-off-by: Junio C Hamano <[email protected]>
</code></pre>
<p>Copy the decompressed content so that we can hash it. (AFAIK Git uses the uncompressed version when it's hashing)</p>
<pre><code>git cat-file -p 9eabf5b536662000f79978c4d1b6e4eff5c8d785 > fi
</code></pre>
<p>Let's SHA-1 the content using Git's own hash command</p>
<pre><code>git hash-object fi
3cf741bbdbcdeed65e5371912742e854a035e665
</code></pre>
<p>Why is the output not <code>[9e]abf5b536662000f79978c4d1b6e4eff5c8d785</code>? I understand the first two characters (<code>9e</code>) are the length in hex. How should I hash the content of <code>fi</code> so that I can get the Git ref <code>abf5b536662000f79978c4d1b6e4eff5c8d785</code>?</p> | 35,433,481 | 3 | 2 | null | 2016-02-16 10:53:19.337 UTC | 12 | 2022-02-27 18:42:35.16 UTC | 2021-06-23 17:41:29.69 UTC | null | 775,954 | null | 3,257,971 | null | 1 | 54 | git|hash | 36,540 | <p>As described in "<a href="https://gist.github.com/masak/2415865" rel="noreferrer">How is git commit sha1 formed </a>", the formula is:</p>
<pre><code>(printf "<type> %s\0" $(git cat-file <type> <ref> | wc -c); git cat-file <type> <ref>)|sha1sum
</code></pre>
<p>In the case of the <strong>commit</strong> 9eabf5b536662000f79978c4d1b6e4eff5c8d785 (which is <code>v2.4.2^{}</code>, and which referenced a tree) :</p>
<pre><code>(printf "commit %s\0" $(git cat-file commit 9eabf5b536662000f79978c4d1b6e4eff5c8d785 | wc -c); git cat-file commit 9eabf5b536662000f79978c4d1b6e4eff5c8d785 )|sha1sum
</code></pre>
<p>That will give 9eabf5b536662000f79978c4d1b6e4eff5c8d785.</p>
<p>As would:</p>
<pre><code>(printf "commit %s\0" $(git cat-file commit v2.4.2{} | wc -c); git cat-file commit v2.4.2{})|sha1sum
</code></pre>
<p>(still 9eabf5b536662000f79978c4d1b6e4eff5c8d785)</p>
<p>Similarly, computing the SHA1 of the tag v2.4.2 would be:</p>
<pre><code>(printf "tag %s\0" $(git cat-file tag v2.4.2 | wc -c); git cat-file tag v2.4.2)|sha1sum
</code></pre>
<p>That would give 29932f3915935d773dc8d52c292cadd81c81071d.</p> |
41,135,658 | How to perform join query in Firebase? | <p>After retrieving group key in HashMap how to perform join query which shows only those <code>grp</code> details which have member as that particular user. And if this structure is wrong please help me with this.</p>
<p>Structure:</p>
<p><img src="https://i.stack.imgur.com/Faqkn.png" alt="screenShot"></p> | 41,141,719 | 1 | 1 | null | 2016-12-14 05:46:14.097 UTC | 8 | 2017-01-28 16:29:55.95 UTC | 2017-01-28 16:29:55.95 UTC | null | 1,930,509 | null | 6,202,145 | null | 1 | 11 | android|join|firebase|firebase-realtime-database | 26,760 | <blockquote>
<p>Use <code>DatabaseReference</code> inside another <code>DatabaseReference</code>: </p>
</blockquote>
<pre><code> // any way you managed to go the node that has the 'grp_key'
DatabaseReference MembersRef = FirebaseDatabase.getInstance()
.getReference()
.child("Members")
.child("1CkPG20Tt2dzrVkYkdfCLo")
.orderByKey().equalTo("-KYnhiAucnasdkadNC")
.addValueEventListener(
new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot child : dataSnapshot.getChildren())
{
Map<String, Object> valuesMap = (HashMap<String, Object>) dataSnapshot.getValue();
// Get push id value.
String key = valuesMap.get("grp_key");
// HERE WHAT CORRESPONDS TO JOIN
DatabaseReference chatGroupRef = FirebaseDatabase.getInstance().getReference()
.child("Chat_groups")
.orderByKey().equalTo(key)
.addValueEventListener(
new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
// repeat!!
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
}
)
}
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
}
);
</code></pre> |
1,882,024 | WiX will not add HKLM registry setting during Windows 7 install | <p>I have written a WiX installer that works perfectly with Windows XP, but when installing to a Windows 7 box I am running into difficulty with registry entries. I need to add an HKLM entry as well as the registry entry for the program to show in the start menu. Here is the code I am using for both types of entry:</p>
<pre><code><!-- Create the registry entries for the program -->
<DirectoryRef Id="TARGETDIR">
<Component Id="RegistryEntriesInst" Guid="...">
<RegistryKey Root="HKLM"
Key="Software\$(var.Manufacturer)\$(var.ProductName)"
Action="createAndRemoveOnUninstall">
<RegistryValue
Type="string"
Name="installed"
Value="true"
KeyPath="yes"/>
</RegistryKey>
</Component>
<Component Id="RegistryEntriesVer" Guid="...">
<RegistryKey Root="HKLM"
Key="Software\$(var.Manufacturer)\$(var.ProductName)"
Action="createAndRemoveOnUninstall">
<RegistryValue
Type="string"
Name="version"
Value="$(var.ProductVersion)"
KeyPath="yes"/>
</RegistryKey>
</Component>
</DirectoryRef>
<!-- To add shortcuts to the start menu to run and uninstall the program -->
<DirectoryRef Id="ApplicationProgramsFolder">
<Component Id="ApplicationShortcut" Guid="...">
<Shortcut Id="ApplicationStartMenuShortcut"
Name="$(var.ProductName)"
Description="..."
Target="[SERVERLOCATION]$(var.Project.TargetFileName)"
WorkingDirectory="SERVERLOCATION"/>
<Shortcut Id="UninstallProduct"
Name="Uninstall $(var.ProductName)"
Description="..."
Target="[System64Folder]msiexec.exe"
Arguments="/x [ProductCode]"/>
<RemoveFolder Id="SERVERLOCATION" On="uninstall"/>
<RegistryValue
Root="HKCU"
Key="Software\$(var.Manufacturer)\$(var.ProductName)"
Name="installed"
Type="integer"
Value="1"
KeyPath="yes"/>
</Component>
</DirectoryRef>
</code></pre>
<p>How can I fix this problem?</p>
<p>On a side note, the registry permissions are the same on the Windows XP and Windows 7 computers.</p> | 1,883,376 | 3 | 1 | null | 2009-12-10 16:04:40.823 UTC | 7 | 2018-02-21 16:42:30.54 UTC | 2016-12-20 21:50:01.917 UTC | null | 63,550 | null | 157,814 | null | 1 | 32 | installation|wix|registry|windows-7-x64 | 20,359 | <p>I have figured out why this is happening.</p>
<p>With the WiX installer being compiled on a x86 platform, Windows 7 picked it up as the 32-bit installer with 32-bit registry keys. Windows 7 64-bit handles 32-bit registry entries by doing just what I saw happening. </p>
<p>The program was still registered; it was just not in the 64-bit portion of the registry. Compile it under a x64 platform while making the necessary changes to make it for a 64-bit system (ProgramFileFolder become ProgramFiles64Folder, etc.), and it will put things in the right place.</p> |
8,560,440 | Removing duplicate columns and rows from a NumPy 2D array | <p>I'm using a 2D shape array to store pairs of longitudes+latitudes. At one point, I have to merge two of these 2D arrays, and then remove any duplicated entry. I've been searching for a function similar to numpy.unique, but I've had no luck. Any implementation I've been
thinking on looks very "unoptimizied". For example, I'm trying with converting the array to a list of tuples, removing duplicates with set, and then converting to an array again:</p>
<pre><code>coordskeys = np.array(list(set([tuple(x) for x in coordskeys])))
</code></pre>
<p>Are there any existing solutions, so I do not reinvent the wheel?</p>
<p>To make it clear, I'm looking for:</p>
<pre><code>>>> a = np.array([[1, 1], [2, 3], [1, 1], [5, 4], [2, 3]])
>>> unique_rows(a)
array([[1, 1], [2, 3],[5, 4]])
</code></pre>
<p>BTW, I wanted to use just a list of tuples for it, but the lists were so big that they consumed my 4Gb RAM + 4Gb swap (numpy arrays are more memory efficient).</p> | 8,564,438 | 6 | 1 | null | 2011-12-19 11:10:27.7 UTC | 10 | 2016-04-02 20:41:51.007 UTC | 2012-03-25 10:59:59.017 UTC | null | 66,549 | null | 1,101,750 | null | 1 | 22 | python|numpy|scipy|duplicate-removal | 27,603 | <p>Here's one idea, it'll take a little bit of work but could be quite fast. I'll give you the 1d case and let you figure out how to extend it to 2d. The following function finds the unique elements of of a 1d array:</p>
<pre><code>import numpy as np
def unique(a):
a = np.sort(a)
b = np.diff(a)
b = np.r_[1, b]
return a[b != 0]
</code></pre>
<p>Now to extend it to 2d you need to change two things. You will need to figure out how to do the sort yourself, the important thing about the sort will be that two identical entries end up next to each other. Second, you'll need to do something like <code>(b != 0).all(axis)</code> because you want to compare the whole row/column. Let me know if that's enough to get you started.</p>
<p>updated: With some help with doug, I think this should work for the 2d case.</p>
<pre><code>import numpy as np
def unique(a):
order = np.lexsort(a.T)
a = a[order]
diff = np.diff(a, axis=0)
ui = np.ones(len(a), 'bool')
ui[1:] = (diff != 0).any(axis=1)
return a[ui]
</code></pre> |
8,459,204 | Adding event listeners to current and future elements with a particular class | <p>With JQuery, is it possible to add an event listener to any element that currently, <strong>or will in the future</strong>, have a particular class?</p>
<p>I'm working on a project that makes heavy use of contentEditable, so the DOM is changing, and elements can have classes added and removed as a result of user input.</p>
<p>I would like to be able to say "elements of class X should do Y when clicked", but if I understand correctly, $(".X").click(Y) will only add the event listener to elements that currently have class X.</p>
<p>Furthermore, if an element is no-longer part of class X, then it will still have the click event listener.</p>
<p>How can I do this?</p> | 8,459,272 | 3 | 1 | null | 2011-12-10 19:24:46.737 UTC | 3 | 2011-12-10 19:35:10.93 UTC | null | null | null | null | 16,050 | null | 1 | 32 | javascript|jquery|html | 12,027 | <p>Yep. What you're talking about is called event delegation. Here's an example:</p>
<pre><code>$('#container').on('click', '.innerElement', function(){
/// Do stuff
});
</code></pre>
<p>In your case, <code>#container</code> would be an element that is known to exist on page load which will contain the child elements you care about (either now or in the future). This approach takes advantage of event bubbling in the DOM.</p>
<p>As another poster mentioned, the live method will also work -- but it has been deprecated in jQuery 1.7, and is generally not as performant as using more selective delegation (such as the example above). </p> |
708,901 | How to send JSON back with JAVA? | <p>I am having problems <a href="https://stackoverflow.com/questions/706412/use-gzip-json-responses-and-jquery">using Gzip compression and JQuery together</a>. It seems that it may be caused by the way I am sending JSON responses in my Struts Actions. I use the next code to send my JSON objects back. </p>
<pre><code>public ActionForward get(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
JSONObject json = // Do some logic here
RequestUtils.populateWithJSON(response, json);
return null;
}
public static void populateWithJSON(HttpServletResponse response,JSONObject json) {
if(json!=null) {
response.setContentType("text/x-json;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
try {
response.getWriter().write(json.toString());
} catch (IOException e) {
throw new ApplicationException("IOException in populateWithJSON", e);
}
}
}
</code></pre>
<p>Is there a better way of sending JSON in a Java web application?</p> | 708,930 | 4 | 1 | null | 2009-04-02 09:03:31.11 UTC | 3 | 2013-04-12 02:23:14.997 UTC | 2017-05-23 11:52:41.043 UTC | null | -1 | Sergio del Amo | 2,138 | null | 1 | 11 | java|json | 48,447 | <p>Instead of </p>
<pre><code>try {
response.getWriter().write(json.toString());
} catch (IOException e) {
throw new ApplicationException("IOException in populateWithJSON", e);
}
</code></pre>
<p>try this</p>
<pre><code>try {
json.write(response.getWriter());
} catch (IOException e) {
throw new ApplicationException("IOException in populateWithJSON", e);
}
</code></pre>
<p>because this will avoid creating a string and the JSONObject will directly write the bytes to the Writer object</p> |
246,806 | I want to convert std::string into a const wchar_t * | <p>Is there any method?
My computer is AMD64.</p>
<pre><code>::std::string str;
BOOL loadU(const wchar_t* lpszPathName, int flag = 0);
</code></pre>
<p>When I used: </p>
<pre><code>loadU(&str);
</code></pre>
<p>the VS2005 compiler says:</p>
<pre><code>Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *'
</code></pre>
<p>How can I do it?</p> | 246,811 | 4 | 0 | null | 2008-10-29 13:35:37.79 UTC | 12 | 2017-12-31 17:41:45.567 UTC | 2017-05-05 00:28:14.21 UTC | Brian R. Bondy | 15,168 | null | 25,749 | null | 1 | 66 | c++|stl|wchar-t|stdstring | 167,772 | <p>If you have a std::wstring object, you can call <code>c_str()</code> on it to get a <code>wchar_t*</code>:</p>
<pre><code>std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();
</code></pre>
<p>Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in <a href="http://msdn.microsoft.com/en-us/library/dd319072%28v=vs.85%29.aspx" rel="noreferrer"><code>MultiByteToWideChar</code></a> routine. That will give you an <code>LPWSTR</code>, which is equivalent to <code>wchar_t*</code>.</p> |
1,335,419 | How can I make sure that FirstOrDefault<KeyValuePair> has returned a value | <p>Here's a simplified version of what I'm trying to do:</p>
<pre><code>var days = new Dictionary<int, string>();
days.Add(1, "Monday");
days.Add(2, "Tuesday");
...
days.Add(7, "Sunday");
var sampleText = "My favorite day of the week is 'xyz'";
var day = days.FirstOrDefault(x => sampleText.Contains(x.Value));
</code></pre>
<p>Since 'xyz' is not present in the dictionary, the FirstOrDefault method will not return a valid value. I want to be able to check for this situation but I realize that I can't compare the result to "null" because KeyValuePair is a struc. The following code is invalid:</p>
<pre><code>if (day == null) {
System.Diagnotics.Debug.Write("Couldn't find day of week");
}
</code></pre>
<p>We you attempt to compile the code, Visual Studio throws the following error: </p>
<pre><code>Operator '==' cannot be applied to operands of type 'System.Collections.Generic.KeyValuePair<int,string>' and '<null>'
</code></pre>
<p>How can I check that FirstOrDefault has returned a valid value?</p> | 1,336,077 | 4 | 3 | null | 2009-08-26 15:07:39.957 UTC | 13 | 2021-07-27 15:54:35.63 UTC | 2019-08-04 16:21:32.08 UTC | null | 153,084 | null | 153,084 | null | 1 | 107 | c#|linq | 44,765 | <p><code>FirstOrDefault</code> doesn't return null, it returns <a href="https://msdn.microsoft.com/en-us/library/xwth0h0d.aspx" rel="noreferrer"><code>default(T)</code></a>.<br />
You should check for:</p>
<pre><code>var defaultDay = default(KeyValuePair<int, string>);
bool b = day.Equals(defaultDay);
</code></pre>
<p>From <a href="http://msdn.microsoft.com/en-us/library/bb340482.aspx" rel="noreferrer">MSDN - <code>Enumerable.FirstOrDefault<TSource></code></a>:</p>
<blockquote>
<p>default(<em>TSource</em>) if source is empty; otherwise, the first element in <em>source</em>.</p>
</blockquote>
<p>Notes:</p>
<ul>
<li>If your code is generic it is better to use <a href="https://msdn.microsoft.com/en-us/library/ms224763.aspx" rel="noreferrer"><code>EqualityComparer<T>.Default.Equals(day, defaultDay)</code></a>, becuase <code>.Equals</code> may be overridden or <code>day</code> could be a <code>null</code>.</li>
<li>In C# 7.1 you will be able to use <code>KeyValuePair<int, string> defaultDay = default;</code>, see <a href="https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.1/target-typed-default.md" rel="noreferrer">Target-typed "default" literal</a>.</li>
<li>See also: <a href="http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8087366974af11d2" rel="noreferrer">Reference Source - <code>FirstOrDefault</code></a></li>
</ul> |
469,159 | an htop-like tool to display disk activity in linux | <p>I am looking for a Linux command-line tool that would report the disk IO activity. Something similar to <code>htop</code> would be really cool. Has someone heard of something like that?</p> | 469,187 | 4 | 2 | null | 2009-01-22 13:41:31.737 UTC | 42 | 2015-02-06 10:37:22.983 UTC | 2014-02-11 14:45:12.023 UTC | null | 1,159,478 | null | 54,579 | null | 1 | 172 | linux|command-line|io | 129,864 | <p>You could use <a href="http://guichaz.free.fr/iotop/" rel="noreferrer">iotop</a>. It doesn't rely on a kernel patch. It Works with stock Ubuntu kernel</p>
<p>There is a package for it in the Ubuntu repos. You can install it using </p>
<pre><code>sudo apt-get install iotop
</code></pre>
<p><img src="https://i.stack.imgur.com/MfDA5.png" alt="iotop"></p> |
23,935,095 | How are MAC addresses used in routing packets? | <p>I recently found that packets are encapsulated within ethernet frames. Packets use IP addresses, frames use MAC addresses.</p>
<p>Why aren't IP addresses used in ethernet frames for routing? I understand that when trying to access a basic website, the computer goes to a DNS to find the IP address relevant to the user-entered domain name. How do computers find the correct MAC address?</p>
<p>Really, how are MAC addresses used in routing internet traffic?</p>
<p>Thanks</p> | 23,935,402 | 5 | 0 | null | 2014-05-29 13:55:03.213 UTC | 6 | 2021-06-20 10:06:53.557 UTC | 2014-05-29 13:57:30.01 UTC | null | 2,101,267 | null | 999,857 | null | 1 | 19 | tcp|ip | 38,145 | <p>IP packets aren't always encapsulated in Ethernet frames. There are other physical media such as ISDN, etc. When packets are routed, IP addresses are used to determine the next hop and the physical address is used to physically identify the interface serving as the next hop. Only the former (determining next-hop) is usually called routing.</p>
<p>To answer your second part, MAC addresses are discovered through ARP (Address Resolution Protocol) in IPv4 & ND6 (Neighbor Discovery) in IPv6.</p>
<p><strong>Update</strong>:
The destination IP address in the IP header is the final destination. In the process of routing (at each hop), you get the next hop's IP address to (eventually) reach the final destination from the routing table (this could be a default gateway's IP address). To send the packet to the next hop, you need its MAC address. While hopping through intermediate links, the IP address in the IP header don't change - only the MAC addresses change.</p> |
25,452,666 | Oracle Insert Into NVarchar2(4000) does not allow 4000 characters? | <p>I have a table with a field datatype of NVarchar2(4000) I am moving data from a SQL Server to an Oracle Server. The SQL Server datatype is also nvarchar(4000). I have checked the MAX Size of this field on the SQL Server side, and the MAX is 3996, which is 4 characters short of the 4000 limit. </p>
<p>When I try to insert this data into Oracle, I get an error "LONG" due to the size. </p>
<p>What is going on here, will the Oracle NVarchar2(4000) not allow 4000 characters? If not, what is the limit, or how can I get around this?</p> | 25,452,725 | 3 | 0 | null | 2014-08-22 17:36:19.803 UTC | 1 | 2019-03-07 15:10:48.623 UTC | null | null | null | null | 2,140,659 | null | 1 | 12 | sql|sql-server|oracle|insert | 40,192 | <p>There is a limit of 4000 bytes not 4000 characters. So NVARCHAR2(4000) with an AL16UTF16 national character set would occupy the maximum 4000 bytes.</p>
<p>From the <a href="http://docs.oracle.com/database/121/REFRN/refrn10321.htm#REFRN10321" rel="noreferrer">oracle docs of MAX_STRING SIZE</a>:</p>
<blockquote>
<p>Tables with virtual columns will be updated with new data type
metadata for virtual columns of VARCHAR2(4000), 4000-byte NVARCHAR2,
or RAW(2000) type.</p>
</blockquote>
<p><strong>Solution:-</strong></p>
<p>Also if you want to store 4000 characters then I would recommend you to use <strong><a href="http://www.orafaq.com/wiki/CLOB" rel="noreferrer">CLOB</a></strong></p>
<blockquote>
<p>A CLOB (Character Large Object) is an Oracle data type that can hold
up to 4 GB of data. CLOBs are handy for storing text.</p>
</blockquote>
<p>You may try like this to change column data type to CLOB:</p>
<pre><code>ALTER TABLE table_name
ADD (tmpcolumn CLOB);
UPDATE table_name SET tmpcolumn =currentnvarcharcolumn;
COMMIT;
ALTER TABLE table_name DROP COLUMN currentnvarcharcolumn;
ALTER TABLE table_name
RENAME COLUMN tmpcolumn TO whatevernameyouwant;
</code></pre> |
48,950,670 | JupyterLab User Settings File | <p>I leverage Docker containers to launch JupyterLabs and would like the ability to apply user settings directly at launch, instead of configuring user settings through the "Advanced Settings Editor" GUI at every container launch. </p>
<p>In reviewing the following pull request, it does seem that this functionality should exist: <a href="https://github.com/jupyterlab/jupyterlab/pull/2585" rel="noreferrer">https://github.com/jupyterlab/jupyterlab/pull/2585</a></p>
<p>I have not found anything referencing this capability in the JupyterLab documentation, so any leads would be greatly appreciated!</p> | 50,750,181 | 4 | 0 | null | 2018-02-23 15:00:31.137 UTC | 5 | 2021-10-18 10:49:59.347 UTC | null | null | null | null | 6,509,204 | null | 1 | 28 | jupyter-lab | 26,922 | <p>Running <code>jupyter-lab --generate-config</code> should generate a config file in <code>/home/<USER>/.jupyter/jupyter_notebook_config.py</code></p> |
19,764,243 | Can not load "IE", it is not registered! error message on Karma | <p>I'm using karma to run my js tests on multiple browsers.
the test works on Chrome & Firefox but I can't activate them on IE.</p>
<p>I'm getting the following error message:</p>
<blockquote>
<p>Can not load "IE", it is not registered! Perhaps you are missing some
plugin?</p>
</blockquote>
<p>On my config file </p>
<pre><code>SET CHROME_BIN=c:\Program Files (x86)\Google\Chrome\Application\chrome.exe
SET FIREFOX_BIN=C:\Program Files (x86)\Mozilla Firefox\firefox.exe
SET IE_BIN=C:\Program Files\Internet Explorer\iexplore.exe
</code></pre>
<p>I also tried this </p>
<pre><code>SET IE_BIN=C:\Program Files (86)\Internet Explorer\iexplore.exe
</code></pre>
<p>I already installed <a href="https://github.com/karma-runner/karma-ie-launcher" rel="noreferrer">karma-ie-launcher</a>. </p>
<p>Can you help me?</p> | 22,194,086 | 7 | 0 | null | 2013-11-04 08:49:59.817 UTC | 3 | 2016-03-01 11:35:47.413 UTC | 2013-11-04 11:37:49.613 UTC | null | 871,672 | null | 871,672 | null | 1 | 29 | javascript|internet-explorer|unit-testing|karma-runner | 15,155 | <p>In the configuration file for your project (e.g. karma.config.js), check if you have the plugins listed</p>
<pre><code>plugins : [
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-opera-launcher',
'karma-ie-launcher',
'karma-jasmine'
],
</code></pre> |
2,365,644 | JAXB validation using annotations | <p>If I have a simple class such as:-</p>
<pre><code>@XmlRootElement
public class MyClass
{
@XmlAttribute(required=true)
private String myattribute
}
</code></pre>
<p>Is it possible to validate a corresponding xml document WITHOUT an xml schema i.e. using only the annotations?</p> | 2,367,327 | 2 | 5 | null | 2010-03-02 18:28:57.327 UTC | 6 | 2012-01-13 17:13:43.307 UTC | null | null | null | null | 187,492 | null | 1 | 29 | java|xml|validation|jaxb | 20,946 | <p>Good question. As far as I know, the <code>required</code> attribute is generated by XJC when it finds a non-optional schema type, and I think it's also used by the schema generator. At runtime, though, it's not used for anything, serving no other purpose than a documentary annotation.</p>
<p>One thing you could consider is the JAXB runtime's <a href="http://java.sun.com/javase/6/docs/api/javax/xml/bind/Unmarshaller.html#unmarshalEventCallback" rel="noreferrer">callback options</a>. In this case, you could just define a <code>afterUnmarshal()</code> method on <code>MyClass</code> which programmatically validates the state of the object, throwing an exception if it doesn't like it. See the above link for other options, including registering separate validator classes.</p>
<p>Having said that, validation against a schema really is the best way. If you don't have one, you should considering writing one. The <a href="http://java.sun.com/javase/6/docs/technotes/tools/share/schemagen.html" rel="noreferrer">schemagen</a> tool can generate a schema from your object model, which you can then modify to add whatever constraints you like. Hopefully, <code>schemagen</code> will generate mandatory schema elements from your <code>required=true</code> class fields.</p> |
3,061,273 | Send an Array with an HTTP Get | <p>How can i send an Array with a HTTP Get request?</p>
<p>I'm Using GWT client to send the request.</p> | 3,061,292 | 2 | 1 | null | 2010-06-17 11:37:41.33 UTC | 26 | 2015-08-13 13:00:54.27 UTC | 2010-06-17 11:42:50.193 UTC | null | 157,882 | null | 354,696 | null | 1 | 126 | java|http|gwt|arrays | 181,970 | <p>That depends on what the target server accepts. There is no definitive standard for this. See also a.o. <a href="http://en.wikipedia.org/wiki/Query_string#Web_forms" rel="noreferrer">Wikipedia: Query string</a>:</p>
<blockquote>
<p>While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. <code>field1=value1&field1=value2&field2=value3</code>).<sup><a href="http://en.wikipedia.org/wiki/Query_string#cite_note-4" rel="noreferrer">[4]</a><a href="http://en.wikipedia.org/wiki/Query_string#cite_note-5" rel="noreferrer">[5]</a></sup></p>
</blockquote>
<p>Generally, when the target server uses a <strong>strong typed</strong> programming language like Java (<a href="https://stackoverflow.com/tags/servlets/info">Servlet</a>), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.</p>
<pre><code>foo=value1&foo=value2&foo=value3
</code></pre>
<pre><code>String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]
</code></pre>
<p>The <code>request.getParameter("foo")</code> will also work on it, but it'll return only the first value.</p>
<pre><code>String foo = request.getParameter("foo"); // value1
</code></pre>
<p>And, when the target server uses a <strong>weak typed</strong> language like PHP or RoR, then you need to suffix the parameter name with braces <code>[]</code> in order to trigger the language to return an array of values instead of a single value.</p>
<pre><code>foo[]=value1&foo[]=value2&foo[]=value3
</code></pre>
<pre><code>$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true
</code></pre>
<p>In case you still use <code>foo=value1&foo=value2&foo=value3</code>, then it'll return only the first value.</p>
<pre><code>$foo = $_GET["foo"]; // value1
echo is_array($foo); // false
</code></pre>
<p>Do note that when you send <code>foo[]=value1&foo[]=value2&foo[]=value3</code> to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.</p>
<pre><code>String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]
</code></pre> |
42,448,372 | Typescript mongoose static model method "Property does not exist on type" | <p>I am currently trying to add a static method to my mongoose schema but I can't find the reason why it doesn't work this way.</p>
<p>My model:</p>
<pre><code>import * as bcrypt from 'bcryptjs';
import { Document, Schema, Model, model } from 'mongoose';
import { IUser } from '../interfaces/IUser';
export interface IUserModel extends IUser, Document {
comparePassword(password: string): boolean;
}
export const userSchema: Schema = new Schema({
email: { type: String, index: { unique: true }, required: true },
name: { type: String, index: { unique: true }, required: true },
password: { type: String, required: true }
});
userSchema.method('comparePassword', function (password: string): boolean {
if (bcrypt.compareSync(password, this.password)) return true;
return false;
});
userSchema.static('hashPassword', (password: string): string => {
return bcrypt.hashSync(password);
});
export const User: Model<IUserModel> = model<IUserModel>('User', userSchema);
export default User;
</code></pre>
<p>IUser:</p>
<pre><code>export interface IUser {
email: string;
name: string;
password: string;
}
</code></pre>
<p>If I now try to call <code>User.hashPassword(password)</code> I am getting the following error <code>[ts] Property 'hashPassword' does not exist on type 'Model<IUserModel>'.</code></p>
<p>I know that I didn't define the method anywhere but I don't really know where I could put it as I can't just put a static method into an interface.
I hope you can help my find the error, thanks in advance!</p> | 42,798,586 | 6 | 0 | null | 2017-02-24 21:12:27.31 UTC | 24 | 2021-07-10 07:52:21.57 UTC | 2017-02-27 18:01:52.987 UTC | null | 4,559,407 | null | 4,559,407 | null | 1 | 43 | node.js|typescript|mongoose | 35,698 | <p>I think you are having the same issue that I just struggled with. This issue is in your call. Several tutorials have you call the <code>.comparePassword()</code> method from the model like this.</p>
<pre><code>User.comparePassword(candidate, cb...)
</code></pre>
<p>This doesn't work because the method is on the <code>schema</code> not on the <code>model</code>. The only way I was able to call the method was by finding this instance of the model using the standard mongoose/mongo query methods.</p>
<p>Here is relevant part of my passport middleware:</p>
<pre><code>passport.use(
new LocalStrategy({
usernameField: 'email'
},
function (email: string, password: string, done: any) {
User.findOne({ email: email }, function (err: Error, user: IUserModel) {
if (err) throw err;
if (!user) return done(null, false, { msg: 'unknown User' });
user.schema.methods.comparePassword(password, user.password, function (error: Error, isMatch: boolean) {
if (error) throw error;
if (!isMatch) return done(null, false, { msg: 'Invalid password' });
else {
console.log('it was a match'); // lost my $HÏT when I saw it
return done(null, user);
}
})
})
})
);
</code></pre>
<p>So I used <code>findOne({})</code> to get the document instance and then had to access the schema methods by digging into the schema properties on the document <code>user.schema.methods.comparePassword</code></p>
<p>A couple of differences that I have noticed:</p>
<ol>
<li>Mine is an <code>instance</code> method while yours is a <code>static</code> method. I'm confident that there is a similar method access strategy.</li>
<li>I found that I had to pass the hash to the <code>comparePassword()</code> function. perhaps this isn't necessary on statics, but I was unable to access <code>this.password</code></li>
</ol> |
22,999,630 | Passing arguments django signals - post_save/pre_save | <p>I am working on a notification app in Django 1.6 and I want to pass additional arguments to Django signals such as <code>post_save</code>. I tried to use partial from functools but no luck. </p>
<pre><code>from functools import partial
post_save.connect(
receiver=partial(notify,
fragment_name="categories_index"),
sender=nt.get_model(),
dispatch_uid=nt.sender
)
</code></pre>
<p><code>notify</code> function has a keyword argument <code>fragment_name</code> which I want to pass as default in my signals.</p>
<p>Any suggestions?</p> | 23,452,387 | 5 | 0 | null | 2014-04-10 21:45:08.113 UTC | 7 | 2021-08-17 03:17:46.273 UTC | 2014-07-13 10:13:23.75 UTC | null | 515,189 | null | 145,277 | null | 1 | 28 | django|signals|argument-passing | 19,015 | <p>Your attempt with partial isn't working because by default these receivers are connected using a weak reference.</p>
<p>According to the <a href="https://docs.djangoproject.com/en/dev/ref/signals/#module-django.db.models.signals" rel="noreferrer">Django docs</a>:</p>
<blockquote>
<p>Django stores signal handlers as weak references by default, so if your handler is a local function, it may be garbage collected. To prevent this, pass weak=False when you call the signal’s connect().</p>
</blockquote>
<pre><code>from functools import partial
post_save.connect(
receiver=partial(notify,
fragment_name="categories_index"),
sender=nt.get_model(),
dispatch_uid=nt.sender,
weak=False
)
</code></pre>
<p>Include weak=False and this partial won't be garbage collected.</p>
<p>My original answer is below and took an approach that wasn't using partial.</p>
<p>You could decorate your post save function prior to connecting it with the post_save receiver. </p>
<pre><code>from django.dispatch import receiver
from django.db.models.signals import pre_save, post_save, post_delete
def extra_args(fragment_name, *args, **kwargs):
def inner1(f, *args, **kwargs):
def inner2(sender, instance, **kwargs):
f(sender, instance, fragment_name=fragment_name, **kwargs)
return inner2
return inner1
@receiver(post_save, sender=ExampleModel)
@extra_args(fragment_name="categories_index")
def my_post_save(sender, instance, fragment_name, **kwargs):
print "fragment_name : ", fragment_name
#rest of post save...
</code></pre>
<p>The extra inner in extra_args is for <a href="https://stackoverflow.com/a/15624856/27604">decorators that take parameters</a>.</p>
<p>If you want to do this programmatically this works the same way but note that you need to include <code>weak=False</code> to have the wrapped function not be garbage collected.</p>
<pre><code>receiver(post_save, sender=aSenderClass, weak=False)(extra_args(fragment_name="meep")(my_post_save))
</code></pre>
<p>Or without wrapping, but calling post_save.connect like your original attempt with partial</p>
<pre><code>post_save.connect(extra_args(fragment_name="meepConnect")(my_post_save), sender=Author, weak=False)
</code></pre> |
30,874,214 | How to access entity manager with spring boot and spring data | <p>How can I get access to the <code>Entity Manager</code> in the repository when using Spring Boot and Spring Data?</p>
<p>Otherwise, I will need to put my big query in an annotation. I would prefer to have something more clear than a long text.</p> | 30,886,571 | 2 | 0 | null | 2015-06-16 17:24:29.047 UTC | 13 | 2020-12-27 13:33:11.29 UTC | 2019-11-04 14:45:18.54 UTC | null | 7,080,548 | null | 1,095,362 | null | 1 | 35 | spring-boot|spring-data|spring-data-jpa | 53,310 | <p>You would define a <code>CustomRepository</code> to handle such scenarios. Consider you have <code>CustomerRepository</code> which extends the default spring data JPA interface <code>JPARepository<Customer,Long></code></p>
<p>Create a new interface <code>CustomCustomerRepository</code> with a custom method signature.</p>
<pre><code>public interface CustomCustomerRepository {
public void customMethod();
}
</code></pre>
<p>Extend <code>CustomerRepository</code> interface using <code>CustomCustomerRepository</code></p>
<pre><code>public interface CustomerRepository extends JpaRepository<Customer, Long>, CustomCustomerRepository{
}
</code></pre>
<p>Create an implementation class named <code>CustomerRepositoryImpl</code> which implements <code>CustomerRepository</code>. Here you can inject the <code>EntityManager</code> using the <code>@PersistentContext</code>. Naming conventions matter here.</p>
<pre><code>public class CustomCustomerRepositoryImpl implements CustomCustomerRepository {
@PersistenceContext
private EntityManager em;
@Override
public void customMethod() {
}
}
</code></pre> |
1,695,699 | Parse CSV file containing a Unicode character using OpenCSV | <p>I'm trying to parse a .csv file with <a href="http://opencsv.sourceforge.net/" rel="noreferrer">OpenCSV</a> in NetBeans 6.0.1. My file contains some Unicode character. When I write it in output the character appears in other form, like (HJ1'-E/;). When when I open this file in Notepad, it looks ok.</p>
<p>The code that I used:</p>
<pre><code>CSVReader reader=new CSVReader(new FileReader("d:\\a.csv"),',','\'',1);
String[] line;
while((line=reader.readNext())!=null){
StringBuilder stb=new StringBuilder(400);
for(int i=0;i<line.length;i++){
stb.append(line[i]);
stb.append(";");
}
System.out.println( stb);
}
</code></pre> | 1,695,729 | 1 | 0 | null | 2009-11-08 07:50:23.007 UTC | 7 | 2017-04-16 00:48:44.443 UTC | 2017-04-16 00:48:44.443 UTC | null | 3,357,935 | null | 187,327 | null | 1 | 16 | java|netbeans|csv|opencsv | 42,697 | <p>First you need to know what encoding your file is in, such as UTF-8 or UTF-16. What's generating this file to start with? </p>
<p>After that, it's relatively straightforward - you need to create a <code>FileInputStream</code> wrapped in an <code>InputStreamReader</code> instead of just a <code>FileReader</code>. (<code>FileReader</code> always uses the default encoding for the system.) Specify the encoding to use when you create the <code>InputStreamReader</code>, and if you've picked the right one, everything should start working.</p>
<p>Note that you don't need to use OpenCSV to check this - you could just read the text of the file yourself and print it all out. I'm not sure I'd trust <code>System.out</code> to be able to handle non-ASCII characters though - you may want to find a different way of examining strings, such as printing out the individual values of characters as integers (preferably in hex) and then comparing them with the <a href="http://unicode.org/charts" rel="noreferrer">charts at unicode.org</a>. On the other hand, you could try the right encoding and see what happens to start with...</p>
<p>EDIT: Okay, so if you're using UTF-8:</p>
<pre><code>CSVReader reader=new CSVReader(
new InputStreamReader(new FileInputStream("d:\\a.csv"), "UTF-8"),
',', '\'', 1);
String[] line;
while ((line = reader.readNext()) != null) {
StringBuilder stb = new StringBuilder(400);
for (int i = 0; i < line.length; i++) {
stb.append(line[i]);
stb.append(";");
}
System.out.println(stb);
}
</code></pre>
<p>(I hope you have a try/finally block to close the file in your real code.)</p> |
30,165,060 | Can @FunctionalInterfaces have default methods? | <p>Why can't I create a <code>@FunctionalInterface</code> with a default method implementation?</p>
<pre><code>@FunctionalInterface
public interface MyInterface {
default boolean authorize(String value) {
return true;
}
}
</code></pre> | 30,165,132 | 4 | 0 | null | 2015-05-11 10:15:56.587 UTC | 7 | 2020-01-28 08:43:00.95 UTC | 2019-07-17 09:03:12.99 UTC | null | 4,675,109 | null | 1,194,415 | null | 1 | 44 | java|java-8 | 24,478 | <p>You can have default methods in a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html" rel="noreferrer">functional interface</a> but its contract requires you to provide one single abstract method (or SAM). Since a default method have an implementation, it's not abstract.</p>
<blockquote>
<p>Conceptually, a functional interface has exactly one abstract method.
Since default methods have an implementation, they are not abstract.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>If a type is annotated with this annotation type, compilers are
required to generate an error message unless:</p>
<p>The type is an interface type and not an annotation type, enum, or
class.</p>
<p>The annotated type satisfies the requirements of a functional
interface.</p>
</blockquote>
<p>Here you don't satisfy the functional interface's requirement, so you need to provide one abstract method. For example:</p>
<pre><code>@FunctionalInterface
interface MyInterface {
boolean authorize(int val);
default boolean authorize(String value) {
return true;
}
}
</code></pre>
<p>Note that if you declare an abstract method overriding one of a public method from the Object's class it doesn't count, because any implementation of this interface will have an implementation of those methods through at least the Object's class. For example:</p>
<pre><code>@FunctionalInterface
interface MyInterface {
default boolean authorize(String value) {
return true;
}
boolean equals(Object o);
}
</code></pre>
<p>does not compile.</p> |
36,814,100 | pandas: to_numeric for multiple columns | <p>I'm working with the following <a href="https://github.com/108michael/ms_thesis/blob/master/test_state_gdp" rel="noreferrer">df</a>:</p>
<pre><code>c.sort_values('2005', ascending=False).head(3)
GeoName ComponentName IndustryId IndustryClassification Description 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
37926 Alabama Real GDP by state 9 213 Support activities for mining 99 98 117 117 115 87 96 95 103 102 (NA)
37951 Alabama Real GDP by state 34 42 Wholesale trade 9898 10613 10952 11034 11075 9722 9765 9703 9600 9884 10199
37932 Alabama Real GDP by state 15 327 Nonmetallic mineral products manufacturing 980 968 940 1084 861 724 714 701 589 641 (NA)
</code></pre>
<p>I want to force numeric on all of the years:</p>
<pre><code>c['2014'] = pd.to_numeric(c['2014'], errors='coerce')
</code></pre>
<p>is there an easy way to do this or do I have to type them all out?</p> | 36,814,203 | 6 | 0 | null | 2016-04-23 17:28:26.643 UTC | 24 | 2021-02-24 04:03:29.847 UTC | 2019-05-01 09:21:15.277 UTC | null | 9,609,843 | null | 5,211,377 | null | 1 | 96 | python|pandas | 181,808 | <p><strong>UPDATE:</strong> you don't need to convert your values afterwards, you can do it <strong>on-the-fly</strong> when reading your CSV:</p>
<pre><code>In [165]: df=pd.read_csv(url, index_col=0, na_values=['(NA)']).fillna(0)
In [166]: df.dtypes
Out[166]:
GeoName object
ComponentName object
IndustryId int64
IndustryClassification object
Description object
2004 int64
2005 int64
2006 int64
2007 int64
2008 int64
2009 int64
2010 int64
2011 int64
2012 int64
2013 int64
2014 float64
dtype: object
</code></pre>
<p>If you need to convert multiple columns to numeric dtypes - use the following technique:</p>
<p>Sample source DF:</p>
<pre><code>In [271]: df
Out[271]:
id a b c d e f
0 id_3 AAA 6 3 5 8 1
1 id_9 3 7 5 7 3 BBB
2 id_7 4 2 3 5 4 2
3 id_0 7 3 5 7 9 4
4 id_0 2 4 6 4 0 2
In [272]: df.dtypes
Out[272]:
id object
a object
b int64
c int64
d int64
e int64
f object
dtype: object
</code></pre>
<p>Converting selected columns to numeric dtypes:</p>
<pre><code>In [273]: cols = df.columns.drop('id')
In [274]: df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
In [275]: df
Out[275]:
id a b c d e f
0 id_3 NaN 6 3 5 8 1.0
1 id_9 3.0 7 5 7 3 NaN
2 id_7 4.0 2 3 5 4 2.0
3 id_0 7.0 3 5 7 9 4.0
4 id_0 2.0 4 6 4 0 2.0
In [276]: df.dtypes
Out[276]:
id object
a float64
b int64
c int64
d int64
e int64
f float64
dtype: object
</code></pre>
<p>PS if you want to select <strong>all</strong> <code>string</code> (<code>object</code>) columns use the following simple trick:</p>
<pre><code>cols = df.columns[df.dtypes.eq('object')]
</code></pre> |
24,322,221 | Passing title, url and image on share.php of facebook | <p>I want to share title , image and description on facebook without javascript just by passing these to share.php of facebook.
I got some code on this site in question <a href="https://stackoverflow.com/questions/15074566/open-source-alternative-to-addthis-addtoany-sharethis-etcfor-social-bookmarking">Open source alternative to AddThis AddToAny, ShareThis etcfor Social Bookmarking</a></p>
<p>and I have read the question <a href="https://stackoverflow.com/questions/22653745/how-to-pass-custom-parameter-in-facebook-sharer-link">how to pass custom parameter in facebook sharer link</a></p>
<p>Now I want to combine both questions. Can I pass Image, title and description simply in the facebook share.php url</p>
<p>like:</p>
<pre><code><a class="scmFacebook" href='http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo $title;?>&amp;p[summary]=<?php echo $summary;?>&amp;p[url]=<?php echo $url; ?>&amp;&p[images][0]=<?php echo $image;?>'>Facebook</a>
</code></pre>
<p>OR
If I am wrong then please show me the right destination.</p> | 24,322,384 | 2 | 0 | null | 2014-06-20 07:36:30.13 UTC | 5 | 2021-02-25 05:58:10.753 UTC | 2017-05-23 11:44:11.68 UTC | null | -1 | null | 3,739,733 | null | 1 | 12 | php|facebook|wordpress|facebook-graph-api | 46,384 | <p>According to the facebook developers (<a href="https://developers.facebook.com/x/bugs/357750474364812/" rel="noreferrer">bug</a>):</p>
<blockquote>
<p>The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.</p>
</blockquote>
<ol>
<li><p>Either you use the <a href="https://developers.facebook.com/docs/plugins/share-button/" rel="noreferrer">Share Button</a> - requires Javascript SDK</p></li>
<li><p>Or, use the latest <a href="https://developers.facebook.com/docs/sharing/reference/share-dialog" rel="noreferrer">Share Dialog </a> - requires just an app id. It has a direct url direction method for invoking the share dialog:</p>
<pre><code>https://www.facebook.com/dialog/share?
app_id={app-id}
&display=popup
&href={link-to-share}
&redirect_uri={redirect-uri}
</code></pre></li>
</ol> |
30,342,796 | How to get ENV variable when doing Docker Inspect | <p>I wonder how I get an Environment variable from docker inspect.</p>
<p>when i run </p>
<pre><code>docker inspect -f "{{.Config.Env.PATH}} " 1e2b8689cf06
</code></pre>
<p>i get the following </p>
<pre><code>FATA[0000] template: :1:9: executing "" at <.Config.Env.PATH>: can't evaluate field PATH in type interface {}
</code></pre> | 30,353,018 | 8 | 0 | null | 2015-05-20 07:16:24.363 UTC | 10 | 2019-10-31 19:37:31.387 UTC | null | null | null | null | 121,816 | null | 1 | 30 | docker | 45,326 | <p>You can get directly with a command similar to</p>
<pre><code>docker inspect --format '{{ index (index .Config.Env) 1 }}' 797
</code></pre>
<p>which shows for me</p>
<pre><code>PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
</code></pre>
<p>You will notice that replacing the <code>1</code> by <code>0</code> like </p>
<pre><code>docker inspect --format '{{ index (index .Config.Env) 0 }}' 797
</code></pre>
<p>gives </p>
<pre><code>DISPLAY=:0
</code></pre>
<p>In fact I had noticed the following for various <code>docker inspect</code> from a more general to a more precise display </p>
<pre><code>docker inspect --format '{{ (.NetworkSettings.Ports) }}' 87c
map[8000/tcp:[map[HostIp:0.0.0.0 HostPort:49153]]]
docker inspect --format '{{ ((index .NetworkSettings.Ports "8000/tcp") 0) }}' 87c
[map[HostIp:0.0.0.0 HostPort:49153]]
docker inspect --format '{{ index (index .NetworkSettings.Ports "8000/tcp") 0 }}' 87c
map[HostIp:0.0.0.0 HostPort:49153]
docker inspect --format '{{ (index (index .NetworkSettings.Ports "8000/tcp") 0).HostIp }}' 87c
0.0.0.0
docker inspect --format '{{ (index (index .NetworkSettings.Ports "8000/tcp") 0).HostPort }}' 87c
49153
</code></pre>
<p><em>Note: <code>docker inspect -f</code> works and is shorter, of course, I posted the "old" syntax.</em></p> |
30,582,600 | Laravel generate slug before save | <p>Im trying to learn laravel 5 with help of <a href="https://laracasts.com/series/laravel-5-fundamentals/episodes/11?autoplay=true#" rel="noreferrer">this wondefull website</a>.
For my activity model I want to generate slugs before I save one to my database so I've created the following model.</p>
<pre><code><?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Activity extends Model {
protected $table = 'activitys';
protected $fillable = [
'title',
'text',
'subtitle'
];
// Here I want to auto generate slug based on the title
public function setSlugAttribute(){
$this->attributes['slug'] = str_slug($this->title , "-");
}
//
}
</code></pre>
<p>But when I save an object with help of the Activity model slug is not filled, i tried changing it to $this->attributes['title'] = "test" for testing but it didnt run. Also I tried adding parameters $title, $slug to setSlugAttribute() but it didnt help.</p>
<p>What am I doing wrong and could someone explain the parameter that is used in some examples for setSomeAttribute($whyParameterHere).</p>
<p><em>Note : there is a slug field in my database.</em></p>
<p>As suggested by user3158900 I've tried :</p>
<pre><code>public function setTitleAttribute($title){
$this->title = $title;
$this->attributes['slug'] = str_slug($this->title , "-");
}
//
</code></pre>
<p>This makes my title field empty but saves the slug the way I want it, why is $this->title empty then ?
If I remove $this->title = $title; both title and slug are empty</p> | 30,583,693 | 7 | 0 | null | 2015-06-01 20:23:04.917 UTC | 5 | 2022-05-06 07:20:36.237 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,667,868 | null | 1 | 21 | php|laravel|laravel-5 | 64,301 | <p>I believe this isn't working because you aren't trying to set a slug attribute so that function never gets hit.</p>
<p>I'd suggest setting <code>$this->attributes['slug'] = ...</code> in your <code>setTitleAttribute()</code> function so it runs whenever you set a title.</p>
<p>Otherwise, another solution would be to create an event on save for your model which would set it there.</p>
<p>Edit: According to comments, it's also necessary to actually set the title attribute in this function as well...</p>
<pre><code>public function setTitleAttribute($value)
{
$this->attributes['title'] = $value;
$this->attributes['slug'] = str_slug($value);
}
</code></pre> |
26,771,953 | Return Lambda from Method in Java 8? | <p>I have just begun to use Java 8 and I am wondering if there is a way to write a method that returns a <code>Function</code>?</p>
<p>Right now I have method like below:</p>
<pre><code>Function<Integer, String> getMyFunction() {
return new Function<Integer, String>() {
@Override public String apply(Integer integer) {
return "Hello, world!"
}
}
}
</code></pre>
<p>Is there a way to write that more succinctly in Java 8? I was hoping this would work but it does not:</p>
<pre><code>Function<Integer, String> getMyFunction() {
return (it) -> { return "Hello, world: " + it }
}
</code></pre> | 26,772,000 | 5 | 0 | null | 2014-11-06 04:51:14.233 UTC | 12 | 2016-09-27 07:19:34.417 UTC | 2016-09-14 06:48:08.193 UTC | null | 1,421,925 | null | 364,135 | null | 1 | 40 | java|lambda|java-8 | 73,497 | <p>Get rid of your return statement inside of your function definition:</p>
<pre><code>Function<Integer, String> getMyFunction() {
return (it) -> "Hello, world: " + it;
}
</code></pre> |
36,147,625 | Xcode 7.3 cannot create __weak reference in file using manual reference counting | <p>After updating to Xcode 7.3, it throws the error <code>Cannot create __weak reference in file using manual reference counting</code> in pod files. Has anyone solved this issue?</p> | 36,172,977 | 7 | 0 | null | 2016-03-22 06:33:32.12 UTC | 27 | 2017-12-22 04:53:45.64 UTC | 2017-12-22 04:53:45.64 UTC | null | 212,339 | null | 364,941 | null | 1 | 87 | objective-c|xcode|cocoapods | 36,578 | <p>Set <code>Build Settings -> Apple LLVM 7.1 - Language - Objective C -> Weak References in Manual Retain Release</code> to <code>YES</code>. </p>
<p><img src="https://i.stack.imgur.com/XoM7Q.jpg" alt="Visual example"></p>
<p>Taken from <a href="https://forums.developer.apple.com/thread/38934">Apple Developers Forums - Xcode 7.3b4, non-arc, cannot create __weak reference</a>.</p> |
27,726,354 | iPad remembering camera permissions after delete—how to clear? | <p>I'm trying to recreate the condition where the following code returns <code>AVAuthorizationStatusNotDetermined</code>:</p>
<pre><code>AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
</code></pre>
<p>However, the iPad appears to remember camera permissions even after the app is deleted and reinstalled, and so either Authorized or NotAuthorized is returned every time. Any idea how to reset the permissions so that NotDetermined is returned?</p>
<p>Thanks for reading.</p> | 27,726,409 | 4 | 0 | null | 2014-12-31 21:13:36.343 UTC | 18 | 2021-01-27 15:30:43.213 UTC | 2018-05-18 01:20:00.477 UTC | null | 1,033,581 | null | 1,781,058 | null | 1 | 66 | ios|ipad|permissions|camera|ios-permissions | 14,989 | <p>You can't reset the permission programmatically. If you want to reset the permission there are two ways:</p>
<ol>
<li>Reset the OS</li>
<li>Uninstall the app and wait for a day</li>
</ol>
<p>I know both of those options are really not helpful for a developer, if they are trying to test it out something.</p>
<p>There are three alternatives for testing your app's first run scenario without resetting the entire OS or waiting a day.</p>
<h2><strong>First option</strong></h2>
<p>As described in <a href="https://developer.apple.com/library/ios/technotes/tn2265/_index.html" rel="noreferrer"><strong>Technical Note TN2265</strong></a> :</p>
<blockquote>
<p>You can achieve the latter without actually waiting a day by following these steps:</p>
<ul>
<li>Delete your app from the device.</li>
<li>Turn the device off completely and turn it back on.</li>
<li>Go to Settings > General > Date & Time and set the date ahead a day or more.</li>
<li>Turn the device off completely again and turn it back on.</li>
</ul>
</blockquote>
<h2><strong>Second option</strong></h2>
<p>When you delete an app the iOS keeps the permission of your app mapped to your app's bundle id, it keeps the data for day. So you can also change your app's bundle id to test it out.</p>
<h2><strong>Third Option</strong></h2>
<p>As suggested by @rmaddy in the comment you can reset all location and privacy permissions : Settings -> General -> Reset -> Reset Location & Privacy.
Note that this will reset <strong>all</strong> location and privacy permissions for <strong>all the apps</strong> on that device.</p> |
27,676,884 | Explicitly Specifying types for Express' "application, request, response..." | <p>I'm working to update a simple NodeJS + ExpressJS app to use TypeScript. I've got it working, but I'm having fits adding some extra data annotations to add extra type checking and code-time autocomplete/IntelliSense in Visual Studio & WebStorm.</p>
<p>I've got the latest <a href="https://github.com/borisyankov/DefinitelyTyped/blob/master/express/express.d.ts" rel="noreferrer">express.d.ts</a> referenced. I've also created the Express app:</p>
<pre><code>var app = express();
</code></pre>
<p>Everything works... but I can't seem to figure out how to add the type info for <strong>app</strong> for autocomplete assistance when you type something like </p>
<pre><code>app.get('/',function(req,res){});
</code></pre>
<p>I've tried annotating <strong>app</strong> (and <strong>req</strong> & <strong>res</strong>) using <code>Express.Application</code> (and <code>.Request</code> & <code>.Response</code>) but that isn't resolving. Looking at the type definition I'm getting confused with how the typedef is written creating the internal "e" reference... </p>
<p>Surprised I can't find anyone asking & resolving this since the express.d.ts typedef was updated for ExpressJS 4.0 (previously I found references to <strong>ExpressServer</strong> but that isn't present today.</p>
<p>Ideas?</p> | 27,676,988 | 3 | 0 | null | 2014-12-28 13:32:59.41 UTC | 8 | 2020-08-28 12:13:47.177 UTC | null | null | null | null | 306,347 | null | 1 | 57 | express|typescript | 57,789 | <p><em>Classic case of "work on something for a while with no success, but when you finally post a question asking for help, you figure it out immediately".</em></p>
<p>The solution:
When you want to use one of the types, you have to import the module as the typedef is in a named module within the typedef. </p>
<p>In the above code (that resided in my <strong>app.ts</strong>), I was getting the type annotations on <strong>app</strong>. Because my import statement at the top of the file was <code>import express = require('express');</code>, I could annotate the <strong>req</strong> & <strong>res</strong> params like this:</p>
<pre><code>app.get('/', function(req:express.Request, res:express.Response){});
</code></pre>
<p>In other files, where I was trying to get type annotations on the <strong>app</strong>, I was missing the import statement at the top of the file. Once added, I could add the annotations for that as well like:</p>
<pre><code>public init(app: express.Application){}
</code></pre> |
41,912,313 | Element overflow hidden in React-Native Android | <p>I have an app here where I need to put the logo in the navbar. That need to overflow the scene layout. Work well in Ios with no problem but in android seem like he not working. I put the code at the bottom of the images. As you can see I use EStyleSheet so that let me use %.</p>
<p>IOS</p>
<p><a href="https://i.stack.imgur.com/PFj08.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PFj08.png" alt="enter image description here"></a></p>
<p>Android</p>
<p><a href="https://i.stack.imgur.com/mkzpM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mkzpM.png" alt="enter image description here"></a></p>
<pre><code>import React from 'react';
import { Scene, Router } from 'react-native-router-flux';
import EStyleSheet from 'react-native-extended-stylesheet';
import { View, Platform } from 'react-native';
import { SmallLogo } from './components';
import { checkColor } from './helpers';
import {
HomeScreen,
ImagePickerScreen,
WaitingResponseScreen,
ResultsScreen
} from './modules';
import Colors from '../constants/Colors';
const styles = EStyleSheet.create({
navStyle: {
flex: 1,
marginTop: '5%',
alignItems: 'center',
},
logoCircle: {
backgroundColor: '$whiteColor',
height: 60,
width: 60,
borderRadius: 30,
justifyContent: 'center',
alignItems: 'center'
}
});
const logoNav = result => (
<View style={styles.navStyle}>
<View style={styles.logoCircle}>
<SmallLogo color={checkColor(result)} />
</View>
</View>
);
const pdTop = Platform.OS === 'ios' ? 64 : 54;
export default () => (
<Router
sceneStyle={{ paddingTop: pdTop }}
navigationBarStyle={{ backgroundColor: Colors.greenColor }}
renderTitle={props => {
if (props.result) {
return logoNav(props.result);
}
return logoNav(null);
}}
backButtonTextStyle={{ color: Colors.whiteColor }}
leftButtonIconStyle={{ tintColor: Colors.whiteColor }}
>
<Scene
key="home"
component={HomeScreen}
/>
<Scene
key="imagesPicker"
hideBackImage
component={ImagePickerScreen}
/>
<Scene
key="waitingResponse"
backTitle="Back"
component={WaitingResponseScreen}
/>
<Scene
key="results"
backTitle="Back"
initial
component={ResultsScreen}
/>
</Router>
);
</code></pre> | 41,914,501 | 6 | 0 | null | 2017-01-28 16:52:27.37 UTC | 4 | 2018-12-23 06:49:03.783 UTC | 2017-04-24 03:24:47.357 UTC | null | 5,670,861 | null | 5,670,861 | null | 1 | 17 | android|reactjs|react-native | 55,196 | <p>In Android you cannot draw outside of the component's boundaries, which is a very annoying thing. I usually do the following as a workaround: Wrap your component in a new <code><View></code> that wraps both the former container and the overflowing data. Set the view <code>backgroundColor</code> to <code>'transparent'</code> so that it is invisible, and the <code>pointerEvents</code> prop to <code>'box-none'</code>, so that events get propagated to children. The dimensions of the view should be those of the former top component plus the overflow (in your case, it is just the height), but I think this should also work with Flexbox nicely in some circumstances.</p> |
24,816,237 | ipython notebook clear cell output in code | <p>In a iPython notebook, I have a while loop that listens to a Serial port and <code>print</code> the received data in real time.</p>
<p>What I want to achieve to only show the latest received data (i.e only one line showing the most recent data. no scrolling in the cell output area)</p>
<p>What I need(i think) is to clear the old cell output when I receives new data, and then prints the new data. I am wondering how can I clear old data programmatically ?</p> | 24,818,304 | 6 | 0 | null | 2014-07-18 02:02:56.79 UTC | 39 | 2022-05-09 18:42:59.83 UTC | null | null | null | null | 2,583,917 | null | 1 | 200 | python|ipython|ipython-notebook | 283,773 | <p>You can use <a href="http://ipython.org/ipython-doc/dev/api/generated/IPython.display.html#IPython.display.clear_output" rel="noreferrer"><code>IPython.display.clear_output</code></a> to clear the output of a cell.</p>
<pre><code>from IPython.display import clear_output
for i in range(10):
clear_output(wait=True)
print("Hello World!")
</code></pre>
<p>At the end of this loop you will only see one <code>Hello World!</code>.</p>
<p>Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.