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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,889,746 |
Creating threads - Task.Factory.StartNew vs new Thread()
|
<p>I am just learning about the new Threading and Parallel libraries in .Net 4</p>
<p>In the past I would create a new Thread like so (as an example):</p>
<pre><code>DataInThread = new Thread(new ThreadStart(ThreadProcedure));
DataInThread.IsBackground = true;
DataInThread.Start();
</code></pre>
<p>Now I can do:</p>
<pre><code>Task t = Task.Factory.StartNew(() =>
{
ThreadProcedure();
});
</code></pre>
<p>What is the difference if any?</p>
<p>Thanks</p>
| 7,889,800 | 4 | 1 | null |
2011-10-25 13:09:32.16 UTC
| 37 |
2013-07-16 07:37:19.413 UTC
| null | null | null | null | 84,539 | null | 1 | 107 |
c#|.net|multithreading|.net-4.0
| 106,135 |
<p>There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.</p>
<p>If you have a long running background work you should specify this by using the correct Task Option.</p>
<p>You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.</p>
|
8,329,485 |
"Unable to find remote helper for 'https'" during git clone
|
<p>I am unable to clone HTTPS repositories. I can clone SSH repos fine, but not HTTPS repos. I cannot test the GIT protocol since I am behind a corporate firewall.</p>
<p>This is what I am trying to do:</p>
<pre><code>$ git clone https://github.com/nvie/gitflow.git
Cloning into gitflow...
fatal: Unable to find remote helper for 'https'
</code></pre>
<p>I have so far tried the following (based on Google searches)</p>
<ul>
<li>Purging and installing Git through <code>apt-get</code></li>
<li>Installing <code>build-deps</code> for Git through <code>apt-get</code></li>
<li>Installing curl dev libraries </li>
<li>Installing expat libraries</li>
<li>Downloading Git source and building using:
<ul>
<li><code>./configure --prefix=/usr --with-curl --with-expat</code></li>
<li>Also tried pointing configure at curl binary (<code>./configure --prefix=/usr --with-curl=/usr/bin/curl</code>)</li>
</ul></li>
</ul>
<p>I have tried everything I can find on the internet with no luck. Can anyone help me?</p>
<p>Git version = 1.7.6.4</p>
<p>OS = Ubuntu 11.04</p>
| 13,018,777 | 25 | 11 | null |
2011-11-30 16:36:14.793 UTC
| 74 |
2021-11-04 08:55:07.977 UTC
|
2016-05-19 04:29:37.583 UTC
| null | 608,639 | null | 680,335 | null | 1 | 279 |
linux|git|ubuntu
| 298,548 |
<p>It looks like not having (lib)curl-devel installed when you compile git can cause this.</p>
<p>If you install (lib)curl-devel, and then rebuild/install git, this should solve the problem:</p>
<pre><code>$ yum install curl-devel
$ # cd to wherever the source for git is
$ cd /usr/local/src/git-1.7.9
$ ./configure
$ make
$ make install
</code></pre>
<p>This worked for me on Centos 6.3.</p>
<p>If you don't have yum, you can download the source to curl-devel here:</p>
<ul>
<li><a href="http://curl.se/dlwiz/?type=devel" rel="nofollow noreferrer">http://curl.se/dlwiz/?type=devel</a></li>
</ul>
<hr />
<p>If you are running Ubuntu instead:</p>
<pre><code>sudo apt-get install libcurl4-openssl-dev
</code></pre>
|
4,821,477 |
XML Schema minOccurs / maxOccurs default values
|
<p>I'm wondering how the XML Schema specification handles these cases:</p>
<pre><code><xsd:element minOccurs="1" name="asdf"/>
</code></pre>
<p>No maxOccurs given -> Is this the cardinality [1..1]?</p>
<pre><code><xsd:element minOccurs="5" maxOccurs="2" name="asdf"/>
</code></pre>
<p>I suppose this is simply invalid?</p>
<pre><code><xsd:element maxOccurs="2" name="asdf"/>
</code></pre>
<p>Is this the cardinality [0..2] or [1..2]?</p>
<p>Is there an "official" definition on how the XML Schema spec handles these cases?</p>
| 4,822,925 | 3 | 0 | null |
2011-01-27 20:28:41.433 UTC
| 47 |
2018-12-10 11:55:56.413 UTC
|
2011-01-28 07:22:06.773 UTC
| null | 43,960 | null | 43,960 | null | 1 | 237 |
xml|xsd
| 279,561 |
<p>The default values for <code>minOccurs</code> and <code>maxOccurs</code> are 1. Thus:</p>
<pre><code><xsd:element minOccurs="1" name="asdf"/>
</code></pre>
<p>cardinality is [1-1] Note: if you specify <em>only</em> minOccurs attribute, it can't be greater than 1, because the default value for maxOccurs is 1.</p>
<pre><code><xsd:element minOccurs="5" maxOccurs="2" name="asdf"/>
</code></pre>
<p>invalid</p>
<pre><code><xsd:element maxOccurs="2" name="asdf"/>
</code></pre>
<p>cardinality is [1-2] Note: if you specify <em>only</em> maxOccurs attribute, it can't be smaller than 1, because the default value for minOccurs is 1.</p>
<pre><code><xsd:element minOccurs="0" maxOccurs="0"/>
</code></pre>
<p>is a valid combination which makes the element prohibited.</p>
<p>For more info see <a href="http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints">http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints</a></p>
|
4,098,186 |
Lists: Count vs Count()
|
<p>Given a list, which method is preferred to determine the number of elements inside?</p>
<pre><code>var myList = new List<string>();
myList.Count
myList.Count()
</code></pre>
| 4,098,210 | 4 | 5 | null |
2010-11-04 15:20:32.603 UTC
| 16 |
2020-11-11 14:44:37.877 UTC
|
2018-01-03 09:55:56.287 UTC
| null | 5,395,773 | null | 248,480 | null | 1 | 136 |
c#|.net|list|linq|count
| 181,011 |
<p><code>Count()</code> is an extension method introduced by LINQ while the <code>Count</code> property is part of the List itself (derived from <code>ICollection</code>). Internally though, LINQ checks if your <code>IEnumerable</code> implements <code>ICollection</code> and if it does it uses the <code>Count</code> property. So at the end of the day, there's no difference which one you use for a <code>List</code>.</p>
<p>To prove my point further, here's the code from Reflector for <code>Enumerable.Count()</code></p>
<pre><code>public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
</code></pre>
|
4,504,592 |
How to use SELECT IN clause in JDBCTemplates?
|
<p>This is my first experience with JDBCTemplates and I ran into a case where I need to use a query that looks like this:</p>
<pre><code>SELECT * FROM table WHERE field IN (?)
</code></pre>
<p>How do I do that? I already tried passing a list/array value but that didn't do the trick, I get an exception. My current code looks like this:</p>
<pre><code>Long id = getJdbcTemplate().queryForLong(query, new Object[]{fieldIds});
</code></pre>
<p><a href="https://docs.spring.io/spring/docs/2.5.x/reference/jdbc.html" rel="nofollow noreferrer">Spring Documentation</a> states that there is no way of doing this besides generating the required number of "?" placeholders to match the size of the parameter List. Is there a workaround?</p>
| 4,504,652 | 5 | 2 | null |
2010-12-21 22:35:59.89 UTC
| 3 |
2021-12-30 19:03:11.883 UTC
|
2021-12-30 19:01:43.067 UTC
| null | 3,157,428 | null | 69,966 | null | 1 | 10 |
java|sql|spring|jdbctemplate
| 39,151 |
<p>I don't think you can do this as a single '?'. It's nothing to do with Spring JDBC templates, it's core SQL.</p>
<p>You'll have to build up a (?, ?, ?) for as many of them as you need.</p>
|
4,731,622 |
Insert a new row into DataTable
|
<p>I have a datatable filled with staff data like..</p>
<pre><code>Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
</code></pre>
<p>I want to modify so that the result would be sth like..</p>
<pre><code>Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Total - - Total Value
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
Total - - Total Value
</code></pre>
<p>to be concluded, I need to insert the total row at the end of each staff record.</p>
<p>So, my question is how to insert a row into a datatable? Tkz..</p>
| 4,731,638 | 5 | 0 | null |
2011-01-19 04:03:03.623 UTC
| 9 |
2021-01-13 09:21:17.977 UTC
|
2015-12-14 08:13:33.6 UTC
| null | 505,893 | null | 398,909 | null | 1 | 63 |
c#|datatable
| 386,967 |
<pre><code>// get the data table
DataTable dt = ...;
// generate the data you want to insert
DataRow toInsert = dt.NewRow();
// insert in the desired place
dt.Rows.InsertAt(toInsert, index);
</code></pre>
|
4,658,269 |
Ruby send vs __send__
|
<p>I understand the concept of <code>some_instance.send</code> but I'm trying to figure out why you can call this both ways. The Ruby Koans imply that there is some reason beyond providing lots of different ways to do the same thing. Here are the two examples of usage:</p>
<pre><code>class Foo
def bar?
true
end
end
foo = Foo.new
foo.send(:bar?)
foo.__send__(:bar?)
</code></pre>
<p>Anyone have any idea about this?</p>
| 4,658,359 | 5 | 0 | null |
2011-01-11 13:48:02.43 UTC
| 32 |
2019-04-18 06:59:33.873 UTC
|
2015-01-23 17:25:00.62 UTC
|
user2555451
| null | null | 483,040 | null | 1 | 179 |
ruby|syntax
| 24,658 |
<p>Some classes (for example the standard library's socket class) define their own <code>send</code> method which has nothing to do with <code>Object#send</code>. So if you want to work with objects of any class, you need to use <code>__send__</code> to be on the safe side.</p>
<p>Now that leaves the question, why there is <code>send</code> and not just <code>__send__</code>. If there were only <code>__send__</code> the name <code>send</code> could be used by other classes without any confusion. The reason for that is that <code>send</code> existed first and only later it was realized that the name <code>send</code> might also usefully be used in other contexts, so <code>__send__</code> was added (that's the same thing that happened with <code>id</code> and <code>object_id</code> by the way).</p>
|
4,654,227 |
Overriding GetHashCode in VB without checked/unchecked keyword support?
|
<p>So I'm trying to figure out how to correctly override <code>GetHashCode()</code> in VB for a large number of custom objects. A bit of searching leads me to <a href="https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode">this wonderful answer</a>.</p>
<p>Except there's one problem: VB lacks both the <code>checked</code> and <code>unchecked</code> keyword in .NET 4.0. As far as I can tell, anyways. So using Jon Skeet's implementation, I tried creating such an override on a rather simple class that has three main members: <code>Name As String</code>, <code>Value As Int32</code>, and <code>[Type] As System.Type</code>. Thus I come up with: </p>
<pre><code>Public Overrides Function GetHashCode() As Int32
Dim hash As Int32 = 17
hash = hash * 23 + _Name.GetHashCode()
hash = hash * 23 + _Value
hash = hash * 23 + _Type.GetHashCode()
Return hash
End Function
</code></pre>
<p>Problem: Int32 is too small for even a simple object such as this. The particular instance I tested has "Name" as a simple 5-character string, and that hash alone was close enough to Int32's upper limit, that when it tried to calc the second field of the hash (Value), it overflowed. Because I can't find a VB equivalent for granular <code>checked</code>/<code>unchecked</code> support, I can't work around this.</p>
<p>I also do not want to remove Integer overflow checks across the entire project. This thing is maybe....40% complete (I made that up, TBH), and I have a lot more code to write, so I need these overflow checks in place for quite some time.</p>
<p>What would be the "safe" version of Jon's <code>GetHashCode</code> version for VB and Int32? Or, does .NET 4.0 have <code>checked</code>/<code>unchecked</code> in it somewhere that I'm not finding very easily on MSDN?
<br/><br/><br/>
<strong>EDIT:</strong><br>
Per the linked SO question, one of the <a href="https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode/4630550#4630550">unloved answers</a> at the very bottom provided a <em>quasi</em>-solution. I say quasi because it feels like it's....cheating. Beggars can't be choosers, though, right?</p>
<p>Translated from from C# into a more readable VB and aligned to the object described above (Name, Value, Type), we get:</p>
<pre><code>Public Overrides Function GetHashCode() As Int32
Return New With { _
Key .A = _Name, _
Key .B = _Value, _
Key .C = _Type
}.GetHashCode()
End Function
</code></pre>
<p>This triggers the compiler apparently to "cheat" by generating an anonymous type, which it then compiles outside of the project namespace, presumably with integer overflow checks disabled, and allows the math to take place and simply wrap around when it overflows. It also seems to involve <code>box</code> opcodes, which I know to be performance hits. No unboxing, though.</p>
<p><strike>But this raises an interesting question. Countless times, I've seen it stated here and elsewhere that both VB and C# generate the same IL code. This is clearly not the case 100% of the time...Like the use of C#'s <code>unchecked</code> keyword simply causes a different opcode to get emitted. So why do I continue to see the assumption that both produce the exact same IL keep getting repeated?</strike> </rhetorical-question></p>
<p>Anyways, I'd rather find a solution that can be implemented within each object module. Having to create Anonymous Types for every single one of my objects is going to look messy from an ILDASM perspective. I'm not kidding when I say I have a <em>lot</em> of classes implemented in my project.
<br /><br /><br />
<strong>EDIT2:</strong> I did open up a bug on MSFT Connect, and the gist of the outcome from the VB PM was that they'll consider it, but don't hold your breath:
<a href="https://connect.microsoft.com/VisualStudio/feedback/details/636564/checked-unchecked-keywords-in-visual-basic" rel="noreferrer">https://connect.microsoft.com/VisualStudio/feedback/details/636564/checked-unchecked-keywords-in-visual-basic</a></p>
<p>A quick look at the changes in .NET 4.5 suggests they've not considered it yet, so maybe .NET 5?</p>
<p>My final implementation, which fits the constraints of GetHashCode, while still being fast and <em>unique enough</em> for VB is below, derived from the "Rotating Hash" example on <a href="http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx" rel="noreferrer">this page</a>:</p>
<pre><code>'// The only sane way to do hashing in VB.NET because it lacks the
'// checked/unchecked keywords that C# has.
Public Const HASH_PRIME1 As Int32 = 4
Public Const HASH_PRIME2 As Int32 = 28
Public Const INT32_MASK As Int32 = &HFFFFFFFF
Public Function RotateHash(ByVal hash As Int64, ByVal hashcode As Int32) As Int64
Return ((hash << HASH_PRIME1) Xor (hash >> HASH_PRIME2) Xor hashcode)
End Function
</code></pre>
<p>I also think the "Shift-Add-XOR" hash may also apply, but I haven't tested it.</p>
| 4,656,890 | 7 | 7 | null |
2011-01-11 04:37:46.1 UTC
| 9 |
2017-10-05 01:28:05.71 UTC
|
2017-05-23 12:01:57.687 UTC
| null | -1 | null | 482,691 | null | 1 | 29 |
vb.net|gethashcode
| 8,205 |
<p>Use Long to avoid the overflow:</p>
<pre><code>Dim hash As Long = 17
'' etc..
Return CInt(hash And &H7fffffffL)
</code></pre>
<p>The And operator ensures no overflow exception is thrown. This however does lose one bit of "precision" in the computed hash code, the result is always positive. VB.NET has no built-in function to avoid it, but you can use a trick:</p>
<pre><code>Imports System.Runtime.InteropServices
Module NoOverflows
Public Function LongToInteger(ByVal value As Long) As Integer
Dim cast As Caster
cast.LongValue = value
Return cast.IntValue
End Function
<StructLayout(LayoutKind.Explicit)> _
Private Structure Caster
<FieldOffset(0)> Public LongValue As Long
<FieldOffset(0)> Public IntValue As Integer
End Structure
End Module
</code></pre>
<p>Now you can write:</p>
<pre><code>Dim hash As Long = 17
'' etc..
Return NoOverflows.LongToInteger(hash)
</code></pre>
|
4,047,808 |
What is the best way to tell if a character is a letter or number in Java without using regexes?
|
<p>What is the best and/or easiest way to recognize if a string.charAt(index) is an A-z letter or a number in Java without using regular expressions? Thanks.</p>
| 4,047,836 | 9 | 0 | null |
2010-10-28 23:01:26.87 UTC
| 30 |
2019-12-30 18:27:57.947 UTC
|
2019-12-30 18:27:57.947 UTC
| null | 11,714,860 | null | 402,070 | null | 1 | 187 |
java|char|numbers|letter
| 418,727 |
<p><code>Character.isDigit(string.charAt(index))</code> (<a href="https://docs.oracle.com/javase/10/docs/api/java/lang/Character.html#isDigit(char)" rel="noreferrer">JavaDoc</a>) will return true if it's a digit<br>
<code>Character.isLetter(string.charAt(index))</code> (<a href="https://docs.oracle.com/javase/10/docs/api/java/lang/Character.html#isLetter(char)" rel="noreferrer">JavaDoc</a>) will return true if it's a letter</p>
|
14,546,592 |
Do I need to close 'PreparedStatement'?
|
<p>I have a website which is getting a massive number of hits. I'm experienced problems, including JDBC connection errors.</p>
<p>I'm a bit confused about closing <code>PreparedStatement</code>. Do I need to close <code>PreparedStatement</code> or is it just enough to only close <code>Statement</code>?</p>
<p>Also, what about <code>ResultSet</code>? Do I need to close it too?</p>
| 14,546,613 | 2 | 6 | null |
2013-01-27 10:46:48.483 UTC
| 5 |
2021-02-06 11:57:52.32 UTC
|
2021-02-06 11:56:37.93 UTC
| null | 63,550 | null | 836,026 | null | 1 | 30 |
java|jdbc
| 46,240 |
<p>Yes, you have to close the prepared statements (<code>PreparedStatement</code> Object) and result sets as they may cause memory leakage.</p>
<p>For more information, see <em><a href="http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html" rel="noreferrer">Using Prepared Statements</a></em>.</p>
|
14,832,983 |
HTTP Status 202 - how to provide information about async request completion?
|
<p>What is the appropriate way of giving an estimate for request completion when the server returns a <code>202 - Accepted</code> status code for asynchronous requests?</p>
<p>From the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.3" rel="noreferrer">HTTP spec</a> (<em>italics added by me</em>):</p>
<blockquote>
<p><strong>202 Accepted</strong></p>
<p>The request has been accepted for processing, but the processing has not been completed. [...]</p>
<p>The entity returned with this response SHOULD include an indication of the request's current status and either a pointer to a status monitor or <em>some estimate of when the user can expect the request to be fulfilled</em>.</p>
</blockquote>
<p>Here are some of thoughts:</p>
<ul>
<li>I have glanced at the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3" rel="noreferrer">max-age</a> directive, but using it would be abusing <code>Cache-Control</code>?</li>
<li>Return the expected wait time in the response body?</li>
<li>Add an application specific <code>X-</code> response header, but the <code>X-</code>headers was deprecated in <a href="http://datatracker.ietf.org/doc/rfc6648/" rel="noreferrer">RFC 6648</a>?</li>
<li>Add a (non <code>X-</code>) specific response header? If so, how should it be named? The SO question <a href="https://stackoverflow.com/questions/3561381/">Custom HTTP headers : naming conventions</a> gave some ideas, but after the deprecation it only answers how HTTP headers are formatted, not how they should be named.</li>
<li>Other suggestions?</li>
</ul>
| 15,655,877 | 3 | 0 | null |
2013-02-12 12:50:22.33 UTC
| 8 |
2013-03-27 09:58:08.517 UTC
|
2020-06-20 09:12:55.06 UTC
| null | -1 | null | 303,598 | null | 1 | 32 |
rest|http-headers|http-status-codes
| 28,607 |
<p>Although not explicitly mentioned specifically for the <code>202 - Accepted</code> response code, the <code>Retry-After</code> header seems to be a suitable option. From the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.37" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>The Retry-After response-header field can be used [...] to indicate how long the service is expected to be unavailable to the requesting client. </p>
</blockquote>
|
14,763,255 |
Why does scrolling a UIWebView *feel* so much different than scrolling any other UIScrollView?
|
<p>I'm building an app that loads in a <em>small</em> amount of simple HTML (locally) into a single full-screen UIWebView. I'm noticing that scrolling this web view <em>feels</em> significantly different than scrolling any other UIScrollView. This does not appear to be a performance or a responsiveness issue, per se... It's just a matter of how the momentum plays out as you drag and flick the web view up and down. It just doesn't feel very "native" (for lack of a better word). It's like scrolling through molasses or pudding... kinda "sticky" and not as "slick" as you would like it to feel.</p>
<p>Does anyone know what causes this? Is there any way to fix it, or at the very least make scrolling a UIWebView feel more "native"?</p>
| 14,763,634 | 1 | 2 | null |
2013-02-07 23:41:50.91 UTC
| 10 |
2013-02-08 00:18:40.767 UTC
| null | null | null | null | 1,456,495 | null | 1 | 33 |
ios|cocoa-touch|uiwebview|uiscrollview
| 7,680 |
<p>I have the same perception. It must have to do with the webView's scrollView deceleration rate. Just ran this test, and 1) it confirms our suspicion and 2) suggests a fix.</p>
<p>I added a scrollView and a webView to my UI then logged the following:</p>
<pre><code>NSLog(@"my scroll view's decel rate is %f", self.scrollView.decelerationRate);
NSLog(@"my web view's decel rate is %f", self.webView.scrollView.decelerationRate);
NSLog(@"normal is %f, fast is %f", UIScrollViewDecelerationRateNormal, UIScrollViewDecelerationRateFast);
</code></pre>
<p>The output confirms the guess about webView being more frictional:</p>
<pre><code>my scroll view's decel rate is 0.998000
my web view's decel rate is 0.989324
normal is 0.998000, fast is 0.990000
</code></pre>
<p>And suggests a fix:</p>
<pre><code>self.webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
</code></pre>
|
14,520,309 |
The precision of std::to_string(double)
|
<p>Is there any way to set the precision of the result when converting a double to string <strong>using <code>std::to_string()</code></strong>?</p>
| 14,520,388 | 3 | 1 | null |
2013-01-25 10:53:11.94 UTC
| 1 |
2021-07-23 02:55:12.753 UTC
|
2021-07-23 02:55:12.753 UTC
| null | 3,889,449 |
user955249
| null | null | 1 | 64 |
c++|c++11
| 30,796 |
<p>No.
<Blockquote><P>
Returns: Each function returns a string object holding the character representation of the value of
its argument that would be generated by calling <code>sprintf(buf, fmt, val)</code> with a format specifier of
<code>"%d"</code>, <code>"%u"</code>, <code>"%ld"</code>, <code>"%lu"</code>, <code>"%lld"</code>, <code>"%llu"</code>, <code>"%f"</code>, <code>"%f"</code>, or <code>"%Lf"</code>, respectively, where buf designates
an internal character buffer of sufficient size.</P></Blockquote></p>
|
51,300,238 |
Delete a Closed Track in Google Play Console
|
<p>In the App Releases page of the Google Play Console, how do you delete a closed track?</p>
<p>There is a <strong>Manage</strong> button for the track but no obvious way of deleting it from the page which appears.</p>
<p>I have accidentally created a track I don't need and it is confusing/annoying to have it there. Hopefully I'm missing something rather than this functionality just not having been implemented!</p>
| 51,321,485 | 4 | 0 | null |
2018-07-12 07:58:37.96 UTC
| 4 |
2022-01-05 09:46:12.903 UTC
| null | null | null | null | 2,518,722 | null | 1 | 42 |
google-play|google-play-console
| 36,486 |
<p>It isn't exactly possible right now.</p>
<p>However, you can:</p>
<ul>
<li>click on the 'Manage' button</li>
<li>expand the 'Managed testers' card</li>
<li>click on the 'Deactivate track' button.</li>
</ul>
<p>The track will go in a 'Deactivated tracks' list in the 'App Releases' page."</p>
<p>It's not totally deleted, but that might be enough for you. I've sent the feedback to the right team that this wasn't completely discoverable, and that complete deletion for unused tracks would be useful.</p>
<p>You also can't delete the default "Alpha" or "Beta" tracks right now, only ones you have created yourself.</p>
|
2,874,308 |
Using a batch file to create folder and copy files into it to multiple PCs
|
<p>I have a folder with numerous files that I need to copy to multiple PCs on a network. I thought if the folder didn't exist it would automatically create it. Here's what I have...</p>
<p>copy "C:\Documents and Settings\follag\Desktop\Music" "\PC NAME\c$\Documents and Settings\All Users\Desktop\Music" </p>
<p>When I look at the destination PC, it is not creating the folder and copying the files. I'm new to this whole batch files and would appreciate any help.</p>
<p>Thanks,</p>
<p>Greg</p>
| 2,874,414 | 2 | 0 | null |
2010-05-20 13:48:57.36 UTC
| 2 |
2016-10-20 14:08:34.493 UTC
|
2010-05-20 13:51:59.03 UTC
| null | 1,450 | null | 346,165 | null | 1 | 8 |
windows|batch-file
| 42,797 |
<p>Try </p>
<pre><code>xcopy "C:\Documents and Settings\follag\Desktop\Music" "\PC NAME\c$\Documents and Settings\All Users\Desktop\Music" /E /I
</code></pre>
|
3,106,195 |
Converting ambiguous grammar to unambiguous
|
<p>I did not understand how a unambiguous grammar is derived from a ambiguous grammar? Consider the example on site: <a href="http://www.d.umn.edu/~hudson/5641/l22m.pdf" rel="noreferrer">Example</a>. How was the grammar derived is confusing to me. </p>
<p>Can anyone please guide me ? </p>
| 3,106,287 | 2 | 2 | null |
2010-06-23 23:07:34.03 UTC
| 9 |
2020-06-07 05:36:50.013 UTC
|
2010-06-23 23:11:11.203 UTC
| null | 21,234 | null | 183,717 | null | 1 | 27 |
grammar|context-free-grammar
| 68,571 |
<p>The example has two grammars:</p>
<h3>Ambiguous:</h3>
<pre><code>E → E + E | E ∗ E | (E) | a
</code></pre>
<h3>Unambiguous:</h3>
<pre><code>E → E + T | T
T → T ∗ F | F
F → (E) | a
</code></pre>
<p>The unambiguous grammar was derived from the ambiguous one using information not specified in the ambiguous grammar:</p>
<ul>
<li>The operator '*' binds tighter than the operator '+'.</li>
<li>Both the operators '*' and '+' are left associative.</li>
</ul>
<h3>Without the external information, there is no way to make the transformation.</h3>
<p>With the external information, we can tell that:</p>
<pre><code>a * a + b * b
</code></pre>
<p>is grouped as if written:</p>
<pre><code>(a * a) + (b * b)
</code></pre>
<p>rather than as:</p>
<pre><code>a * ((a + b) * b)
</code></pre>
<p>The second assumes that '+' binds tighter than '*', and that the operators bind from right to left rather than left to right.</p>
<hr>
<h3>Comment</h3>
<blockquote>
<p>How would associativity come into the picture for examples like:</p>
</blockquote>
<pre><code> S → aA | Ba
A → BA | a
B → aB | epsilon
</code></pre>
<blockquote>
<p>This is an ambiguous grammar, so how to go about converting it to unambiguous?</p>
</blockquote>
<p>I wonder if the 'epsilon' is ε, the empty string; let's analyze the grammar both ways.</p>
<h3>ε is the empty string</h3>
<p>The rule for B says a B is either an empty string or an a followed by a valid B, which amounts to an indefinitely long string of 0 or more a's.</p>
<p>The rule for A says an A is either an a or a B followed by an a. So, an indefinitely long string of a's could be an A too. So, there is no way for the grammar to choose whether a string of a's is either an A or B.</p>
<p>And the rule for S is no help; an S is either an a followed by an indefinitely long string of a's or an indefinitely long string of a's followed by an a. It requires at least one a, but any number of a's from one upwards is OK, but the grammar has no basis to decide between the left and right alternatives.</p>
<p>So, this grammar is inherently ambiguous and cannot, in my estimation, be made unambiguous; it certainly cannot be made unambiguous without other information not in our possession.</p>
<h3>ε is not the empty string</h3>
<p>What about if ε is not the empty string?</p>
<ul>
<li>B is either ε or an aε.</li>
<li>A is either an a or a B followed by an a (so either an a or an aε or an aaε).</li>
<li>Either: S is an a followed by an A (hence aa, aaε, or aaaε)</li>
<li>Or: S is a B followed by an a (hence εa or aεa).</li>
</ul>
<p>In this case, the grammar is unambiguous as it stands (though not necessarily LR(1)). Clearly, a lot hinges on the meaning of 'epsilon' in the comment/question.</p>
<h3>Associativity</h3>
<p>I don't think associativity affects this grammar. It generally comes into play with infix operators (such as the '+' in 'a + b').</p>
|
2,508,918 |
Why does the Java compiler not like primitive int as type for values in HashMap?
|
<p>The compiler complains about this code:</p>
<pre><code> HashMap<String,int> userName2ind = new HashMap<String,int>();
for (int i=0; i<=players.length; i++) {
userName2ind.put(orderedUserNames[i],i+1);
}
</code></pre>
<p>It writes "unexpected type" and point on <code>int</code>. If I replace <code>int</code> by <code>String</code> and <code>i+1</code> by <code>i+"1"</code>, the compilation goes OK. What is wrong with in here?</p>
| 2,508,933 | 2 | 4 | null |
2010-03-24 15:24:31.543 UTC
| 4 |
2014-04-24 21:53:08.48 UTC
|
2014-04-24 21:53:08.48 UTC
| null | 657,970 | null | 245,549 | null | 1 | 29 |
java|types|integer|hashmap
| 29,692 |
<p>It's fine with <code>Integer</code>, but not okay with <code>int</code> - <a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html" rel="noreferrer">Java generics only work with reference types</a>, basically :(</p>
<p>Try this - although be aware it will box everything:</p>
<pre><code>HashMap<String,Integer> userName2ind = new HashMap<String,Integer>();
for (int i=0; i<=players.length; i++) {
userName2ind.put(orderedUserNames[i],i+1);
}
</code></pre>
|
35,188,540 |
Get a variable from the URL in a Flask route
|
<p>I have a number of URLs that start with <code>landingpage</code> and end with a unique id. I need to be able to get the id from the URL, so that I can pass some data from another system to my Flask app. How can I get this value?</p>
<pre><code>http://localhost/landingpageA
http://localhost/landingpageB
http://localhost/landingpageC
</code></pre>
| 35,189,294 | 2 | 0 | null |
2016-02-03 21:56:19.737 UTC
| 17 |
2020-09-11 01:49:14.547 UTC
|
2016-02-03 22:52:45.197 UTC
| null | 400,617 | null | 4,001,343 | null | 1 | 32 |
python|url|flask
| 87,270 |
<p>This is answered in the <a href="http://flask.pocoo.org/docs/latest/quickstart/#variable-rules" rel="noreferrer">quickstart</a> of the docs.</p>
<p>You want a variable URL, which you create by adding <code><name></code> placeholders in the URL and accepting corresponding <code>name</code> arguments in the view function.</p>
<pre><code>@app.route('/landingpage<id>') # /landingpageA
def landing_page(id):
...
</code></pre>
<p>More typically the parts of a URL are separated with <code>/</code>.</p>
<pre><code>@app.route('/landingpage/<id>') # /landingpage/A
def landing_page(id):
...
</code></pre>
<p>Use <code>url_for</code> to generate the URLs to the pages.</p>
<pre><code>url_for('landing_page', id='A')
# /landingpage/A
</code></pre>
<p>You could also pass the value as part of the query string, and <a href="http://flask.pocoo.org/docs/latest/quickstart/#the-request-object" rel="noreferrer">get it from the request</a>, although if it's always required it's better to use the variable like above.</p>
<pre><code>from flask import request
@app.route('/landingpage')
def landing_page():
id = request.args['id']
...
# /landingpage?id=A
</code></pre>
|
27,725,803 |
How to use generic protocol as a variable type
|
<p>Let's say I have a protocol :</p>
<pre><code>public protocol Printable {
typealias T
func Print(val:T)
}
</code></pre>
<p>And here is the implementation </p>
<pre><code>class Printer<T> : Printable {
func Print(val: T) {
println(val)
}
}
</code></pre>
<p>My expectation was that I must be able to use <code>Printable</code> variable to print values like this :</p>
<pre><code>let p:Printable = Printer<Int>()
p.Print(67)
</code></pre>
<p>Compiler is complaining with this error : </p>
<blockquote>
<p>"protocol 'Printable' can only be used as a generic constraint because
it has Self or associated type requirements"</p>
</blockquote>
<p>Am I doing something wrong ? Anyway to fix this ?</p>
<pre><code>**EDIT :** Adding similar code that works in C#
public interface IPrintable<T>
{
void Print(T val);
}
public class Printer<T> : IPrintable<T>
{
public void Print(T val)
{
Console.WriteLine(val);
}
}
//.... inside Main
.....
IPrintable<int> p = new Printer<int>();
p.Print(67)
</code></pre>
<p>EDIT 2: Real world example of what I want. Note that this will not compile, but presents what I want to achieve.</p>
<pre><code>protocol Printable
{
func Print()
}
protocol CollectionType<T where T:Printable> : SequenceType
{
.....
/// here goes implementation
.....
}
public class Collection<T where T:Printable> : CollectionType<T>
{
......
}
let col:CollectionType<Int> = SomeFunctiionThatReturnsIntCollection()
for item in col {
item.Print()
}
</code></pre>
| 27,726,029 | 3 | 1 | null |
2014-12-31 19:57:30.45 UTC
| 41 |
2018-04-18 02:57:02.22 UTC
|
2014-12-31 23:31:04.497 UTC
| null | 574,019 | null | 574,019 | null | 1 | 97 |
ios|xcode|generics|swift
| 37,156 |
<p>As Thomas points out, you can declare your variable by not giving a type at all (or you could explicitly give it as type <code>Printer<Int></code>. But here's an explanation of why you can't have a type of the <code>Printable</code> protocol.</p>
<p>You can't treat protocols with associated types like regular protocols and declare them as standalone variable types. To think about why, consider this scenario. Suppose you declared a protocol for storing some arbitrary type and then fetching it back:</p>
<pre><code>// a general protocol that allows for storing and retrieving
// a specific type (as defined by a Stored typealias
protocol StoringType {
typealias Stored
init(_ value: Stored)
func getStored() -> Stored
}
// An implementation that stores Ints
struct IntStorer: StoringType {
typealias Stored = Int
private let _stored: Int
init(_ value: Int) { _stored = value }
func getStored() -> Int { return _stored }
}
// An implementation that stores Strings
struct StringStorer: StoringType {
typealias Stored = String
private let _stored: String
init(_ value: String) { _stored = value }
func getStored() -> String { return _stored }
}
let intStorer = IntStorer(5)
intStorer.getStored() // returns 5
let stringStorer = StringStorer("five")
stringStorer.getStored() // returns "five"
</code></pre>
<p>OK, so far so good.</p>
<p>Now, the main reason you would have a type of a variable be a protocol a type implements, rather than the actual type, is so that you can assign different kinds of object that all conform to that protocol to the same variable, and get polymorphic behavior at runtime depending on what the object actually is.</p>
<p>But you can't do this if the protocol has an associated type. How would the following code work in practice?</p>
<pre><code>// as you've seen this won't compile because
// StoringType has an associated type.
// randomly assign either a string or int storer to someStorer:
var someStorer: StoringType =
arc4random()%2 == 0 ? intStorer : stringStorer
let x = someStorer.getStored()
</code></pre>
<p>In the above code, what would the type of <code>x</code> be? An <code>Int</code>? Or a <code>String</code>? In Swift, all types must be fixed at compile time. A function cannot dynamically shift from returning one type to another based on factors determined at runtime.</p>
<p>Instead, you can only use <code>StoredType</code> as a generic constraint. Suppose you wanted to print out any kind of stored type. You could write a function like this:</p>
<pre><code>func printStoredValue<S: StoringType>(storer: S) {
let x = storer.getStored()
println(x)
}
printStoredValue(intStorer)
printStoredValue(stringStorer)
</code></pre>
<p>This is OK, because at compile time, it's as if the compiler writes out two versions of <code>printStoredValue</code>: one for <code>Int</code>s, and one for <code>String</code>s. Within those two versions, <code>x</code> is known to be of a specific type.</p>
|
2,736,965 |
How to programatically trigger a mouse left click in C#?
|
<p>How could I programmatically trigger a left-click event on the mouse?</p>
<p>Thanks.</p>
<p>edit: the event is not triggered directly on a button. I'm aiming for the Windows platform.</p>
| 2,737,001 | 3 | 2 | null |
2010-04-29 11:46:08.237 UTC
| 7 |
2017-05-16 11:45:11.917 UTC
|
2012-05-05 04:29:30.843 UTC
| null | 210,916 | null | 279,362 | null | 1 | 7 |
c#|click|mouse
| 38,846 |
<p><a href="https://web.archive.org/web/20140214230712/http://www.pinvoke.net/default.aspx/user32.sendinput" rel="nofollow noreferrer">https://web.archive.org/web/20140214230712/http://www.pinvoke.net/default.aspx/user32.sendinput</a></p>
<p>Use the Win32 API to send input.</p>
<p><strong>Update:</strong></p>
<p>Since I no longer work with Win32 API, I will not update this answer to be correct when the platform changes or websites become unavailable. Since this answer doesn't even conform to Stackoverflow standards (does not contain the answer itself, but rather a link to an external, now defunct resource), there's no point giving it any points or spending any more time on it.</p>
<p>Instead, take a look at this question on Stackoverflow, which I think is a duplicate:</p>
<p><a href="https://stackoverflow.com/questions/2416748/how-to-simulate-mouse-click-in-c">How to simulate Mouse Click in C#?</a></p>
|
63,388,135 |
VS Code: ModuleNotFoundError: No module named 'pandas'
|
<p>Tried to import <code>pandas</code> in VS Code with</p>
<pre><code>import pandas
</code></pre>
<p>and got</p>
<pre><code>Traceback (most recent call last):
File "c:\Users\xxxx\hello\sqltest.py", line 2, in <module>
import pandas
ModuleNotFoundError: No module named 'pandas'
</code></pre>
<p>Tried to install <code>pandas</code> with</p>
<pre><code>pip install pandas
pip3 install pandas
python -m pip install pandas
</code></pre>
<p>separately which returned</p>
<pre><code>(.venv) PS C:\Users\xxxx\hello> pip3 install pandas
Requirement already satisfied: pandas in c:\users\xxxx\hello\.venv\lib\site-packages (1.1.0)
Requirement already satisfied: pytz>=2017.2 in c:\users\xxxx\hello\.venv\lib\site-packages (from pandas) (2020.1)
Requirement already satisfied: numpy>=1.15.4 in c:\users\xxxx\hello\.venv\lib\site-packages (from pandas) (1.19.1)
Requirement already satisfied: python-dateutil>=2.7.3 in c:\users\xxxx\hello\.venv\lib\site-packages (from pandas) (2.8.1)
Requirement already satisfied: six>=1.5 in c:\users\xxxx\hello\.venv\lib\site-packages (from python-dateutil>=2.7.3->pandas) (1.15.0)
</code></pre>
<p>Tried:</p>
<pre><code>sudo pip install pandas
</code></pre>
<p>and got</p>
<pre><code>(.venv) PS C:\Users\xxxx\hello> sudo pip install pandas
sudo : The term 'sudo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ sudo pip install pandas
+ ~~~~
+ CategoryInfo : ObjectNotFound: (sudo:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code></pre>
<p>I also tried to change the python path under workspace settings following <a href="https://stackoverflow.com/a/54107016/11901732">this answer</a>. with <code>C:\Users\xxxx\AppData\Local\Microsoft\WindowsApps\python.exe</code> which is the python path I found in Command Prompt using <code>where python</code> but didn't work.</p>
<p>Then I tried</p>
<pre><code>python -m venv .venv
</code></pre>
<p>which returned</p>
<pre><code>(.venv) PS C:\Users\xxxx\hello> python -m venv .venv
Error: [Errno 13] Permission denied: 'C:\\Users\\xxxx\\hello\\.venv\\Scripts\\python.exe'
</code></pre>
<hr />
<p>Update:</p>
<p>Tried</p>
<pre><code>python3.8.5 -m pip install pandas
</code></pre>
<p>and returned</p>
<pre><code>(.venv) PS C:\Users\xxxx\hello> python3.8.5 -m pip install pandas
python3.8.5 : The term 'python3.8.5' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python3.8.5 -m pip install pandas
+ ~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (python3.8.5:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code></pre>
| 63,390,341 | 8 | 8 | null |
2020-08-13 04:27:37.853 UTC
| 3 |
2022-09-12 21:58:45.3 UTC
|
2020-08-13 05:30:23.877 UTC
| null | 11,901,732 | null | 11,901,732 | null | 1 | 8 |
python|visual-studio-code
| 54,945 |
<p>The solution seems fairly simple! First things first though!</p>
<p>From looking at your post, you seem to have followed a guide into installing <code>Pandas</code>. Nothing is wrong about that but I must point out first based on your information that you provided to us, you seem to run <strong>Windows Powershell</strong> <code>PS C:\Users\xxxx\hello></code> and <code>the error format matches Powershell</code>. Therefore, <code>sudo</code> isn't <em>recognized</em> because <code>sudo</code> is the admin command for <code>Unix-based</code> systems like <code>Debian, Ubuntu, and so on</code> which is why it's not a valid command!</p>
<p>But here's how to properly install: (I assume you're running Windows but if that's not the case, correct me and Ill give you the Unix version!)</p>
<p>1 - Windows key, search up <code>CMD</code> and run it as <code>administrator</code> this is important to avoid permissions issues!</p>
<p>2 - Run <code>pip3 install pandas</code> <strong>OR</strong> <code>python3 -m pip3 install pandas</code></p>
|
56,913,676 |
Dynamic updates in real time to a django template
|
<p>I'm building a django app that will provide real time data. I'm fairly new to Django, and now i'm focusing on how to update my data in real time, without having to reload the whole page.</p>
<p>Some clarification: the real time data should be update regularly, not only through a user input.</p>
<p><strong>View</strong></p>
<pre><code>def home(request):
symbol = "BTCUSDT"
tst = client.get_ticker(symbol=symbol)
test = tst['lastPrice']
context={"test":test}
return render(request,
"main/home.html", context
)
</code></pre>
<p><strong>Template</strong></p>
<pre><code><h3> var: {{test}} </h3>
</code></pre>
<p>I already asked this question, but i'm having some doubts:</p>
<p>I've been told to use Ajax, and that's ok, but is Ajax good for this case, where i will have a page loaded with data updated in real time every x seconds?</p>
<p>I have also been told to use DRF (Django Rest Framework). I've been digging through it a lot, but what it's not clear to me is how does it work with this particular case.</p>
| 56,964,980 | 2 | 1 | null |
2019-07-06 11:27:43.103 UTC
| 13 |
2019-07-10 07:11:09.167 UTC
| null | null | null | null | 10,290,511 | null | 1 | 8 |
python|django|ajax|django-templates|django-views
| 18,212 |
<p>Here below, I'm giving a checklist of the actions needed to implement a solution based on Websocket and Django Channels, as suggested in a previous comment.
The motivation for this are given at the end.</p>
<h2>1) Connect to the Websocket and prepare to receive messages</h2>
<p>On the client, you need to execute the follwing javascript code:</p>
<pre><code><script language="javascript">
var ws_url = 'ws://' + window.location.host + '/ws/ticks/';
var ticksSocket = new WebSocket(ws_url);
ticksSocket.onmessage = function(event) {
var data = JSON.parse(event.data);
console.log('data', data);
// do whatever required with received data ...
};
</script>
</code></pre>
<p>Here, we open the Websocket, and later elaborate the notifications sent by the server in the <code>onmessage</code> callback.</p>
<p>Possible improvements:</p>
<ul>
<li>support SSL connections</li>
<li>use ReconnectingWebSocket: a small wrapper on WebSocket API that automatically reconnects</li>
</ul>
<pre><code> <script language="javascript">
var prefix = (window.location.protocol == 'https:') ? 'wss://' : 'ws://';
var ws_url = prefix + window.location.host + '/ws/ticks/';
var ticksSocket = new ReconnectingWebSocket(ws_url);
...
</script>
</code></pre>
<h2>2) Install and configure Django Channels and Channel Layers</h2>
<p>To configure Django Channels, follow these instructions:</p>
<p><a href="https://channels.readthedocs.io/en/latest/installation.html" rel="noreferrer">https://channels.readthedocs.io/en/latest/installation.html</a></p>
<p>Channel Layers is an optional component of Django Channels which provides a "group" abstraction which we'll use later; you can follow the instructions given here:</p>
<p><a href="https://channels.readthedocs.io/en/latest/topics/channel_layers.html#" rel="noreferrer">https://channels.readthedocs.io/en/latest/topics/channel_layers.html#</a></p>
<h2>3) Publish the Websocket endpoint</h2>
<p>Routing provides for Websocket (and other protocols) a mapping between the published endpoints and the associated server-side code, much as urlpattens does for HTTP in a traditional Django project</p>
<p>file <code>routing.py</code></p>
<pre><code>from django.urls import path
from channels.routing import ProtocolTypeRouter, URLRouter
from . import consumers
application = ProtocolTypeRouter({
"websocket": URLRouter([
path("ws/ticks/", consumers.TicksSyncConsumer),
]),
})
</code></pre>
<h2>4) Write the consumer</h2>
<p>The Consumer is a class which provides handlers for Websocket standard (and, possibly, custom) events. In a sense, it does for Websocket what a Django view does for HTTP.</p>
<p>In our case:</p>
<ul>
<li>websocket_connect(): we accept the connections and register incoming clients to the "ticks" group</li>
<li>websocket_disconnect(): cleanup by removing che client from the group</li>
<li>new_ticks(): our custom handler which broadcasts the received ticks to it's Websocket client</li>
<li>I assume TICKS_GROUP_NAME is a constant string value defined in project's settings</li>
</ul>
<p>file <code>consumers.py</code>:</p>
<pre><code>from django.conf import settings
from asgiref.sync import async_to_sync
from channels.consumer import SyncConsumer
class TicksSyncConsumer(SyncConsumer):
def websocket_connect(self, event):
self.send({
'type': 'websocket.accept'
})
# Join ticks group
async_to_sync(self.channel_layer.group_add)(
settings.TICKS_GROUP_NAME,
self.channel_name
)
def websocket_disconnect(self, event):
# Leave ticks group
async_to_sync(self.channel_layer.group_discard)(
settings.TICKS_GROUP_NAME,
self.channel_name
)
def new_ticks(self, event):
self.send({
'type': 'websocket.send',
'text': event['content'],
})
</code></pre>
<h2>5) And finally: broadcast the new ticks</h2>
<p>For example: </p>
<pre><code>ticks = [
{'symbol': 'BTCUSDT', 'lastPrice': 1234, ...},
...
]
broadcast_ticks(ticks)
</code></pre>
<p>where:</p>
<pre><code>import json
from asgiref.sync import async_to_sync
import channels.layers
def broadcast_ticks(ticks):
channel_layer = channels.layers.get_channel_layer()
async_to_sync(channel_layer.group_send)(
settings.TICKS_GROUP_NAME, {
"type": 'new_ticks',
"content": json.dumps(ticks),
})
</code></pre>
<p>We need to enclose the call to <code>group_send()</code> in the <code>async_to_sync()</code> wrapper, as channel.layers provides only the async implementation, and we're calling it from a sync context. Much more details on this are given in the Django Channels documentation.</p>
<p>Notes:</p>
<ul>
<li>make sure that "type" attribute matches the name of the consumer's handler (that is: 'new_ticks'); this is required</li>
<li>every client has it's own consumer; so when we wrote self.send() in the consumer's handler, that meant: send the data to a single client</li>
<li>here, we send the data to the "group" abstraction, and Channel Layers in turn will deliver it to every registered consumer</li>
</ul>
<h2>Motivations</h2>
<p>Polling is still the most appropriate choice in some cases, being simple and effective.</p>
<p>However, on some occasions you might suffer a few limitations:</p>
<ul>
<li>you keep querying the server even when no new data are available</li>
<li>you introduce some latency (in the worst case, the full period of the polling). The tradeoff is: less latency = more traffic. </li>
</ul>
<p>With Websocket, you can instead notify the clients only when (and as soon as) new data are available, by sending them a specific message. </p>
|
42,652,980 |
Error:Failed to open zip file. Gradle's dependency cache may be corrupt
|
<p>I updated android studio 2.3 and there is a bug, gradle doesn't build and it keeps giving me the same error for all projects. </p>
<pre><code>Error:Failed to open zip file.
Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
<a href="syncProject">Re-download dependencies and sync project (requires network)</a>
<a href="syncProject">Re-download dependencies and sync project (requires network)</a>
</code></pre>
<p>I have already searched for a solution, but have not found any. I tried: </p>
<pre><code>Invalidate Caches / Restart...
</code></pre>
<p>but nothing has changed.</p>
| 42,654,435 | 20 | 1 | null |
2017-03-07 16:08:28.007 UTC
| 35 |
2022-01-11 13:40:14.117 UTC
|
2017-12-30 12:19:32.79 UTC
| null | 1,705,337 | null | 4,363,391 | null | 1 | 108 |
android|android-studio|gradle|error-handling|sdk
| 210,724 |
<p><strong>UPDATE 17 JULY 2018:</strong></p>
<p>Even if the following solution still works as of today,I've found (thanks to the answer posted by Hamid Asghari and to the comment posted by Mahendra Dabi) that simply deleting the gradle dist directory and performing a reboot of the ide, will fix the issue (please read Hamid post for a full answer, and remember that OSX and Linux have the same gradle path).</p>
<p>If you still want to follow my original solution, you should at least consider using a more up-to-date version of Gradle (direct link of the gradle distribution repo: <a href="https://services.gradle.org/distributions/" rel="noreferrer">https://services.gradle.org/distributions/</a>)</p>
<hr>
<p><strong>Original answer (dated 7 March 2017):</strong></p>
<p>I've faced the same issue this morning after upgrading Android Studio to 2.3.
To solve the issue:</p>
<p>1) Manually download Gradle 3.3 binary (direct link: <a href="https://services.gradle.org/distributions/gradle-3.3-bin.zip" rel="noreferrer">https://services.gradle.org/distributions/gradle-3.3-bin.zip</a>)</p>
<p>2) Open your android studio root directory, and extract the zip to the gradle folder (for example in my Debian machine the full path is /opt/android-studio/gradle/gradle-3.3)</p>
<p>3) Open Android Studio, go to File->Settings->Build, Exectution, Deployment->Gradle and set "Gradle home" to point your new gradle-3.3 folder.</p>
<p>4) Sync and you are ready to go!</p>
|
20,939,159 |
How to set default value on an input box with select2 initialized on it?
|
<p>How do I set default value on an input box with select2? Here is my HTML:</p>
<pre><code><input type="text" id="itemId0" value="Item no. 1">
</code></pre>
<p>and my javascript:</p>
<pre><code>$("#itemId0").select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
</code></pre>
<p>Here is the issue:</p>
<p>If I won't initialize my input box into a <code>select2</code> box, I can display the default value of my input box which is "Item no. 1":
<img src="https://i.stack.imgur.com/7VPDw.png" alt="1st"></p>
<p>but when I initialize it with <code>select2</code> eg. <code>$("#itemId0").select2({code here});</code> I can't then display the default value of my text box:
<img src="https://i.stack.imgur.com/CtznT.png" alt="2"></p>
<p>Anyone knows how can I display the default value please?</p>
| 20,939,609 | 9 | 0 | null |
2014-01-05 21:05:55.27 UTC
| 7 |
2020-04-01 18:57:00.52 UTC
|
2020-04-01 18:57:00.52 UTC
| null | 10,794,031 | null | 2,997,398 | null | 1 | 25 |
javascript|jquery
| 96,172 |
<p>You need to utilize the <code>initSelection</code> method as described in Select2's documentation.</p>
<p>From the <a href="http://ivaynberg.github.io/select2/">documentation</a>:</p>
<blockquote>
<p>Called when Select2 is created to allow the user to initialize the selection based on the value of the element select2 is attached to.</p>
</blockquote>
<p>In your case, take a look at the <a href="http://ivaynberg.github.io/select2/#ajax">Loading Remote Data</a> example as it shows how to incorporate it along with AJAX requests.</p>
<p>I hope this helps.</p>
|
38,705,377 |
"Setup has detected that Visual Studio 2015 Update 3 may not be completely installed...."
|
<blockquote>
<p>"...Please repair Visual Studio 2015 Update 3, then install this
product again."</p>
</blockquote>
<p>I'm getting this when I try and update the ASP.NET Web Tools Extension in my version of VS 2015 which I installed only today. After I got this error I checked and my version was Update 3. I tried to install it regardless and got a message saying that I already had it.</p>
<p>Any ideas on how I can get around this issue?</p>
| 38,705,908 | 2 | 4 | null |
2016-08-01 18:07:07.907 UTC
| 4 |
2016-09-16 15:41:20.067 UTC
|
2016-09-16 15:41:20.067 UTC
|
user1228
| null | null | 736,370 | null | 1 | 33 |
visual-studio|visual-studio-2015
| 3,815 |
<p>Ok after some digging I got to the bottom of this. It seems that I need to have .Net Core Installed. However when I go to install that I get the same error. The workaround is to run the downloaded .exe from the command line with the added parameter:</p>
<blockquote>
<p>DotNetCore.1.0.0-VS2015Tools.Preview2.exe SKIP_VSU_CHECK=1</p>
</blockquote>
<p>This will install the latest version of Web Tools as well.</p>
|
50,156,326 |
Json Format for a TimeSpan that can be bound using Microsoft.Extensions.Configuration
|
<p>In a project I need to configure some third party library via the Micorosoft.Extensions.Configuration.</p>
<p>The library gives an options class and I used the configurationSection.Bind(optionsClassInstance) method to bind the values.</p>
<p>It works well except the nested TimeSpan value.
I can't figure out what the json structure of a timespan is so it could be bound.</p>
<p>There are no errors. The values from the json are simply not bound.</p>
<p>So far I just used "timespan": { "Days": 0, "Hours": 1, "Minutes": 0 }</p>
<hr>
<p>Thanks to the answer I tested successfully the given values with the given results:</p>
<p>1.02:03:04.567 = 1 day, 2 hours, 3 minutes, 4 seconds, 567 milliseconds</p>
<p>1.02:03:04 = 1 day, 2 hours, 3 minutes, 4 seconds, 0 milliseconds</p>
<p>02:03:04 = 0 days, 2 hours, 3 minutes, 4 seconds, 0 milliseconds</p>
<p>03:04 = 0 days, 3 hours, 4 minutes, 0 seconds, 0 milliseconds</p>
<p>04 = 4 days, 0 hours, 0 minutes, 0 seconds, 0 milliseconds</p>
| 50,157,340 | 1 | 0 | null |
2018-05-03 13:31:26.033 UTC
| 2 |
2018-05-15 07:43:18.607 UTC
|
2018-05-15 07:43:18.607 UTC
| null | 639,019 | null | 639,019 | null | 1 | 28 |
.net-core|asp.net-core-2.0
| 8,789 |
<p>Timespan format in .net core is <code>D.HH:mm:nn</code> (so "1.02:03:04" is 1 day, 2 hours, 3 mins, 4 seconds).</p>
<p>javascript wont be able to read that (we use a custom JsonConverter for timespan objects for that reason), but .Net can.</p>
<pre><code>{"timespan":"1.02:03:04"}
</code></pre>
|
40,605,834 |
Spring JpaRepositroy.save() does not appear to throw exception on duplicate saves
|
<p>I'm currently playing around on Spring boot 1.4.2 in which I've pulled in Spring-boot-starter-web and Spring-boot-starter-jpa.</p>
<p>My main issue is that when I save a new entity it works fine (all cool).</p>
<p>However if I save a new product entity with the same id (eg a duplicate entry), it does not throw an exception. I was expecting ConstrintViolationException or something similar.</p>
<p>Given the following set up:</p>
<p>Application.java</p>
<pre><code>@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
</code></pre>
<p>ProductRepository.java</p>
<pre><code>@Repository
public interface ProductRepository extends JpaRepository<Product, String> {}
</code></pre>
<p>JpaConfig.java</p>
<pre><code>@Configuration
@EnableJpaRepositories(basePackages = "com.verric.jpa.repository" )
@EntityScan(basePackageClasses ="com.verric.jpa")
@EnableTransactionManagement
public class JpaConfig {
@Bean
JpaTransactionManager transactionManager() {
return new JpaTransactionManager();
}
}
</code></pre>
<p>Note JpaConfig.java and Application.java are in the same package.</p>
<p>ProductController.java</p>
<pre><code>@RestController
@RequestMapping(path = "/product")
public class ProductController {
@Autowired
ProductRepository productRepository;
@PostMapping("createProduct")
public void handle(@RequestBody @Valid CreateProductRequest request) {
Product product = new Product(request.getId(), request.getName(), request.getPrice(), request.isTaxable());
try {
productRepository.save(product);
} catch (DataAccessException ex) {
System.out.println(ex.getCause().getMessage());
}
}
}
</code></pre>
<p>and finally Product.java</p>
<pre><code>@Entity(name = "product")
@Getter
@Setter
@AllArgsConstructor
@EqualsAndHashCode(of = "id")
public class Product {
protected Product() { /* jpa constructor*/ }
@Id
private String id;
@Column
private String name;
@Column
private Long price;
@Column
private Boolean taxable;
}
</code></pre>
<p>The getter, setter and equalsHashcode.. are <a href="https://projectlombok.org/" rel="noreferrer">lombok</a> annotations.</p>
<p><strong>Miscellaneous:</strong></p>
<p>Spring boot : 1.4.2</p>
<p>Hibernate ORM: 5.2.2.FINAL</p>
<p>This issue happens regardless if I annotate the controller with or without <code>@Transactional</code></p>
<p>The underlying db shows the exception clearly </p>
<pre><code>2016-11-15 18:03:49 AEDT [40794-1] verric@stuff ERROR: duplicate key value violates unique constraint "product_pkey"
2016-11-15 18:03:49 AEDT [40794-2] verric@stuff DETAIL: Key (id)=(test001) already exists
</code></pre>
<p>I know that is better (more common) to break the data access stuff into its own service layer instead of dumping it in the controller</p>
<p>The semantics of the controller aren't ReST</p>
<p><strong>Things I've tried:</strong></p>
<p><a href="https://stackoverflow.com/questions/23325413/spring-crudrepository-exceptions">Spring CrudRepository exceptions</a></p>
<p>I've tried implementing the answer from this question, unfortunately my code never ever hits the DataAccesException exception </p>
<p><a href="https://stackoverflow.com/questions/25266248/does-spring-jpa-throw-an-error-if-save-function-is-unsuccessful">Does Spring JPA throw an error if save function is unsuccessful?</a></p>
<p>Again similar response to the question above.</p>
<p><a href="http://www.baeldung.com/spring-dataIntegrityviolationexception" rel="noreferrer">http://www.baeldung.com/spring-dataIntegrityviolationexception</a></p>
<p>I tried adding the bean to my JPAconfig.java class that is:</p>
<pre><code> @Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
</code></pre>
<p>But nothing seemed to happen.</p>
<p>Sorry for long post, ty in advance</p>
| 40,608,937 | 5 | 0 | null |
2016-11-15 09:08:07.26 UTC
| 8 |
2022-02-25 08:27:48.743 UTC
|
2017-05-23 12:00:10.777 UTC
| null | -1 | null | 1,982,646 | null | 1 | 35 |
java|spring-data|spring-data-jpa
| 73,685 |
<p>I think you are aware of <code>CrudRepository.save()</code> is used for both insert and update. If an Id is non existing then it will considered an insert if Id is existing it will be considered update. You may get an Exception if your send the Id as null.</p>
<p>Since you don't have any other annotations apart from <code>@Id</code> on your <code>id</code> variable, The Unique Id generation must be handled by your code Or else you need to make use of <code>@GeneratedValue</code> annotation. </p>
|
33,640,864 |
How to sort based on/compare multiple values in Kotlin?
|
<p>Say I have a <code>class Foo(val a: String, val b: Int, val c: Date)</code> and I want to sort a list of <code>Foo</code>s based on all three properties. How would I go about this?</p>
| 33,640,865 | 3 | 0 | null |
2015-11-10 22:27:46.187 UTC
| 19 |
2020-12-12 17:27:02.477 UTC
| null | null | null | null | 615,306 | null | 1 | 95 |
comparable|kotlin
| 37,687 |
<p>Kotlin's stdlib offers a number of useful helper methods for this.</p>
<p>First, you can define a comparator using the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/compare-by.html" rel="noreferrer"><code>compareBy()</code></a> method and pass it to the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/sorted-with.html" rel="noreferrer"><code>sortedWith()</code></a> extension method to receive a sorted copy of the list:</p>
<pre><code>val list: List<Foo> = ...
val sortedList = list.sortedWith(compareBy({ it.a }, { it.b }, { it.c }))
</code></pre>
<p>Second, you can let <code>Foo</code> implement <code>Comparable<Foo></code> using the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/compare-values-by.html" rel="noreferrer"><code>compareValuesBy()</code></a> helper method:</p>
<pre><code>class Foo(val a: String, val b: Int, val c: Date) : Comparable<Foo> {
override fun compareTo(other: Foo)
= compareValuesBy(this, other, { it.a }, { it.b }, { it.c })
}
</code></pre>
<p>Then you can call the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/sorted.html" rel="noreferrer"><code>sorted()</code></a> extension method without parameters to receive a sorted copy of the list:</p>
<pre><code>val sortedList = list.sorted()
</code></pre>
<h3>Sorting direction</h3>
<p>If you need to sort ascending on some values and descending on other values, the stdlib also offers functions for that:</p>
<pre><code>list.sortedWith(compareBy<Foo> { it.a }.thenByDescending { it.b }.thenBy { it.c })
</code></pre>
<h3>Performance considerations</h3>
<p>The <code>vararg</code> version of <code>compareValuesBy</code> is not inlined in the bytecode meaning anonymous classes will be generated for the lambdas. However, if the lambdas themselves don't capture state, singleton instances will be used instead of instantiating the lambdas everytime.</p>
<p>As noted by <a href="https://stackoverflow.com/users/3761545/paul-woitaschek">Paul Woitaschek</a> in the comments, comparing with multiple selectors will instantiate an array for the vararg call everytime. You can't optimize this by extracting the array as it will be copied on every call. What you can do, on the other hand, is extract the logic into a static comparator instance and reuse it:</p>
<pre><code>class Foo(val a: String, val b: Int, val c: Date) : Comparable<Foo> {
override fun compareTo(other: Foo) = comparator.compare(this, other)
companion object {
// using the method reference syntax as an alternative to lambdas
val comparator = compareBy(Foo::a, Foo::b, Foo::c)
}
}
</code></pre>
|
33,924,198 |
How do you cleanly list all the containers in a kubernetes pod?
|
<p>I am looking to list all the containers in a pod in a script that gather's logs after running a test. <code>kubectl describe pods -l k8s-app=kube-dns</code> returns a lot of info, but I am just looking for a return like:</p>
<pre><code>etcd
kube2sky
skydns
</code></pre>
<p>I don't see a simple way to format the describe output. Is there another command? (and I guess worst case there is always parsing the output of describe).</p>
| 33,925,363 | 14 | 0 | null |
2015-11-25 18:44:47.217 UTC
| 34 |
2022-05-08 07:35:59.953 UTC
| null | null | null | null | 557,406 | null | 1 | 139 |
kubernetes
| 162,406 |
<p>You can use <code>get</code> and choose one of the supported output template with the <code>--output</code> (<code>-o</code>) flag. </p>
<p>Take <code>jsonpath</code> for example,
<code>kubectl get pods -l k8s-app=kube-dns -o jsonpath={.items[*].spec.containers[*].name}</code> gives you <code>etcd kube2sky skydns</code>. </p>
<p>Other supported output output templates are go-template, go-template-file, jsonpath-file. See <a href="http://kubernetes.io/docs/user-guide/jsonpath/" rel="noreferrer">http://kubernetes.io/docs/user-guide/jsonpath/</a> for how to use jsonpath template. See <a href="https://golang.org/pkg/text/template/#pkg-overview" rel="noreferrer">https://golang.org/pkg/text/template/#pkg-overview</a> for how to use go template. </p>
<p>Update: Check this doc for other example commands to list container images: <a href="https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/" rel="noreferrer">https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/</a></p>
|
44,906,317 |
What are possible values for data_augmentation_options in the TensorFlow Object Detection pipeline configuration?
|
<p>I have successfully trained an object detection model with TensorFlow with the sample configurations given here: <a href="https://github.com/tensorflow/models/tree/master/object_detection/samples/configs" rel="noreferrer">https://github.com/tensorflow/models/tree/master/object_detection/samples/configs</a></p>
<p>Now I want to fine tune my configuration to get better results. One of the promising options I see in there is "data_augmentation_options" under "train_config". Currently, it looks like this: </p>
<pre><code>train_config: {
batch_size: 1
...
data_augmentation_options {
random_horizontal_flip {
}
}
}
</code></pre>
<p>Are there other options to do random scaling, cropping or tweaking of brightness?</p>
| 46,901,051 | 2 | 0 | null |
2017-07-04 12:42:38.723 UTC
| 29 |
2021-07-12 18:43:46.113 UTC
| null | null | null | null | 2,730,201 | null | 1 | 60 |
tensorflow|configuration|object-detection
| 34,569 |
<p>The list of options is provided in <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/protos/preprocessor.proto" rel="noreferrer">preprocessor.proto</a>: </p>
<pre><code>NormalizeImage normalize_image = 1;
RandomHorizontalFlip random_horizontal_flip = 2;
RandomPixelValueScale random_pixel_value_scale = 3;
RandomImageScale random_image_scale = 4;
RandomRGBtoGray random_rgb_to_gray = 5;
RandomAdjustBrightness random_adjust_brightness = 6;
RandomAdjustContrast random_adjust_contrast = 7;
RandomAdjustHue random_adjust_hue = 8;
RandomAdjustSaturation random_adjust_saturation = 9;
RandomDistortColor random_distort_color = 10;
RandomJitterBoxes random_jitter_boxes = 11;
RandomCropImage random_crop_image = 12;
RandomPadImage random_pad_image = 13;
RandomCropPadImage random_crop_pad_image = 14;
RandomCropToAspectRatio random_crop_to_aspect_ratio = 15;
RandomBlackPatches random_black_patches = 16;
RandomResizeMethod random_resize_method = 17;
ScaleBoxesToPixelCoordinates scale_boxes_to_pixel_coordinates = 18;
ResizeImage resize_image = 19;
SubtractChannelMean subtract_channel_mean = 20;
SSDRandomCrop ssd_random_crop = 21;
SSDRandomCropPad ssd_random_crop_pad = 22;
SSDRandomCropFixedAspectRatio ssd_random_crop_fixed_aspect_ratio = 23;
</code></pre>
<p>You can see the details about each option in <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/core/preprocessor.py" rel="noreferrer">preprocessor.py</a>. Arguments can be provided as key-value pairs.</p>
<pre><code> data_augmentation_options {
ssd_random_crop {
}
}
data_augmentation_options {
random_pixel_value_scale {
minval: 0.6
}
}
</code></pre>
|
36,433,572 |
How does ancestry path work with git log?
|
<p>I've read the <a href="https://git-scm.com/docs/git-log">git log documentation</a>, but I still find it very difficult to understand what the <code>--ancestry-path</code> option does. I see different ways to invoke <code>git log</code>:</p>
<pre><code>$ git log origin/master..HEAD
$ git log --ancestry-path origin/master..HEAD
</code></pre>
<p>In the first command, I get a list of commits that are on HEAD but not on <code>origin/master</code>, basically this shows me what is on my branch that isn't merged.</p>
<p>In the second command, I get nothing. If I change to 3 dots (<code>...</code>) it shows me <em>something</em>, but I'm not sure how to make sense of it. Basically, how is the addition of <code>--ancestry-path</code> any different? What exactly does it <em>simplify</em>?</p>
| 36,437,843 | 3 | 0 | null |
2016-04-05 17:52:57.88 UTC
| 13 |
2022-09-11 13:33:07.457 UTC
| null | null | null | null | 157,971 | null | 1 | 26 |
git
| 8,015 |
<p><a href="https://stackoverflow.com/a/36433669/1256452">Matthieu Moy's answer</a> is correct but may not help you very much, if you haven't been exposed to the necessary graph theory.</p>
<h3>DAGs</h3>
<p>First, let's take a quick look at <strong>D</strong>irected <strong>A</strong>cyclic <strong>G</strong>raphs or DAGs. A DAG is just a graph (hence the <code>g</code>), i.e., a collection of nodes and connections between them—these work like train stations on rail lines, for instance, where the stations are the nodes—that is "directed" (the <code>d</code>: trains only run one way) and have no loops in them (the <code>a</code>).</p>
<p>Linear chains and tree structures are valid DAGs (note: newer commits are to the right, in general, here):</p>
<pre><code>o <- o <- o
</code></pre>
<p>or:</p>
<pre><code> o <- o
/
o <- o
\ o
\ /
o
\
o <- o
</code></pre>
<p>(imagine the diagonal connections having arrow heads so that they point up-and-left or down-and-left, as needed).</p>
<p>However, non-tree graphs can have nodes that merge back (these are git's merges):</p>
<pre><code> o <- o
/ \
o <- o \
\ o \
\ / \
o o
\ /
o <- o
</code></pre>
<p>or:</p>
<pre><code> o--o
/ \
o--o o--o
\ /
o--o
</code></pre>
<p>(I'm just compressing the notation further here, nodes still generally point leftward).</p>
<p>Next, git's <code>..</code> notation does not mean what most people usually first think it means. In particular, let's take a look at this graph again, add another node, and use some single letters to mark particular nodes:</p>
<pre><code> o---o
/ \
A--o \
\ B \
\ / \
o C--D
\ /
o---o
</code></pre>
<p>And, let's do one more thing, and stop thinking about this as just <code>git log</code> but rather the more general case of "selecting revisions with ancestry".</p>
<h3>Selecting revisions (commits), with ancestry</h3>
<p>If we select revision <code>A</code>, we get just revision <code>A</code>, because it has no ancestors (nothing to the left of it).</p>
<p>If we select revision <code>B</code> we get this piece of the graph:</p>
<pre><code>A--o
\ B
\ /
o
</code></pre>
<p>This is because select-with-ancestry means "Take the commit I identify, and all the commits I can get to by following the arrows back out of it." Here the result is somewhat interesting, but not <em>very</em> interesting since there are no merges and following the arrows nets us a linear chain of four commits, starting from <code>B</code> and going back to <code>A</code>.</p>
<p>Selecting either <code>C</code> or <code>D</code> with ancestry, though, gets us much further. Let's see what we get with <code>D</code>:</p>
<pre><code> o---o
/ \
A--o \
\ \
\ \
o C--D
\ /
o---o
</code></pre>
<p>This is, in fact, everything <em>except</em> commit <code>B</code>. Why didn't we get <code>B</code>? Because the arrows all point leftward: we get <code>D</code>, which points to <code>C</code>, which points to two un-lettered commits; those two point left, and so on, but when we hit the node just left-and-down of <code>B</code>, we aren't allowed to go rightward, against the arrow, so we can't reach <code>B</code>.</p>
<h3>Two-dot notation</h3>
<p>Now, the two-dot notation in git is really just shorthand syntax for set subtraction.<sup>1</sup> That is, if we write <code>B..D</code> for instance, it means: "Select <code>D</code> with ancestry, and then select <code>B</code> with ancestry, and then give me the set of commits from the <code>D</code> selection after excluding (subtracting away) all commits from the <code>B</code> selection."</p>
<p>Selecting <code>D</code> with ancestry gets the entire graph <em>except</em> for the <code>B</code> commit. Subtracting away the <code>B</code> selection removes <code>A</code>, the two <code>o</code> nodes we drew earlier, and <code>B</code>. How can we remove <code>B</code> when it's not in the set? Easy: we just <em>pretend</em> to remove it and say we're done! That is, set subtraction only bothers to remove things that are actually in the set.</p>
<p>The result for <code>B..D</code> is therefore this graph:</p>
<pre><code> o---o
\
\
\
\
C--D
/
o---o
</code></pre>
<h3>Three-dot notation</h3>
<p>The three-dot notation is different. It's more useful in a simple branch-y graph, perhaps even a straight tree. Let's start with the tree-like graph this time and look at both two- and three-dot notation. Here's our tree-like graph, with some single letter names for nodes put in:</p>
<pre><code> o--I
/
G--H
\ J
\ /
K
\
o--L
</code></pre>
<p>This time I've added extra letters because we'll need to talk about some of the places the commits "join up", in particular at nodes <code>H</code> and <code>K</code>.</p>
<p>Using two-dot notation, what do we get for <code>L..I</code>? To find the answer, start at node <code>I</code> and work backwards. You must always move leftward, even if you also go up or down. These are the commits that are selected. Then, start at node <code>L</code> and work backwards, finding the nodes to <em>un</em>-select; if you come across any earlier selected ones, toss them out. (Making the final list is left as an exercise, though I'll put the answer in as a footnote.<sup>2</sup>)</p>
<p>Now let's see the three-dot notation in action. What it does is a bit complicated, because it must find the <em>merge base</em> between two branches in the graph. The merge base has a formal definition,<sup>3</sup> but for our purposes it's just: "The point where, when following the graph backwards, we meet up at some commit."</p>
<p>In this case, for instance, if we ask for <code>L...I</code> or <code>I...L</code>—both produce the same result—git finds all commits that are reachable from <em>either</em> commit, but not from <em>both</em>. That is, it excludes the merge base and all earlier commits, but keeps the commits beyond that point.</p>
<p>The merge base of <code>L</code> and <code>I</code> (or <code>I</code> and <code>L</code>) is commit <code>H</code>, so we get things after <code>H</code>, but not <code>H</code> itself, and we cannot reach node <code>J</code> from either <code>I</code> or <code>L</code> since it's not in their ancestry. Hence, the result for <code>I...L</code> or <code>L...I</code> is:</p>
<pre><code> o--I
K
\
o--L
</code></pre>
<p>(Note that these histories do not join up, since we tossed out node <code>H</code>.)</p>
<h3><code>--ancestry-path</code></h3>
<p>Now, all these are ordinary selection operations. None have been modified with <code>--ancestry-path</code>. The <a href="https://www.kernel.org/pub/software/scm/git/docs/git-rev-list.html" rel="noreferrer">documentation for <code>git log</code> and <code>git rev-list</code></a>—these two are almost the same command, except for their output format—describes <code>--ancestry-path</code> this way:</p>
<blockquote>
<p>When given a range of commits to display (e.g. <code>commit1..commit2</code> or
<code>commit2 ^commit1</code>), only display commits that exist directly on the
ancestry chain between the <code>commit1</code> and <code>commit2</code>, i.e. commits that
are both descendants of <code>commit1</code>, and ancestors of <code>commit2</code>.</p>
</blockquote>
<p>We define <em>ancestors</em> here in terms of the commit DAG: a first commit is a <em>direct ancestor</em> of a second if the second has an arrow pointing back at the first, and an <em>indirect ancestor</em> if the second points back at the first through some chain of commits. (For selection purposes a commit is also considered an ancestor of itself.)</p>
<p><em>Descendants</em> (also sometimes called <em>children</em>) are defined similarly, but by going against the arrows in the graph. A commit is a child (or descendant) of another commit if there's a path between them.</p>
<p>Note that the description of the <code>--ancestry-path</code> talks about using the two-dot notation, not the three-dot notation, probably because the implementation of the three-dot notation is a little bit weird inside. As noted earlier, <code>B...D</code> excludes (as if with leading <code>^</code>) the <em>merge base</em> (or bases, if there is/are more than one) of the two commits, so the merge base is the one that play the "must be child-of" role. I'll mention how <code>--ancestry-path</code> works with this, though I'm not sure how useful it is in "real world" examples.</p>
<h3>Practical examples</h3>
<p>What does this mean in practice? Well, it depends on the arguments you give, and the actual commit DAG. Let's look at the funky loopy graph again:</p>
<pre><code> o---o
/ \
A--o \
\ B \
\ / \
o C--D
\ /
o---o
</code></pre>
<p>Suppose we ask for <code>B..D</code> here <em>without</em> <code>--ancestry-path</code>. This means we take commit <code>D</code> and its ancestors, but exclude <code>B</code> and its ancestors, just as we saw before. Now let's add <code>--ancestry-path</code>. Everything we had earlier was an ancestor of <code>D</code>, and that's still true, but this new flag says we must <em>also</em> toss out commits that are <em>not</em> children of <code>B</code>.</p>
<p>How many children does node <code>B</code> have? Well, none! So we must toss out every commit, giving us a <em>completely empty list</em>.</p>
<hr />
<p>What if we ask for <code>B...D</code>, without the special <code>--ancestry-path</code> notation? That gives us everything reachable from either <code>D</code> <em>or</em> <code>B</code>, but excludes everything reachable from both <code>D</code> <em>and</em> <code>B</code>:</p>
<pre><code> o---o
\
\
B \
\
C--D
/
o---o
</code></pre>
<p>This is the same as <code>B..D</code> except that we get node <code>B</code> as well.</p>
<p>[Note: the section below on mixing <code>--ancestry-path</code> with <code>B...D</code> was wrong for almost a year, between April 2016 and Feb 2017. It has been fixed to note that the "must be child" part starts from the <em>merge base(s)</em>, not from the left side of the <code>B...D</code> notation.]</p>
<p>Suppose we add <code>--ancestry-path</code> here. We <em>start</em> with the same graph we just got for <code>B...D</code> without <code>--ancestry-path</code>, but then <em>discard</em> items that are not children of the merge base. The merge base is the <code>o</code> just to the left of <code>B</code>. The top row <code>o</code> commits are not children of this node, so they are discarded. Again, as with ancestors, we consider a node its own child, so we <em>would</em> keep this node itself—giving this partial result:</p>
<pre><code> B
/
o C--D
\ /
o---o
</code></pre>
<p>But, while we are (or <code>--ancestry-path</code> is) discarding children of this merge base node, the merge base node itself, to the down-and-left of <code>B</code>, was not in the <code>B...D</code> graph in the first place. Hence, the final result (actually tested in Git 2.10.1) is:</p>
<pre><code> B
C--D
/
o---o
</code></pre>
<p>(Again, I'm not really sure how useful this is in practice. The starting graph, again, is that of <code>B...D</code>: everything reachable from <em>either</em> commit, minus everything reachable from <em>both</em> commits: this works by discarding starting from every merge base, if there are two or more. The child-of checking code also handles a list of commits. It retains everything that <em>is</em> a child of <em>any</em> of the merge bases, if there are multiple merge bases. See the function <code>limit_to_ancestry</code> in <a href="https://github.com/git/git/blob/master/revision.c" rel="noreferrer"><code>revision.c</code></a>.)</p>
<h3>Thus, it depends on the graph <em>and</em> the selectors</h3>
<p>The final action of <code>X..Y</code> or <code>X...Y</code>, with or without <code>--ancestry-path</code>, depends on the commit graph. To predict it, you must draw the graph. (Use <code>git log --graph</code>, perhaps with <code>--oneline --decorate --all</code>, or use a viewer that draws the graph for you.)</p>
<hr />
<p><sup>1</sup>There's an exception in <code>git diff</code>, which does its own special handling for <code>X..Y</code> and <code>X...Y</code>. When you are not using <code>git diff</code> you should just ignore its special handling.</p>
<p><sup>2</sup>We start with <code>I</code> and the <code>o</code> to its left, and also <code>H</code> and <code>G</code>. Then we lose <code>H</code> and <code>G</code> when we work back from <code>L</code>, so the result is just <code>o--I</code>.</p>
<p><sup>3</sup>The formal definition is that the merge base is the <strong>L</strong>owest <strong>C</strong>ommon <strong>A</strong>ncestor, or LCA, of the given nodes in the graph. In some graphs there may be multiple LCAs; for Git, these are all merge bases, and <code>X...Y</code> will exclude all of them.</p>
<p>It's interesting / instructive to run <code>git rev-parse B...D</code> for the graph I drew. These commit hashes here depend on not just the graph itself, and the commit, but also the <em>time stamps</em> at which one makes the commits, so if you build this same graph, you will get different hashes, but here are the ones I got while revising the answer to fix the description of <code>--ancestry-path</code> interacting with <code>B...D</code>:</p>
<pre><code>$ git rev-parse B...D
3f0490d4996aecc6a17419f9cf5a4ab420c34cc2
7f0b666b4098282301a9f95e056a646483c2e5fc
^843eaf75d78520f9a569da35d4e561a036a7f107
</code></pre>
<p>but we can see that these are <code>D</code>, <code>B</code>, and the merge base, in that order, using several more commands:</p>
<pre><code>$ git rev-parse B # this produces the middle hash
7f0b666b4098282301a9f95e056a646483c2e5fc
</code></pre>
<p>and:</p>
<pre><code>$ git rev-parse D # this produces the first hash
3f0490d4996aecc6a17419f9cf5a4ab420c34cc2
</code></pre>
<p>and:</p>
<pre><code>$ git merge-base B D # this produces the last, negated, hash
843eaf75d78520f9a569da35d4e561a036a7f107
</code></pre>
<p>Graphs with multiple merge bases do occur, but they're somewhat harder to construct—the easy way is with "criss cross" merges, where you run <code>git checkout br1; git merge br2; git checkout br2; git merge br1</code>. If you get this situation and run <code>git rev-list</code> you will see several negated hashes, one per merge base. Run <code>git merge-base --all</code> and you will see the same set of merge bases.</p>
|
44,427,682 |
Why does '<', '> ' work with wrapper classes while '==' doesn't ?
|
<p>I know that '==' doesn't work with values outside the range of [-128,127] as there is a cache maintained of Integer objects within this range and the same reference is returned if value is within the range. But why does '>', '<', '>=', '<=' give correct answers even outside the range ?</p>
<pre><code>Integer a=150;
Integer b=150;
System.out.println(a==b); //returns false
Integer a=150;
Integer b=150;
System.out.println(a>=b); // returns true
</code></pre>
<p>Why is this happening ?</p>
| 44,427,723 | 1 | 0 | null |
2017-06-08 05:57:22.457 UTC
| 4 |
2017-06-08 15:17:10.333 UTC
| null | null | null | null | 8,063,278 | null | 1 | 50 |
java
| 3,409 |
<p>The <code><</code>, <code>></code>, <code><=</code> and <code>>=</code> operators are only defined for primitive types. Therefore using them on wrapper types causes the compiler to unbox the objects into primitives.</p>
<p>This means</p>
<pre><code>System.out.println(a>=b);
</code></pre>
<p>is equivalent to</p>
<pre><code>System.out.println(a.intValue()>=b.intValue());
</code></pre>
<p>However, the <code>==</code> and <code>!=</code> operators exist for both primitive types and reference types, so using them to compare two objects of primitive wrapper types compares the references instead of the primitive values they wrap.</p>
<p>As Holger commented, comparison of object references with <code>==</code> and <code>!=</code> existed in the Java language before auto-boxing and auto-unboxing were introduced, but comparison with <code><</code>, <code>></code>, <code><=</code> and <code>>=</code> was not supported for any reference types before auto-unboxing was introduced.</p>
<p>This means that in the early days of Java, the <code>a>=b</code> of your code snippet would not pass compilation (since <code>a</code> and <code>b</code> are not primitive numeric types). On the other hand your <code>a==b</code> snippet would still pass compilation and return <code>false</code>.</p>
<p>Changing the behavior of <code>==</code> and <code>!=</code> for reference types that happen to be wrappers of numeric primitives would change the behavior of existing code, thus breaking backwards compatibility, which is probably the reason it wasn't done.</p>
|
26,158,411 |
Amazon EC2 custom AMI not running bootstrap (user-data)
|
<p>I have encountered an issue when creating custom AMIs (images) on EC2 instances. If I start up a Windows default 2012 server instance with a custom bootstrap/user-data script such as;</p>
<pre><code><powershell>
PowerShell "(New-Object System.Net.WebClient).DownloadFile('http://download.microsoft.com/download/3/2/2/3224B87F-CFA0-4E70-BDA3-3DE650EFEBA5/vcredist_x64.exe','C:\vcredist_x64.exe')"
</powershell>
</code></pre>
<p>It will work as intended and go to the URL and download the file, and store it on the C: Drive.</p>
<p>But if I setup a Windows Server Instance, then create a image from it, and store it as a Custom AMI, then deploy it with the exact same custom user-data script it will not work. But if I go to the instance url (<code>http://169.254.169.254/latest/user-data</code>) it will show the script has imported successfully but has not been executed.</p>
<p>After checking the error logs I have noticed this on a regular occasion: </p>
<pre><code>Failed to fetch instance metadata http://169.254.169.254/latest/user-data with exception The remote server returned an error: (404) Not Found.
</code></pre>
| 26,161,256 | 5 | 0 | null |
2014-10-02 09:54:02.547 UTC
| 8 |
2021-09-07 19:04:53.94 UTC
|
2017-08-05 06:23:37.107 UTC
| null | 1,033,581 | null | 1,091,244 | null | 1 | 28 |
amazon-web-services|amazon-ec2
| 26,634 |
<h2>Update 4/15/2017: For EC2Launch and Windows Server 2016 AMIs</h2>
<p>Per AWS documentation for EC2Launch, Windows Server 2016 users can continue using the persist tags introduced in EC2Config 2.1.10:</p>
<blockquote>
<p>For EC2Config version 2.1.10 and later, or for EC2Launch, you can use
true in the user data to enable the plug-in after
user data execution. </p>
</blockquote>
<p><strong>User data example:</strong></p>
<pre><code><powershell>
insert script here
</powershell>
<persist>true</persist>
</code></pre>
<p><strong>For subsequent boots:</strong></p>
<p>Windows Server 2016 users must additionally enable <a href="http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2launch.html#ec2launch-config" rel="noreferrer">configure and enable EC2Launch</a> instead of EC2Config. EC2Config was deprecated on Windows Server 2016 AMIs in favor of EC2Launch. </p>
<p>Run the following powershell to schedule a Windows Task that will run the user data on next boot:</p>
<pre><code>C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts\InitializeInstance.ps1 –Schedule
</code></pre>
<p>By design, this task is disabled after it is run for the first time. However, using the persist tag causes Invoke-UserData to schedule a separate task via Register-FunctionScheduler, to persist your user data on subsequent boots. You can see this for yourself at <code>C:\ProgramData\Amazon\EC2-Windows\Launch\Module\Scripts\Invoke-Userdata.ps1</code>.</p>
<p><strong>Further troubleshooting:</strong></p>
<p>If you're having additional issues with your user data scripts, you can find the user data execution logs at <code>C:\ProgramData\Amazon\EC2-Windows\Launch\Log\UserdataExecution.log</code> for instances sourced from the WS 2016 base AMI.</p>
<hr>
<h2>Original Answer: For EC2Config and older versions of Windows Server</h2>
<p>User data execution is automatically disabled after the initial boot. When you created your image, it is probable that execution had already been disabled. This is configurable manually within <code>C:\Program Files\Amazon\Ec2ConfigService\Settings\Config.xml</code>.</p>
<p>The <a href="http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_WinAMI.html" rel="noreferrer">documentation for "Configuring a Windows Instance Using the EC2Config Service"</a> suggests several options:</p>
<ul>
<li><p>Programmatically create a scheduled task to run at system start using <code>schtasks.exe /Create</code>, and point the scheduled task to the user data script (or another script) at <code>C:\Program Files\Amazon\Ec2ConfigServer\Scripts\UserScript.ps1</code>.</p></li>
<li><p>Programmatically enable the user data plug-in in Config.xml.</p></li>
</ul>
<p>Example, from the documentation:</p>
<pre><code><powershell>
$EC2SettingsFile="C:\Program Files\Amazon\Ec2ConfigService\Settings\Config.xml"
$xml = [xml](get-content $EC2SettingsFile)
$xmlElement = $xml.get_DocumentElement()
$xmlElementToModify = $xmlElement.Plugins
foreach ($element in $xmlElementToModify.Plugin)
{
if ($element.name -eq "Ec2SetPassword")
{
$element.State="Enabled"
}
elseif ($element.name -eq "Ec2HandleUserData")
{
$element.State="Enabled"
}
}
$xml.Save($EC2SettingsFile)
</powershell>
</code></pre>
<ul>
<li>Starting with EC2Config version 2.1.10, you can use <code><persist>true</persist></code> to enable the plug-in after user data execution.</li>
</ul>
<p>Example, from the documentation:</p>
<pre><code><powershell>
insert script here
</powershell>
<persist>true</persist>
</code></pre>
|
40,349,213 |
"Conversion failed because the data value overflowed the specified type" error applies to only one column of the same table
|
<p>I am trying to import data from database access file into SQL server. To do that, I have created SSIS package through SQL Server Import/Export wizard. All tables have passed validation when I execute package through execute package utility with "validate without execution" option checked. However, during the execution I received the following chunk of errors (using a picture, since blockquote uses a lot of space):</p>
<p><a href="https://i.stack.imgur.com/m0G2u.png" rel="noreferrer"><img src="https://i.stack.imgur.com/m0G2u.png" alt="Errors"></a></p>
<p>Upon the investigation, I found exactly the table and the column, which was causing the problem. However, this is problem I have been trying to solve for a couple days now, and I'm running dry on possible options.</p>
<h1>Structure of the troubled table column</h1>
<p>As noted from the error list, the trouble occurs in RHF Repairs table on the Date Returned column. In Access, the column in question is Date/Time type. Inside the actual table, all inputs are in a form of 'mmddyy', which when clicked upon, turn into 'mm/dd/yyyy' format:</p>
<p><a href="https://i.stack.imgur.com/k3P8y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/k3P8y.png" alt="Input for March 8, 2004"></a></p>
<p>In SSIS package, it created OLEDB Source/Destination relationship like following:</p>
<p><a href="https://i.stack.imgur.com/HdzGq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HdzGq.png" alt="Relationship in SSIS"></a></p>
<p>Inside this relationship, in both output columns and external columns data type is DT_DATE (I still think it is a key cause of my problems). What bugs me the most is that the adjacent to Date Returned column is exactly the same as what I described above, and none of the errors applied to it or any other columns of the same type, Date Returned is literally the only black sheep in the flock.</p>
<h1>What have I tried</h1>
<p>I have tried every option from the following <a href="https://stackoverflow.com/questions/27720417/ssis-intermittent-error-conversion-failed-because-the-data-value-overflowed-t">thread</a>, the error remains the same.</p>
<p>I tried Data conversion option, trying to convert this column into datestamp or even unicode string. It didn't work.</p>
<p><a href="https://i.stack.imgur.com/6SjGp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6SjGp.png" alt="Data Conversion"></a></p>
<p>I tried to specify data type with the advanced source editor to both datestamp/unicode string. I tried specifying it only in output columns, tried in both external and output columns, same result.</p>
<p>Plowing through the data in access table also did not give me anything. All of them use the same 6-char formatting through it all.</p>
<p>At this point, I literally exhausted all options I could think of. <strong>Can you please point me in the right direction on what else I could possibly try to resolve it</strong>, since it drives me nuts for last two days.</p>
<p>PS: On my end, I will plow through each row individually, while not trying to get discouraged by the fact that there are 4000+ row entries...</p>
<h1>UPDATE:</h1>
<p>I resolved this matter by plowing through data. There were 3 faulty entries among 4000+ rows... Since the issue was resolved in a manner unlikely to help others, please close that question.</p>
| 40,351,184 | 3 | 3 | null |
2016-10-31 19:28:12.697 UTC
| 3 |
2021-07-15 20:59:22.153 UTC
|
2017-05-23 12:30:51.377 UTC
| null | -1 | null | 6,406,617 | null | 1 | 6 |
sql-server|date|ssis|sql-server-2012|data-conversion
| 39,804 |
<p>It sounds to me like you have one or more bad dates in the column. With 4,000 rows, I actually would visually scan and look for something very short or very long. </p>
<p>You could change your source to selecting top 1 instead of all 4,000. Do those insert? If so, that would lend weight to the bad date scenario. If 1 row does not flow through, it is another issue.</p>
|
20,929,355 |
JQuery Validate input file type
|
<p>I have a form that can have 0-hundreds of <code><input type="file"></code> elements. I have named them sequentially depending on how many are dynamically added to the page. </p>
<p>For example:</p>
<pre><code><input type="file" required="" name="fileupload1" id="fileupload1">
<input type="file" required="" name="fileupload2" id="fileupload2">
<input type="file" required="" name="fileupload3" id="fileupload3">
<input type="file" required="" name="fileupload999" id="fileupload999">
</code></pre>
<p>In my JQuery I want to validate these inputs on acceptable MIME/file type. Like this:</p>
<pre><code>$("#formNew").validate({
rules: {
fileupload: {
required: true,
accept: "image/jpeg, image/pjpeg"
}
}
</code></pre>
<p>Immediately my problem is that the <code>name</code> attribute of the input file elements is dynamic. It has to be dynamic so that my web application can deal with each upload correctly. So obviously using "fileupload" isn't going to work in the rules section.</p>
<p>How do I set the rules for all inputs which have a name like "fileupload"?</p>
<p>This is the code that dynamically adds the inputs:</p>
<pre><code>var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
$('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
filenumber++;
return false;
});
$("#FileUploader").on('click', '.RemoveFileUpload', function () { //Remove input
if (filenumber > 0) {
$(this).parent('li').remove();
filenumber--;
}
return false;
});
</code></pre>
| 20,929,391 | 3 | 0 | null |
2014-01-05 02:35:20.82 UTC
| 5 |
2015-10-28 14:25:28.787 UTC
|
2014-10-18 08:38:30.833 UTC
| null | 2,893,413 | null | 1,774,037 | null | 1 | 12 |
jquery|jquery-validate
| 117,302 |
<p>One the elements are added, use the rules method to add the rules</p>
<pre><code>//bug fixed thanks to @Sparky
$('input[name^="fileupload"]').each(function () {
$(this).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
})
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/arunpjohny/8dAU8/" rel="noreferrer">Fiddle</a></p>
<hr>
<p>Update</p>
<pre><code>var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
var $li = $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
$('#FileUpload' + filenumber).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
filenumber++;
return false;
});
</code></pre>
|
31,592,726 |
How to store a file with file extension with multer?
|
<p>Managed to store my files in a folder but they store without the file extension.</p>
<p>Does any one know how would I store the file with file extension?</p>
| 31,867,456 | 16 | 0 | null |
2015-07-23 16:11:22.817 UTC
| 20 |
2021-10-10 19:24:18.673 UTC
|
2015-12-04 00:05:02.747 UTC
| null | 3,924,118 | null | 3,355,603 | null | 1 | 68 |
node.js|express|npm|multer
| 86,503 |
<p>From the docs: "Multer will not append any file extension for you, your function should return a filename complete with an file extension."</p>
<p>Here's how you can add the extension:</p>
<pre><code>var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '.jpg') //Appending .jpg
}
})
var upload = multer({ storage: storage });
</code></pre>
<p>I would recommend using the <code>mimetype</code> property to determine the extension. For example:</p>
<pre><code>filename: function (req, file, cb) {
console.log(file.mimetype); //Will return something like: image/jpeg
</code></pre>
<p>More info: <a href="https://github.com/expressjs/multer">https://github.com/expressjs/multer</a></p>
|
41,772,697 |
"Flex: none" vs. Non-specified (omitted) flex property
|
<p>Is there a difference between <code>flex: none</code> and leaving the flex property undefined?</p>
<p>I tested it in several simple layouts and I don't see the difference.</p>
<p>For example, I could remove <code>flex: none</code> from blue item (see code below), and the layout, as I understand, remains the same. Does I understand it right?</p>
<p>And, the second question, what about more complex layouts? Should I write <code>flex: none</code> or I can simply omit it?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-container {
display: flex;
width: 400px;
height: 150px;
background-color: lightgrey;
}
.flex-item {
margin: 10px;
}
.item1 {
flex: none; /* Could be omitted? */
background-color: cornflowerblue;
}
.item2 {
flex: 1;
background-color: orange;
}
.item3 {
flex: 1;
background-color: green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
<div class="flex-item item1">flex item 1</div>
<div class="flex-item item2">flex item 2</div>
<div class="flex-item item3">flex item 3</div>
</div></code></pre>
</div>
</div>
</p>
<p><a href="https://jsfiddle.net/r4s8z835/" rel="noreferrer">https://jsfiddle.net/r4s8z835/</a></p>
| 41,773,340 | 2 | 0 | null |
2017-01-20 21:34:33.377 UTC
| 9 |
2017-01-20 22:37:35.343 UTC
|
2017-01-20 22:37:35.343 UTC
| null | 3,597,276 | null | 5,587,480 | null | 1 | 13 |
html|css|flexbox
| 13,832 |
<blockquote>
<p>Is there a difference between <code>flex: none</code> and leaving the flex property undefined?</p>
</blockquote>
<p><code>flex: none</code> is equivalent to <code>flex: 0 0 auto</code>, which is shorthand for:</p>
<ul>
<li><code>flex-grow: 0</code></li>
<li><code>flex-shrink: 0</code></li>
<li><code>flex-basis: auto</code></li>
</ul>
<p>Simply put, <code>flex: none</code> sizes the flex item according to the width / height of the content, but doesn't allow it to shrink. This means the item has the potential to overflow the container.</p>
<p>If you omit the <code>flex</code> property (and longhand properties), the initial values are as follows:</p>
<ul>
<li><code>flex-grow: 0</code></li>
<li><code>flex-shrink: 1</code></li>
<li><code>flex-basis: auto</code></li>
</ul>
<p>This is known as <code>flex: initial</code>.</p>
<p>This means the item will not grow when there is free space available (just like <code>flex: none</code>), but it can shrink when necessary (unlike <code>flex: none</code>).</p>
<hr>
<blockquote>
<p>I could remove <code>flex: none</code> from blue item (see code below), and the layout, as I understand, remains the same.</p>
</blockquote>
<p>In terms of <a href="https://jsfiddle.net/r4s8z835/" rel="noreferrer"><strong>your demo</strong></a>, the reason there is no difference when <code>flex: none</code> is removed is that the two siblings (<code>.item2</code> and <code>.item3</code>) are flexible (<code>flex: 1</code>), and there is enough space in the container to accommodate the content of <code>.item1</code>.</p>
<p>However, if <code>.item1</code> had more content, <code>flex: none</code> would make a big difference.</p>
<p><a href="https://jsfiddle.net/r4s8z835/4/" rel="noreferrer"><strong>revised fiddle</strong></a></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-container {
display: flex;
width: 400px;
height: 150px;
background-color: lightgrey;
}
.flex-item {
margin: 10px;
}
.item1 {
flex: none; /* Now try removing it. */
background-color: cornflowerblue;
}
.item2 {
flex: 1;
background-color: orange;
}
.item3 {
flex: 1;
background-color: green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
<div class="flex-item item1">flex item 1 flex item 1 flex item 1 flex item 1flex item 1 flex item 1flex item 1flex item 1</div>
<div class="flex-item item2">flex item 2</div>
<div class="flex-item item3">flex item 3</div>
</div></code></pre>
</div>
</div>
</p>
|
24,471,229 |
Uncaught TypeError: Undefined is not a function on indexOf
|
<p>I currently have this code to check the website URL GET options for a specific ID, but whenever this code is run, I get a weird error: <code>Uncaught TypeError: Undefined is not a function</code></p>
<p>Here is my code:</p>
<pre><code><script language="JavaScript">
var familyid = "id=8978566";
var corporateid = "id=8978565";
if(window.location.indexOf(familyid) === -1)
{
document.write("Family ID not found");
}
</script>
</code></pre>
<p>It would be awesome if i could get some guidance on this issue... I couldn't find similar issues using the <code>.indexOf()</code> function</p>
| 24,471,253 | 1 | 0 | null |
2014-06-28 21:41:47.707 UTC
| 4 |
2014-06-28 21:45:42.753 UTC
| null | null | null | null | 2,400,000 | null | 1 | 16 |
javascript|get|typeerror|indexof|location-href
| 40,776 |
<p>window.location is a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location" rel="noreferrer"><code>Location</code></a> object, not a string, and <code>indexOf</code> is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf" rel="noreferrer">String</a> (or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" rel="noreferrer">Array</a>) method.</p>
<p>If you want to search the query params, try</p>
<pre><code>window.location.search.indexOf(familyId)
</code></pre>
<p>or if you want check the whole url, </p>
<pre><code>window.location.toString().indexOf(familyId)
</code></pre>
|
24,911,021 |
Vagrant corrupted index file C:\Users\USERNAME\.vagrant.d/data/machine-index/index
|
<p>My Windows 8.1 just crashed. Now I have some files on my dist that are corrupted. This includes my vagrant machine index (Not shure if the naming is right but I know that it is this file -> C:\Users\USERNAME.vagrant.d/data/machine-index/index).</p>
<p>So There is a lot of binary or hexdecimal stuff in there (Again not shure because I don't deal with this stuff usualy so correct me if I'm wrong!) And Vagrant spits out the following message if I try to start everything after boot.</p>
<p><code>vagrant up</code> returns this</p>
<pre><code>The machine index which stores all required information about
running Vagrant environments has become corrupt. This is usually
caused by external tampering of the Vagrant data folder.
Vagrant cannot manage any Vagrant environments if the index is
corrupt. Please attempt to manually correct it. If you are unable
to manually correct it, then remove the data file at the path below.
This will leave all existing Vagrant environments "orphaned" and
they'll have to be destroyed manually.
Path: C:/Users/Username/.vagrant.d/data/machine-index/index
</code></pre>
| 25,227,659 | 3 | 0 | null |
2014-07-23 12:53:06.437 UTC
| 10 |
2021-11-17 12:04:02.517 UTC
|
2017-03-07 20:06:48.657 UTC
| null | 472,495 | null | 1,401,296 | null | 1 | 57 |
virtual-machine|vagrant|windows-8.1
| 18,664 |
<p>Same thing happened to me. So I just deleted the index file and the .lock file from the machine-index folder to get Vagrant working again.</p>
|
2,704,583 |
Multithreading improvements in .NET 4
|
<p>I have heard that the .NET 4 team has added new classes in the framework that make working with threads better and easier.</p>
<p>Basically the question is what are the new ways to run multithreaded tasks added in .NET 4 and what are they designed to be used for?</p>
<p><strong>UPD:</strong> Just to make it clear, I'm not looking for <em>a single</em> way of running parallel tasks in .NET 4, I want to find out which are the new ones added, and if possible what situation would <em>each</em> of them be best suited for..</p>
| 2,708,064 | 3 | 0 | null |
2010-04-24 13:20:58.283 UTC
| 20 |
2011-09-27 23:50:40.387 UTC
|
2010-05-15 22:06:21.477 UTC
| null | 164,901 | null | 254,716 | null | 1 | 28 |
c#|.net|multithreading|.net-4.0
| 25,175 |
<p>With the lack of responses, I decided to evaluate on the answers below with that I've learned..
As @Scott stated, .NET 4 added the Task Parallel Library which adds a number of innovations, new methods and approaches to parallelism.</p>
<ul>
<li>One of the first things to mention is the <code>Parallel.For</code> and <code>Parallel.ForEach</code> methods, which allow the developer to process multiple items in multiple threads. The Framework in this case will decide how many threads are necessary, and when to create new threads, and when not to.<br>
This is a very simple and straightforward way to parallelize existing code, and add some performance boost. </li>
<li>Another way, somewhat similar to the previous approaches is using the PLINQ extenders. They take an existing enumeration, and extend it with parallel linq extenders. So if you have an existing linq query, you can easily convert it to PLINQ. What this means is all the operations on the PLINQ enumerable will also take advantage of multiple threads, and filtering your list of objects using a <code>.Where</code> clause, for example, will run in multiple threads now!</li>
<li>One of the bigger innovations in the TPL is the new <code>Task</code> class. In some ways it may look like the already well known <code>Thread</code> class, but it takes advantage of the new Thread Pool in .NET 4 (which has been improved a lot compared on previous versions), and is much more functional than the regular <code>Thread</code> class. For example you can chain Tasks where tasks in the middle of the chain will only start when the previous ones finish. Examples and in-depth explanation in a screencast on <a href="http://channel9.msdn.com/posts/philpenn/Task-and-TaskTResult-Waiting-and-Continuations/" rel="noreferrer">Channel 9</a></li>
<li>To enhance the work with Task classes, we can use the <code>BlockingCollection<></code>. This works perfectly in situations where you have a producer-consumer scenario. You can have multiple threads producing some objects, that will then be consumed and processed by consumer methods. This can be easily parallelised and controlled with the Task factory and the blocking collection. Useful screencast with examples from <a href="http://channel9.msdn.com/posts/philpenn/BlockingCollectionT-Demonstration-in-Producer-Consumer-Scenarios/" rel="noreferrer">Channel 9</a><br>
These can also use different backing storage classes (ConcurrentQueue, ConcurentStack, ConcurrentBag), which are all thread safe, and are different in terms of element ordering and performance. Examples and explanations of them in a different <a href="http://channel9.msdn.com/posts/philpenn/Concurrent-Programming-with-NET4-Collections/" rel="noreferrer">video here</a></li>
<li>One more new thing that has been added (which probably isn't part of the TPL, but helps us here anyway) is the <code>CountdownEvent</code> class, which can help us in "task coordination scenarios" (c). Basically allows us to wait until all parallel tasks are finished. Screencast with example usage on <a href="http://channel9.msdn.com/posts/philpenn/The-NET4-Countdown-Synchronization-Primitive/" rel="noreferrer">Channel 9</a></li>
</ul>
<p>You can see a number of screencasts and videos on Channel 9 that are tagged with <a href="http://channel9.msdn.com/tags/Parallel+Computing/" rel="noreferrer">"Parallel Computing"</a></p>
|
2,521,592 |
Difference between IEnumerable Count() and Length
|
<p>What are the key differences between <code>IEnumerable</code> <code>Count()</code> and <code>Length</code>?</p>
| 2,521,614 | 3 | 0 | null |
2010-03-26 07:05:15.05 UTC
| 13 |
2018-07-19 17:56:49.4 UTC
|
2010-03-26 07:13:41.487 UTC
| null | 58,635 | null | 94,494 | null | 1 | 76 |
c#|.net|ienumerable
| 109,114 |
<p>By calling Count on <code>IEnumerable<T></code> I'm assuming you're referring to the extension method <code>Count</code> on <code>System.Linq.Enumerable</code>. <code>Length</code> is not a method on <code>IEnumerable<T></code> but rather a property on array types in .Net such as <code>int[]</code>.</p>
<p>The difference is performance. The<code>Length</code> property is guaranteed to be a O(1) operation. The complexity of the <code>Count</code> extension method differs based on runtime type of the object. It will attempt to cast to several types which support O(1) length lookup like <code>ICollection<T></code> via a <code>Count</code> property. If none are available then it will enumerate all items and count them which has a complexity of O(N). </p>
<p>For example</p>
<pre><code>int[] list = CreateSomeList();
Console.WriteLine(list.Length); // O(1)
IEnumerable<int> e1 = list;
Console.WriteLine(e1.Count()); // O(1)
IEnumerable<int> e2 = list.Where(x => x <> 42);
Console.WriteLine(e2.Count()); // O(N)
</code></pre>
<p>The value <code>e2</code> is implemented as a C# iterator which does not support O(1) counting and hence the method <code>Count</code> must enumerate the entire collection to determine how long it is. </p>
|
2,712,076 |
How to use an iterator?
|
<p>I'm trying to calculate the distance between two points. The two points I stored in a vector in C++: (0,0) and (1,1).</p>
<p>I'm supposed to get results as</p>
<pre><code>0
1.4
1.4
0
</code></pre>
<p>But the actual result that I got is</p>
<pre><code>0
1
-1
0
</code></pre>
<p>I think there's something wrong with the way I use iterator in vector.
How can I fix this problem?</p>
<p>I posted the code below.</p>
<pre><code>typedef struct point {
float x;
float y;
} point;
float distance(point *p1, point *p2)
{
return sqrt((p1->x - p2->x)*(p1->x - p2->x) +
(p1->y - p2->y)*(p1->y - p2->y));
}
int main()
{
vector <point> po;
point p1; p1.x = 0; p1.y = 0;
point p2; p2.x = 1; p2.y = 1;
po.push_back(p1);
po.push_back(p2);
vector <point>::iterator ii;
vector <point>::iterator jj;
for (ii = po.begin(); ii != po.end(); ii++)
{
for (jj = po.begin(); jj != po.end(); jj++)
{
cout << distance(ii,jj) << " ";
}
}
return 0;
}
</code></pre>
| 2,712,125 | 3 | 0 | null |
2010-04-26 08:42:35.63 UTC
| 43 |
2019-10-13 22:32:55.043 UTC
|
2015-10-11 10:54:30.583 UTC
| null | 63,550 |
user188276
| null | null | 1 | 76 |
c++|pointers|vector|iterator|using-statement
| 45,063 |
<p>That your code compiles at all is probably because you have a <code>using namespace std</code> somewhere. (Otherwise <code>vector</code> would have to be <code>std::vector</code>.) <a href="https://stackoverflow.com/questions/2879555/c-stl-how-to-write-wrappers-for-cout-cerr-cin-and-endl/2880136#2880136"><strong>That's something I would advise against</strong></a> and you have just provided a good case why:<br>
By accident, your call picks up <code>std::distance()</code>, which takes two iterators and calculates the distance between them. Remove the using directive and prefix all standard library types with <code>std::</code> and the compiler will tell you that you tried to pass a <code>vector <point>::iterator</code> where a <code>point*</code> was required. </p>
<p>To get a pointer to an object an iterator points to, you'd have to dereference the iterator - which gives a reference to the object - and take the address of the result: <code>&*ii</code>.<br>
(Note that a pointer would perfectly fulfill all requirements for a <code>std::vector</code> iterator and some earlier implementations of the standard library indeed used pointers for that, which allowed you to treat <code>std::vector</code> iterators as pointers. But modern implementations use a special iterator class for that. I suppose the reason is that using a class allows overloading functions for pointers and iterators. Also, using pointers as <code>std::vector</code> iterators encourages mixing pointers and iterators, which will prevent the code to compile when you change your container.) </p>
<p>But rather than doing this, I suggest you change your function so that it takes references instead (see <a href="https://stackoverflow.com/questions/2139224/2139254#2139254">this answer</a> for why that's a good idea anyway.) : </p>
<pre><code>float distance(const point& p1, const point& p2)
{
return sqrt((p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y));
}
</code></pre>
<p>Note that the points are taken by <code>const</code> references. This indicates to the caller that the function won't change the points it is passed. </p>
<p>Then you can call it like this: <code>distance(*ii,*jj)</code>.</p>
<hr>
<p>On a side note, this </p>
<pre><code>typedef struct point {
float x;
float y;
} point;
</code></pre>
<p>is a C-ism unnecessary in C++. Just spell it </p>
<pre><code>struct point {
float x;
float y;
};
</code></pre>
<p>That would make problems if this <code>struct</code> definition ever was to parse from a C compiler (the code would have to refer to <code>struct point</code> then, not simply <code>point</code>), but I guess <code>std::vector</code> and the like would be far more of a challenge to a C compiler anyway. </p>
|
2,407,872 |
How to structure Javascript programs in complex web applications?
|
<p>I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more or less) thing.</p>
<p>Let's have an look at an arbitrary exemplary UI widget that makes up a tiny part of the application: The widget may be a part of a window and the window may be a part of a window manager:</p>
<ol>
<li>The eventhandlers use DOM elements as parameters. The DOM element represents a widget in the browser.</li>
<li>A lot of times I use jQuery objects (Basically wrappers around DOM elements) to do something with the widget. Sometimes they are used transiently, sometimes they are stored in a variable for later purposes.</li>
<li>The AJAX function calls use string identifiers for these widgets. They are processed server side.</li>
<li>Beside that I have a widget class whose instances represent a widget. It is instantiated through the new operator.</li>
</ol>
<p>Now I have somehow four different object identifiers for the same thing, which needs to be kept in sync until the page is loaded anew. This seems not to be a good thing.</p>
<h3>Any advice?</h3>
<br/>
<br/>
<b>EDIT:</b><br/>
*@Will Morgan*: It's a form designer that allows to create web forms within the browser. The backend is Zope, a python web application server. It's difficult to get more explicit as this is a general problem I observe all the time when doing Javascript development with the trio jQuery, DOM tree and my own prototyped class instances.
<p><b>EDIT2:</b><br />
I think it would helpful to make an example, albeit an artificial one. Below you see a logger widget that can be used to add a block element to a web page in which logged items are displayed.</p>
<pre><code>makeLogger = function(){
var rootEl = document.createElement('div');
rootEl.innerHTML = 'Logged items:';
rootEl.setAttribute('class', 'logger');
var append = function(msg){
// append msg as a child of root element.
var msgEl = document.createElement('div');
msgEl.innerHTML = msg;
rootEl.appendChild(msgEl);
};
return {
getRootEl: function() {return rootEl;},
log : function(msg) {append(msg);}
};
};
// Usage
var logger = makeLogger();
var foo = document.getElementById('foo');
foo.appendChild(logger.getRootEl());
logger.log('What\'s up?');
</code></pre>
<p>At this point I have a wrapper around the HTMLDivElement (the hosted object). With having the logger instance (the native object) at hand I can easily work with it through the function <em>logger.getRootEl()</em>.<br />
Where I get stuck is when I only have the DOM element at hand and need to do something with the public API returned by function <em>makeLogger</em> (e.g. in event handlers). And this is where the mess starts. I need to hold all the native objects in a repository or something so that I can retrieve again. It would be so much nicer to have a connection (e.g. a object property) from the hosted object back to my native object.
I know it can be done, but it has some drawbacks:</p>
<ul>
<li>These kind of (circular) references are potentially memory leaking up to IE7</li>
<li>When to pass the <i>hosted object</i> and when to pass the <i>native object</i> (in functions)?</li>
</ul>
<p>For now, I do the back referencing with jQuery's data() method. But all in all I don't like the way I have to keep track of the relation between the hosted object and its native counterpart.</p>
<h3>How do you handle this scenario?</h3>
<br/>
<br/>
<b>EDIT3:</b><br/>
After some insight I've gained from Anurag's example..<br/>
*@Anurag:* If I've understood your example right, the critical point is to set up the correct (what's correct depends on your needs, though) <b><i>execution context</i></b> for the event handlers. And this is in your case the presentation object instance, which is done with Mootool's bind() function. So you ensure that you're *ALWAYS* dealing with the wrapper object (I've called it the native object) instead of the DOM object, right?
<br/>
<br/>
<b><i>A note for the reader:</i></b> You're not forced to use Mootools to achieve this. In jQuery, you would setup your event handlers with the *$.proxy()* function, or if you're using plain old Javascript, you would utilize the *apply* property that every function exposes.
| 2,437,556 | 4 | 5 |
2010-03-09 15:16:02.93 UTC
|
2010-03-09 09:25:52.707 UTC
| 18 |
2021-03-27 18:00:03.277 UTC
|
2021-03-27 18:00:03.277 UTC
| null | 712,558 | null | 49,628 | null | 1 | 27 |
javascript|architecture|web-applications
| 3,473 |
<p>For the four objects that need to be synchronized, you could have a single object and pass the reference around in a constructor, or as function arguments.</p>
<p>The way I fix this problem is to never lose a reference to the wrapper object. Whenever a DOM object is needed (for example inserting into the page), this wrapper object provides it. But sticking that widget onto the screen, the wrapper object sets up all event handling and AJAX handling code specific to the widget, so the reference the the wrapper is maintained at all times in these event handlers and AJAX callbacks.</p>
<p>I've created a <a href="http://jsfiddle.net/YHcTv/5/" rel="nofollow noreferrer">simple example</a> on jsfiddle using MooTools that might make sense to you.</p>
|
2,845,769 |
Can a std::string contain embedded nulls?
|
<p>For regular C strings, a null character <code>'\0'</code> signifies the end of data.</p>
<p>What about <code>std::string</code>, can I have a string with embedded null characters?</p>
| 2,845,774 | 4 | 1 | null |
2010-05-16 22:42:00.193 UTC
| 5 |
2015-11-03 21:11:37.163 UTC
|
2015-11-03 21:11:37.163 UTC
| null | 827,263 | null | 115,751 | null | 1 | 47 |
c++|stdstring|c-strings|null-terminated
| 23,106 |
<p>Yes you can have embedded nulls in your <code>std::string</code>. </p>
<p>Example:</p>
<pre><code>std::string s;
s.push_back('\0');
s.push_back('a');
assert(s.length() == 2);
</code></pre>
<p>Note: <code>std::string</code>'s <code>c_str()</code> member will always append a null character to the returned char buffer; However, <code>std::string</code>'s <code>data()</code> member may or may not append a null character to the returned char buffer.</p>
<p><strong>Be careful of operator+=</strong></p>
<p>One thing to look out for is to not use <code>operator+=</code> with a <code>char*</code> on the RHS. It will only add up until the null character.</p>
<p>For example:</p>
<pre><code>std::string s = "hello";
s += "\0world";
assert(s.length() == 5);
</code></pre>
<p>The correct way:</p>
<pre><code>std::string s = "hello";
s += std::string("\0world", 6);
assert(s.length() == 11);
</code></pre>
<p><strong>Storing binary data more common to use std::vector</strong></p>
<p>Generally it's more common to use <code>std::vector</code> to store arbitrary binary data.</p>
<pre><code>std::vector<char> buf;
buf.resize(1024);
char *p = &buf.front();
</code></pre>
<p>It is probably more common since <code>std::string</code>'s <code>data()</code> and <code>c_str()</code> members return const pointers so the memory is not modifiable. with &buf.front() you are free to modify the contents of the buffer directly.</p>
|
3,050,984 |
Javascript event e.which?
|
<p>What is the functionality of Javascript event <code>e.which</code>? Please brief with example.</p>
| 3,051,017 | 4 | 4 | null |
2010-06-16 05:50:38.677 UTC
| 21 |
2021-11-03 03:00:07.423 UTC
|
2020-09-29 08:14:05.473 UTC
| null | 4,370,109 | null | 300,097 | null | 1 | 74 |
javascript|dom-events
| 109,581 |
<p><code>e.which</code> is not an event, <code>which</code> is a property of the <code>event</code> object, which most people label as <code>e</code> in their event handlers. It contains the key code of the key which was pressed to trigger the event (eg: keydown, keyup).</p>
<pre><code>document.onkeypress = function(myEvent) { // doesn't have to be "e"
console.log(myEvent.which);
};
</code></pre>
<p>With that code, the console will print out the code of any key you press on the keyboard.</p>
<h2>Deprecation notice (as of September 2020)</h2>
<p><a href="https://developer.mozilla.org/docs/Web/API/KeyboardEvent/which" rel="nofollow noreferrer">KeyboardEvent.which</a> has been deprecated. Please look for alternatives, such as <a href="https://developer.mozilla.org/docs/Web/API/KeyboardEvent/key" rel="nofollow noreferrer">KeyboardEvent.key</a>. Read the full API <a href="https://developer.mozilla.org/docs/Web/API/KeyboardEvent" rel="nofollow noreferrer">here</a>.</p>
|
3,068,929 |
How to read file contents into a variable in a batch file?
|
<p>This batch file releases a build from TEST to LIVE. I want to add a check constraint in this file that ensures there is an accomanying release document in a specific folder.</p>
<pre><code>"C:\Program Files\Windows Resource Kits\Tools\robocopy.exe" "\\testserver\testapp$"
"\\liveserver\liveapp$" *.* /E /XA:H /PURGE /XO /XD ".svn" /NDL /NC /NS /NP
del "\\liveserver\liveapp$\web.config"
ren "\\liveserver\liveapp$\web.live.config" web.config
</code></pre>
<p>So I have a couple of questions about how to achieve this...</p>
<ol>
<li><p>There is a <code>version.txt</code> file in the <code>\\testserver\testapp$</code> folder, and the only contents of this file is the build number (for example, 45 - for build 45)
How do I read the contents of the <code>version.txt</code> file into a variable in the batch file?</p></li>
<li><p>How do I check if a file ,<code>\\fileserver\myapp\releasedocs\ {build}.doc</code>, exists using the variable from part 1 in place of {build}?</p></li>
</ol>
| 3,069,068 | 4 | 0 | null |
2010-06-18 10:45:21.72 UTC
| 51 |
2021-09-20 15:25:34.467 UTC
|
2019-03-01 00:23:29.997 UTC
| null | 6,389,010 | null | 190,578 | null | 1 | 203 |
batch-file
| 517,559 |
<p>Read file contents into a variable:</p>
<pre><code>for /f "delims=" %%x in (version.txt) do set Build=%%x
</code></pre>
<p>or</p>
<pre><code>set /p Build=<version.txt
</code></pre>
<p>Both will act the same with only a single line in the file, for more lines the <code>for</code> variant will put the <em>last</em> line into the variable, while <code>set /p</code> will use the <em>first.</em></p>
<p>Using the variable – just like any other environment variable – it is one, after all:</p>
<pre><code>%Build%
</code></pre>
<p>So to check for existence:</p>
<pre><code>if exist \\fileserver\myapp\releasedocs\%Build%.doc ...
</code></pre>
<p>Although it may well be that no UNC paths are allowed there. Can't test this right now but keep this in mind.</p>
|
46,265,835 |
How to debug a Python module run with python -m from the command line?
|
<p>I know that a Python script can be debugged from the command line with</p>
<pre><code>python -m pdb my_script.py
</code></pre>
<p>if <code>my_script.py</code> is a script intended to be run with <code>python my_script.py</code>.</p>
<p>However, a python module <code>my_module.py</code> should be run with <code>python -m my_module</code>. Even scripts that contain relative imports should be run with <code>python -m</code>. How can I run <code>python -m my_module</code> under <code>pdb</code>'s control? The following <strong>does not work</strong>:</p>
<pre><code>python -m pdb -m my_module
</code></pre>
| 48,213,473 | 6 | 0 | null |
2017-09-17 15:37:15.433 UTC
| 4 |
2019-11-19 13:22:06.583 UTC
|
2018-11-06 15:25:54.273 UTC
| null | 895,245 | null | 898,649 | null | 1 | 34 |
python|debugging|python-module|pdb
| 31,646 |
<p>You can't do it now, because <code>-m</code> terminates option list</p>
<pre><code>python -h
...
-m mod : run library module as a script (terminates option list)
...
</code></pre>
<p>That means it's <strong>mod's</strong> job to interpret the rest of the arguments list and this behavior fully depends on how <strong>mod</strong> is designed internally and whether it support another <strong>-m</strong></p>
<p>Lets check out what's happening inside <a href="https://github.com/python/cpython/blob/2.7/Lib/pdb.py#L1314" rel="noreferrer">pdb</a> of <strong>python 2.x</strong>. Actually, nothing intereseting, it only expects a script name to be supplied:</p>
<pre><code> if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
print "usage: pdb.py scriptfile [arg] ..."
sys.exit(2)
mainpyfile = sys.argv[1] # Get script filename
if not os.path.exists(mainpyfile):
print 'Error:', mainpyfile, 'does not exist'
sys.exit(1)
del sys.argv[0] # Hide "pdb.py" from argument list
# Replace pdb's dir with script's dir in front of module search path.
sys.path[0] = os.path.dirname(mainpyfile)
# Note on saving/restoring sys.argv: it's a good idea when sys.argv was
# modified by the script being debugged. It's a bad idea when it was
# changed by the user from the command line. There is a "restart" command
# which allows explicit specification of command line arguments.
pdb = Pdb()
while True:
try:
pdb._runscript(mainpyfile)
</code></pre>
<p>Same for the currently released versions of <strong><a href="https://github.com/python/cpython/blob/3.6/Lib/pdb.py#L1667" rel="noreferrer">python 3.x</a></strong></p>
<h2>Good news</h2>
<p>The pull request that allows to do what you're asking has been <a href="https://github.com/python/cpython/pull/4752" rel="noreferrer">merged</a> 5 days ago. What a mysterious coincidence! Here's the <a href="https://github.com/python/cpython/blob/master/Lib/pdb.py#L1693" rel="noreferrer">code</a></p>
<p>So just wait a bit for the upcoming python 3.x versions to have this issue resolved )</p>
|
36,419,054 |
Go project's main goroutine sleep forever?
|
<p>Is there any API to let the <code>main</code> goroutine sleep forever? </p>
<p>In other words, I want my project always run except when I stop it.</p>
| 36,419,222 | 3 | 0 | null |
2016-04-05 06:48:58.083 UTC
| 8 |
2020-11-25 08:43:43.207 UTC
|
2016-04-06 16:20:03.05 UTC
| null | 102,371 | null | 5,324,031 | null | 1 | 32 |
go|blocking|goroutine
| 12,474 |
<h3>"Sleeping"</h3>
<p>You can use numerous constructs that block forever without "eating" up your CPU.</p>
<p>For example a <code>select</code> without any <code>case</code> (and no <code>default</code>):</p>
<pre><code>select{}
</code></pre>
<p>Or receiving from a channel where nobody sends anything:</p>
<pre><code><-make(chan int)
</code></pre>
<p>Or receiving from a <code>nil</code> channel also blocks forever:</p>
<pre><code><-(chan int)(nil)
</code></pre>
<p>Or sending on a <code>nil</code> channel also blocks forever:</p>
<pre><code>(chan int)(nil) <- 0
</code></pre>
<p>Or locking an already locked <code>sync.Mutex</code>:</p>
<pre><code>mu := sync.Mutex{}
mu.Lock()
mu.Lock()
</code></pre>
<h3>Quitting</h3>
<p>If you do want to provide a way to quit, a simple channel can do it. Provide a <code>quit</code> channel, and receive from it. When you want to quit, close the <code>quit</code> channel as "a receive operation on a closed channel can always proceed immediately, yielding the element type's <a href="https://golang.org/ref/spec#The_zero_value" rel="noreferrer">zero value</a> after any previously sent values have been received".</p>
<pre><code>var quit = make(chan struct{})
func main() {
// Startup code...
// Then blocking (waiting for quit signal):
<-quit
}
// And in another goroutine if you want to quit:
close(quit)
</code></pre>
<p>Note that issuing a <code>close(quit)</code> may terminate your app at any time. Quoting from <a href="https://golang.org/ref/spec#Program_execution" rel="noreferrer">Spec: Program execution:</a></p>
<blockquote>
<p>Program execution begins by initializing the main package and then invoking the function <code>main</code>. When that function invocation returns, the program exits. <strong>It does not wait for other (non-<code>main</code>) goroutines to complete.</strong></p>
</blockquote>
<p>When <code>close(quit)</code> is executed, the last statement of our <code>main()</code> function can proceed which means the <code>main</code> goroutine can return, so the program exits.</p>
<h2>Sleeping without blocking</h2>
<p>The above constructs block the goroutine, so if you don't have other goroutines running, that will cause a deadlock.</p>
<p>If you don't want to block the <code>main</code> goroutine but you just don't want it to end, you may use a <a href="https://golang.org/pkg/time/#Sleep" rel="noreferrer"><code>time.Sleep()</code></a> with a sufficiently large duration. The max duration value is</p>
<pre><code>const maxDuration time.Duration = 1<<63 - 1
</code></pre>
<p>which is approximately 292 years.</p>
<pre><code>time.Sleep(time.Duration(1<<63 - 1))
</code></pre>
<p>If you fear your app will run longer than 292 years, put the above sleep in an endless loop:</p>
<pre><code>for {
time.Sleep(time.Duration(1<<63 - 1))
}
</code></pre>
|
37,262,468 |
Static initialisation block in Kotlin
|
<p>What is the equivalent of a <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html" rel="noreferrer">static initialisation block</a> in Kotlin?</p>
<p>I understand that Kotlin is designed to not have static things. I am looking for something with equivalent semantics - code is run once when the class is first loaded.</p>
<p>My specific use case is that I want to enable the DayNight feature from Android AppCompat library and <a href="https://medium.com/@chrisbanes/appcompat-v23-2-daynight-d10f90c83e94#.4yv9vdlav" rel="noreferrer">the instructions</a> say to put some code in static initialisation block of <code>Application</code> class.</p>
| 37,262,603 | 2 | 1 | null |
2016-05-16 20:11:30.413 UTC
| 8 |
2021-06-11 09:25:02.317 UTC
|
2018-03-06 10:36:14.633 UTC
| null | 1,402,641 | null | 1,402,641 | null | 1 | 94 |
java|static|kotlin|initializer
| 21,531 |
<p>From some point of view, <a href="https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects" rel="noreferrer"><code>companion object</code>s</a> in Kotlin are equivalent to static parts of Java classes. Particularly, they are initialized before class' first usage, and this lets you use their <code>init</code> blocks as a replacement for Java static initializers:</p>
<pre><code>class C {
companion object {
init {
//here goes static initializer code
}
}
}
</code></pre>
<p>@voddan it's not an overkill, actually this is what suggested on the site of Kotlin: "A companion object is initialized when the corresponding class is loaded (resolved), matching the semantics of a Java static initializer." <a href="https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects" rel="noreferrer">Semantic difference between object expressions and declarations</a></p>
|
49,007,179 |
How make select2 readonly?
|
<p>I know that "readonly" feature does not exist for select2. Please check <a href="https://github.com/select2/select2/issues/3387" rel="noreferrer">here</a>.
How do I achieve that?
Any help would be appreciated.
Thanks.
Note: I cant use disabled. If I use disabled, I will not get the list of selected value.</p>
| 53,538,617 | 7 | 1 | null |
2018-02-27 11:05:40.483 UTC
| 1 |
2022-09-14 13:49:23.083 UTC
|
2018-02-27 13:07:33.017 UTC
| null | 7,300,810 | null | 7,300,810 | null | 1 | 5 |
html|jquery-select2|readonly
| 43,319 |
<p>I guess that issue is resolved or may be available for higher version as this worked for me.</p>
<p>Please go through the example to make a select2 readonly here: <a href="http://select2.github.io/select2/" rel="noreferrer">Select 2</a> </p>
<p>In js code:</p>
<pre><code>$("select").select2("readonly", true);
</code></pre>
<p>You can put your own CSS like:</p>
<pre><code>.select2-container.select2-container-disabled .select2-choice {
background-color: #ddd;
border-color: #a8a8a8;
}
</code></pre>
|
1,083,774 |
Getting the name of the controller and action method in the view in ASP.Net MVC
|
<p>Is there a way in a view in ASP.Net MVC to get the names of the controller and actien method that are using the view?</p>
| 1,083,781 | 2 | 0 | null |
2009-07-05 09:54:25.86 UTC
| 8 |
2011-10-12 14:26:01.21 UTC
| null | null | null | null | 6,068 | null | 1 | 33 |
asp.net-mvc
| 3,775 |
<p>Try this:</p>
<pre><code><%= ViewContext.RouteData.Values["Controller"] %>
<%= ViewContext.RouteData.Values["Action"] %>
</code></pre>
|
2,555,284 |
Java Priority Queue with a custom anonymous comparator
|
<p>Forgive me if this is a tried question, but I'm having a little difficulty figuring it out.</p>
<p>I currently have a class Node, and each 'node' is a square in a maze. I'm trying to implement the A* algorithm, so each of these nodes will have an f-cost (int) data member inside of it. I was wondering if there's a way that I can create a priority queue of these nodes, and set up the f-cost variable as the comparator?</p>
<p>I've looked at examples online, but all I can find are String priority queues. Can I implement Comparator for the Node class? Would this allow me to access the data member stored inside it?</p>
<p>Many Thanks!</p>
| 2,555,325 | 5 | 0 | null |
2010-03-31 18:03:26.947 UTC
| 5 |
2019-10-18 19:33:50.217 UTC
|
2017-08-11 11:07:47.73 UTC
| null | 247,708 | null | 247,708 | null | 1 | 15 |
java|priority-queue
| 48,881 |
<p>Absolutely.</p>
<p>You can use a <code>PriorityQueue</code> based on an anonymous <code>Comparator</code> passed to the constructor:</p>
<pre><code>int initCapacity = 10;
PriorityQueue<Node> pq = new PriorityQueue<Node>(initCapacity, new Comparator<Node>() {
public int compare(Node n1, Node n2) {
// compare n1 and n2
}
});
// use pq as you would use any PriorityQueue
</code></pre>
<p>If your <code>Node</code> class already implements <code>Comparable</code> you don't even need to define a new <code>Comparator</code>, as that order will be used by default. Barring any other method, the natural ordering between objects will be used.</p>
|
2,720,770 |
How to create small SPACES in HTML?
|
<p>There is em dash and en dash. Is there an "en" equivalent to <em>&nbsp;</em> ? Is there an <em>en</em> equivalent to pure <em>Ascii 32</em>?</p>
<p>I want a better way to write this:</p>
<pre><code>123<span class="spanen">&nbsp;</span>456<span class="spanen">&nbsp;</span>789
</code></pre>
<p>or this:</p>
<pre><code>123<span class="spanen"> </span>456<span class="spanen"> </span>789
</code></pre>
| 2,720,847 | 5 | 1 | null |
2010-04-27 11:39:03.7 UTC
| 11 |
2020-02-28 17:05:16.047 UTC
| null | null | null | null | 89,021 | null | 1 | 36 |
html|layout|typography
| 42,873 |
<p>Don't use hacks that make no sense. If you wish to separate some words, I suggest you use the CSS property <a href="http://www.htmldog.com/reference/cssproperties/word-spacing/" rel="noreferrer">word-spacing</a>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.strangeNumbers {
word-spacing: 0.5em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="strangeNumbers">123 456</span></code></pre>
</div>
</div>
</p>
|
3,201,018 |
Django internationalization language codes
|
<p>Where can I find list of languages and language_code like this.</p>
<pre><code>(Swedish,sv)
(English,en)
</code></pre>
| 3,201,048 | 5 | 0 | null |
2010-07-08 06:02:16.35 UTC
| 11 |
2018-07-04 10:35:21.49 UTC
|
2014-10-18 11:16:45.76 UTC
| null | 2,698,552 | null | 221,149 | null | 1 | 38 |
python|django|internationalization|django-views|django-i18n
| 50,079 |
<p>Wiki: </p>
<p><a href="http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes" rel="noreferrer">http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes</a></p>
|
2,993,468 |
From Now() to Current_timestamp in Postgresql
|
<p>In mysql I am able to do this:</p>
<pre><code>SELECT *
FROM table
WHERE auth_user.lastactivity > NOW() - 100
</code></pre>
<p>now in postgresql I am using this query:</p>
<pre><code>SELECT *
FROM table
WHERE auth_user.lastactivity > CURRENT_TIMESTAMP - 100
</code></pre>
<p>but I get this error:</p>
<pre><code>operator does not exist: timestamp with time zone - integer
</code></pre>
<p>How can I resolve ?</p>
| 2,993,481 | 5 | 0 | null |
2010-06-07 21:55:20.297 UTC
| 14 |
2020-09-06 22:29:27.327 UTC
|
2010-06-07 22:24:35.207 UTC
| null | 135,152 | null | 244,413 | null | 1 | 78 |
sql|datetime|postgresql
| 215,482 |
<p>Use an interval instead of an integer:</p>
<pre><code>SELECT *
FROM table
WHERE auth_user.lastactivity > CURRENT_TIMESTAMP - INTERVAL '100 days'
</code></pre>
|
2,350,489 |
How to catch segmentation fault in Linux?
|
<p>I need to catch segmentation fault in third party library cleanup operations. This happens sometimes just before my program exits, and I cannot fix the real reason of this. In Windows programming I could do this with __try - __catch. Is there cross-platform or platform-specific way to do the same? I need this in Linux, gcc.</p>
| 2,350,530 | 5 | 0 | null |
2010-02-28 08:11:50.987 UTC
| 30 |
2021-12-05 10:11:30.88 UTC
|
2014-09-20 16:13:30.25 UTC
| null | 3,151,258 | null | 279,313 | null | 1 | 102 |
c++|segmentation-fault|try-catch
| 150,333 |
<p>On Linux we can have these as exceptions, too.</p>
<p>Normally, when your program performs a segmentation fault, it is sent a <code>SIGSEGV</code> signal. You can set up your own handler for this signal and mitigate the consequences. Of course you should really be sure that you <em>can</em> recover from the situation. In your case, I think, you should debug your code instead.</p>
<p>Back to the topic. I recently encountered <a href="https://github.com/Plaristote/segvcatch" rel="noreferrer">a library</a> (<a href="http://www.visualdata.ru/ext/segvcatch-doc/" rel="noreferrer">short manual</a>) that transforms such signals to exceptions, so you can write code like this:</p>
<pre><code>try
{
*(int*) 0 = 0;
}
catch (std::exception& e)
{
std::cerr << "Exception caught : " << e.what() << std::endl;
}
</code></pre>
<p><strike>Didn't check it, though.</strike> Works on my x86-64 Gentoo box. It has a platform-specific backend (borrowed from gcc's java implementation), so it can work on many platforms. It just supports x86 and x86-64 out of the box, but you can get backends from libjava, which resides in gcc sources.</p>
|
2,616,643 |
Is there a standard cyclic iterator in C++
|
<p>Based on the following question: <a href="https://stackoverflow.com/questions/2553522/interview-question-check-if-one-string-is-a-rotation-of-other-string">Check if one string is a rotation of other string</a></p>
<p>I was thinking of making a cyclic iterator type that takes a range, and would be able to solve the above problem like so:</p>
<pre><code>std::string s1 = "abc" ;
std::string s2 = "bca" ;
std::size_t n = 2; // number of cycles
cyclic_iterator it(s2.begin(),s2.end(),n);
cyclic_iterator end;
if (std::search(it, end, s1.begin(),s1.end()) != end)
{
std::cout << "s1 is a rotation of s2" << std::endl;
}
</code></pre>
<p>My question, Is there already something like this available? I've checked Boost and STL and neither have an exact implementation. </p>
<p>I've got a simple hand-written (derived from a <code>std::forward_iterator_tag</code> specialised version of <code>std::iterator</code>) one but would rather use an already made/tested implementation.</p>
| 2,617,049 | 6 | 7 | null |
2010-04-11 09:59:40.953 UTC
| 9 |
2019-01-04 09:46:26.347 UTC
|
2017-10-18 03:09:46.827 UTC
| null | 3,745,896 | null | 313,764 | null | 1 | 27 |
c++|stl|iterator
| 21,625 |
<p>There is nothing like this in the standard. Cycles don't play well with C++ iterators because a sequence representing the entire cycle would have <code>first == last</code> and hence be the empty sequence.</p>
<p>Possibly you could introduce some state into the iterator, a Boolean flag to represent "not done yet." The flag participates in comparison. Set it <code>true</code> before iterating and to <code>false</code> upon increment/decrement.</p>
<p>But it might just be better to manually write the algorithms you need. Once you've managed to represent the whole cycle, representing an empty sequence might have become impossible.</p>
<p><strong>EDIT:</strong> Now I notice that you specified the number of cycles. That makes a big difference.</p>
<pre><code>template< class I >
class cyclic_iterator
/* : public iterator< bidirectional, yadda yadda > */ {
I it, beg, end;
int cnt;
cyclic_iterator( int c, I f, I l )
: it( f ), beg( f ), end( l ), cnt( c ) {}
public:
cyclic_iterator() : it(), beg(), end(), cnt() {}
cyclic_iterator &operator++() {
++ it;
if ( it == end ) {
++ cnt;
it = beg;
}
} // etc for --, post-operations
friend bool operator==
( cyclic_iterator const &lhs, cyclic_iterator const &rhs )
{ return lhs.it == rhs.it && lhs.cnt == rhs.cnt; } // etc for !=
friend pair< cyclic_iterator, cyclic_iterator > cycle_range
( int c, I f, I l ) {//factory function, better style outside this scope
return make_pair( cyclic_iterator( 0, f, l ),
cyclic_iterator( c, f, l ) );
}
};
</code></pre>
|
2,443,752 |
Django: Display image in admin interface
|
<p>I've defined a model which contains a link an image. Is there a way to display the image in the model items list? My model looks like this:</p>
<pre><code>class Article(models.Model):
url = models.CharField(max_length = 200, unique = True)
title = models.CharField(max_length = 500)
img = models.CharField(max_length = 100) # Contains path to image
def __unicode__(self):
return u"%s" %title
</code></pre>
<p>Is there a way to display the image together with title?</p>
| 2,444,076 | 8 | 0 | null |
2010-03-14 20:56:39.327 UTC
| 24 |
2022-07-24 05:50:15.967 UTC
|
2010-03-15 09:51:27.813 UTC
| null | 63,550 | null | 126,545 | null | 1 | 37 |
django|django-models
| 28,045 |
<p>You can create a model instance method with another name, allow HTML tags for its output and add this method as a list field. Here is an example:</p>
<p>First add a new method returning the HTML for the image inclusion:</p>
<pre><code>class Article(models.Model):
...
def admin_image(self):
return '<img src="%s"/>' % self.img
admin_image.allow_tags = True
</code></pre>
<p>Then add this method to the list:</p>
<pre><code>class ArticleAdmin(admin.ModelAdmin):
...
list_display = ('url', 'title', 'admin_image')
</code></pre>
|
2,514,172 |
Listing each branch and its last revision's date in Git
|
<p>I need to delete old and unmaintained branches from our remote repository. I'm trying to find a way with which to list the remote branches by their last modified date, and I can't.</p>
<p>Is there an easy way to list remote branches this way?</p>
| 2,514,279 | 11 | 2 | null |
2010-03-25 09:08:23.937 UTC
| 72 |
2022-08-19 17:31:54.293 UTC
|
2022-08-19 17:31:54.293 UTC
| null | 11,407,695 | null | 222,187 | null | 1 | 178 |
git|remote-branch
| 64,873 |
<p><a href="http://www.commandlinefu.com/commands/view/2345/show-git-branches-by-date-useful-for-showing-active-branches" rel="noreferrer">commandlinefu</a> has 2 interesting propositions:</p>
<pre><code>for k in $(git branch | perl -pe s/^..//); do echo -e $(git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k -- | head -n 1)\\t$k; done | sort -r
</code></pre>
<p>or:</p>
<pre><code>for k in $(git branch | sed s/^..//); do echo -e $(git log --color=always -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k --)\\t"$k";done | sort
</code></pre>
<p>That is for local branches, in a Unix syntax. Using <code>git branch -r</code>, you can similarly show remote branches:</p>
<pre><code>for k in $(git branch -r | perl -pe 's/^..(.*?)( ->.*)?$/\1/'); do echo -e $(git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k -- | head -n 1)\\t$k; done | sort -r
</code></pre>
<hr />
<p><a href="https://stackoverflow.com/users/191991/michael-forrest">Michael Forrest</a> mentions <a href="https://stackoverflow.com/questions/2514172/listing-each-branch-and-its-last-revisions-date-in-git/2514279#comment27884192_2514279">in the comments</a> that zsh requires escapes for the <code>sed</code> expression:</p>
<pre><code>for k in git branch | perl -pe s\/\^\.\.\/\/; do echo -e git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k -- | head -n 1\\t$k; done | sort -r
</code></pre>
<p><a href="https://stackoverflow.com/users/1025068/kontinuity">kontinuity</a> adds <a href="https://stackoverflow.com/questions/2514172/listing-each-branch-and-its-last-revisions-date-in-git/2514279#comment65532526_2514279">in the comments</a>:</p>
<blockquote>
<p>If you want to add it your zshrc the following escape is needed.</p>
</blockquote>
<pre><code>alias gbage='for k in $(git branch -r | perl -pe '\''s/^..(.*?)( ->.*)?$/\1/'\''); do echo -e $(git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k -- | head -n 1)\\t$k; done | sort -r'
</code></pre>
<p>In multiple lines:</p>
<pre><code>alias gbage='for k in $(git branch -r | \
perl -pe '\''s/^..(.*?)( ->.*)?$/\1/'\''); \
do echo -e $(git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k -- | \
head -n 1)\\t$k; done | sort -r'
</code></pre>
<hr />
<p>Note: <a href="https://stackoverflow.com/users/1202867/n8tr">n8tr</a>'s <a href="https://stackoverflow.com/a/23943986/6309">answer</a>, based on <a href="https://git-scm.com/docs/git-for-each-ref" rel="noreferrer"><code>git for-each-ref refs/heads</code></a> is cleaner. <a href="https://stackoverflow.com/a/41307509/6309">And faster</a>.<br />
See also "<a href="https://stackoverflow.com/a/36026316/6309">Name only option for <code>git branch --list</code>?</a>"</p>
<p>More generally, <a href="https://stackoverflow.com/users/874188/tripleee">tripleee</a> reminds us <a href="https://stackoverflow.com/questions/2514172/listing-each-branch-and-its-last-revisions-date-in-git#comment106493431_2514279">in the comments</a>:</p>
<blockquote>
<ul>
<li>Prefer modern <code>$(command substitution)</code> syntax over obsolescent backtick syntax.</li>
</ul>
</blockquote>
<p>(I illustrated that point in 2014 with "<a href="https://stackoverflow.com/a/24592916/6309">What is the difference between <code>$(command)</code> and <code>`command`</code> in shell programming?</a>")</p>
<blockquote>
<ul>
<li><a href="https://mywiki.wooledge.org/DontReadLinesWithFor" rel="noreferrer">Don't read lines with <code>for</code></a>.</li>
<li>Probably switch to <code>git for-each-ref refs/remote</code> to get remote branch names in machine-readable format</li>
</ul>
</blockquote>
|
3,107,765 |
How to ignore the case sensitivity in List<string>
|
<p>Let us say I have this code</p>
<pre><code>string seachKeyword = "";
List<string> sl = new List<string>();
sl.Add("store");
sl.Add("State");
sl.Add("STAMP");
sl.Add("Crawl");
sl.Add("Crow");
List<string> searchResults = sl.FindAll(s => s.Contains(seachKeyword));
</code></pre>
<p>How can I ignore the letter case in Contains search?</p>
<p>Thanks,</p>
| 3,107,816 | 12 | 0 | null |
2010-06-24 06:49:33.067 UTC
| 4 |
2021-08-29 12:29:19.913 UTC
| null | null | null | null | 374,958 | null | 1 | 67 |
c#
| 78,239 |
<p>The best option would be using the ordinal case-insensitive comparison, however the <code>Contains</code> method does not support it.</p>
<p>You can use the following to do this:</p>
<pre><code>sl.FindAll(s => s.IndexOf(searchKeyword, StringComparison.OrdinalIgnoreCase) >= 0);
</code></pre>
<p>It would be better to wrap this in an extension method, such as:</p>
<pre><code>public static bool Contains(this string target, string value, StringComparison comparison)
{
return target.IndexOf(value, comparison) >= 0;
}
</code></pre>
<p>So you could use:</p>
<pre><code>sl.FindAll(s => s.Contains(searchKeyword, StringComparison.OrdinalIgnoreCase));
</code></pre>
|
2,393,156 |
Does C# support the use of static local variables?
|
<blockquote>
<p>Related: <a href="https://stackoverflow.com/questions/2079830/how-do-i-create-a-static-local-variable-in-java">How do I create a static local variable in Java?</a> </p>
</blockquote>
<hr>
<p>Pardon if this is a duplicate; I was pretty sure this would have been asked previously, and I looked but didn't find a dupe. </p>
<p>Is it possible for me to create a static local variable in C#? If so, how?</p>
<p>I have a static private method that is used rarely. the static method uses a Regular Expression, which I would like to initialize <em>once</em>, and only when necessary. </p>
<p>In C, I could do this with a local static variable. Can I do this in C#? </p>
<p>When I try to compile this code:</p>
<pre><code> private static string AppendCopyToFileName(string f)
{
static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
}
</code></pre>
<p>...it gives me an error: </p>
<blockquote>
<p>error CS0106: The modifier 'static' is not valid for this item</p>
</blockquote>
<hr>
<p>If there's no local static variable, I suppose I could approximate what I want by creating a tiny new private static class, and inserting both the method and the variable (field) into the class. Like this: </p>
<pre><code>public class MyClass
{
...
private static class Helper
{
private static readonly System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
internal static string AppendCopyToFileName(string f)
{
// use re here...
}
}
// example of using the helper
private static void Foo()
{
if (File.Exists(name))
{
// helper gets JIT'd first time through this code
string newName = Helper.AppendCopyToFileName(name);
}
}
...
}
</code></pre>
<p>Thinking about this more, using a helper class like this there would yield a bigger net savings in efficiency, because the Helper class would not be JIT'd or loaded unless necessary. Right?</p>
| 2,393,230 | 14 | 3 | null |
2010-03-06 16:20:03.133 UTC
| 6 |
2022-01-16 18:36:59.483 UTC
|
2017-05-23 12:25:19.71 UTC
| null | -1 | null | 48,082 | null | 1 | 30 |
c#|static
| 23,477 |
<p>No, C# does not support this. You can come close with:</p>
<pre><code>private static System.Text.RegularExpressions.Regex re =
new System.Text.RegularExpressions.Regex("\\(copy (\\d+)\\)$");
private static string AppendCopyToFileName(string f)
{
}
</code></pre>
<p>The only difference here is the visibility of 're'. It is exposed to the classm not just to the method. </p>
<p>The <code>re</code> variable will be initialized the first time the containing class is used in some way. So keep this in a specialized small class. </p>
|
3,105,296 |
If REST applications are supposed to be stateless, how do you manage sessions?
|
<p>I'm in need of some clarification. I've been reading about REST, and building RESTful applications. According to wikipedia, REST itself is defined to be <em>Representational State Transfer</em>. I therefore don't understand all this stateless <em>gobbledeygook</em> that everyone keeps spewing.</p>
<p>From wikipedia:</p>
<blockquote>
<p>At any particular time, a client can either be in transition between
application states or "at rest". A client in a rest state is able to
interact with its user, but creates no load and consumes no per-client
storage on the set of servers or on the network.</p>
</blockquote>
<p>Are they just saying don't use session/application level data store???</p>
<p>I get that one goal of REST is to make URI access consistent and available, for instance, instead of hiding paging requests inside posts, making the page number of a request a part of the GET URI. Makes sense to me. But it seems like it is just going overboard saying that <em>no per client data</em> (session data) should ever be stored server side.</p>
<p>What if I had a queue of messages, and my user wanted to read the messages, but as he read them, wanted to block certain senders messages coming through for the duration of his session? Wouldn't it make sense to store this in a place on the server side, and have the server only send messages (or message ID's) that were not blocked by the user?</p>
<p>Do I really have to send the entire list of message senders to block each time I request the new message list? The message list pertinent to me wouldn't/shouldn't even be a publicly available resource in the first place..</p>
<p>Again, just trying to understand this. Someone <em>please</em> clarify.</p>
<hr />
<p><strong>Update:</strong></p>
<p>I have found a stack overflow question that has an answer that doesn't quite get me all the way there:
<a href="https://stackoverflow.com/questions/2641901/how-to-manage-state-in-rest">How to manage state in REST</a>
which says that the client state that is important <em>should</em> all be transferred on every request.... Ugg.. seems like a lot of overhead... Is this right??</p>
| 3,105,337 | 15 | 5 | null |
2010-06-23 20:30:57.247 UTC
| 402 |
2022-03-16 21:46:18.81 UTC
|
2020-08-05 21:52:08.26 UTC
| null | 2,112,692 | null | 2,112,692 | null | 1 | 610 |
rest|session-state
| 322,155 |
<h3>The fundamental explanation is:</h3>
<blockquote>
<p>No client session state on the server.</p>
</blockquote>
<p>By stateless it means that the <strong>server</strong> does not store any state about the <strong>client session</strong> on the server side.</p>
<p>The <em>client session</em> is stored on the client. The server is stateless means that every server can service any client at any time, there is no <em>session affinity</em> or <em>sticky sessions</em>. The relevant session information is stored on the client and passed to the server as needed.</p>
<p>That does not preclude other services that the web server talks to from maintaining state about business objects such as shopping carts, just not about the client's current application/session state.</p>
<p>The <strong>client's</strong> application state should never be stored on the server, but passed around from the <strong>client</strong> to every place that needs it.</p>
<p>That is where the <em>ST</em> in <em>REST</em> comes from, <em>State Transfer</em>. You transfer the state around instead of having the server store it. <strong>This is the only way to scale to millions of concurrent users.</strong> If for no other reason than because millions of sessions is millions of sessions.</p>
<p>The load of session management is amortized across all the clients, the clients store their session state and the servers can service many orders of magnitude or more clients in a stateless fashion.</p>
<p>Even for a service that you think will <em>only</em> need in the 10's of thousands of concurrent users, you still should make your service stateless. Tens of thousands is still tens of thousands and there will be time and space cost associated with it.</p>
<p>Stateless is how the HTTP protocol and the web in general was designed to operate and is an overall simpler implementation and you have a single code path instead of a bunch of server side logic to maintain a bunch of session state.</p>
<h3>There are some very basic implementation principles:</h3>
<p>These are principles not implementations, how you meet these principles may vary.</p>
<p>In summary, the <a href="https://www.infoq.com/articles/rest-introduction" rel="noreferrer">five key principles</a> are:</p>
<ol>
<li>Give every “thing” an ID</li>
<li>Link things together</li>
<li>Use standard methods</li>
<li>Resources with multiple representations</li>
<li>Communicate statelessly</li>
</ol>
<h3>There is nothing about authentication or authorization in the REST <a href="https://www.ics.uci.edu/%7Efielding/pubs/dissertation/rest_arch_style.htm" rel="noreferrer">dissertation</a>.</h3>
<p>Because there is nothing different from authenticating a request that is RESTful from one that is not. Authentication is irrelevant to the RESTful discussion.</p>
<p>Explaining how to create a stateless application for your particular requirements, is <em>too-broad</em> for StackOverflow.</p>
<p>Implementing Authentication and Authorization as it pertains to REST is even more so <em>too-broad</em> and various approaches to implementations are explained in great detail on the internet in general.</p>
<blockquote>
<p><strong>Comments asking for help/info on this will/should just be flagged as
<em>No Longer Needed</em></strong>.</p>
</blockquote>
|
3,182,393 |
Android textview outline text
|
<p>Is there a simple way to have text be able to have a black outline? I have textviews that will be different colors, but some of the colors don't show up on my background so well, so I was wondering if there's an easy way to get a black outline or something else that will do the job? I'd prefer not to have to create a custom view and make a canvas and such.</p>
| 3,196,036 | 16 | 2 | null |
2010-07-05 22:03:38.073 UTC
| 36 |
2022-05-15 10:51:20.607 UTC
| null | null | null | null | 375,874 | null | 1 | 97 |
android|colors|textview
| 156,004 |
<p>You can put a shadow behind the text, which can often help readability. Try experimenting with 50% translucent black shadows on your green text. Details on how to do this are over here: <a href="https://stackoverflow.com/questions/2486936/android-shadow-on-text">Android - shadow on text?</a></p>
<p>To really add a stroke around the text, you need to do something a bit more involved, like this:
<a href="https://stackoverflow.com/questions/1723846/how-do-you-draw-text-with-a-border-on-a-mapview-in-android">How do you draw text with a border on a MapView in Android?</a></p>
|
33,781,818 |
Multiple catch in javascript
|
<p>Is it possible to use multiple catch in J<code>S(ES5 or ES6)</code> like I describe below (it is only example):</p>
<pre><code>try {
// just an error
throw 1;
}
catch(e if e instanceof ReferenceError) {
// here i would like to manage errors which is 'undefined' type
}
catch(e if typeof e === "string") {
// here i can manage all string exeptions
}
// and so on and so on
catch(e) {
// and finally here i can manage another exeptions
}
finally {
// and a simple finally block
}
</code></pre>
<p>This is the same as we have in <code>C#</code> or in a <code>Java</code>.</p>
<p>Thanks in advance!</p>
| 33,781,851 | 4 | 2 | null |
2015-11-18 13:51:45.953 UTC
| 4 |
2018-12-30 04:53:30.593 UTC
|
2015-11-18 14:16:26.917 UTC
| null | 2,168,733 |
user5548116
| null | null | 1 | 35 |
javascript
| 36,145 |
<p>No. That does not exist in JavaScript or EcmaScript.</p>
<p>You can accomplish the same thing with an <code>if[...else if]...else</code> inside of the <code>catch</code>.</p>
<p>There are some non-standard implementations (and are not on any standard track) that <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#Conditional_catch_clauses" rel="noreferrer">do have it according to MDN</a>.</p>
|
50,844,087 |
What's the difference among "git fetch && git checkout" versus "git checkout" only?
|
<p>Should do we always do as: </p>
<pre><code>git fetch && git checkout
</code></pre>
<p>Or only, </p>
<pre><code>git checkout
</code></pre>
<p>?</p>
<p>For example when doing a checkout from a branch in bitbucket they provide the command as: </p>
<p><a href="https://i.stack.imgur.com/zUmsV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zUmsV.png" alt="enter image description here"></a></p>
<pre><code>git fetch && git checkout develop
</code></pre>
<p>But why is this necessary if </p>
<blockquote>
<p>git checkout</p>
</blockquote>
<p>will do the same, isn't it? </p>
| 50,991,451 | 6 | 0 | null |
2018-06-13 18:37:33.517 UTC
| 5 |
2020-04-24 13:22:50.65 UTC
|
2020-04-22 15:59:56.027 UTC
| null | 1,792,086 | null | 1,792,086 | null | 1 | 27 |
git|git-checkout|git-fetch
| 42,983 |
<p>To chime in here since I have to use Bitbucket daily for multiple projects and multiple branches I will give you my recommendation. </p>
<p>If you checkout from Bitbucket, i.e. create a branch, then you should be ok using the commands that they have provided as you pasted in your example. However, since it is likely that after the initial checkout you will be switching branches, creating branches and your local will get out of sync I recommend the following using your terminal. :</p>
<ol>
<li><code>git checkout develop</code> or whatever branch you need</li>
<li><code>git fetch && git pull</code> i.e. fetch all branches and latest changes as well as pull in all changes from the branch you are on. </li>
</ol>
<p>Yes this does seem like duplicate work but working with Bitbucket I will say that this is the safest and sanest way to ensure that you have the latest from the branch that you are working on. </p>
<p>That being said, you should always create branches and never push directly to your <code>develop</code> or <code>master</code> branches. </p>
<p>So let's say that you are on <code>develop</code> branch and you have done the above by checking out the branch and have fetched and pulled the latest you would then create a branch off of that main branch using standard <code>git checkout -b my-feature-branch</code></p>
<p>Example of what we do at my shop:</p>
<ol>
<li><code>git checkout develop</code> </li>
<li><code>git fetch && git pull</code></li>
<li><code>git checkout -b feature/JIRA_ISSUE_NUMBER-update-layout-for-this-page</code></li>
</ol>
<p>Now you have checked out the develop branch, pulled down all the latest changes and remote branches and created a feature branch from that develop branch. </p>
<p>Hope this helps. </p>
|
50,835,221 |
Pass command line -- argument to child script in Yarn
|
<p>I have a package.json that looks similar to this:</p>
<pre><code>"scripts": {
"dev": "cross-env BABEL_ENV=client webpack --config webpack/client.development.js && yarn dev:stub-server | cross-env BABEL_ENV=server babel-node src/server/server.js",
"dev:stub-server": "./node_modules/.bin/robohydra ./stubs/robohydra-config.json -p 3100"
}
</code></pre>
<p>I added some logic in the code to change the way the <code>dev:stub-server</code> is configured depending on a command line argument. So, whenever I run the following I get what I expect:</p>
<pre><code>yarn dev:stub-server --results=4
$ ./node_modules/.bin/robohydra ./stubs/robohydra-config.json -p 3100 -- --results=4
</code></pre>
<p>As you can see, the options are forwarded to the underlying script and everything works as expected.</p>
<p>My problem is that I cannot have the <code>--results</code> propagated from the <code>yarn dev</code> command to <code>dev:stub-server</code> in the correct position. The parent script runs <code>dev:stub-server</code> but the argument is forwarded to the underlying script at the end as follows:</p>
<pre><code>yarn dev --results=2
$ cross-env BABEL_ENV=client webpack --config webpack/client.development.js && yarn dev:stub-server | cross-env BABEL_ENV=server babel-node src/server/server.js --results=2
</code></pre>
<p>Is there a way to make the above work as follows instead?</p>
<pre><code>yarn dev --results=2
$ cross-env BABEL_ENV=client webpack --config webpack/client.development.js && yarn dev:stub-server --results=2 | cross-env BABEL_ENV=server babel-node src/server/server.js
</code></pre>
<p>Thanks in advance!</p>
| 50,862,023 | 8 | 1 | null |
2018-06-13 10:44:16.777 UTC
| 1 |
2021-05-20 16:33:14.333 UTC
|
2018-06-15 07:01:30.92 UTC
| null | 1,611,459 | null | 4,024,167 | null | 1 | 34 |
node.js|npm|package.json|yarnpkg|npm-scripts
| 47,415 |
<p><a href="https://yarnpkg.com/lang/en/docs/cli/run/" rel="noreferrer">Yarn's <code>run</code></a> only supports appending your <code>args</code> to the end of the command chain, and at least as of date 2018-06-14, there isn't a way to override that.</p>
<p>When I've needed this in the past, I've cooked up my own <code>dev.js</code> script that was called by my <code>package.json</code>, and pulled args out environment variables.</p>
|
10,575,239 |
Android BroadcastReceiver or simple callback method?
|
<p>In my projects I am using <code>BroadcastReceiver</code>s as a callback from a long running thread (eg. notify the activity that a download was finished and send some response data from a Worker <code>Thread</code> so that the activity can display the appropriate message to the user..).
To use <code>BroadcastReceiver</code>s I have to be careful to register and unregister the broadcast receiver each time I am using it and also have to care of what messages to send esspecialy when I am using this method for more different actions(like downloading, making WebService calls etc..). And also to send custom Objects through Broadcast's intent I need also to make the objects <code>Parcelable</code>. </p>
<p>Unlike this approach, I have seen also the callback methods approach which appears to be simpler than the method I use. Callback methods are simple Interface methods implementation that can be used to achieve the same effect like the BroadcastRecaiver's in app messaging.
This approach doesn't need Parcelable implementation to return complex objects and it doesn't use keys like <code>BroadcastReceiver</code>.. I think the bad part is that I need to check the callback object for null value before I want to call a callback method.. and also to make sure I am running the code from the implementation on the UI thread so I can update the UI without errors. </p>
<p>Ok, I hope you understood what I meant to say :). </p>
<p>Now the question is do you think that the callback method is better (lighter, cleaner, faster..) than the <code>BroadcastReceiver</code> approach when are used just inside of a single application? (Note that I am not using Android <code>Service</code> for background work.. just <code>AsyncTask</code> and <code>Thread</code>s)</p>
<p>Thank you! </p>
| 10,672,673 | 5 | 0 | null |
2012-05-13 21:03:30.887 UTC
| 34 |
2018-02-06 18:14:03.667 UTC
| null | null | null | null | 449,310 | null | 1 | 57 |
android|multithreading|callback|broadcastreceiver
| 16,425 |
<p>This is a very interesting question and I ran into the same problem. In my opinion both mechanisms can be used altogether and the right approach to use depends on your use case. Here are some points to be taken into account before deciding.</p>
<p>Using the callback-mechanism has some benefits, but there are also limitations:</p>
<p>PRO</p>
<ul>
<li>It is simple and straight forward to implement.</li>
<li>You get type-safety between the components that interact with each other.</li>
<li>You can return arbitrary objects.</li>
<li>It simplifies testing as you only have to inject a mock-callback (e.g. generated through mockito or something similar) in unit tests.</li>
</ul>
<p>CONTRA</p>
<ul>
<li>You have to switch to the main thread in order to do UI manipulations.</li>
<li>You can only have a 1-to-1 relationship. A 1-to-n relationship (observer pattern) is not realizable without further work. In this case I would prefer Android's <code>Observer</code> / <code>Observable</code> mechanism.</li>
<li>As you already said, you always have to check for <code>null</code> before invoking callback functions if the callback may be optional.</li>
<li>If your component should offer a kind of service API with different service functions and you do not want to have a callback interface with only a few generic callback functions, you have to decide whether you provide a special callback interface for each service function or whether you provide a single callback interface with a lot of callback functions. In the later case all callback clients used for service calls to your API have to implement the complete callback interface although the majority of the method bodies will be empty. You can work around this by implementing a stub with empty bodies and make your callback client inherit from that stub, but this is not possible if already inheriting from another base class. Maybe you can use some kind of dynamic proxy callback (see <a href="http://developer.android.com/reference/java/lang/reflect/Proxy.html" rel="noreferrer">http://developer.android.com/reference/java/lang/reflect/Proxy.html</a>), but then it gets really complex and I would think of using another mechanism.</li>
<li>The client for the callback calls has to be propagated through various methods/components if it is not directly accessible by the caller of the service.</li>
</ul>
<p>Some points regarding the <code>BroadcastReceiver</code>-approach:</p>
<p>PRO</p>
<ul>
<li>You achieve a loose coupling between your components.</li>
<li>You can have a 1-to-n relationship (including 1-to-0).</li>
<li>The <code>onReceive()</code> method is always executed on the main thread.</li>
<li>You can notify components in your entire application, so the communicating components do not have to "see" eachother.</li>
</ul>
<p>CONTRA</p>
<ul>
<li>This is a very generic approach, so marshalling and unmarshalling of data transported by the <code>Intent</code> is an additional error source.</li>
<li>You have to make your <code>Intent</code>'s actions unique (e.g. by prepending the package name) if you want to eliminate correlations with other apps, as their original purpose is to do broadcasts between applications.</li>
<li>You have to manage the <code>BroadcastReceiver</code>-registration and unregistration. If you want to do this in a more comfortable way, you can implement a custom annotation to annotate your Activity with the actions that should be registered and implement a base <code>Activity</code>class that does registration and unregistration with <code>IntentFilter</code>s in its <code>onResume()</code> resp. <code>onPause()</code>methods.</li>
<li>As you already said, the data that is sent with the <code>Intent</code> has to implement the <code>Parcelable</code> interface, but furthermore there is a strict size limitation and it will cause performance issues if you transport a large amount of data with your <code>Intent</code>. See <a href="http://code.google.com/p/android/issues/detail?id=5878" rel="noreferrer">http://code.google.com/p/android/issues/detail?id=5878</a> for a discussion on that. So if you want to send images for example you have to store them temporary in a repository and send a corresponding ID or URL to access the image from the receiver of your <code>Intent</code> that deletes it from the repository after usage. This leads to further problems if there are several receivers (when should the image be removed from the repository and who should do that?).</li>
<li>If you overuse this kind of notification mechanism the control flow of your application may get hidden and when debugging you end up drawing graphs with sequences of <code>Intent</code>s to understand what has triggered a specific error or why this notification chain is broken at some point.</li>
</ul>
<p>In my opinion, even a mobile app should have an architecture base on at least 2 layers: the UI-layer and the core layer (with business logic, etc.). In general, long running tasks are executed in an own thread (maybe via <code>AsyncTask</code> or <code>HandlerThread</code> if using <code>MessageQueue</code>s) inside the core layer and the UI should be updated once this task has been finished. In general with callbacks you achieve a tight coupling between your components, so I would prefer using this approach only within a layer and not for communication across layer boundaries. For message broadcasting between UI- and core-layer I would use the <code>BroadcastReceiver</code>-approach that lets you decouple your UI layer from the logic layer.</p>
|
10,647,558 |
When it's necessary to execute invalidate() on a View?
|
<p>My answer to <a href="https://stackoverflow.com/questions/10607821/swapping-image-in-imageview/10608396#10608396">this question</a> was just accepted but I started to wonder when exactly one needs to invalidate() a View and when it is not necessary?</p>
<p>After a bit of thinking I came to realization that it <em>should</em> work more or less like this:</p>
<ul>
<li>actual drawing of "everything" occurs after <code>onResume()</code></li>
<li>in "free" time parts of the screen can be redrawn but only those that were <code>invalidated</code> (and everything underneath)</li>
</ul>
<p>Therefore, it would seem, if I change something after <code>onResume()</code> (e.g. as a response to a button click, I should <code>invalidate()</code> the changed <code>View</code>). </p>
<p>However, from what scana in <a href="https://stackoverflow.com/questions/10607821/swapping-image-in-imageview/10608396#10608396">this question</a> says, it must be more complex then that and it depends somethimes on what method one uses.</p>
<p>E.g. on whether one uses</p>
<pre><code>lastClicked.setImageBitmap();
</code></pre>
<p>or</p>
<pre><code>lastClicked.setImageResource();
</code></pre>
<p>So, when it's necessary to execute invalidate() on a View and how does it really work ?</p>
| 10,647,842 | 4 | 0 | null |
2012-05-18 06:08:22.737 UTC
| 17 |
2019-01-24 17:12:33.113 UTC
|
2017-05-23 12:34:14.767 UTC
| null | -1 | null | 432,779 | null | 1 | 58 |
android|android-imageview|android-view
| 70,605 |
<p>Usually, the system handles resizing, hiding, showing and a ton of other things for your widgets automatically but it sometimes has issues if the underlying buffer for drawn pixels or backing data has changed or is stale (you swap the image resource on a View or the raw dataset changes). This occurs because there is no way that the OS can know that the data changed in the specific manner that it did.</p>
<p>In these cases where you are dealing with drawing, you have to tell the system that its underlying data is not in a good state with <em>Widget.invalidate()</em> and the re-drawing gets queued on the main thread just as you mentioned. Depending on the system implementation and Android version what is tracked for changes by the system varies but what I normally do is assume that system resources (byte arrays, char arrays, resource indexes, manual drawing on the context) are not tracked and need an <em>invalidate</em> and everything else will be handled by the system.</p>
|
18,637,148 |
Using app.configure in express
|
<p>I found some code where they set up Express without using <code>app.configure</code> and I was wondering, what's the difference between using <code>app.configure</code> without an environment specifier and not using it?</p>
<p>In other words, what's the difference between this:</p>
<pre><code>var app = require(express);
app.configure(function(){
app.set('port', process.env.PORT || config.port);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, 'site')));
}
</code></pre>
<p>and this:</p>
<pre><code>var app = require(express);
app.set('port', process.env.PORT || config.port);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(express.static(path.join(__dirname, 'site')));
</code></pre>
<p>Thanks.</p>
| 18,637,317 | 1 | 3 | null |
2013-09-05 13:03:47.153 UTC
| 15 |
2015-09-29 08:36:55.633 UTC
| null | null | null | null | 2,319,804 | null | 1 | 123 |
node.js|express
| 81,530 |
<p>It is optional and remain for legacy reason, according to the doc.
In your example, the two piece of codes have no difference at all.
<a href="http://expressjs.com/api.html#app.configure" rel="noreferrer">http://expressjs.com/api.html#app.configure</a></p>
<p><strong>Update 2015:</strong></p>
<p>@IlanFrumer points out that app.configure is removed in Express 4.x. If you followed some outdated tutorials and wondering why it didn't work, You should remove <code>app.configure(function(){ ... }</code>. Like this:</p>
<pre><code>var express = require('express');
var app = express();
app.use(...);
app.use(...);
app.get('/', function (req, res) {
...
});
</code></pre>
|
33,265,663 |
api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file
|
<p>I am facing this .dll library missing error:</p>
<blockquote>
<p>This programme can't start because api-ms-win-crt-runtime-l1-1-0.dll
is missing. Try to reinstall this.</p>
</blockquote>
<p>When I try to open an Microsoft Office file.</p>
<p>How do I solve that?</p>
| 33,274,879 | 8 | 0 | null |
2015-10-21 17:30:41.643 UTC
| 44 |
2019-08-15 09:31:58.213 UTC
|
2016-11-03 20:23:20.09 UTC
| null | 63,550 | null | 5,472,671 | null | 1 | 162 |
crt
| 1,120,913 |
<p>The default solution is to install <a href="https://support.microsoft.com/en-us/kb/2999226" rel="noreferrer">KB2999226</a> of Microsoft.</p>
|
31,270,759 |
A better approach to handling exceptions in a functional way
|
<p>Exceptions, especially checked ones, can severely interrupt the flow of program logic when the FP idiom is used in Java 8. Here is an arbitrary example:</p>
<pre><code>String s1 = "oeu", s2 = "2";
Stream.of(s1, s2).forEach(s ->
System.out.println(Optional.of(s).map(Integer::parseInt).get()));
</code></pre>
<p>The above code breaks when there's an exception for an unparseable string. But say I just want to replace that with a default value, much like I can with <code>Optional</code>:</p>
<pre><code>Stream.of(s1, s2).forEach(s ->
System.out.println(Optional.of(s)
.map(Integer::parseInt)
.orElse(-1)));
</code></pre>
<p>Of course, this still fails because <code>Optional</code> only handles <code>null</code>s. I would like something as follows:</p>
<pre><code>Stream.of(s1, s2).forEach(s ->
System.out.println(
Exceptional.of(s)
.map(Integer::parseInt)
.handle(NumberFormatException.class, swallow())
.orElse(-1)));
</code></pre>
<hr>
<p><strong>Note:</strong> this is a self-answered question.</p>
| 31,270,760 | 4 | 2 | null |
2015-07-07 14:01:41.997 UTC
| 41 |
2021-12-27 13:44:45.157 UTC
|
2015-07-08 08:17:49.273 UTC
| null | 1,103,872 | null | 1,103,872 | null | 1 | 60 |
java|java-8|java-stream
| 12,327 |
<p>Presented below is the full code of the <code>Exceptional</code> class. It has a quite large API which is a pure extension of the <code>Optional</code> API so it can be a drop-in replacement for it in any existing code—except that it isn't a subtype of the final <code>Optional</code> class. The class can be seen as being in the same relationship with the <a href="http://mauricio.github.io/2014/02/17/scala-either-try-and-the-m-word.html" rel="noreferrer"><code>Try</code></a> monad as <code>Optional</code> is with the <code>Maybe</code> monad: it draws inspiration from it, but is adapted to the Java idiom (such as actually throwing exceptions, even from non-terminal operations).</p>
<p>These are some key guidelines followed by the class:</p>
<ul>
<li><p>as opposed to the monadic approach, doesn't ignore Java's exception mechanism; </p></li>
<li><p>instead it relieves the impedance mismatch between exceptions and higher-order functions;</p></li>
<li><p>exception handling not statically typesafe (due to sneaky throwing), but always safe at runtime (never swallows an exception except on explicit request).</p></li>
</ul>
<p>The class tries to cover all the typical ways to handle an exception:</p>
<ul>
<li><code>recover</code> with some handling code which provides a substitute value;</li>
<li><code>flatRecover</code> which, analogous to <code>flatMap</code>, allows to return a new <code>Exceptional</code> instance which will be unwrapped and the state of the current instance suitably updated;</li>
<li><code>propagate</code> an exception, throwing it from the <code>Exceptional</code> expression and making the <code>propagate</code> call declare this exception type;</li>
<li><code>propagate</code> it after wrapping into another exception (<em>translate</em> it);</li>
<li><code>handle</code> it, resulting in an empty <code>Exceptional</code>;</li>
<li>as a special case of handling, <code>swallow</code> it with an empty handler block.</li>
</ul>
<p>The <code>propagate</code> approach allows one to selectively pick which checked exceptions he wants to expose from his code. Exceptions which remain unhandled at the time a terminal operation is called (like <code>get</code>) will be <em>sneakily</em> thrown without declaration. This is often considered as an advanced and dangerous approach, but is nevertheless often employed as a way to somewhat alleviate the nuisance of checked exceptions in combination with lambda shapes which do not declare them. The <code>Exceptional</code> class hopes to offer a cleaner and more selective alternative to sneaky throw.</p>
<hr>
<pre><code>/*
* Copyright (c) 2015, Marko Topolnik. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public final class Exceptional<T>
{
private final T value;
private final Throwable exception;
private Exceptional(T value, Throwable exc) {
this.value = value;
this.exception = exc;
}
public static <T> Exceptional<T> empty() {
return new Exceptional<>(null, null);
}
public static <T> Exceptional<T> ofNullable(T value) {
return value != null ? of(value) : empty();
}
public static <T> Exceptional<T> of(T value) {
return new Exceptional<>(Objects.requireNonNull(value), null);
}
public static <T> Exceptional<T> ofNullableException(Throwable exception) {
return exception != null? new Exceptional<>(null, exception) : empty();
}
public static <T> Exceptional<T> ofException(Throwable exception) {
return new Exceptional<>(null, Objects.requireNonNull(exception));
}
public static <T> Exceptional<T> from(TrySupplier<T> supplier) {
try {
return ofNullable(supplier.tryGet());
} catch (Throwable t) {
return new Exceptional<>(null, t);
}
}
public static Exceptional<Void> fromVoid(TryRunnable task) {
try {
task.run();
return new Exceptional<>(null, null);
} catch (Throwable t) {
return new Exceptional<>(null, t);
}
}
public static <E extends Throwable> Consumer<? super E> swallow() {
return e -> {};
}
public T get() {
if (value != null) return value;
if (exception != null) sneakyThrow(exception);
throw new NoSuchElementException("No value present");
}
public T orElse(T other) {
if (value != null) return value;
if (exception != null) sneakyThrow(exception);
return other;
}
public T orElseGet(Supplier<? extends T> other) {
if (value != null) return value;
if (exception != null) sneakyThrow(exception);
return other.get();
}
public Stream<T> stream() {
return value == null ? Stream.empty() : Stream.of(value);
}
public<U> Exceptional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (value == null) return new Exceptional<>(null, exception);
final U u;
try {
u = mapper.apply(value);
} catch (Throwable exc) {
return new Exceptional<>(null, exc);
}
return ofNullable(u);
}
public<U> Exceptional<U> flatMap(Function<? super T, Exceptional<U>> mapper) {
Objects.requireNonNull(mapper);
return value != null ? Objects.requireNonNull(mapper.apply(value)) : empty();
}
public Exceptional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (value == null) return this;
final boolean b;
try {
b = predicate.test(value);
} catch (Throwable t) {
return ofException(t);
}
return b ? this : empty();
}
public <X extends Throwable> Exceptional<T> recover(
Class<? extends X> excType, Function<? super X, T> mapper)
{
Objects.requireNonNull(mapper);
return excType.isInstance(exception) ? ofNullable(mapper.apply(excType.cast(exception))) : this;
}
public <X extends Throwable> Exceptional<T> recover(
Iterable<Class<? extends X>> excTypes, Function<? super X, T> mapper)
{
Objects.requireNonNull(mapper);
for (Class<? extends X> excType : excTypes)
if (excType.isInstance(exception))
return ofNullable(mapper.apply(excType.cast(exception)));
return this;
}
public <X extends Throwable> Exceptional<T> flatRecover(
Class<? extends X> excType, Function<? super X, Exceptional<T>> mapper)
{
Objects.requireNonNull(mapper);
return excType.isInstance(exception) ? Objects.requireNonNull(mapper.apply(excType.cast(exception))) : this;
}
public <X extends Throwable> Exceptional<T> flatRecover(
Iterable<Class<? extends X>> excTypes, Function<? super X, Exceptional<T>> mapper)
{
Objects.requireNonNull(mapper);
for (Class<? extends X> c : excTypes)
if (c.isInstance(exception))
return Objects.requireNonNull(mapper.apply(c.cast(exception)));
return this;
}
public <E extends Throwable> Exceptional<T> propagate(Class<E> excType) throws E {
if (excType.isInstance(exception))
throw excType.cast(exception);
return this;
}
public <E extends Throwable> Exceptional<T> propagate(Iterable<Class<? extends E>> excTypes) throws E {
for (Class<? extends E> excType : excTypes)
if (excType.isInstance(exception))
throw excType.cast(exception);
return this;
}
public <E extends Throwable, F extends Throwable> Exceptional<T> propagate(
Class<E> excType, Function<? super E, ? extends F> translator)
throws F
{
if (excType.isInstance(exception))
throw translator.apply(excType.cast(exception));
return this;
}
public <E extends Throwable, F extends Throwable> Exceptional<T> propagate(
Iterable<Class<E>> excTypes, Function<? super E, ? extends F> translator)
throws F
{
for (Class<? extends E> excType : excTypes)
if (excType.isInstance(exception))
throw translator.apply(excType.cast(exception));
return this;
}
public <E extends Throwable> Exceptional<T> handle(Class<E> excType, Consumer<? super E> action) {
if (excType.isInstance(exception)) {
action.accept(excType.cast(exception));
return empty();
}
return this;
}
public <E extends Throwable> Exceptional<T> handle(Iterable<Class<E>> excTypes, Consumer<? super E> action) {
for (Class<? extends E> excType : excTypes)
if (excType.isInstance(exception)) {
action.accept(excType.cast(exception));
return empty();
}
return this;
}
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) return value;
if (exception != null) sneakyThrow(exception);
throw exceptionSupplier.get();
}
public boolean isPresent() {
return value != null;
}
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
if (exception != null) sneakyThrow(exception);
}
public boolean isException() {
return exception != null;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
return obj instanceof Exceptional && Objects.equals(value, ((Exceptional)obj).value);
}
@Override
public int hashCode() {
return Objects.hashCode(value);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void sneakyThrow(Throwable t) throws T {
throw (T) t;
}
}
</code></pre>
<hr>
<pre><code>@FunctionalInterface
public interface TrySupplier<T> {
T tryGet() throws Throwable;
}
</code></pre>
<hr>
<pre><code>@FunctionalInterface
public interface TryRunnable {
void run() throws Throwable;
}
</code></pre>
|
19,472,239 |
How to setup OWIN with Windows authentication and a custom role provider
|
<p>In MVC4 I enabled <code><authentication mode="Windows"/></code> in the web.config and created a custom role provider which then would automatically wrap the <code>WindowsIdentity</code> with a <code>RolePrincipal</code> for you. Worked like a charm. </p>
<p>How would you do this in MVC5 using OWIN and/or Microsoft.ASPNET.Identity? </p>
| 19,475,245 | 1 | 0 | null |
2013-10-19 23:26:05.573 UTC
| 8 |
2013-10-20 08:12:39.783 UTC
| null | null | null | null | 687,086 | null | 1 | 12 |
authentication|roleprovider|asp.net-mvc-5|windows-identity|owin
| 16,284 |
<p>Its the similar way to configure in web.config or configure at IIS Website.</p>
<pre><code><authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
</code></pre>
<p>Above is sufficient for intranet application. For additional scenarios like providing additional claims transformation as well as mixed authentication, for ASP.NET application, you can use custom OWIN middleware handler. </p>
<p>Have a look at example of such <a href="https://github.com/JabbR/JabbR/blob/master/JabbR/Middleware/WindowsPrincipalHandler.cs">WindowsPrincipalHandler</a>. You need to register it in startup.cs like <code>app.Use(typeof(WindowsPrincipalHandler))</code></p>
|
47,146,115 |
Firestore Pricing - Does The Amount Of Documents In A Collection Matters?
|
<p>I have read in the <a href="https://firebase.google.com/docs/firestore/pricing" rel="noreferrer">documentation</a> that I'm being charged for the amount of the requests I'm making to <code>read</code>, <code>write</code> or <code>update</code> <code>documents</code>. I have also read that reading a <code>collection</code> is priced the same as a reading a <code>document</code> ("<em>For queries other than document reads, such as a request for a list of collection IDs, you are billed for one document read.</em>"), correct me if I'm wrong.</p>
<p>My question is: Does reading a <code>collection</code> with a big amount of <code>documents</code> in it (let's say - 10,000 <code>documents</code>) is priced the same as reading one with 10? </p>
<p>I'd like to get some explaination about it...</p>
| 47,147,934 | 1 | 0 | null |
2017-11-06 21:28:19.53 UTC
| 8 |
2017-11-07 00:11:11.983 UTC
| null | null | null | null | 7,483,311 | null | 1 | 22 |
firebase|google-cloud-firestore
| 7,107 |
<p>It depends on what you mean by "reading a collection", but for most people this means "querying a bunch of documents from a collection". And the answer is that the pricing generally depends on the number of documents retrieved.</p>
<p>To oversimplify things just a bit:</p>
<p>If you have a collection of 10 employees and you run a <code>collection("employees").get()</code> call, you will get back 10 employee documents, and be charged for 10 reads.</p>
<p>If you have a collection of 10,000 employees and you run a <code>collection("employees").get()</code> call, you will get back 10,000 employees, and be charged for 10,000 reads.</p>
<p>If you have a collection of 10,000 employees and you run a <code>collection("employees").get().limit(10)</code> call, you will get back 10 employees, and be charged for 10 reads.</p>
<p>If you have a collection of 10,000 employees, 4 of which are named "Courtney" and you run a <code>collection("employees").where("first_name", "==", "Courtney")</code> call, you will get back 4 employees and be charged for 4 reads.</p>
|
47,369,351 |
kubectl apply vs kubectl create?
|
<p>What I understood by the documentation is that:</p>
<ul>
<li>
<pre class="lang-sh prettyprint-override"><code>kubectl create
</code></pre>
Creates a new k8s resource in the cluster</li>
<li>
<pre class="lang-sh prettyprint-override"><code>kubectl replace
</code></pre>
Updates a resource in the live cluster</li>
<li>
<pre class="lang-sh prettyprint-override"><code>kubectl apply
</code></pre>
If I want to do create + replace (<em><a href="https://kubernetes.io/docs/user-guide/kubectl-overview/" rel="noreferrer">Reference</a></em>)</li>
</ul>
<p><strong>My questions are</strong></p>
<ol>
<li>Why are there three operations for doing the same task in a cluster?</li>
<li>What are the use cases for these operations?</li>
<li>How do they differ from each other under the hood?</li>
</ol>
| 47,389,305 | 9 | 0 | null |
2017-11-18 18:05:32.477 UTC
| 109 |
2022-05-24 03:24:52.773 UTC
|
2022-01-19 07:59:17.477 UTC
| null | 5,963,316 | null | 8,803,619 | null | 1 | 432 |
kubernetes|kubectl
| 151,747 |
<p>Those are two different approaches:</p>
<h3>Imperative Management</h3>
<p><code>kubectl create</code> is what we call <a href="https://kubernetes.io/docs/tutorials/object-management-kubectl/imperative-object-management-configuration/" rel="noreferrer">Imperative Management</a>. On this approach you tell the Kubernetes API what you want to create, replace or delete, not how you want your K8s cluster world to look like.</p>
<h3>Declarative Management</h3>
<p><code>kubectl apply</code> is part of the <a href="https://kubernetes.io/docs/tutorials/object-management-kubectl/declarative-object-management-configuration/" rel="noreferrer">Declarative Management</a> approach, where changes that you may have applied to a live object (i.e. through <code>scale</code>) are "<strong>maintained</strong>" even if you <code>apply</code> other changes to the object.</p>
<blockquote>
<p>You can read more about imperative and declarative management in the <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/object-management/" rel="noreferrer">Kubernetes Object Management</a> documentation.</p>
</blockquote>
<h3>In laymans They do different things. If the resource exists, <code>kubectl create</code> will error out and <code>kubectl apply</code> will not error out.</h3>
|
34,247,702 |
Configure Django and Google Cloud Storage?
|
<p>I am <strong><em>not</em></strong> using Appengine.</p>
<p>I have a plain vanilla Django application running on a VM. I want to use Google Cloud Storage for serving my staticfiles, and also for uploading/serving my media files.</p>
<p>I have a bucket. </p>
<p>How do I link my Django application to my bucket? I've tried <code>django-storages</code>. That may work, but what do I have to do to prepare my bucket to be used by my django application? And what baseline configuration do I need in my Django settings?</p>
<p>Current settings:</p>
<pre><code># Google Cloud Storage
# http://django-storages.readthedocs.org/en/latest/backends/apache_libcloud.html
LIBCLOUD_PROVIDERS = {
'google': {
'type' : 'libcloud.storage.types.Provider.GOOGLE_STORAGE',
'user' : <I have no idea>,
'key' : <ditto above>,
'bucket': <my bucket name>,
}
}
DEFAULT_LIBCLOUD_PROVIDER = 'google'
DEFAULT_FILE_STORAGE = 'storages.backends.apache_libcloud.LibCloudStorage'
STATICFILES_STORAGE = 'storages.backends.apache_libcloud.LibCloudStorage'
</code></pre>
| 37,170,899 | 7 | 0 | null |
2015-12-13 03:33:55.5 UTC
| 25 |
2022-05-20 00:07:16.753 UTC
|
2022-05-12 13:12:38.227 UTC
| null | 8,172,439 | null | 2,714,733 | null | 1 | 28 |
python|python-3.x|django|google-cloud-platform|google-cloud-storage
| 18,827 |
<p>Django-storages has a backend for Google Cloud Storage, but it is not documented, I realised looking in the repo. Got it working with this setup:</p>
<pre><code>DEFAULT_FILE_STORAGE = 'storages.backends.gs.GSBotoStorage'
GS_ACCESS_KEY_ID = 'YourID'
GS_SECRET_ACCESS_KEY = 'YourKEY'
GS_BUCKET_NAME = 'YourBucket'
STATICFILES_STORAGE = 'storages.backends.gs.GSBotoStorage'
</code></pre>
<p>To get YourKEY and YourID you should create <code>Interoperability</code> keys, in the settings tab.</p>
<p>Hope it helps and you don't have to learn it the hard way :)</p>
<p>Ah in case you haven't yet, the dependencies are:</p>
<pre><code>pip install django-storages
pip install boto
</code></pre>
|
21,217,778 |
Select multiple columns from a table, but group by one
|
<p>The table name is "OrderDetails" and columns are given below:</p>
<pre><code>OrderDetailID || ProductID || ProductName || OrderQuantity
</code></pre>
<p>I'm trying to select multiple columns and Group By ProductID while having SUM of OrderQuantity.</p>
<pre><code> Select ProductID,ProductName,OrderQuantity Sum(OrderQuantity)
from OrderDetails Group By ProductID
</code></pre>
<p>But of course this code gives an error. I have to add other column names to group by, but that's not what I want and since my data has many items so <strong>results are unexpected that way.</strong></p>
<p>Sample Data Query: </p>
<p>ProductID,ProductName,OrderQuantity from OrderDetails</p>
<p>Results are below:</p>
<pre><code> ProductID ProductName OrderQuantity
1001 abc 5
1002 abc 23 (ProductNames can be same)
2002 xyz 8
3004 ytp 15
4001 aze 19
1001 abc 7 (2nd row of same ProductID)
</code></pre>
<p>Expected result:</p>
<pre><code> ProductID ProductName OrderQuantity
1001 abc 12 (group by productID while summing)
1002 abc 23
2002 xyz 8
3004 ytp 15
4001 aze 19
</code></pre>
<p>How do I select multiple columns and Group By ProductID column since ProductName is not unique? </p>
<p>While doing that, also get the sum of the OrderQuantity column.</p>
| 38,779,277 | 12 | 1 | null |
2014-01-19 14:08:48.53 UTC
| 32 |
2022-04-08 14:15:59.64 UTC
|
2018-10-06 13:23:22.69 UTC
| null | 63,550 | null | 3,087,919 | null | 1 | 103 |
sql|group-by
| 288,804 |
<p>I use this trick to group by one column when I have a multiple columns selection:</p>
<pre><code>SELECT MAX(id) AS id,
Nume,
MAX(intrare) AS intrare,
MAX(iesire) AS iesire,
MAX(intrare-iesire) AS stoc,
MAX(data) AS data
FROM Produse
GROUP BY Nume
ORDER BY Nume
</code></pre>
<p>This works.</p>
|
18,892,051 |
Complete.obs of cor() function
|
<p>I am establishing a correlation matrix for my data, which looks like this</p>
<pre><code>df <- structure(list(V1 = c(56, 123, 546, 26, 62, 6, NA, NA, NA, 15
), V2 = c(21, 231, 5, 5, 32, NA, 1, 231, 5, 200), V3 = c(NA,
NA, 24, 51, 53, 231, NA, 153, 6, 700), V4 = c(2, 10, NA, 20,
56, 1, 1, 53, 40, 5000)), .Names = c("V1", "V2", "V3", "V4"), row.names = c(NA,
10L), class = "data.frame")
</code></pre>
<p>This gives the following data frame:</p>
<pre><code> V1 V2 V3 V4
1 56 21 NA 2
2 123 231 NA 10
3 546 5 24 NA
4 26 5 51 20
5 62 32 53 56
6 6 NA 231 1
7 NA 1 NA 1
8 NA 231 153 53
9 NA 5 6 40
10 15 200 700 5000
</code></pre>
<p>I normally use a complete.obs command to establish my correlation matrix using this command</p>
<pre><code>crm <- cor(df, use="complete.obs", method="pearson")
</code></pre>
<p>My question here is, how does the complete.obs treat the data? does it omit any row having a "NA" value, make a "NA" free table and make a correlation matrix at once like this?</p>
<pre><code>df2 <- structure(list(V1 = c(26, 62, 15), V2 = c(5, 32, 200), V3 = c(51,
53, 700), V4 = c(20, 56, 5000)), .Names = c("V1", "V2", "V3",
"V4"), row.names = c(NA, 3L), class = "data.frame")
</code></pre>
<p>or does it omit "NA" values in a pairwise fashion, for example when calculating correlation between V1 and V2, the row that contains an NA value in V3, (such as rows 1 and 2 in my example) do they get omitted too?</p>
<p>If this is the case, I am looking forward to establish a command that reserves as much as possible of the data, by omitting NA values in a pairwise fashion.</p>
<p>Many thanks,</p>
| 18,892,108 | 1 | 0 | null |
2013-09-19 10:19:18.003 UTC
| 4 |
2017-11-11 10:11:59.213 UTC
|
2017-11-11 10:11:59.213 UTC
| null | 3,670,097 | null | 1,826,552 | null | 1 | 12 |
r|matrix|correlation|na
| 52,139 |
<p>Look at the help file for <code>cor</code>, i.e. <code>?cor</code>. In particular, </p>
<blockquote>
<p>If ‘use’ is ‘"everything"’, ‘NA’s will propagate conceptually, i.e., a
resulting value will be ‘NA’ whenever one of its contributing
observations is ‘NA’.</p>
<p>If ‘use’ is ‘"all.obs"’, then the presence of missing observations
will produce an error. If ‘use’ is ‘"complete.obs"’ then missing
values are handled by casewise deletion (and if there are no complete
cases, that gives an error).</p>
</blockquote>
<p>To get a better feel about what is going on, is to create an (even) simpler example:</p>
<pre><code>df1 = df[1:5,1:3]
cor(df1, use="pairwise.complete.obs", method="pearson")
cor(df1, use="complete.obs", method="pearson")
cor(df1[3:5,], method="pearson")
</code></pre>
<p>So, when we use <code>complete.obs</code>, we discard the <em>entire</em> row if an <code>NA</code> is present. In my example, this means we discard rows 1 and 2. However, <code>pairwise.complete.obs</code> uses the non-<code>NA</code> values when calculating the correlation between <code>V1</code> and <code>V2</code>.</p>
|
46,772,852 |
Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)
|
<p>I am currently working on password reset page of an Angular 4 project. We are using Angular Material to create the dialog, however, when the client clicks out of the dialog, it will close automatically. Is there a way to avoid the dialog close until our code side call "close" function? Or how should I create an <em>unclosable</em> modal?</p>
| 46,774,826 | 3 | 0 | null |
2017-10-16 14:35:41.273 UTC
| 27 |
2021-05-27 21:13:17.093 UTC
|
2020-02-29 16:57:23.93 UTC
| null | 4,245,771 | null | 5,802,031 | null | 1 | 195 |
angular|dialog|modal-dialog|angular-material
| 178,337 |
<p>There are two ways to do it.</p>
<ol>
<li><p>In the method that opens the dialog, pass in the following configuration option <code>disableClose</code> as the second parameter in <code>MatDialog#open()</code> and set it to <code>true</code>:</p>
<pre class="lang-ts prettyprint-override"><code>export class AppComponent {
constructor(private dialog: MatDialog){}
openDialog() {
this.dialog.open(DialogComponent, { disableClose: true });
}
}
</code></pre></li>
<li><p>Alternatively, do it in the dialog component itself.</p>
<pre class="lang-ts prettyprint-override"><code>export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>){
dialogRef.disableClose = true;
}
}
</code></pre></li>
</ol>
<p>Here's what you're looking for:</p>
<p><a href="https://material.angular.io/components/dialog/api#MatDialogConfig" rel="noreferrer" title="View the docs for MatDialogConfig"><img src="https://i.stack.imgur.com/om5sF.jpg" alt="<code>disableClose</code> property in material.angular.io"></a></p>
<p>And here's a <a href="https://stackblitz.com/edit/dialog-disable-close-so" rel="noreferrer">Stackblitz demo</a></p>
<hr>
<h1>Other use cases</h1>
<p>Here's some other use cases and code snippets of how to implement them.</p>
<h2>Allow <kbd>esc</kbd> to close the dialog but disallow clicking on the backdrop to close the dialog</h2>
<p>As what @MarcBrazeau said in the comment below my answer, you can allow the <kbd>esc</kbd> key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:</p>
<pre class="lang-ts prettyprint-override"><code>import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
selector: 'app-third-dialog',
templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {
}
@HostListener('window:keyup.esc') onKeyUp() {
this.dialogRef.close();
}
}
</code></pre>
<hr>
<h2>Prevent <kbd>esc</kbd> from closing the dialog but allow clicking on the backdrop to close</h2>
<blockquote>
<p>P.S. This is an answer which originated from <a href="https://stackoverflow.com/a/51015306">this answer</a>, where the demo was based on this answer.</p>
</blockquote>
<p>To prevent the <kbd>esc</kbd> key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using <code>MatDialogRef#backdropClick</code> to listen for click events to the backdrop.</p>
<p>Initially, the dialog will have the configuration option <code>disableClose</code> set as <code>true</code>. This ensures that the <code>esc</code> keypress, as well as clicking on the backdrop will not cause the dialog to close.</p>
<p>Afterwards, subscribe to the <code>MatDialogRef#backdropClick</code> method (which emits when the backdrop gets clicked and returns as a <code>MouseEvent</code>).</p>
<p>Anyways, enough technical talk. Here's the code:</p>
<pre class="lang-ts prettyprint-override"><code>openDialog() {
let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
// ...
}
</code></pre>
<p>Alternatively, this can be done in the dialog component:</p>
<pre class="lang-ts prettyprint-override"><code>export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>) {
dialogRef.disableClose = true;
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
}
}
</code></pre>
|
27,948,128 |
How to convert Scala Map into JSON String?
|
<p>For example, I have this Map value in Scala:</p>
<pre><code>val m = Map(
"name" -> "john doe",
"age" -> 18,
"hasChild" -> true,
"childs" -> List(
Map("name" -> "dorothy", "age" -> 5, "hasChild" -> false),
Map("name" -> "bill", "age" -> 8, "hasChild" -> false)
)
)
</code></pre>
<p>I want to convert it to its JSON string representation:</p>
<pre><code>{
"name": "john doe",
"age": 18,
"hasChild": true,
"childs": [
{
"name": "dorothy",
"age": 5,
"hasChild": false
},
{
"name": "bill",
"age": 8,
"hasChild": false
}
]
}
</code></pre>
<p>I'm currenly working on Play framework v2.3, but the solution doesn't need to use Play JSON library, although it will be nice if someone can provide both Play and non-Play solution.</p>
<p>This is what I have done so far without success:</p>
<pre><code>// using jackson library
val mapper = new ObjectMapper()
val res = mapper.writeValueAsString(m)
println(res)
</code></pre>
<p>Result:</p>
<pre><code>{"empty":false,"traversableAgain":true}
</code></pre>
<p>I don't understand why I got that result.</p>
| 27,948,884 | 7 | 0 | null |
2015-01-14 16:44:53.053 UTC
| 7 |
2020-08-21 04:48:28.787 UTC
| null | null | null | null | 844,005 | null | 1 | 27 |
json|scala|playframework|playframework-2.0
| 48,075 |
<p>As a non play solution, you can consider using <a href="https://github.com/json4s/json4s">json4s</a> which provides a wrapper around jackson and its easy to use.
If you are using json4s then you can convert map to json just by using:</p>
<pre><code>write(m)
//> res0: String = {"name":"john doe","age":18,"hasChild":true,"childs":[{"name":"dorothy","age":5,"hasChild":false},{"name":"bill","age":8,"hasChild":false}]}
</code></pre>
<p>--Updating to include the full example--</p>
<pre><code>import org.json4s._
import org.json4s.native.Serialization._
import org.json4s.native.Serialization
implicit val formats = Serialization.formats(NoTypeHints)
val m = Map(
"name" -> "john doe",
"age" -> 18,
"hasChild" -> true,
"childs" -> List(
Map("name" -> "dorothy", "age" -> 5, "hasChild" -> false),
Map("name" -> "bill", "age" -> 8, "hasChild" -> false)))
write(m)
</code></pre>
<p>Output:</p>
<pre><code> res0: String = {"name":"john doe","age":18,"hasChild":true,"childs":[{"name"
:"dorothy","age":5,"hasChild":false},{"name":"bill","age":8,"hasChild":false }]}
</code></pre>
<p>Alternative way:</p>
<pre><code>import org.json4s.native.Json
import org.json4s.DefaultFormats
Json(DefaultFormats).write(m)
</code></pre>
|
8,716,064 |
HTML/JS: How to change option value of select type using JS
|
<p>I've been trying to figure out how to set a value to a an option in a select type. But no matter how much I try to understand I just can't (feels ashamed)..</p>
<p>So I was hoping that you guys could help me since you've helped me so many times before.. :)</p>
<p>Let's say we have:</p>
<pre><code><select name="box" id="test">
<option value='tval'>Content</option>
</code></pre>
<p>shouldn't this next code change the text from 'Content' to 'box'?</p>
<pre><code>function changeContent(form){
form.document.getElementById('test').options['tval'].value = 'box';
}
</code></pre>
<p>or am I completely wrong here? I've looked up so many different articles but no one could help me understand how to do this..</p>
<p>Thanks guys!</p>
| 8,716,126 | 5 | 0 | null |
2012-01-03 17:18:39.077 UTC
| 2 |
2022-08-31 14:33:28.113 UTC
|
2022-08-31 14:33:28.113 UTC
| null | 1,007,220 | null | 826,211 | null | 1 | 5 |
javascript|html|html-select
| 41,610 |
<p>If You need to change the text rather than the value;</p>
<pre><code>function changeContent(){
document.getElementById('test').options[0].text = 'box';
}
</code></pre>
<p>To set both the value and text;</p>
<pre><code>function changeContent(){
var opt= document.getElementById('test').options[0];
opt.value = 'box';
opt.text = 'box';
}
</code></pre>
|
26,866,879 |
Initialize nested struct definition
|
<p>How do you initialize the following struct?</p>
<pre><code>type Sender struct {
BankCode string
Name string
Contact struct {
Name string
Phone string
}
}
</code></pre>
<p><strong>I tried:</strong></p>
<pre><code>s := &Sender{
BankCode: "BC",
Name: "NAME",
Contact {
Name: "NAME",
Phone: "PHONE",
},
}
</code></pre>
<p><strong>Didn't work:</strong></p>
<pre><code>mixture of field:value and value initializers
undefined: Contact
</code></pre>
<p><strong>I tried:</strong></p>
<pre><code>s := &Sender{
BankCode: "BC",
Name: "NAME",
Contact: Contact {
Name: "NAME",
Phone: "PHONE",
},
}
</code></pre>
<p><strong>Didn't work:</strong></p>
<pre><code>undefined: Contact
</code></pre>
| 26,867,130 | 3 | 0 | null |
2014-11-11 14:13:18.35 UTC
| 17 |
2020-02-23 21:02:40.847 UTC
|
2020-02-23 21:02:40.847 UTC
| null | 13,860 | null | 1,188,357 | null | 1 | 65 |
struct|go|initialization
| 56,249 |
<p>Your <code>Contact</code> is a field with anonymous struct type. As such, you have to repeat the type definition:</p>
<pre><code>s := &Sender{
BankCode: "BC",
Name: "NAME",
Contact: struct {
Name string
Phone string
}{
Name: "NAME",
Phone: "PHONE",
},
}
</code></pre>
<p>But in most cases it's better to define a separate type as rob74 proposed.</p>
|
26,819,222 |
Dynamic content added with AngularJS click event not working on the added content
|
<p>I just started on AngularJS this week for a new project, and I have to come up to speed ASAP.</p>
<p>One of my requirements, is to add html content dynamically and that content might have a click event on it.</p>
<p>So the code Angular code I have below displays a button, and when clicked, it dynamically adds another button. Clicking on the dynamically added buttons, should add another button, but I cannot get the ng-click to work on the dynamically added buttons</p>
<p><code><button type="button" id="btn1" ng-click="addButton()">Click Me</button></code></p>
<p>The working code sample is here
<a href="http://plnkr.co/edit/pTq2THCmXqw4MO3uLyi6?p=preview">http://plnkr.co/edit/pTq2THCmXqw4MO3uLyi6?p=preview</a></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.addButton = function() {
alert("button clicked");
var btnhtml = '<button type="button" ng-click="addButton()">Click Me</button>';
angular.element(document.getElementById('foo')).append((btnhtml));
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.0.x" src="//code.angularjs.org/1.3.0/angular.js" data-semver="1.3.0"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div id="foo">
<button type="button" id="btn1" ng-click="addButton()">Click Me
</button>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><a href="http://plnkr.co/edit/pTq2THCmXqw4MO3uLyi6?p=preview">http://plnkr.co/edit/pTq2THCmXqw4MO3uLyi6?p=preview</a></p>
| 26,819,263 | 2 | 0 | null |
2014-11-08 16:16:57.63 UTC
| 10 |
2017-04-03 08:55:54.687 UTC
| null | null | null | null | 3,495,052 | null | 1 | 21 |
angularjs|angularjs-ng-click|dynamic-html
| 36,811 |
<pre><code>app.controller('MainCtrl', function($scope,$compile) {
var btnhtml = '<button type="button" ng-click="addButton()">Click Me</button>';
var temp = $compile(btnhtml)($scope);
//Let's say you have element with id 'foo' in which you want to create a button
angular.element(document.getElementById('foo')).append(temp);
var addButton = function(){
alert('Yes Click working at dynamically added element');
}
});
</code></pre>
<p>you need to add <code>$compile</code> service here, that will bind the <code>angular directives</code> like <code>ng-click</code> to your controller scope. and dont forget to add <code>$compile</code> dependency in your controller as well like below.</p>
<p>here is the <a href="http://plnkr.co/edit/nqpMcXNtr05w7qXGVYbz?p=preview" rel="noreferrer"><strong>plunker demo</strong></a></p>
|
26,891,658 |
What is the difference between fetch="EAGER" and fetch="LAZY" in doctrine
|
<p>What is the difference between <code>fetch="EAGER"</code> and <code>fetch="LAZY"</code> in annotation <code>@ManyToOne</code> in Doctrine ?</p>
<pre><code>/**
* @ManyToOne(targetEntity="Cart", cascade={"all"}, fetch="EAGER")
*/
/**
* @ManyToOne(targetEntity="Cart", cascade={"all"}, fetch="LAZY")
*/
</code></pre>
| 26,895,601 | 2 | 0 | null |
2014-11-12 16:22:23.767 UTC
| 14 |
2021-04-08 15:10:30.31 UTC
|
2017-06-28 10:56:14.847 UTC
| null | 269,804 | null | 889,923 | null | 1 | 76 |
orm|doctrine-orm|many-to-many
| 77,261 |
<p>To explain it simply, when you are loading an entity and if it has an association with one or more entities, what should doctrine do?</p>
<p>If the association is marked as <strong>EAGER</strong>, it will fetch and load the associated entity as well.</p>
<p>If the association is marked as <strong>LAZY</strong>, doctrine will create proxy objects (dummy objects) in place of the actual entity. Only when you make the first call to that associated entity (like <code>$cart->getItems()</code>), doctrine will fetch and load that object(s) from database. (This is the <a href="https://www.doctrine-project.org/projects/doctrine-orm/en/current/tutorials/extra-lazy-associations.html#extra-lazy-associations" rel="noreferrer">default Behaviour</a>)</p>
<p>Refer: <a href="https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/advanced-configuration.html#association-proxies" rel="noreferrer">https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/advanced-configuration.html#association-proxies</a></p>
|
30,508,805 |
Adding Bundles to existing ASP.NET Webforms solution
|
<p>I am trying to add Bundles to an existing ASP.NET Webforms solution but my bundles always render empty and I am unsure why. I have been following <a href="http://igorzelmanovich.blogspot.co.uk/2012/09/using-aspnet-bundling-and-minification.html" rel="noreferrer">this blog post</a>.</p>
<p>So far I have:</p>
<ul>
<li>Added the Microsoft ASP.NET Web Optimization Framework NuGet package</li>
<li>Ensured required references are included</li>
<li>Tried using debug="false" and debug="true" in Web.config</li>
<li>Added the following code to my solution</li>
</ul>
<p><strong>Global.asax.cs</strong></p>
<pre><code>protected void Application_Start(object sender, EventArgs e)
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
</code></pre>
<p><strong>App_Start/BundleConfig.cs</strong></p>
<pre><code>public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkID=303951
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/Global").Include(
"~/js/jquery-{version}.js",
"~/js/jquery-ui.js"));
bundles.Add(new ScriptBundle("~/bundles/GlobalHead").Include(
"~/js/modernizr*"));
bundles.Add(new StyleBundle("~/Content/Global").Include(
"~/css/site.css"));
}
}
</code></pre>
<p><strong>Site.Master</strong></p>
<pre><code><head runat="server">
<asp:PlaceHolder runat="server">
<%: Scripts.Render("~/bundle/GlobalHead") %>
<%: Styles.Render("~/Content/Global") %>
</asp:PlaceHolder>
</head>
<body>
<%: Scripts.Render("~/bundle/Global") %>
</body>
</code></pre>
<p><strong>Web.Config</strong></p>
<pre><code><namespaces>
<add namespace="System.Web.Optimization" />
</namespaces>
</code></pre>
<p><strong>Update</strong></p>
<p>To be clear, when I open a web page and inspect the resources with chrome dev tools, I can see</p>
<pre><code>Content/Site.css
bundle/Global.js
bundle/GlobalHead.js
</code></pre>
<p>But when inspecting them they have no content.</p>
| 30,509,546 | 1 | 0 | null |
2015-05-28 14:00:57.07 UTC
| 11 |
2016-07-18 07:41:09.137 UTC
|
2015-05-28 14:31:14.033 UTC
| null | 4,903,560 | null | 4,903,560 | null | 1 | 44 |
c#|asp.net|webforms|bundle
| 31,430 |
<p>Simple solution, I had some typing errors.</p>
<p>In the Site.Master I missed the 's' from the end of bundles. Making my Site.Master look like this.</p>
<pre><code><head runat="server">
<asp:PlaceHolder runat="server">
<%: Scripts.Render("~/bundles/GlobalHead") %>
<%: Styles.Render("~/Content/Global") %>
</asp:PlaceHolder>
</head>
<body>
<%: Scripts.Render("~/bundles/Global") %>
</body>
</code></pre>
|
20,380,720 |
Selenium WebDriver can't find element by link text
|
<p>I'm trying to select an element that includes an anchor, but the text is buried in a paragraph inside of a div. Here's the HTML I'm working with:</p>
<pre><code><a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026" href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026">
<div class="col-lg-2 col-sm-3 col-xs-4 item-list-image">
<img ng-src="csa/images/library/Service_Design.png" src="csa/images/library/Service_Design.png">
</div>
<div class="col-lg-8 col-sm-9 col-xs-8">
<div class="col-xs-12">
<p>
<strong class="ng-binding">Smoke Sequential</strong>
</p>
</code></pre>
<p>The code I'm using to try to snag it is targeting the "Smoke Sequential" text with:</p>
<pre><code>driver.findElement(By.linkText(service)).click();
</code></pre>
<p>Where the variable 'service' holds "Smoke Sequential" in it. When I run it, I get the following error:</p>
<pre><code>org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"Smoke Sequential"}
</code></pre>
<p>Any help would be greatly appreciated.</p>
| 20,387,927 | 5 | 0 | null |
2013-12-04 16:29:11.333 UTC
| 2 |
2017-09-08 02:58:08.947 UTC
| null | null | null | null | 2,657,756 | null | 1 | 13 |
java|html|selenium|selenium-webdriver
| 114,036 |
<p>The problem might be in the rest of the html, the part that you didn't post.</p>
<p>With this example (I just closed the open tags):</p>
<pre><code><a class="item" ng-href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026" href="#/catalog/90d9650a36988e5d0136988f03ab000f/category/DATABASE_SERVERS/service/90cefc7a42b3d4df0142b52466810026">
<div class="col-lg-2 col-sm-3 col-xs-4 item-list-image">
<img ng-src="csa/images/library/Service_Design.png" src="csa/images/library/Service_Design.png">
</div>
<div class="col-lg-8 col-sm-9 col-xs-8">
<div class="col-xs-12">
<p>
<strong class="ng-binding">Smoke Sequential</strong>
</p>
</div>
</div>
</a>
</code></pre>
<p>I was able to find the element without trouble with:</p>
<pre><code>driver.findElement(By.linkText("Smoke Sequential")).click();
</code></pre>
<p>If there is more text inside the element, you could try a find by partial link text:</p>
<pre><code>driver.findElement(By.partialLinkText("Sequential")).click();
</code></pre>
|
20,612,645 |
How to find the installed pandas version
|
<p>I am having trouble with some of pandas functionalities. How do I check what is my installation version?</p>
| 20,612,691 | 6 | 0 | null |
2013-12-16 13:55:12.397 UTC
| 42 |
2022-05-15 20:34:23.413 UTC
|
2017-01-06 02:34:34.367 UTC
| null | 4,627,108 | null | 1,945,306 | null | 1 | 311 |
python|pandas
| 431,299 |
<p>Check <code>pandas.__version__</code>:</p>
<pre><code>In [76]: import pandas as pd
In [77]: pd.__version__
Out[77]: '0.12.0-933-g281dc4e'
</code></pre>
<p>Pandas also provides a utility function, <code>pd.show_versions()</code>, which reports the version of its dependencies as well:</p>
<pre><code>In [53]: pd.show_versions(as_json=False)
INSTALLED VERSIONS
------------------
commit: None
python: 2.7.6.final.0
python-bits: 64
OS: Linux
OS-release: 3.13.0-45-generic
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
pandas: 0.15.2-113-g5531341
nose: 1.3.1
Cython: 0.21.1
numpy: 1.8.2
scipy: 0.14.0.dev-371b4ff
statsmodels: 0.6.0.dev-a738b4f
IPython: 2.0.0-dev
sphinx: 1.2.2
patsy: 0.3.0
dateutil: 1.5
pytz: 2012c
bottleneck: None
tables: 3.1.1
numexpr: 2.2.2
matplotlib: 1.4.2
openpyxl: None
xlrd: 0.9.3
xlwt: 0.7.5
xlsxwriter: None
lxml: 3.3.3
bs4: 4.3.2
html5lib: 0.999
httplib2: 0.8
apiclient: None
rpy2: 2.5.5
sqlalchemy: 0.9.8
pymysql: None
psycopg2: 2.4.5 (dt dec mx pq3 ext)
</code></pre>
|
42,645,196 |
How to SSH and run commands in EC2 using boto3?
|
<p>I want to be able to ssh into an EC2 instance, and run some shell commands in it, like <a href="https://stackoverflow.com/a/15503965/4993513">this</a>.</p>
<p>How do I do it in boto3? </p>
| 42,688,515 | 7 | 2 | null |
2017-03-07 10:01:01.62 UTC
| 13 |
2021-04-12 11:55:20.177 UTC
|
2017-05-23 11:53:57.677 UTC
| null | -1 | null | 4,993,513 | null | 1 | 30 |
python|amazon-ec2|boto3
| 41,299 |
<p>You can use the following code snippet to ssh to an EC2 instance and run some command from boto3.</p>
<pre><code>import boto3
import botocore
import paramiko
key = paramiko.RSAKey.from_private_key_file(path/to/mykey.pem)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect/ssh to an instance
try:
# Here 'ubuntu' is user name and 'instance_ip' is public IP of EC2
client.connect(hostname=instance_ip, username="ubuntu", pkey=key)
# Execute a command(cmd) after connecting/ssh to an instance
stdin, stdout, stderr = client.exec_command(cmd)
print stdout.read()
# close the client connection once the job is done
client.close()
break
except Exception, e:
print e
</code></pre>
|
20,119,414 |
define aggfunc for each values column in pandas pivot table
|
<p>Was trying to generate a pivot table with multiple "values" columns. I know I can use aggfunc to aggregate values the way I want to, but what if I don't want to sum or avg both columns but instead I want sum of one column while mean of the other one. So is it possible to do so using pandas?</p>
<pre><code>df = pd.DataFrame({
'A' : ['one', 'one', 'two', 'three'] * 6,
'B' : ['A', 'B', 'C'] * 8,
'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4,
'D' : np.random.randn(24),
'E' : np.random.randn(24)
})
</code></pre>
<p>Now this will get a pivot table with sum:</p>
<pre><code>pd.pivot_table(df, values=['D','E'], rows=['B'], aggfunc=np.sum)
</code></pre>
<p>And this for mean:</p>
<pre><code>pd.pivot_table(df, values=['D','E'], rows=['B'], aggfunc=np.mean)
</code></pre>
<p>How can I get sum for <code>D</code> and mean for <code>E</code>?</p>
<p>Hope my question is clear enough.</p>
| 20,120,225 | 3 | 0 | null |
2013-11-21 11:14:46.027 UTC
| 11 |
2019-02-02 11:56:27.393 UTC
|
2016-01-07 22:28:06.12 UTC
| null | 384,803 | null | 2,814,765 | null | 1 | 22 |
python|python-2.7|pandas
| 44,749 |
<p>You can <strong>concat two DataFrames</strong>:</p>
<pre><code>>>> df1 = pd.pivot_table(df, values=['D'], rows=['B'], aggfunc=np.sum)
>>> df2 = pd.pivot_table(df, values=['E'], rows=['B'], aggfunc=np.mean)
>>> pd.concat((df1, df2), axis=1)
D E
B
A 1.810847 -0.524178
B 2.762190 -0.443031
C 0.867519 0.078460
</code></pre>
<p>or you can <strong>pass list of functions</strong> as <code>aggfunc</code> parameter and then reindex:</p>
<pre><code>>>> df3 = pd.pivot_table(df, values=['D','E'], rows=['B'], aggfunc=[np.sum, np.mean])
>>> df3
sum mean
D E D E
B
A 1.810847 -4.193425 0.226356 -0.524178
B 2.762190 -3.544245 0.345274 -0.443031
C 0.867519 0.627677 0.108440 0.078460
>>> df3 = df3.ix[:, [('sum', 'D'), ('mean','E')]]
>>> df3.columns = ['D', 'E']
>>> df3
D E
B
A 1.810847 -0.524178
B 2.762190 -0.443031
C 0.867519 0.078460
</code></pre>
<p>Alghouth, it would be nice to have an option to defin <code>aggfunc</code> for each column individually. Don't know how it could be done, may be pass into <code>aggfunc</code> dict-like parameter, like <code>{'D':np.mean, 'E':np.sum}</code>.</p>
<p><strong>update</strong> Actually, in your case you can <strong>pivot by hand</strong>:</p>
<pre><code>>>> df.groupby('B').aggregate({'D':np.sum, 'E':np.mean})
E D
B
A -0.524178 1.810847
B -0.443031 2.762190
C 0.078460 0.867519
</code></pre>
|
1,538,463 |
how can I put a breakpoint on "something is printed to the terminal" in gdb?
|
<p>I would like to know from where inside a <em>huge</em> application a certain message is printed. The application is so big and old that it uses all conceivable ways of printing text to the terminal; for example printf(), fprintf(stdout, ...) etc.</p>
<p>I write to put a breakpoint on the write() system call but then I'm flooded with too many breakpoint stops because of various file I/O operations that use write() as well.</p>
<p>So basically I want gdb to stop whenever the program prints something to the terminal but at the same time I don't want gdb to stop when the program writes something to a file.</p>
| 1,538,511 | 2 | 2 | null |
2009-10-08 15:11:43.58 UTC
| 9 |
2010-01-06 20:09:41.463 UTC
| null | null | null | null | 186,437 | null | 1 | 32 |
gdb|printf|breakpoints|conditional-breakpoint
| 12,169 |
<p>Use a conditional breakpoint that checks the first parameter. On 64-bit x86 systems the condition would be:</p>
<p>(gdb) b write if 1==$rdi</p>
<p>On 32-bit systems, it is more complex because the parameter is on the stack, meaning that you need to cast $esp to an int * and index the fd parameter. The stack at that point has the return address, the length, buffer and finally fd.</p>
<p>This varies greatly between hardware platforms.</p>
|
46,160,461 |
How do you set the document title in React?
|
<p>I would like to set the document title (in the browser title bar) for my React application. I have tried using <a href="https://github.com/gaearon/react-document-title" rel="noreferrer">react-document-title</a> (seems out of date) and setting <code>document.title</code> in the <code>constructor</code> and <code>componentDidMount()</code> - none of these solutions work.</p>
| 46,176,359 | 20 | 2 | null |
2017-09-11 16:36:52.39 UTC
| 39 |
2022-08-09 11:17:24.343 UTC
|
2018-06-05 02:13:20.73 UTC
| null | 1,341,825 | null | 655,214 | null | 1 | 230 |
javascript|reactjs|dom
| 257,268 |
<p>For React 16.8+ you can use the <a href="https://reactjs.org/docs/hooks-effect.html" rel="noreferrer">Effect Hook</a> in function components:</p>
<pre><code>import React, { useEffect } from 'react';
function Example() {
useEffect(() => {
document.title = 'My Page Title';
});
}
</code></pre>
<p><br />
To manage all valid head tags, including <code><title></code>, in declarative way, you can use <a href="https://github.com/nfl/react-helmet" rel="noreferrer">React Helmet</a> component:</p>
<pre><code>import React from 'react'
import { Helmet } from 'react-helmet'
const TITLE = 'My Page Title'
class MyComponent extends React.PureComponent {
render () {
return (
<>
<Helmet>
<title>{ TITLE }</title>
</Helmet>
...
</>
)
}
}
</code></pre>
|
28,969,032 |
What the equivalent of activity life cycle in iOS?
|
<p>Actually, I would say that both iOS <code>ViewControllers</code> and Android <code>Activities</code> have their lifecycle methods. For example an equivalent of <code>ViewController.viewDidLoad()</code> is <code>Activity.onCreate()</code> ?</p>
<p>Else I still need to know the equivalent of the other :</p>
<ul>
<li><code>OnStart()</code></li>
<li><code>OnRestart()</code></li>
<li><code>OnResume()</code></li>
<li><code>OnStop()</code></li>
<li><code>OnDestroy()</code></li>
<li><code>OnPause()</code></li>
</ul>
| 28,969,161 | 1 | 1 | null |
2015-03-10 16:27:02.883 UTC
| 42 |
2017-04-19 05:44:54.1 UTC
|
2015-03-10 16:54:22.69 UTC
| null | 250,260 | null | 3,672,184 | null | 1 | 67 |
android|ios|objective-c|mapping|android-lifecycle
| 27,992 |
<p>This is a comparison between the lifecycle of Android vs iOS:</p>
<p><img src="https://i.stack.imgur.com/Jn6MZ.png" alt="enter image description here"></p>
<ul>
<li><strong>Note</strong>: viewDidUnload is deprecated after iOS 6 </li>
</ul>
|
6,105,182 |
Error while opening port in Python using TI Chronos
|
<p>I'm trying to get accelerometer data from TI Chronos. I get the following error message when I run the code:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python32\chronos_accel.py", line 50, in <module>
.
.
.
raise SerialException("could not open port %s: %s" % (self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port COM4: [Error 5] Access is denied.
</code></pre>
<p>Why is access denied? I'm the system administrator. Could it be a problem with the code?</p>
| 6,109,643 | 6 | 5 | null |
2011-05-24 02:42:37.613 UTC
| 2 |
2019-11-14 13:17:15.053 UTC
|
2019-11-14 13:01:26.143 UTC
| null | 63,550 | null | 732,923 | null | 1 | 6 |
python|port
| 80,778 |
<p>I figured it out. It was simple enough.</p>
<p>I just disabled the COM port in the <a href="http://en.wikipedia.org/wiki/Device_Manager" rel="nofollow noreferrer">Device Manager</a> window and enabled it again.</p>
|
5,978,917 |
Render WPF control on top of WindowsFormsHost
|
<p>I know that default WPF behavior is to render WPF controls and then on top render WinForms, but are there any way to render WPF on top of <code>WindowsFormsHost</code>?</p>
<p><strong>Edit</strong>: I have found a temp hack as well. When wpf control overlaps <code>WindowsFormsHost</code>, I change the size of the <code>WindowsFormsHost</code> (This only works when you have rectangular object which overlaps, doesn't work for other shapes.)</p>
| 5,979,041 | 6 | 1 | null |
2011-05-12 13:42:27.033 UTC
| 10 |
2020-05-04 23:16:08.803 UTC
|
2014-03-24 14:39:52.023 UTC
| null | 45,382 | null | 230,506 | null | 1 | 15 |
wpf|windowsformshost
| 24,095 |
<p>This "airspace" issue is <a href="http://bartwullems.blogspot.com/2010/11/wpf-vnext-microsoft-will-solve-airspace.html" rel="noreferrer">suppose to be fixed</a> in WPF vNext. There are a couple solutions out there, such as <a href="http://blogs.msdn.com/b/pantal/archive/2007/07/31/managed-directx-interop-with-wpf-part-2.aspx" rel="noreferrer">here</a>, <a href="http://jmorrill.hjtcentral.com/Home/tabid/428/EntryId/61/Over-coming-the-Interop-Airspace-Issue-in-WPF.aspx" rel="noreferrer">here</a>, and <a href="http://bartwullems.blogspot.com/2010/11/wpf-and-winforms-airspace-problem.html" rel="noreferrer">here</a>.</p>
<p>One way to do this is to host the WPF content in a transparent Popup or Window, which overlays the Interop content.</p>
|
5,728,558 |
Get the DOM path of the clicked <a>
|
<p>HTML</p>
<pre><code><body>
<div class="lol">
<a class="rightArrow" href="javascriptVoid:(0);" title"Next image">
</div>
</body>
</code></pre>
<p>Pseudo Code</p>
<pre><code>$(".rightArrow").click(function() {
rightArrowParents = this.dom(); //.dom(); is the pseudo function ... it should show the whole
alert(rightArrowParents);
});
</code></pre>
<p>Alert message would be:</p>
<p><strong>body div.lol a.rightArrow</strong></p>
<p>How can I get this with javascript/jquery?</p>
| 5,728,626 | 11 | 2 | null |
2011-04-20 10:00:56.847 UTC
| 11 |
2022-07-30 20:04:07.37 UTC
|
2015-01-26 11:52:31.78 UTC
| null | 106,224 | null | 497,060 | null | 1 | 28 |
javascript|jquery|html|dom|css-selectors
| 48,276 |
<p>Using jQuery, like this (followed by a solution that doesn't use jQuery except for the event; lots fewer function calls, if that's important):</p>
<pre><code>$(".rightArrow").click(function() {
var rightArrowParents = [];
$(this).parents().addBack().not('html').each(function() {
var entry = this.tagName.toLowerCase();
if (this.className) {
entry += "." + this.className.replace(/ /g, '.');
}
rightArrowParents.push(entry);
});
alert(rightArrowParents.join(" "));
return false;
});
</code></pre>
<p><strong>Live example:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".rightArrow").click(function() {
var rightArrowParents = [];
$(this).parents().addBack().not('html').each(function() {
var entry = this.tagName.toLowerCase();
if (this.className) {
entry += "." + this.className.replace(/ /g, '.');
}
rightArrowParents.push(entry);
});
alert(rightArrowParents.join(" "));
return false;
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lol multi">
<a href="#" class="rightArrow" title="Next image">Click here</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
<p>(In the live examples, I've updated the <code>class</code> attribute on the <code>div</code> to be <code>lol multi</code> to demonstrate handling multiple classes.)</p>
<p>That uses <a href="http://api.jquery.com/parents/" rel="noreferrer"><code>parents</code></a> to get the ancestors of the element that was clicked, removes the <code>html</code> element from that via <a href="http://api.jquery.com/not/" rel="noreferrer"><code>not</code></a> (since you started at <code>body</code>), then loops through creating entries for each parent and pushing them on an array. Then we use <a href="http://api.jquery.com/addBack" rel="noreferrer"><code>addBack</code></a> to add the <code>a</code> back into the set, which also changes the order of the set to what you wanted (<code>parents</code> is special, it gives you the parents in the reverse of the order you wanted, but then <code>addBAck</code> puts it back in DOM order). Then it uses <code>Array#join</code> to create the space-delimited string.</p>
<p>When creating the entry, if there's anything on <code>className</code> we replace spaces with <code>.</code> to support elements that have more than one class (<code><p class='foo bar'></code> has <code>className</code> = <code>"foo bar"</code>, so that entry ends up being <code>p.foo.bar</code>).</p>
<p>Just for completeness, this is one of those places where jQuery may be overkill, you can readily do this just by walking up the DOM:</p>
<pre><code>$(".rightArrow").click(function() {
var rightArrowParents = [],
elm,
entry;
for (elm = this; elm; elm = elm.parentNode) {
entry = elm.tagName.toLowerCase();
if (entry === "html") {
break;
}
if (elm.className) {
entry += "." + elm.className.replace(/ /g, '.');
}
rightArrowParents.push(entry);
}
rightArrowParents.reverse();
alert(rightArrowParents.join(" "));
return false;
});
</code></pre>
<p><strong>Live example:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".rightArrow").click(function() {
var rightArrowParents = [],
elm,
entry;
for (elm = this; elm; elm = elm.parentNode) {
entry = elm.tagName.toLowerCase();
if (entry === "html") {
break;
}
if (elm.className) {
entry += "." + elm.className.replace(/ /g, '.');
}
rightArrowParents.push(entry);
}
rightArrowParents.reverse();
alert(rightArrowParents.join(" "));
return false;
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="lol multi">
<a href="#" class="rightArrow" title="Next image">Click here</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
<p>There we just use the standard <a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1060184317" rel="noreferrer"><code>parentNode</code> property</a> of the element repeatedly to walk up the tree until either we run out of parents or we see the <code>html</code> element. Then we reverse our array (since it's backward to the output you wanted), and join it, and we're good to go.</p>
|
5,219,081 |
Eclipse error: No source available for ""
|
<p>Using Eclipse Helios in Mac OS X Leopard and debugging C++ code calling fsf gdb 7.1, the debugging stops at first line of main. Then after the first step I get</p>
<pre><code>No source available for ""
View disassembly
</code></pre>
<p>Why this error? Should I give additional options for compilation? Eclipse generated automatically the Makefile</p>
| 5,459,312 | 1 | 0 | null |
2011-03-07 11:25:03.8 UTC
| 1 |
2015-08-24 01:16:12.633 UTC
|
2015-08-24 01:16:12.633 UTC
| null | 1,677,912 | null | 171,546 | null | 1 | 6 |
eclipse|debugging|assembly
| 40,641 |
<p>I had the same problem and the following solved it:</p>
<p>Go to menu <code>Run->Debug Configurations...</code> and a dialogue window opens. On the left there should be selected your project name (say <em>MyProject</em> for example) under <code>C/C++ Application</code>. If not select it. Then on the right side, select the tab <code>main</code> and make sure that in the textbox under <code>C/C++ Application</code> reads: <em>Debug/MyProject</em>. Also check that <em>Debug</em> is selected in the dropdown box next to <code>Build Configuration:</code> below.</p>
<p>In my case instead of <em>Debug/MyProject</em>, it was <em>Release/MyProject</em>. I never understood why. Anyway...</p>
<p>Hope that helps</p>
|
670,015 |
NSTextField with "padding" on the right
|
<p>I am trying to get the "remaining chars notice" to show up within my rounded NSTextField and I got it with two NSTextFields with help of the Interface Builder and it already looks like that:</p>
<p><a href="http://jeenaparadies.net/t/s/Twittia-NSTextField1.png" rel="noreferrer">alt text http://jeenaparadies.net/t/s/Twittia-NSTextField1.png</a></p>
<p>But when I write a little bit more it looks like that:</p>
<p><a href="http://jeenaparadies.net/t/s/Twittia-NSTextField2.png" rel="noreferrer">alt text http://jeenaparadies.net/t/s/Twittia-NSTextField2.png</a></p>
<p>The only thing I could think of is to subclass NSTextField and do something with it so it does not draw text under the number but I have no idea how to begin and need really some help with it.</p>
| 670,739 | 1 | 0 | null |
2009-03-21 21:14:48.407 UTC
| 9 |
2009-03-22 09:10:16.177 UTC
| null | null | null |
Jeena
| 63,779 | null | 1 | 6 |
objective-c|cocoa|nstextfield
| 5,249 |
<p>The simplest way is probably to subclass <code>NSTextFieldCell</code> and override <code>-drawInteriorWithFrame:inView:</code> and <code>-selectWithFrame:inView:editor:delegate:start:length:</code>.</p>
<p>You'll need to decide how much space to allocate for your count and draw in the abbreviated space. Something like this example code should work although this hasn't been tested in a rounded text field.</p>
<p>You can find more information about subclassing <code>NSCell</code> in Apple's <a href="http://developer.apple.com/SampleCode/PhotoSearch/index.html" rel="noreferrer">PhotoSearch example code</a>.</p>
<pre><code>- (void)drawInteriorWithFrame:(NSRect)bounds inView:(NSView *)controlView {
NSRect titleRect = [self titleRectForBounds:bounds];
NSRect countRect = [self countAreaRectForBounds:bounds];
titleRect = NSInsetRect(titleRect, 2, 0);
NSAttributedString *title = [self attributedStringValue];
NSAttributedString *count = [self countAttributedString];
if (title)
[title drawInRect:titleRect];
[count drawInRect:countRect];
}
- (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength {
NSRect selectFrame = aRect;
NSRect countRect = [self countAreaRectForBounds:aRect];
selectFrame.size.width -= countRect.size.width + PADDING_AROUND_COUNT;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(__textChanged:) name:NSTextDidChangeNotification object:textObj];
[super selectWithFrame:selectFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
}
- (void)endEditing:(NSText *)editor {
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSTextDidChangeNotification object:editor];
[super endEditing:editor];
}
- (void)__textChanged:(NSNotification *)notif {
[[self controlView] setNeedsDisplay:YES];
}
</code></pre>
|
818,996 |
Abstract Types / Type Parameters in Scala
|
<p>I am trying to write some Scala code that needs to do something like:</p>
<pre><code>class Test[Type] {
def main {
SomeFunc classOf[Type]
val testVal: Type = new Type()
}
}
</code></pre>
<p>and it's failing. I'm obviously not understanding something about Scala generic parameters. Clearly, the misunderstanding is that in C++, templates essentially function like string substitutions, so new Type() will work as long as the class being passed in has a default constructor. However, in Scala, types are different kinds of objects. </p>
| 820,345 | 1 | 1 | null |
2009-05-04 06:33:27.147 UTC
| 10 |
2011-12-08 17:36:15.437 UTC
| null | null | null | null | 74,493 | null | 1 | 16 |
scala|types
| 4,605 |
<p>As you point out, C++ has templates. In short, C++ says "there is a Test for all types T such that Test compiles." That makes it easy to implicitly add constraints on T, but on the down side they're implicit and may be hard for a user of your class to understand without reading code.</p>
<p>Scala's parametric polymorphism (aka generics) work much more like ML, Haskell, Java, and C#. In Scala, when you write "class Test[T]" you are saying "for all T there exists a type Test[T]" without constraint. That's simpler to reason about formally, but it does mean that you have to be explicit about constraints. For instance, in Scala you can say "class Test[T <: Foo]" to say that T must be a subtype of Foo. </p>
<p>C# has a way to add a constraint to T regarding constructors, but unfortunately Scala does not.</p>
<p>There are a couple of ways to solve your problem in Scala. One is typesafe but a bt more verbose. The other is not typesafe.</p>
<p>The typesafe way looks like</p>
<pre><code>class Test[T](implicit val factory : () => T) {
val testVal = factory
}
</code></pre>
<p>Then you can have a body of factories for types useful in your system</p>
<pre><code>object Factories {
implicit def listfact[X]() = List[X]()
implicit def setfact[X]() = Set[X]()
// etc
}
import Factories._
val t = new Test[Set[String]]
</code></pre>
<p>If users of your library need their own factories then they can add their own equivalent of the Factories object. One advantage to this solution is that anything with a factory can be used, whether or not there's a no-arg constructor.</p>
<p>The not-so-typesafe way uses reflection and a feature in Scala called manifests which are a way to get around a Java constraint regarding type erasure</p>
<pre><code> class Test[T](implicit m : Manifest[T]) {
val testVal = m.erasure.newInstance().asInstanceOf[T]
}
</code></pre>
<p>With this version you still write </p>
<pre><code>class Foo
val t = new Test[Foo]
</code></pre>
<p>However, if there's no no-arg constructor available you get a runtime exception instead of a static type error</p>
<pre><code>scala> new Test[Set[String]]
java.lang.InstantiationException: scala.collection.immutable.Set
at java.lang.Class.newInstance0(Class.java:340)
</code></pre>
|
19,712,610 |
How to actually set up basic Titan + Rexster + Cassandra?
|
<p>I am trying to set up a completely basic Titan Rexster Cassandra instance, but I can't seem to break the code. I have tried a whole lot of things now to get it to work but I just can't seem to get it to work. No matter how much I read about it I am not able to set it up properly.</p>
<p>What I want is a Titan-rexster-cassandra instance running in embedded mode with a few indexes including elastic search. After all the stuff I have read it seems that this is what I should get when i download titan-server-0.4.0 and run the <code>bin/titan.sh start</code> command. An this also starts the server. However: When I try to add an index to this, nothing happens. When I try to populate it over RexPro nothing is added. </p>
<p>When I restart the server my graph is gone. It is no longer in the Rexster list of graphs when I go to <code>http://localhost:8182/graphs</code>. So it appears that my data does not persist, or at least disappears for rexster.</p>
<p>I feel like I have tried just about everything to get this to work:</p>
<ul>
<li>Changing the <code>.properties</code> to include the search-index like so: <code>storrage.index.search.backend=elasticsearch</code>...</li>
<li>Changing the <code>.properties</code> files (all of them) to use <code>cassandra</code>, <code>embeddedcassandra</code> and <code>cassandrathrift</code> for <code>storage.backend</code></li>
<li>Trying to start the server with properties as indicated in <a href="https://stackoverflow.com/questions/16397426/proper-way-of-starting-a-titan-graph-server-and-connect-with-gremlin">this question</a> to point to specific config files. </li>
<li>I have looked through the <code>titan.sh</code> file to see what actually happens, then gone to the config files indicated by these and had a look to see what goes on there, upon which I have tried a lot of things such as the above.</li>
</ul>
<p>I have struggled with this for well over a week, probably two or even more and I am starting to lose faith. I am considering going back to neo4j, but unfortunately I really need the scalability of Titan. However if I can't get it to work then it is no use. I feel like there might be some trivial but essential thing that I have not figured out, or forgot.</p>
<p>Do anyone know of a guide out there that brings you from absolute scratch (eg. starting a fresh VM or something), or close to it, to getting a titan-rexster-cassandra instance running with elastic search index? Or perhaps, if you are awesome, provide such a guide? I feel lost :(</p>
<hr>
<p><strong>Key Points:</strong></p>
<p>Ubuntu 12.04 (also tried 13.10. Same issue)</p>
<p>Titan 0.4.0</p>
<p><strong>Goal:</strong> To get persistance, index a vertex name property with Elastic search, and get edges with weight.</p>
<p>Connecting with ruby rexpro like this: </p>
<pre><code>require "rexpro" #the "rexpro" gem
rexpro_client = Rexpro::Client.new(host: 'the.ip.of.my.machine.running.rexster', port: 8184)
results = rexpro_client.execute("g.getClass()", graph_name: "graph").results
#=> returns the following: class com.thinkaurelius.titan.graphdb.database.StandardTitanGraph
</code></pre>
<hr>
<p>The steps I follow to create the problem where the DB does not persist:</p>
<ul>
<li>On WindowsAzure: Create a new small (1 core, 1.75GB ram) VM with <code>Ubuntu 12.04 LTS</code> with name <code>vmname</code> (or whatever).</li>
<li>Log on to this VM with SSH when it is ready (<code>ssh azureuser@vmname.cloudhost.net -p 22</code>)</li>
<li>Run: <code>sudo apt-get update</code></li>
<li>Run: <code>sudo apt-get install openjdk-7-jdk openjdk-7-jre p7zip-full</code></li>
<li>Run: <code>mkdir /home/azureuser/Downloads</code></li>
<li>Run: <code>wget -O /home/azureuser/Downloads/titan-server-0.4.0.zip "http://s3.thinkaurelius.com/downloads/titan/titan-server-0.4.0.zip"</code></li>
<li>Run: <code>cd /home/azureuser/Downloads/</code></li>
<li>Run: <code>7z x titan-server-0.4.0.zip</code></li>
<li>Run: <code>cd /home/azureuser/Downloads/titan-server-0.4.0</code></li>
<li>Run: <code>sudo bin/titan.sh -c cassandra-es start</code></li>
<li>Run: <code>sudo bin/rexster-console.sh</code></li>
<li>In rexster console, run: <code>g = rexster.getGraph("graph")</code>, returns <code>titangraph[cassandra:null]</code></li>
<li>CTRL-C out of rexster consloe</li>
<li>Run: <code>sudo bin/titan.sh stop</code></li>
<li>Run: <code>sudo bin/titan.sh -c cassandra-es start</code></li>
<li>Run: <code>sudo bin/rexster-console.sh</code></li>
<li>In rexster console, run: <code>g = rexster.getGraph("graph")</code>. <strong>Now this returns null, not a graph.</strong></li>
</ul>
<p>There appears to be some issues here when shutting down and starting up againt: </p>
<p><strong>On shutdown</strong></p>
<pre><code>[WARN] ShutdownManager - ShutdownListener JVM Shutdown Hook Remover threw an exception, continuing with shutdown
</code></pre>
<p><strong>On Startup #2</strong></p>
<pre><code>Starting Cassandra...
xss = -Dtitan.logdir=/home/azureuser/Downloads/titan-server-0.4.0/log -ea -javaagent:/home/azureuser/Downloads/titan-server-0.4.0/lib/jamm-0.2.5.jar -XX:+UseThreadPriorities -XX:ThreadPriorityPolicy=42 -Xms840M -Xmx840M -Xmn100M -XX:+HeapDumpOnOutOfMemoryError -Xss256k
Starting Titan + Rexster...
INFO 12:00:12,780 Logging initialized
INFO 12:00:12,805 JVM vendor/version: OpenJDK 64-Bit Server VM/1.7.0_25
INFO 12:00:12,806 Heap size: 870318080/870318080
INFO 12:00:12,806 Classpath: /home/azureuser/Downloads/titan-server-0.4.0/conf:/home/azureuser/Downloads/titan-server-0.4.0/build/classes/main:/home/azureuser/Downloads/titan-server-0.4.0/build/classes/thrift:/home/azureuser/Downloads/titan-server-0.4.0/lib/activation-...
INFO 12:00:13,397 JNA mlockall successful
INFO 12:00:13,419 Loading settings from file:/home/azureuser/Downloads/titan-server-0.4.0/conf/cassandra.yaml
INFO 12:00:14,093 DiskAccessMode 'auto' determined to be mmap, indexAccessMode is mmap
INFO 12:00:14,093 disk_failure_policy is stop
INFO 12:00:14,101 Global memtable threshold is enabled at 276MB
INFO 12:00:14,878 Initializing key cache with capacity of 41 MBs.
INFO 12:00:14,892 Scheduling key cache save to each 14400 seconds (going to save all keys).
INFO 12:00:14,894 Initializing row cache with capacity of 0 MBs and provider org.apache.cassandra.cache.SerializingCacheProvider
INFO 12:00:14,955 Scheduling row cache save to each 0 seconds (going to save all keys).
INFO 12:00:15,273 Opening db/cassandra/data/system/schema_keyspaces/system-schema_keyspaces-ib-2 (167 bytes)
INFO 12:00:15,347 Opening db/cassandra/data/system/schema_keyspaces/system-schema_keyspaces-ib-1 (264 bytes)
INFO 12:00:15,376 Opening db/cassandra/data/system/schema_columnfamilies/system-schema_columnfamilies-ib-11 (717 bytes)
INFO 12:00:15,387 Opening db/cassandra/data/system/schema_columnfamilies/system-schema_columnfamilies-ib-9 (6183 bytes)
INFO 12:00:15,392 Opening db/cassandra/data/system/schema_columnfamilies/system-schema_columnfamilies-ib-10 (687 bytes)
INFO 12:00:15,411 Opening db/cassandra/data/system/schema_columns/system-schema_columns-ib-2 (209 bytes)
INFO 12:00:15,416 Opening db/cassandra/data/system/schema_columns/system-schema_columns-ib-1 (3771 bytes)
INFO 12:00:15,450 Opening db/cassandra/data/system/local/system-local-ib-3 (109 bytes)
INFO 12:00:15,455 Opening db/cassandra/data/system/local/system-local-ib-2 (120 bytes)
INFO 12:00:15,521 Opening db/cassandra/data/system/local/system-local-ib-1 (356 bytes)
Processes forked. Setup may take some time.
Run bin/rexster-console.sh to connect.
azureuser@neugle:~/Downloads/titan-server-0.4.0$ INFO 12:00:16,705 completed pre-loading (8 keys) key cache.
INFO 12:00:16,777 Replaying db/cassandra/commitlog/CommitLog-2-1383479792488.log, db/cassandra/commitlog/CommitLog-2-1383479792489.log
INFO 12:00:16,802 Replaying db/cassandra/commitlog/CommitLog-2-1383479792488.log
INFO 12:00:17,178 Finished reading db/cassandra/commitlog/CommitLog-2-1383479792488.log
INFO 12:00:17,179 Replaying db/cassandra/commitlog/CommitLog-2-1383479792489.log
INFO 12:00:17,179 Finished reading db/cassandra/commitlog/CommitLog-2-1383479792489.log
INFO 12:00:17,191 Enqueuing flush of Memtable-local@1221155490(52/52 serialized/live bytes, 22 ops)
INFO 12:00:17,194 Writing Memtable-local@1221155490(52/52 serialized/live bytes, 22 ops)
INFO 12:00:17,204 Enqueuing flush of Memtable-users@1341189399(28/28 serialized/live bytes, 2 ops)
INFO 12:00:17,211 Enqueuing flush of Memtable-system_properties@1057472358(26/26 serialized/live bytes, 1 ops)
INFO 12:00:17,416 Completed flushing db/cassandra/data/system/local/system-local-ib-4-Data.db (84 bytes) for commitlog position ReplayPosition(segmentId=1383480016398, position=142)
INFO 12:00:17,480 Writing Memtable-users@1341189399(28/28 serialized/live bytes, 2 ops)
INFO 12:00:17,626 Completed flushing db/cassandra/data/system_auth/users/system_auth-users-ib-1-Data.db (64 bytes) for commitlog position ReplayPosition(segmentId=1383480016398, position=142)
INFO 12:00:17,630 Writing Memtable-system_properties@1057472358(26/26 serialized/live bytes, 1 ops)
INFO 12:00:17,776 Completed flushing db/cassandra/data/titan/system_properties/titan-system_properties-ib-1-Data.db (64 bytes) for commitlog position ReplayPosition(segmentId=1383480016398, position=142)
INFO 12:00:17,780 Log replay complete, 12 replayed mutations
INFO 12:00:17,787 Fixing timestamps of schema ColumnFamily schema_keyspaces...
INFO 12:00:17,864 Enqueuing flush of Memtable-local@1592659210(65/65 serialized/live bytes, 2 ops)
INFO 12:00:17,872 Writing Memtable-local@1592659210(65/65 serialized/live bytes, 2 ops)
[INFO] Application - .:Welcome to Rexster:.
INFO 12:00:18,027 Completed flushing db/cassandra/data/system/local/system-local-ib-5-Data.db (97 bytes) for commitlog position ReplayPosition(segmentId=1383480016398, position=297)
INFO 12:00:18,036 Enqueuing flush of Memtable-schema_keyspaces@1453195003(527/527 serialized/live bytes, 12 ops)
INFO 12:00:18,038 Writing Memtable-schema_keyspaces@1453195003(527/527 serialized/live bytes, 12 ops)
[INFO] RexsterProperties - Using [/home/azureuser/Downloads/titan-server-0.4.0/conf/rexster-cassandra-es.xml] as configuration source.
INFO 12:00:18,179 Completed flushing db/cassandra/data/system/schema_keyspaces/system-schema_keyspaces-ib-3-Data.db (257 bytes) for commitlog position ReplayPosition(segmentId=1383480016398, position=1227)
[INFO] Application - Rexster is watching [/home/azureuser/Downloads/titan-server-0.4.0/conf/rexster-cassandra-es.xml] for change.
[WARN] AstyanaxStoreManager - Couldn't set custom Thrift Frame Size property, use 'cassandrathrift' instead.
INFO 12:00:18,904 Cassandra version: 1.2.2
INFO 12:00:18,906 Thrift API version: 19.35.0
INFO 12:00:18,906 CQL supported versions: 2.0.0,3.0.1 (default: 3.0.1)
[INFO] ConnectionPoolMBeanManager - Registering mbean: com.netflix.MonitoredResources:type=ASTYANAX,name=ClusterTitanConnectionPool,ServiceType=connectionpool
[INFO] CountingConnectionPoolMonitor - AddHost: 127.0.0.1
INFO 12:00:19,087 Loading persisted ring state
INFO 12:00:19,097 Starting up server gossip
INFO 12:00:19,162 Enqueuing flush of Memtable-local@114523622(251/251 serialized/live bytes, 9 ops)
INFO 12:00:19,169 Writing Memtable-local@114523622(251/251 serialized/live bytes, 9 ops)
INFO 12:00:19,314 Completed flushing db/cassandra/data/system/local/system-local-ib-6-Data.db (238 bytes) for commitlog position ReplayPosition(segmentId=1383480016398, position=51470)
INFO 12:00:19,369 Compacting [SSTableReader(path='db/cassandra/data/system/local/system-local-ib-3-Data.db'), SSTableReader(path='db/cassandra/data/system/local/system-local-ib-2-Data.db'), SSTableReader(path='db/cassandra/data/system/local/system-local-ib-4-Data.db'), SSTableReader(path='db/cassandra/data/system/local/system-local-ib-1-Data.db'), SSTableReader(path='db/cassandra/data/system/local/system-local-ib-6-Data.db'), SSTableReader(path='db/cassandra/data/system/local/system-local-ib-5-Data.db')]
INFO 12:00:19,479 Starting Messaging Service on port 7000
INFO 12:00:19,585 Using saved token [7398637255000140098]
INFO 12:00:19,588 Enqueuing flush of Memtable-local@365797436(84/84 serialized/live bytes, 4 ops)
INFO 12:00:19,588 Writing Memtable-local@365797436(84/84 serialized/live bytes, 4 ops)
INFO 12:00:19,666 Compacted 6 sstables to [db/cassandra/data/system/local/system-local-ib-7,]. 1,004 bytes to 496 (~49% of original) in 286ms = 0.001654MB/s. 6 total rows, 1 unique. Row merge counts were {1:0, 2:0, 3:0, 4:0, 5:0, 6:1, }
INFO 12:00:19,796 Completed flushing db/cassandra/data/system/local/system-local-ib-8-Data.db (120 bytes) for commitlog position ReplayPosition(segmentId=1383480016398, position=51745)
INFO 12:00:19,810 Enqueuing flush of Memtable-local@1775610672(50/50 serialized/live bytes, 2 ops)
INFO 12:00:19,812 Writing Memtable-local@1775610672(50/50 serialized/live bytes, 2 ops)
INFO 12:00:19,967 Completed flushing db/cassandra/data/system/local/system-local-ib-9-Data.db (109 bytes) for commitlog position ReplayPosition(segmentId=1383480016398, position=51919)
INFO 12:00:20,088 Node localhost/127.0.0.1 state jump to normal
INFO 12:00:20,108 Startup completed! Now serving reads.
^C
azureuser@neugle:~/Downloads/titan-server-0.4.0$ sudo bin/rexster-console.sh[WARN] GraphConfigurationContainer - Could not load graph graph. Please check the XML configuration.
[WARN] GraphConfigurationContainer - GraphConfiguration could not be found or otherwise instantiated: [com.thinkaurelius.titan.tinkerpop.rexster.TitanGraphConfiguration]. Ensure that it is in Rexster's path.
com.tinkerpop.rexster.config.GraphConfigurationException: GraphConfiguration could not be found or otherwise instantiated: [com.thinkaurelius.titan.tinkerpop.rexster.TitanGraphConfiguration]. Ensure that it is in Rexster's path.
at com.tinkerpop.rexster.config.GraphConfigurationContainer.getGraphFromConfiguration(GraphConfigurationContainer.java:137)
at com.tinkerpop.rexster.config.GraphConfigurationContainer.<init>(GraphConfigurationContainer.java:54)
at com.tinkerpop.rexster.server.XmlRexsterApplication.reconfigure(XmlRexsterApplication.java:99)
at com.tinkerpop.rexster.server.XmlRexsterApplication.<init>(XmlRexsterApplication.java:47)
at com.tinkerpop.rexster.Application.<init>(Application.java:96)
at com.tinkerpop.rexster.Application.main(Application.java:188)
Caused by: java.lang.IllegalArgumentException: Could not instantiate implementation: com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager
at com.thinkaurelius.titan.diskstorage.Backend.instantiate(Backend.java:339)
at com.thinkaurelius.titan.diskstorage.Backend.getImplementationClass(Backend.java:351)
at com.thinkaurelius.titan.diskstorage.Backend.getStorageManager(Backend.java:294)
at com.thinkaurelius.titan.diskstorage.Backend.<init>(Backend.java:112)
at com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration.getBackend(GraphDatabaseConfiguration.java:682)
at com.thinkaurelius.titan.graphdb.database.StandardTitanGraph.<init>(StandardTitanGraph.java:72)
at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:40)
at com.thinkaurelius.titan.tinkerpop.rexster.TitanGraphConfiguration.configureGraphInstance(TitanGraphConfiguration.java:25)
at com.tinkerpop.rexster.config.GraphConfigurationContainer.getGraphFromConfiguration(GraphConfigurationContainer.java:119)
... 5 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.thinkaurelius.titan.diskstorage.Backend.instantiate(Backend.java:328)
... 13 more
Caused by: com.thinkaurelius.titan.diskstorage.TemporaryStorageException: Temporary failure in storage backend
at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.ensureKeyspaceExists(AstyanaxStoreManager.java:429)
at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.<init>(AstyanaxStoreManager.java:172)
... 18 more
Caused by: com.netflix.astyanax.connectionpool.exceptions.BadRequestException: BadRequestException: [host=127.0.0.1(127.0.0.1):9160, latency=42(60), attempts=1]InvalidRequestException(why:Keyspace names must be case-insensitively unique ("titan" conflicts with "titan"))
at com.netflix.astyanax.thrift.ThriftConverter.ToConnectionPoolException(ThriftConverter.java:159)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:65)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:28)
at com.netflix.astyanax.thrift.ThriftSyncConnectionFactoryImpl$ThriftConnection.execute(ThriftSyncConnectionFactoryImpl.java:151)
at com.netflix.astyanax.connectionpool.impl.AbstractExecuteWithFailoverImpl.tryOperation(AbstractExecuteWithFailoverImpl.java:69)
at com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool.executeWithFailover(AbstractHostPartitionConnectionPool.java:256)
at com.netflix.astyanax.thrift.ThriftClusterImpl.executeSchemaChangeOperation(ThriftClusterImpl.java:146)
at com.netflix.astyanax.thrift.ThriftClusterImpl.addKeyspace(ThriftClusterImpl.java:246)
at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.ensureKeyspaceExists(AstyanaxStoreManager.java:424)
... 19 more
Caused by: InvalidRequestException(why:Keyspace names must be case-insensitively unique ("titan" conflicts with "titan"))
at org.apache.cassandra.thrift.Cassandra$system_add_keyspace_result.read(Cassandra.java:33158)
at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:78)
at org.apache.cassandra.thrift.Cassandra$Client.recv_system_add_keyspace(Cassandra.java:1408)
at org.apache.cassandra.thrift.Cassandra$Client.system_add_keyspace(Cassandra.java:1395)
at com.netflix.astyanax.thrift.ThriftClusterImpl$9.internalExecute(ThriftClusterImpl.java:250)
at com.netflix.astyanax.thrift.ThriftClusterImpl$9.internalExecute(ThriftClusterImpl.java:247)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:60)
... 26 more
[WARN] GraphConfigurationContainer - Could not instantiate implementation: com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager
java.lang.IllegalArgumentException: Could not instantiate implementation: com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager
at com.thinkaurelius.titan.diskstorage.Backend.instantiate(Backend.java:339)
at com.thinkaurelius.titan.diskstorage.Backend.getImplementationClass(Backend.java:351)
at com.thinkaurelius.titan.diskstorage.Backend.getStorageManager(Backend.java:294)
at com.thinkaurelius.titan.diskstorage.Backend.<init>(Backend.java:112)
at com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration.getBackend(GraphDatabaseConfiguration.java:682)
at com.thinkaurelius.titan.graphdb.database.StandardTitanGraph.<init>(StandardTitanGraph.java:72)
at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:40)
at com.thinkaurelius.titan.tinkerpop.rexster.TitanGraphConfiguration.configureGraphInstance(TitanGraphConfiguration.java:25)
at com.tinkerpop.rexster.config.GraphConfigurationContainer.getGraphFromConfiguration(GraphConfigurationContainer.java:119)
at com.tinkerpop.rexster.config.GraphConfigurationContainer.<init>(GraphConfigurationContainer.java:54)
at com.tinkerpop.rexster.server.XmlRexsterApplication.reconfigure(XmlRexsterApplication.java:99)
at com.tinkerpop.rexster.server.XmlRexsterApplication.<init>(XmlRexsterApplication.java:47)
at com.tinkerpop.rexster.Application.<init>(Application.java:96)
at com.tinkerpop.rexster.Application.main(Application.java:188)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.thinkaurelius.titan.diskstorage.Backend.instantiate(Backend.java:328)
... 13 more
Caused by: com.thinkaurelius.titan.diskstorage.TemporaryStorageException: Temporary failure in storage backend
at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.ensureKeyspaceExists(AstyanaxStoreManager.java:429)
at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.<init>(AstyanaxStoreManager.java:172)
... 18 more
Caused by: com.netflix.astyanax.connectionpool.exceptions.BadRequestException: BadRequestException: [host=127.0.0.1(127.0.0.1):9160, latency=42(60), attempts=1]InvalidRequestException(why:Keyspace names must be case-insensitively unique ("titan" conflicts with "titan"))
at com.netflix.astyanax.thrift.ThriftConverter.ToConnectionPoolException(ThriftConverter.java:159)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:65)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:28)
at com.netflix.astyanax.thrift.ThriftSyncConnectionFactoryImpl$ThriftConnection.execute(ThriftSyncConnectionFactoryImpl.java:151)
at com.netflix.astyanax.connectionpool.impl.AbstractExecuteWithFailoverImpl.tryOperation(AbstractExecuteWithFailoverImpl.java:69)
at com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool.executeWithFailover(AbstractHostPartitionConnectionPool.java:256)
at com.netflix.astyanax.thrift.ThriftClusterImpl.executeSchemaChangeOperation(ThriftClusterImpl.java:146)
at com.netflix.astyanax.thrift.ThriftClusterImpl.addKeyspace(ThriftClusterImpl.java:246)
at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.ensureKeyspaceExists(AstyanaxStoreManager.java:424)
... 19 more
Caused by: InvalidRequestException(why:Keyspace names must be case-insensitively unique ("titan" conflicts with "titan"))
at org.apache.cassandra.thrift.Cassandra$system_add_keyspace_result.read(Cassandra.java:33158)
at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:78)
at org.apache.cassandra.thrift.Cassandra$Client.recv_system_add_keyspace(Cassandra.java:1408)
at org.apache.cassandra.thrift.Cassandra$Client.system_add_keyspace(Cassandra.java:1395)
at com.netflix.astyanax.thrift.ThriftClusterImpl$9.internalExecute(ThriftClusterImpl.java:250)
at com.netflix.astyanax.thrift.ThriftClusterImpl$9.internalExecute(ThriftClusterImpl.java:247)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:60)
... 26 more
[INFO] HttpReporterConfig - Configured HTTP Metric Reporter.
[INFO] ConsoleReporterConfig - Configured Console Metric Reporter.
[INFO] HttpRexsterServer - HTTP/REST thread pool configuration: kernal[4 / 4] worker[8 / 8]
[INFO] HttpRexsterServer - Using org.glassfish.grizzly.strategies.LeaderFollowerNIOStrategy IOStrategy for HTTP/REST.
[INFO] HttpRexsterServer - Rexster Server running on: [http://localhost:8182]
[INFO] RexProRexsterServer - Using org.glassfish.grizzly.strategies.LeaderFollowerNIOStrategy IOStrategy for RexPro.
[INFO] RexProRexsterServer - RexPro thread pool configuration: kernal[4 / 4] worker[8 / 8]
[INFO] RexProRexsterServer - Rexster configured with no security.
[INFO] RexProRexsterServer - RexPro Server bound to [0.0.0.0:8184]
[INFO] ShutdownManager$ShutdownSocketListener - Bound shutdown socket to /127.0.0.1:8183. Starting listener thread for shutdown requests.
^C
</code></pre>
| 19,718,418 | 2 | 0 | null |
2013-10-31 17:05:01.13 UTC
| 12 |
2016-11-28 22:19:50.513 UTC
|
2017-05-23 10:30:20.08 UTC
| null | -1 | null | 741,850 | null | 1 | 11 |
cassandra|titan|rexster
| 10,051 |
<p>As a first note, <code>embeddedcassandra</code> is no longer what you want in Titan 0.4.0. You can read more about that <a href="https://groups.google.com/forum/#!searchin/aureliusgraphs/embeddedcassandra/aureliusgraphs/EasJTTkDtfY/sPcrWLT9JKsJ">here</a>. In the Titan Server distribution for 0.4.0 cassandra and rexster run in separate JVMs and should generally run out-of-the-box from the distribution. </p>
<p>Also note, that I would say it is recommended to create types/indices by way of the Gremlin Console directly. I like being "close to the graph" when working with <code>TypeMaker</code>. You can read more about such production implementation patterns <a href="http://thinkaurelius.com/2013/07/25/developing-a-domain-specific-language-in-gremlin/">here</a>.</p>
<p>As for your specific problem, your issue helped uncover a hole in the documentation (which has since been <a href="https://github.com/thinkaurelius/titan/wiki/Rexster-Graph-Server#getting-started-quickly-with-titan-serverzip">remedied</a>). To ensure that elasticsearch gets started with Titan Server make sure that you do:</p>
<pre><code>bin/titan.sh -c cassandra-es start
</code></pre>
<p>At this point you can connect via Rexster to construct and query elasticsearch indices. Here's an example from Rexster Console:</p>
<pre><code>rexster[groovy]> g = rexster.getGraph("graph")
==>titangraph[cassandra:null]
rexster[groovy]> g.makeKey("name").dataType(String.class).indexed("search",Vertex.class).make()
==>v[74]
rexster[groovy]> g.commit()
==>null
rexster[groovy]> g.addVertex([name:'marko'])
==>v[4]
rexster[groovy]> g.addVertex([name:'stephen'])
==>v[8]
rexster[groovy]> g.commit()
==>null
rexster[groovy]> g.V.has('name',PREFIX,'mar')
==>v[4]
</code></pre>
<p>Note that by starting Titan Server in this mode, elasticsearch is running in <a href="https://github.com/thinkaurelius/titan/wiki/Using-Elastic-Search#elasticsearch-embedded-configuration">embedded mode</a> to the Titan instance started by Rexster which means that:</p>
<blockquote>
<p>Elasticsearch will not be accessible from outside of this particular
Titan instance, i.e., remote connections will not be possible</p>
</blockquote>
<p>So if you are trying to connect via a Titan Gremlin Console, I don't believe it will work. Connections have to run through Rexster.</p>
|
45,273,731 |
Binning a column with pandas
|
<p>I have a data frame column with numeric values:</p>
<pre><code>df['percentage'].head()
46.5
44.2
100.0
42.12
</code></pre>
<p>I want to see the column as <a href="https://en.wikipedia.org/wiki/Data_binning" rel="noreferrer">bin counts</a>:</p>
<pre><code>bins = [0, 1, 5, 10, 25, 50, 100]
</code></pre>
<p>How can I get the result as bins with their <em>value counts</em>?</p>
<pre><code>[0, 1] bin amount
[1, 5] etc
[5, 10] etc
...
</code></pre>
| 45,273,750 | 3 | 0 | null |
2017-07-24 06:13:08.7 UTC
| 54 |
2022-08-25 17:26:25.943 UTC
|
2022-08-25 17:26:25.943 UTC
| null | 7,758,804 | null | 140,100 | null | 1 | 170 |
python|pandas|numpy|dataframe|binning
| 205,597 |
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="noreferrer"><code>pandas.cut</code></a>:</p>
<pre><code>bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
percentage binned
0 46.50 (25, 50]
1 44.20 (25, 50]
2 100.00 (50, 100]
3 42.12 (25, 50]
</code></pre>
<hr />
<pre><code>bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
</code></pre>
<p>Or <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="noreferrer"><code>numpy.searchsorted</code></a>:</p>
<pre><code>bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
</code></pre>
<hr />
<p>...and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="noreferrer"><code>value_counts</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="noreferrer"><code>groupby</code></a> and aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="noreferrer"><code>size</code></a>:</p>
<pre><code>s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50] 3
(50, 100] 1
(10, 25] 0
(5, 10] 0
(1, 5] 0
(0, 1] 0
Name: percentage, dtype: int64
</code></pre>
<hr />
<pre><code>s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1] 0
(1, 5] 0
(5, 10] 0
(10, 25] 0
(25, 50] 3
(50, 100] 1
dtype: int64
</code></pre>
<p>By default <code>cut</code> returns <code>categorical</code>.</p>
<p><code>Series</code> methods like <code>Series.value_counts()</code> will use all categories, even if some categories are not present in the data, <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html#operations" rel="noreferrer">operations in categorical</a>.</p>
|
45,511,956 |
Remove a named volume with docker-compose?
|
<p>If I have a docker-compose file like:</p>
<pre class="lang-yml prettyprint-override"><code>version: "3"
services:
postgres:
image: postgres:9.4
volumes:
- db-data:/var/lib/db
volumes:
db-data:
</code></pre>
<p>... then doing <code>docker-compose up</code> creates a named volume for <code>db-data</code>. Is there a way to remove this volume via <code>docker-compose</code>? If it were an anonymous volume, then <code>docker-compose rm -v postgres</code> would do the trick. But as it stands, I don't know how to remove the <code>db-data</code> volume without reverting to <code>docker</code> commands. It feels like this should be possible from within the <code>docker-compose</code> CLI. Am I missing something?</p>
| 45,512,667 | 4 | 0 | null |
2017-08-04 16:52:41.907 UTC
| 13 |
2022-01-21 21:14:07.587 UTC
|
2021-11-12 18:28:35.483 UTC
| null | 8,172,439 | null | 318,206 | null | 1 | 102 |
postgresql|docker|docker-compose|volumes|docker-named-volume
| 55,889 |
<pre><code>docker-compose down -v
</code></pre>
<p>removes all volumes attached. See the <a href="https://docs.docker.com/compose/reference/down/" rel="noreferrer">docs</a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.