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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,628,742 | What is the difference between ArrayAdapter , BaseAdapter and ListAdapter | <p>Could you please tell me difference between <code>ArrayAdapter</code> , <code>BaseAdapter</code> and <code>ListAdapter</code>.</p> | 11,628,842 | 2 | 0 | null | 2012-07-24 10:18:19.14 UTC | 11 | 2017-08-02 22:15:29.607 UTC | 2015-04-13 08:19:48.583 UTC | null | 1,143,026 | null | 1,143,026 | null | 1 | 40 | android|android-arrayadapter|listadapter|baseadapter | 41,704 | <p><strong><code>BaseAdapter</code></strong> as the name suggests, is a base class for all the adapters.</p>
<p>When you are extending the Base adapter class you need to implement all the methods like <code>getCount()</code>, <code>getId()</code> etc.</p>
<p><strong><code>ArrayAdapter</code></strong> is a class which can work with array of data. You need to override only <code>getview()</code> method.</p>
<p><strong><code>ListAdapter</code></strong> is a an interface implemented by concrete adapter classes.</p>
<p><code>BaseAdapter</code> is an abstract class whereas <code>ArrayAdapter</code> and <code>ListAdapter</code> are the concrete classes.</p>
<p><code>ArrayAdapter</code> and <code>ListAdapter</code> classes are developed since in general we deal with the array data sets and list data sets.</p> |
11,631,443 | Capturing process output via OutputDataReceived event | <p>I'm trying to capture process output in "realtime" (while it's running). The code I use is rather simple (see below). For some strange reason the OutputDataReceived event is never called. Why?</p>
<pre><code>private void button2_Click(object sender, EventArgs e)
{
// Setup the process start info
var processStartInfo = new ProcessStartInfo("ping.exe", "-t -n 3 192.168.100.1")
{
UseShellExecute = false,
RedirectStandardOutput = true
};
// Setup the process
mProcess = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true };
// Register event
mProcess.OutputDataReceived += OnOutputDataReceived;
// Start process
mProcess.Start();
mProcess.WaitForExit();
}
void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
//Never gets called...
}
</code></pre> | 11,632,538 | 2 | 0 | null | 2012-07-24 13:02:26.473 UTC | 5 | 2017-12-07 16:17:37.293 UTC | null | null | null | null | 619,774 | null | 1 | 57 | c#|process|stdout | 39,819 | <p>You need to call </p>
<pre><code>mProcess.BeginOutputReadLine();
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline" rel="noreferrer">BeginOutputReadLine</a> - "Begins asynchronous read operations on the redirected StandardOutput stream of the application."</p> |
4,009,536 | Concurrent programming techniques, pros, cons | <p>There is at least three well-known approaches for creating concurrent applications:</p>
<ol>
<li><p>Multithreading and memory synchronization through locking(.NET, Java). Software Transactional Memory (<a href="http://en.wikipedia.org/wiki/Software_transactional_memory" rel="noreferrer">link text</a>) is another approach to synchronization.</p></li>
<li><p>Asynchronous message passing (Erlang).</p></li>
</ol>
<p>I would like to learn if there are other approaches and discuss various pros and cons of these approaches applied to large distributed applications. My main focus is on simplifying life of the programmer.</p>
<p>For example, in my opinion, using multiple threads is easy when there is no dependencies between them, which is pretty rare. In all other cases thread synchronization code becomes quite cumbersome and hard to debug and reason about. </p> | 4,009,708 | 4 | 7 | null | 2010-10-24 17:48:52.897 UTC | 13 | 2010-12-28 14:18:35.943 UTC | 2010-10-25 15:00:02.59 UTC | user166010 | null | user166010 | null | null | 1 | 21 | java|.net|concurrency|erlang | 3,727 | <p>I'd strongly recommend looking at <a href="http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey" rel="nofollow">this presentation</a> by Rich Hickey. It describes an approach to building high performance, concurrent applications which I would argue is distinct from lock-based or message-passing designs.</p>
<p>Basically it emphasises:</p>
<ul>
<li>Lock free, multi-threaded concurrent applications</li>
<li>Immutable persistent data structures</li>
<li>Changes in state handled by Software Transactional Memory</li>
</ul>
<p>And talks about how these principles influenced the design of the <a href="http://clojure.org/" rel="nofollow">Clojure</a> language.</p> |
3,900,153 | PHP Multiple Curl Requests | <p>I'm currently using Curl for PHP a lot. It takes a lot of time to get results of about 100 pages each time. For every request i'm using code like this</p>
<pre><code>$ch = curl_init();
// get source
curl_close($ch);
</code></pre>
<p>What are my options to speed things up?</p>
<p>How should I use the <code>multi_init()</code> etc?</p> | 3,900,160 | 4 | 1 | null | 2010-10-10 11:44:12.237 UTC | 8 | 2019-07-12 19:07:25.563 UTC | 2019-07-12 19:07:25.563 UTC | null | 5,198,305 | null | 470,433 | null | 1 | 35 | php|curl|curl-multi | 71,364 | <ul>
<li>Reuse the same cURL handler ($ch) without running curl_close. This will speed it up just a little bit.</li>
<li>Use <a href="http://php.net/curl_multi_init" rel="noreferrer">curl_multi_init</a> to run the processes in parallel. This can have a tremendous effect.</li>
</ul> |
3,737,985 | ASP.NET MVC MultiSelectList with selected values not selecting properly | <p>I know others have asked this question, but I'm totally confused by this:</p>
<p>This displays the dropdown with no values selected:</p>
<pre><code><%= Html.DropDownList("items", new MultiSelectList(Model.AvailableItems,
"id", "name", Model.items), new { multiple = "multiple" })%>
</code></pre>
<p>This displays the dropdown with the values that I'm passing in (Model.items) selected properly like what I'd expect:</p>
<pre><code><%= Html.DropDownList("somethingelse", new MultiSelectList(Model.AvailableItems,
"id", "name", Model.items), new { multiple = "multiple" })%>
</code></pre>
<p>But the problem is that this item is now named "somethingelse" when i POST. I know I can hack around this but what's going?</p> | 3,763,711 | 6 | 2 | null | 2010-09-17 18:33:54.99 UTC | 12 | 2018-04-02 13:14:13.143 UTC | null | null | null | null | 39,034 | null | 1 | 28 | asp.net-mvc | 58,900 | <p>The problem you have is using Model.Items as a parameter. The code </p>
<pre><code><%= Html.DropDownList("items", new MultiSelectList(Model.AvailableItems,
"id", "name", Model.items), new { multiple = "multiple" })%>
</code></pre>
<p>isn't actually working as you would expect. It's working because the name of the dropdown is "items". That's because there was a form param called "items" posted back to your action. That param gets stored in the action's ViewState (don't confuse with ViewData).
The Html.DropdownList() sees that there is a ViewState param named the same as you have named your dropdown and uses that ViewState param to work out the selected values. <strong>It completely ignores the Model.items that you passed in.</strong></p>
<p>If anyone can explain the logic of not being able to override the default behavior then I'd love to hear it.</p>
<p>So, that's your first problem. To get around it all you have to do is to rename the dropdown to something else - exactly like you did in your second example. Now your second problem comes into play: the list of selected items must be a collection of simple objects (I think it actually needs to be an IEnumerable but I'm not 100% sure).</p>
<p>The DropDownList() method will try and match those selected values to the Value in your <code>AvailableItems</code> collection. If it can't do that it will try to match against the Text.</p>
<p>So, try this to see if it works</p>
<pre><code><%= Html.DropDownList("somethingelse", new MultiSelectList(Model.AvailableItems,
"id", "name", Model.items.Select(c=> c.name)), new { multiple = "multiple" })%>
</code></pre>
<p>Good luck</p> |
3,307,090 | how to add background image to activity? | <p>using theme or ImageView ?</p> | 3,307,132 | 7 | 0 | null | 2010-07-22 08:39:28.8 UTC | 16 | 2021-11-04 14:04:57.84 UTC | null | null | null | null | 281,887 | null | 1 | 78 | android|image|background | 409,600 | <p>use the <code>android:background</code> attribute in your xml. Easiest way if you want to apply it to a whole activity is to put it in the root of your layout. So if you have a RelativeLayout as the start of your xml, put it in here:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootRL"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
</RelativeLayout>
</code></pre> |
3,790,379 | How to query a CLOB column in Oracle | <p>I'm trying to run a query that has a few columns that are a CLOB datatype. If i run the query like normal, all of those fields just have <code>(CLOB)</code> as the value.</p>
<p>I tried using <code>DBMS_LOB.substr(column</code>) and i get the error </p>
<pre><code>ORA-06502: PL/SQL: numeric or value error: character string buffer too small
</code></pre>
<p>How can i query the CLOB column?</p> | 3,790,523 | 8 | 1 | null | 2010-09-24 19:35:43.853 UTC | 9 | 2020-06-23 05:46:48.57 UTC | 2010-09-24 19:48:36.577 UTC | null | 411,247 | null | 222,403 | null | 1 | 57 | sql|oracle|plsql|clob|ora-06502 | 505,440 | <p>When getting the substring of a CLOB column and using a query tool that has size/buffer restrictions sometimes you would need to set the BUFFER to a larger size. For example while using SQL Plus use the <code>SET BUFFER 10000</code> to set it to 10000 as the default is 4000.</p>
<p>Running the <code>DBMS_LOB.substr</code> command you can also specify the amount of characters you want to return and the offset from which. So using <code>DBMS_LOB.substr(column, 3000)</code> might restrict it to a small enough amount for the buffer.</p>
<p>See <a href="http://download-west.oracle.com/docs/cd/A87860_01/doc/appdev.817/a76936/dbms_lo2.htm#1009072" rel="noreferrer">oracle documentation</a> for more info on the substr command</p>
<pre>
DBMS_LOB.SUBSTR (
lob_loc IN CLOB CHARACTER SET ANY_CS,
amount IN INTEGER := 32767,
offset IN INTEGER := 1)
RETURN VARCHAR2 CHARACTER SET lob_loc%CHARSET;
</pre> |
3,972,854 | Parse Math Expression | <p>Is there an easy way to parse a simple math expression represented as a string such as (x+(2*x)/(1-x)), provide a value for x, and get a result?</p>
<p>I looked at the VSAEngine per several online examples, however, I am getting a warning that this assembly has been deprecated and not to use it.</p>
<p>If it makes any differences, I am using .NET 4.0.</p> | 3,972,939 | 9 | 1 | null | 2010-10-19 21:19:13.523 UTC | 9 | 2022-03-14 13:36:01.593 UTC | 2013-04-30 15:26:00.043 UTC | null | 337,759 | null | 214,048 | null | 1 | 14 | c#|.net|c#-4.0 | 47,869 | <p>You can try using <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.compute.aspx" rel="nofollow noreferrer">DataTable.Compute</a>.</p>
<p>A related one is <a href="http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx" rel="nofollow noreferrer">DataColumn.Expression</a>.</p>
<p>Also check out: <a href="https://stackoverflow.com/questions/1452282/doing-math-in-vb-net-like-eval-in-javascript">Doing math in vb.net like Eval in javascript</a></p>
<p>Note: I haven't used these myself.</p> |
3,581,510 | WordPress hook directly after body tag | <p>I'm having problems finding the right hook to use for my plugin. I'm trying to add a message to the top of each page by having my plugin add a function. What's the best hook to use? I want to insert content right after the <code><body></code> tag.</p>
<hr>
<p>EDIT: I know it's three years later now, but here is a <a href="http://en.wikipedia.org/wiki/Trac" rel="noreferrer">Trac</a> ticket for anyone who is interested: <a href="http://core.trac.wordpress.org/ticket/12563" rel="noreferrer">http://core.trac.wordpress.org/ticket/12563</a></p>
<hr>
<p><strong>EDIT: July 31st, 2019</strong></p>
<p>The linked <a href="https://core.trac.wordpress.org/ticket/12563" rel="noreferrer">Trac Ticket</a> was closed as this feature was added in WordPress 5.2. You will find the Developer notes for this feature here (requires JavaScript enabled to display):</p>
<p><em><a href="https://make.wordpress.org/core/2019/04/24/miscellaneous-developer-updates-in-5-2/" rel="noreferrer">Miscellaneous Developer Updates in 5.2</a></em></p>
<p>I will not update the "correct answer" to one that mentions 5.2 for historical reasons, but rest assured that I'm aware and that the built-in hook is the correct one to use.</p> | 3,581,527 | 9 | 4 | null | 2010-08-27 05:20:45.207 UTC | 7 | 2020-04-16 09:23:00.743 UTC | 2019-11-23 22:04:59.62 UTC | null | 63,550 | null | 172,964 | null | 1 | 34 | php|wordpress | 69,192 | <h1>WordPress 5.2 or newer:</h1>
<p>Use the <a href="https://developer.wordpress.org/reference/functions/wp_body_open/" rel="noreferrer">wp_body_open</a> hook.</p>
<h1>WordPress 5.1 or older:</h1>
<p>That's kinda difficult... Most themes don't have any hooks in that area. You could hook a javascript/html solution into <code>wp_footer</code> and display it at the top of the page... sort of how Stack Overflow does it, or how Twitter does their notifications.</p>
<p>This is the best reference for all the hooks included in WordPress:
<a href="http://adambrown.info/p/wp_hooks/" rel="noreferrer">http://adambrown.info/p/wp_hooks/</a></p> |
3,553,779 | Android dismiss keyboard | <p>How do I dismiss the keyboard when a button is pressed?</p> | 3,553,811 | 10 | 1 | null | 2010-08-24 05:25:18.797 UTC | 25 | 2022-05-22 18:57:35.66 UTC | 2017-03-04 02:47:12.043 UTC | null | 1,926,291 | null | 454,665 | null | 1 | 156 | android | 73,050 | <p>You want to disable or dismiss a virtual Keyboard?</p>
<p>If you want to just dismiss it you can use the following lines of code in your button's on click Event</p>
<pre><code>InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
</code></pre> |
3,362,553 | What's harder, synchronizing 2 threads or 1000 threads? | <p>On Paul Tyma's <a href="http://www.mailinator.com/tymaPaulMultithreaded.pdf" rel="nofollow noreferrer">presentation</a>, I found an interview question:</p>
<blockquote>
<p>What's harder, synchronizing 2 threads or synchronizing 1000 threads?</p>
</blockquote>
<p>From my perspective, of course synchronizing 1000 threads is harder, but I can't think of a good reasons for that beside 'of course'. But since it's <em>interview question</em>, may be I'm wrong (interview questions have to be tricky, isn't it?).</p> | 3,362,586 | 14 | 2 | null | 2010-07-29 12:45:39.03 UTC | 12 | 2010-08-03 08:52:58.31 UTC | 2010-07-29 14:02:28.253 UTC | null | 193,653 | null | 153,621 | null | 1 | 11 | java|multithreading|synchronization | 2,960 | <p>Synchronizing a thousand threads is just as easy as synchronizing two threads: just lock access to all important data.</p>
<p>Now, synchronizing a thousand threads <strong>with good performance</strong> is more difficult. If I were asking this question, I'd look for answers mentioning "the thundering herd problem", "lock contention", "lock implementation scalability", "avoiding spinlocks", etc.</p> |
3,653,065 | Get local IP address in Node.js | <p>I have a simple Node.js program running on my machine and I want to get the local IP address of a PC on which my program is running. How do I get it with Node.js?</p> | 8,440,736 | 41 | 2 | null | 2010-09-06 16:51:13.293 UTC | 107 | 2022-05-21 01:06:21.157 UTC | 2020-12-21 18:30:31.257 UTC | null | 63,550 | null | 217,288 | null | 1 | 400 | javascript|node.js|ip | 511,441 | <p>This information can be found in <a href="https://nodejs.org/api/os.html#os_os_networkinterfaces" rel="noreferrer"><code>os.networkInterfaces()</code></a>, — an object, that maps network interface names to its properties (so that one interface can, for example, have several addresses):</p>
<pre class="lang-js prettyprint-override"><code>'use strict';
const { networkInterfaces } = require('os');
const nets = networkInterfaces();
const results = Object.create(null); // Or just '{}', an empty object
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
// Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
// 'IPv4' is in Node <= 17, from 18 it's a number 4 or 6
const familyV4Value = typeof net.family === 'string' ? 'IPv4' : 4
if (net.family === familyV4Value && !net.internal) {
if (!results[name]) {
results[name] = [];
}
results[name].push(net.address);
}
}
}
</code></pre>
<pre class="lang-json prettyprint-override"><code>// 'results'
{
"en0": [
"192.168.1.101"
],
"eth0": [
"10.0.0.101"
],
"<network name>": [
"<ip>",
"<ip alias>",
"<ip alias>",
...
]
}
</code></pre>
<pre class="lang-json prettyprint-override"><code>// results["en0"][0]
"192.168.1.101"
</code></pre> |
8,010,120 | Specifying exact percentage widths in relation to parent DIV in CSS | <p>I am attempting to create a visual element using DIV elements and CSS which should display data in the format demonstrated below.</p>
<p>[-----50%-----|--25%--|--25%--]</p>
<p>When using the code and CSS I've specified below, my final element always spills onto the next line and the CSS percentage values I'm specifying don't seem to create the layout properly.</p>
<p>Could anybody suggest a better way to do this?</p>
<p><strong>My HTML</strong></p>
<pre><code><div class="visual-indicator-title">
All Items</div>
<div class="visual-indicator-holder">
<div class="vi-internal-element" style="width: 25%; background-color: #5E9BD1;">
25%</div>
<div class="vi-internal-element" style="width: 25%; background-color: #AB884D;">
25%</div>
<div class="vi-internal-element" style="width: 50%;">
50%</div>
</div>
<div class="visual-legend">
<ul class="inline-block">
<li>
<div class="legend-blue">
</div>
Sales</li>
<li><span class="legend-tan"></span>Processed</li>
<li><span class="legend-grey"></span>Pending Processing</li>
</ul>
</code></pre>
<p></p>
<p><strong>My CSS</strong></p>
<pre><code>.visual-indicator-title{
font-size:12px;
font-weight:bold;
color:#777777;
}
.visual-indicator-holder
{
width:100%;
background-color:#666666;
height:28px;
border-radius: 8px;
}
.visual-indicator-holder .vi-internal-element
{
font-size:11px;
text-align:center;
color:#ffffff;
background-color:#777777;
border-radius: 6px;
display:inline-block;
}
</code></pre> | 8,010,313 | 4 | 0 | null | 2011-11-04 13:45:37.337 UTC | 5 | 2011-11-08 00:11:18.377 UTC | 2011-11-08 00:11:18.377 UTC | null | 106,224 | null | 598,247 | null | 1 | 25 | css | 47,827 | <p>The reason this happens is that with <code>inline</code> or <code>inline-block</code>, white space in the element will affect the rendering (adds space). Here is your demo working with white space removed, no changes to the CSS: <a href="http://jsfiddle.net/fZXnU/" rel="noreferrer">http://jsfiddle.net/fZXnU/</a></p>
<p>Removing white space is not trivial though, so you'd be better off floating the elements (which triggers <code>display:block</code>). Working demo with plenty of white space: <a href="http://jsfiddle.net/fZXnU/1/" rel="noreferrer">http://jsfiddle.net/fZXnU/1/</a></p> |
8,339,988 | Performance of LINQ Any vs FirstOrDefault != null | <p>There are multiple places in an Open Source Project (OSP) code I contribute, where it has to be determined if an element in a collection satisfies a certain condition.</p>
<p>I've seen the use of LINQ expression <code>Any(lambda expression)</code> in some cases and <code>FirstOrDefault(lambda expression) != null</code> in others but never given a thought about it.</p>
<p>I have reached now a point where I have to do some iterations to collections made from queries to a DB and want to optimize the runtime.</p>
<p>So I figured that <code>FirstOrDefault(lambda expression) != null</code> should be faster than <code>Any(lambda expression)</code>,right?</p>
<p>In the case of <code>FirstOrDefault(lambda expression) != null</code>, the iteration (probably) stops when it finds an element that satisfies the condition (worse case scenario it iterates through the entire collection and returns <code>null</code>).</p>
<p>In the case of <code>Any(lambda expression)</code> I imagine that the iteration continues to the end of the collection even if an element that satisfies the condition is found.</p>
<p>Edit: The above is not true as Jackson Pope mentioned and linked the related MSDN article.</p>
<p>Are my thoughts correct or am I missing something?</p> | 8,340,035 | 7 | 3 | null | 2011-12-01 10:41:50.11 UTC | 8 | 2020-02-01 23:27:01.867 UTC | 2016-02-06 18:37:57.767 UTC | null | 934,625 | null | 934,625 | null | 1 | 51 | c#|linq | 42,826 | <p>The enumeration in <code>Any()</code> stops as soon as it finds a matching item as well:</p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any" rel="noreferrer">https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any</a></p>
<p>I would expect the performance to be very similar. Note that the <code>FirstOrDefault</code> version won't work with a collection of value types (since the default isn't null) but the <code>Any</code> version would.</p> |
7,755,240 | List distinct values in a vector in R | <p>How can I list the distinct values in a vector where the values are replicative? I mean, similarly to the following SQL statement:</p>
<pre><code>SELECT DISTINCT product_code
FROM data
</code></pre> | 7,755,396 | 7 | 0 | null | 2011-10-13 13:57:24.907 UTC | 14 | 2021-04-27 08:40:39.737 UTC | 2020-01-21 13:59:47.217 UTC | null | 680,068 | null | 192,377 | null | 1 | 113 | r|vector|distinct-values|r-faq | 263,552 | <p>Do you mean <code>unique</code>:</p>
<pre><code>R> x = c(1,1,2,3,4,4,4)
R> x
[1] 1 1 2 3 4 4 4
R> unique(x)
[1] 1 2 3 4
</code></pre> |
7,901,360 | Delete last char of string | <p>I am retrieving a lot of information in a list, linked to a database and I want to create a string of groups, for someone who is connected to the website.</p>
<p>I use this to test but this is not dynamic, so it is really bad:</p>
<pre><code>string strgroupids = "6";
</code></pre>
<p>I want to use this now. But the string returned is something like <code>1,2,3,4,5,</code></p>
<pre><code>groupIds.ForEach((g) =>
{
strgroupids = strgroupids + g.ToString() + ",";
strgroupids.TrimEnd(',');
});
strgroupids.TrimEnd(new char[] { ',' });
</code></pre>
<p>I want to delete the <code>,</code> after the <code>5</code> but it's definitely not working. </p> | 7,901,378 | 12 | 1 | null | 2011-10-26 10:20:45.65 UTC | 44 | 2022-03-03 13:29:20.85 UTC | 2019-04-25 15:27:21.543 UTC | null | 1,536,976 | null | 1,005,335 | null | 1 | 328 | c#|string|char | 575,143 | <pre><code>strgroupids = strgroupids.Remove(strgroupids.Length - 1);
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.string.remove.aspx" rel="noreferrer">MSDN:</a></p>
<blockquote>
<p><strong>String.Remove(Int32):</strong></p>
<p>Deletes all the characters from this string beginning at a specified
position and continuing through the last position</p>
</blockquote> |
4,349,202 | Let user download a XML file | <p>I have prepared an XML string in PHP and I would like to let the user download the string in an XML file.</p>
<p>Is it possible to offer the user the download (e.g. text.xml) without physically saving the xml file to the server?</p> | 4,349,224 | 3 | 0 | null | 2010-12-03 19:34:17.957 UTC | 3 | 2021-09-03 09:20:14.437 UTC | 2011-08-18 12:25:57.013 UTC | null | 328,193 | null | 508,666 | null | 1 | 14 | php|header | 42,837 | <pre><code><?php
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="text.xml"');
echo $xml_contents;
</code></pre> |
4,722,998 | Python: Regular expression to match alpha-numeric not working? | <p>I am looking to match a string that is inputted from a website to check if is alpha-numeric and possibly contains an underscore.
My code:</p>
<pre><code>if re.match('[a-zA-Z0-9_]',playerName):
# do stuff
</code></pre>
<p>For some reason, this matches with crazy chars for example: nIg○▲ ☆ ★ ◇ ◆</p>
<p>I only want regular A-Z and 0-9 and _ matching, is there something i am missing here?</p> | 4,723,154 | 3 | 0 | null | 2011-01-18 10:31:13.853 UTC | 4 | 2014-05-04 00:46:16.7 UTC | null | null | null | null | 368,699 | null | 1 | 52 | python|regex | 95,277 | <p>Python has a special sequence <code>\w</code> for matching alphanumeric and underscore when the <code>LOCALE</code> and <code>UNICODE</code> flags are not specified. So you can modify your pattern as,</p>
<p><code>pattern = '^\w+$'</code></p> |
4,757,178 | How do you set your pythonpath in an already-created virtualenv? | <p>What file do I edit, and how? I created a virtual environment.</p> | 4,758,351 | 6 | 3 | null | 2011-01-21 09:24:23.08 UTC | 59 | 2020-12-31 19:22:31.907 UTC | 2013-01-28 03:36:51.35 UTC | null | 140,827 | null | 179,736 | null | 1 | 134 | python|linux|unix|virtualenv | 177,772 | <p>The most elegant solution to this problem is <a href="https://stackoverflow.com/a/47184788/237059">here</a>.</p>
<p>Original answer remains, but this is a messy solution:</p>
<hr />
<p>If you want to change the <code>PYTHONPATH</code> used in a virtualenv, you can add the following line to your virtualenv's <code>bin/activate</code> file:</p>
<pre><code>export PYTHONPATH="/the/path/you/want"
</code></pre>
<p>This way, the new <code>PYTHONPATH</code> will be set each time you use this virtualenv.</p>
<p><strong>EDIT:</strong> <em>(to answer @RamRachum's comment)</em></p>
<p>To have it restored to its original value on <code>deactivate</code>, you could add</p>
<pre><code>export OLD_PYTHONPATH="$PYTHONPATH"
</code></pre>
<p>before the previously mentioned line, and add the following line to your <code>bin/postdeactivate</code> script.</p>
<pre><code>export PYTHONPATH="$OLD_PYTHONPATH"
</code></pre> |
4,465,872 | Why does typeid.name() return weird characters using GCC and how to make it print unmangled names? | <p>How come when I run this <code>main.cpp</code>:</p>
<pre><code>#include <iostream>
#include <typeinfo>
using namespace std;
struct Blah {};
int main() {
cout << typeid(Blah).name() << endl;
return 0;
}
</code></pre>
<p>By compiling it with GCC version 4.4.4:</p>
<pre><code>g++ main.cpp
</code></pre>
<p>I get this:</p>
<pre><code>4Blah
</code></pre>
<p>On Visual C++ 2008, I would get:</p>
<pre><code>struct Blah
</code></pre>
<p>Is there a way to make it just print <code>Blah</code> or <code>struct Blah</code>?</p> | 4,465,907 | 7 | 2 | null | 2010-12-16 22:13:32.503 UTC | 30 | 2021-03-09 05:46:22.617 UTC | 2015-06-05 13:01:42.227 UTC | null | 895,245 | null | 65,313 | null | 1 | 54 | c++|gcc|g++|rtti | 49,949 | <p>The return of <code>name</code> is implementation defined : an implementation is not even required to return different strings for different types.</p>
<p>What you get from g++ is a <a href="http://en.wikipedia.org/wiki/Name_mangling" rel="noreferrer">decorated name</a>, that you can "demangle" using the <a href="http://sourceware.org/binutils/docs-2.16/binutils/c_002b_002bfilt.html" rel="noreferrer"><code>c++filt</code></a> command or <a href="http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html" rel="noreferrer"><code>__cxa_demangle</code></a>.</p> |
4,611,122 | How to implement reCaptcha for ASP.NET MVC? | <p>How do I implement reCaptcha in ASP.NET MVC and C#?</p> | 4,611,154 | 8 | 0 | null | 2011-01-06 02:00:51.82 UTC | 27 | 2020-12-28 13:25:12.167 UTC | 2011-01-07 01:43:32.593 UTC | null | 16,587 | null | 397,524 | null | 1 | 83 | c#|asp.net|asp.net-mvc-2 | 117,615 | <p>There are a few great examples:</p>
<ul>
<li><a href="http://mvcrecaptcha.codeplex.com/" rel="nofollow noreferrer">MVC reCaptcha</a> - making reCaptcha more MVC'ish.</li>
<li><a href="http://www.dotnetcurry.com/ShowArticle.aspx?ID=611&AspxAutoDetectCookieSupport=1" rel="nofollow noreferrer">ReCaptcha Webhelper in ASP.NET MVC 3</a></li>
<li><a href="http://code.google.com/p/recaptcha/source/browse/trunk/recaptcha-plugins/dotnet/library/RecaptchaControlMvc.cs?r=125" rel="nofollow noreferrer">ReCaptcha Control for ASP.NET MVC</a> from Google Code.</li>
</ul>
<p>This has also been covered before in <a href="https://stackoverflow.com/questions/1178305/asp-net-mvc-and-recaptcha-action">this Stack Overflow question</a>.</p>
<p>NuGet <strong>Google reCAPTCHA V2</strong> for MVC 4 and 5</p>
<ul>
<li><a href="https://www.nuget.org/packages/reCAPTCH.MVC/" rel="nofollow noreferrer">NuGet Package</a></li>
<li><a href="http://recaptchamvc.apphb.com/" rel="nofollow noreferrer">Demo And Document</a></li>
</ul> |
4,337,902 | How to fill OpenCV image with one solid color? | <p>How to fill OpenCV image with one solid color?</p> | 4,339,441 | 9 | 0 | null | 2010-12-02 17:28:17.267 UTC | 6 | 2021-02-17 19:07:58.737 UTC | 2012-06-11 20:58:46.217 UTC | null | 744,859 | null | 434,051 | null | 1 | 87 | image-processing|opencv | 169,323 | <p>Using the OpenCV C API with <code>IplImage* img</code>: </p>
<p>Use <a href="http://opencv.willowgarage.com/documentation/operations_on_arrays.html?highlight=cvset#cvSet" rel="noreferrer">cvSet()</a>: <code>cvSet(img, CV_RGB(redVal,greenVal,blueVal));</code></p>
<p>Using the OpenCV C++ API with <code>cv::Mat img</code>, then use either: </p>
<p><a href="http://docs.opencv.org/modules/core/doc/basic_structures.html?highlight=setto#mat-operator" rel="noreferrer"><code>cv::Mat::operator=(const Scalar& s)</code></a> as in: </p>
<pre><code>img = cv::Scalar(redVal,greenVal,blueVal);
</code></pre>
<p>or <a href="http://docs.opencv.org/modules/core/doc/basic_structures.html?highlight=setto#Mat&%20Mat::setTo%28InputArray%20value,%20InputArray%20mask%29" rel="noreferrer">the more general, mask supporting, <code>cv::Mat::setTo()</code></a>: </p>
<pre><code>img.setTo(cv::Scalar(redVal,greenVal,blueVal));
</code></pre> |
4,427,234 | Get column index from label in a data frame | <p>Say we have the following data frame:</p>
<pre><code>> df
A B C
1 1 2 3
2 4 5 6
3 7 8 9
</code></pre>
<p>We can select column 'B' from its index:</p>
<pre><code>> df[,2]
[1] 2 5 8
</code></pre>
<p>Is there a way to get the index (2) from the column label ('B')?</p> | 4,427,459 | 10 | 1 | null | 2010-12-13 09:09:31.993 UTC | 44 | 2022-04-08 23:10:19.153 UTC | null | null | null | null | 488,719 | null | 1 | 97 | r | 223,619 | <p>you can get the index via <code>grep</code> and <code>colnames</code>:</p>
<pre><code>grep("B", colnames(df))
[1] 2
</code></pre>
<p>or use </p>
<pre><code>grep("^B$", colnames(df))
[1] 2
</code></pre>
<p>to only get the columns called "B" without those who contain a B e.g. "ABC".</p> |
14,767,167 | Substring from NSString | <p>I am using <code>NSString</code> and I want to get a substring of it that contains the first 20 characters of my string. How can I do that?</p> | 14,767,218 | 5 | 3 | null | 2013-02-08 06:46:22.007 UTC | 7 | 2013-07-11 00:16:51.783 UTC | 2013-07-11 00:16:51.783 UTC | null | 23,897 | null | 1,661,811 | null | 1 | 18 | ios|nsstring|substring | 49,197 | <p>You can use <code>substringToIndex</code>.</p>
<pre><code>NSString *mystring = @"This is a test message having more than 20 characters";
NSString *newString = [mystring substringToIndex:20];
NSLog(@"%@", newString);
</code></pre> |
1,615,117 | PowerShell script not accepting $ (dollar) sign | <p>I am trying to open an SQL data connection using a PowerShell script and my password contains a <code>$</code> sign:</p>
<pre><code>$cn = new-object system.data.SqlClient.SqlConnection("Data Source=DBNAME;Initial Catalog=Catagory;User ID=User;Password=pass$word;")
</code></pre>
<p>When I try to open a connection it says:</p>
<blockquote>
<p>Login failed</p>
</blockquote> | 1,615,145 | 1 | 0 | null | 2009-10-23 18:18:50.697 UTC | 10 | 2019-02-11 13:35:57.833 UTC | 2019-02-11 13:33:14.093 UTC | null | 63,550 | null | 24,958 | null | 1 | 106 | powershell|escaping | 70,549 | <p>Escape it by using backtick (`) as an escape character for the dollar sign ($).</p>
<p>Also, try to enclose the statement in single-quotes instead of the double-quotes you are using now.</p> |
27,077,357 | Can I install Xcode 6 on Mavericks? | <p>Is possible install Xcode 6 on a Mac running OS X Mavericks or do I need upgrade to Yosemite? With Xcode 5, it was necessary to upgrade from Mountain Lion to Mavericks.</p> | 27,077,403 | 3 | 0 | null | 2014-11-22 12:25:58.98 UTC | null | 2015-10-24 01:19:44.733 UTC | 2014-11-22 12:40:54.22 UTC | null | 1,549,818 | null | 832,424 | null | 1 | 9 | macos|xcode6|osx-mavericks | 51,914 | <p>You can install Xcode 6.2 on Maverick provided the OS X version is 10.9.5 at least.</p>
<p>The downloads for older Xcode versions can be found here: <a href="https://stackoverflow.com/a/10335943">https://stackoverflow.com/a/10335943</a></p> |
17,722,641 | Spring @SessionAttribute how to retrieve the session object in same controller | <p>I am using Spring 3.2.0 MVC. In that I have to store one object to session.
Currently I am using HttpSession set and get attribute to store and retrieve the value.</p>
<p>It returns only the String not Object. I want to use @SessionAttribute when I tried it sets the object in session but I could not retrieve the session object</p>
<pre><code> @RequestMapping(value = "/sample-login", method = RequestMethod.POST)
public String getLoginClient(HttpServletRequest request,ModelMap modelMap) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
User user = sample.createClient(userName, password);
modelMap.addAttribute("userObject", user);
return "user";
}
@RequestMapping(value = "/user-byName", method = RequestMethod.GET)
public
@ResponseBody
String getUserByName(HttpServletRequest request,@ModelAttribute User user) {
String fas= user.toString();
return fas;
}
</code></pre>
<p>Both methods are in same controller. How would I use this to retrieve the object?</p> | 17,723,028 | 1 | 2 | null | 2013-07-18 11:49:11.127 UTC | 11 | 2017-03-24 22:04:07.623 UTC | 2017-03-24 22:04:07.623 UTC | null | 13,302 | null | 1,577,467 | null | 1 | 11 | java|spring|spring-mvc | 60,223 | <p><code>@SessionAttributes</code> annotation are used on the class level to :</p>
<ol>
<li>Mark a model attribute should be persisted to HttpSession <strong>after handler methods are executed</strong></li>
<li>Populate your model with previously saved object from HttpSession <strong>before handler methods are executed -- if one do exists</strong></li>
</ol>
<p>So you can use it alongside your <code>@ModelAttribute</code> annotation like in this example:</p>
<pre><code>@Controller
@RequestMapping("/counter")
@SessionAttributes("mycounter")
public class CounterController {
// Checks if there's a model attribute 'mycounter', if not create a new one.
// Since 'mycounter' is labelled as session attribute it will be persisted to
// HttpSession
@RequestMapping(method = GET)
public String get(Model model) {
if(!model.containsAttribute("mycounter")) {
model.addAttribute("mycounter", new MyCounter(0));
}
return "counter";
}
// Obtain 'mycounter' object for this user's session and increment it
@RequestMapping(method = POST)
public String post(@ModelAttribute("mycounter") MyCounter myCounter) {
myCounter.increment();
return "redirect:/counter";
}
}
</code></pre>
<p>Also don't forget common noobie pitfall: make sure you make your session objects Serializable.</p> |
30,606,360 | subtract value from previous row by group | <p>In R, let's say I have this data frame:</p>
<pre><code>Data
id date value
2380 10/30/12 21.01
2380 10/31/12 22.04
2380 11/1/12 22.65
2380 11/2/12 23.11
20100 10/30/12 35.21
20100 10/31/12 37.07
20100 11/1/12 38.17
20100 11/2/12 38.97
20103 10/30/12 57.98
20103 10/31/12 60.83
</code></pre>
<p>And I want to subtract the previous value from the current value, by group ID date, to create this:</p>
<pre><code>id date value diff
2380 10/30/12 21.01 0
2380 10/31/12 22.04 1.03
2380 11/1/12 22.65 0.61
2380 11/2/12 23.11 0.46
20100 10/30/12 35.21 0
20100 10/31/12 37.07 1.86
20100 11/1/12 38.17 1.1
20100 11/2/12 38.97 0.8
20103 10/30/12 57.98 0
20103 10/31/12 60.83 2.85
</code></pre> | 30,606,691 | 3 | 0 | null | 2015-06-02 20:51:48.183 UTC | 24 | 2022-09-06 07:47:43.67 UTC | 2018-10-02 04:56:36.493 UTC | null | 3,962,914 | null | 4,013,612 | null | 1 | 55 | r|dataframe|lag | 61,279 | <p>With <code>dplyr</code>:</p>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
data %>%
group_by(id) %>%
arrange(date) %>%
mutate(diff = value - lag(value, default = first(value)))
</code></pre>
<p>For clarity you can <code>arrange</code> by <code>date</code> and grouping column (as per <a href="https://stackoverflow.com/questions/30606360/in-r-subtract-value-from-previous-row-by-group-and-date/30606691#comment80951330_30606691">comment</a> by <a href="https://stackoverflow.com/users/2583119/lawyer">lawyer</a>)</p>
<pre class="lang-r prettyprint-override"><code>data %>%
group_by(id) %>%
arrange(date, .by_group = TRUE) %>%
mutate(diff = value - lag(value, default = first(value)))
</code></pre>
<p>or <code>lag</code> with <code>order_by</code>:</p>
<pre><code>data %>%
group_by(id) %>%
mutate(diff = value - lag(value, default = first(value), order_by = date))
</code></pre>
<p>With <code>data.table</code>:</p>
<pre class="lang-r prettyprint-override"><code>library(data.table)
dt <- as.data.table(data)
setkey(dt, id, date)
dt[, diff := value - shift(value, fill = first(value)), by = id]
</code></pre> |
40,426,106 | Spark 2.0.x dump a csv file from a dataframe containing one array of type string | <p>I have a dataframe <code>df</code> that contains one column of type array</p>
<p><code>df.show()</code> looks like</p>
<pre><code>|ID|ArrayOfString|Age|Gender|
+--+-------------+---+------+
|1 | [A,B,D] |22 | F |
|2 | [A,Y] |42 | M |
|3 | [X] |60 | F |
+--+-------------+---+------+
</code></pre>
<p>I try to dump that <code>df</code> in a csv file as follow:</p>
<pre><code>val dumpCSV = df.write.csv(path="/home/me/saveDF")
</code></pre>
<p>It is not working because of the column <code>ArrayOfString</code>. I get the error:</p>
<blockquote>
<p>CSV data source does not support array string data type</p>
</blockquote>
<p>The code works if I remove the column <code>ArrayOfString</code>. But I need to keep <code>ArrayOfString</code>!</p>
<p>What would be the best way to dump the csv dataframe including column ArrayOfString (ArrayOfString should be dumped as one column on the CSV file)</p> | 40,426,866 | 6 | 0 | null | 2016-11-04 15:15:09.157 UTC | 9 | 2021-08-26 13:52:25.147 UTC | 2017-02-16 09:57:11.307 UTC | null | 13,302 | null | 1,364,364 | null | 1 | 43 | arrays|csv|apache-spark | 67,672 | <p>The reason why you are getting this error is that csv file format doesn't support array types, you'll need to express it as a string to be able to save.</p>
<p>Try the following :</p>
<pre class="lang-scala prettyprint-override"><code>import org.apache.spark.sql.functions._
val stringify = udf((vs: Seq[String]) => vs match {
case null => null
case _ => s"""[${vs.mkString(",")}]"""
})
df.withColumn("ArrayOfString", stringify($"ArrayOfString")).write.csv(...)
</code></pre>
<p>or</p>
<pre class="lang-scala prettyprint-override"><code>import org.apache.spark.sql.Column
def stringify(c: Column) = concat(lit("["), concat_ws(",", c), lit("]"))
df.withColumn("ArrayOfString", stringify($"ArrayOfString")).write.csv(...)
</code></pre> |
40,729,162 | Merging results from model.predict() with original pandas DataFrame? | <p>I am trying to merge the results of a <code>predict</code> method back with the original data in a <code>pandas.DataFrame</code> object.</p>
<pre><code>from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
import numpy as np
data = load_iris()
# bear with me for the next few steps... I'm trying to walk you through
# how my data object landscape looks... i.e. how I get from raw data
# to matrices with the actual data I have, not the iris dataset
# put feature matrix into columnar format in dataframe
df = pd.DataFrame(data = data.data)
# add outcome variable
df['class'] = data.target
X = np.matrix(df.loc[:, [0, 1, 2, 3]])
y = np.array(df['class'])
# finally, split into train-test
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8)
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
# I've got my predictions now
y_hats = model.predict(X_test)
</code></pre>
<p>To merge these predictions back with the original <code>df</code>, I try this:</p>
<pre><code>df['y_hats'] = y_hats
</code></pre>
<p>But that raises:</p>
<blockquote>
<p>ValueError: Length of values does not match length of index</p>
</blockquote>
<p>I know I could split the <code>df</code> into <code>train_df</code> and <code>test_df</code> and this problem would be solved, but in reality I need to follow the path above to create the matrices <code>X</code> and <code>y</code> (my actual problem is a text classification problem in which I normalize the <em>entire</em> feature matrix before splitting into train and test). How can I align these predicted values with the appropriate rows in my <code>df</code>, since the <code>y_hats</code> array is zero-indexed and seemingly all information about <em>which</em> rows were included in the <code>X_test</code> and <code>y_test</code> is lost? Or will I be relegated to splitting dataframes into train-test first, and then building feature matrices? I'd like to just fill the rows included in <code>train</code> with <code>np.nan</code> values in the dataframe.</p> | 40,729,371 | 9 | 1 | null | 2016-11-21 20:52:51.263 UTC | 21 | 2022-07-23 16:42:46.213 UTC | null | null | null | null | 5,015,569 | null | 1 | 32 | python|pandas|scikit-learn | 102,691 | <p>your y_hats length will only be the length on the test data (20%) because you predicted on X_test. Once your model is validated and you're happy with the test predictions (by examining the accuracy of your model on the X_test predictions compared to the X_test true values), you should rerun the predict on the full dataset (X). Add these two lines to the bottom:</p>
<pre><code>y_hats2 = model.predict(X)
df['y_hats'] = y_hats2
</code></pre>
<p><strong>EDIT</strong> per your comment, here is an updated result the returns the dataset with the prediction appended where they were in the test datset</p>
<pre><code>from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
import numpy as np
data = load_iris()
# bear with me for the next few steps... I'm trying to walk you through
# how my data object landscape looks... i.e. how I get from raw data
# to matrices with the actual data I have, not the iris dataset
# put feature matrix into columnar format in dataframe
df = pd.DataFrame(data = data.data)
# add outcome variable
df_class = pd.DataFrame(data = data.target)
# finally, split into train-test
X_train, X_test, y_train, y_test = train_test_split(df,df_class, train_size = 0.8)
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
# I've got my predictions now
y_hats = model.predict(X_test)
y_test['preds'] = y_hats
df_out = pd.merge(df,y_test[['preds']],how = 'left',left_index = True, right_index = True)
</code></pre> |
33,937,067 | Firefox webdriver opens first run page all the time | <p>How to disable this "first run" page once and for all for FF?</p>
<p>When FF driver is created, it opens tab with -
<a href="https://www.mozilla.org/en-US/firefox/42.0/firstrun/learnmore/" rel="noreferrer">https://www.mozilla.org/en-US/firefox/42.0/firstrun/learnmore/</a>
and additional tab with target page.</p> | 34,622,056 | 9 | 0 | null | 2015-11-26 11:08:39.647 UTC | 7 | 2022-08-31 13:42:43.583 UTC | null | null | null | null | 1,515,074 | null | 1 | 42 | firefox|selenium|selenium-webdriver|selenium-firefoxdriver | 31,007 | <p>To turn off this annoying start page:</p>
<p><a href="https://i.stack.imgur.com/6HTE4.png"><img src="https://i.stack.imgur.com/6HTE4.png" alt="More protection. The most privacy. Mozilla Firefox firstrun screen"></a></p>
<p>in C# with Selenium 2.48 I found the following solution:</p>
<pre><code>FirefoxProfile prof = new FirefoxProfile();
prof.SetPreference("browser.startup.homepage_override.mstone", "ignore");
prof.SetPreference("startup.homepage_welcome_url.additional", "about:blank");
Driver = new FirefoxDriver(prof);
</code></pre>
<p>...and it will never bother you again.</p>
<p>Note: One of these settings alone will also work. I use them together to make it bullet-proof.</p> |
27,753,246 | match Vs exec in JavaScript | <p>I need some clarification for match Vs exec in JavaScript; <a href="https://stackoverflow.com/questions/9214754/what-is-the-difference-between-regexp-s-exec-function-and-string-s-match-fun">here</a> some one says that </p>
<p><em>"exec with a global regular expression is meant to be used in a loop"</em> but first of all as you see in my example this is not the case; in my example exec with global regular expression is returning all of the matches in an array! Secondly they say that for String.match it returns all of the matches with no need of looping through! But again that's not happening in my example and it is just returning the input string? Have I misunderstood/done something wrong?</p>
<pre><code>var myString = "[22].[44].[33].";
var myRegexp = /.*\[(\d*)*\].*\[(\d*)*\].*\[(\d*)*\].*/g;
var execResult = myRegexp.exec(myString);
console.log(execResult.length);
console.log(execResult[1]);// returns 22 and execResult has all of my matches from index 1 to the length of array
var matchResult = myString.match(myRegexp);
console.log(matchResult.length);
console.log(matchResult);// returns just myString which is "[22].[44].[33]."! Why is that?
</code></pre> | 27,753,327 | 2 | 0 | null | 2015-01-03 09:04:28.987 UTC | 24 | 2020-01-03 10:45:17.657 UTC | 2017-05-23 12:34:23.013 UTC | null | -1 | user3399784 | null | null | 1 | 62 | javascript|regex | 58,655 | <ol>
<li><p><code>string.match</code> finds the first match and returns it with the actual match, the index at which the text was found and the actual input, <em>when the global flag is not used.</em></p></li>
<li><p><code>string.match</code> just returns all the matches, <em>when the global flag is used.</em></p></li>
</ol>
<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>var myString = "[22].[44].[33].";
console.log(myString.match(/\d+/));
// [ '22', index: 1, input: '[22].[44].[33].' ]
console.log(myString.match(/\d+/g));
// [ '22', '44', '33' ]</code></pre>
</div>
</div>
</p>
<p><strong>The main difference between <code>string.match</code> and <code>regex.exec</code> is, the <code>regex</code> object will be updated of the current match with <code>regex.exec</code> call.</strong> For example,</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>var myString = "[22].[44].[33].", myRegexp = /\d+/g, result;
while (result = myRegexp.exec(myString)) {
console.log(result, myRegexp.lastIndex);
}</code></pre>
</div>
</div>
</p>
<p>will return</p>
<pre><code>[ '22', index: 1, input: '[22].[44].[33].' ] 3
[ '44', index: 6, input: '[22].[44].[33].' ] 8
[ '33', index: 11, input: '[22].[44].[33].' ] 13
</code></pre>
<p>As you can see, the <code>lastIndex</code> property is updated whenever a match is found. So, keep two things in mind when you use <code>exec</code>, or <strong>you will run into an infinite loop.</strong></p>
<ol>
<li><p>If you don't use <code>g</code> option, then you will always get the first match, if there is one, otherwise <code>null</code>. So, the following will run into an infinite loop.</p>
<pre><code>var myString = "[22].[44].[33].", myRegexp = /\d+/, result;
while (result = myRegexp.exec(myString)) {
console.log(result, myRegexp.lastIndex);
}
</code></pre></li>
<li><p>Don't forget to use the same regular expression object with subsequent calls. Because, the regex object is updated every time, and if you pass new object, again the program will run into an infinite loop.</p>
<pre><code>var myString = "[22].[44].[33].", result;
while (result = /\d+/g.exec(myString)) {
console.log(result);
}
</code></pre></li>
</ol> |
49,779,543 | Swift Package Manager C-interop: Non-system libraries | <p>How can I use the Swift Package Manager to include C code (in my case, a single <code>.c</code> file and a header file) <em>without</em> requiring the user to install my C library into <code>/usr/local/lib</code>?</p>
<p>I had thought to create a Package in a subdirectory of my main package containing the header + lib, and use relative paths, and finally build with <code>swift build -Xlinker ./relative/path/to/mylib</code>, however I'm not having any success resolving the dependency since it's expected to be a standalone git repository. Error message is:</p>
<p><code>error: failed to clone; fatal: repository '/absolute/path/to/mylib' does not exist</code></p>
<p>Moreover it's not clear to me whether using the <code>-Xlinker</code> flag is the correct approach.</p>
<p>I can't use a bridging header with a pure SwiftPM approach and installing my library system-wide seems overkill as well as not very portable.</p>
<p>Any ideas?</p> | 49,825,930 | 1 | 0 | null | 2018-04-11 15:54:09.05 UTC | 9 | 2018-04-13 22:28:44.893 UTC | null | null | null | null | 135,700 | null | 1 | 14 | c|swift|interop|swift-package-manager | 4,726 | <p>I have done that in <a href="https://github.com/bscothern/Once" rel="noreferrer">this project</a> on github. It replaces <code>pthread_once_t</code> by wrapping it in C and re-exposing it to swift. It was done as a fun exercise in getting around what Swift tries to limit you into since <code>pthread_once_t</code> and <code>dispatch_once</code> are not available directly.</p>
<p>Here is a trimmed down version the <code>Package.swift</code> file:</p>
<pre><code>// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "Once",
products: [
.library(
name: "Once",
targets: ["OnceC", "Once"]),
],
dependencies: [
],
targets: [
.target(
name: "OnceC",
dependencies: [],
path: "Sources/OnceC"),
.target(
name: "Once",
dependencies: ["OnceC"],
path: "Sources/Swift"),
.testTarget(
name: "OnceTests",
dependencies: ["Once"]),
]
)
</code></pre>
<p>You can easily replace the product library with an executable. The main part is that the product's targets needs to contain both the C and Swift targets needed to build.</p>
<p>Then in your targets section make the swift target lists the C target as a dependency.</p>
<hr>
<p>You can learn more about the required layout for C targets in the SwiftPM Usage.md <a href="https://github.com/apple/swift-package-manager/blob/master/Documentation/Usage.md#c-language-targets" rel="noreferrer">here</a></p>
<h2>C language targets</h2>
<p>The C language targets are similar to Swift targets except that the C language
libraries should contain a directory named <code>include</code> to hold the public headers. </p>
<p>To allow a Swift target to import a C language target, add a target
dependency in the manifest file. Swift Package Manager will
automatically generate a modulemap for each C language library target for these
3 cases:</p>
<ul>
<li><p>If <code>include/Foo/Foo.h</code> exists and <code>Foo</code> is the only directory under the
include directory then <code>include/Foo/Foo.h</code> becomes the umbrella header.</p></li>
<li><p>If <code>include/Foo.h</code> exists and <code>include</code> contains no other subdirectory then
<code>include/Foo.h</code> becomes the umbrella header.</p></li>
<li><p>Otherwise if the <code>include</code> directory only contains header files and no other
subdirectory, it becomes the umbrella directory.</p></li>
</ul>
<p>In case of complicated <code>include</code> layouts, a custom <code>module.modulemap</code> can be
provided inside <code>include</code>. SwiftPM will error out if it can not generate
a modulemap w.r.t the above rules.</p>
<p>For executable targets, only one valid C language main file is allowed i.e. it
is invalid to have <code>main.c</code> and <code>main.cpp</code> in the same target.</p>
<hr>
<p>The only other important thing is how you actually do your <code>#import</code> in the C code once it is compiled as a compatible module. If you use the <code>import/Foo/Foo.h</code> organization you need to use <code>#include <Foo/Foo.h></code> and if you do <code>import/Foo.h</code> you can use <code>#import "Foo.h"</code>.</p> |
35,890,540 | When to use Spring Security`s antMatcher()? | <p>When do we use <code>antMatcher()</code> vs <code>antMatchers()</code>?</p>
<p>For example:</p>
<pre class="lang-java prettyprint-override"><code>http
.antMatcher("/high_level_url_A/**")
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse()
.anyRequest().authenticated()
.and()
.antMatcher("/high_level_url_B/**")
.authorizeRequests()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse()
.anyRequest().authenticated()
.and()
...
</code></pre>
<p>What I expect here is, </p>
<ul>
<li>Any request matches to <code>/high_level_url_A/**</code> should be authenticated + <code>/high_level_url_A/sub_level_1</code> only for USER and <code>/high_level_url_A/sub_level_2</code> only for USER2</li>
<li>Any request matches to <code>/high_level_url_B/**</code> should be authenticated + <code>/high_level_url_B/sub_level_1</code> for public access and <code>/high_level_url_A/sub_level_2</code> only for USER3.</li>
<li>Any other pattern I don't care - But should be public ?</li>
</ul>
<p>I have seen latest examples do not include <code>antMatcher()</code> these days. Why is that? Is <code>antMatcher()</code> no longer required?</p> | 41,527,591 | 3 | 0 | null | 2016-03-09 11:37:15.88 UTC | 54 | 2019-03-31 07:16:16.7 UTC | 2017-11-14 20:51:22.85 UTC | null | 1,684,269 | null | 508,957 | null | 1 | 79 | spring-mvc|spring-security|spring-security4 | 194,875 | <p>You need <a href="http://docs.spring.io/spring-security/site/docs/4.2.x/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html#antMatcher-java.lang.String-" rel="noreferrer"><code>antMatcher</code></a> for multiple <a href="http://docs.spring.io/spring-security/site/docs/4.2.x/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html" rel="noreferrer"><code>HttpSecurity</code></a>, see <a href="http://docs.spring.io/spring-security/site/docs/4.2.x/reference/htmlsingle/#multiple-httpsecurity" rel="noreferrer">Spring Security Reference</a>:</p>
<blockquote>
<p><strong>5.7 Multiple HttpSecurity</strong></p>
<p>We can configure multiple HttpSecurity instances just as we can have multiple <code><http></code> blocks. The key is to extend the <code>WebSecurityConfigurationAdapter</code> multiple times. For example, the following is an example of having a different configuration for URL’s that start with <code>/api/</code>.</p>
<pre><code>@EnableWebSecurity
public class MultiHttpSecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) { 1
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
@Configuration
@Order(1) 2
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**") 3
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
@Configuration 4
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
}
</code></pre>
<p>1 Configure Authentication as normal</p>
<p>2 Create an instance of <code>WebSecurityConfigurerAdapter</code> that contains <code>@Order</code> to specify which <code>WebSecurityConfigurerAdapter</code> should be considered first.</p>
<p>3 The <code>http.antMatcher</code> states that this <code>HttpSecurity</code> will only be applicable to URLs that start with <code>/api/</code></p>
<p>4 Create another instance of <code>WebSecurityConfigurerAdapter</code>. If the URL does not start with <code>/api/</code> this configuration will be used. This configuration is considered after <code>ApiWebSecurityConfigurationAdapter</code> since it has an <code>@Order</code> value after <code>1</code> (no <code>@Order</code> defaults to last).</p>
</blockquote>
<p>In your case you need no <a href="http://docs.spring.io/spring-security/site/docs/4.2.x/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html#antMatcher-java.lang.String-" rel="noreferrer"><code>antMatcher</code></a>, because you have only one configuration. Your modified code:</p>
<pre class="lang-java prettyprint-override"><code>http
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse() // for /high_level_url_A/**
.antMatchers("/high_level_url_A/**").authenticated()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse() // for /high_level_url_B/**
.antMatchers("/high_level_url_B/**").authenticated()
.anyRequest().permitAll()
</code></pre> |
42,987,521 | Pip: could not find a version. No matching distribution found | <p>I'm trying to install Flask-ACL:
<a href="https://mikeboers.github.io/Flask-ACL" rel="noreferrer">https://mikeboers.github.io/Flask-ACL</a></p>
<pre><code>$ pip search acl | grep -i flask
Flask-ACL (0.0.1) - Access control lists for Flask.
flask-miracle-acl (0.2) - The fabric between the Flask framework and Miracle ACL
Flask-Sandbox (0.1.0)- ACL Route controls for Flask
Flask-SimpleACL (1.2)- Simple ACL extension
$ pip install Flask-ACL
Collecting Flask-ACL
Could not find a version that satisfies the requirement Flask-ACL (from versions: )
No matching distribution found for Flask-ACL
</code></pre>
<p>What's wrong here?</p>
<p>P.S. Pip was upgraded a few minutes ago.</p>
<p>UPDATE:</p>
<pre><code>$ python --version
Python 2.7.3
</code></pre>
<p>I'm running it under virtualenv.</p>
<pre><code>pip install -Iv Flask-ACL
Collecting Flask-ACL
1 location(s) to search for versions of Flask-ACL:
* https://pypi.python.org/simple/flask-acl/
Getting page https://pypi.python.org/simple/flask-acl/
Looking up "https://pypi.python.org/simple/flask-acl/" in the cache
Current age based on date: 507
Freshness lifetime from max-age: 600
Freshness lifetime from request max-age: 600
The response is "fresh", returning cached response
600 > 507
Analyzing links from page https://pypi.python.org/simple/flask-acl/
Could not find a version that satisfies the requirement Flask-ACL (from versions: )
</code></pre>
<p>Cleaning up...
No matching distribution found for Flask-ACL</p>
<p>As I can see, there is no such package on Pypi:</p>
<pre><code>https://pypi.python.org/simple/flask-acl/
</code></pre>
<p>but this one exist:</p>
<pre><code>https://pypi.python.org/pypi/Flask-ACL
</code></pre>
<p>What is wrong with my <code>pip</code>?</p> | 42,987,658 | 4 | 0 | null | 2017-03-23 21:39:28.3 UTC | 3 | 2021-09-24 09:02:27.86 UTC | 2017-03-23 21:52:38.927 UTC | null | 7,335,432 | null | 7,335,432 | null | 1 | 19 | python|pip|package | 81,435 | <p>The developers of Flask-ACL made a mistake that they did not manage to upload the Flask-ACL library onto PyPi(where pip searches for modules). so you will have to install it using pip from their GitHub page. </p>
<p>You can do so like this:</p>
<pre><code>pip install "git+https://github.com/mikeboers/Flask-ACL"
</code></pre> |
28,954,168 | How to use class methods as callbacks | <p>I have a class with methods that I want to use as callbacks.<br />
How can I pass them as arguments?</p>
<pre class="lang-php prettyprint-override"><code>Class MyClass {
public function myMethod() {
// How should these be called?
$this->processSomething(this->myCallback);
$this->processSomething(self::myStaticCallback);
}
private function processSomething(callable $callback) {
// Process something...
$callback();
}
private function myCallback() {
// Do something...
}
private static function myStaticCallback() {
// Do something...
}
}
</code></pre> | 28,954,220 | 4 | 0 | null | 2015-03-10 00:25:43.423 UTC | 19 | 2022-03-04 21:58:58.82 UTC | 2022-02-22 21:17:31.31 UTC | null | 2,756,409 | null | 3,751,064 | null | 1 | 126 | php|oop|callback | 101,635 | <p>Check the <a href="http://php.net/manual/en/language.types.callable.php" rel="noreferrer"><code>callable</code> manual</a> to see all the different ways to pass a function as a callback. I copied that manual here and added some examples of each approach based on your scenario.</p>
<blockquote>
<h2>Callable</h2>
</blockquote>
<hr>
<blockquote>
<ul>
<li>A <strong>PHP function</strong> is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: <em>array()</em>, <em>echo</em>, <em>empty()</em>, <em>eval()</em>, <em>exit()</em>, <em>isset()</em>, <em>list()</em>, <em>print</em> or <em>unset()</em>.</li>
</ul>
</blockquote>
<pre><code> // Not applicable in your scenario
$this->processSomething('some_global_php_function');
</code></pre>
<hr>
<blockquote>
<ul>
<li>A <strong>method of an instantiated object</strong> is passed as an array containing an object at index <em>0</em> and the method name at index <em>1</em>.</li>
</ul>
</blockquote>
<pre><code> // Only from inside the same class
$this->processSomething([$this, 'myCallback']);
$this->processSomething([$this, 'myStaticCallback']);
// From either inside or outside the same class
$myObject->processSomething([new MyClass(), 'myCallback']);
$myObject->processSomething([new MyClass(), 'myStaticCallback']);
</code></pre>
<hr>
<blockquote>
<ul>
<li><strong>Static class methods</strong> can also be passed without instantiating an object of that class by passing the class name instead of an object at index <em>0</em>.</li>
</ul>
</blockquote>
<pre><code> // Only from inside the same class
$this->processSomething([__CLASS__, 'myStaticCallback']);
// From either inside or outside the same class
$myObject->processSomething(['\Namespace\MyClass', 'myStaticCallback']);
$myObject->processSomething(['\Namespace\MyClass::myStaticCallback']); // PHP 5.2.3+
$myObject->processSomething([MyClass::class, 'myStaticCallback']); // PHP 5.5.0+
</code></pre>
<hr>
<blockquote>
<ul>
<li>Apart from common user-defined function, <strong>anonymous functions</strong> can also be passed to a callback parameter. </li>
</ul>
</blockquote>
<pre><code> // Not applicable in your scenario unless you modify the structure
$this->processSomething(function() {
// process something directly here...
});
</code></pre>
<hr> |
27,988,565 | When to use api.one and api.multi in odoo | openerp? | <p>Recently odoo (formerly OpenERP) V8 has been released. In new API method decorators are introduced. in <code>models.py</code> methods needs to be decorated with <code>@api.one</code> or <code>@api.multi</code>.</p>
<p>Referring <a href="https://www.odoo.com/documentation/8.0/" rel="noreferrer">odoo documentation</a> i can not determine the exact use. Can anybody explain in detail.</p>
<p>Thanks.</p> | 27,988,737 | 3 | 0 | null | 2015-01-16 16:37:01.363 UTC | 8 | 2016-09-12 06:13:26.63 UTC | null | null | null | null | 3,999,697 | null | 1 | 12 | openerp|odoo|openerp-8 | 13,333 | <p>Generally both decoarators are used to decorate a record-style method where '<code>self</code>' contains <strong>recordset</strong>(s). Let me explain in brief when to use <code>@api.one</code> and <code>@api.multi</code>:</p>
<p><strong>1.</strong> <code>@api.one</code>:</p>
<ul>
<li><p>Decorate a record-style method where '<strong>self</strong>' is expected to be a singleton instance.</p></li>
<li><p>The decorated method automatically loops on records (i.e, for each record in recordset it calls the method), and <strong>makes a list with the results</strong>.</p></li>
<li><p>In case the method is decorated with @returns, it concatenates the resulting instances. Such a method:</p>
<p>@api.one
def method(self, args):
return self.name</p></li>
</ul>
<p>may be called in both record and traditional styles, like::</p>
<pre><code># recs = model.browse(cr, uid, ids, context)
names = recs.method(args)
names = model.method(cr, uid, ids, args, context=context)
</code></pre>
<ul>
<li>Each time 'self' is redefined as current record.</li>
</ul>
<p><strong>2.</strong> <code>@api.multi</code>:</p>
<ul>
<li><p>Decorate a record-style method where '<code>self</code>' is a recordset. The method typically defines an operation on records. Such a method:</p>
<p>@api.multi
def method(self, args):</p></li>
</ul>
<p>may be called in both record and traditional styles, like::</p>
<pre><code># recs = model.browse(cr, uid, ids, context)
recs.method(args)
model.method(cr, uid, ids, args, context=context)
</code></pre>
<p><strong>When to use:</strong></p>
<ol>
<li><p>If you are using @api.one, the returned value is in a list.
This is not always supported by the web client, e.g. on button action
methods.
In that case, you should use @api.multi to decorate your method, and probably call self.ensure_one() in
the method definition.</p></li>
<li><p>It is always better use @api.multi with self.ensure_one() instead of @api.one to avoid the side effect in return values.</p></li>
</ol> |
47,585,279 | How to access values in array column? | <p>I have a Dataframe with one column. Each row of that column has an Array of String values: </p>
<p>Values in my Spark 2.2 Dataframe </p>
<pre><code>["123", "abc", "2017", "ABC"]
["456", "def", "2001", "ABC"]
["789", "ghi", "2017", "DEF"]
org.apache.spark.sql.DataFrame = [col: array]
root
|-- col: array (nullable = true)
| |-- element: string (containsNull = true)
</code></pre>
<p>What is the best way to access elements in the array? For example, I would like extract distinct values in the fourth element for the year 2017 (answer "ABC", "DEF").</p> | 54,520,375 | 4 | 0 | null | 2017-12-01 01:23:25.12 UTC | 7 | 2020-07-08 14:21:55.823 UTC | 2017-12-01 09:56:45.617 UTC | null | 1,305,344 | null | 3,439,308 | null | 1 | 28 | scala|apache-spark|apache-spark-sql | 68,479 | <p>Since Spark 2.4.0, there is a new function <code>element_at($array_column, $index)</code>.</p>
<p><a href="https://spark.apache.org/docs/latest/api/scala/org/apache/spark/sql/functions$.html#element_at(column:org.apache.spark.sql.Column,value:Any):org.apache.spark.sql.Column" rel="noreferrer">See Spark docs</a></p> |
37,347,991 | How much time does it take for firebase analytics first report? | <p>We wanted to try out the new analytics capabilities provided by firebase and followed all the steps in the getting started guide.</p>
<p>We've run the app, <code>logged</code> a lot of events, and it's been a few hours, yet there is no data on the dashboard - We just see a banner saying "Your analytics data will appear here soon"</p>
<p>How much time does it take to get our first reports, events, etc.?</p> | 37,348,235 | 7 | 0 | null | 2016-05-20 13:29:07.48 UTC | 7 | 2020-12-17 19:41:05.51 UTC | 2020-12-17 19:41:05.51 UTC | null | 12,515,963 | null | 5,912,571 | null | 1 | 51 | firebase|firebase-analytics | 34,329 | <p>It takes a few hours. I would say it takes like 4 hours or something like that, based on current experiments.</p>
<p><strong>Firebase</strong> says that it can take up to 24h hours, but the docs say that the dashboard updates "a few times every day". </p>
<p>And if you send the Firebase events to <strong>BigQuery</strong>, they create a new dataset there everyday, but it seems that the "old" events are not sent immediately, maybe that takes a few hours too, don't know yet.</p>
<hr>
<p>If you want to test other features, or see if Firebase is working for your app, you can force a crash, and see it in the Crash panel, cause this works almost real time.<br>
Or you can send a notification to all users, this should work too, and it is faster than waiting for 4h or more to see if it is working really.<br>
Remember to add the dependencies if you are going to try this:</p>
<pre><code>compile 'com.google.firebase:firebase-crash:9.0.0'
compile 'com.google.firebase:firebase-messaging:9.0.0'
</code></pre> |
38,527,535 | Set null as empty string value for input field | <p>I have an <code>input</code> field mapped to an entity in my controller with a <code>ngModel</code> 2-way binding:</p>
<pre class="lang-html prettyprint-override"><code><input type="text" [(ngModel)]="entity.one_attribute" />
</code></pre>
<p>When I initialize my controller, I have this entity:</p>
<pre class="lang-typescript prettyprint-override"><code>{ one_attribute: null }
</code></pre>
<p>If a user starts to fill in the field but does not submit the form immediately and empties the field, my entity is updated to become:</p>
<pre class="lang-typescript prettyprint-override"><code>{ one_attribute: "" }
</code></pre>
<p>Is it possible to define that empty string should be changed to <code>null</code> automatically?</p> | 43,094,103 | 6 | 2 | null | 2016-07-22 13:19:40.307 UTC | 7 | 2022-06-12 00:30:29.59 UTC | 2019-05-22 22:30:00.113 UTC | null | 3,345,644 | null | 1,951,430 | null | 1 | 28 | angular|angular2-template | 56,789 | <p>After viewing a bunch of answers about <code>ValueAccessor</code> and <code>HostListener</code> solutions, I made a working solution (tested with RC1):</p>
<pre class="lang-typescript prettyprint-override"><code>import {NgControl} from "@angular/common";
import {Directive, ElementRef, HostListener} from "@angular/core";
@Directive({
selector: 'input[nullValue]'
})
export class NullDefaultValueDirective {
constructor(private el: ElementRef, private control: NgControl) {}
@HostListener('input', ['$event.target'])
onEvent(target: HTMLInputElement){
this.control.viewToModelUpdate((target.value === '') ? null : target.value);
}
}
</code></pre>
<p>Then use it that way on your input fields:</p>
<pre class="lang-html prettyprint-override"><code><input [(ngModel)]="bindedValue" nullValue/>
</code></pre> |
24,725,059 | Wait For Asynchronous Operation To Complete in Swift | <p>I am not sure how to handle this situation as I am very new to iOS development and Swift. I am performing data fetching like so:</p>
<pre><code>func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!)
{
loadShows()
completionHandler(UIBackgroundFetchResult.NewData)
println("Background Fetch Complete")
}
</code></pre>
<p>My loadShows() function parses a bunch of data it gets from a website loaded into a UIWebView. The problem is that I have a timer that waits for 10 seconds or so in the loadShows function. This allows for the javascript in the page to fully load before I start parsing the data. My problem is that the completion handler completes before my loadShows() does. </p>
<p>What I would like to do is add a bool for "isCompletedParsingShows" and make the completionHandler line wait to complete until that bool is true. What is the best way to handle this?</p> | 24,725,314 | 3 | 0 | null | 2014-07-13 16:53:48.523 UTC | 18 | 2018-11-26 12:30:01.033 UTC | 2018-11-26 12:30:01.033 UTC | null | 5,620,447 | null | 3,792,045 | null | 1 | 24 | ios|swift|asynchronous | 46,652 | <p>you have to pass your async function the handler to call later on: </p>
<pre><code>func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
loadShows(completionHandler)
}
func loadShows(completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
//....
//DO IT
//....
completionHandler(UIBackgroundFetchResult.NewData)
println("Background Fetch Complete")
}
</code></pre>
<h1>OR (cleaner way IMHO)</h1>
<p>add an intermediate completionHandler</p>
<pre><code>func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
loadShows() {
completionHandler(UIBackgroundFetchResult.NewData)
println("Background Fetch Complete")
}
}
func loadShows(completionHandler: (() -> Void)!) {
//....
//DO IT
//....
completionHandler()
}
</code></pre> |
28,827,928 | Template does not update when using ui-router and ion-tabs | <p><strong>CODE</strong></p>
<p><a href="http://codepen.io/hawkphil/pen/LEBNVB">http://codepen.io/hawkphil/pen/LEBNVB</a></p>
<p>I have two pages (<code>link1</code> and <code>link2</code>) from the side menu. Each page has 2 tabs:</p>
<p><code>link1</code>: <code>tab 1.1</code> and <code>tab 1.2</code> </p>
<p><code>link2</code>: <code>tab 2.1</code> and <code>tab 2.2</code></p>
<p>I am using <code>ion-tabs</code> for each page to contain the 2 tabs.</p>
<p>This is a very simple design: I want to click on the <code>link1</code> or <code>link2</code> to go to appropriate route. But for some reason, the state has changed correctly (see Console) but the actual html template did not get updated. <strong>Can you find out what's wrong and how to fix?</strong></p>
<p>There seems to be some caching problem or something.</p>
<p><strong>HTML</strong></p>
<p>
</p>
<pre><code><title>Tabs Example</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</code></pre>
<p></p>
<p></p>
<pre><code><ion-side-menus enable-menu-with-back-views="false">
<ion-side-menu-content>
<ion-nav-bar class="bar-positive">
<ion-nav-back-button>
</ion-nav-back-button>
<ion-nav-buttons side="left">
<button class="button button-icon button-clear ion-navicon" menu-toggle="left">
</button>
</ion-nav-buttons>
<ion-nav-buttons side="right">
<button class="button button-icon button-clear ion-navicon" menu-toggle="right">
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-nav-view name="menuContent"></ion-nav-view>
</ion-side-menu-content>
<ion-side-menu side="left">
<ion-header-bar class="bar-balanced">
<h1 class="title">Left</h1>
</ion-header-bar>
<ion-content>
<ion-list>
<ion-item nav-clear menu-close ui-sref="link1">
Link 1
</ion-item>
<ion-item nav-clear menu-close ui-sref="link2">
Link 2
</ion-item>
</ion-list>
</ion-content>
</ion-side-menu>
<ion-side-menu side="right">
<ion-header-bar class="bar-calm">
<h1 class="title">Right Menu</h1>
</ion-header-bar>
<ion-content>
<div class="list list-inset">
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" placeholder="Search">
</label>
</div>
<div class="list">
<a class="item item-avatar" href="#">
<img src="img/avatar1.jpg">
<h2>Venkman</h2>
<p>Back off, man. I'm a scientist.</p>
</a>
</div>
</ion-content>
</ion-side-menu>
</ion-side-menus>
</ion-side-menus>
<script id="link1.html" type="text/ng-template">
<ion-tabs class="tabs-icon-top tabs-positive">
<ion-tab title="Home" icon="ion-home">
<ion-view view-title="Home">
<ion-content has-header="true" has-tabs="true" padding="true">
<p>Test</p>
<p>Test Tab 1.1</p>
</ion-content>
</ion-view>
</ion-tab>
<ion-tab title="About" icon="ion-ios-information">
<ion-view view-title="Home">
<ion-content has-header="true" has-tabs="true" padding="true">
<p>Test</p>
<p>Test Tab 1.2</p>
</ion-content>
</ion-view>
</ion-tab>
</ion-tabs>
</script>
<script id="link2.html" type="text/ng-template">
<ion-tabs class="tabs-icon-top tabs-positive">
<ion-tab title="Home" icon="ion-home">
<ion-view view-title="Home">
<ion-content has-header="true" has-tabs="true" padding="true">
<p>Test</p>
<p>Test Tab 2.1</p>
</ion-content>
</ion-view>
</ion-tab>
<ion-tab title="About" icon="ion-ios-information">
<ion-view view-title="Home">
<ion-content has-header="true" has-tabs="true" padding="true">
<p>Test</p>
<p>Test Tab 2.2</p>
</ion-content>
</ion-view>
</ion-tab>
</ion-tabs>
</script>
</code></pre>
<p>
</p>
<p><strong>JS</strong></p>
<pre><code>angular.module('ionicApp', ['ionic'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('link1', {
url: "/link1",
views: {
'menuContent': {
templateUrl: "link1.html"
}
}
})
.state('link2', {
url: "/link2",
views: {
'menuContent': {
templateUrl: "link2.html"
}
}
});
$urlRouterProvider.otherwise("/link1");
})
.controller('AppCtrl', ['$scope', '$rootScope', '$state', '$stateParams', function($scope, $rootScope, $state, $stateParams) {
$rootScope.$on('$stateChangeSuccess', function(evt, toState, toParams, fromState, fromParams) {
console.log(toState);
});
}])
</code></pre> | 28,932,268 | 1 | 0 | null | 2015-03-03 09:13:07.71 UTC | 9 | 2015-11-03 14:23:24.157 UTC | null | null | null | null | 149,367 | null | 1 | 12 | javascript|html|angularjs|angular-ui-router|ionic-framework | 11,553 | <p>You are currently referring to the latest release which is <code>1.0.0-rc.0</code> which has bug while transition from one state to another it is not loading the view.</p>
<p>Further research found that, they had 14 beta releases from version <code>1.0.0-beta.1</code> to <code>1.0.0-beta.14</code> after they are now on version <code>1.0.0-rc.0</code> which is release candidate.</p>
<p><code>nav-view</code> is working perfect till <code>1.0.0-beta.13</code> version but it stop working after <code>1.0.0-beta.14</code>(which is last beta release),</p>
<p>I would suggest you to degrade your version to <code>1.0.0-beta.13</code>, I know depending on beta version is not good thing but still until ionic release stable version you have to rely on it.</p>
<p><strong><a href="http://codepen.io/anon/pen/VYGQZX">Working Codepen</a></strong> with <code>1.0.0-beta.13</code></p>
<p><strong>Update:</strong></p>
<p>Your problem is your view are getting cached because by default caching is enabled inside your ionic app.</p>
<p>Straight from <a href="http://ionicframework.com/docs/1.0.0-beta.14/api/directive/ionNavView/">Ionic Doc</a> (Latest Release doc 1.0.0-beta.14)</p>
<blockquote>
<p>By default, views are cached to improve performance. When a view is
navigated away from, its element is left in the DOM, and its scope is
disconnected from the $watch cycle. When navigating to a view that is
already cached, its scope is then reconnected, and the existing
element that was left in the DOM becomes the active view. This also
allows for the scroll position of previous views to be maintained.Maximum capacity of caching view is 10.</p>
</blockquote>
<p>So by mentioning <code>cache: false</code> on <code>$stateProvider</code> states function or disabling cache of nav-view globally by doing <code>$ionicConfigProvider.views.maxCache(0);</code> inside angular config phase.</p>
<p>So in your case this is what exact problem, your 1st view is getting cache & showing it again & again</p>
<p>There are 3 ways to solve this issue</p>
<p><strong>1. Disable cache globally</strong></p>
<p>Disable all caching by setting it to 0, before using it add <code>$ionicConfigProvider</code> dependency. </p>
<pre><code>$ionicConfigProvider.views.maxCache(0);
</code></pre>
<p><a href="http://codepen.io/anon/pen/JoeYMe?editors=101"><strong>Codepen</strong></a></p>
<p><strong>2. Disable cache within state provider</strong></p>
<pre><code>$stateProvider
.state('link1', {
url: "/link1",
cache: false,
views: {
'menuContent': {
templateUrl: "link1.html"
}
}
})
.state('link2', {
url: "/link2",
cache: false,
views: {
'menuContent': {
templateUrl: "link2.html"
}
}
});
</code></pre>
<p><a href="http://codepen.io/anon/pen/gbQaob?editors=101"><strong>Codepen</strong></a></p>
<p><strong>3. Disable cache with an attribute</strong></p>
<pre><code> <ion-tab title="Home" icon="ion-home">
<ion-view cache-view="false" view-title="Home">
<!-- Ion content here -->
</ion-view>
</ion-tab>
<ion-tab title="About" icon="ion-ios-information">
<ion-view cache-view="false" view-title="Home">
<!-- Ion content here -->
</ion-view>
</ion-tab>
</code></pre>
<p><strong><a href="http://codepen.io/anon/pen/XJymEq">Codepen</a></strong></p>
<p>I believe the updated approach would be great to implement. Thanks.</p>
<p>Github issue for the same issue <a href="https://github.com/driftyco/ionic/issues/3684"><strong>link here</strong></a></p> |
18,607,010 | Accessing factory defined in another module in angularjs | <p>Can we call the factory functions defined in one module from another module? If so, how?</p>
<p>Let's say my first module is defined in <code>moduleOne.js</code> file as:</p>
<pre><code>var myModule = angular.module('MyServiceModuleOne', []);
myModule.factory('notify', function () {
return {
sampleFun: function () {
// some code to call sampleFunTwo()
},
};
});
</code></pre>
<p>And my second module in <code>moduleTwo.js</code> as:</p>
<pre><code>var myModuleTwo = angular.module('MyServiceModuleTwo', []);
myModuleTwo.factory('notifytwo', function () {
return {
sampleFunTwo: function () {
// code
},
};
});
</code></pre>
<p>How to call <code>sampleFunTwo()</code> from <code>sampleFun()</code>?</p>
<p>Thanks.</p> | 18,607,352 | 1 | 0 | null | 2013-09-04 06:38:40.247 UTC | 2 | 2016-09-08 18:59:41.983 UTC | 2016-09-08 18:59:41.983 UTC | null | 717,267 | null | 2,440,226 | null | 1 | 28 | javascript|angularjs|dependency-injection|module | 26,385 | <p>You need to <em>inject</em> <code>MyServiceModuleTwo</code> into <code>MyServiceModule</code>:</p>
<pre><code>var myModuleTwo= angular.module('MyServiceModuleTwo',[]);
var myModule= angular.module('MyServiceModuleOne', ['MyServiceModuleTwo']);
</code></pre>
<p>Then <em>inject</em> <code>notifytwo</code> into <code>notify</code>:</p>
<pre><code>myModule.factory('notify', function(notifytwo) {
return {
sampleFun: function() {
notifytwo.sampleFunTwo();
}
};
});
myModuleTwo.factory('notifytwo', function() {
return {
sampleFunTwo: function() {
alert('From notify two');
}
};
});
</code></pre>
<p>And the code on <a href="http://plnkr.co/edit/jcOwg8HgBGPtod4yCR5j">plunker</a></p> |
23,479,879 | Clean Architecture vs Onion Architecture | <p>I have been reading up on the <a href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/" rel="noreferrer">Onion Architecture</a> and today I found out about Uncle Bob's <a href="http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html" rel="noreferrer">Clean Architecture</a>.</p>
<p>For the life of me I cannot see any differences between them, they look identical (other than the naming convention).</p>
<p>Is there any differences between the two architectural styles? If yes, can you explain it to me please?</p>
<p>Cheers</p> | 23,493,075 | 3 | 0 | null | 2014-05-05 19:06:04.703 UTC | 9 | 2018-10-30 01:14:40.213 UTC | 2018-07-24 17:35:22.407 UTC | null | 5,170,364 | null | 3,373,870 | null | 1 | 58 | architecture|onion-architecture|clean-architecture | 26,705 | <p>The term "Clean Architecture" is just the name of the article. The onion architecture is a specific application of the concepts explained in the article.</p> |
25,533,513 | AngularJS window.onbeforeunload in one controller is being triggered on another controller | <p>Here is my problem, I have two views (View1 and View2) and a controller for each view (Ctrl1 and Ctrl2). In View1 I'm trying to warn the user before he leaves the page accidentally without saving changes.</p>
<p>I'm using window.onbeforeunload, which works just fine, but my problem is that even though I have onbeforeunload only on one controller, the event seems to be triggered in the second controller as well! But I don't have even have that event in there. When the user leaves a page and there are unsaved changes, he gets warned by the onbeforeunload, if the user dismiss the alert and leaves the page, is he taken back to the second view, if the user tries to leave now this other view, we would also get warned about unsaved changes! When that's not even the case! Why is this happening?</p>
<p>I'm also using $locationChangeStart, which works just fine, but only when the user changes the route, not when they refresh the browser, hit 'back', or try to close it, that's why I'm forced to use onbeforeunload (If you a better approach, please let me know). Any help or a better approach would be greatly appreciated!</p>
<pre><code>//In this controller I check for window.onbeforeunload
app.controller("Ctrl1", function ($scope, ...)){
window.onbeforeunload = function (event) {
//Check if there was any change, if no changes, then simply let the user leave
if(!$scope.form.$dirty){
return;
}
var message = 'If you leave this page you are going to lose all unsaved changes, are you sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
//This works only when user changes routes, not when user refreshes the browsers, goes to previous page or try to close the browser
$scope.$on('$locationChangeStart', function( event ) {
if (!$scope.form.$dirty) return;
var answer = confirm('If you leave this page you are going to lose all unsaved changes, are you sure you want to leave?')
if (!answer) {
event.preventDefault();
}
});
}
//This other controller has no window.onbeforeunload, yet the event is triggered here too!
app.controller("Ctrl2", function ($scope, ...)){
//Other cool stuff ...
}
</code></pre>
<p>I tried checking the current path with $location.path() to only warn the user when he is in the view I want the onbeforeunload to be triggered, but this seems kinda 'hacky' the solution would be to not execute onbeforeunload on the other controller at all.</p>
<p><strong>I added $location.path() != '/view1'</strong> in the first which seems to work, but it doesn't seem right to me, besides I don't only have two views, I have several views and this would get tricky with more controllers involved:</p>
<pre><code>app.controller("Ctrl1", function ($scope, ...)){
window.onbeforeunload = function (event) {
//Check if there was any change, if no changes, then simply let the user leave
if($location.path() != '/view1' || !$scope.form.$dirty){
return;
}
var message = 'If you leave this page you are going to lose all unsaved changes, are you sure you want to leave?';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
}
//This works only when user changes routes, not when user refreshes the browsers, goes to previous page or try to close the browser
$scope.$on('$locationChangeStart', function( event ) {
if (!$scope.form.$dirty) return;
var answer = confirm('If you leave this page you are going to lose all unsaved changes, are you sure you want to leave?')
if (!answer) {
event.preventDefault();
}
});
}
</code></pre> | 25,533,964 | 4 | 0 | null | 2014-08-27 17:29:33.427 UTC | 8 | 2019-06-05 23:39:11.25 UTC | 2015-09-16 09:31:16.397 UTC | null | 1,897,703 | null | 1,146,058 | null | 1 | 23 | angularjs|onbeforeunload | 42,342 | <p>Unregister the onbeforeunload event when the controller which defined it goes out of scope:</p>
<pre><code>$scope.$on('$destroy', function() {
delete window.onbeforeunload;
});
</code></pre> |
38,793,723 | Uncaught TypeError: $.post is not a function | <p>I am getting this error in Console:</p>
<blockquote>
<p>Uncaught TypeError: $.post is not a function</p>
</blockquote>
<p>for this piece of code:</p>
<pre><code><script type="text/javascript">
$('#cl_submit').click(function() { //#cl_submit is a button
$('#cl_stage1msg').html('Processing...');
$.post("process/cookie.php", $("#cl").serialize(), function(response) { //#cl is a form
$('#cl_stage1msg').html(response);
});
return false;
});
</script> <!-- popup included -->
</code></pre>
<p>I just couldn't find anything wrong in this. Why is this not working, any clues?</p>
<p>However, <code>$('#cl_stage1msg').html('Processing...');</code> is working fine.</p>
<p>Seems like only the post function is not getting recognised. </p>
<p>I am using <a href="https://code.jquery.com/jquery-3.1.0.slim.min.js" rel="noreferrer">https://code.jquery.com/jquery-3.1.0.slim.min.js</a></p> | 38,793,829 | 2 | 4 | null | 2016-08-05 16:16:25.973 UTC | 6 | 2020-11-15 20:03:17.323 UTC | 2016-09-17 09:46:03.623 UTC | null | 3,104,045 | null | 3,104,045 | null | 1 | 79 | javascript|jquery | 83,043 | <p>You are using the <strong>slim version</strong> of jQuery, which <strong>doesn't include the Ajax methods</strong> (in your case <code>$.post()</code>).</p>
<p>Use the <strong>non-slim build</strong>, available here <a href="http://jquery.com/download/" rel="noreferrer">http://jquery.com/download/</a>, such as:</p>
<p><code>https://code.jquery.com/jquery-3.5.1.min.js</code></p>
<hr />
<p>From <a href="https://blog.jquery.com/2016/06/09/jquery-3-0-final-released/" rel="noreferrer">jQuery 3.0 release post</a>:</p>
<blockquote>
<p>Slim build</p>
<p>[...] Sometimes you
don’t need ajax, or you prefer to use one of the many standalone
libraries that focus on ajax requests.[...] Along with the regular version of jQuery that includes the
ajax and effects modules, we’re releasing a “slim” version [...], it excludes ajax, effects, and
currently deprecated code.</p>
</blockquote> |
7,632,372 | SQL Server: Endless WHILE EXISTS loop | <p>I have problem with the following WHILE EXISTS loop. Could you consider what can be reason why it is endless loop and why it doesn't update values?</p>
<pre><code>declare @part varchar(20)
while exists ((select top 1 * from part1 p where isnull(brojRacuna,'')=''))
begin
set @part=''
set @part=(select top 1 partija from part1 p where isnull(brojRacuna,'')='')
begin tran
update part1
set BrojRacuna= (select dbo.dev_brojracuna (@part))
where partija like @part
print @part
commit
end
</code></pre>
<p><strong>EDIT 1:</strong> Because I didn't find solution in first moment, I created cursor and updated data in that way. After that I found that left couple rows that are not updated, because function had an issue with data and couldn't update values for that rows. In that case, fields have been empty always and loop became endless.</p> | 7,632,471 | 1 | 3 | null | 2011-10-03 07:54:47.257 UTC | 0 | 2016-10-25 00:09:01.623 UTC | 2011-10-03 12:29:18.937 UTC | null | 335,175 | null | 335,175 | null | 1 | 7 | sql|sql-server|tsql|loops|while-loop | 66,399 | <p>I don't understand why you select the partija value, since you have it in the where clause, you can simplify a lot this way:</p>
<pre><code>declare @part varchar(20)
while exists ((select 1 from part1 p where isnull(brojRacuna,'')='' and partija='1111'))
begin
begin tran
update part1
set BrojRacuna= (select dbo.dev_brojracuna ('1111'))
where partija like '1111'
commit
end
</code></pre>
<p>By the way, if you have an endless loop, maybe the function dev_brojracuna doesn't return the correct value, and brojRacuna remains unaltered.</p> |
24,586,257 | How to import multiple contacts vCard VCF file into Outlook? | <p>I have multiple contacts vCard VCF file created on my Android device and I would like to import it to Outlook 2010. It seems that Outlook doesn't support multiple contacts VCF file and import just first contact from such file.
Is there any way to import my 1000 contacts from such VCF file into Outlook 2010?</p> | 24,586,258 | 6 | 0 | null | 2014-07-05 12:07:13.157 UTC | null | 2022-09-08 20:46:31.887 UTC | null | null | null | null | 2,580,231 | null | 1 | 8 | import|outlook|outlook-2010|vcf-vcard | 53,238 | <p>After many tries with different 3-rd party software this workaround did the job just fine and simple:</p>
<ol>
<li>Import file (from leftside menu "Import contacts") to Google Contacts <a href="https://contacts.google.com/" rel="nofollow noreferrer">https://contacts.google.com/</a> in a group named "Imported [date]" is automatically created</li>
<li>Export (from top menu "More") "Imported [date]" group as Outlook CSV format</li>
<li>Import it to Outlook: File/Open/Import/Import from another program or file/Comma Separated Values/ Choose source file/Choose destination Outlook folder/Finish</li>
</ol>
<p>Note that Outlook failed to open the CSV file until I removed some contacts with Chinese characters.</p> |
39,130,263 | docker-proxy using port when no containers are running | <p>On a ubunty 1404 machine, docker-proxy is using port 6379, however there are no docker containers running.</p>
<pre><code>$ sudo netstat -tulpn | grep docker
tcp6 0 0 :::6379 :::* LISTEN 28438/docker-proxy
tcp6 0 0 :::2376 :::* LISTEN 28266/dockerd
$ docker ps -all
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
$
</code></pre>
<p>After I stop docker service, this process is gone, and that port is available, however when I start docker back up, docker-proxy is still using that port even though there are no docker containers running.</p>
<pre><code>$ docker info
## Output:
Containers: 0
Running: 0
Paused: 0
Stopped: 0
Images: 0
Server Version: 1.12.0
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 0
Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
Volume: local
Network: bridge null host overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Security Options: apparmor
Kernel Version: 4.2.0-38-generic
Operating System: Ubuntu 14.04.4 LTS
OSType: linux
Architecture: x86_64
CPUs: 16
Total Memory: 31.32 GiB
Name: xxxxx
ID: LILE:5WFT:2EPL:OXCN:GZG7:C4WE:AFCX:LNAT:TBMG:XQFP:QX7W:XLYK
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
WARNING: No swap limit support
Insecure Registries:
127.0.0.0/8
</code></pre> | 39,261,726 | 5 | 0 | null | 2016-08-24 18:09:40.127 UTC | 12 | 2021-10-14 09:56:46.33 UTC | null | null | null | null | 4,589,203 | null | 1 | 51 | ubuntu|docker | 23,237 | <p>Try:</p>
<p><code>
sudo service docker stop
sudo rm -f /var/lib/docker/network/files/local-kv.db
</code></p>
<p>From this <a href="https://github.com/docker/compose/issues/3277" rel="noreferrer">ticket</a>.</p> |
3,162,645 | Convert a quadratic bezier to a cubic one | <p>What is the algorithm to convert a quadratic bezier (with 3 points) to a cubic one (with 4 points)?</p> | 3,162,732 | 3 | 0 | null | 2010-07-02 00:59:02.033 UTC | 13 | 2022-05-12 15:02:34.24 UTC | 2022-05-12 15:02:34.24 UTC | null | 242,457 | null | 146,780 | null | 1 | 43 | algorithm|vector|graphics|bezier|cubic-bezier | 11,525 | <p>From <a href="https://fontforge.org/docs/techref/bezier.html#converting-truetype-to-postscript" rel="noreferrer">https://fontforge.org/docs/techref/bezier.html#converting-truetype-to-postscript</a>:</p>
<blockquote>
<p>Any quadratic spline can be expressed as a cubic (where the cubic term is zero). The end points of the cubic will be the same as the quadratic's.</p>
</blockquote>
<blockquote>
<p>CP<sub>0</sub> = QP<sub>0</sub><br/>
CP<sub>3</sub> = QP<sub>2</sub></p>
</blockquote>
<blockquote>
<p>The two control points for the cubic are:</p>
</blockquote>
<blockquote>
<p>CP<sub>1</sub> = QP<sub>0</sub> + 2/3 *(QP<sub>1</sub>-QP<sub>0</sub>)<br/>
CP<sub>2</sub> = QP<sub>2</sub> + 2/3 *(QP<sub>1</sub>-QP<sub>2</sub>)</p>
</blockquote>
<blockquote>
<p>...There is a slight error introduced due to rounding, but it is unlikely to be noticeable.</p>
</blockquote> |
2,701,547 | How to make System command calls in Java/Groovy? | <p>What I want to do is invoke maven from a groovy script. The groovy script in question is used as a maven wrapper to build J2EE projects by downloading a tag and invoking maven on what was downloaded. How should I accomplish invoking maven to build/package the EAR (the groovy script is already capable of downloading the tag from SCM).</p> | 2,702,668 | 4 | 0 | null | 2010-04-23 19:48:26.33 UTC | 11 | 2019-10-25 07:54:00.33 UTC | 2010-04-23 20:06:16.65 UTC | null | 17,675 | null | 17,675 | null | 1 | 40 | command-line|groovy|build-automation | 65,772 | <p>The simplest way to invoke an external process in Groovy is to use the execute() command on a string. For example, to execute maven from a groovy script run this:</p>
<pre><code>"cmd /c mvn".execute()
</code></pre>
<p>If you want to capture the output of the command and maybe print it out, you can do this:</p>
<pre><code>print "cmd /c mvn".execute().text
</code></pre>
<p>The 'cmd /c' at the start invokes the Windows command shell. Since mvn.bat is a batch script you need this. For Unix you can invoke the system shell.</p> |
2,682,147 | Where is the System.Runtime.Serialization.Json namespace? | <p>I've added the reference to <strong>System.Runtime.Serialization</strong> dll to my project but still can't find the <strong>System.Runtime.Serialization.Json</strong> namespace and hence can't find the <strong>DataContractJsonSerializer</strong> class. What am I missing here?</p> | 2,682,197 | 4 | 0 | null | 2010-04-21 10:40:42.127 UTC | 4 | 2017-09-22 23:18:25.127 UTC | null | null | null | null | 309,699 | null | 1 | 52 | c#|asp.net|asp.net-mvc|json|serialization | 51,147 | <p>Try in System.ServiceModel.Web.dll</p> |
28,895,067 | Using UUIDs instead of ObjectIDs in MongoDB | <p>We are migrating a database from MySQL to MongoDB for performance reasons and considering what to use for IDs of the MongoDB documents. We are debating between using ObjectIDs, which is the MongoDB default, or using UUIDs instead (which is what we have been using up until now in MySQL). So far, the arguments we have to support any of these options are the following:</p>
<p><strong>ObjectIDs:</strong>
ObjectIDs are the MongoDB default and I assume (although I'm not sure) that this is for a reason, meaning that I expect that MongoDB can handle them more efficiently than UUIDs or has another reason for preferring them. I also found <a href="https://stackoverflow.com/a/22607171/267121">this stackoverflow answer</a> that mentions that usage of ObjectIDs makes indexing more efficient, it would be nice however to have some metrics on how much this "more efficient" is.</p>
<p><strong>UUIDs:</strong>
Our basic argument in favour of using UUIDs (and it is a quite important one) is that they are supported, one way or another, by virtually any database. This means that if some way down the road we decide to switch from MongoDB to something else for whatever reason and we already have an API that retrieves documents from the DB based on their IDs nothing changes for the clients of this API since the IDs can continue to be exactly the same. If we were to use ObjectIDs I'm not really sure how we would go about migrating them to another DB.</p>
<p>Does anyone have any insights on whether one of these options may be better than the other and why? Have you ever used UUIDs in MongoDB instead of ObjectIDs and if yes what were the advantages / problems you came across?</p> | 51,777,857 | 8 | 0 | null | 2015-03-06 08:43:11.827 UTC | 31 | 2022-07-20 10:30:36.953 UTC | 2019-04-24 09:42:18.507 UTC | null | 1,225,882 | null | 267,121 | null | 1 | 120 | mongodb | 74,989 | <p>Using UUIDs in Mongo is certainly possible and reasonably well supported. For example, the Mongo docs list UUIDs as one of the common options for <a href="https://docs.mongodb.com/manual/core/document/#the-_id-field" rel="noreferrer">the <code>_id</code> field</a>.</p>
<h3>Considerations</h3>
<ul>
<li><strong>Performance</strong> – As other answers mention, <a href="https://github.com/Restuta/mongo.Guid-vs-ObjectId-performance" rel="noreferrer">benchmarks</a> show UUIDs cause a performance drop for inserts. In the worst case measured (going from 10M to 20M docs in a collection) they've about ~2-3x slower – the difference between inserting 2,000 (UUID) and 7,500 (ObjectID) docs per second. This is a large difference but its significance depends entirely on you use case. Will you be batch inserting millions of docs at a time? For most apps I've build the common case is inserting individual documents. The same benchmarks show that, for that usage pattern, the difference is <em>much</em> smaller (6,250 -vs- 7,500; ~20%). Not insignificant.. but not earth shattering either.</li>
<li><strong>Portability</strong> – Many other DB platforms have good UUID support so portability would be improved. Alternatively, since UUIDs are larger (more bits) it is possible to <a href="https://gist.github.com/enaeseth/5768348" rel="noreferrer">repack an ObjectID into the "shape" of a UUID</a>. This approach isn't as nice as direct portability but it does give you a way to "map" between existing ObjectIDs and UUIDs.</li>
<li><strong>Decentralisation</strong> – One of the big selling points of UUIDs is that they're universally unique. This makes it practical to generate them anywhere, in a decentralised fashion (in contrast to, for example an auto-incrementing value, that requires a centralised source of truth to determine the "next" value). Of course, Mongo Object IDs profess this benefit too. The difference is, UUIDs are based on a 15+ year old standard and supported on (nearly?) all platforms, languages, etc. This makes them very useful if you ever need to create entities (or specifically, sets of <em>related</em> entities) in disjointed systems, without interacting with the database. You can create a dataset with IDs and foreign keys in place, then write the whole graph into the database at some point in the future without conflict. Although this is also possible with Mongo ObjectIDs, finding code to generate them/work with the format will often be harder.</li>
</ul>
<h3>Corrections</h3>
<p>Contrary to some of the other answers:</p>
<ul>
<li><strong>UUIDs do have native Mongo support</strong> – You can use the <a href="https://docs.mongodb.com/manual/reference/method/UUID" rel="noreferrer"><code>UUID()</code> function</a> in the Mongo Shell exactly the same way you'd use <code>ObjectID()</code>; to <a href="https://docs.mongodb.com/manual/reference/method/UUID/#convert-character-string-to-uuid" rel="noreferrer">convert a UUID string into equivalent BSON object</a>.</li>
<li><strong>UUIDs are not especially large</strong> – When encoded using binary subtype <code>0x04</code> they're 128 bits, compared to 96 bits for ObjectIDs. (If encoded as strings they <em>will</em> be pretty wasteful, taking around 288 bits.)</li>
<li><strong>UUIDs can include a timestamp</strong> – Specifically, UUIDv1 encodes a timestamp with 60 bits of precision, compared to 32 bits in ObjectIDs. This is over 6 orders of magnitude more precision, so nano-seconds instead of seconds. It can actually be a decent way of storing create timestamps with more accuracy than Mongo/JS Date objects support, however...
<ul>
<li>The build in <code>UUID()</code> function only generates v4 (random) UUIDs so, to leverage this this, you'd to lean on on your app or Mongo driver for ID creation.</li>
<li>Unlike ObjectIDs, because of <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier#Format" rel="noreferrer">the way UUIDs are chunked</a>, the timestamp doesn't give you a natural order. This can be good or bad depending on your use case. (New standards may change this; see 2021 update below.)</li>
<li>Including timestamps in your IDs is sometimes a Bad Idea. You end up leaking the created time of documents anywhere an ID is exposed. (Of course ObjectIDs also encode a timestamp so this is partly true for them too.)</li>
<li>If you do this with (spec compliant) v1 UUIDs, you're also encoding part of the servers MAC address, which can <em>potentially</em> be used to identify the machine. Probably not an issue for most systems but also not ideal. (New standards may change this; see 2021 update below.)</li>
</ul>
</li>
</ul>
<h3>Conclusion</h3>
<p>If you think about your Mongo DB in isolation, ObjectIDs are the obvious choice. They work well out of the box and are a perfectly capable default. Using UUIDs instead <em>does</em> add some friction, both when working with the values (needing to convert to binary types, etc.) and in terms of performance. Whether this slight inconvenience is worth having a standardised ID format really depends on the importance you place on portability and your architectural choices.</p>
<p>Will you be syncing data between different database platforms? Will you migrate your data to a different platform in the future? Do you need to generate IDs <em>outside</em> the database, in other systems or in the browser? If not now at some point in the future? UUIDs might be worth the hassle.</p>
<h3>Aug 2021 Update</h3>
<p>The IEFT recently published a draft update to the UUID spec that would introduce some new versions of the format.</p>
<p>Specifically, <a href="https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format#section-4.3" rel="noreferrer">UUIDv6</a> and <a href="https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format#section-4.4" rel="noreferrer">UUIDv7</a> are based on UUIDv1 but flip the timestamp chunks so the bits are arranged from most significant to least significant. This gives the resultant values a natural order that (more or less) reflects the order in which they were created. The new versions also exclude data derived from the servers MAC address, addressing a long-standing criticism of v1 UUIDs.</p>
<p>It'll take time for these changes to flow though to implementations but (IMHO) they significantly modernise and improve the format.</p> |
38,056,774 | Spark cache vs broadcast | <p>It looks like broadcast method makes a distributed copy of RDD in my cluster. On the other hand execution of cache() method simply loads data in memory. </p>
<p>But I do not understand how does cached RDD is distributed in the cluster.</p>
<p>Could you please tell me in what cases should I use <code>rdd.cache()</code> and <code>rdd.broadcast()</code> methods? </p> | 38,056,939 | 4 | 1 | null | 2016-06-27 14:37:15.217 UTC | 16 | 2017-12-17 17:13:15.933 UTC | 2016-06-27 14:51:40.14 UTC | null | 1,870,803 | null | 1,545,453 | null | 1 | 27 | caching|apache-spark | 25,873 | <blockquote>
<p>Could you please tell me in what cases should I use rdd.cache() and
rdd.broadcast() methods?</p>
</blockquote>
<p>RDDs are divided into <em>partitions</em>. These partitions themselves act as an immutable subset of the entire RDD. When Spark executes each stage of the graph, each partition gets sent to a worker which operates on the subset of the data. In turn, each worker can <em>cache</em> the data if the RDD needs to be re-iterated.</p>
<p>Broadcast variables are used to send some immutable state <em>once</em> to each worker. You use them when you want a local copy of a variable.</p>
<p>These two operations are quite different from each other, and each one represents a solution to a different problem.</p> |
56,532,366 | Using @ViewBuilder to create Views which support multiple children | <p>Some Views in SwiftUI, like VStack and HStack support having multiple views as children, like this:</p>
<pre class="lang-swift prettyprint-override"><code>VStack {
Text("hello")
Text("world")
}
</code></pre>
<p>From what I gather, they use <a href="https://developer.apple.com/documentation/swiftui/viewbuilder" rel="noreferrer">ViewBuilder</a> to make this possible as explained <a href="https://stackoverflow.com/questions/56434549/what-enables-swiftuis-dsl/56435128#56435128">here</a>. </p>
<p>How can we use @ViewBuilder for creating our own Views which support multiple children? For example, let's say that I want to create a <code>Layout</code> View which accepts arbitrary children -- something like this:</p>
<pre class="lang-swift prettyprint-override"><code>struct Layout : View {
let content: Some View
var body : some View {
VStack {
Text("This is a layout")
content()
}
}
}
</code></pre>
<p>Any idea how to implement this pattern in SwiftUI? </p> | 56,533,097 | 2 | 0 | null | 2019-06-10 19:21:18.663 UTC | 12 | 2019-06-10 21:34:04.32 UTC | null | null | null | null | 1,198,166 | null | 1 | 28 | swift|swiftui | 16,824 | <p>Here's an example view that does nothing, just to demonstrate how to use <code>@ViewBuilder</code>.</p>
<pre class="lang-swift prettyprint-override"><code>struct Passthrough<Content>: View where Content: View {
let content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
content()
}
}
</code></pre>
<p>Usage:</p>
<pre class="lang-swift prettyprint-override"><code>Passthrough {
Text("one")
Text("two")
Text("three")
}
</code></pre> |
38,290,143 | Difference between become and become_user in Ansible | <p>Recently I started digging into Ansible and writing my own playbooks. However, I have a troubles with understanding difference between <code>become</code> and <code>become_user</code>.
As I understand it <code>become_user</code> is something similar to <code>su <username></code>, and <code>become</code> means something like <code>sudo su</code> or "perform all commands as a sudo user". But sometimes these two directives are mixed. </p>
<p>Could you explain the correct meaning of them?</p> | 38,290,243 | 4 | 0 | null | 2016-07-10 08:42:22.91 UTC | 21 | 2022-07-19 18:21:05.273 UTC | 2022-07-19 18:21:05.273 UTC | null | 967,621 | null | 1,755,357 | null | 1 | 68 | ansible|root|ansible-2.x | 93,355 | <p><code>become_user</code> defines the user which is being used for <a href="http://docs.ansible.com/ansible/become.html" rel="noreferrer">privilege escalation</a>.</p>
<p><code>become</code> simply is a flag to either activate or deactivate the same.</p>
<p>Here are three examples which should make it clear:</p>
<ol>
<li><p>This task will be executed as <code>root</code>, because <code>root</code> is the default user for privilege escalation:</p>
<pre><code> - do: something
become: true
</code></pre>
</li>
<li><p>This task will be executed as user <code>someone</code>, because the user is explicitly set:</p>
<pre><code> - do: something
become: true
become_user: someone
</code></pre>
</li>
<li><p>This task will not do anything with <code>become_user</code>, because <code>become</code> is not set and defaults to <code>false</code>/<code>no</code>:</p>
<pre><code> - do: something
become_user: someone
</code></pre>
</li>
</ol>
<p>...unless become was set to <code>true</code> on a higher level, e.g. a block, the playbook, group or host-vars etc.</p>
<p>Here is an example with a <a href="https://docs.ansible.com/ansible/2.5/user_guide/playbooks_blocks.html" rel="noreferrer">block</a>:</p>
<pre><code> - become: true
block:
- do: something
become_user: someone
- do: something
</code></pre>
<p>The first 1st is ran as user <code>someone</code>, the 2nd as <code>root</code>.</p>
<blockquote>
<p>As I understand it become_user is something similar to su , and become means something like sudo su or "perform all commands as a sudo user".</p>
</blockquote>
<p>The default <code>become_method</code> is <code>sudo</code>, so <code>sudo do something</code> or <code>sudo -u <become_user> do something</code></p>
<p><sub><sup>Fineprint: Of course "<em>do: something</em>" is pseudocode. Put your actual Ansible module there.</sup></sub></p> |
2,721,546 | Why don't Java Generics support primitive types? | <p>Why do generics in Java work with classes but not with primitive types?</p>
<p>For example, this works fine:</p>
<pre><code>List<Integer> foo = new ArrayList<Integer>();
</code></pre>
<p>but this is not allowed:</p>
<pre><code>List<int> bar = new ArrayList<int>();
</code></pre> | 2,721,557 | 5 | 1 | null | 2010-04-27 13:24:17.633 UTC | 97 | 2020-06-03 19:50:19.527 UTC | 2017-12-18 11:58:03.857 UTC | null | 1,898,563 | null | 202,375 | null | 1 | 278 | java|generics|primitive | 95,811 | <p>Generics in Java are an entirely compile-time construct - the compiler turns all generic uses into casts to the right type. This is to maintain backwards compatibility with previous JVM runtimes.</p>
<p>This:</p>
<pre><code>List<ClassA> list = new ArrayList<ClassA>();
list.add(new ClassA());
ClassA a = list.get(0);
</code></pre>
<p>gets turned into (roughly):</p>
<pre><code>List list = new ArrayList();
list.add(new ClassA());
ClassA a = (ClassA)list.get(0);
</code></pre>
<p>So, anything that is used as generics has to be convertable to Object (in this example <code>get(0)</code> returns an <code>Object</code>), and the primitive types aren't. So they can't be used in generics.</p> |
2,601,620 | Why does select SCOPE_IDENTITY() return a decimal instead of an integer? | <p>So I have a table with an identity column as the primary key, so it is an integer. So, why does <code>SCOPE_IDENTITY()</code> always return a decimal value instead of an int to my C# application? This is really annoying since decimal values will not implicitly convert to integers in C#, which means I now have to rewrite a bunch of stuff and have a lot of helper methods because I use SQL Server and Postgres, which Postgres does return an integer for the equivalent function..</p>
<p>Why does <code>SCOPE_IDENTITY()</code> not just return a plain integer? Are there people out there that commonly use decimal/non-identity values for primary keys?</p> | 2,601,878 | 5 | 0 | null | 2010-04-08 16:20:53.27 UTC | 10 | 2020-12-04 14:17:42.273 UTC | null | null | null | null | 69,742 | null | 1 | 98 | sql-server|primary-key|scope-identity | 30,464 | <p>In SQL Server, the <code>IDENTITY</code> property can be assigned to <code>tinyint</code>, <code>smallint</code>, <code>int</code>, <code>bigint</code>, <code>decimal(p, 0)</code>, or <code>numeric(p, 0)</code> columns. Therefore the <code>SCOPE_IDENTITY</code> function has to return a data type that can encompass all of the above.</p>
<p>As previous answers have said, just cast it to <code>int</code> on the server before returning it, then ADO.NET will detect its type as you expect.</p> |
2,480,584 | How do I use a file grep comparison inside a bash if/else statement? | <p>When our server comes up we need to check a file to see how the server is configured. </p>
<p>We want to search for the following string inside our /etc/aws/hosts.conf file: </p>
<pre><code>MYSQL_ROLE=master
</code></pre>
<p>Then, we want to test whether that string exists and use an if/else statement to run one of two options depending on whether the string exists or not. </p>
<p>What is the BASH syntax for the if statement? </p>
<pre><code>if [ ????? ]; then
#do one thing
else
#do another thing
fi
</code></pre> | 2,480,611 | 5 | 0 | null | 2010-03-19 21:06:22.553 UTC | 27 | 2021-09-21 14:44:06.05 UTC | null | null | null | null | 77,413 | null | 1 | 147 | bash | 231,510 | <p>From <code>grep --help</code>, but also see <a href="http://google.com/search?q=man+grep" rel="noreferrer">man grep</a>:</p>
<blockquote>
<p>Exit status is 0 if any line was selected, 1 otherwise;
if any error occurs and -q was not given, the exit status is 2.</p>
</blockquote>
<pre><code>if grep --quiet MYSQL_ROLE=master /etc/aws/hosts.conf; then
echo exists
else
echo not found
fi
</code></pre>
<p>You may want to use a more specific regex, such as <code>^MYSQL_ROLE=master$</code>, to avoid that string in comments, names that merely start with "master", etc.</p>
<p>This works because the <em>if</em> takes a command and runs it, and uses the return value of that command to decide how to proceed, with zero meaning true and non-zero meaning false—the same as how other return codes are interpreted by the shell, and the opposite of a language like C.</p> |
2,741,312 | Using CSS to insert text | <p>I'm relatively new to CSS, and have used it to change the style and formatting of text.</p>
<p>I would now like to use it to insert text as shown below:</p>
<pre><code><span class="OwnerJoe">reconcile all entries</span>
</code></pre>
<p>Which I hope I could get to show as:</p>
<p><strong>Joe's Task: reconcile all entries</strong></p>
<p>That is, simply by virtue of being of class "Owner Joe", I want the text <code>Joe's Task:</code> to be displayed.</p>
<p>I could do it with code like:</p>
<pre><code><span class="OwnerJoe">Joe's Task:</span> reconcile all entries.
</code></pre>
<p>But that seems awfully redundant to both specify the class and the text.</p>
<p>Is it possible to do what I'm looking for?</p>
<p><strong>EDIT</strong> One idea is to try to set it up as a ListItem <code><li></code> where the "bullet" is the text "Joe's Task". I see examples of how to set various bullet-styles and even images for bullets. Is it possible to use a small block of text for the list-bullet?</p> | 2,741,342 | 5 | 4 | null | 2010-04-29 23:08:34.157 UTC | 42 | 2022-03-17 01:42:51.607 UTC | 2010-04-29 23:14:45.28 UTC | null | 34,824 | null | 34,824 | null | 1 | 252 | html|css | 513,876 | <p>It is, but requires a CSS2 capable browser (all major browsers, IE8+).</p>
<pre class="lang-css prettyprint-override"><code>.OwnerJoe:before {
content: "Joe's Task: ";
}
</code></pre>
<p>But I would rather recommend using Javascript for this. With jQuery:</p>
<pre class="lang-js prettyprint-override"><code>$('.OwnerJoe').each(function() {
$(this).before($('<span>').text("Joe's Task: "));
});
</code></pre> |
2,620,419 | .net dictionary and lookup add / update | <p>I am sick of doing blocks of code like this for various bits of code I have:</p>
<pre><code>if (dict.ContainsKey[key]) {
dict[key] = value;
}
else {
dict.Add(key,value);
}
</code></pre>
<p>and for lookups (i.e. key -> list of value)</p>
<pre><code>if (lookup.ContainsKey[key]) {
lookup[key].Add(value);
}
else {
lookup.Add(new List<valuetype>);
lookup[key].Add(value);
}
</code></pre>
<p>Is there another collections lib or extension method I should use to do this in one line of code no matter what the key and value types are?</p>
<p>e.g.</p>
<pre><code>dict.AddOrUpdate(key,value)
lookup.AddOrUpdate(key,value)
</code></pre> | 2,620,451 | 6 | 1 | null | 2010-04-12 07:11:46.767 UTC | 5 | 2015-09-27 10:16:45.507 UTC | 2010-04-12 07:19:51.737 UTC | null | 76,337 | null | 88,091 | null | 1 | 39 | c#|collections | 23,730 | <p>As Evgeny says, the indexer will already replace existing values - so if you <em>just</em> want to unconditionally set the value for a given key, you can do</p>
<pre><code>dictionary[key] = value;
</code></pre>
<p>The more interesting case is the "get a value, or insert it if necessary". It's easy to do with an extension method:</p>
<pre><code>public static TValue GetOrCreateValue<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary,
TKey key,
TValue value)
{
return dictionary.GetOrCreateValue(key, () => value);
}
public static TValue GetOrCreateValue<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary,
TKey key,
Func<TValue> valueProvider)
{
TValue ret;
if (!dictionary.TryGetValue(key, out ret))
{
ret = valueProvider();
dictionary[key] = ret;
}
return ret;
}
</code></pre>
<p>Note the use of a delegate to create the default value - that facilitates scenarios like the "list as value" one; you don't want to create the empty list unless you have to:</p>
<pre><code>dict.GetOrCreateValue(key, () => new List<int>()).Add(item);
</code></pre>
<p>Also note how this only performs the lookup once if the key is already present - there's no need to do a <code>ContainsKey</code> and <em>then</em> look up the value. It still requires two lookups when it's creating the new value though.</p> |
2,625,294 | How do I autoformat some Python code to be correctly formatted? | <p>I have some existing code which isn't formatted consistently -- sometimes two spaces are used for indent, sometimes four, and so on. The code itself is correct and well-tested, but the formatting is awful.</p>
<p>Is there a place online where I can simply paste a snippet of Python code and have it be indented/formatted automatically for me? Alternatively, is there an <code>X</code> such that I can do something like <code>X --input=*.py</code> and have it overwrite each file with a formatted version?</p> | 2,625,361 | 7 | 2 | null | 2010-04-12 20:42:57.67 UTC | 25 | 2022-07-25 01:08:15.13 UTC | null | null | null | null | 75,170 | null | 1 | 104 | python|formatting | 124,560 | <p>Edit: Nowadays, I would recommend <a href="https://github.com/hhatto/autopep8" rel="noreferrer">autopep8</a>, since it not only corrects indentation problems but also (at your discretion) makes code conform to many other PEP8 guidelines.</p>
<hr>
<p>Use <code>reindent.py</code>. It should come with the standard distribution of Python, though on Ubuntu you need to install the <code>python2.6-examples</code> package.</p>
<p>You can also find it on the <a href="http://svn.python.org/projects/python/trunk/Tools/scripts/reindent.py" rel="noreferrer">web</a>.</p>
<p>This script attempts to convert any python script to conform with the 4-space standard.</p> |
2,540,277 | jQuery counter to count up to a target number | <p>I'm trying to find out if anyone knows about an already existing jQuery plugin that will count up to a target number at a specified speed.</p>
<p>For example, take a look at Google's number of MB of free storage on the <a href="http://gmail.com" rel="noreferrer">Gmail homepage</a>, under the heading that reads "Lots of space". It has a starting number in a <code><span></code> tag, and slowly counts upward every second.</p>
<p>I'm looking for something similar, but I'd like to be able to specify:</p>
<ul>
<li>The start number</li>
<li>The end number</li>
<li>The amount of time it should take to get from start to end.</li>
<li>A custom callback function that can execute when a counter is finished.</li>
</ul> | 2,540,673 | 11 | 0 | null | 2010-03-29 18:23:49.98 UTC | 44 | 2021-06-03 13:55:53.94 UTC | null | null | null | null | 107,277 | null | 1 | 48 | jquery|jquery-plugins|timer|counter | 202,092 | <p>I ended up creating my own plugin. Here it is in case this helps anyone:</p>
<pre><code>(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
</code></pre>
<p>Here's some sample code of how to use it:</p>
<pre><code><script type="text/javascript"><!--
jQuery(function($) {
$('.timer').countTo({
from: 50,
to: 2500,
speed: 1000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
//--></script>
<span class="timer"></span>
</code></pre>
<p>View the demo on JSFiddle: <a href="http://jsfiddle.net/YWn9t/" rel="nofollow noreferrer">http://jsfiddle.net/YWn9t/</a></p> |
25,210,330 | Script for clearing Chrome or Firefox cache on Windows | <p>With Internet Explorer you can create a <code>.bat</code> file to clear the cache.</p>
<p>Example:</p>
<pre><code>RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255
REM History:
REM RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1
REM Cookies:
REM RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2
REM Temp Internet Files:
REM RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
REM Form Data:
REM RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16
REM Passwords:
REM RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32
REM OR
REM All:
rundll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351
</code></pre>
<p>Is there any way to do this with Chrome and/or Firefox ?</p>
<p>That is, with a <code>.bat</code> file or powershell script, running on a Windows machine, clear the cache of Chrome or Firefox?</p>
<p>I promise, I've looked.</p> | 25,213,068 | 3 | 0 | null | 2014-08-08 18:49:50.533 UTC | 10 | 2019-10-21 17:06:39.523 UTC | 2016-11-23 09:43:32.85 UTC | null | 911,419 | null | 214,977 | null | 1 | 10 | google-chrome|powershell|firefox|windows-7|browser-cache | 96,716 | <p>In Chrome, you can clear the cache by deleting the contents of the Cache folder in <code>%LocalAppData%\Google\Chrome\User Data\Default\Cache</code>. The history, cookies, and so on are SQLite database files in the parent folder, so you could get rid of them too if you wanted everything gone, like in your example with Internet Explorer:</p>
<pre><code>$Items = @('Archived History',
'Cache\*',
'Cookies',
'History',
'Login Data',
'Top Sites',
'Visited Links',
'Web Data')
$Folder = "$($env:LOCALAPPDATA)\Google\Chrome\User Data\Default"
$Items | % {
if (Test-Path "$Folder\$_") {
Remove-Item "$Folder\$_"
}
}
</code></pre> |
45,615,591 | How does "only:" at "before_action" work in Rails? | <p>After scaffold generation we usually get a line like that:</p>
<pre class="lang-ruby prettyprint-override"><code>before_action :set_newsletter_email, only: [:show, :edit, :update, :destroy]
</code></pre>
<p>Could someone explain to me how exactly this <code>only:</code> symbol works?</p> | 45,615,785 | 3 | 0 | null | 2017-08-10 13:47:15.377 UTC | 3 | 2022-07-06 14:56:43.517 UTC | 2022-07-06 14:56:43.517 UTC | null | 74,089 | null | 3,668,967 | null | 1 | 35 | ruby-on-rails | 43,703 | <p>The <code>only</code> option of <code>before_action</code> defines one action OR a list of actions when the method/block will be executed first.</p>
<p>Ex:</p>
<pre><code># defined actions: [:show, :edit, :update, :destroy]
before_action :set_newsletter_email, only: [:show, :edit]
</code></pre>
<p>The <code>set_newsletter_email</code> method will be called just before the <code>show</code> and <code>edit</code> actions.</p>
<hr />
<p>The opposite option <code>except</code> define when NOT to execute the method/block.</p>
<pre><code># defined actions: [:show, :edit, :update, :destroy]
before_action :set_newsletter_email, except: [:show, :edit]
</code></pre>
<p>The <code>set_newsletter_email</code> method will be called for all existing actions EXCEPT <code>show</code> and <code>edit</code>.</p>
<hr />
<p><code>only</code> / <code>except</code> is just a kind of whitelist/blacklist.</p> |
42,374,151 | All com.android.support libraries must use the exact same version specification | <p>After updating to android studio 2.3 I got this error message.
I know it's just a hint as the app run normally but it's really strange.</p>
<blockquote>
<p>All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.1.1, 24.0.0. Examples include com.android.support:animated-vector-drawable:25.1.1 and com.android.support:mediarouter-v7:24.0.0</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/trji5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/trji5.png" alt="enter image description here"></a></p>
<p>my gradle:</p>
<pre><code>dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support:support-v4:25.1.1'
compile 'com.android.support:design:25.1.1'
compile 'com.android.support:recyclerview-v7:25.1.1'
compile 'com.android.support:cardview-v7:25.1.1'
compile 'com.google.android.gms:play-services-maps:10.2.0'
compile 'com.google.android.gms:play-services:10.2.0'
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
compile 'com.blankj:utilcode:1.3.6'
compile 'com.orhanobut:logger:1.15'
compile 'com.facebook.stetho:stetho:1.4.2'
provided 'com.google.auto.value:auto-value:1.2'
annotationProcessor 'com.google.auto.value:auto-value:1.2'
annotationProcessor 'com.ryanharter.auto.value:auto-value-parcel:0.2.5'
compile 'com.mikepenz:iconics-core:2.8.2@aar'
compile('com.mikepenz:materialdrawer:5.8.1@aar') { transitive = true }
compile 'com.mikepenz:google-material-typeface:2.2.0.3.original@aar'
compile 'me.zhanghai.android.materialprogressbar:library:1.3.0'
compile 'com.github.GrenderG:Toasty:1.1.1'
compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.8.0'
compile 'com.github.MAXDeliveryNG:slideview:1.0.0'
compile 'com.facebook.fresco:fresco:1.0.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.google.maps.android:android-maps-utils:0.4.4'
compile 'com.github.jd-alexander:library:1.1.0'
}
</code></pre> | 42,374,426 | 54 | 1 | null | 2017-02-21 17:35:02.123 UTC | 231 | 2022-09-15 12:34:56.683 UTC | 2019-06-22 10:16:05.217 UTC | null | 6,296,561 | null | 3,998,402 | null | 1 | 802 | android|build.gradle | 388,111 | <p>You can solve this with one of the following solutions:</p>
<h2>Update:</h2>
<p>As of Android studio 3.0, it becomes much easier as it now shows a more helpful hint, so we only need to follow this hint.<br>
for example:
<img src="https://i.stack.imgur.com/BObtK.png" alt="1]"></p>
<blockquote>
<p>All com.android.support libraries must use the exact same version
specification (mixing versions can lead to runtime crashes). Found
versions 27.0.2, 26.1.0. Examples include
com.android.support:animated-vector-drawable:27.0.2 and
com.android.support:customtabs:26.1.0</p>
<p>there are some combinations of libraries, or tools and libraries, that
are incompatible, or can lead to bugs. One such incompatibility is
compiling with a version of the Android support libraries that is not
the latest version (or in particular, a version lower than your
targetSdkVersion.)</p>
</blockquote>
<p><strong>Solution:</strong><br>
Add explicitly the library with the old version but with a new version number.<br>
in my case <code>com.android.support:customtabs:26.1.0</code> so I need to add: </p>
<pre><code>implementation "com.android.support:customtabs:27.0.2"
</code></pre>
<p>ie: Take the library from the second item, and implement it with the version number from the first.</p>
<p>Note: don't forget to press sync now so gradle can rebuild the dependency graph and see if there are any more conflicts.</p>
<p><strong>Explanation:</strong><br>
you may be confused by the error message as don't use <code>customtabs</code> so how I have a conflict!!<br>
well.. you didn't use it directly but one of your libraries uses an old version of <code>customtabs</code> internally, so you need to ask for it directly. </p>
<p>if you curious to know which of your libraries is responsible for the old version and maybe ask the author to update his lib, Run a Gradle dependency report, see the old answer to know how.</p>
<p>Note this </p>
<hr>
<h2>Old answer:</h2>
<p>inspired by <a href="https://stackoverflow.com/a/42582204/1843331">CommonsWare answer</a>:</p>
<p>Run a Gradle dependency report to see what your full tree of
dependencies is.</p>
<p>From there, you will see which one of your libraries are asking for a different version of the Android Support libraries.
For whatever it is asking for, you can ask for it directly with the
25.2.0 version or use Gradle's other conflict resolution approaches to get the same versions.</p>
<hr>
<h2>Update:</h2>
<p>As of gradle plugin version: 3.0 <code>compile</code> has been replaced by <code>implementation</code> or <code>api</code> see <a href="https://stackoverflow.com/a/44493379/3998402">this answer</a> for the difference.</p>
<p>hence use instead:</p>
<pre><code>./gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath
</code></pre>
<p>or for windows cmd: </p>
<pre><code>gradlew -q dependencies app:dependencies --configuration debugAndroidTestCompileClasspath
</code></pre>
<p>and search for the conflicted version.</p>
<p>For me, the error disappeared after removing <code>com.google.android.gms:play-services:10.2.0</code></p>
<p>And only include <code>com.google.android.gms:play-services-location:10.2.0</code> and <code>com.google.android.gms:play-services-maps:10.2.0</code> as they are the only two play services that I use.</p>
<p>I think the <code>gms:play-services</code> depend on some old components of the support library, so we need to add them explicitly ourselves.</p>
<hr>
<p>for AS 3.0 an older.</p>
<p>Run:</p>
<pre><code>./gradlew -q dependencies <module-name>:dependencies --configuration implementation
</code></pre>
<p>Example:</p>
<pre><code>./gradlew -q dependencies app:dependencies --configuration implementation
</code></pre>
<hr>
<p>if someone knows a better way in the new gradle plugin please let me know.</p> |
5,645,916 | Getting server address and application name | <p>Environment: NetBeans 6.9.1, GlassFish 3.1</p>
<p>I have a Java Web Application. How to get the server address and the application name dynamically? The '2in1' solution would be the best for me: <code>http://localhost:8080/AppName/</code>.</p>
<p>Is there a practical way to get that information?</p>
<p>Let's say the value of <code>AppName</code> will be fixed, so I only need the host address. Is it possible to retrieve it via JMX? Any other ways?</p> | 5,648,259 | 2 | 0 | null | 2011-04-13 07:41:00.007 UTC | 3 | 2018-05-24 06:28:20.323 UTC | 2018-05-24 06:28:20.323 UTC | null | 6,296,561 | null | 157,762 | null | 1 | 8 | java|servlets|jmx | 46,361 | <p>The <code>HttpServletRequest</code> object will give you what you need:</p>
<ul>
<li><code>HttpServletRequest#getLocalAddr()</code>: The server's IP address as a string</li>
<li><code>HttpServletRequest#getLocalName()</code>: The name of the server receiving the request</li>
<li><code>HttpServletRequest#getServerName()</code>: The name of the server that the request was sent to</li>
<li><code>HtppServletRequest#getLocalPort()</code>: The port the server received the request on</li>
<li><code>HttpServletRequest#getServerPort()</code>: The port the request was sent to</li>
<li><code>HttpServletRequest#getContextPath()</code>: The part of the path that identifies the application</li>
</ul> |
5,734,763 | System.Drawing.Brush from System.Drawing.Color | <p>I'm developing a WinForm Printing application for our company.</p>
<p>When the document is printed, I need to take the <code>System.Drawing.Color</code> property of each Control on the document and create a <code>System.Drawing.Brush</code> object to draw it.</p>
<p>Is there a way to convert the <code>System.Drawing.Color</code> value to a <code>System.Drawing.Brush</code> value?</p>
<p>NOTE: I've tried looking into the <code>System.Windows.Media.SolidColorBrush()</code> method, but it does not seem to be helpful.</p> | 5,734,807 | 2 | 0 | null | 2011-04-20 18:14:41.02 UTC | 4 | 2011-04-20 18:18:20.773 UTC | null | null | null | null | 153,923 | null | 1 | 35 | c#|winforms|system.drawing|printdocument|system.drawing.color | 35,004 | <p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.drawing.solidbrush.aspx">SolidBrush</a> class:</p>
<pre><code>using (SolidBrush brush = new SolidBrush(yourColor)) {
// ...
}
</code></pre> |
5,659,068 | Jni Tutorial for android | <p>Hi, can anyone suggest me some good resources to learn JNI for Android and some good JNI Tutorials?</p> | 10,315,838 | 2 | 2 | null | 2011-04-14 05:47:09.997 UTC | 29 | 2015-06-25 13:21:04.627 UTC | 2012-04-06 05:22:40.587 UTC | null | 669,265 | null | 587,012 | null | 1 | 54 | android|java-native-interface | 58,575 | <p>I would suggest downloading the ndk. Unzip it and browse the sample folder <a href="http://developer.android.com/sdk/ndk/index.html">ndk</a> codes. Start with the hello-jni and go further. It explains a lot with ease.
You can also browse <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/jniTOC.html">these</a> <a href="http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html">links</a> and <a href="http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html">this</a> while going through the code and keep coming back and forth.</p> |
23,129,054 | Integration of python in C# Application | <p>I have the following problem:
I got an old application which is written in python. This application allows the user to specify small python steps which will be executed, python steps are basically small python scripts, I call them steps because the execution of this application involves other steps like executing something from commandline. These python steps are stored as python code in an xml file.</p>
<p>Now I want to rewrite the application by using C# .NET. Is there a best practise solution to do something like this?</p>
<p>I don't want to call python as external programm and pass the actual python step(script) to the python interpreter - I want something built in. I just came across IronPython and .NET python but I am not quite sure which one to use.
I want to achieve some sort of debugging for the small scripts, that is why the call the interpreter solution is not acceptable.</p>
<p>What is more important is that a lot of those scripts already exist. Therefore I have to use a C# implementation of python which has the same syntax as python as well as the same built in libs of python. Is this even possible?</p>
<p>Thanks and Greetings
Xeun</p> | 23,129,574 | 3 | 0 | null | 2014-04-17 09:12:39.41 UTC | 6 | 2018-12-04 12:01:07.523 UTC | null | null | null | null | 2,486,702 | null | 1 | 19 | c#|python|ironpython|python.net | 62,085 | <p><a href="http://ironpython.net/" rel="noreferrer">IronPython</a> is what you want. It compiles to .NET bytecode. You can reasonably easily call python code from another .NET language (and the other way around). IronPython is supported in Visual Studio too, I think.</p> |
23,105,894 | How to change Google consent screen email? | <p>I created new Google Play game and would like to change the email displayed on Google Consent Screen. Google Developers Console <a href="https://console.developers.google.com/project/760943112345/apiui/consent">screen</a> has a dropdown to choose email, but just one - admin's email - is here. I've added another user as the owner, but it is not appeared on the consent screen.</p> | 23,107,132 | 5 | 0 | null | 2014-04-16 09:52:28.967 UTC | 7 | 2022-08-20 10:32:04.42 UTC | 2017-02-22 12:45:53.553 UTC | null | 1,841,839 | null | 604,388 | null | 1 | 56 | oauth|google-api|google-oauth|google-developers-console | 19,411 | <p>You need a second email address then add that person / email as admin of the project. Then you will be able to add that email in the consent screen.</p>
<p>The Console has changed a lot since 2014, You need to add another user as the admin then you must login to console with that email and connect it. Then you will be able to change it.</p>
<p><a href="https://i.stack.imgur.com/T8AaK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/T8AaK.png" alt="enter image description here" /></a></p>
<p>A new user can be added via the <a href="https://console.cloud.google.com/iam-admin/iam" rel="noreferrer">Iam</a> for your project.</p>
<p><a href="https://i.stack.imgur.com/eBbr4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eBbr4.png" alt="enter image description here" /></a></p> |
19,596,268 | Select all elements except one in a vector | <p>My question is very similar to <a href="https://stackoverflow.com/questions/13469718/extract-every-element-but-the-nth-element-of-vector">this one</a> but I can't manage exactly how to apply that answer to my problem.</p>
<p>I am looping through a vector with a variable <code>k</code> and want to select the whole vector except the single value at index <code>k</code>.</p>
<p>Any idea?</p>
<pre><code>for k = 1:length(vector)
newVector = vector( exluding index k); <---- what mask should I use?
% other operations to do with the newVector
end
</code></pre> | 19,596,342 | 6 | 0 | null | 2013-10-25 17:43:09.33 UTC | 2 | 2019-05-13 19:08:58.51 UTC | 2017-05-23 12:03:05.607 UTC | null | -1 | null | 907,921 | null | 1 | 16 | matlab|vector|indexing | 53,675 | <p><code>vector([1:k-1 k+1:end])</code> will do. Depending on the other operations, there may be a better way to handle this, though.</p>
<p>For completeness, if you want to remove one element, you do not need to go the <code>vector = vector([1:k-1 k+1:end])</code> route, you can use <code>vector(k)=[];</code></p> |
32,429,369 | How to opt out of running a doc test? | <p>I'm writing a Rust library and I want to provide examples in my documentation that</p>
<ol>
<li>compile as part of running <code>cargo test</code></li>
<li>do <em>not</em> run. </li>
</ol>
<p>Is this possible?</p>
<p>I'm writing a database client library, and the examples make use of a hypothetical, non-existing database server. As such, the examples always fail when run, but it's important that the examples be valid syntactically. Hence my requirements above.</p>
<p>If there's no way to do what I want, then how does one opt out of having <code>cargo test</code> run a specific doc test? I.e., have <code>cargo run</code> compile-and-run some doc tests but completely ignore some others?</p> | 32,429,385 | 2 | 0 | null | 2015-09-06 23:42:07.047 UTC | 4 | 2021-03-23 07:48:24.77 UTC | 2017-06-01 14:56:59.503 UTC | null | 155,423 | null | 1,094,609 | null | 1 | 48 | rust|rust-cargo | 9,383 | <p>This is documented in <a href="https://doc.rust-lang.org/rustdoc/" rel="noreferrer"><em>The rustdoc book</em></a>, specifically the <a href="https://doc.rust-lang.org/rustdoc/documentation-tests.html#attributes" rel="noreferrer">chapter about attributes</a>.</p>
<p>Your opening codeblock delimiter should look like:</p>
<pre><code>/// ```no_run
</code></pre>
<p>From the book:</p>
<blockquote>
<pre><code>/// ```no_run
/// loop {
/// println!("Hello, world");
/// }
/// ```
</code></pre>
<p>The <code>no_run</code> attribute will compile your code, but not run it. This is
important for examples such as "Here's how to retrieve a web page,"
which you would want to ensure compiles, but might be run in a test
environment that has no network access.</p>
</blockquote>
<p>To omit build completely use <code>ignore</code> instead of <code>no_run</code>.</p> |
47,391,735 | *ngIf with multiple async pipe variables | <p>Been trying to combine two observables into one <code>*ngIf</code> and show the user interface when both have emitted.</p>
<p>Take:</p>
<pre class="lang-xml prettyprint-override"><code><div *ngIf="{ language: language$ | async, user: user$ | async } as userLanguage">
<b>{{userLanguage.language}}</b> and <b>{{userLanguage.user}}</b>
</div>
</code></pre>
<p>From: <a href="https://stackoverflow.com/questions/44855599/putting-two-async-subscriptions-in-one-angular-ngif-statement">Putting two async subscriptions in one Angular *ngIf statement</a></p>
<p>This works as far as it compiles however in my case <code>language$</code> and <code>user$</code> would be from two HTTP requests and it seems <code>user$</code> throws runtime errors like <code>TypeError: _v.context.ngIf.user is undefined</code>.</p>
<p>Essentially what I really want is (this doesn't work):</p>
<pre class="lang-xml prettyprint-override"><code><div *ngIf="language$ | async as language && user$ | async as user">
<b>{{language}}</b> and <b>{{user}}</b>
</div>
</code></pre>
<p>Is the best solution:</p>
<ul>
<li>Subscribe inside the component and write to variables</li>
<li>To combine the two observables inside the component with say <code>withLatestFrom</code></li>
<li>Add null checks <code>{{userLanguage?.user}}</code></li>
</ul> | 47,392,169 | 3 | 0 | null | 2017-11-20 12:10:46.353 UTC | 20 | 2021-07-26 06:19:28.423 UTC | 2019-02-07 08:52:08.443 UTC | null | 430,885 | null | 156,728 | null | 1 | 69 | angular | 43,694 | <p>This condition should be handled with nested <code>ngIf</code> directives:</p>
<pre class="lang-xml prettyprint-override"><code><ng-container *ngIf="language$ | async as language">
<div *ngIf="user$ | async as user">
<b>{{language}}</b> and <b>{{user}}</b>
</div>
<ng-container>
</code></pre>
<p>The downside is that HTTP requests will be performed in series.</p>
<p>In order to perform them concurrently and still have <code>language</code> and <code>user</code> variables, more nesting is required:</p>
<pre class="lang-xml prettyprint-override"><code><ng-container *ngIf="{ language: language$ | async, user: user$ | async } as userLanguage">
<ng-container *ngIf="userLanguage.language as language">
<ng-container *ngIf="userLanguage.user as user">
<div><b>{{language}}</b> and <b>{{user}}</b></div>
</ng-container>
</ng-container>
</ng-container>
</code></pre>
<p>More efficient way way to do this is to move logic from template to component class at this point and create a single observable, e.g. with <code>withLatestFrom</code></p> |
62,032,050 | How to remove query param with react hooks? | <p>I know we can replace query params in component based classes doing something along the lines of:</p>
<pre><code> componentDidMount() {
const { location, replace } = this.props;
const queryParams = new URLSearchParams(location.search);
if (queryParams.has('error')) {
this.setError(
'There was a problem.'
);
queryParams.delete('error');
replace({
search: queryParams.toString(),
});
}
}
</code></pre>
<p>Is there a way to do it with react hooks in a functional component?</p> | 62,032,451 | 2 | 0 | null | 2020-05-26 21:55:01.143 UTC | 5 | 2022-08-14 16:49:17.643 UTC | null | null | null | null | 2,418,295 | null | 1 | 31 | reactjs|react-router|react-hooks | 42,973 | <p>Yes, you can use <a href="https://reacttraining.com/react-router/web/api/Hooks/usehistory" rel="noreferrer"><code>useHistory</code></a> & <a href="https://reacttraining.com/react-router/web/api/Hooks/uselocation" rel="noreferrer"><code>useLocation</code></a> hooks from react-router:</p>
<pre><code>
import React, { useState, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
export default function Foo() {
const [error, setError] = useState('')
const location = useLocation()
const history = useHistory()
useEffect(() => {
const queryParams = new URLSearchParams(location.search)
if (queryParams.has('error')) {
setError('There was a problem.')
queryParams.delete('error')
history.replace({
search: queryParams.toString(),
})
}
}, [])
return (
<>Component</>
)
}
</code></pre>
<p>As <code>useHistory()</code> returns <a href="https://reacttraining.com/react-router/web/api/history" rel="noreferrer">history</a> object which has <code>replace</code> function which can be used to replace the current entry on the history stack.</p>
<p>And <code>useLocation()</code> returns <a href="https://reacttraining.com/react-router/web/api/location" rel="noreferrer">location</a> object which has <code>search</code> property containing the URL query string e.g. <code>?error=occurred&foo=bar"</code> which can be converted into object using <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams" rel="noreferrer">URLSearchParams</a> API (which is not supported in IE).</p> |
8,910,671 | select max codeigniter | <p>Im trying to get an max value with codeigniter from an table but it isnt working. This is the error i get:</p>
<blockquote>
<p>Severity: 4096</p>
<p>Message: Object of class CI_DB_mysql_result could not be converted to
string</p>
<p>Filename: database/DB_active_rec.php</p>
<p>Line Number: 427</p>
</blockquote>
<p>This is my function:</p>
<pre><code>public function getPeriodeNummer($bedrijf_id) {
$this->db->select_max('id');
$this->db->where('bedrijf_id', $bedrijf_id);
$result = $this->db->get('rapporten');
$this->db->select('periode_nummer');
$this->db->where('rapporten_id', $result);
$query = $this->db->get('statistieken_onderhoud');
$data = $query + 1;
return $data;
}
</code></pre>
<p>What im trying to do is as followed:</p>
<ol>
<li>Select the highest <code>id</code> where <code>bedrijf_id</code> = <code>$bedrijf_id</code> from <code>rapporten</code>.</li>
<li>Select the <code>periode_nummer</code> from <code>statistieken_onderhoud</code> where <code>rapporten_id</code> = the highest <code>id</code> i got from step 1.</li>
<li>Add 1 to the <code>periode_nummer</code> i got from step 2 and <code>return</code> that number.</li>
</ol>
<p>Thanks in forward for your help!</p> | 8,911,049 | 6 | 0 | null | 2012-01-18 13:11:17.2 UTC | 2 | 2021-08-02 08:38:13.917 UTC | 2012-01-18 13:48:02.993 UTC | null | 379,317 | null | 1,002,705 | null | 1 | 6 | php|mysql|codeigniter | 72,820 | <p>Try</p>
<pre><code>public function getPeriodeNummer($bedrijf_id) {
$this->db->select_max('id');
$this->db->where('bedrijf_id', $bedrijf_id);
$res1 = $this->db->get('rapporten');
if ($res1->num_rows() > 0)
{
$res2 = $res1->result_array();
$result = $res2[0]['id'];
$this->db->select('periode_nummer');
$this->db->where('rapporten_id', $result);
$query = $this->db->get('statistieken_onderhoud');
if ($query->num_rows() > 0)
{
$row = $query->result_array();
$data['query'] = 1 + $row[0]['periode_nummer'];
}
return $data['query'];
}
return NULL;
}
</code></pre> |
8,522,566 | Best way to separate game logic from rendering for a fast-paced game for Android with OpenGL? | <p>I've been studying and making little games for a while, and I have decided lately that I would try to develop games for Android.</p>
<p>For me, jumping from native C++ code to Android Java wasn't that hard, but it gives me headaches to think about how could I maintain the logic separate from the rendering.</p>
<p>I've been reading around here and on other sites that:</p>
<blockquote>
<p>It is better to not create another thread for it, just because
Android will for sure have no problems for processing.</p>
</blockquote>
<p>Meaning the code would be something like this:</p>
<pre><code>public void onDrawFrame(GL10 gl) {
doLogicCalculations();
clearScreen();
drawSprites();
}
</code></pre>
<p>But I'm not sure if that would be the best approach. Since I don't think I like how it will look like if I put my logic inside the <code>GLRenderer::onDrawFrame</code> method. As far as I know, this method is meant to just draw, and I may slow down the frames if I put logic there. Not to mention that it hurts the concepts of POO in my understanding.</p>
<p>I think that using threads might be the way, this is how I was planning:</p>
<p>Main Activity:</p>
<pre><code>public void onCreate(Bundle savedInstanceState) {
//set fullscreen, etc
GLSurfaceView view = new GLSurfaceView(this);
//Configure view
GameManager game = new GameManager();
game.start(context, view);
setContentView(view);
}
</code></pre>
<p>GameManager:</p>
<pre><code>OpenGLRenderer renderer;
Boolean running;
public void start(Context context, GLSurfaceView view) {
this.renderer = new OpenGLRenderer(context);
view.setRenderer(this.renderer);
//create Texturelib, create sound system...
running = true;
//create a thread to run GameManager::update()
}
public void update(){
while(running){
//update game logic here
//put, edit and remove sprites from renderer list
//set running to false to quit game
}
}
</code></pre>
<p>and finally, OpenGLRenderer:</p>
<pre><code>ListOrMap toDraw;
public void onDrawFrame(GL10 gl) {
for(sprite i : toDraw)
{
i.draw();
}
}
</code></pre>
<p>This is a rough idea, not fully complete.
This pattern would keep it all separated and would look a little better, but is it the best for performance?</p>
<p>As long as I researched, most examples of threaded games use canvas or surfaceview, those won't fit my case, because I'm using OpenGLES.</p>
<p>So here are my questions: </p>
<blockquote>
<p>Which is the best way to separate my
game logic from the rendering when using OpenGLES? Threading my
application? Put the logic in a separate method and just call it from
the draw method?</p>
</blockquote> | 8,524,506 | 2 | 0 | null | 2011-12-15 15:34:48.403 UTC | 11 | 2016-06-04 01:40:52.547 UTC | 2016-06-04 01:40:52.547 UTC | null | 1,091,440 | null | 1,091,440 | null | 1 | 14 | android|opengl-es | 7,585 | <p>So I think there are two ways you can go here. </p>
<ol>
<li><p><strong>Do all updates from <code>onDrawFrame()</code>:</strong> This is similar to using GLUT, and Android will call this function as often as possible. (Turn that off with <code>setRenderMode(RENDERMODE_WHEN_DIRTY)</code>.) This function gets called on it own thread (not the UI thread) and it means you call your logic update here. Your initial issue was that this seems a little messy, and I agree, but only because the function is named <code>onDrawFrame()</code>. If it was called <code>onUpdateScene()</code>, then updating the logic would fit this model well. But it's not the worse thing in the world, it was designed this way, and people do it.</p></li>
<li><p><strong>Give logic its own thread:</strong> This is more complicated since now you're dealing with three threads: the UI thread for input, the render thread <code>onDrawFrame()</code> for drawing stuff, and the logic thread for continuously working with both input and rendering data. Use this if you need to have a really accurate model of what's happening even if your framerate is dropping (for example, precise collision response). This may be conceptually a little cleaner, but not practically cleaner.</p></li>
</ol>
<p>I would recommend #1. You really don't need #2. If you do, you can add it later I guess, but most people are just using the first option because the hardware is fast enough so you don't have to design around it.</p> |
8,820,240 | How to format Numbers in Velocity Templates? | <p>I am getting a java object in my velocity template. The object has a double value which I want to format to 2 decimal places and display it in my template.</p>
<p>The class for which im getting an object is something like this</p>
<pre><code>Class Price
{
double value;
String currency;
}
</code></pre>
<p>In my velocity template, im getting the value like this</p>
<pre><code>$price.value
</code></pre>
<p>but I need to format it to 2 decimal places before displaying it.</p>
<p>I want to convert </p>
<p>23.59004 to 23.59</p>
<p>35.7 to 35.70</p>
<p>3.0 to 3.00</p>
<p>9 to 9.00</p>
<p>Please tell me how can I do it in velocity template? I searched a lot for this and found that I can use velocity tools, but there are no examples related to it? and can i use velocity tools in templates?</p> | 8,820,321 | 7 | 0 | null | 2012-01-11 13:40:34.967 UTC | 5 | 2021-04-25 04:33:55.837 UTC | null | null | null | null | 828,077 | null | 1 | 17 | java|velocity | 46,820 | <p>Velocity tools are expected to be used in Velocity templates; essentially they are objects added to the variables available in a template so that you can use <code>$numberTool.format("#0.00", $val)</code> or similar. If none of the available tools don't fit your needs, simply create a POJO and add it to the template.</p>
<p>To make it working you also should add the following maven dependency:</p>
<pre><code><dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
</code></pre>
<p>and write following code:</p>
<pre><code>context.put("numberTool", new NumberTool());
</code></pre> |
8,740,792 | Postgresql - update rule - possible to have a last modified date, automatically updated "on update" of that row? | <p>I want to have a "lastmodified" timestamp (or datetime? not sure if it makes a difference other than presentation of the data) to log the last modified date/time of that record's entry.</p>
<p>Apparently this is possible using triggers. Since I haven't used triggers before, I thought I could first try an "update rule" since that is new to me too:</p>
<p><a href="http://www.postgresql.org/docs/8.3/static/rules-update.html" rel="noreferrer">http://www.postgresql.org/docs/8.3/static/rules-update.html</a></p>
<p>What I have is this table to log a customer's session data:</p>
<pre><code>CREATE TABLE customer_session (
customer_sessionid serial PRIMARY KEY,
savedsearch_contents text,
lastmodified timestamp default now()
); /*
@ lastmodified - should be updated whenever the table is updated for this entry, just for reference.
*/
</code></pre>
<p>Then I could create a rule like this. I'm not sure about the syntax, or whether to use NEW or OLD. Could anyone advise the correct syntax?</p>
<pre><code>CREATE RULE customer_session_lastmodified AS
ON UPDATE TO customer_session
DO UPDATE customer_session SET lastmodified = current_timestamp WHERE customer_sessionid = NEW.customer_sessionid
</code></pre>
<p>As you can see I want to update the lastmodified entry of THAT customer_sessionid only, so I'm not sure how to reference it. The UPDATE query would be like this:</p>
<pre><code>UPDATE customer_session SET savedsearch_contents = 'abcde'
WHERE customer_sessionid = {unique customer ID}
</code></pre>
<p>Many thanks!</p> | 8,745,713 | 2 | 0 | null | 2012-01-05 10:16:54.9 UTC | 6 | 2016-03-26 07:29:18.31 UTC | null | null | null | null | 732,264 | null | 1 | 28 | postgresql | 20,625 | <p>You cannot do it with a rule, since it would create an infinite recursion. The correct way is to create a <em>before trigger</em>, just as <em>duffymo</em> proposed.</p>
<pre><code>CREATE FUNCTION sync_lastmod() RETURNS trigger AS $$
BEGIN
NEW.lastmodified := NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER
sync_lastmod
BEFORE UPDATE ON
customer_session
FOR EACH ROW EXECUTE PROCEDURE
sync_lastmod();
</code></pre> |
8,375,625 | How to select a table column with jQuery | <p>I want to select a table column and all I know is the header text of the column. (th.innerText)</p>
<p>I tried the following code but it doesn't work:</p>
<pre><code>ownerIndex = $('th:contains("Owner")').index();
$('table tr td:nth-child(ownerIndex)')
</code></pre>
<p>any ideas?</p> | 8,375,709 | 4 | 0 | null | 2011-12-04 13:28:59.207 UTC | 4 | 2021-10-26 04:11:37.24 UTC | 2017-11-15 14:23:20.373 UTC | null | 4,370,109 | user963395 | null | null | 1 | 38 | jquery|html-table|jquery-selectors | 70,802 | <p>Ok. I found a solution:</p>
<pre><code>$('table tr td:nth-child('+ownerIndex+')')
</code></pre> |
27,382,944 | KDiff3: "There is a line end style conflict" | <p>I am trying to use KDiff3 to solve conflicts on windows. But when run the merge I get:</p>
<p>KDiff3: "There is a line end style conflict"</p>
<p>And nothing is merged/solved:</p>
<p><img src="https://i.stack.imgur.com/2hmiL.png" alt="first screenshot"></p>
<p>Even though I selected DOS line ending before running the merge:</p>
<p><img src="https://i.stack.imgur.com/28vwR.png" alt="second screenshot"></p>
<p>Any ideas?</p>
<p>It seems to work if I just save instead of pressing the Merge button. That could be a solution.</p> | 37,351,396 | 2 | 2 | null | 2014-12-09 15:41:35.377 UTC | 2 | 2018-06-12 20:29:35.447 UTC | 2018-06-12 20:29:35.447 UTC | null | 4,298,200 | null | 363,603 | null | 1 | 100 | kdiff3 | 27,164 | <p>Here's a screenshot to walk you through the process that Matt Wilkie described in <a href="https://stackoverflow.com/a/28912211/4298200">his answer</a>.</p>
<ol>
<li>Click in the C pane. </li>
<li>Choose an encoding other than 'conflict' </li>
<li>Save</li>
</ol>
<p><a href="https://i.stack.imgur.com/iIsRv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iIsRv.png" alt="enter image description here"></a></p> |
896,519 | ASP.NET AJAX Control Toolkit: Show a ModalPopup and then do PostBack | <p>I want to show a modal popup when a user click on an asp button. The user must select an option of a panel. The value of the option selected must be saved to an input hidden and then the asp.net button <strong>must do</strong> a <strong>PostBack</strong>.</p>
<p>Can I do that?</p>
<p>Thank you!</p> | 2,337,305 | 3 | 0 | null | 2009-05-22 05:51:14.363 UTC | 2 | 2011-08-19 13:24:12.07 UTC | 2009-10-21 15:22:30.68 UTC | null | 109,941 | null | 68,571 | null | 1 | 2 | c#|asp.net-ajax|ajaxcontroltoolkit|modal-popup | 57,850 | <p>Finally, I've decided to use jQuery to show a ModalPopUp. The following question has the answer to this question:</p>
<p><a href="https://stackoverflow.com/questions/2325431/jquery-uis-dialog-doesnt-work-on-asp-net">jQuery UI's Dialog doesn't work on ASP.NET</a></p>
<p>If you are not agree, tell me.</p> |
1,106,984 | Avoiding split-brain, votes and quorum | <p>Suppose you have n processes, n > 2. You want to have agreement amongst them that one is to be active. So they need to vote amonst each other to determine which one is active.</p>
<p>All processes may fail at any time, we want to have one process active if possible, but ...</p>
<p>We <em>must</em> never have two active at the same time, so if they can't be sure it is better to have no-one active. (Ie. we want to avoid split brain)</p>
<p>The only available communication mechanism between them is pub-sub messaging (not point to point).</p>
<p>One or more databases are available, but no one database should be a single point of failure. Ie. it would be very undesirabloe if all the processes were available to work, and the were prevented from doing so by the loss of a single database. </p>
<p>Design? What messages need to be published? </p> | 1,107,301 | 3 | 1 | null | 2009-07-09 23:38:24.323 UTC | 13 | 2018-05-16 20:03:04.413 UTC | 2009-07-10 00:17:29.077 UTC | null | 45,654 | null | 82,511 | null | 1 | 15 | messaging | 8,261 | <p>Theory:</p>
<p>This is leader election, which is a form of the <a href="http://en.wikipedia.org/wiki/Consensus_(computer_science)" rel="nofollow noreferrer">Consensus Problem</a>, also sometimes called <a href="http://en.wikipedia.org/wiki/Two_Generals'_Problem" rel="nofollow noreferrer">The Two Generals Problem</a>. Under some sets of assumptions (fully async and messages can be lost) it's been proven impossible, and the proof is particularly elegant.</p>
<p>The intuition of this problem is: imagine some algorithm exists that allows consensus to be reached in some fixed number of messages. Since failures are tolerated, we can drop one message from the protocol, and it should still work. We can repeat this process until there are no messages at all, clearly an impossibility.</p>
<p>In practice we overcome this using failure detectors to simulate a synchronous system. </p>
<p>The most widely known algorithm that solves consensus is <a href="http://en.wikipedia.org/wiki/Paxos_algorithm" rel="nofollow noreferrer">Paxos</a>, which can tolerate failure of up to half of the participating nodes. Paxos has the reputation of being very difficult to implement as even slight misunderstandings of the details of the protocol destroy it's correctness.</p>
<p>Practical solutions:</p>
<p>While the problem in general is quite difficult, getting working systems up is far easier. There are off the shelf implementations of Paxos or equivalent algorithms available. <a href="http://hadoop.apache.org/zookeeper/" rel="nofollow noreferrer">Apache Zookeeper</a> is the best I'm aware of. For your specific problem, I'm pretty sure it'll be your quickest route. Other Paxos implementations are around, and it also might be possible to build something on network redundancy virtual ip tools like <a href="https://www.gsp.com/cgi-bin/man.cgi?section=8&topic=wackamole" rel="nofollow noreferrer">Wackamole</a>. I believe the high end versions of most commercial databases offer quorum features as an (expensive) option.</p>
<p>Also, for many applications it's acceptable to weaken correctness slightly or otherwise adjust the problem to allow much simpler solutions. </p>
<p>For example, if a single point of failure is tolerable because recovery is likely to be quick, then the problem is trivial: just have one special node do the work.</p>
<p>Another approach might be to build the system around idempotent actions, so duplicate processing becomes tolerable.</p>
<p>Lastly you might partition the workload into a pool of non-redundant systems: here failures will delay processing until recovery but only for items at that node, not for the entire workload.</p>
<p>These sorts of compromises are so much simpler that they're often a better choice. One has to weigh the utility of a full solution against the complexity of implementing it and see if there's really value. This is why so many practical systems just use <a href="http://en.wikipedia.org/wiki/Two-phase_commit_protocol" rel="nofollow noreferrer">2 Phase</a> or <a href="http://en.wikipedia.org/wiki/Three-phase_commit_protocol" rel="nofollow noreferrer">3 Phase Commit</a>, even though they block in some scenarios: the decreased availability is tolerable compared to the complexity of a full quorum system.</p> |
240,788 | How to execute an Oracle stored procedure via a database link | <p>Can I call a stored procedure in Oracle via a database link?</p>
<p>The database link is functional so that syntax such as...</p>
<pre><code>SELECT * FROM myTable@myRemoteDB
</code></pre>
<p>is functioning. But is there a syntax for...</p>
<pre><code>EXECUTE mySchema.myPackage.myProcedure('someParameter')@myRemoteDB
</code></pre> | 240,798 | 3 | 0 | null | 2008-10-27 17:43:26.293 UTC | 5 | 2021-02-26 16:05:20.13 UTC | null | null | null | dacracot | 13,930 | null | 1 | 34 | database|oracle|stored-procedures|database-link | 111,224 | <p>The syntax is</p>
<pre><code>EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );
</code></pre> |
1,333,786 | How to combine imported and local resources in WPF user control | <p>I'm writing several WPF user controls that need both shared and individual resources.</p>
<p>I have figured out the syntax for loading resources from a separate resource file:</p>
<pre><code><UserControl.Resources>
<ResourceDictionary Source="ViewResources.xaml" />
</UserControl.Resources>
</code></pre>
<p>However, when I do this, I cannot also add resources locally, like:</p>
<pre><code><UserControl.Resources>
<ResourceDictionary Source="ViewResources.xaml" />
<!-- Doesn't work: -->
<ControlTemplate x:Key="validationTemplate">
...
</ControlTemplate>
<style x:key="textBoxWithError" TargetType="{x:Type TextBox}">
...
</style>
...
</UserControl.Resources>
</code></pre>
<p>I've had a look at ResourceDictionary.MergedDictionaries, but that only lets me merge more than one external dictionary, not define further resources locally.</p>
<p>I must be missing something trivial?</p>
<p>It should be mentioned: I'm hosting my user controls in a WinForms project, so putting shared resources in App.xaml is not really an option.</p> | 1,333,870 | 3 | 0 | null | 2009-08-26 10:37:07.183 UTC | 25 | 2017-05-22 21:58:23.89 UTC | null | null | null | null | 32,050 | null | 1 | 83 | wpf|xaml|resources | 54,128 | <p>I figured it out. The solution involves MergedDictionaries, but the specifics must be just right, like this:</p>
<pre><code><UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ViewResources.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- This works: -->
<ControlTemplate x:Key="validationTemplate">
...
</ControlTemplate>
<style x:key="textBoxWithError" TargetType="{x:Type TextBox}">
...
</style>
...
</ResourceDictionary>
</UserControl.Resources>
</code></pre>
<p>That is, the local resources must be nested <strong>within</strong> the ResourceDictionary tag. So the example <a href="http://learnwpf.com/post/2006/05/27/How-do-I-separate-out-resources-into-multiple-files-in-WPF.aspx" rel="noreferrer">here</a> is incorrect.</p> |
22,301,555 | Left and right align on same line | <p>I want to create a <code>div</code> that has a header containing two pieces of text. One piece of text will be aligned left and one right. The header will have a gray background that will expand with the text:</p>
<pre><code><div id="expand-box">
<div id="expand-box-header">
<span style="float: left;">Top left header</span>
<span style="float: right;">Top right header</span>
</div>
Lorem ipsum dorem nori seota ostiy
</div>
</code></pre>
<p>CSS:</p>
<pre><code>#expand-box
{
width: 100%;
padding: 0;
border: 2px solid #BBB;
margin: 7px 0 0 0;
}
#expand-box-header
{
background-color: #BBB;
margin: 0;
color: #FFF;
padding: 0 0 3px 2px;
}
</code></pre>
<p>While this works, the two <code>spans</code> float over the <code>expand-box-header</code> gray background and the Lorem Ipsum text floats higher than it should.</p> | 22,304,981 | 5 | 0 | null | 2014-03-10 13:31:11.557 UTC | 1 | 2014-03-10 15:53:21.573 UTC | null | null | null | null | 2,725,552 | null | 1 | 28 | html|css | 48,049 | <p>The reason your code wasn't working is because floating divs don't affect the size of the surrounding element. The problem you get with <strong>inline-block on your left side float</strong> is that you lose one of your headers as the screen is made smaller. I shrank the screen size on the JSfiddle Mehmet Eren Yener provided and the right header disappears. If your headers are long, and the screen is small - the right header will vanish. </p>
<p>I think the better approach would be to either use a <strong>clearfix</strong> class or to use the <strong>overflow</strong> tag. There's also the <strong>Empty Div Method</strong> - but I'm not really a fan of that one. If you use one of these methods instead the left header will stack on top of the right header when they get too close.</p>
<p><strong>Here are examples of using Clearfix and Overflow:</strong></p>
<p><strong>Clearfix: <a href="http://jsfiddle.net/ATP33/">http://jsfiddle.net/ATP33/</a></strong></p>
<p>HTML:</p>
<pre><code> <div id="expand-box">
<div id="expand-box-header" class="clearfix">
<span style="float: left;">Top left header</span>
<span style="float: right;">Top right header</span>
</div>
<div id="expand_box_sub_header">Lorem ipsum dorem nori seota ostiy</div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>#expand-box {
width: 100%;
padding: 0;
border: 2px solid #BBB;
margin: 7px 0 0 0;}
#expand-box-header {
background-color: #BBB;
margin: 0;
color: #FFF;
padding: 0 0 3px 2px;}
#expand_box_sub_header { clear: both; }
.clearfix:after { content: "\00A0"; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;}
.clearfix{ display: inline-block;}
html[xmlns] .clearfix { display: block;}
* html .clearfix{ height: 1%;}
.clearfix {display: block}
</code></pre>
<p><strong>Overflow: <a href="http://jsfiddle.net/RL8ta/">http://jsfiddle.net/RL8ta/</a></strong></p>
<p>HTML:</p>
<pre><code><div id="expand-box">
<div id="expand-box-header">
<span style="float: left;">Top left header</span>
<span style="float: right;">Top right header</span>
</div>
<div id="expand_box_sub_header">Lorem ipsum dorem nori seota ostiy</div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>#expand-box {
width: 100%;
padding: 0;
border: 2px solid #BBB;
margin: 7px 0 0 0;}
#expand-box-header {
background-color: #BBB;
margin: 0;
color: #FFF;
padding: 0 0 3px 2px;
overflow: auto;}
#expand_box_sub_header { clear: both; }
</code></pre> |
35,266,455 | MySQL Workbench: Reconnecting to database when "MySQL server has gone away"? | <p>I have a lot of tabs and queries open in MySQL workbench. I left it open before I went to sleep, but this morning I am getting an error <code>MySQL server has gone away</code> when trying to run queries.</p>
<p>The database is up, and I am able to connect to it if I open a new connection on MySQL workbench, but the current connection is dead. How do I reconnect?</p>
<p>I don't want to open a new connection as I would have to copy my queries and tabs over.</p> | 35,267,150 | 1 | 2 | null | 2016-02-08 09:45:11.613 UTC | 3 | 2016-05-17 16:44:37.96 UTC | null | null | null | null | 5,045,227 | null | 1 | 51 | mysql-workbench | 22,487 | <p>Done it.</p>
<pre><code>Query Menu -> Reconnect to Server
</code></pre> |
6,103,974 | How do I start an Intent from an OnClickListener | <p>My Main Activity extends ListActivity and displays a List. I am using custom Listitems defined in a class named DefinitionAdapter.
I also have a seperate class that implements OnClickListener.</p>
<p>In the class DefinitionAdapter I set the OnClickListener to the ListItems:</p>
<pre><code> public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
...
v.setOnClickListener(new OnItemClickListener(position) );
return v;
}
</code></pre>
<p>My custom OnClickListener is supposed to start another activity. </p>
<pre><code>public class OnItemClickListener implements OnClickListener extends Activity {
private int position;
public OnItemClickListener(int p) {
position = p;
}
@Override
public void onClick(View v) {
Intent intent = new Intent(this, ShowDefinition.class);
startActivity(intent);
}
}
</code></pre>
<p>I am not sure that I am doing that right. I added my new activity to the manifest, as well as the activity i extended the listener with:</p>
<pre><code><activity android:name="ShowDefinition" android:label="@string/app_name">
</activity>
<activity android:name="OnItemClickListener" android:label="@string/app_name">
</activity>
</code></pre>
<p>Nonetheless, if I click on an Item in my List, the application always breaks with a NullPointerException. I think I am using the intent wrong... any Ideas?</p>
<p>In regard to Nikita Beloglazov's comment:</p>
<p>It breaks when I create the Intent:</p>
<pre><code>Intent intent = new Intent(this, ShowDefinition.class);
</code></pre>
<p>Here's the stacktrace:</p>
<pre><code>05-23 22:56:46.629: ERROR/AndroidRuntime(258): Uncaught handler: thread main exiting due to uncaught exception
05-23 22:56:46.659: ERROR/AndroidRuntime(258): java.lang.NullPointerException
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.content.ComponentName.<init>(ComponentName.java:75)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.content.Intent.<init>(Intent.java:2551)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at com.andiandy.juradefinitions.OnItemClickListener.onClick(OnItemClickListener.java:22)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.View.performClick(View.java:2364)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.View.onTouchEvent(View.java:4179)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.View.dispatchTouchEvent(View.java:3709)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:852)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.os.Looper.loop(Looper.java:123)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at android.app.ActivityThread.main(ActivityThread.java:4363)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at java.lang.reflect.Method.invoke(Method.java:521)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-23 22:56:46.659: ERROR/AndroidRuntime(258): at dalvik.system.NativeStart.main(Native Method)
</code></pre> | 6,104,047 | 3 | 2 | null | 2011-05-23 22:59:59.747 UTC | 2 | 2011-05-23 23:40:57.287 UTC | 2011-05-23 23:09:12.787 UTC | null | 632,997 | null | 632,997 | null | 1 | 15 | android|android-intent|listener|listactivity | 48,601 | <p>Your OnItemClickListener should not extend Activity. Instead, you should arrange for the OnItemClickListener to have access to your ListActivity instance. Any view that is already part of the activity (like the ListView) has access to the ListActivity instance via <code>getContext()</code>. Then implement <code>onClick</code> like this:</p>
<pre><code>@Override
public void onClick(View v) {
Intent intent = new Intent(context, ShowDefinition.class);
context.startActivity(intent);
}
</code></pre> |
5,836,560 | Color values in imshow for matplotlib? | <p>I'd like to know the color value of a point I click on when I use imshow() in matplotlib. Is there a way to find this information through the event handler in matplotlib (the same way as the x,y coordinates of your click are available)? If not, how would I find this information?</p>
<p>Specifically I'm thinking about a case like this:</p>
<pre><code>imshow(np.random.rand(10,10)*255, interpolation='nearest')
</code></pre>
<p>Thanks!
--Erin</p> | 5,837,744 | 4 | 0 | null | 2011-04-29 19:33:10.7 UTC | 10 | 2016-08-18 20:22:30.95 UTC | null | null | null | user671110 | null | null | 1 | 8 | python|matplotlib | 6,739 | <p>Here's a passable solution. It only works for <code>interpolation = 'nearest'</code>. I'm still looking for a cleaner way to retrieve the interpolated value from the image (rather than rounding the picked x,y and selecting from the original array.) Anyway:</p>
<pre><code>from matplotlib import pyplot as plt
import numpy as np
im = plt.imshow(np.random.rand(10,10)*255, interpolation='nearest')
fig = plt.gcf()
ax = plt.gca()
class EventHandler:
def __init__(self):
fig.canvas.mpl_connect('button_press_event', self.onpress)
def onpress(self, event):
if event.inaxes!=ax:
return
xi, yi = (int(round(n)) for n in (event.xdata, event.ydata))
value = im.get_array()[xi,yi]
color = im.cmap(im.norm(value))
print xi,yi,value,color
handler = EventHandler()
plt.show()
</code></pre> |
6,125,351 | Good class design by example | <p>I am trying to work out the best way to design a class that has its properties persisted in a database. Let's take a basic example of a <code>Person</code>. To create a new person and place it in the database, I want the <code>DateOfBirth</code> property to be optional (i.e. NULLable in the DB).</p>
<p>Here's my sample code:</p>
<pre><code>namespace BusinessLayer
{
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
</code></pre>
<p>I'm unsure as to whether the fields should be public or not. Should I do it like this:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Person person1 = new Person("Kate","Middleton",null);
}
}
</code></pre>
<p>or like this:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Person person1 = new Person();
person1.FirstName = "Kate";
person1.LastName = "Middleton";
}
}
</code></pre>
<p>I'm also wondering how I should be dealing with the optional properties of the class. Once the fields have been populated how do I then save them to the DB? I have a DatabaseComponenet class to save the information. How do I deal with the optional when saving to the database?</p>
<p>So, would I do something like this:</p>
<pre><code>public int Save()
{
int personId;
personId = DatabaseComponent.InsertPerson(FirstName, LastName, DateOfBirth);
return personId;
}
</code></pre>
<p>Thanks for any help! Some useful URLs on good class design would also be appreciated.</p> | 6,125,560 | 4 | 0 | null | 2011-05-25 13:38:57.357 UTC | 16 | 2011-05-25 19:08:09.377 UTC | 2011-05-25 13:40:03.45 UTC | null | 37,213 | null | 38,211 | null | 1 | 27 | c#|c#-4.0 | 79,815 | <p>First, I'd put two distinct public constructor to Person:</p>
<pre><code>namespace BusinessLayer
{
class Person
{
public Person(string firstName, string lastName): this(firstName, lastName, DateTime.Now)
{}
public Person(string firstName, string lastName, DateTime birthDate)
{
FirstName = firstName;
LastName = lastName;
DateOfBirth = birthDate;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
</code></pre>
<p>this allows you to write both </p>
<pre><code>var p = new Person("Marilyin", "Manson");
var p2 = new Person("Alice", "Cooper", new DateTime(...));
</code></pre>
<p>and</p>
<pre><code>var p = new Person { FirstName="Marilyn", LastName="Manson" };
</code></pre>
<p>I can't see why you should limit to only one form.</p>
<p>As for the DatabaseComponent I'd strongly suggest to write a method that allows you to save a Person instead of the signature you are implicitly declaring.</p>
<p>That's because, should one day change the way a Person is defined, you'd probably have to change the code in each point you invoke <code>Save()</code> method. By saving just a Person, you only have to change the <code>Save()</code> implementation.</p>
<p>Don't you plan to use an ORM by the way?</p> |
6,171,588 | Preventing race condition of if-exists-update-else-insert in Entity Framework | <p>I've been reading other questions on how to implement if-exists-insert-else-update semantics in EF, but either I'm not understanding how the answers work, or they are in fact not addressing the issue. A common solution offered is to wrap the work in a transaction scope (eg: <a href="https://stackoverflow.com/questions/4189954/implementing-if-not-exists-insert-using-entity-framework-without-race-conditions">Implementing if-not-exists-insert using Entity Framework without race conditions</a>):</p>
<pre><code>using (var scope = new TransactionScope()) // default isolation level is serializable
using(var context = new MyEntities())
{
var user = context.Users.SingleOrDefault(u => u.Id == userId); // *
if (user != null)
{
// update the user
user.property = newProperty;
context.SaveChanges();
}
else
{
user = new User
{
// etc
};
context.Users.AddObject(user);
context.SaveChanges();
}
}
</code></pre>
<p>But I fail to see how this solves anything, as for this to work, the line I have starred above should <em>block</em> if a second thread tries to access the same user ID, unblocking only when the first thread has finished its work. Using a transaction will <em>not</em> cause this however, and we'll get an UpdateException thrown due to the key violation that occurs when the second thread attempts to create the same user for a second time.</p>
<p>Instead of catching the exception caused by the race condition, it would be better to prevent the race condition from happening in the first place. One way to do this would be for the starred line to take out an exclusive lock on the database row that matches its condition, meaning that in the context of this block, only one thread at a time could work with a user.</p>
<p>It seems that this must be a common problem for users of the EF, so I'm looking for a clean, generic solution that I can use everywhere.</p>
<p>I'd really like to avoid using a stored procedure to create my user if possible.</p>
<p>Any ideas?</p>
<p><strong>EDIT</strong>: I tried executing the above code concurrently on two different threads using the same user ID, and despite taking out serializable transactions, they were both able to enter the critical section (*) concurrently. This lead to an UpdateException being thrown when the second thread attempted to insert the same user ID that the first had just inserted. This is because, as pointed out by Ladislav below, a serializable transaction takes exclusive locks only after it has begun modifying data, not reading.</p> | 6,173,482 | 4 | 3 | null | 2011-05-30 01:39:47.853 UTC | 16 | 2018-01-18 19:36:18.857 UTC | 2017-05-23 12:34:25.273 UTC | null | -1 | null | 289,319 | null | 1 | 38 | .net|entity-framework|transactions|race-condition | 12,305 | <p>When using serializable transaction SQL Server issues shared locks on read records / tables. Shared locks doesn't allow other transactions modifying locked data (transactions will block) but it allows other transactions reading data before the transaction which issued locks start modifying data. That is the reason why the example doesn't work - concurrent reads are allowed with shared locks until the first transaction starts modifying data.</p>
<p>You want isolation where select command locks the whole table exclusively for a single client. It must lock the whole table because otherwise it will not solve concurrency for inserting "the same" record. Granular control for locking records or tables by select commands is possible when using hints but you must write direct SQL queries to use them - EF has no support for that. I described approach for exclusively locking that table <a href="https://stackoverflow.com/questions/5018060/disable-read-write-to-a-table-via-sqltransaction-in-net/5018268#5018268">here</a> but it is like creating sequential access to the table and it affects all other clients accessing this table.</p>
<p>If you are really sure that this operation happens just in your single method and there are not other applications using your database you can simply place the code into critical section (.NET synchronization for example with <code>lock</code>) and ensure on the .NET side that only single thread can access critical section. That is not so reliable solution but any playing with locks and transaction levels has a big impact on the database performance and throughput. You can combine this approach with optimistic concurrency (unique constraints, timestamps, etc).</p> |
46,107,706 | Kotlin iterator to list? | <p>I have an iterator of strings from <a href="http://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/JsonNode.html#fieldNames%28%29" rel="noreferrer">fieldNames</a> of <code>JsonNode</code>:</p>
<pre><code>val mm = ... //JsonNode
val xs = mm.fieldNames()
</code></pre>
<p>I want to loop over the fields while keeping count, something like:</p>
<pre><code>when mm.size() {
1 -> myFunction1(xs[0])
2 -> myFunction2(xs[0], xs[1])
3 -> myFunction3(xs[0], xs[1], xs[2])
else -> print("invalid")
}
</code></pre>
<p>Obviously the above code does not work as <code>xs</code> the Iterator cannot be indexed like so. I tried to see if I can convert the iterator to list by <code>mm.toList()</code> but that does not exist.</p>
<p>How can I achieve this? </p> | 46,108,166 | 2 | 1 | null | 2017-09-08 02:25:33.627 UTC | 1 | 2021-10-24 07:08:21.47 UTC | null | null | null | null | 4,438,271 | null | 1 | 29 | kotlin | 16,272 | <p>Probably the easiest way is to convert iterator to <code>Sequence</code> first and then to <code>List</code>:</p>
<pre><code>listOf(1,2,3).iterator().asSequence().toList()
</code></pre>
<p>result:</p>
<pre><code>[1, 2, 3]
</code></pre> |
45,758,998 | How Can I Mask My Material-UI TextField? | <p>I have a TextField for phone numbers in a short form. And then i want to mask this form field like (0)xxx xxx xx xx.</p>
<p>I'm trying to use <a href="https://github.com/sanniassin/react-input-mask" rel="noreferrer">react-input-mask</a> plugin with <a href="https://github.com/callemall/material-ui" rel="noreferrer">Material-UI</a>. But if i want to change input value, this is not updating the my main TextField.</p>
<pre><code> <TextField
ref="phone"
name="phone"
type="text"
value={this.state.phone}
onChange={this.onChange}
>
<InputMask value={this.state.phone} onChange={this.onChange} mask="(0)999 999 99 99" maskChar=" " />
</TextField>
</code></pre>
<p>Actually, I couldn't find any documentation for masking with Material-UI. I'm trying to figure out how can i use with another plugins.</p> | 45,763,029 | 5 | 1 | null | 2017-08-18 14:23:14.917 UTC | 4 | 2021-03-04 20:17:23.093 UTC | 2018-02-12 12:01:29.367 UTC | null | 8,762,152 | null | 5,078,918 | null | 1 | 29 | reactjs|material-ui|input-mask | 76,278 | <h1>Update</h1>
<p>versions: material-ui 0.20.2, react-input-mask 2.0.4</p>
<p>Seems like the API changed a bit:</p>
<pre><code><InputMask
mask="(0)999 999 99 99"
value={this.state.phone}
disabled={false}
maskChar=" "
>
{() => <TextField />}
</InputMask>
</code></pre>
<p>Demo</p>
<p><a href="https://codesandbox.io/s/throbbing-bird-9qgw9?fontsize=14&hidenavigation=1&theme=dark" rel="noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit throbbing-bird-9qgw9"></a></p>
<h1>Original</h1>
<p>This should do the trick:</p>
<pre><code><TextField
ref="phone"
name="phone"
type="text"
value={this.state.phone}
onChange={this.onChange}
>
<InputMask mask="(0)999 999 99 99" maskChar=" " />
</TextField>
</code></pre>
<p>Demo:</p>
<p><a href="https://codesandbox.io/s/yl8p9jvq9" rel="noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit yl8p9jvq9"></a></p> |
29,314,033 | Drop rows containing empty cells from a pandas DataFrame | <p>I have a <code>pd.DataFrame</code> that was created by parsing some excel spreadsheets. A column of which has empty cells. For example, below is the output for the frequency of that column, 32320 records have missing values for <em>Tenant</em>.</p>
<pre><code>>>> value_counts(Tenant, normalize=False)
32320
Thunderhead 8170
Big Data Others 5700
Cloud Cruiser 5700
Partnerpedia 5700
Comcast 5700
SDP 5700
Agora 5700
dtype: int64
</code></pre>
<p>I am trying to drop rows where Tenant is missing, however <code>.isnull()</code> option does not recognize the missing values. </p>
<pre><code>>>> df['Tenant'].isnull().sum()
0
</code></pre>
<p>The column has data type "Object". What is happening in this case? How can I drop records where <em>Tenant</em> is missing?</p> | 29,314,880 | 8 | 1 | null | 2015-03-28 05:30:48.69 UTC | 60 | 2022-05-14 07:53:00.397 UTC | 2021-02-05 14:49:51.973 UTC | null | 7,109,869 | null | 3,923,448 | null | 1 | 147 | python|pandas|dataframe|drop | 438,549 | <p>Pandas will recognise a value as null if it is a <code>np.nan</code> object, which will print as <code>NaN</code> in the DataFrame. Your missing values are probably empty strings, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to <code>np.nan</code> objects using <code>replace()</code>, and then call <code>dropna()</code>on your DataFrame to delete rows with null tenants.</p>
<p>To demonstrate, we create a DataFrame with some random values and some empty strings in a <code>Tenants</code> column:</p>
<pre><code>>>> import pandas as pd
>>> import numpy as np
>>>
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
>>> df['Tenant'] = np.random.choice(['Babar', 'Rataxes', ''], 10)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640
</code></pre>
<p>Now we replace any empty strings in the <code>Tenants</code> column with <code>np.nan</code> objects, like so:</p>
<pre><code>>>> df['Tenant'].replace('', np.nan, inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239 NaN
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214 NaN
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640 NaN
</code></pre>
<p>Now we can drop the null values:</p>
<pre><code>>>> df.dropna(subset=['Tenant'], inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
</code></pre> |
32,447,388 | Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node' | <pre><code>var line = "<p><strong>" + name + ": </strong>" + message.field_message_body.und[0].value + "</p>";
console.log(line);
console.log(document.getElementById("messages"));
document.getElementById("messages").appendChild(line);
</code></pre>
<blockquote>
<p>messages exists and it returns </p>
</blockquote>
<p><code><div id=messages"></div></code></p>
<p>Nothing appears to be empty, so I'm not sure why this is being thrown.</p>
<p>Does anyone have any idea why it might be throwing this error?</p> | 32,447,411 | 2 | 1 | null | 2015-09-07 23:57:10.467 UTC | 3 | 2015-11-09 03:23:42.98 UTC | 2015-11-09 03:23:42.98 UTC | null | 2,735,598 | null | 756,566 | null | 1 | 7 | javascript|jquery | 45,194 | <p>The <code>line</code> variable you're passing isn't a <code>Node</code>, it's a <code>String</code>. Try first using</p>
<pre><code>var line = document.createElement("p");
line.innerHTML = "<strong>" + name + ": </strong>" + message.field_message_body.und[0].value;
document.getElementById("messages").appendChild(line);
</code></pre> |
6,049,687 | jquery ui dialog box need to return value, when user presses button, but not working | <p>I'v got a jquery ui dialog box I want to use to prompt the user to confirm a deletion. When the user presses "yes" or "no" I need to return "True" or "False" to continue some javascript execution. The problem with the code below is when the dialog box shows up it immediately is executing a "return true;" but the user hasn't pressed the "Yes" button yet?</p>
<p>What am I doing wrong?</p>
<p>HTML:</p>
<pre><code><div id="modal_confirm_yes_no" title="Confirm"></div>
</code></pre>
<p>Javascript call:</p>
<pre><code>$("#modal_confirm_yes_no").html("Are you sure you want to delete this?");
var answer = $("#modal_confirm_yes_no").dialog("open");
if (answer)
{
//delete
}
else
{
//don't delete
}
</code></pre>
<p>Jquery dialog:</p>
<pre><code>$("#modal_confirm_yes_no").dialog({
bgiframe: true,
autoOpen: false,
minHeight: 200,
width: 350,
modal: true,
closeOnEscape: false,
draggable: false,
resizable: false,
buttons: {
'Yes': function(){
$(this).dialog('close');
return true;
},
'No': function(){
$(this).dialog('close');
return false;
}
}
});
</code></pre> | 6,049,720 | 5 | 1 | null | 2011-05-18 18:57:56.793 UTC | 4 | 2017-06-10 14:57:51.017 UTC | 2012-11-08 14:33:33.47 UTC | null | 561,731 | null | 249,034 | null | 1 | 21 | jquery|jquery-ui | 41,961 | <p>javascript is asynchronous.</p>
<p>so you have to use callbacks:</p>
<pre><code> $("#modal_confirm_yes_no").dialog({
bgiframe: true,
autoOpen: false,
minHeight: 200,
width: 350,
modal: true,
closeOnEscape: false,
draggable: false,
resizable: false,
buttons: {
'Yes': function(){
$(this).dialog('close');
callback(true);
},
'No': function(){
$(this).dialog('close');
callback(false);
}
}
});
function callback(value){
//do something
}
</code></pre> |
6,019,853 | PHP - cannot use a scalar as an array warning | <p>I have the following code:</p>
<pre><code> $final = array();
foreach ($words as $word) {
$query = "SELECT Something";
$result = $this->_db->fetchAll($query, "%".$word."%");
foreach ($result as $row)
{
$id = $row['page_id'];
if (!empty($final[$id][0]))
{
$final[$id][0] = $final[$id][0]+3;
}
else
{
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
}
}
}
</code></pre>
<p>The code SEEMS to work fine, but I get this warning:</p>
<pre><code>Warning: Cannot use a scalar value as an array in line X, Y, Z (the line with: $final[$id][0] = 3, and the next 2).
</code></pre>
<p>Can anyone tell me how to fix this?</p> | 6,019,900 | 5 | 6 | null | 2011-05-16 15:45:50.84 UTC | 5 | 2020-11-10 14:59:04.133 UTC | 2018-05-22 15:20:07.847 UTC | null | 2,263,631 | null | 569,872 | null | 1 | 61 | php|arrays|zend-framework|warnings|scalar | 179,895 | <p>You need to set<code>$final[$id]</code> to an array before adding elements to it. Intiialize it with either</p>
<pre><code>$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
</code></pre>
<p>or</p>
<pre><code>$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
</code></pre> |
18,168,541 | what is zookeeper port and its usage? | <p>I am quite new for zookeeper port through which I am coming across from past few days.<br>
I introduced with <strong>zookeeper port</strong> keyword at two occasion:</p>
<ul>
<li>while configuring neo4j db cluster (<a href="http://lists.neo4j.org/pipermail/user/2011-August/011451.html" rel="noreferrer">link</a>) and</li>
<li>while running compiled voltdb catalog (<a href="http://voltdb.com/docs/UsingVoltDB/clivoltdb.php" rel="noreferrer">link</a>) (See Network Configuration Arguments)</li>
</ul>
<p>Then, I came across <a href="http://zookeeper.apache.org/" rel="noreferrer">Apache Zookeeper</a>, (which I guess is related to distributed application, I am a newbie in distributed application as well). hence question came in my mind: </p>
<ol>
<li>is there any implementation of apache zookeeper in above 2 scenarios ? </li>
<li>What exactly this zookeeper port do internally ? </li>
</ol>
<p>Any help would be appreciated, Thanks. </p> | 18,186,224 | 1 | 0 | null | 2013-08-11 03:44:20.293 UTC | 8 | 2016-08-31 19:02:06.64 UTC | 2013-08-12 04:36:07.04 UTC | null | 1,660,192 | null | 1,660,192 | null | 1 | 27 | java|neo4j|distributed-computing|apache-zookeeper|voltdb | 69,045 | <p>Zookeeper is used in distributed applications mainly for configuration management and high availability operations. Zookeeper does this by a Master-Slave architecture. Neo4j and VoltDb might be using zookeeper for this purpose</p>
<p>Coming to the ports understanding :
suppose u have 3 servers for zookeepers ... You need to mention in configuration as </p>
<pre><code>clientPort=2181
server.1=zookeeper1:2888:3888
server.2=zookeeper2:2888:3888
server.3=zookeeper3:2888:3888
</code></pre>
<p>Out of these one server will be the master and rest all will be slaves.If any server goes OFF then zookeeper elects leader automatically .</p>
<blockquote>
<p>Servers listen on three ports: 2181 for client connections; 2888 for
follower connections, if they are the leader; and 3888 for other
server connections during the leader election phase .</p>
</blockquote> |
39,279,824 | Use None instead of np.nan for null values in pandas DataFrame | <p>I have a pandas DataFrame with mixed data types. I would like to replace all null values with None (instead of default np.nan). For some reason, this appears to be nearly impossible. </p>
<p>In reality my DataFrame is read in from a csv, but here is a simple DataFrame with mixed data types to illustrate my problem. </p>
<pre><code>df = pd.DataFrame(index=[0], columns=range(5))
df.iloc[0] = [1, 'two', np.nan, 3, 4]
</code></pre>
<p>I can't do:</p>
<pre><code>>>> df.fillna(None)
ValueError: must specify a fill method or value
</code></pre>
<p>nor:</p>
<pre><code>>>> df[df.isnull()] = None
TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value
</code></pre>
<p>nor:</p>
<pre><code>>>> df.replace(np.nan, None)
TypeError: cannot replace [nan] with method pad on a DataFrame
</code></pre>
<p>I used to have a DataFrame with only string values, so I could do:</p>
<pre><code>>>> df[df == ""] = None
</code></pre>
<p>which worked. But now that I have mixed datatypes, it's a no go.</p>
<p>For various reasons about my code, it would be helpful to be able to use None as my null value. Is there a way I can set the null values to None? Or do I just have to go back through my other code and make sure I'm using np.isnan or pd.isnull everywhere? </p> | 39,279,898 | 2 | 1 | null | 2016-09-01 19:51:12.333 UTC | 12 | 2022-01-21 15:58:46.057 UTC | null | null | null | null | 1,945,087 | null | 1 | 45 | python|pandas|dataframe | 51,854 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="noreferrer">Use <code>pd.DataFrame.where</code></a><br>
Uses <code>df</code> value when condition is met, otherwise uses <code>None</code></p>
<pre><code>df.where(df.notnull(), None)
</code></pre>
<p><a href="https://i.stack.imgur.com/sMhz6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sMhz6.png" alt="enter image description here"></a></p> |
43,974,979 | React Native - React Navigation transitions | <p>I'd like to use <a href="https://reactnavigation.org/" rel="noreferrer">React Navigation</a> in my new react native app but I can't find any example showing how to create custom view transitions in there. Default transitions are working fine but I'd like to be able to customize them in few places and the docs don't come very helpfull in this subject.
Anyone tried that already? Anywhere I could see a working example?
Thanks in advance.</p> | 43,981,835 | 1 | 0 | null | 2017-05-15 08:46:03.2 UTC | 12 | 2018-11-05 19:27:09.313 UTC | null | null | null | null | 2,550,879 | null | 1 | 18 | react-native|react-navigation | 20,126 | <p>You can find detailed version of this post on <a href="http://blog.coder.si/2018/11/react-native-navigation-custom-scene.html" rel="noreferrer">this link</a></p>
<p>I hope this is clear enough with step-by-step for how to create custom transition.</p>
<p>Create a Scene or Two to navigate</p>
<pre><code>class SceneOne extends Component {
render() {
return (
<View>
<Text>{'Scene One'}</Text>
</View>
)
}
}
class SceneTwo extends Component {
render() {
return (
<View>
<Text>{'Scene Two'}</Text>
</View>
)
}
}
</code></pre>
<p>Declare your app scenes</p>
<pre><code>let AppScenes = {
SceneOne: {
screen: SceneOne
},
SceneTwo: {
screen: SceneTwo
},
}
</code></pre>
<p>Declare custom transition</p>
<pre><code>let MyTransition = (index, position) => {
const inputRange = [index - 1, index, index + 1];
const opacity = position.interpolate({
inputRange,
outputRange: [.8, 1, 1],
});
const scaleY = position.interpolate({
inputRange,
outputRange: ([0.8, 1, 1]),
});
return {
opacity,
transform: [
{scaleY}
]
};
};
</code></pre>
<p>Declare custom transitions configurator</p>
<pre><code>let TransitionConfiguration = () => {
return {
// Define scene interpolation, eq. custom transition
screenInterpolator: (sceneProps) => {
const {position, scene} = sceneProps;
const {index} = scene;
return MyTransition(index, position);
}
}
};
</code></pre>
<p>Create app navigator using Stack Navigator</p>
<pre><code>const AppNavigator = StackNavigator(AppScenes, {
transitionConfig: TransitionConfiguration
});
</code></pre>
<p>Use App Navigator in your project</p>
<pre><code>class App extends Component {
return (
<View>
<AppNavigator />
</View>
)
}
</code></pre>
<p>Register your app in eq. <code>index.ios.js</code></p>
<pre><code>import { AppRegistry } from 'react-native';
AppRegistry.registerComponent('MyApp', () => App);
</code></pre>
<h2>Update #1</h2>
<p>As for the question on how to set transition per scene, this is how I'm doing it.</p>
<p>When you navigate using <code>NavigationActions</code> from <code>react-navigation</code>, you can pass through some props. In my case it looks like this</p>
<pre><code>this.props.navigate({
routeName: 'SceneTwo',
params: {
transition: 'myCustomTransition'
}
})
</code></pre>
<p>and then inside the Configurator you can switch between these transition like this</p>
<pre><code>let TransitionConfiguration = () => {
return {
// Define scene interpolation, eq. custom transition
screenInterpolator: (sceneProps) => {
const {position, scene} = sceneProps;
const {index, route} = scene
const params = route.params || {}; // <- That's new
const transition = params.transition || 'default'; // <- That's new
return {
myCustomTransition: MyCustomTransition(index, position),
default: MyTransition(index, position),
}[transition];
}
}
};
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.