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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15,479,928 | Why is the order in dictionaries and sets arbitrary? | <p>I don't understand how looping over a dictionary or set in python is done by 'arbitrary' order.</p>
<p>I mean, it's a programming language so everything in the language must be 100% determined, correct? Python must have some kind of algorithm that decides which part of the dictionary or set is chosen, 1st, second and so on. </p>
<p>What am I missing?</p> | 15,479,974 | 5 | 2 | null | 2013-03-18 14:59:06.22 UTC | 54 | 2020-04-26 12:29:07.227 UTC | 2019-01-24 20:06:58.92 UTC | null | 2,370,483 | user1971598 | null | null | 1 | 163 | python|dictionary|set|python-internals | 20,515 | <blockquote>
<p><strong>Note:</strong> This answer was written before the implementation of the <code>dict</code> type changed, in Python 3.6. Most of the implementation details in this answer still apply, but the listing order of keys in <em>dictionaries</em> is no longer determined by hash values. The set implementation remains unchanged.</p>
</blockquote>
<p>The order is not arbitrary, but depends on the insertion and deletion history of the dictionary or set, as well as on the specific Python implementation. For the remainder of this answer, for 'dictionary', you can also read 'set'; sets are implemented as dictionaries with just keys and no values.</p>
<p>Keys are hashed, and hash values are assigned to slots in a dynamic table (it can grow or shrink based on needs). And that mapping process can lead to collisions, meaning that a key will have to be slotted in a <em>next</em> slot based on what is already there.</p>
<p>Listing the contents loops over the slots, and so keys are listed in the order they <em>currently</em> reside in the table.</p>
<p>Take the keys <code>'foo'</code> and <code>'bar'</code>, for example, and lets assume the table size is 8 slots. In Python 2.7, <code>hash('foo')</code> is <code>-4177197833195190597</code>, <code>hash('bar')</code> is <code>327024216814240868</code>. Modulo 8, that means these two keys are slotted in slots 3 and 4 then:</p>
<pre><code>>>> hash('foo')
-4177197833195190597
>>> hash('foo') % 8
3
>>> hash('bar')
327024216814240868
>>> hash('bar') % 8
4
</code></pre>
<p>This informs their listing order:</p>
<pre><code>>>> {'bar': None, 'foo': None}
{'foo': None, 'bar': None}
</code></pre>
<p>All slots except 3 and 4 are empty, looping over the table first lists slot 3, then slot 4, so <code>'foo'</code> is listed before <code>'bar'</code>.</p>
<p><code>bar</code> and <code>baz</code>, however, have hash values that are exactly 8 apart and thus map to the exact same slot, <code>4</code>:</p>
<pre><code>>>> hash('bar')
327024216814240868
>>> hash('baz')
327024216814240876
>>> hash('bar') % 8
4
>>> hash('baz') % 8
4
</code></pre>
<p>Their order now depends on which key was slotted first; the second key will have to be moved to a next slot:</p>
<pre><code>>>> {'baz': None, 'bar': None}
{'bar': None, 'baz': None}
>>> {'bar': None, 'baz': None}
{'baz': None, 'bar': None}
</code></pre>
<p>The table order differs here, because one or the other key was slotted first.</p>
<p>The technical name for the underlying structure used by CPython (the most commonly used Python implemenation) is a <a href="http://en.wikipedia.org/wiki/hash_table" rel="noreferrer">hash table</a>, one that uses open addressing. If you are curious, and understand C well enough, take a look at the <a href="http://hg.python.org/cpython/file/tip/Objects/dictobject.c" rel="noreferrer">C implementation</a> for all the (well documented) details. You could also watch this <a href="http://pyvideo.org/video/276/the-mighty-dictionary-55" rel="noreferrer">Pycon 2010 presentation by Brandon Rhodes</a> about how CPython <code>dict</code> works, or pick up a copy of <a href="http://shop.oreilly.com/product/9780596510046.do" rel="noreferrer">Beautiful Code</a>, which includes a chapter on the implementation written by Andrew Kuchling.</p>
<p>Note that as of Python 3.3, a random hash seed is used as well, making hash collisions unpredictable to prevent certain types of denial of service (where an attacker renders a Python server unresponsive by causing mass hash collisions). This means that the order of a given dictionary or set is then <em>also</em> dependent on the random hash seed for the current Python invocation.</p>
<p>Other implementations are free to use a different structure for dictionaries, as long as they satisfy the documented Python interface for them, but I believe that all implementations so far use a variation of the hash table.</p>
<p>CPython 3.6 introduces a <em>new</em> <code>dict</code> implementation that maintains insertion order, and is faster and more memory efficient to boot. Rather than keep a large sparse table where each row references the stored hash value, and the key and value objects, the new implementation adds a smaller hash <em>array</em> that only references indices in a separate 'dense' table (one that only contains as many rows as there are actual key-value pairs), and it is the dense table that happens to list the contained items in order. See the <a href="https://mail.python.org/pipermail/python-dev/2012-December/123028.html" rel="noreferrer">proposal to Python-Dev for more details</a>. Note that in Python 3.6 this is considered an <em>implementation detail</em>, Python-the-language does not specify that other implementations have to retain order. This changed in Python 3.7, where this detail was <a href="https://mail.python.org/pipermail/python-dev/2017-December/151283.html" rel="noreferrer">elevated to be a <em>language specification</em></a>; for any implementation to be properly compatible with Python 3.7 or newer it <strong>must</strong> copy this order-preserving behaviour. And to be explicit: this change doesn't apply to sets, as sets already have a 'small' hash structure.</p>
<p>Python 2.7 and newer also provides an <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="noreferrer"><code>OrderedDict</code> class</a>, a subclass of <code>dict</code> that adds an additional data structure to record key order. At the price of some speed and extra memory, this class remembers in what order you inserted keys; listing keys, values or items will then do so in that order. It uses a doubly-linked list stored in an additional dictionary to keep the order up-to-date efficiently. See the <a href="https://mail.python.org/pipermail/python-dev/2012-December/123028.html" rel="noreferrer">post by Raymond Hettinger outlining the idea</a>. <code>OrderedDict</code> objects have other advantages, such as being <em>re-orderable</em>.</p>
<p>If you wanted an ordered set, you can install the <a href="https://pypi.python.org/pypi/oset" rel="noreferrer"><code>oset</code> package</a>; it works on Python 2.5 and up.</p> |
19,798,742 | Change value attribute by class via JavaScript | <p>I have the following HTML:</p>
<pre><code><input class="vertical-tabs-active-tab" type="hidden" value="account" name="tabs__active_tab">
</code></pre>
<p>I need JavaScript that will change the value of "account" to "yolo".</p>
<p>I thought I could do this:</p>
<pre><code>document.getElementsByClassName('vertical-tabs-active-tab').setAttribute("value", "yolo");
</code></pre>
<p>But that produces an error of: </p>
<pre><code>document.getElementsByClassName(...).setAttribute is not a function
</code></pre>
<p>I'm not able to add an "id" to input, I have to change the value based on class.</p> | 19,798,792 | 3 | 9 | null | 2013-11-05 20:53:08.783 UTC | 3 | 2017-05-12 23:57:27.987 UTC | 2017-05-12 23:57:27.987 UTC | null | 4,076,315 | null | 2,957,962 | null | 1 | 9 | javascript|html|setattribute|getelementsbyclassname | 56,296 | <pre><code>document.getElementsByClassName('vertical-tabs-active-tab')[0].setAttribute("value", "yolo");
</code></pre>
<p><code>document.getElementsByClassName</code> returns an array of elements, specify the index of the element you wish to change.</p> |
4,897,844 | Is sizeof(bool) defined in the C++ language standard? | <p>I can't find an answer in the standard documentation. Does the C++ language standard require <code>sizeof(bool)</code> to always be 1 (for 1 byte), or is this size implementation-defined?</p> | 4,897,859 | 4 | 0 | null | 2011-02-04 12:15:30.123 UTC | 18 | 2019-01-31 00:15:06.877 UTC | 2019-01-30 22:45:38.333 UTC | null | 1,593,077 | null | 547,231 | null | 1 | 133 | c++|boolean|sizeof|implementation-defined-behavior | 99,341 | <p><code>sizeof(bool)</code> is implementation defined, and the standard puts notable emphasis on this fact.</p>
<p>§5.3.3/1, abridged:</p>
<blockquote>
<p><code>sizeof(char)</code>, <code>sizeof(signed char)</code> and <code>sizeof(unsigned char)</code> are 1; the result of <code>sizeof</code> applied to any other fundamental type is implementation-defined. [Note: in particular, <code>sizeof(bool)</code> and <code>sizeof(wchar_t)</code> are implementation-defined.<sup>69)</sup>]</p>
</blockquote>
<p>Footnote 69):</p>
<blockquote>
<p><code>sizeof(bool)</code> is not required to be 1.</p>
</blockquote> |
5,579,073 | javac: java.lang.OutOfMemoryError when running ant from Eclipse | <p>I have given loads of memory to eclipse in the ini file but its still not using anything more than 300mb which i can see in the task manager.</p>
<pre><code> [javac] The system is out of resources.
[javac] Consult the following stack trace for details.
[javac] java.lang.OutOfMemoryError: Java heap space
[javac] at com.sun.tools.javac.comp.Attr.selectSym(Attr.java:1938)
[javac] at com.sun.tools.javac.comp.Attr.visitSelect(Attr.java:1835)
[javac] at com.sun.tools.javac.tree.JCTree$JCFieldAccess.accept(JCTree.java:1522)
[javac] at com.sun.tools.javac.comp.Attr.attribTree(Attr.java:360)
[javac] at com.sun.tools.javac.comp.Attr.attribExpr(Attr.java:377)
[javac] at com.sun.tools.javac.comp.Annotate.enterAttributeValue(Annotate.java:190)
[javac] at com.sun.tools.javac.comp.Annotate.enterAnnotation(Annotate.java:167)
[javac] at com.sun.tools.javac.comp.MemberEnter.enterAnnotations(MemberEnter.java:743)
[javac] at com.sun.tools.javac.comp.MemberEnter.access$300(MemberEnter.java:42)
[javac] at com.sun.tools.javac.comp.MemberEnter$5.enterAnnotation(MemberEnter.java:711)
[javac] at com.sun.tools.javac.comp.Annotate.flush(Annotate.java:95)
[javac] at com.sun.tools.javac.comp.Annotate.enterDone(Annotate.java:87)
[javac] at com.sun.tools.javac.comp.Enter.complete(Enter.java:485)
[javac] at com.sun.tools.javac.comp.Enter.main(Enter.java:442)
[javac] at com.sun.tools.javac.main.JavaCompiler.enterTrees(JavaCompiler.java:819)
[javac] at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:727)
[javac] at com.sun.tools.javac.main.Main.compile(Main.java:353)
[javac] at com.sun.tools.javac.main.Main.compile(Main.java:279)
[javac] at com.sun.tools.javac.main.Main.compile(Main.java:270)
[javac] at com.sun.tools.javac.Main.compile(Main.java:69)
[javac] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[javac] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[javac] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javac] at java.lang.reflect.Method.invoke(Method.java:597)
[javac] at org.apache.tools.ant.taskdefs.compilers.Javac13.execute(Javac13.java:56)
[javac] at org.apache.tools.ant.taskdefs.Javac.compile(Javac.java:1065)
[javac] at org.apache.tools.ant.taskdefs.Javac.execute(Javac.java:882)
[javac] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
[javac] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
[javac] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javac] at java.lang.reflect.Method.invoke(Method.java:597)
[javac] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
</code></pre>
<p>this is my ini file which i have. </p>
<pre><code>--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
512M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize1024m
--vm
C:\Program Files\Java\jdk1.6.0_24\bin\javaw.exe -vmargs -Xms512m -Xmx1024m
</code></pre>
<p>I have no idea why it wont use the memory I am giving it. Do i need to do anything else to change the heap size?</p>
<p>Thanks</p> | 5,579,224 | 5 | 1 | null | 2011-04-07 09:44:01.55 UTC | 3 | 2014-02-21 20:57:17.837 UTC | 2014-02-21 20:57:17.837 UTC | null | 1,684,569 | null | 696,523 | null | 1 | 12 | java|eclipse | 41,163 | <p>Not Eclipse is running out of memory, but ant. Ant is run as an external tool from eclipse, so it does not inherit the VM settings you are using for eclipse. You can set the options for it in the external tool run configuration. Go to Run -> External Tools -> External Tool Configurations... Then under "Ant Builds" you have to look up your ant build, and you can set the vm arguments in the JRE tab.</p> |
5,040,920 | Converting from signed char to unsigned char and back again? | <p>I'm working with JNI and have an array of type jbyte, where jbyte is represented as an signed char i.e. ranging from -128 to 127. The jbytes represent image pixels. For image processing, we usually want pixel components to range from 0 to 255. I therefore want to convert the jbyte value to the range 0 to 255 (i.e. the same range as unsigned char), do some calculations on the value and then store the result as a jbyte again.</p>
<p>How can I do these conversion safely? </p>
<p>I managed to get this code to work, where a pixel value is incremented by 30 but clamped to the value 255, but I don't understand if it's safe or portable:</p>
<pre><code> #define CLAMP255(v) (v > 255 ? 255 : (v < 0 ? 0 : v))
jbyte pixel = ...
pixel = CLAMP_255((unsigned char)pixel + 30);
</code></pre>
<p>I'm interested to know how to do this in both C and C++.</p> | 5,042,335 | 5 | 1 | null | 2011-02-18 11:47:28.38 UTC | 42 | 2017-09-14 02:20:40.15 UTC | 2011-02-18 11:58:32.317 UTC | null | 580,100 | null | 580,100 | null | 1 | 68 | c++|c|java-native-interface | 130,897 | <p>This is one of the reasons why C++ introduced the new cast style, which includes <code>static_cast</code> and <code>reinterpret_cast</code></p>
<p>There's two things you can mean by saying conversion from signed to unsigned, you might mean that you wish the unsigned variable to contain the value of the signed variable modulo the maximum value of your unsigned type + 1. That is if your signed char has a value of -128 then <code>CHAR_MAX+1</code> is added for a value of 128 and if it has a value of -1, then <code>CHAR_MAX+1</code> is added for a value of 255, this is what is done by static_cast. On the other hand you might mean to interpret the bit value of the memory referenced by some variable to be interpreted as an unsigned byte, regardless of the signed integer representation used on the system, i.e. if it has bit value <code>0b10000000</code> it should evaluate to value 128, and 255 for bit value <code>0b11111111</code>, this is accomplished with reinterpret_cast.</p>
<p>Now, for the two's complement representation this happens to be exactly the same thing, since -128 is represented as <code>0b10000000</code> and -1 is represented as <code>0b11111111</code> and likewise for all in between. However other computers (usually older architectures) may use different signed representation such as sign-and-magnitude or ones' complement. In ones' complement the <code>0b10000000</code> bitvalue would not be -128, but -127, so a static cast to unsigned char would make this 129, while a reinterpret_cast would make this 128. Additionally in ones' complement the <code>0b11111111</code> bitvalue would not be -1, but -0, (yes this value exists in ones' complement,) and would be converted to a value of 0 with a static_cast, but a value of 255 with a reinterpret_cast. Note that in the case of ones' complement the unsigned value of 128 can actually not be represented in a signed char, since it ranges from -127 to 127, due to the -0 value.</p>
<p>I have to say that the vast majority of computers will be using two's complement making the whole issue moot for just about anywhere your code will ever run. You will likely only ever see systems with anything other than two's complement in very old architectures, think '60s timeframe.</p>
<p>The syntax boils down to the following:</p>
<pre><code>signed char x = -100;
unsigned char y;
y = (unsigned char)x; // C static
y = *(unsigned char*)(&x); // C reinterpret
y = static_cast<unsigned char>(x); // C++ static
y = reinterpret_cast<unsigned char&>(x); // C++ reinterpret
</code></pre>
<p>To do this in a nice C++ way with arrays:</p>
<pre><code>jbyte memory_buffer[nr_pixels];
unsigned char* pixels = reinterpret_cast<unsigned char*>(memory_buffer);
</code></pre>
<p>or the C way:</p>
<pre><code>unsigned char* pixels = (unsigned char*)memory_buffer;
</code></pre> |
5,012,516 | Create counter within consecutive runs of certain values | <p>I have an hourly value. I want to count how many consecutive hours the value has been zero since the last time it was not zero. This is an easy job for a spreadsheet or for loop, but I am hoping for a snappy vectorized one-liner to accomplish the task.</p>
<pre><code>x <- c(1, 0, 1, 0, 0, 0, 1, 1, 0, 0)
df <- data.frame(x, zcount = NA)
df$zcount[1] <- ifelse(df$x[1] == 0, 1, 0)
for(i in 2:nrow(df))
df$zcount[i] <- ifelse(df$x[i] == 0, df$zcount[i - 1] + 1, 0)
</code></pre>
<p>Desired output:</p>
<pre><code>R> df
x zcount
1 1 0
2 0 1
3 1 0
4 0 1
5 0 2
6 0 3
7 1 0
8 1 0
9 0 1
10 0 2
</code></pre> | 5,016,069 | 6 | 0 | null | 2011-02-16 04:22:52.507 UTC | 17 | 2021-07-06 21:54:24.787 UTC | 2018-10-31 22:53:09.523 UTC | null | 1,851,712 | null | 573,546 | null | 1 | 18 | r | 13,625 | <p>Here's a way, building on Joshua's <code>rle</code> approach: (EDITED to use <code>seq_len</code> and <code>lapply</code> as per Marek's suggestion)</p>
<pre><code>> (!x) * unlist(lapply(rle(x)$lengths, seq_len))
[1] 0 1 0 1 2 3 0 0 1 2
</code></pre>
<p><strong>UPDATE</strong>. Just for kicks, here's another way to do it, around 5 times faster:</p>
<pre><code>cumul_zeros <- function(x) {
x <- !x
rl <- rle(x)
len <- rl$lengths
v <- rl$values
cumLen <- cumsum(len)
z <- x
# replace the 0 at the end of each zero-block in z by the
# negative of the length of the preceding 1-block....
iDrops <- c(0, diff(v)) < 0
z[ cumLen[ iDrops ] ] <- -len[ c(iDrops[-1],FALSE) ]
# ... to ensure that the cumsum below does the right thing.
# We zap the cumsum with x so only the cumsums for the 1-blocks survive:
x*cumsum(z)
}
</code></pre>
<p>Try an example:</p>
<pre><code>> cumul_zeros(c(1,1,1,0,0,0,0,0,1,1,1,0,0,1,1))
[1] 0 0 0 1 2 3 4 5 0 0 0 1 2 0 0
</code></pre>
<p>Now compare times on a million-length vector:</p>
<pre><code>> x <- sample(0:1, 1000000,T)
> system.time( z <- cumul_zeros(x))
user system elapsed
0.15 0.00 0.14
> system.time( z <- (!x) * unlist( lapply( rle(x)$lengths, seq_len)))
user system elapsed
0.75 0.00 0.75
</code></pre>
<p>Moral of the story: one-liners are nicer and easier to understand, but not always the fastest!</p> |
5,059,897 | Problem running MVC3 app in IIS 7 | <p>I am having a problem getting a MVC 3 project running in IIS7 on a computer running Windows 7 Home-64 bit. Here is what I did.</p>
<ol>
<li>Installed IIS 7.</li>
<li>Accessed the server and got the IIS welcome page.</li>
<li>Created a directory named d:\MySite and copied the MVC application to it. (The MVC app is just the standard app that is created when you create a new MVC3 project in visual studio. It just displays a home page and an account logon page. It runs fine inside the Visual Studio development server and I also copied it out to my hosting site and it works fine there)</li>
<li>Started IIS management console.</li>
<li>Stopped the default site.</li>
<li>Added a new site named "MySite" with a physical directory of "d:\Mysite"</li>
<li>Changed the application pool named MySite to use .Net Framework 4.0, Integrated pipeline</li>
</ol>
<p>When I access the site in the browser I get a list of the files in the d:\MySite directory. It is as if IIS is not recognizing the contents of d:\MySite as an MVC application.</p>
<p>What do I need to do to resolve this? </p>
<p>As requested, here is the web.config:</p>
<pre><code> <?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
</code></pre> | 5,062,315 | 6 | 5 | null | 2011-02-20 20:48:41.643 UTC | 5 | 2013-12-05 10:56:55.353 UTC | 2011-02-20 22:04:55.1 UTC | null | 2,645 | null | 2,645 | null | 1 | 29 | asp.net-mvc|iis-7|asp.net-mvc-3 | 40,764 | <p>I posted this question on "ServerFault" as well and got a resolution to the issue <a href="https://serverfault.com/questions/237928/problem-running-mvc3-app-in-iis-7" title="here">here</a>.</p>
<p>The answer is:</p>
<p>Since IIS was installed after .NET 4, you likely need to run the <a href="http://msdn.microsoft.com/en-us/library/k6h9cz8h.aspx" rel="nofollow noreferrer">aspnet_regiis.exe</a> tool to register all the .NET 4 stuff with IIS.</p> |
4,956,822 | What's the difference between Future and FutureTask in Java? | <p>Since use <code>ExecutorService</code> can <code>submit</code> a <code>Callable</code> task and return a <code>Future</code>, why need to use <code>FutureTask</code> to wrap <code>Callable</code> task and use the method <code>execute</code>? I feel they both do the same thing.</p> | 4,956,886 | 6 | 0 | null | 2011-02-10 12:03:58.593 UTC | 13 | 2021-05-22 07:35:39.153 UTC | null | null | null | null | 590,091 | null | 1 | 56 | java|executorservice|callable|futuretask | 32,539 | <p>In fact you are correct. The two approaches are identical. You generally don't need to wrap them yourself. If you are, you're likely duplicating the code in AbstractExecutorService:</p>
<pre><code>/**
* Returns a <tt>RunnableFuture</tt> for the given callable task.
*
* @param callable the callable task being wrapped
* @return a <tt>RunnableFuture</tt> which when run will call the
* underlying callable and which, as a <tt>Future</tt>, will yield
* the callable's result as its result and provide for
* cancellation of the underlying task.
* @since 1.6
*/
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
</code></pre>
<p>The only difference between Future and RunnableFuture, is the run() method:</p>
<pre><code>/**
* A {@link Future} that is {@link Runnable}. Successful execution of
* the <tt>run</tt> method causes completion of the <tt>Future</tt>
* and allows access to its results.
* @see FutureTask
* @see Executor
* @since 1.6
* @author Doug Lea
* @param <V> The result type returned by this Future's <tt>get</tt> method
*/
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
</code></pre>
<p>A good reason to let the Executor construct the FutureTask for you is to ensure that there is no possible way more than one reference exists to the FutureTask instance. That is, the Executor <em>owns</em> this instance.</p> |
5,409,259 | Binding ItemsSource of a ComboBoxColumn in WPF DataGrid | <p>I have two simple Model classes and a ViewModel...</p>
<pre><code>public class GridItem
{
public string Name { get; set; }
public int CompanyID { get; set; }
}
public class CompanyItem
{
public int ID { get; set; }
public string Name { get; set; }
}
public class ViewModel
{
public ViewModel()
{
GridItems = new ObservableCollection<GridItem>() {
new GridItem() { Name = "Jim", CompanyID = 1 } };
CompanyItems = new ObservableCollection<CompanyItem>() {
new CompanyItem() { ID = 1, Name = "Company 1" },
new CompanyItem() { ID = 2, Name = "Company 2" } };
}
public ObservableCollection<GridItem> GridItems { get; set; }
public ObservableCollection<CompanyItem> CompanyItems { get; set; }
}
</code></pre>
<p>...and a simple Window:</p>
<pre><code><Window x:Class="DataGridComboBoxColumnApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" />
<DataGridComboBoxColumn ItemsSource="{Binding CompanyItems}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValueBinding="{Binding CompanyID}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
</code></pre>
<p>The ViewModel is set to the MainWindow's <code>DataContext</code> in App.xaml.cs:</p>
<pre><code>public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow window = new MainWindow();
ViewModel viewModel = new ViewModel();
window.DataContext = viewModel;
window.Show();
}
}
</code></pre>
<p>As you can see I set the <code>ItemsSource</code> of the DataGrid to the <code>GridItems</code> collection of the ViewModel. This part works, the single Grid line with Name "Jim" is displayed.</p>
<p>I also want to set the <code>ItemsSource</code> of the ComboBox in every row to the <code>CompanyItems</code> collection of the ViewModel. This part does not work: The ComboBox remains empty and in the Debugger Output Window I see an error message:</p>
<blockquote>
<p>System.Windows.Data Error: 2 : Cannot
find governing FrameworkElement or
FrameworkContentElement for target
element.
BindingExpression:Path=CompanyItems;
DataItem=null; target element is
'DataGridComboBoxColumn'
(HashCode=28633162); target property
is 'ItemsSource' (type 'IEnumerable')</p>
</blockquote>
<p>I believe that WPF expects <code>CompanyItems</code> to be a property of <code>GridItem</code> which is not the case, and that's the reason why the binding fails.</p>
<p>I've already tried to work with a <code>RelativeSource</code> and <code>AncestorType</code> like so:</p>
<pre><code><DataGridComboBoxColumn ItemsSource="{Binding CompanyItems,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}}}"
DisplayMemberPath="Name"
SelectedValuePath="ID"
SelectedValueBinding="{Binding CompanyID}" />
</code></pre>
<p>But that gives me another error in the debugger output:</p>
<blockquote>
<p>System.Windows.Data Error: 4 : Cannot
find source for binding with reference
'RelativeSource FindAncestor,
AncestorType='System.Windows.Window',
AncestorLevel='1''.
BindingExpression:Path=CompanyItems;
DataItem=null; target element is
'DataGridComboBoxColumn'
(HashCode=1150788); target property is
'ItemsSource' (type 'IEnumerable')</p>
</blockquote>
<p><strong>Question: How can I bind the ItemsSource of the DataGridComboBoxColumn to the CompanyItems collection of the ViewModel? Is it possible at all?</strong></p>
<p>Thank you for help in advance!</p> | 5,409,984 | 8 | 1 | null | 2011-03-23 17:28:44.503 UTC | 34 | 2021-08-19 12:10:27.757 UTC | null | null | null | null | 270,591 | null | 1 | 87 | .net|wpf|binding|wpfdatagrid|datagridcomboboxcolumn | 131,647 | <p>Pls, check if DataGridComboBoxColumn xaml below would work for you:</p>
<pre><code><DataGridComboBoxColumn
SelectedValueBinding="{Binding CompanyID}"
DisplayMemberPath="Name"
SelectedValuePath="ID">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.CompanyItems, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
</code></pre>
<p>Here you can find another solution for the problem you're facing: <a href="http://joemorrison.org/blog/2009/02/17/excedrin-headache-35401281-using-combo-boxes-with-the-wpf-datagrid/" rel="noreferrer">Using combo boxes with the WPF DataGrid</a></p> |
5,506,888 | Permutations - all possible sets of numbers | <p>I have numbers, from 0 to 8. I would like in result, all possible sets of those numbers, each set should use all numbers, each number can occur only once in a set.</p>
<p>I would like to see solution made in PHP that could print out result. Or, at least, I would like some refreshment in theory of combinatorics, as I have long forgotten it. What is the formula to calculate how many permutations will there be?</p>
<p>Example sets:</p>
<ul>
<li>0-1-2-3-4-5-6-7-8</li>
<li>0-1-2-3-4-5-6-8-7</li>
<li>0-1-2-3-4-5-8-6-7</li>
<li>0-1-2-3-4-8-5-6-7</li>
<li>0-1-2-3-8-4-5-6-7</li>
<li>0-1-2-8-3-4-5-6-7</li>
<li>and so on...</li>
</ul> | 5,506,933 | 12 | 0 | null | 2011-03-31 22:04:56.6 UTC | 25 | 2021-03-02 10:00:38.217 UTC | 2014-02-04 08:33:43.04 UTC | null | 618,728 | null | 588,973 | null | 1 | 40 | php|permutation|combinatorics | 63,399 | <p>You're looking for the permutations formula:</p>
<pre><code>nPk = n!/(n-k)!
</code></pre>
<p>In your case, you have 9 entries and you want to choose all of them, that's 9P9 = 9! = 362880</p>
<p>You can find a PHP algorithm to permutate in recipe 4.26 of O'Reilly's "PHP Cookbook".</p>
<pre><code>pc_permute(array(0, 1, 2, 3, 4, 5, 7, 8));
</code></pre>
<p>Copied in from O'Reilly:</p>
<pre><code>function pc_permute($items, $perms = array( )) {
if (empty($items)) {
print join(' ', $perms) . "\n";
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
pc_permute($newitems, $newperms);
}
}
}
</code></pre> |
5,349,425 | What's the fastest way to loop through an array in JavaScript? | <p>I learned from books that you should write for loop like this:</p>
<pre><code>for(var i=0, len=arr.length; i < len; i++){
// blah blah
}
</code></pre>
<p>so the <code>arr.length</code> will not be calculated each time. </p>
<p>Others say that the compiler will do some optimization to this, so you can just write: </p>
<pre><code>for(var i=0; i < arr.length; i++){
// blah blah
}
</code></pre>
<p>I just want to know which is the best way in practice? </p> | 7,252,102 | 24 | 6 | null | 2011-03-18 08:05:06.463 UTC | 96 | 2022-07-24 15:40:46.553 UTC | 2017-05-23 03:41:27.61 UTC | null | 325,241 | null | 325,241 | null | 1 | 299 | javascript|performance|loops | 299,570 | <p>After performing this test with most modern browsers:
<a href="https://jsben.ch/wY5fo" rel="noreferrer">https://jsben.ch/wY5fo</a></p>
<p><strong>Currently</strong>, the fastest form of loop (and in my opinion the most syntactically obvious).</p>
<p>A standard for-loop with length caching</p>
<pre class="lang-js prettyprint-override"><code> var i = 0, len = myArray.length;
while (i < len) {
// your code
i++
}
</code></pre>
<p>I would say, this is definitely a case where I applaud JavaScript engine developers. A runtime should be optimized for <em>clarity, not cleverness</em>.</p> |
29,393,601 | Downloading file from ajax result using blob | <p>I use this code to download excel file from server.</p>
<pre><code>$.ajax({
headers: CLIENT.authorize(),
url: '/server/url',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData),
success: function (data) {
alert('Data size: ' + data.length);
var blob = new Blob([data], { type: "application/vnd.ms-excel" });
alert('BLOB SIZE: ' + data.length);
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
document.location = downloadUrl;
},
});
</code></pre>
<p>The problem I experience is that even though data and blob sizes are identical, the moment document.location gets assigned I'm prompted to download almoste two times larger excel file. And when I try to open it, excel complains about wrong file format and opened file contains a lot of garbage, even though required text is still there.</p>
<p>Any ideas what is causing this and how to avoid it?</p> | 29,556,434 | 1 | 5 | null | 2015-04-01 14:33:19.95 UTC | 9 | 2015-04-10 08:11:24.783 UTC | null | null | null | null | 1,218,970 | null | 1 | 24 | javascript|jquery | 60,637 | <p>So I solved the problem using AJAX 2. It natively supports binary streams. You can't use jQuery for that, unless you base64 encode everything, apparently.</p>
<p>Working code looks like this:</p>
<pre><code>var xhr = new XMLHttpRequest();
xhr.open('POST', '/le/url', true);
xhr.responseType = 'blob';
$.each(SERVER.authorization(), function(k, v) {
xhr.setRequestHeader(k, v);
});
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function(e) {
preloader.modal('hide');
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'application/vnd.ms-excel'});
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = "data.xls";
document.body.appendChild(a);
a.click();
} else {
alert('Unable to download excel.')
}
};
xhr.send(JSON.stringify(jsonData));
</code></pre>
<p>Hope this helps.</p> |
12,088,026 | How would I do MySQL count(*) in Doctrine2? | <p>I have the following Doctrine2 query:</p>
<pre><code>$qb = $em->createQueryBuilder()
->select('t.tag_text, COUNT(*) as num_tags')
->from('CompanyWebsiteBundle:Tag2Post', 't2p')
->innerJoin('t2p.tags', 't')
->groupBy('t.tag_text')
;
$tags = $qb->getQuery()->getResult();
</code></pre>
<p>When run I get the following error: </p>
<pre><code>[Semantical Error] line 0, col 21 near '*) as num_tags': Error: '*' is not defined.
</code></pre>
<p>How would I do MySQL count(*) in Doctrine2?</p> | 12,088,240 | 3 | 0 | null | 2012-08-23 08:50:45.707 UTC | 4 | 2014-08-11 02:28:02.137 UTC | 2013-10-14 23:15:31.343 UTC | user212218 | null | null | 505,107 | null | 1 | 16 | php|mysql|symfony|doctrine-orm | 38,259 | <p>You're trying to do it in DQL not "in Doctrine 2".</p>
<p>You need to specify which field (note, I don't use the term column) you want to count, this is because you are using an ORM, and need to think in OOP way.</p>
<pre><code>$qb = $em->createQueryBuilder()
->select('t.tag_text, COUNT(t.tag_text) as num_tags')
->from('CompanyWebsiteBundle:Tag2Post', 't2p')
->innerJoin('t2p.tags', 't')
->groupBy('t.tag_text')
;
$tags = $qb->getQuery()->getResult();
</code></pre>
<p>However, if you require performance, you may want to use a <a href="http://docs.doctrine-project.org/en/latest/reference/native-sql.html" rel="noreferrer"><code>NativeQuery</code></a> since your result is a simple scalar not an object.</p> |
12,454,794 | Why covariance and contravariance do not support value type | <p><code>IEnumerable<T></code> is <em>co-variant</em> but it does not support value type, just only reference type. The below simple code is compiled successfully:</p>
<pre><code>IEnumerable<string> strList = new List<string>();
IEnumerable<object> objList = strList;
</code></pre>
<p>But changing from <code>string</code> to <code>int</code> will get compiled error:</p>
<pre><code>IEnumerable<int> intList = new List<int>();
IEnumerable<object> objList = intList;
</code></pre>
<p>The reason is explained in <a href="http://msdn.microsoft.com/en-us/library/dd799517.aspx#InterfaceCovariantTypeParameters" rel="noreferrer">MSDN</a>:</p>
<blockquote>
<p>Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.</p>
</blockquote>
<p>I have searched and found that some questions mentioned the reason is <em>boxing between value type and reference type</em>. But it does not still clear up my mind much why boxing is the reason?</p>
<p>Could someone please give a simple and detailed explanation why covariance and contravariance do not support value type and how <em>boxing</em> affects this?</p> | 12,454,932 | 4 | 2 | null | 2012-09-17 07:27:13.873 UTC | 44 | 2022-04-12 17:17:52.667 UTC | 2012-09-19 07:26:57.193 UTC | null | 783,681 | null | 783,681 | null | 1 | 158 | c#|.net|c#-4.0|covariance|contravariance | 10,663 | <p>Basically, variance applies when the CLR can ensure that it doesn't need to make any <em>representational change</em> to the values. References all look the same - so you can use an <code>IEnumerable<string></code> as an <code>IEnumerable<object></code> without any change in representation; the native code itself doesn't need to know what you're doing with the values at all, so long as the infrastructure has guaranteed that it will definitely be valid.</p>
<p>For value types, that doesn't work - to treat an <code>IEnumerable<int></code> as an <code>IEnumerable<object></code>, the code using the sequence would have to know whether to perform a boxing conversion or not.</p>
<p>You might want to read Eric Lippert's <a href="https://ericlippert.com/2009/03/03/representation-and-identity/" rel="nofollow noreferrer">blog post on representation and identity</a> for more on this topic in general.</p>
<p>EDIT: Having reread Eric's blog post myself, it's at least as much about <em>identity</em> as representation, although the two are linked. In particular:</p>
<blockquote>
<p>This is why covariant and contravariant conversions of interface and delegate types require that all varying type arguments be of reference types. To ensure that a variant reference conversion is always identity-preserving, all of the conversions involving type arguments must also be identity-preserving. The easiest way to ensure that all the non-trivial conversions on type arguments are identity-preserving is to restrict them to be reference conversions.</p>
</blockquote> |
19,116,545 | git tag: fatal: Failed to resolve 'HEAD' as a valid ref | <p>I am cloning a single branch from a repository and creating a tag in a python script. The commands are as follows.</p>
<pre><code>git clone -b master --single-branch <repository adress>
git tag -a testag -m 'test'
</code></pre>
<p>It clones successfully but when it comes to adding the tag, it breaks with the following error:</p>
<pre><code>fatal: Failed to resolve 'HEAD' as a valid ref.
</code></pre> | 31,640,816 | 5 | 5 | null | 2013-10-01 12:46:29.053 UTC | 2 | 2017-08-11 09:10:55.07 UTC | 2014-01-19 14:30:07.033 UTC | null | 1,433,392 | null | 1,185,665 | null | 1 | 14 | git | 41,732 | <p>I had the same issue. You have to commit first before tagging</p>
<pre><code>git commit
</code></pre>
<p>because you put tags on commits. So when there is no commit (like in your situation), you can't create a tag.</p> |
24,101,718 | Swift Beta performance: sorting arrays | <p>I was implementing an algorithm in Swift Beta and noticed that the performance was very poor. After digging deeper I realized that one of the bottlenecks was something as simple as sorting arrays. The relevant part is here:</p>
<pre><code>let n = 1000000
var x = [Int](repeating: 0, count: n)
for i in 0..<n {
x[i] = random()
}
// start clock here
let y = sort(x)
// stop clock here
</code></pre>
<p>In C++, a similar operation takes <strong>0.06s</strong> on my computer.</p>
<p>In Python, it takes <strong>0.6s</strong> (no tricks, just y = sorted(x) for a list of integers).</p>
<p>In Swift it takes <strong>6s</strong> if I compile it with the following command:</p>
<pre><code>xcrun swift -O3 -sdk `xcrun --show-sdk-path --sdk macosx`
</code></pre>
<p>And it takes as much as <strong>88s</strong> if I compile it with the following command:</p>
<pre><code>xcrun swift -O0 -sdk `xcrun --show-sdk-path --sdk macosx`
</code></pre>
<p>Timings in Xcode with "Release" vs. "Debug" builds are similar.</p>
<p>What is wrong here? I could understand some performance loss in comparison with C++, but not a 10-fold slowdown in comparison with pure Python.</p>
<hr>
<p><strong>Edit:</strong> weather noticed that changing <code>-O3</code> to <code>-Ofast</code> makes this code run almost as fast as the C++ version! However, <code>-Ofast</code> changes the semantics of the language a lot — in my testing, it <strong>disabled the checks for integer overflows and array indexing overflows</strong>. For example, with <code>-Ofast</code> the following Swift code runs silently without crashing (and prints out some garbage):</p>
<pre><code>let n = 10000000
print(n*n*n*n*n)
let x = [Int](repeating: 10, count: n)
print(x[n])
</code></pre>
<p>So <code>-Ofast</code> is not what we want; the whole point of Swift is that we have the safety nets in place. Of course, the safety nets have some impact on the performance, but they should not make the programs 100 times slower. Remember that Java already checks for array bounds, and in typical cases, the slowdown is by a factor much less than 2. And in Clang and GCC we have got <code>-ftrapv</code> for checking (signed) integer overflows, and it is not that slow, either.</p>
<p>Hence the question: how can we get reasonable performance in Swift without losing the safety nets?</p>
<hr>
<p><strong>Edit 2:</strong> I did some more benchmarking, with very simple loops along the lines of</p>
<pre><code>for i in 0..<n {
x[i] = x[i] ^ 12345678
}
</code></pre>
<p>(Here the xor operation is there just so that I can more easily find the relevant loop in the assembly code. I tried to pick an operation that is easy to spot but also "harmless" in the sense that it should not require any checks related to integer overflows.)</p>
<p>Again, there was a huge difference in the performance between <code>-O3</code> and <code>-Ofast</code>. So I had a look at the assembly code:</p>
<ul>
<li><p>With <code>-Ofast</code> I get pretty much what I would expect. The relevant part is a loop with 5 machine language instructions.</p></li>
<li><p>With <code>-O3</code> I get something that was beyond my wildest imagination. The inner loop spans 88 lines of assembly code. I did not try to understand all of it, but the most suspicious parts are 13 invocations of "callq _swift_retain" and another 13 invocations of "callq _swift_release". That is, <strong>26 subroutine calls in the inner loop</strong>!</p></li>
</ul>
<hr>
<p><strong>Edit 3:</strong> In comments, Ferruccio asked for benchmarks that are fair in the sense that they do not rely on built-in functions (e.g. sort). I think the following program is a fairly good example:</p>
<pre><code>let n = 10000
var x = [Int](repeating: 1, count: n)
for i in 0..<n {
for j in 0..<n {
x[i] = x[j]
}
}
</code></pre>
<p>There is no arithmetic, so we do not need to worry about integer overflows. The only thing that we do is just lots of array references. And the results are here—Swift -O3 loses by a factor almost 500 in comparison with -Ofast:</p>
<ul>
<li>C++ -O3: <strong>0.05 s</strong></li>
<li>C++ -O0: 0.4 s</li>
<li>Java: <strong>0.2 s</strong></li>
<li>Python with PyPy: 0.5 s</li>
<li>Python: <strong>12 s</strong></li>
<li>Swift -Ofast: 0.05 s</li>
<li>Swift -O3: <strong>23 s</strong></li>
<li>Swift -O0: 443 s</li>
</ul>
<p>(If you are concerned that the compiler might optimize out the pointless loops entirely, you can change it to e.g. <code>x[i] ^= x[j]</code>, and add a print statement that outputs <code>x[0]</code>. This does not change anything; the timings will be very similar.)</p>
<p>And yes, here the Python implementation was a stupid pure Python implementation with a list of ints and nested for loops. It should be <strong>much</strong> slower than unoptimized Swift. Something seems to be seriously broken with Swift and array indexing.</p>
<hr>
<p><strong>Edit 4:</strong> These issues (as well as some other performance issues) seems to have been fixed in Xcode 6 beta 5.</p>
<p>For sorting, I now have the following timings:</p>
<ul>
<li>clang++ -O3: 0.06 s</li>
<li>swiftc -Ofast: 0.1 s</li>
<li>swiftc -O: 0.1 s</li>
<li>swiftc: 4 s</li>
</ul>
<p>For nested loops:</p>
<ul>
<li>clang++ -O3: 0.06 s</li>
<li>swiftc -Ofast: 0.3 s</li>
<li>swiftc -O: 0.4 s</li>
<li>swiftc: 540 s</li>
</ul>
<p>It seems that there is no reason anymore to use the unsafe <code>-Ofast</code> (a.k.a. <code>-Ounchecked</code>); plain <code>-O</code> produces equally good code.</p> | 24,102,237 | 9 | 21 | null | 2014-06-07 23:53:45.487 UTC | 312 | 2020-04-19 16:54:39.293 UTC | 2019-02-08 12:29:16.65 UTC | null | 11,023,101 | null | 383,299 | null | 1 | 974 | swift|performance|sorting|xcode6|compiler-optimization | 117,178 | <p>tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].</p>
<hr>
<p>Here is an in-place quicksort in Swift Beta:</p>
<pre><code>func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
if (end - start < 2){
return
}
var p = a[start + (end - start)/2]
var l = start
var r = end - 1
while (l <= r){
if (a[l] < p){
l += 1
continue
}
if (a[r] > p){
r -= 1
continue
}
var t = a[l]
a[l] = a[r]
a[r] = t
l += 1
r -= 1
}
quicksort_swift(&a, start, r + 1)
quicksort_swift(&a, r + 1, end)
}
</code></pre>
<p>And the same in C:</p>
<pre><code>void quicksort_c(int *a, int n) {
if (n < 2)
return;
int p = a[n / 2];
int *l = a;
int *r = a + n - 1;
while (l <= r) {
if (*l < p) {
l++;
continue;
}
if (*r > p) {
r--;
continue;
}
int t = *l;
*l++ = *r;
*r-- = t;
}
quicksort_c(a, r - a + 1);
quicksort_c(l, a + n - l);
}
</code></pre>
<p>Both work:</p>
<pre><code>var a_swift:CInt[] = [0,5,2,8,1234,-1,2]
var a_c:CInt[] = [0,5,2,8,1234,-1,2]
quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))
// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]
</code></pre>
<p>Both are called in the same program as written.</p>
<pre><code>var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
x_swift[i] = CInt(random())
x_c[i] = CInt(random())
}
let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)
let swift_stop:UInt64 = mach_absolute_time();
let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();
</code></pre>
<p>This converts the absolute times to seconds:</p>
<pre><code>static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;
mach_timebase_info_data_t timebase_info;
uint64_t abs_to_nanos(uint64_t abs) {
if ( timebase_info.denom == 0 ) {
(void)mach_timebase_info(&timebase_info);
}
return abs * timebase_info.numer / timebase_info.denom;
}
double abs_to_seconds(uint64_t abs) {
return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}
</code></pre>
<p>Here is a summary of the compiler's optimazation levels:</p>
<pre><code>[-Onone] no optimizations, the default for debug.
[-O] perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.
</code></pre>
<p>Time in seconds with <strong>[-Onone]</strong> for <strong>n=10_000</strong>:</p>
<pre><code>Swift: 0.895296452
C: 0.001223848
</code></pre>
<p>Here is Swift's builtin sort() for <strong>n=10_000</strong>:</p>
<pre><code>Swift_builtin: 0.77865783
</code></pre>
<p>Here is <strong>[-O]</strong> for <strong>n=10_000</strong>:</p>
<pre><code>Swift: 0.045478346
C: 0.000784666
Swift_builtin: 0.032513488
</code></pre>
<p>As you can see, Swift's performance improved by a factor of 20.</p>
<p>As per <a href="https://stackoverflow.com/questions/24101718/swift-performance-sorting-arrays/24102759#24102759">mweathers' answer</a>, setting <strong>[-Ofast]</strong> makes the real difference, resulting in these times for <strong>n=10_000</strong>:</p>
<pre><code>Swift: 0.000706745
C: 0.000742374
Swift_builtin: 0.000603576
</code></pre>
<p>And for <strong>n=1_000_000</strong>:</p>
<pre><code>Swift: 0.107111846
C: 0.114957179
Swift_sort: 0.092688548
</code></pre>
<p>For comparison, this is with <strong>[-Onone]</strong> for <strong>n=1_000_000</strong>:</p>
<pre><code>Swift: 142.659763258
C: 0.162065333
Swift_sort: 114.095478272
</code></pre>
<p>So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.</p>
<p>It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:</p>
<blockquote>
<p>A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.</p>
</blockquote>
<p>They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance <em>and</em> overflow checks / precise arithmetic then choose another language for now.</p>
<p>BETA 3 UPDATE:</p>
<p><strong>n=10_000</strong> with <strong>[-O]</strong>:</p>
<pre><code>Swift: 0.019697268
C: 0.000718064
Swift_sort: 0.002094721
</code></pre>
<p>Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.</p>
<p><strong>FINAL UPDATE:</strong></p>
<p><strong>[-Onone]</strong>:</p>
<pre><code>Swift: 0.678056695
C: 0.000973914
</code></pre>
<p><strong>[-O]</strong>:</p>
<pre><code>Swift: 0.001158492
C: 0.001192406
</code></pre>
<p><strong>[-Ounchecked]</strong>:</p>
<pre><code>Swift: 0.000827764
C: 0.001078914
</code></pre> |
22,911,722 | How to find array index of largest value? | <p>The title above sums up my question, to clarify things an example is:</p>
<pre><code>array[0] = 1
array[1] = 3
array[2] = 7 // largest
array[3] = 5
</code></pre>
<p>so the result I would like is 2, since it contains the largest element 7. </p> | 22,911,923 | 9 | 9 | null | 2014-04-07 11:55:24.683 UTC | 2 | 2022-01-19 14:08:30.937 UTC | 2014-04-07 12:39:29.587 UTC | null | 474,189 | null | 3,307,418 | null | 1 | 14 | java|arrays | 68,778 | <pre><code>public int getIndexOfLargest( int[] array )
{
if ( array == null || array.length == 0 ) return -1; // null or empty
int largest = 0;
for ( int i = 1; i < array.length; i++ )
{
if ( array[i] > array[largest] ) largest = i;
}
return largest; // position of the first largest found
}
</code></pre> |
19,111,028 | std::dynarray vs std::vector | <p>C++14 presents <a href="http://en.cppreference.com/w/cpp/container/dynarray"><code>std::dynarray</code></a>:</p>
<blockquote>
<p>std::dynarray is a sequence container that encapsulates arrays with a
size that is fixed at construction and does not change throughout the
lifetime of the object.</p>
</blockquote>
<p><code>std::dynarray</code> must be allocated in run-time as same as <code>std::vector</code>.</p>
<p>So what are the benefits and the usage of <code>std::dynarray</code> while we can use <code>std::vector</code> which is more dynamic (and also re-sizable)?</p> | 19,111,606 | 2 | 12 | null | 2013-10-01 08:05:37.903 UTC | 12 | 2016-12-01 05:05:21.743 UTC | 2016-12-01 05:05:21.743 UTC | null | 734,069 | null | 952,747 | null | 1 | 89 | c++|stdvector | 20,120 | <blockquote>
<p>So what are the benefits and the usage of <code>std::dynarray</code>, when we can use <code>std::vector</code> which is more dynamic (Re-sizable)?</p>
</blockquote>
<p><code>dynarray</code> is smaller and simpler than <code>vector</code>, because it doesn't need to manage separate size and capacity values, and it doesn't need to store an allocator.</p>
<p>However the main performance benefit is intended to come from the fact that implementations are encouraged to allocate <code>dynarray</code> on the stack when possible, avoiding any heap allocation. e.g.</p>
<pre><code>std::dynarray<int> d(5); // can use stack memory for elements
auto p = new std::dynarray<int>(6); // must use heap memory for elements
</code></pre>
<p>This optimisation requires cooperation from the compiler, it can't be implemented as a pure library type, and the necessary compiler magic has not been implemented and noone is sure how easy it is to do. Because of the lack of implementation experience, at the C++ committee meeting in Chicago last week it was decided to pull <code>std::dynarray</code> from C++14 and to issue a separate array extensions TS (technical specification) document defining <code>std::experimental::dynarray</code> and arrays of runtime bound (ARBs, similar to C99 VLAs.) This means <code>std::dynarray</code> will almost certainly not be in C++14.</p> |
8,763,398 | Why is it illegal to take the address of an rvalue temporary? | <p>According to " <a href="https://stackoverflow.com/questions/8763043/how-to-go-around-the-warning-rvalue-used-as-lvalue">How to get around the warning "rvalue used as lvalue"?</a> ", Visual Studio will merely warn on code such as this:</p>
<pre><code>int bar() {
return 3;
}
void foo(int* ptr) {
}
int main() {
foo(&bar());
}
</code></pre>
<p>In C++ it is <em>not allowed</em> to take the address of a temporary (or, at least, of an object referred to by an <em>rvalue</em> expression?), and I thought that this was because temporaries are not guaranteed to even have storage.</p>
<p>But then, although diagnostics may be presented in any form the compiler chooses, I'd still have expected MSVS to <em>error</em> rather than <em>warn</em> in such a case.</p>
<p>So, are temporaries guaranteed to have storage? And if so, why is the above code disallowed in the first place?</p> | 9,780,041 | 6 | 18 | null | 2012-01-06 19:32:54.407 UTC | 13 | 2016-10-01 13:06:38.533 UTC | 2017-05-23 11:46:43.57 UTC | null | -1 | null | 560,648 | null | 1 | 33 | c++ | 26,253 | <p>You're right in saying that "temporaries are not guaranteed to even have storage", in the sense that the temporary may not be stored in addressable memory. In fact, very often functions compiled for RISC architectures (e.g. ARM) will return values in general use registers and would expect inputs in those registers as well.</p>
<p>MSVS, producing code for x86 architectures, may <em>always</em> produce functions that return their values on the stack. Therefore they're stored in addressable memory and have a valid address.</p> |
20,499,444 | What does webform_DoPostBackWithOptions() do? | <p>I have a button declared like this:</p>
<pre><code><asp:Button id=Send runat="server" EnableViewState="False"
ToolTip="Email me this report" CssClass="Button" Text="Email me this report">
</asp:Button>
</code></pre>
<p>But if I do Inspect Element in browser, it shows like this:</p>
<pre><code><input type="submit" class="Button" title="Email me this report"
id="ctl03_Toolbar_Send" onclick="javascript:WebForm_DoPostBackWithOptions(new
WebForm_PostBackOptions("ctl03$Toolbar$Send","", true, "", "";, false, false))"
value="Email me this report" name="ctl03$Toolbar$Send">
</code></pre>
<p>I wonder where the onclick event comes from? What does it do?</p>
<p>Thanks for your help in advance.</p> | 20,501,708 | 4 | 5 | null | 2013-12-10 16:11:41.117 UTC | 8 | 2019-08-13 14:38:41.533 UTC | 2019-04-02 16:47:45.737 UTC | null | 72,642 | null | 2,752,085 | null | 1 | 24 | javascript|asp.net | 69,442 | <p>If you set the PostBackUrl property for the Button server control, then it means it is cross page posting and then asp.net framework instead of normal __DoPostBack() adds "WebForm_DoPostBackWithOptions". Check if you have "PostBackUrl" Property set for this button.</p>
<pre><code><asp:Button id=Send runat="server" EnableViewState="False" PostBackUrl="~/Page2.aspx"
ToolTip="Email me this report" CssClass="Button" Text="Email me this report">
</asp:Button>
</code></pre>
<p>If in your case you have not set the "PostBackUrl", then ASP.NET framework also does not add this by default for Button Control, so this means there has to be another control setting the OnClick attribute value probably using following sever side code -</p>
<pre><code> PostBackOptions myPostBackOptions = new PostBackOptions(this);
myPostBackOptions.ActionUrl = "Page2.aspx";
myPostBackOptions.AutoPostBack = false;
myPostBackOptions.RequiresJavaScriptProtocol = true;
myPostBackOptions.PerformValidation = true;
// Add the client-side script to the HyperLink1 control.
Button1.OnClientClick = Page.ClientScript.GetPostBackEventReference(myPostBackOptions);
</code></pre> |
11,111,737 | How to properly format JSON string in java? | <p>I have a jersey client that is getting JSON from a source that I need to get into properly formatted JSON:</p>
<p>My JSON String looks like the folllowing when grabbing it via http request:</p>
<pre><code>{
"properties": [
{
someproperty: "aproperty",
set of data: {
keyA: "SomeValueA",
keyB: "SomeValueB",
keyC: "SomeValueC"
}
}
]
}
</code></pre>
<p>I am having problems because the json has to be properly formatted and keyA, keB, and keyC are not surrounded in quotes. Is there some library that helps add quotes or some best way to go about turning this string to properly formatted json? Or if there is some easy way to convert this to a json object without writing a bunch of classes with variables and lists that match the incoming structure?</p> | 11,111,855 | 4 | 1 | null | 2012-06-20 01:36:59.96 UTC | 1 | 2012-06-20 10:19:00.09 UTC | 2012-06-20 02:04:29.387 UTC | null | 971,888 | null | 971,888 | null | 1 | 5 | java|json | 43,728 | <p>you can use <a href="http://json-lib.sourceforge.net/" rel="noreferrer">json-lib</a>. it's very convenient! you can construct your json string like this:</p>
<pre><code>JSONObject dataSet = new JSONObject();
dataSet.put("keyA", "SomeValueA") ;
dataSet.put("keyB", "SomeValueB") ;
dataSet.put("keyC", "SomeValueC") ;
JSONObject someProperty = new JSONObject();
dataSet.put("someproperty", "aproperty") ;
JSONArray properties = new JSONArray();
properties.add(dataSet);
properties.add(someProperty);
</code></pre>
<p>and of course you can get your JSON String simply by calling <code>properties.toString()</code> </p> |
11,208,632 | Hide/Show menu item in application's main menu by pressing Option key | <p>I want to add a menu item into the application's main menu that will be used quite rare. I want it to be hidden by default and show it only when user hold down Option key. How do i do this?</p>
<p>It seems that I should handle <code>flagsChanged:</code>, but it is <code>NSResponder</code>'s method and <code>NSMenu</code> does not inherits from <code>NSResponder</code>? I tried it inside main window controller, and it works when I press Option key before I click on menu. The following use case doe not work: click on menu item (there is no item), press option key — my item should appear, release option key — item should disappear.</p>
<p>I've also tried NSEvent's <code>addLocalMonitorForEventsMatchingMask:handler:</code> and <code>addGlobalMonitorForEventsMatchingMask:handler:</code> for <code>NSFlagsChangedMask</code> but when option key pressed while main menu is open neither local or global handlers are not fired. </p>
<p>How can I do this?</p> | 12,333,909 | 5 | 0 | null | 2012-06-26 13:41:34.363 UTC | 11 | 2018-01-28 04:18:10.69 UTC | 2013-03-16 20:03:31.62 UTC | null | 22,368 | null | 29,364 | null | 1 | 9 | cocoa|nsmenu | 5,499 | <p>Add the following to applicationDidFinishLaunching.</p>
<pre><code>// Dynamically update QCServer menu when option key is pressed
NSMenu *submenu = [[[NSApp mainMenu] itemWithTitle:@"QCServer"] submenu];
NSTimer *t = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(updateMenu:) userInfo:submenu repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSEventTrackingRunLoopMode];
</code></pre>
<p>then add</p>
<pre><code>- (void)updateMenu:(NSTimer *)t {
static NSMenuItem *menuItem = nil;
static BOOL isShowing = YES;
// Get global modifier key flag, [[NSApp currentEvent] modifierFlags] doesn't update while menus are down
CGEventRef event = CGEventCreate (NULL);
CGEventFlags flags = CGEventGetFlags (event);
BOOL optionKeyIsPressed = (flags & kCGEventFlagMaskAlternate) == kCGEventFlagMaskAlternate;
CFRelease(event);
NSMenu *menu = [t userInfo];
if (!menuItem) {
// View Batch Jobs...
menuItem = [menu itemAtIndex:6];
[menuItem retain];
}
if (!isShowing && optionKeyIsPressed) {
[menu insertItem:menuItem atIndex:6];
[menuItem setEnabled:YES];
isShowing = YES;
} else if (isShowing && !optionKeyIsPressed) {
[menu removeItem:menuItem];
isShowing = NO;
}
NSLog(@"optionKeyIsPressed %d", optionKeyIsPressed);
}
</code></pre>
<p>The timer only fires while controls are being tracked so it's not too much of a performance hit. </p> |
11,160,939 | How to write integer values to a file using out.write()? | <p>I am generating some numbers (let's say, <code>num</code>) and writing the numbers to an output file using <code>outf.write(num).</code></p>
<p>But the interpreter is throwing an error:</p>
<pre class="lang-none prettyprint-override"><code> outf.write(num)
TypeError: argument 1 must be string or read-only character buffer, not int.
</code></pre>
<p>How can I solve this problem?</p> | 11,160,976 | 5 | 3 | null | 2012-06-22 17:08:18.57 UTC | 5 | 2022-05-21 12:54:46.047 UTC | 2022-05-21 12:54:46.047 UTC | null | 2,745,495 | null | 1,464,849 | null | 1 | 27 | python|file-io | 137,448 | <p><a href="http://docs.python.org/library/stdtypes.html?highlight=write#file.write">write()</a> only takes a <em>single string</em> argument, so you could do this:</p>
<pre><code>outf.write(str(num))
</code></pre>
<p>or</p>
<pre><code>outf.write('{}'.format(num)) # more "modern"
outf.write('%d' % num) # deprecated mostly
</code></pre>
<p>Also note that <code>write</code> will not append a newline to your output so if you need it you'll have to supply it yourself.</p>
<p><strong>Aside</strong>:</p>
<p>Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):</p>
<pre><code>num = 7
outf.write('{:03d}\n'.format(num))
num = 12
outf.write('%03d\n' % num)
</code></pre>
<p>to get three spaces, with leading zeros for your integer value followed by a newline:</p>
<pre><code>007
012
</code></pre>
<p><a href="http://docs.python.org/library/string.html#format-string-syntax">format()</a> will be around for a long while, so it's worth learning/knowing.</p> |
11,386,854 | GNU Octave method to operate on each item in a matrix. octave "arrayfun(...)" example | <p>In GNU Octave version 3.4.3, I am having trouble applying a custom function to operate on each item/element in a matrix.</p>
<p>I have a (2,3) matrix that looks like:</p>
<pre><code>mymatrix = [1,2,3;4,5,6];
mymatrix
1 2 3
4 5 6
</code></pre>
<p>I want to use each element of the matrix as an input, and run a custom function against it, and have the output of the function replace the content of mymatrix item by item. </p> | 11,524,041 | 4 | 0 | null | 2012-07-08 21:27:23.517 UTC | 6 | 2018-04-03 15:50:35.35 UTC | 2018-04-03 15:10:06.387 UTC | null | 445,131 | null | 445,131 | null | 1 | 47 | linux|function|octave | 23,442 | <p>Simpler way, As Nasser Pointed out, the following octave code:</p>
<pre><code>f=@(x) x+5;
A = [1, 0, -1; 3, 4, 5];
result = f(A)
result
</code></pre>
<p>applies (x+5) to every element passed in, it prints: </p>
<pre><code>result =
6 5 4
8 9 10
</code></pre> |
12,842,203 | Use a Google Docs Spreadsheet as a datasource for a dynamic Google Sites webpage | <p>I have a Google Form that feeds a Google Docs Spreadsheet. I'd like to--in turn--have that Google Docs Spreadsheet feed a webpage. </p>
<p>In plainer English, babysitters fill out the form to sign up to be in our community's Babysitter Directory. The spreadsheet houses all of the data. I'd like to code a webpage to pull selected bits of the data for the online directory.</p>
<p>I've tried doing a separate sheet in the spreadsheet, using a QUERY to select the columns that I want to include (and the order in which I want to include them), publishing that sheet to the web, then embedding that sheet into the webpage in an iFrame. And that works.</p>
<p>But even with the QUERY, there are SO many columns that users need to scroll WAY over to the right to see all the data for each babysitter. It's unwieldy.</p>
<p>What would be way better would be if I could break the data for each entry over multiple lines and do some nice formatting for a directory, rather than just a linear spreadsheet. So that, essentially, each babysitter's "entry" in the directory is more than 1 line long. Does that make sense?</p>
<p>If I was working in Office, I would know exactly what to do: use the Excel spreadsheet as the datasource for a Word Mail Merge and I would put move the fields around on the page to make it all look good.</p>
<p>And, to be sure, if I can do this in a Google Doc, then embed the Doc into the webpage, that's fine, too. But I would think there's some way I can do it directly in the Google Site?</p>
<p>Can I?</p>
<p>If anybody has even just a reference page for me to take a look at, I'd appreciate it.</p>
<p>Thanks!</p> | 12,842,458 | 2 | 0 | null | 2012-10-11 14:41:30.313 UTC | 1 | 2017-05-01 19:20:12.337 UTC | null | null | null | null | 1,512,425 | null | 1 | 10 | google-apps-script|google-docs | 41,391 | <p>Are you trying to do this in Google Sites? If so, you can embed the entire spreadsheet on the page, but if you only want certain columns, you can try inserting an Apps Script widget on the page.</p>
<p>You need to know how to write a Google Apps Script that will run JS functions and render HTML, <a href="https://developers.google.com/apps-script/your_first_script" rel="noreferrer">here is a tutorial</a> </p>
<p>To create the Script that can run on your page, go to:</p>
<pre><code>More > Manage site > Apps Script > Add new script
</code></pre>
<p>Here's also a link to how to <a href="https://developers.google.com/apps-script/storing_data_spreadsheets#reading" rel="noreferrer">interact with Spreadsheet data</a>.</p> |
13,198,646 | Can't bind to local XXXX for debugger | <p>I keep getting the <code>Can't bind to local XXXX for debugger</code> message in console, but not for 1 port, for all random ports. I have done what's stated in <a href="https://stackoverflow.com/questions/3318738/i-get-error-in-ddmscant-bind-to-local-8600-for-debugger-why">this question</a>, but with no luck.
I'm running Windows 8. <strong>In fact, these problems started after the upgrade to Windows 8.</strong></p>
<pre><code>[2012-11-02 16:40:41 - ddms] Can't bind to local 8627 for debugger
[2012-11-02 16:40:41 - ddms] Can't bind to local 8617 for debugger
[2012-11-02 16:40:42 - ddms] Can't bind to local 8605 for debugger
[2012-11-02 16:40:42 - ddms] Can't bind to local 8610 for debugger
[2012-11-02 16:41:46 - ddms] Can't bind to local 8611 for debugger
[2012-11-02 16:41:46 - ddms] Can't bind to local 8611 for debugger
[2012-11-02 16:41:47 - ddms] Can't bind to local 8611 for debugger
[2012-11-02 16:42:36 - ddms] Can't bind to local 8611 for debugger
[2012-11-02 16:42:38 - ddms] Can't bind to local 8611 for debugger
[2012-11-02 16:42:39 - ddms] Can't bind to local 8622 for debugger
[2012-11-02 16:42:39 - ddms] Can't bind to local 8608 for debugger
[2012-11-02 16:42:39 - ddms] Can't bind to local 8608 for debugger
[2012-11-02 16:42:48 - ddms] Can't bind to local 8609 for debugger
[2012-11-02 16:42:48 - ddms] Can't bind to local 8609 for debugger
[2012-11-02 16:43:32 - ddms] Can't bind to local 8609 for debugger
[2012-11-02 16:43:36 - ddms] Can't bind to local 8625 for debugger
[2012-11-02 16:43:36 - ddms] Can't bind to local 8619 for debugger
</code></pre>
<p>What can I do?</p>
<p><em>Edit</em><br>
I've tried a new install of the Android SDK, and a new Eclipse install. I've also tried to turn off my firewall.</p> | 15,431,225 | 7 | 2 | null | 2012-11-02 15:47:45.27 UTC | 2 | 2017-09-11 09:34:51.697 UTC | 2017-05-23 12:17:24.993 UTC | null | -1 | null | 675,383 | null | 1 | 11 | android|ddms | 45,524 | <p>I had same problem and none of given solutions worked. Then I have uninstalled all JRE 7 and installed latest JRE 6 (<a href="http://www.oracle.com/technetwork/java/javase/downloads/jre6downloads-1902815.html" rel="noreferrer">http://www.oracle.com/technetwork/java/javase/downloads/jre6downloads-1902815.html</a>). It have immediately fixed the problem.</p> |
13,017,840 | Using PySerial is it possible to wait for data? | <p>I've got a Python program which is reading data from a serial port via the <strong>PySerial</strong> module. The two conditions I need to keep in mind are: I don't know how much data will arrive, and I don't know when to expect data.</p>
<p>Based on this I have came up with the follow code snippets:</p>
<pre><code>#Code from main loop, spawning thread and waiting for data
s = serial.Serial(5, timeout=5) # Open COM5, 5 second timeout
s.baudrate = 19200
#Code from thread reading serial data
while 1:
tdata = s.read(500) # Read 500 characters or 5 seconds
if(tdata.__len__() > 0): #If we got data
if(self.flag_got_data is 0): #If it's the first data we recieved, store it
self.data = tdata
else: #if it's not the first, append the data
self.data += tdata
self.flag_got_data = 1
</code></pre>
<p>So this code will loop forever getting data off the serial port. We'll get up to 500 characters store the data, then alert the main loop by setting a flag. If no data is present we'll just go back to sleep and wait.</p>
<p>The code is working, but I don't like the 5s timeout. I need it because I don't know how much data to expect, but I don't like that it's waking up every 5 seconds even when no data is present. </p>
<p>Is there any way to check when data becomes available before doing the <code>read</code>? I'm thinking something like the <code>select</code> command in Linux.</p>
<p><strong>Note:</strong> I found the <code>inWaiting()</code> method, but really that seems it just change my "sleep" to a poll, so that's not what I want here. I just want to sleep until data comes in, then go get it.</p> | 13,018,267 | 3 | 0 | null | 2012-10-22 18:53:15.713 UTC | 11 | 2020-02-19 19:26:05.45 UTC | 2019-05-06 04:35:03.803 UTC | null | 1,287,812 | null | 1,348,709 | null | 1 | 24 | python|serial-port|pyserial | 89,698 | <p>Ok, I actually got something together that I like for this. Using a combination of <code>read()</code> with no timeout and the <code>inWaiting()</code> method:</p>
<pre><code>#Modified code from main loop:
s = serial.Serial(5)
#Modified code from thread reading the serial port
while 1:
tdata = s.read() # Wait forever for anything
time.sleep(1) # Sleep (or inWaiting() doesn't give the correct value)
data_left = s.inWaiting() # Get the number of characters ready to be read
tdata += s.read(data_left) # Do the read and combine it with the first character
... #Rest of the code
</code></pre>
<p>This seems to give the results I wanted, I guess this type of functionality doesn't exist as a single method in Python</p> |
12,941,703 | Use cURL with SNI (Server Name Indication) | <p>I am trying to use cURL to post to an API that just started using SNI (so they could host multiple ssl certs on 1 IP address). </p>
<p>My cURL stopped working as a result of this move to SNI. They explained that it's because cURL is getting *.domain-a.com back instead of *.domain-b.com so the SSL fails. </p>
<p>This seems to be a bug in cURL because the API URL has no errors when visited from a browser.</p>
<p>Using this code, it does work: </p>
<pre><code>exec('curl -k -d "parameters=here", https://urlhere.com/', $output);
print_r($output);
</code></pre>
<p>However, using -k is bad because it doesn't verify the SSL cert. </p>
<p>Using this code, does NOT work: </p>
<pre><code>exec('curl -d "parameters=here", https://urlhere.com/', $output);
print_r($output);
</code></pre>
<p>So my question is, how can I use curl with SNI and still verify the SSL (not have to use -k). Is there another setting in PHP or a cURL option I can set to work around this?</p> | 12,942,331 | 2 | 0 | null | 2012-10-17 19:16:50.317 UTC | 13 | 2018-10-16 21:59:20.373 UTC | null | null | null | null | 922,522 | null | 1 | 38 | php|ssl|curl|sni | 83,602 | <p>To be able to use SNI, three conditions are required:</p>
<ul>
<li>Using a version of Curl that supports it, at least 7.18.1, according to the <a href="http://curl.haxx.se/changes.html" rel="noreferrer">change logs</a>.</li>
<li>Using a version of Curl compiled against a library that supports SNI, e.g. OpenSSL 0.9.8j (depending on the compilation options some older versions).</li>
<li>Using TLS 1.0 at least (not SSLv3).</li>
</ul>
<p>Note that Curl's debug code (<code>-v</code>) only displays the major version number (mainly to distinguish between SSLv2 and SSLv3+ types of messages, see <a href="https://github.com/bagder/curl/blob/9547be37c252416f856fea664ff91c4fbfd86c2c/lib/ssluse.c#L1383" rel="noreferrer"><code>ssl_tls_trace</code></a>), so it will still display "SSLv3" when you use TLS 1.0 or above (because they're effectively SSL v3.1 or above, 3 is the same major version number).</p>
<p>You could check that your installed version of curl can use SNI using Wireshark. If you make a connection using <code>curl -1 https://something</code>, if you expand the "Client Hello" message, you should be able to see a "<code>server_name</code>" extension.</p>
<p>I'm not sure which SSL/TLS version is used by default (depending on your compilation options) when you use <code>curl</code> without <code>-1</code> (for TLS 1.0) or <code>-3</code> (for SSLv3), but you can try to force <code>-1</code> on your command, since it won't work with SSLv3 anyway.</p> |
16,666,294 | How can I connect to the FitBit Zip over Bluetooth 4.0 LE on Linux with bluez? | <p>I purchased a FitBit zip. This device uses Bluetooth 4.0 LE. I would like to at least connect to it via bluez. If that is successful I want to see how much of the protocol I can figure out.</p>
<p>I am using a Lenovo P500 Ideapad which has integrated support for Bluetooth 4.0. It seems to work (kind of)</p>
<p>When I do:</p>
<pre><code>hcitool lescan
</code></pre>
<p>I am able to find the device's bluetooth address, which (though potentially irrelevant) is: CF:D9:24:DB:F4:7B</p>
<p>Now, I read in another question: <a href="https://stackoverflow.com/questions/15657007/bluetooth-low-energy-listening-for-notifications-indications-in-linux">Bluetooth Low Energy: listening for notifications/indications in linux</a> that I can listen for notifications and other protocol features. I've worked with old bluetooth, but I have no experience with bluetooth LE.</p>
<p>I am getting stuck trying to use <code>hcitool lecc</code> or <code>gatttool</code> to connect to the device. The connection times out and seems to leave bluetooth in a bad state on the Linux box. I am able to fix that by reloading bluetooth related kernel modules.</p>
<p>Any hints are appreciated. I'm trying with the latest bluez now.</p> | 21,832,044 | 2 | 0 | null | 2013-05-21 09:16:09.813 UTC | 8 | 2021-08-23 10:13:32.003 UTC | 2017-05-23 12:17:05.377 UTC | null | -1 | null | 615,740 | null | 1 | 25 | linux|reverse-engineering|bluez|fitbit | 16,447 | <p>Have a look at the <a href="https://github.com/benallard/galileo" rel="nofollow noreferrer">galileo project</a>, we are able to connect to the tracker (and synchronise it) using the Fitbit dongle, which is also a BluetoothLE connector. The bytes used there should help you figure out the one you need ...</p>
<p><strong>Full Disclosure</strong>: I am the maintainer of this project.</p> |
16,830,946 | Request for example: Recurrent neural network for predicting next value in a sequence | <p>Can anyone give me a practicale example of a recurrent neural network in (pybrain) python in order to predict the next value of a sequence ?
(I've read the pybrain documentation and there is no clear example for it I think.)
I also found this <a href="https://stackoverflow.com/questions/12689293/event-sequences-recurrent-neural-networks-pybrain">question</a>. But I fail to see how it works in a more general case. So therefore I'm asking if anyone here could work out a <strong>clear example of how to predict the next value of a sequence in pybrain, with a recurrent neural network</strong>.</p>
<p>To give an example.</p>
<p>Say for example we have a sequence of numbers in the range [1,7].</p>
<pre><code>First run (So first example): 1 2 4 6 2 3 4 5 1 3 5 6 7 1 4 7 1 2 3 5 6
Second run (So second example): 1 2 5 6 2 4 4 5 1 2 5 6 7 1 4 6 1 2 3 3 6
Third run (So third example): 1 3 5 7 2 4 6 7 1 3 5 6 7 1 4 6 1 2 2 3 7
and so on.
</code></pre>
<p>Now given for example the start of a new sequence: <strong>1 3 5 7 2 4 6 7 1 3</strong> </p>
<p>what is/are the next value(s)</p>
<p>This question might seem lazy, but I think there lacks a good and decent example of how to do this with pybrain. </p>
<hr>
<p><strong>Additionally: How can this be done if more than 1 feature is present:</strong></p>
<p>Example:</p>
<p>Say for example we have several sequences (each sequence having 2 features) in the range [1,7].</p>
<pre><code>First run (So first example): feature1: 1 2 4 6 2 3 4 5 1 3 5 6 7 1 4 7 1 2 3 5 6
feature2: 1 3 5 7 2 4 6 7 1 3 5 6 7 1 4 6 1 2 2 3 7
Second run (So second example): feature1: 1 2 5 6 2 4 4 5 1 2 5 6 7 1 4 6 1 2 3 3 6
feature2: 1 2 3 7 2 3 4 6 2 3 5 6 7 2 4 7 1 3 3 5 6
Third run (So third example): feature1: 1 3 5 7 2 4 6 7 1 3 5 6 7 1 4 6 1 2 2 3 7
feature2: 1 2 4 6 2 3 4 5 1 3 5 6 7 1 4 7 1 2 3 5 6
and so on.
</code></pre>
<p>Now given for example the start of a new sequences: </p>
<pre><code> feature 1: 1 3 5 7 2 4 6 7 1 3
feature 2: 1 2 3 7 2 3 4 6 2 4
</code></pre>
<p>what is/are the next value(s)</p>
<hr>
<p>Feel free to use your own example as long it is similar to these examples and has some in depth explanation.</p> | 18,756,932 | 2 | 0 | null | 2013-05-30 08:04:51.587 UTC | 15 | 2013-09-12 20:12:06.697 UTC | 2017-05-23 11:53:50.157 UTC | null | -1 | null | 329,829 | null | 1 | 29 | python|machine-learning|neural-network|time-series|pybrain | 13,857 | <p>Issam Laradji's worked for me to predict sequence of sequences, except my version of pybrain required a tuple for the UnserpervisedDataSet object:</p>
<pre><code>from pybrain.tools.shortcuts import buildNetwork
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.datasets import SupervisedDataSet,UnsupervisedDataSet
from pybrain.structure import LinearLayer
ds = SupervisedDataSet(21, 21)
ds.addSample(map(int,'1 2 4 6 2 3 4 5 1 3 5 6 7 1 4 7 1 2 3 5 6'.split()),map(int,'1 2 5 6 2 4 4 5 1 2 5 6 7 1 4 6 1 2 3 3 6'.split()))
ds.addSample(map(int,'1 2 5 6 2 4 4 5 1 2 5 6 7 1 4 6 1 2 3 3 6'.split()),map(int,'1 3 5 7 2 4 6 7 1 3 5 6 7 1 4 6 1 2 2 3 7'.split()))
net = buildNetwork(21, 20, 21, outclass=LinearLayer,bias=True, recurrent=True)
trainer = BackpropTrainer(net, ds)
trainer.trainEpochs(100)
ts = UnsupervisedDataSet(21,)
ts.addSample(map(int,'1 3 5 7 2 4 6 7 1 3 5 6 7 1 4 6 1 2 2 3 7'.split()))
[ int(round(i)) for i in net.activateOnDataset(ts)[0]]
</code></pre>
<p>gives:</p>
<p><em><code>=> [1, 2, 5, 6, 2, 4, 5, 6, 1, 2, 5, 6, 7, 1, 4, 6, 1, 2, 2, 3, 6]</code></em></p>
<p>To predict smaller sequences, just train it up as such, either as sub sequences or as overlapping sequences (overlapping shown here):</p>
<pre><code>from pybrain.tools.shortcuts import buildNetwork
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.datasets import SupervisedDataSet,UnsupervisedDataSet
from pybrain.structure import LinearLayer
ds = SupervisedDataSet(10, 11)
z = map(int,'1 2 4 6 2 3 4 5 1 3 5 6 7 1 4 7 1 2 3 5 6 1 2 5 6 2 4 4 5 1 2 5 6 7 1 4 6 1 2 3 3 6 1 3 5 7 2 4 6 7 1 3 5 6 7 1 4 6 1 2 2 3 7'.split())
obsLen = 10
predLen = 11
for i in xrange(len(z)):
if i+(obsLen-1)+predLen < len(z):
ds.addSample([z[d] for d in range(i,i+obsLen)],[z[d] for d in range(i+1,i+1+predLen)])
net = buildNetwork(10, 20, 11, outclass=LinearLayer,bias=True, recurrent=True)
trainer = BackpropTrainer(net, ds)
trainer.trainEpochs(100)
ts = UnsupervisedDataSet(10,)
ts.addSample(map(int,'1 3 5 7 2 4 6 7 1 3'.split()))
[ int(round(i)) for i in net.activateOnDataset(ts)[0]]
</code></pre>
<p>gives:</p>
<p><em><code>=> [3, 5, 6, 2, 4, 5, 6, 1, 2, 5, 6]</code></em></p>
<p>Not too good...</p> |
25,471,114 | How to validate an e-mail address in swift? | <p>Does anyone know how to validate an e-mail address in Swift? I found this code:</p>
<pre><code>- (BOOL) validEmail:(NSString*) emailString {
if([emailString length]==0){
return NO;
}
NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
NSLog(@"%i", regExMatches);
if (regExMatches == 0) {
return NO;
} else {
return YES;
}
}
</code></pre>
<p>but I can't translate it to Swift.</p> | 25,471,164 | 40 | 9 | null | 2014-08-24 11:15:58.583 UTC | 94 | 2022-05-30 13:34:35.697 UTC | 2021-11-09 08:36:18.893 UTC | null | 8,090,893 | null | 3,842,100 | null | 1 | 404 | ios|swift|validation|email|nsregularexpression | 258,853 | <p>I would use <a href="https://developer.apple.com/documentation/foundation/nspredicate" rel="noreferrer"><code>NSPredicate</code></a>:</p>
<pre class="lang-swift prettyprint-override"><code>func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
</code></pre>
<p><em>for versions of Swift earlier than 3.0:</em></p>
<pre class="lang-swift prettyprint-override"><code>func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
</code></pre>
<p><em>for versions of Swift earlier than 1.2:</em></p>
<pre class="lang-swift prettyprint-override"><code>func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
return emailPred.evaluateWithObject(email)
}
return false
}
</code></pre> |
4,395,000 | T4 template to Generate Enums | <p>I'm looking at creating a T4 template to generate enums of my database.
Essentially, I want the same feature as SubSonic e.g. Product.Columns.ProductId for Linq-to-SQL or Entity Framework 4. </p>
<p>Any help would be much appreciated.
thanks. </p> | 4,480,173 | 2 | 0 | null | 2010-12-09 04:59:46.08 UTC | 20 | 2017-02-08 16:33:15.073 UTC | 2017-02-08 16:33:15.073 UTC | null | 1,566,165 | null | 332,395 | null | 1 | 19 | linq-to-sql|t4 | 8,647 | <p>I have written one for my needs that converts a lookup table of your choice to an enum:
Put this code inside an <strong>EnumGenerator.ttinclude</strong> file:</p>
<pre><code><#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".generated.cs" #>
<#@ Assembly Name="System.Data" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
string tableName = Path.GetFileNameWithoutExtension(Host.TemplateFile);
string path = Path.GetDirectoryName(Host.TemplateFile);
string columnId = tableName + "ID";
string columnName = "Name";
string connectionString = "data source=.;initial catalog=DBName;integrated security=SSPI";
#>
using System;
using System.CodeDom.Compiler;
namespace Services.<#= GetSubNamespace() #>
{
/// <summary>
/// <#= tableName #> auto generated enumeration
/// </summary>
[GeneratedCode("TextTemplatingFileGenerator", "10")]
public enum <#= tableName #>
{
<#
SqlConnection conn = new SqlConnection(connectionString);
string command = string.Format("select {0}, {1} from {2} order by {0}", columnId, columnName, tableName);
SqlCommand comm = new SqlCommand(command, conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
bool loop = reader.Read();
while(loop)
{
#> /// <summary>
/// <#= reader[columnName] #> configuration setting.
/// </summary>
<#= Pascalize(reader[columnName]) #> = <#= reader[columnId] #><# loop = reader.Read(); #><#= loop ? ",\r\n" : string.Empty #>
<#
}
#> }
}
<#+
private string Pascalize(object value)
{
Regex rx = new Regex(@"(?:[^a-zA-Z0-9]*)(?<first>[a-zA-Z0-9])(?<reminder>[a-zA-Z0-9]*)(?:[^a-zA-Z0-9]*)");
return rx.Replace(value.ToString(), m => m.Groups["first"].ToString().ToUpper() + m.Groups["reminder"].ToString().ToLower());
}
private string GetSubNamespace()
{
Regex rx = new Regex(@"(?:.+Services\s)");
string path = Path.GetDirectoryName(Host.TemplateFile);
return rx.Replace(path, string.Empty).Replace("\\", ".");
}
#>
</code></pre>
<p>Then whenever you'd like an enum to be generated, just create a <strong>tt</strong> file with the same name as database table like <strong>UserType.tt</strong> and put this code in:</p>
<pre><code><#@ include file="..\..\T4 Templates\EnumGenerator.ttinclude" #>
</code></pre>
<p>An even more advanced template is now available in my <a href="http://erraticdev.blogspot.com/2011/01/generate-enum-of-database-lookup-table.html" rel="noreferrer">blog post</a>.</p> |
9,973,159 | MySQL Left join WHERE table2.field = "X" | <p>I have the following tables:</p>
<p><strong>pages</strong>:</p>
<pre><code>+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| page_id | int(11) | NO | PRI | NULL | auto_increment |
| type | varchar(20) | NO | | NULL | |
| categories | varchar(255) | NO | | NULL | |
| title | varchar(255) | NO | MUL | NULL | |
| text | longtext | NO | MUL | NULL | |
+------------+--------------+------+-----+---------+----------------+
</code></pre>
<p><strong>custom</strong>:</p>
<pre><code>+---------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+-------+
| page_id | int(10) unsigned | NO | PRI | NULL | |
| key | varchar(255) | NO | PRI | NULL | |
| value | longtext | NO | | NULL | |
+---------+------------------+------+-----+---------+-------+
</code></pre>
<p>I want to join the tables in a way where:<br>
1) all the entries from the first table are returned <code>LEFT JOIN custom ON pages.page_id = custom.page_id</code><br>
2) <code>pages.type IN ('type_a', 'type_b', 'type_c')</code><br>
3) "key" from the second table has value "votes" <code>custom.key = 'votes'</code></p>
<p>I made everything so far, but the third condition is the problem. If there isn't entry for <code>key = 'votes'</code> in table <strong>custom</strong> the query returns only these with entries. I want to return <code>NULL</code> if missing entries. </p>
<p>I need <code>key = 'votes'</code>, because I have other entries for this page_id where the key is not 'votes' and this duplicates the rows from <strong>pages</strong></p> | 9,973,201 | 3 | 0 | null | 2012-04-02 08:33:49.133 UTC | 4 | 2012-04-02 08:42:08.677 UTC | null | null | null | null | 1,156,999 | null | 1 | 24 | mysql|join|left-join | 52,129 | <p>Simply add your contraint <code>custom.key='votes'</code> to the <code>LEFT JOIN</code></p>
<pre><code>SELECT *
FROM pages LEFT JOIN custom
ON pages.page_id=custom.page_id AND custom.key='votes'
WHERE pages.type IN('type_a','type_b','type_c') ;
</code></pre> |
9,726,705 | Assign multiple objects to .GlobalEnv from within a function | <p>A post on here a day back has me wondering how to assign values to multiple objects in the global environment from within a function. This is my attempt using <code>lapply</code> (<code>assign</code> may be safer than <code><<-</code> but I have never actually used it and am not familiar with it). </p>
<pre><code>#fake data set
df <- data.frame(
x.2=rnorm(25),
y.2=rnorm(25),
g=rep(factor(LETTERS[1:5]), 5)
)
#split it into a list of data frames
LIST <- split(df, df$g)
#pre-allot 5 objects in R with class data.frame()
V <- W <- X <- Y <- Z <- data.frame()
#attempt to assign the data frames in the LIST to the objects just created
lapply(seq_along(LIST), function(x) c(V, W, X, Y, Z)[x] <<- LIST[[x]])
</code></pre>
<p>Please feel free to shorten any/all parts of my code to make this work (or work better/faster).</p> | 9,726,880 | 3 | 7 | null | 2012-03-15 19:24:23.39 UTC | 10 | 2022-05-03 17:41:53.99 UTC | 2016-04-28 13:28:11.56 UTC | null | 202,229 | null | 1,000,343 | null | 1 | 33 | r|global|environment|assign|assignment-operator | 21,214 | <p><strong>Update of 2018-10-10:</strong></p>
<p>The most succinct way to carry out this specific task is to use <code>list2env()</code> like so:</p>
<pre><code>## Create an example list of five data.frames
df <- data.frame(x = rnorm(25),
g = rep(factor(LETTERS[1:5]), 5))
LIST <- split(df, df$g)
## Assign them to the global environment
list2env(LIST, envir = .GlobalEnv)
## Check that it worked
ls()
## [1] "A" "B" "C" "D" "df" "E" "LIST"
</code></pre>
<hr>
<p><strong>Original answer, demonstrating use of assign()</strong></p>
<p>You're right that <code>assign()</code> is the right tool for the job. Its <code>envir</code> argument gives you precise control over where assignment takes place -- control that is not available with either <code><-</code> or <code><<-</code>. </p>
<p>So, for example, to assign the value of <code>X</code> to an object named <code>NAME</code> in the the global environment, you would do:</p>
<pre><code>assign("NAME", X, envir = .GlobalEnv)
</code></pre>
<p>In your case:</p>
<pre><code>df <- data.frame(x = rnorm(25),
g = rep(factor(LETTERS[1:5]), 5))
LIST <- split(df, df$g)
NAMES <- c("V", "W", "X", "Y", "Z")
lapply(seq_along(LIST),
function(x) {
assign(NAMES[x], LIST[[x]], envir=.GlobalEnv)
}
)
ls()
[1] "df" "LIST" "NAMES" "V" "W" "X" "Y" "Z"
</code></pre> |
10,140,669 | How to get Redis running on Azure? | <p>I have seen several references to people running Redis on Azure, but no implementation or any sort of 'howto' on it. Has anyone seen such an example?</p> | 10,190,091 | 3 | 3 | null | 2012-04-13 12:18:02.05 UTC | 17 | 2018-07-25 02:04:37.793 UTC | 2018-07-25 02:04:37.793 UTC | null | 1,033,581 | null | 11,220 | null | 1 | 35 | azure|redis | 10,245 | <ol>
<li>Download Redis for Windows - see the section 'Redis Service builds for Windows' on <a href="https://github.com/ServiceStack/ServiceStack.Redis">https://github.com/ServiceStack/ServiceStack.Redis</a>. I ended up using the win64 version from dmajkic <a href="https://github.com/dmajkic/redis/downloads">https://github.com/dmajkic/redis/downloads</a></li>
<li>Create an Azure worker role, delete the default class (you don't need c# code at all). Add the file redis-server.exe from the downloaded redis source (the exe can be found in redis/src).</li>
<li><p>In the service definition file add the following config</p>
<pre><code><WorkerRole name="my.Worker" vmsize="Small">
<Runtime executionContext="limited">
<EntryPoint>
<ProgramEntryPoint commandLine="redis-server.exe" setReadyOnProcessStart="true" />
</EntryPoint>
</Runtime>
<Imports>
<Import moduleName="Diagnostics" />
<Import moduleName="RemoteAccess" />
<Import moduleName="RemoteForwarder" />
</Imports>
<Endpoints>
<InternalEndpoint name="Redis" protocol="tcp" port="6379" />
</Endpoints>
</WorkerRole>
</code></pre></li>
<li><p>You can refer to the redis server from your web role using the following</p>
<pre><code>var ipEndpoint = RoleEnvironment.Roles["my.Worker"].Instances[0].InstanceEndpoints["Redis"].IPEndpoint;
host = string.Format("{0}:{1}", ipEndpoint.Address, ipEndpoint.Port);
</code></pre></li>
</ol>
<p>Hope that helps.</p> |
9,828,311 | How to get min, seconds and milliseconds from datetime.now() in python? | <pre><code>>>> a = str(datetime.now())
>>> a
'2012-03-22 11:16:11.343000'
</code></pre>
<p>I need to get a string like that: <code>'16:11.34'</code>.</p>
<p>Should be as compact as possible. </p>
<p>Or should I use time() instead?
How do I get it?</p> | 9,828,399 | 8 | 4 | null | 2012-03-22 18:27:48.883 UTC | 5 | 2022-07-24 09:33:23.383 UTC | 2012-03-22 20:31:28.73 UTC | null | 673,993 | null | 673,993 | null | 1 | 35 | python|datetime|time | 152,192 | <p>What about:</p>
<p><code>datetime.now().strftime('%M:%S.%f')[:-4]</code></p>
<p>I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.</p>
<p><strong>EDIT</strong></p>
<p>If the <code>%f</code> modifier doesn't work for you, you can try something like:</p>
<pre><code>now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]
</code></pre>
<p>Again, I'm assuming you just want to truncate the precision.</p> |
28,321,457 | TaskContinuationOptions.RunContinuationsAsynchronously and Stack Dives | <p>In <a href="https://devblogs.microsoft.com/pfxteam/new-task-apis-in-net-4-6/" rel="noreferrer">this blog post</a>, Stephan Toub describes a new feature that will be included in .NET 4.6 which adds another value to the TaskCreationOptions and TaskContinuationOptions enums called <code>RunContinuationsAsynchronously</code>.</p>
<p>He explains:</p>
<blockquote>
<p>"I talked about a ramification of calling {Try}Set* methods on
TaskCompletionSource, that any synchronous continuations off
of the TaskCompletionSource’s Task could run synchronously as
part of the call. If we were to invoke SetResult here while holding
the lock, then synchronous continuations off of that Task would be run
while holding the lock, and that could lead to very real problems.
So, while holding the lock we grab the TaskCompletionSource to
be completed, but we don’t complete it yet, delaying doing so until
the lock has been released"</p>
</blockquote>
<p>And gives the following example to demonstrate:</p>
<pre><code>private SemaphoreSlim _gate = new SemaphoreSlim(1, 1);
private async Task WorkAsync()
{
await _gate.WaitAsync().ConfigureAwait(false);
try
{
// work here
}
finally { _gate.Release(); }
}
</code></pre>
<blockquote>
<p>Now imagine that you have lots of calls to WorkAsync:</p>
</blockquote>
<pre><code>await Task.WhenAll(from i in Enumerable.Range(0, 10000) select WorkAsync());
</code></pre>
<blockquote>
<p>We've just created 10,000 calls to WorkAsync that will be
appropriately serialized on the semaphore. One of the tasks will
enter the critical region, and the others will queue up on the
WaitAsync call, inside SemaphoreSlim effectively enqueueing the task
to be completed when someone calls Release. If Release completed that
Task synchronously, then when the first task calls Release, it'll
synchronously start executing the second task, and when it calls
Release, it'll synchronously start executing the third task, and so
on. <strong>If the "//work here" section of code above didn't include any
awaits that yielded, then we're potentially going to stack dive here
and eventually potentially blow out the stack.</strong></p>
</blockquote>
<p>I'm having a hard time grasping the part where he talks about executing the continuation synchronously.</p>
<h2>Question</h2>
<p>How could this possibly cause a stack dive? More so, And what is <code>RunContinuationsAsynchronously</code> effectively going to do in order to solve that problem?</p> | 28,321,688 | 2 | 6 | null | 2015-02-04 12:29:54.517 UTC | 12 | 2021-04-20 09:54:48.253 UTC | 2021-04-20 09:54:48.253 UTC | null | 1,402,846 | null | 1,870,803 | null | 1 | 26 | c#|.net|task-parallel-library|async-await|.net-4.6 | 8,871 | <p>The key concept here is that a task's continuation may run synchronously on the same thread that completed the antecedent task.</p>
<p>Let's imagine that this is <code>SemaphoreSlim.Release</code>'s implementation (it's actually Toub's <a href="http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266983.aspx" rel="noreferrer"><code>AsyncSemphore</code></a>'s):</p>
<pre><code>public void Release()
{
TaskCompletionSource<bool> toRelease = null;
lock (m_waiters)
{
if (m_waiters.Count > 0)
toRelease = m_waiters.Dequeue();
else
++m_currentCount;
}
if (toRelease != null)
toRelease.SetResult(true);
}
</code></pre>
<p>We can see that it synchronously completes a task (using <code>TaskCompletionSource</code>).
In this case, if <code>WorkAsync</code> has no other asynchronous points (i.e. no <code>await</code>s at all, or all <code>await</code>s are on an already completed task) and calling <code>_gate.Release()</code> may complete a pending call to <code>_gate.WaitAsync()</code> synchronously on the same thread you may reach a state in which a single thread sequentially releases the semaphore, completes the next pending call, executes <code>// work here</code> and then releases the semaphore again etc. etc.</p>
<p>This means that the same thread goes deeper and deeper in the stack, hence stack dive.</p>
<p><code>RunContinuationsAsynchronously</code> makes sure the continuation doesn't run synchronously and so the thread that releases the semaphore moves on and the continuation is scheduled for another thread (which one depends on the other continuation parameters e.g. <code>TaskScheduler</code>)</p>
<p>This logically resembles posting the completion to the <code>ThreadPool</code>:</p>
<pre><code>public void Release()
{
TaskCompletionSource<bool> toRelease = null;
lock (m_waiters)
{
if (m_waiters.Count > 0)
toRelease = m_waiters.Dequeue();
else
++m_currentCount;
}
if (toRelease != null)
Task.Run(() => toRelease.SetResult(true));
}
</code></pre> |
9,787,853 | join or merge with overwrite in pandas | <p>I want to perform a join/merge/append operation on a dataframe with datetime index.</p>
<p>Let's say I have <code>df1</code> and I want to add <code>df2</code> to it. <code>df2</code> can have fewer or more columns, and overlapping indexes. For all rows where the indexes match, if <code>df2</code> has the same column as <code>df1</code>, I want the values of <code>df1</code> be overwritten with those from <code>df2</code>. </p>
<p>How can I obtain the desired result? </p> | 9,794,891 | 2 | 0 | null | 2012-03-20 13:36:09.263 UTC | 20 | 2021-09-24 03:13:33.243 UTC | 2012-03-20 15:48:45.95 UTC | null | 192,839 | null | 566,942 | null | 1 | 63 | python|pandas | 49,834 | <p>How about: <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="noreferrer"><code>df2.combine_first(df1)</code></a>? </p>
<pre><code>In [33]: df2
Out[33]:
A B C D
2000-01-03 0.638998 1.277361 0.193649 0.345063
2000-01-04 -0.816756 -1.711666 -1.155077 -0.678726
2000-01-05 0.435507 -0.025162 -1.112890 0.324111
2000-01-06 -0.210756 -1.027164 0.036664 0.884715
2000-01-07 -0.821631 -0.700394 -0.706505 1.193341
2000-01-10 1.015447 -0.909930 0.027548 0.258471
2000-01-11 -0.497239 -0.979071 -0.461560 0.447598
In [34]: df1
Out[34]:
A B C
2000-01-03 2.288863 0.188175 -0.040928
2000-01-04 0.159107 -0.666861 -0.551628
2000-01-05 -0.356838 -0.231036 -1.211446
2000-01-06 -0.866475 1.113018 -0.001483
2000-01-07 0.303269 0.021034 0.471715
2000-01-10 1.149815 0.686696 -1.230991
2000-01-11 -1.296118 -0.172950 -0.603887
2000-01-12 -1.034574 -0.523238 0.626968
2000-01-13 -0.193280 1.857499 -0.046383
2000-01-14 -1.043492 -0.820525 0.868685
In [35]: df2.comb
df2.combine df2.combineAdd df2.combine_first df2.combineMult
In [35]: df2.combine_first(df1)
Out[35]:
A B C D
2000-01-03 0.638998 1.277361 0.193649 0.345063
2000-01-04 -0.816756 -1.711666 -1.155077 -0.678726
2000-01-05 0.435507 -0.025162 -1.112890 0.324111
2000-01-06 -0.210756 -1.027164 0.036664 0.884715
2000-01-07 -0.821631 -0.700394 -0.706505 1.193341
2000-01-10 1.015447 -0.909930 0.027548 0.258471
2000-01-11 -0.497239 -0.979071 -0.461560 0.447598
2000-01-12 -1.034574 -0.523238 0.626968 NaN
2000-01-13 -0.193280 1.857499 -0.046383 NaN
2000-01-14 -1.043492 -0.820525 0.868685 NaN
</code></pre>
<p>Note that it takes the values from <code>df1</code> for indices that do not overlap with <code>df2</code>. If this doesn't do exactly what you want I would be willing to improve this function / add options to it.</p> |
9,837,602 | Why isn't there a Guid.IsNullOrEmpty() method | <p>This keeps me wondering why Guid in .NET does not have <code>IsNullOrEmpty()</code> method (where empty means all zeros)</p>
<p>I need this at several places in my ASP.NET MVC code when writing the REST API.</p>
<p>Or am I missing something because nobody on the Internet has asked for the same?</p> | 9,837,628 | 7 | 1 | null | 2012-03-23 10:27:14.267 UTC | 13 | 2020-10-01 08:33:49.583 UTC | 2012-07-14 21:23:41.65 UTC | null | 727,208 | null | 15,065 | null | 1 | 113 | c#|asp.net-mvc | 95,156 | <p><code>Guid</code> is a <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/value-types" rel="noreferrer">value type</a>, so a variable of type <code>Guid</code> can't be null to start with. If you want to know if it's the same as the empty guid, you can just use:</p>
<pre><code>if (guid == Guid.Empty)
</code></pre> |
10,115,799 | Set up DNS based URL forwarding in Amazon Route53 | <p>I'm trying to setup forwarding in Amazon Route53. My last DNS service (Nettica) allowed me to route requests to "aws.example.com" to "https://myaccount.signin.aws.amazon.com/console/".</p>
<p>Is this functionality supported by Route53?</p>
<p>How does Nettica achieve this? Does it insert a special A, CNAME, PTR, or TXT record(s)?</p> | 14,289,082 | 5 | 1 | null | 2012-04-12 00:20:30.313 UTC | 116 | 2019-01-23 03:46:32.243 UTC | 2013-05-13 20:13:16.937 UTC | null | 59,087 | null | 498,782 | null | 1 | 158 | dns|forwarding|amazon-route53 | 192,954 | <p>I was running into the exact same problem that Saurav described, but I really needed to find a solution that did not require anything other than Route 53 and S3. I created a how-to guide for my blog detailing what I did. </p>
<p>Here is what I came up with. </p>
<hr>
<h1>Objective</h1>
<p>Using only the tools available in Amazon S3 and Amazon Route 53, create a URL Redirect that automatically forwards <a href="http://url-redirect-example.vivekmchawla.com" rel="noreferrer">http://url-redirect-example.vivekmchawla.com</a> to the AWS Console sign-in page aliased to "MyAccount", located at <a href="https://myaccount.signin.aws.amazon.com/console/" rel="noreferrer">https://myaccount.signin.aws.amazon.com/console/</a> .</p>
<p>This guide will teach you set up URL forwarding to any URL, not just ones from Amazon. You will learn how to set up forwarding to specific folders (like "/console" in my example), and how to change the protocol of the redirect from HTTP to HTTPS (or vice versa).</p>
<hr>
<h1>Step One: Create Your S3 Bucket</h1>
<p><img src="https://i.stack.imgur.com/MMDEu.png" alt="Open the S3 Management Console and click "Create Bucket""></p>
<p>Open the S3 management console and click "Create Bucket". </p>
<hr>
<h1>Step Two: Name Your S3 Bucket</h1>
<p><img src="https://i.stack.imgur.com/cfg1z.png" alt="Name your S3 Bucket"></p>
<ol>
<li><p>Choose a Bucket Name. This step is really important! You must name the bucket EXACTLY the same as the URL you want to set up for forwarding. For this guide, I'll use the name "url-redirect-example.vivekmchawla.com". </p></li>
<li><p>Select whatever region works best for you. If you don't know, keep the default. </p></li>
<li><p>Don't worry about setting up logging. Just click the "Create" button when you're ready. </p></li>
</ol>
<hr>
<h1>Step 3: Enable Static Website Hosting and Specify Routing Rules</h1>
<p><img src="https://i.stack.imgur.com/8SAUW.png" alt="Enable Static Website Hosting and Specify Routing Rules"></p>
<ol>
<li>In the properties window, open the settings for "Static Website Hosting".</li>
<li>Select the option to "Enable website hosting".</li>
<li>Enter a value for the "Index Document". This object (document) will never be served by S3, and you never have to upload it. Just use any name you want.</li>
<li>Open the settings for "Edit Redirection Rules".</li>
<li><p>Paste the following XML snippet in it's entirety.</p>
<pre><code><RoutingRules>
<RoutingRule>
<Redirect>
<Protocol>https</Protocol>
<HostName>myaccount.signin.aws.amazon.com</HostName>
<ReplaceKeyPrefixWith>console/</ReplaceKeyPrefixWith>
<HttpRedirectCode>301</HttpRedirectCode>
</Redirect>
</RoutingRule>
</RoutingRules>
</code></pre></li>
</ol>
<p>If you're curious about what the above XML is doing, visit the <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HowDoIWebsiteConfiguration.html#configure-bucket-as-website-routing-rule-syntax" rel="noreferrer">AWM Documentation for "Syntax for Specifying Routing Rules"</a>. A bonus technique (not covered here) is forwarding to specific pages at the destination host, for example <code>http://redirect-destination.com/console/special-page.html</code>. Read about the <code><ReplaceKeyWith></code> element if you need this functionality.</p>
<hr>
<h1>Step 4: Make Note of Your Redirect Bucket's "Endpoint"</h1>
<p><img src="https://i.stack.imgur.com/BXHyR.png" alt="Make a note of your Redirect Bucket's Endpoint"></p>
<p>Make note of the Static Website Hosting "endpoint" that Amazon automatically created for this bucket. You'll need this for later, so highlight the entire URL, then copy and paste it to notepad.</p>
<p><strong>CAUTION!</strong> At this point you can actually click this link to check to see if your Redirection Rules were entered correctly, but be careful! Here's why...</p>
<p>Let's say you entered the wrong value inside the <code><Hostname></code> tags in your Redirection Rules. Maybe you accidentally typed <code>myaccount.amazon.com</code>, instead of <code>myaccount.signin.aws.amazon.com</code>. If you click the link to test the Endpoint URL, AWS will happily redirect your browser to the wrong address!</p>
<p>After noticing your mistake, you will probably edit the <code><Hostname></code> in your Redirection Rules to fix the error. Unfortunately, when you try to click the link again, you'll most likely end up being redirected back to the wrong address! Even though you fixed the <code><Hostname></code> entry, your browser is caching the previous (incorrect!) entry. This happens because we're using an HTTP 301 (permanent) redirect, which browsers like Chrome and Firefox will cache by default.</p>
<p>If you copy and paste the Endpoint URL to a different browser (or clear the cache in your current one), you'll get another chance to see if your updated <code><Hostname></code> entry is finally the correct one.</p>
<p>To be safe, if you want to test your Endpoint URL and Redirect Rules, you should open a private browsing session, like "Incognito Mode" in Chrome. Copy, paste, and test the Endpoint URL in Incognito Mode and anything cached will go away once you close the session.</p>
<hr>
<h1>Step 5: Open the Route53 Management Console and Go To the Record Sets for Your Hosted Zone (Domain Name)</h1>
<p><img src="https://i.stack.imgur.com/TxPwi.png" alt="Open the Route 53 Management Console to Add Record Sets to your Hosted Zone"></p>
<ol>
<li>Select the Hosted Zone (domain name) that you used when you created your bucket. Since I named my bucket "url-redirect-example.vivekmchawla.com", I'm going to select the vivekmchawla.com Hosted Zone.</li>
<li>Click on the "Go to Record Sets" button.</li>
</ol>
<hr>
<h1>Step 6: Click the "Create Record Set" Button</h1>
<p><img src="https://i.stack.imgur.com/RNRfE.png" alt="Click the Create Record Set button"></p>
<p>Clicking "Create Record Set" will open up the Create Record Set window on the right side of the Route53 Management Console.</p>
<hr>
<h1>Step 7: Create a CNAME Record Set</h1>
<p><img src="https://i.stack.imgur.com/xn7nh.png" alt="Create a CNAME Record Set"></p>
<ol>
<li><p>In the Name field, enter the hostname portion of the URL that you used when naming your S3 bucket. The "hostname portion" of the URL is everything to the LEFT of your Hosted Zone's name. I named my S3 bucket "url-redirect-example.vivekmchawla.com", and my Hosted Zone is "vivekmchawla.com", so the hostname portion I need to enter is "url-redirect-example".</p></li>
<li><p>Select "CNAME - Canonical name" for the Type of this Record Set.</p></li>
<li><p>For the Value, paste in the Endpoint URL of the S3 bucket we created back in Step 3.</p></li>
<li><p>Click the "Create Record Set" button. Assuming there are no errors, you'll now be able to see a new CNAME record in your Hosted Zone's list of Record Sets.</p></li>
</ol>
<hr>
<h1>Step 8: Test Your New URL Redirect</h1>
<p>Open up a new browser tab and type in the URL that we just set up. For me, that's <a href="http://url-redirect-example.vivekmchawla.com/" rel="noreferrer">http://url-redirect-example.vivekmchawla.com</a>. If everything worked right, you should be sent directly to an AWS sign-in page. </p>
<p>Because we used the <code>myaccount.signin.aws.amazon.com</code> alias as our redirect's destination URL, Amazon knows exactly which account we're trying to access, and takes us directly there. This can be very handy if you want to give a short, clean, branded AWS login link to employees or contractors.</p>
<p><img src="https://i.stack.imgur.com/Kr8UI.png" alt="All done! Your URL forwarding should take you to the AWS sign-in page."></p>
<hr>
<h1>Conclusions</h1>
<p>I personally love the various AWS services, but if you've decided to migrate DNS management to Amazon Route 53, the lack of easy URL forwarding can be frustrating. I hope this guide helped make setting up URL forwarding for your Hosted Zones a bit easier.</p>
<p>If you'd like to learn more, please take a look at the following pages from the AWS Documentation site.</p>
<ul>
<li><a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-custom-domain-walkthrough.html" rel="noreferrer">Example: Setting Up a Static Website Using a Custom Domain</a></li>
<li><a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HowDoIWebsiteConfiguration.html" rel="noreferrer">Configure a Bucket for Website Hosting</a></li>
<li><a href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/R53Example.html" rel="noreferrer">Creating a Domain that Uses Route 53</a></li>
<li><a href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/RRSchanges.html" rel="noreferrer">Creating, Changing, and Deleting Resource Records</a></li>
</ul>
<p>Cheers!</p> |
7,824,967 | How do I subscribe to PropertyChanged event in my ViewModel? | <p>I have core functionality encapsulated in <code>ViewModelBase</code></p>
<p>Now I want to see when PropertyChanged event was raised by ViewModelBase and act on it. For example, when one property was changed on ViewModelBase - I want to change property on my ViewModel</p>
<p>How do I achieve this?</p>
<pre><code>public class MaintainGroupViewModel : BaseViewModel<MEMGroup>
{
public abstract class BaseViewModel<T> : NotificationObject, INavigationAware
where T : Entity
{
</code></pre> | 7,825,063 | 3 | 1 | null | 2011-10-19 16:49:41.753 UTC | 4 | 2011-10-19 16:58:40.537 UTC | null | null | null | null | 509,600 | null | 1 | 23 | c#|mvvm|inotifypropertychanged | 56,166 | <p>I am concerned that you're effectively doing a 'manual binding' (bad) for a property in a derived class to a value on the base class (also bad). The whole point of using inheritance is that the derived class can access things in the base class. Use a <code>protected</code> modifier to indicate things should only be accessible to derived classes.</p>
<p>I would suggest this (potentially) more correct method:</p>
<p>Base class:</p>
<pre><code>protected virtual void OnMyValueChanged() { }
</code></pre>
<p>Derived class:</p>
<pre><code>protected override void OnMyValueChanged() { /* respond here */ }
</code></pre>
<p>Really, subscribing to an event in the base class of the very class you're writing just seems incredibly backwards - what's the point of using inheritance over composition if you're going to compose yourself around yourself? You're literally asking an object to tell itself when something happens. A method call is what you should use for that.</p>
<p>In terms of <em>"when one property was changed on ViewModelBase - I want to change property on my ViewModel"</em>, ... they are the same object!</p> |
11,698,283 | Passing a string array as a parameter to a function java | <p>I would like to pass a string array as a parameter to a function. Please look at the code below </p>
<pre><code>String[] stringArray = {'a', 'b', 'c', 'd', 'e'};
functionFoo(stringArray);
</code></pre>
<p>Instead of:</p>
<pre><code>functionFoo('a', 'b', 'c', 'd', 'e');
</code></pre>
<p>but if I do this I am getting an error stating that convert <code>String[]</code> into <code>String</code>. I would like to know if it is possible to pass the values like that or what is the correct way to do it.</p> | 11,698,289 | 8 | 2 | null | 2012-07-28 04:27:43.933 UTC | 4 | 2021-04-25 00:00:16.583 UTC | 2019-01-09 21:39:21.453 UTC | null | 7,602,110 | null | 1,305,675 | null | 1 | 13 | java|function|arrays | 169,609 | <p>How about:</p>
<pre><code>public class test {
public static void someFunction(String[] strArray) {
// do something
}
public static void main(String[] args) {
String[] strArray = new String[]{"Foo","Bar","Baz"};
someFunction(strArray);
}
}
</code></pre> |
11,727,598 | PIL image.open() working for some images but not others | <p>I use PIL to open AREA files from NOAA on a regular basis. In the last batch of images I received, the image.open() command simply does not work. Here is a simple code I wrote which yields the same results. It will open, rotate, and perform normal tasks with a file from a month ago, and not with a file from today.</p>
<pre><code>from PIL import Image
im = Image.open("path/to/file")
im.show()
</code></pre>
<p>Here's the error:</p>
<pre><code>File "image_goes.py", line 2, in <module>
im = Image.open("path/to/file")
File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 1980, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file
</code></pre>
<p>Here's what I have tried: </p>
<ol>
<li>Opening the image on two separate machines.</li>
<li>Changing the folder of the file in case there was a permission problem</li>
<li>Redownloading the image, as well as two other batches, both using FTP manually AND our automatic script.</li>
</ol>
<p>My hypothesis was that there was a problem with our downloading script and that it was not fully downloading the file, but that hypothesis is rejected by the fact that the new files are the correct size and that I manually downloaded them using an FTP client and got the same results.</p>
<p>My only other theory is that there is a problem with the NOAA files today or that they have been changed in such a way that PIL can no longer handle them, but I find that unlikely.</p>
<p>Any help greatly appreciated,
Thanks</p> | 11,895,901 | 3 | 3 | null | 2012-07-30 18:41:25.557 UTC | 5 | 2021-03-15 21:12:26.523 UTC | null | null | null | null | 881,216 | null | 1 | 20 | python|image|python-imaging-library|noaa | 108,349 | <p>Maybe be the content is not actually synced to the disk. try <code>Image.open(open("path/to/file", 'rb'))</code></p> |
20,090,415 | img onclick call to JavaScript function | <p>I am trying to make a img that when it is clicked a JavaScript function is called.</p>
<p>I have searched on the web but haven't found anything that actually works (prob because of a mistake I made).</p>
<p>This code was made to pass JavaScript variables to a c# application.</p>
<p>Can anybody tell me what I am doing wrong?</p>
<pre><code> <script type="text/javascript">
function exportToForm(a,b,c,d,e) {
window.external.values(a.value, b.value, c.value, d.value, e.value);
}
</script>
</head>
<body>
<img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
<button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
</body>
</code></pre> | 20,090,475 | 5 | 5 | null | 2013-11-20 08:03:02.143 UTC | 6 | 2017-10-04 14:08:55.24 UTC | 2017-07-23 16:21:21.65 UTC | null | 438,581 | null | 2,787,169 | null | 1 | 17 | javascript|html | 238,132 | <p>This should work(with or without 'javascript:' part): </p>
<pre><code><img onclick="javascript:exportToForm('1.6','55','10','50','1')" src="China-Flag-256.png" />
<script>
function exportToForm(a, b, c, d, e) {
alert(a, b);
}
</script>
</code></pre> |
3,628,757 | Make An Integer Null | <p>I have an update function that updates an sql server db table through a dataset. One of the fields in the table is an integer and accepts null values. So when I am populating the update function I need a way to enter a null in when the function wants an integer.</p>
<p>I tried to do it this way but <code>_intDLocation = ""</code> throws an exception</p>
<pre><code>Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Integer
If _dLocation <> "" Then
_intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
Else
'NEED HELP HERE
_intDLocation = ""
End If
</code></pre> | 3,628,782 | 4 | 0 | null | 2010-09-02 15:45:38.103 UTC | null | 2017-05-11 17:35:40.133 UTC | 2010-09-02 15:49:54.423 UTC | null | 9,453 | null | 245,926 | null | 1 | 15 | vb.net|nullable | 45,279 | <p>Integers cannot be set to Null. You have to make the integer "nullable" by adding a question mark after the word Integer. Now _intDLocation is no longer a normal integer. It is an instance of <code>Nullable(Of Integer)</code>.</p>
<pre><code>Dim _dLocation As String = udDefaultLocationTextEdit.Text
Dim _intDLocation As Integer?
If _dLocation <> "" Then
_intDLocation = Integer.Parse(udDefaultLocationTextEdit.Text)
Else
_intDLocation = Nothing
End If
</code></pre>
<p>Later on, if you want to check for null you can use this handy, readable syntax:</p>
<pre><code>If _intDLocation.HasValue Then
DoSomething()
End If
</code></pre>
<p>In some cases you will need to access the value as an actual integer, not a nullable integer. For those cases, you simply access</p>
<pre><code>_intDLocation.Value
</code></pre>
<p>Read all about Nullable <a href="http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx" rel="noreferrer">here</a>.</p> |
4,000,886 | GPS coordinates: 1km square around a point | <p>I was hoping someone out there could provide me with an equation to calculate a 1km square (X from a.aaa to b.bbb, Y from c.ccc to c.ccc) around a given point, say <code>lat = 53.38292839</code> and <code>lon = -6.1843984</code>? I'll also need 2km, 5km and 10km squares around a point.</p>
<p>I've tried googling around to no avail... It's late at night and was hoping someone might have quick fix handy before I delve into the trigonometry...</p>
<p>I'll be running all this in Javascript, although any language is fine.</p> | 4,000,985 | 4 | 5 | null | 2010-10-22 20:53:27.303 UTC | 15 | 2019-08-02 07:19:20.457 UTC | 2019-01-15 03:08:30.58 UTC | null | 5,660,517 | null | 395,974 | null | 1 | 19 | javascript|math|gps|coordinates | 25,668 | <p>If the world were a perfect sphere, according to basic trigonometry...</p>
<p>Degrees of latitude have the same linear distance anywhere in the world, because all lines of latitude are the same size. So 1 degree of latitude is equal to 1/360th of the circumference of the Earth, which is 1/360th of 40,075 km.</p>
<p>The length of a lines of longitude depends on the latitude. The line of longitude at latitude l will be cos(l)*40,075 km. One degree of longitude will be 1/360th of that.</p>
<p>So you can work backwards from that. Assuming you want something very close to one square kilometre, you'll want 1 * (360/40075) = 0.008983 degrees of latitude.</p>
<p>At your example latitude of 53.38292839, the line of longitude will be cos(53.38292839)*40075 = [approx] 23903.297 km long. So 1 km is 1 * (360/23903.297) = 0.015060 degrees.</p>
<p>In reality the Earth isn't a perfect sphere, it's fatter at the equator. And the above gives a really good answer for most of the useful area of the world, but is prone to go a little odd near the poles (where rectangles in long/lat stop looking anything like rectangles on the globe). If you were on the equator, for example, the hypothetical line of longitude is 0 km long. So how you'd deal with a need to count degrees on that will depend on why you want the numbers.</p> |
3,946,086 | Python equivalent to Java's BitSet | <p>Is there a Python class or module that implements a structure that is similar to the BitSet? </p> | 3,946,103 | 4 | 2 | null | 2010-10-15 20:59:46.223 UTC | 6 | 2020-03-20 13:40:43.267 UTC | null | null | null | null | 277,256 | null | 1 | 34 | java|python|bitset | 25,034 | <p>There's nothing in the standard library. Try:</p>
<p><a href="http://pypi.python.org/pypi/bitarray" rel="noreferrer">http://pypi.python.org/pypi/bitarray</a></p> |
4,034,962 | Which language has the best Git API Bindings? | <p>I am looking at building an application with heavy ties to git..</p>
<p>Are there language bindings available and if so which are the most comprehensive?</p>
<p>Would it mean going to Bare Metal C?</p>
<p>Or does perl / python / php / C# have a set of full bindings?</p>
<p>Thanks</p>
<p>Daniel</p> | 4,036,822 | 4 | 7 | null | 2010-10-27 15:34:36.657 UTC | 22 | 2013-08-13 20:44:43.47 UTC | 2011-08-31 17:13:43.38 UTC | null | 74,296 | null | 415,286 | null | 1 | 42 | c#|c|git|binding | 14,100 | <p>There are three different approaches with respect to using Git from within some programming language:</p>
<ul>
<li><p><strong>Reimplementation</strong> of Git in different language. That is what the following projects do:</p>
<ul>
<li><strong><a href="http://www.eclipse.org/jgit/" rel="noreferrer">JGit</a></strong> which is reimplementation of Git in Java (used among others by <a href="http://www.eclipse.org/egit/" rel="noreferrer">EGit</a>, the <a href="http://www.eclipse.org" rel="noreferrer">Eclipse</a> Git plugin, and <a href="http://code.google.com/p/gerrit" rel="noreferrer">Gerrit Code Review</a>),</li>
<li><strong><a href="http://grit.rubyforge.org/" rel="noreferrer">Grit</a></strong> is Ruby library for extracting information from a git repository in an object oriented manner, which includes a <em>partial</em> native Ruby implementation. Used e.g. by GitHub.</li>
<li><a href="http://www.eqqon.com/index.php/GitSharp" rel="noreferrer">GitSharp</a> which is remplemantation of Git in C# for .NET and Mono, and which is following JGit wrt. functionality, </li>
<li><a href="http://samba.org/~jelmer/dulwich/" rel="noreferrer">Dulwich</a> which is pure-Python read-write implementation of the Git file formats and protocols.</li>
<li><a href="http://p3rl.org/Git::PurePerl" rel="noreferrer">Git::PurePerl</a> is pure Perl interface to Git repositories (it was mostly based on Grit, initially).</li>
<li><a href="http://fimml.at/glip" rel="noreferrer">Glip</a> is "git library in PHP" - pure PHP implementation. Used by its author for eWiki.</li>
<li><a href="https://github.com/mono/ngit" rel="noreferrer">NGit</a> .NET port of JGit used by Monodevelop</li>
</ul>
<p><br>The problem with reimplementations is that they do not always implement the full functionality, and sometimes implement it wrong. On the other hand they are native, implement good performance; they may be licensed differently than C (original) implementation of Git, which is GPLv2.</p></li>
<li><p><strong>Wrappers</strong> which call Git commands and wrap result it in some kind, suitably for target language.</p>
<ul>
<li>The <a href="http://repo.or.cz/w/git.git/tree/HEAD:/perl" rel="noreferrer">Git.pm</a> module distributed with git (and used by some of its commands), <a href="http://p3rl.org/Git::Wrapper" rel="noreferrer">Git::Wrapper</a> and <a href="http://p3rl.org/Git::Repository" rel="noreferrer">Git::Repository</a> wrap git commands for Perl.</li>
<li><a href="http://javagit.sourceforge.net/" rel="noreferrer">JavaGit</a> is a Java API that provides access to git repositories via calling git commands.</li>
<li><a href="http://gitorious.org/git-python" rel="noreferrer">GitPython</a> is a Python library used to interact with Git repositories, by calling the Git executables and parsing output.</li>
<li><a href="http://github.com/vincenthz/hs-libgit/" rel="noreferrer">hs-libgit</a> is Haskell wrapper for git.</li>
</ul>
<p><br>The problem with wrappers is that they can be slow (they require forking a git process), and that they require git to be installed to work.</p>
<p>Note also that git itself is highly scriptable (e.g. using shell scripts), thanks to the fact that beside higher level commands meant for end user (<em>porcelain</em>) it also provides low level commands meant for scripting (<em>plumbing</em>).<br></p></li>
<li><p>Finally there are <strong>bindings to libgit2</strong>, which means to be re-entrant linkable library with a solid API (was Google Summer of Code 2010 project).</p>
<ul>
<li><a href="http://libgit2.github.com/" rel="noreferrer">libgit2</a> itself is a portable, pure C implementation.</li>
<li><a href="http://github.com/libgit2/rugged" rel="noreferrer">Rugged</a> - Ruby bindings.</li>
<li><a href="http://github.com/libgit2/php-git" rel="noreferrer">php-git</a> - PHP bindings.</li>
<li><a href="http://github.com/libgit2/luagit2" rel="noreferrer">luagit2</a> - Lua bindings.</li>
<li><a href="http://github.com/libgit2/GitForDelphi" rel="noreferrer">GitForDelphi</a> - Delphi bindings.</li>
<li><a href="http://github.com/libgit2/libgit2sharp" rel="noreferrer">libgit2sharp</a> - .NET bindings.</li>
<li><a href="http://github.com/libgit2/pygit2" rel="noreferrer">pygit2</a> - Python bindings.</li>
<li><a href="http://github.com/schacon/geef" rel="noreferrer">Geef</a> is a simple Erlang NIF that exposes some of the libgit2 library functions to Erlang.
Monodevelop uses a .NET port for JGit </li>
</ul>
<p><br>Libgit2 is quite new project; it is work in progress, so not everything is implemented at the time of being. See <a href="http://libgit2.github.com/" rel="noreferrer">libgit2 homepage</a> for details.<br></p></li>
</ul>
<p><em>All this information can be found at <a href="https://git.wiki.kernel.org/index.php/InterfacesFrontendsAndTools" rel="noreferrer">InterfacesFrontendsAndTools</a> page on Git Wiki</em></p> |
3,428,216 | Adding system header search path to Xcode | <p>(Posting this question for reference purpose, I'll answer immediately)</p>
<p>How to add header search paths to Xcode?
Especially when including with this syntax:</p>
<pre><code>include <myheader.h>
</code></pre>
<ol>
<li>Adding path globally to all projects like system headers.</li>
<li>Adding path to only to a specific project.</li>
</ol> | 3,428,303 | 4 | 0 | null | 2010-08-06 22:22:06.957 UTC | 25 | 2020-08-24 02:59:21.09 UTC | 2014-05-26 21:56:21.867 UTC | null | 246,776 | null | 246,776 | null | 1 | 59 | xcode|search|path|header|system | 118,633 | <p>We have two options.</p>
<ol>
<li><p>Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.</p>
<ul>
<li><a href="https://help.apple.com/xcode/mac/11.4/#/deva52afe8a4" rel="nofollow noreferrer">https://help.apple.com/xcode/mac/11.4/#/deva52afe8a4</a></li>
</ul>
</li>
<li><p>Set <code>HEADER_SEARCH_PATHS</code> parameter in build settings on project info. I added <code>"${SRCROOT}"</code> here without recursion. This setting works well for most projects.</p>
</li>
</ol>
<p>About 2nd option:</p>
<p>Xcode uses Clang which has GCC compatible command set.
<a href="http://gcc.gnu.org/onlinedocs/cpp/Search-Path.html" rel="nofollow noreferrer">GCC has an option <code>-Idir</code></a> which adds system header searching paths. And this option is accessible via <code>HEADER_SEARCH_PATHS</code> in Xcode project build setting.</p>
<p>However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.</p>
<p>But, some OS X users (like me) may put their projects on path including whitespace which <strong>should be escaped</strong>. You can escape it like <code>/Users/my/work/a\ project\ with\ space</code> if you input it manually. You also can escape them with quotes to use environment variable like <code>"${SRCROOT}"</code>.</p>
<p>Or just use <code>.</code> to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.</p>
<p>The <code>${SRCROOT}</code> is predefined value by Xcode. This means source directory. You can find more values in <a href="http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html" rel="nofollow noreferrer">Reference document</a>.</p>
<p>PS. Actually you don't have to use braces <code>{}</code>. I get same result with <code>$SRCROOT</code>. If you know the difference, please let me know.</p> |
3,688,235 | How can I set a hot key ("win+Key") combination to call an application? | <p>I need to set a hot key at the operating system level, that once set will call whatever I tell it to call.
The hot key set must be done from inside my preference option, but the application must not have to be open so that the hot key works.</p> | 3,730,487 | 6 | 2 | null | 2010-09-10 20:49:11.413 UTC | 9 | 2011-09-15 06:26:47.033 UTC | 2010-09-15 10:13:29.767 UTC | null | 48,705 | null | 48,705 | null | 1 | 7 | delphi|keyboard-shortcuts | 5,022 | <p>This does what you want.</p>
<p>First, you need a program that runs in the background and listens to, and responds to, keystrokes. Like this:</p>
<pre><code>program Project1;
uses
Windows, Messages, ShellAPI;
var
W: HWND;
M: MSG;
const
WM_SETHOTKEY = WM_APP + 1;
WM_UNSETHOTKEY = WM_APP + 2;
AppName = 'Rejbrand Hot Key Listener';
const
FileNames: array[0..1] of string = ('notepad.exe', 'pbrush.exe');
begin
if FindWindow('STATIC', PChar(AppName)) <> 0 then
Exit;
W := CreateWindow('STATIC', PChar(AppName), 0, 0, 0, 100, 100, HWND_MESSAGE, 0, HInstance, nil);
while GetMessage(M, W, 0, 0) do
case M.message of
WM_HOTKEY:
ShellExecute(0, nil, PChar(FileNames[M.wParam]), nil, nil, SW_SHOWNORMAL);
WM_SETHOTKEY:
RegisterHotKey(W, M.wParam, M.lParam shr 16, M.lParam and $FFFF);
WM_UNSETHOTKEY:
UnregisterHotKey(W, M.wParam);
end;
end.
</code></pre>
<p>(To create this program, select New/VCL Forms Application, and then remove the main form from the project. Then select Project/View Source and remove the <code>Application.Initialize</code> nonsense. The program should look like the above.)</p>
<p>The above program listens to the messages <code>WM_SETHOTKEY</code> that registers a new Windows hotkey, <code>WM_UNSETHOTKEY</code> that removes a previously registered hotkey, and <code>WM_HOTKEY</code> that is sent by Windows when a registered hotkey is activated by the end-user. The first two messages are defined by me, in this application.</p>
<p>To register a hotkey, send the message <code>WM_SETHOTKEY</code> to the window <code>W</code>. The <code>wParam</code> of the message should be the index (in the <code>FileNames</code> array) of the program to start. The <code>lParam</code> should be of the form $MMMMKKKK where $MMMM are the modifiers (<kbd>Ctrl</kbd>, <kbd>Alt</kbd>, <kbd>Shift</kbd>) and $KKKK the virtual-key code of the hotkey. To remove a hotkey, send a <code>WM_UNSETHOTKEY</code> message with the program index as <code>wParam</code> to <code>W</code>.</p>
<h1>Sample usage</h1>
<p>From <em>any</em> application, you can do (assuming that Project1.exe is running in the background)</p>
<pre><code>const
WM_SETHOTKEY = WM_APP + 1;
WM_UNSETHOTKEY = WM_APP + 2;
const
MODIFIER_ALT = MOD_ALT shl 16;
MODIFIER_CTRL = MOD_CONTROL shl 16;
MODIFIER_SHIFT = MOD_SHIFT shl 16;
procedure TForm1.RegisterHotkeys;
var
w: HWND;
begin
w := FindWindow('STATIC', 'Rejbrand Hot Key Listener');
PostMessage(w, WM_UNSETHOTKEY, 0, MODIFIER_CTRL + MODIFIER_ALT + ord('N'));
PostMessage(w, WM_SETHOTKEY, 1, MODIFIER_CTRL + MODIFIER_ALT + ord('P'));
end;
</code></pre>
<p>Now, even if you close this new program, notepad.exe and pbrush.exe will start on <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>N</kbd> and <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>P</kbd>, respectively.</p>
<h1>Some more discussion</h1>
<p>Notice that, when compiled, Project1.exe is only 20 kB small! This is <em>tiny</em> for an application made in Delphi!</p>
<p>To unregister a previously registered hotkey, do</p>
<pre><code>PostMessage(w, WM_UNSETHOTKEY, N, 0);
</code></pre>
<p>where N, in this example, is = 0 for notepad and = 1 for pbrush.</p>
<p>To quit project1.exe, do</p>
<pre><code>PostMessage(w, WM_QUIT, 0, 0);
</code></pre>
<p>But, of course, if you quit project1.exe, all hotkeys are unregistered by Windows.</p>
<p>You might want to do</p>
<pre><code>procedure TForm1.RegisterHotkeys;
var
w: HWND;
begin
w := FindWindow('STATIC', 'Rejbrand Hot Key Listener');
if w = 0 then
MessageBox('Error: Rejbrand Hot Key Listener not running!');
PostMessage(w, WM_UNSETHOTKEY, 0, MODIFIER_CTRL + MODIFIER_ALT + ord('N'));
PostMessage(w, WM_SETHOTKEY, 1, MODIFIER_CTRL + MODIFIER_ALT + ord('P'));
end;
</code></pre>
<p>or even start project1.exe if you cannot find the window.</p> |
3,531,505 | Setting submit value in jQuery submit | <p>I want to use jQuery to submit my form and i can do that like so </p>
<pre><code> $('#myform_id').submit();
</code></pre>
<p>and thats all good but normally someone clicks a submit button than that submit button has a value so when I do the submit via jQuery I also need to set a submit value how do i do that ?</p>
<p><strong>EDIT</strong></p>
<p>as noted by some answers I could do this by simulating a user click but I don't want to do that I want to pass the submit value when I use the .submit() command if that is possible</p>
<p>ultimately the submit using ajax form </p>
<p>** Clarifying **</p>
<p>ok so I have jQuery setup to use jquery validate and has a submit handler like so</p>
<pre><code>$("#myform_id").validate({
submitHandler: function() {
run_ajax(obj);
}
});
</code></pre>
<p>then that calls I function i call run_ajax passing and object containing information about what type of ajax i want and what have you.</p>
<p>and ultimately runs this</p>
<pre><code>obj.formitem.ajaxSubmit({
dataType:'json',
data: obj.pdata,
});
</code></pre>
<p>where</p>
<pre><code> obj.formitem == $('#myform_id');
</code></pre>
<p>so when the form is submit all that happens all good.</p>
<p>so I load the page with this form into jquery dialog and I want them to be able to click a button in the dialog that triggers the form submit and also tells the form what type of submit was requested</p>
<p>hopefully this is clear now sorry for confusion</p> | 3,531,528 | 7 | 1 | null | 2010-08-20 13:53:46.197 UTC | 4 | 2012-04-21 21:49:48.533 UTC | 2010-10-18 20:37:43.083 UTC | null | 139,010 | null | 234,670 | null | 1 | 17 | jquery|forms | 42,185 | <p>One quick way would be <code>$('#myform_id #submitButtonID').click();</code></p> |
3,723,220 | How do you convert a PIL `Image` to a Django `File`? | <p>I'm trying to convert an <code>UploadedFile</code> to a PIL <code>Image</code> object to thumbnail it, and then convert the PIL <code>Image</code> object that my thumbnail function returns back into a <code>File</code> object. How can I do this?</p> | 4,544,525 | 7 | 2 | null | 2010-09-16 02:07:39.883 UTC | 29 | 2019-06-26 21:43:47.04 UTC | 2016-03-05 03:43:44.097 UTC | null | 128,463 | null | 128,463 | null | 1 | 56 | python|django|python-imaging-library|django-file-upload|django-uploads | 34,628 | <p>The way to do this without having to write back to the filesystem, and then bring the file back into memory via an open call, is to make use of StringIO and Django InMemoryUploadedFile. Here is a quick sample on how you might do this. This assumes that you already have a thumbnailed image named 'thumb':</p>
<pre><code>import StringIO
from django.core.files.uploadedfile import InMemoryUploadedFile
# Create a file-like object to write thumb data (thumb data previously created
# using PIL, and stored in variable 'thumb')
thumb_io = StringIO.StringIO()
thumb.save(thumb_io, format='JPEG')
# Create a new Django file-like object to be used in models as ImageField using
# InMemoryUploadedFile. If you look at the source in Django, a
# SimpleUploadedFile is essentially instantiated similarly to what is shown here
thumb_file = InMemoryUploadedFile(thumb_io, None, 'foo.jpg', 'image/jpeg',
thumb_io.len, None)
# Once you have a Django file-like object, you may assign it to your ImageField
# and save.
...
</code></pre>
<p>Let me know if you need more clarification. I have this working in my project right now, uploading to S3 using django-storages. This took me the better part of a day to properly find the solution here.</p> |
3,342,941 | Kill child process when parent process is killed | <p>I'm creating new processes using <code>System.Diagnostics.Process</code> class from my application.<br><br> I want this processes to be killed when/if my application has crashed. But if I kill my application from Task Manager, child processes are not killed.<br><br> Is there any way to make child processes dependent on parent process?</p> | 4,657,392 | 16 | 0 | null | 2010-07-27 11:06:38.48 UTC | 86 | 2021-06-18 01:31:16.553 UTC | 2020-01-18 20:50:03.427 UTC | null | 384,670 | null | 188,826 | null | 1 | 173 | c#|.net|process | 103,255 | <p>From <a href="http://www.xtremevbtalk.com/showpost.php?p=1335552&postcount=22" rel="noreferrer">this forum</a>, credit to 'Josh'.</p>
<p><code>Application.Quit()</code> and <code>Process.Kill()</code> are possible solutions, but have proven to be unreliable. When your main application dies, you are still left with child processes running. What we really want is for the child processes to die as soon as the main process dies.</p>
<p>The solution is to use "job objects" <a href="http://msdn.microsoft.com/en-us/library/ms682409(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms682409(VS.85).aspx</a>.</p>
<p>The idea is to create a "job object" for your main application, and register your child processes with the job object. If the main process dies, the OS will take care of terminating the child processes.</p>
<pre><code>public enum JobObjectInfoType
{
AssociateCompletionPortInformation = 7,
BasicLimitInformation = 2,
BasicUIRestrictions = 4,
EndOfJobTimeInformation = 6,
ExtendedLimitInformation = 9,
SecurityLimitInformation = 5,
GroupInformation = 11
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
public Int64 PerProcessUserTimeLimit;
public Int64 PerJobUserTimeLimit;
public Int16 LimitFlags;
public UInt32 MinimumWorkingSetSize;
public UInt32 MaximumWorkingSetSize;
public Int16 ActiveProcessLimit;
public Int64 Affinity;
public Int16 PriorityClass;
public Int16 SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
struct IO_COUNTERS
{
public UInt64 ReadOperationCount;
public UInt64 WriteOperationCount;
public UInt64 OtherOperationCount;
public UInt64 ReadTransferCount;
public UInt64 WriteTransferCount;
public UInt64 OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
public IO_COUNTERS IoInfo;
public UInt32 ProcessMemoryLimit;
public UInt32 JobMemoryLimit;
public UInt32 PeakProcessMemoryUsed;
public UInt32 PeakJobMemoryUsed;
}
public class Job : IDisposable
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr CreateJobObject(object a, string lpName);
[DllImport("kernel32.dll")]
static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
private IntPtr m_handle;
private bool m_disposed = false;
public Job()
{
m_handle = CreateJobObject(null, null);
JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();
info.LimitFlags = 0x2000;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
extendedInfo.BasicLimitInformation = info;
int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);
if (!SetInformationJobObject(m_handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length))
throw new Exception(string.Format("Unable to set information. Error: {0}", Marshal.GetLastWin32Error()));
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private void Dispose(bool disposing)
{
if (m_disposed)
return;
if (disposing) {}
Close();
m_disposed = true;
}
public void Close()
{
Win32.CloseHandle(m_handle);
m_handle = IntPtr.Zero;
}
public bool AddProcess(IntPtr handle)
{
return AssignProcessToJobObject(m_handle, handle);
}
}
</code></pre>
<p>Looking at the constructor ...</p>
<pre><code>JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();
info.LimitFlags = 0x2000;
</code></pre>
<p>The key here is to setup the job object properly. In the constructor I'm setting the "limits" to 0x2000, which is the numeric value for <code>JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE</code>.</p>
<p>MSDN defines this flag as:</p>
<blockquote>
<p>Causes all processes associated with
the job to terminate when the last
handle to the job is closed.</p>
</blockquote>
<p>Once this class is setup...you just have to register each child process with the job. For example:</p>
<pre><code>[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
Excel.Application app = new Excel.ApplicationClass();
uint pid = 0;
Win32.GetWindowThreadProcessId(new IntPtr(app.Hwnd), out pid);
job.AddProcess(Process.GetProcessById((int)pid).Handle);
</code></pre> |
3,905,946 | How can I add double quotes to a string that is inside a variable? | <p>I have a string variable such as this:</p>
<pre><code>string title = string.empty;
</code></pre>
<p>I have to display the content of whatever is passed to it inside a <em>div</em> within double quotes. I have written something like this:</p>
<pre><code>...
...
<div>"+ title +@"</div>
...
...
</code></pre>
<p>How can I add the double quotes here? So that it will display like:</p>
<pre><code>"How to add double quotes"
</code></pre> | 3,905,970 | 20 | 2 | null | 2010-10-11 11:57:46.423 UTC | 34 | 2022-07-03 10:58:42.053 UTC | 2022-06-16 15:55:05.77 UTC | null | 17,142,802 | null | 386,263 | null | 1 | 207 | c#|asp.net|double-quotes | 669,684 | <p>You need to escape them by doubling them (verbatim string literal):</p>
<pre><code>string str = @"""How to add doublequotes""";
</code></pre>
<p>Or with a normal string literal you escape them with a <code>\</code>:</p>
<pre><code>string str = "\"How to add doublequotes\"";
</code></pre> |
7,766,057 | Why do you need a while loop while waiting for a condition variable | <p>Say you have this code</p>
<pre><code>pthread_mutex_lock(&cam->video_lock);
while(cam->status == WAIT_DISPLAY) // <-- Why is this a 'while' and not an 'if'?
pthread_cond_wait(&cam->video_cond, &cam->video_lock);
pthread_mutex_unlock(&cam->video_lock);
</code></pre>
<p>My question is, why do you need a while loop here. Wouldn't <strong>pthread_cond_wait</strong> just wait until the signalling thread signals <strong>cam_video_cond</strong>? OK, I know you might have a case where <strong>cam->status</strong> is not equal to <strong>WAIT_DISPAY</strong> when <strong>pthread_cond_wait</strong> is called, but in that case you could just check it through an <strong>if</strong> condition rather than using <strong>while</strong>. </p>
<p>Am I missing something here? My understanding of <strong>pthread_cond_wait</strong> is that it just waits for infinite if <strong>cam_video_cond</strong> is not signalled. Moreover, it unlocks the <strong>cam_video_lock</strong> mutex when called, but when the condition is signalled, before returning, it relocks <strong>cam_video_lock</strong>. Am I right?</p> | 7,766,310 | 4 | 2 | null | 2011-10-14 10:03:01.247 UTC | 15 | 2021-08-13 21:46:58.61 UTC | 2011-10-14 10:17:08.453 UTC | null | 760,807 | null | 760,807 | null | 1 | 21 | c|linux|pthreads|signals | 13,430 | <blockquote>
<p>It is recommended that all threads check the condition after returning
from <strong>pthread_cond_wait</strong> because there are several reasons the condition
might not be true. One of these reasons is a spurious wakeup; that is,
a thread might get woken up even though no thread signalled the
condition.</p>
</blockquote>
<p>Source : <a href="http://en.wikipedia.org/wiki/Spurious_wakeup" rel="noreferrer">Spurious wakeup</a></p> |
8,132,742 | How to delete file of certain extension? | <p>I have an application that should unzip and install some other application, i get new Zip file with installation image via network and then should unzip it and install. All file except the part that Zip file comes with different name each time because of version change and all my C:\ has a lot of .zip files with different versions. Msi file is not overwritten by Zip i'm using but i'm more than fine with just deleting it prior to unzipping.</p>
<p>I want to delete all .msi and .zip files on C:.
How can i do that via C#?</p>
<p>thanks...</p> | 8,132,800 | 7 | 0 | null | 2011-11-15 07:15:23.263 UTC | 6 | 2020-11-10 11:48:50.703 UTC | null | null | null | null | 185,824 | null | 1 | 30 | c#|.net | 43,560 | <p>You could try something like this:</p>
<pre><code>DirectoryInfo di = new DirectoryInfo(@"C:\");
FileInfo[] files = di.GetFiles("*.msi")
.Where(p => p.Extension == ".msi").ToArray();
foreach (FileInfo file in files)
try
{
file.Attributes = FileAttributes.Normal;
File.Delete(file.FullName);
}
catch { }
</code></pre>
<p>Note that I first try to set attributes to "normal", because <code>File.Delete()</code> fails if file is read-only...<br>
Note the use of <code>GetFiles()</code>: see <a href="http://msdn.microsoft.com/it-it/library/8he88b63.aspx" rel="noreferrer">this link</a> for details.</p>
<p><strong>EDITED:</strong><br>
If you need to get more than one extension you could use this:</p>
<pre><code>public List<FileInfo> GetFiles(string path, params string[] extensions)
{
List<FileInfo> list = new List<FileInfo>();
foreach (string ext in extensions)
list.AddRange(new DirectoryInfo(path).GetFiles("*" + ext).Where(p =>
p.Extension.Equals(ext,StringComparison.CurrentCultureIgnoreCase))
.ToArray());
return list;
}
</code></pre>
<p>so you can change part of my answer to</p>
<pre><code>List<FileInfo> files = GetFiles(@"C:\", ".msi", ".zip");
</code></pre> |
8,151,342 | Do we have a Readonly field in java (which is set-able within the scope of the class itself)? | <p>How can we have a variable that is <em>writable</em> within the class but only "readable" outside it?</p>
<p>For example, instead of having to do this:</p>
<pre><code>Class C {
private int width, height;
int GetWidth(){
return width;
}
int GetHeight(){
return height;
}
// etc..
</code></pre>
<p>I would like to do something like this:</p>
<pre><code>Class C {
public_readonly int width, height;
// etc...
</code></pre>
<p>What's the best solution?</p> | 8,151,396 | 7 | 0 | null | 2011-11-16 12:02:01.07 UTC | 9 | 2018-07-07 05:33:50.27 UTC | 2013-08-16 18:16:09.703 UTC | null | 632,951 | null | 632,951 | null | 1 | 45 | java|readonly | 72,808 | <p>There's no way to do this in Java.</p>
<p>Your two options (one which you mentioned) are using public getters and making the field private, or thorough documentation in the class.</p>
<p>The overhead on getter methods in extremely small (if at all). If you're doing it a large number of times, you might want to cache the fetched value instead of calling the get method.</p>
<p>EDIT:</p>
<p>One way to do it, although it has even more overhead than the getter, is defining a public inner class (let's call it <code>innerC</code>) with a constructor that is only available to your <code>C</code> class, and make your fields public. That way, you can't create <code>innerC</code> instances outside your class so changing your fields from outside is impossible, yet you can change them from inside. You could however read them from the outside.</p> |
8,222,528 | iOS5 show numeric keypad by default without using type="number" or type="tel" | <p>With the release of iOS5, Apple has added their own validation to input type="number" form fields. This is causing some issues; see this question below which sums it up:</p>
<p><a href="https://stackoverflow.com/questions/7833257/input-type-number-new-validation-removes-leading-zeros-and-formats-number-in-s">Input type='number' new validation removes leading zeros and formats number in Safari for iPhone iOS5 and latest Safari for Mac</a></p>
<p>Although input type="tel" works to bring up a numeric keypad on the iphone, it's the <strong>telephone keypad</strong> which has no decimal points.</p>
<p>Is there a way to set the numeric keypad as default using html/js? This not an iphone app. At minimum I need numbers and a decimal point in the keypad.</p>
<p><strong>Update</strong></p>
<p>Number input fields in Safari 5.1/iOS 5 only accept digits and decimal points. The default value for one of my inputs is <strong>$500,000</strong>. This is resulting in Safari showing a blank input field because $ , % are invalid characters.</p>
<p>Furthermore, when I run my own validation <code>onblur</code>, Safari clears the input field because I'm adding a $ to the value.</p>
<p>Thus Safari 5.1/iOS5's implementation of input type="number" has rendered it unusable.</p>
<p><strong>jsfiddle</strong></p>
<p>Try it here - <a href="http://jsfiddle.net/mjcookson/4ePeE/" rel="nofollow noreferrer">http://jsfiddle.net/mjcookson/4ePeE/</a> The default value of $500,000 won't appear in Safari 5.1, but if you remove the $ and , symbols, it will. Frustrating.</p> | 15,490,064 | 11 | 10 | null | 2011-11-22 05:46:33.433 UTC | 11 | 2015-12-10 05:11:31.06 UTC | 2017-05-23 11:54:04.337 UTC | null | -1 | null | 872,018 | null | 1 | 36 | javascript|iphone|html|ios5|input | 18,963 | <h2>Working solution: Tested on iPhone 5, Android 2.3, 4</h2>
<p>Tadeck's solution (bounty winner) of using a <code><span></code> to contain the input field symbols and place a formatted <code><span></code> on top of the currency input is essentially what I ended up doing.</p>
<p>My final code is different and shorter however so I'm posting it here. This solution resolves the iOS5 validation issue of $ , % symbols inside input fields and so <code>input type="number"</code> can be used by default.</p>
<h2>Symbol field eg. "xx %" "xx years"</h2>
<pre><code><input name="interest-rate" value="6.4" maxlength="4" min="1" max="20" />
<span class="symbol">%</span>
</code></pre>
<ul>
<li>Simply use a number input field and a span outside the input to display the symbol.</li>
</ul>
<h2>Currency field eg. "$xxx,xxx"</h2>
<pre><code><span id="formatted-currency">$500,000</span>
<input id="currency-field" type="number" name="loan-amount" value="500000" maxlength="8" min="15000" max="10000000" />
</code></pre>
<ul>
<li>Position the span on top of the currency input and set the input to
display:none</li>
<li>When a user clicks/taps on the span, hide the span and show the
input. If you position the span perfectly the transition is seamless.</li>
<li>The number input type takes care of the validation.</li>
<li>On blur and submit of the input, set the span html to be the input's
value. Format the span. Hide the input and show the span with the
formatted value.</li>
</ul>
<p></p>
<pre><code>$('#formatted-currency').click(function(){
$(this).hide();
$('#currency-field').show().focus();
});
$('#currency-field').blur(function(){
$('#formatted-currency').html(this.value);
$('#formatted-currency').formatCurrency({
roundToDecimalPlace : -2
});
$(this).hide();
$('#formatted-currency').show();
});
// on submit
$('#formatted-currency').html($('#currency-field').val());
$('#formatted-currency').formatCurrency({
roundToDecimalPlace : -2
});
$('#currency-field').hide();
$('#formatted-currency').show();
</code></pre> |
8,090,579 | How to display activity indicator in middle of the iphone screen? | <p>When we draw the image, we want to display the activity indicator.
Can anyone help us?</p> | 8,090,599 | 15 | 1 | null | 2011-11-11 06:50:32.743 UTC | 23 | 2019-08-10 07:05:18.01 UTC | 2014-07-14 07:03:56.14 UTC | null | 501,483 | null | 1,041,190 | null | 1 | 80 | iphone|ios|ipad | 137,352 | <pre><code>UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityView.center=self.view.center;
[activityView startAnimating];
[self.view addSubview:activityView];
</code></pre> |
4,076,968 | How to get missing values in sql? | <p>I need help.</p>
<p>I have a sql table t2 related to two other tables t1 and t3.</p>
<p>t2 has fields:</p>
<pre><code>idFromt3 idFromt1 Value
1 14 text1
2 14 text2
1 44 text1
2 44 text2
3 44 text3
</code></pre>
<p>I'm searching for values, where ifFromt3 is missing.
I want to fint in this example, the value ifFromt3 = 3, because of it's not present.</p>
<p>I'm doing it like this example, but it doesn't work correctly.</p>
<pre><code>SELECT t3.idFromt3, t3.idFromt1
FROM t3
INNER JOIN t2
ON t3.LanguageMessageCodeID <> t2.idFromt2
</code></pre>
<p>This are the 3 tables.</p>
<pre><code>CREATE TABLE [dbo].[t3](
[t3ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
)
CREATE TABLE [dbo].[t2](
[t2ID] [int] IDENTITY(1,1) NOT NULL,
[t3ID] [int] NOT NULL,
[t1ID] [int] NOT NULL,
)
CREATE TABLE [dbo].[t1](
[t1ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
)
</code></pre>
<p><strong>UPDATE:</strong> </p>
<p>Tables with data:
<a href="http://www.2shared.com/photo/40yY6FC-/Untitled.html" rel="nofollow">http://www.2shared.com/photo/40yY6FC-/Untitled.html</a></p>
<p>And I need a query, that returns all missing combinations in table LangugageMessageCodes.</p>
<p>In this case:</p>
<pre><code>LanguageMessageCodeID LanguageID
3 14
1 47
2 47
3 47
</code></pre>
<p>please. help.</p>
<p>regards.</p> | 4,076,991 | 3 | 1 | null | 2010-11-02 10:56:03.383 UTC | null | 2020-03-13 11:41:33.623 UTC | 2010-11-02 16:23:40.073 UTC | null | 492,873 | null | 492,873 | null | 1 | 5 | sql | 40,009 | <pre><code>SELECT *
FROM t2
WHERE t2.idFromt3 NOT IN
(
SELECT LanguageMessageCodeID
FROM t3
)
</code></pre>
<p>or </p>
<pre><code>SELECT *
FROM t2
WHERE NOT EXISTS
(
SELECT NULL
FROM t3
WHERE t3.LanguageMessageCodeID = t2.id
)
</code></pre>
<p>or</p>
<pre><code>SELECT t2.*
FROM t2
LEFT JOIN
t3
ON t3.LanguageMessageCodeID = t2.id
WHERE t3.LanguageMessageCodeID IS NULL
</code></pre>
<p><strong>Update:</strong></p>
<p>Try this:</p>
<pre><code>SET NOCOUNT ON
DECLARE @t1 TABLE (id INT NOT NULL PRIMARY KEY)
DECLARE @t2 TABLE (t3id INT NOT NULL, t1id INT NOT NULL, PRIMARY KEY (t1id, t3id))
DECLARE @t3 TABLE (id INT NOT NULL)
INSERT
INTO @t1
VALUES (14)
INSERT
INTO @t1
VALUES (44)
INSERT
INTO @t2
VALUES (1, 14)
INSERT
INTO @t2
VALUES (2, 14)
INSERT
INTO @t2
VALUES (1, 44)
INSERT
INTO @t2
VALUES (2, 44)
INSERT
INTO @t2
VALUES (3, 44)
INSERT
INTO @t3
VALUES (1)
INSERT
INTO @t3
VALUES (2)
INSERT
INTO @t3
VALUES (3)
SELECT t1.id, t3.id
FROM @t1 t1
CROSS JOIN
@t3 t3
WHERE NOT EXISTS
(
SELECT NULL
FROM @t2 t2
WHERE t2.t1id = t1.id
AND t2.t3id = t3.id
)
</code></pre> |
4,192,972 | Assessing the quality of an image with respect to compression? | <p>I have images that I am using for a computer vision task. The task is sensitive to image quality. I'd like to remove all images that are below a certain threshold, but I am unsure if there is any method/heuristic to automatically detect images that are heavily compressed via JPEG. Anyone have an idea?</p> | 4,194,109 | 3 | 1 | null | 2010-11-16 10:05:30.81 UTC | 15 | 2012-06-27 18:52:57.233 UTC | null | null | null | null | 290,379 | null | 1 | 12 | compression|computer-vision|jpeg | 5,973 | <p>Image Quality Assessment is a rapidly developing research field. As you don't mention being able to access the original (uncompressed) images, you are interested in <em>no reference</em> image quality assessment. This is actually a pretty hard problem, but here are some points to get you started:</p>
<ul>
<li>Since you mention JPEG, there are two major degradation features that manifest themselves in JPEG-compressed images: <strong>blocking</strong> and <strong>blurring</strong></li>
<li>No-reference image quality assessment metrics typically look for those two features</li>
<li>Blocking is fairly easy to pick up, as it appears only on macroblock boundaries. Macroblocks are a fixed size -- 8x8 or 16x16 depending on what the image was encoded with</li>
<li>Blurring is a bit more difficult. It occurs because higher frequencies in the image have been attenuated (removed). You can break up the image into blocks, DCT (Discrete Cosine Transform) each block and look at the high-frequency components of the DCT result. If the high-frequency components are lacking for a majority of blocks, then you are probably looking at a blurry image</li>
<li>Another approach to blur detection is to measure the average width of edges of the image. Perform Sobel edge detection on the image and then measure the distance between local minima/maxima on each side of the edge. Google for "A no-reference perceptual blur metric" by Marziliano -- it's a famous approach. "No Reference Block Based Blur Detection" by Debing is a more recent paper</li>
</ul>
<p>Regardless of what metric you use, think about how you will deal with false positives/negatives. As opposed to simple thresholding, I'd use the metric result to sort the images and then snip the end of the list that looks like it contains only blurry images.</p>
<p>Your task will be a lot simpler if your image set contains fairly similar content (e.g. faces only). This is because the image quality assessment metrics
can often be influenced by image content, unfortunately.</p>
<p>Google Scholar is truly your friend here. I wish I could give you a concrete solution, but I don't have one yet -- if I did, I'd be a very successful Masters student.</p>
<p><strong>UPDATE:</strong></p>
<p>Just thought of another idea: for each image, re-compress the image with JPEG and examine the change in file size before and after re-compression. If the file size after re-compression is significantly smaller than before, then it's likely the image is not heavily compressed, because it had some significant detail that was removed by re-compression. Otherwise (very little difference or file size after re-compression is greater) it is likely that the image was heavily compressed.</p>
<p>The use of the quality setting during re-compression will allow you to determine what exactly <em>heavily compressed</em> means.</p>
<p>If you're on Linux, this shouldn't be too hard to implement using bash and imageMagick's convert utility.</p>
<p>You can try other variations of this approach:</p>
<ul>
<li>Instead of JPEG compression, try another form of degradation, such as Gaussian blurring</li>
<li>Instead of merely comparing file-sizes, try a full reference metric such as <a href="http://en.wikipedia.org/wiki/Structural_similarity" rel="noreferrer">SSIM</a> -- there's an OpenCV implementation <a href="http://mehdi.rabah.free.fr/SSIM/" rel="noreferrer">freely available</a>. Other implementations (e.g. Matlab, C#) also exist, so look around.</li>
</ul>
<p>Let me know how you go.</p> |
4,466,859 | 'Delegate 'System.Action' does not take 0 arguments.' Is this a C# compiler bug (lambdas + two projects)? | <p>Consider the code below. Looks like perfectly valid C# code right?</p>
<pre><code>//Project B
using System;
public delegate void ActionSurrogate(Action addEvent);
//public delegate void ActionSurrogate2();
// Using ActionSurrogate2 instead of System.Action results in the same error
// Using a dummy parameter (Action<double, int>) results in the same error
// Project A
public static class Class1 {
public static void ThisWontCompile() {
ActionSurrogate b = (a) =>
{
a(); // Error given here
};
}
}
</code></pre>
<p>I get a compiler error 'Delegate 'Action' does not take 0 arguments.' at the indicated position using the (Microsoft) C# 4.0 compiler. Note that you have to declare ActionSurrogate in a different project for this error to manifest.</p>
<p>It gets more interesting:</p>
<pre><code>// Project A, File 1
public static class Class1 {
public static void ThisWontCompile() {
ActionSurrogate b = (a) => { a(); /* Error given here */ };
ActionSurrogate c = (a) => { a(); /* Error given here too */ };
Action d = () => { };
ActionSurrogate c = (a) => { a(); /* No error is given here */ };
}
}
</code></pre>
<p>Did I stumble upon a C# compiler bug here?</p>
<p>Note that this is a pretty annoying bug for someone who likes using lambdas a lot and is trying to create a data structures library for future use... (me)</p>
<p>EDIT: removed erronous case.</p>
<p>I copied and stripped my original project down to the minimum to make this happen. This is literally all the code in my new project.</p> | 4,466,888 | 3 | 5 | null | 2010-12-17 01:04:29.267 UTC | 8 | 2022-02-27 22:59:29.103 UTC | 2010-12-17 01:48:52.773 UTC | null | 492,448 | null | 492,448 | null | 1 | 44 | c#|compiler-errors|lambda|compiler-bug | 21,325 | <p>This probably is a problem with type inference, apperently the compiler infers <code>a</code> as an <code>Action<T></code> instead of <code>Action</code> (it might think <code>a</code> is <code>ActionSurrogate</code>, which would fit the <code>Action<Action>></code> signature). Try specifying the type of <code>a</code> explicitly:</p>
<pre><code> ActionSurrogate b = (Action a) =>
{
a();
};
</code></pre>
<p>If this is not the case - might check around your project for any self defined <code>Action</code> delegates taking one parameter.</p> |
4,834,899 | Removing scrollbar from <object> Embed | <p>Currently I am using object to embed a adsense ad in a webpage</p>
<pre><code><object data="frontpage_blogrool_center_top_728x90" type="text/html" width="732" height="95" ></object>
</code></pre>
<p>I made the object larger than the original so that the scrollbar will not appear on the webpage but it still appears in IE8. Is there anyway to remove it?</p> | 4,834,911 | 5 | 0 | null | 2011-01-29 03:08:58.607 UTC | 3 | 2020-08-08 15:08:42.317 UTC | null | null | null | null | 192,604 | null | 1 | 7 | html|css | 64,617 | <p>Add <code>style="overflow:hidden; width: 732px; height: 95px"</code> to the element:</p>
<pre><code><object data="frontpage_blogrool_center_top_728x90"
type="text/html" width="732" height="95"
style="overflow:hidden; width: 732px; height: 95px"></object>
</code></pre> |
4,049,856 | Replace PHP's realpath() | <p>Apparently, <code>realpath</code> is very buggy. In PHP 5.3.1, it causes random crashes.
In 5.3.0 and less, <code>realpath</code> randomly fails and returns false (for the same string of course), plus it always fails on <code>realpath</code>-ing the same string twice/more (and of course, it works the first time).</p>
<p>Also, it is so buggy in earlier PHP versions, that it is completely unusable. Well...it already is, since it's not consistent.</p>
<p>Anyhow, what options do I have? Maybe rewrite it by myself? Is this advisable?</p> | 4,050,444 | 6 | 4 | null | 2010-10-29 07:27:53.15 UTC | 10 | 2015-03-31 15:25:38.823 UTC | null | null | null | null | 314,056 | null | 1 | 10 | php|path|realpath | 26,283 | <p>Thanks to Sven Arduwie's code (<a href="https://stackoverflow.com/a/4049876/662581">pointed out by Pekka</a>) and some modification, I've built a (hopefully) better implementation:</p>
<pre><code>/**
* This function is to replace PHP's extremely buggy realpath().
* @param string The original path, can be relative etc.
* @return string The resolved path, it might not exist.
*/
function truepath($path){
// whether $path is unix or not
$unipath=strlen($path)==0 || $path{0}!='/';
// attempts to detect if path is relative in which case, add cwd
if(strpos($path,':')===false && $unipath)
$path=getcwd().DIRECTORY_SEPARATOR.$path;
// resolve path parts (single dot, double dot and double delimiters)
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
$absolutes = array();
foreach ($parts as $part) {
if ('.' == $part) continue;
if ('..' == $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
$path=implode(DIRECTORY_SEPARATOR, $absolutes);
// resolve any symlinks
if(file_exists($path) && linkinfo($path)>0)$path=readlink($path);
// put initial separator that could have been lost
$path=!$unipath ? '/'.$path : $path;
return $path;
}
</code></pre>
<p><strong>NB:</strong> Unlike PHP's <code>realpath</code>, this function does not return false on error; it returns a path which is as far as it could to resolving these quirks.</p>
<p><strong>Note 2:</strong> Apparently some people can't read properly. Truepath() does not work on network resources including UNC and URLs. <strong>It works for the local file system only.</strong></p> |
4,260,207 | How do you get the width and height of a multi-dimensional array? | <p>I have an array defined:</p>
<pre><code>int [,] ary;
// ...
int nArea = ary.Length; // x*y or total area
</code></pre>
<p>This is all well and good, but I need to know how wide this array is in the <code>x</code> and <code>y</code> dimensions individually. Namely, <code>ary.Length</code> might return 12 - but does that mean the array is 4 high and 3 wide, or 6 high and 2 wide?</p>
<p>How can I retrieve this information?</p> | 4,260,228 | 6 | 2 | null | 2010-11-23 19:50:46.267 UTC | 24 | 2020-04-15 19:55:39.49 UTC | 2017-08-17 16:59:28.01 UTC | null | 120,888 | null | 120,888 | null | 1 | 250 | c#|.net|arrays|multidimensional-array | 216,922 | <p>You use <a href="http://msdn.microsoft.com/en-us/library/system.array.getlength.aspx">Array.GetLength</a> with the index of the dimension you wish to retrieve.</p> |
4,796,764 | Read file from line 2 or skip header row | <p>How can I skip the header row and start reading a file from line2?</p> | 4,796,785 | 8 | 0 | null | 2011-01-25 17:25:08.93 UTC | 56 | 2019-11-15 17:57:46.007 UTC | 2011-01-25 17:28:33.16 UTC | null | 12,855 | null | 131,238 | null | 1 | 295 | python|file-io | 413,919 | <pre><code>with open(fname) as f:
next(f)
for line in f:
#do something
</code></pre> |
4,575,689 | Calculating the number of days between two dates in Objective-C | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2548008/how-can-i-compare-two-dates-return-a-number-of-days">How can I compare two dates, return a number of days</a> </p>
</blockquote>
<p>I have two dates (as NSString in the form "yyyy-mm-dd"), for example:</p>
<pre><code>NSString *start = "2010-11-01";
NSString *end = "2010-12-01";
</code></pre>
<p>I'd like to implement:</p>
<pre><code>- (int)numberOfDaysBetween:(NSString *)startDate and:(NSString *)endDate {
}
</code></pre> | 4,576,575 | 8 | 6 | null | 2011-01-01 20:42:45.41 UTC | 19 | 2022-08-26 02:30:19.04 UTC | 2020-03-12 18:23:59.777 UTC | null | 1,033,581 | null | 412,082 | null | 1 | 59 | objective-c|ios|nsstring|nsdate | 68,496 | <pre><code>NSString *start = @"2010-09-01";
NSString *end = @"2010-12-01";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:startDate
toDate:endDate
options:0];
</code></pre>
<p><code>components</code> now holds the difference.</p>
<pre><code>NSLog(@"%ld", [components day]);
</code></pre> |
14,783,330 | Dynamic Libraries, plugin frameworks, and function pointer casting in c++ | <p>I am trying to create a very open plugin framework in c++, and it seems to me that I have come up with a way to do so, but a nagging thought keeps telling me that there is something very, very wrong with what I am doing, and it either won't work or it will cause problems.</p>
<p>The design I have for my framework consists of a Kernel that calls each plugin's <code>init</code> function. The init function then turns around and uses the Kernel's <code>registerPlugin</code> and <code>registerFunction</code> to get a unique id and then register each function the plugin wants to be accessible using that id, respectively.</p>
<p>The function registerPlugin returns the unique id. The function registerFunction takes that id, the function name, and a generic function pointer, like so:</p>
<pre><code>bool registerFunction(int plugin_id, string function_name, plugin_function func){}
</code></pre>
<p>where plugin_function is</p>
<pre><code>typedef void (*plugin_function)();
</code></pre>
<p>The kernel then takes the function pointer and puts it in a map with the <code>function_name</code> and <code>plugin_id</code>. All plugins registering their function must caste the function to type <code>plugin_function</code>.</p>
<p>In order to retrieve the function, a different plugin calls the Kernel's</p>
<pre><code>plugin_function getFunction(string plugin_name, string function_name);
</code></pre>
<p>Then that plugin must cast the <code>plugin_function</code> to its original type so it can be used. It knows (in theory) what the correct type is by having access to a <code>.h</code> file outlining all the functions the plugin makes available. Plugins, by the by, are implemented as dynamic libraries.</p>
<p>Is this a smart way to accomplish the task of allowing different plugins to connect with each other? Or is this a crazy and really terrible programming technique? If it s, please point me in the direction of the correct way to accomplish this.</p>
<p>EDIT: If any clarification is needed, ask and it will be provided.</p> | 14,807,441 | 7 | 7 | null | 2013-02-09 00:02:59.36 UTC | 10 | 2013-08-28 15:15:55.193 UTC | 2013-03-30 22:21:30.65 UTC | null | 771,665 | null | 771,665 | null | 1 | 8 | c++|plugins|frameworks|function-pointers|dynamic-library | 4,820 | <p>Function pointers are strange creatures. They're not necessarily the same size as data pointers, and hence cannot be safely cast to <code>void*</code> and back. But, the C++ (and C) specifications allow <a href="https://stackoverflow.com/a/11240372/21475">any function pointer to be safely cast to another function pointer</a> type (though you have to later cast it back to the earlier type before calling it if you want defined behaviour). This is akin to the ability to safely cast any data pointer to <code>void*</code> and back.</p>
<p>Pointers to methods are where it gets really hairy: a method pointer might be larger than a normal function pointer, depending on the compiler, whether the application is 32- or 64-bit, etc. But even more interesting is that, even on the same compiler/platform, not all method pointers are the same size: Method pointers to virtual functions may be bigger than normal method pointers; if multiple inheritance (with e.g. virtual inheritance in the diamond pattern) is involved, the method pointers can be even bigger. This varies with compiler and platform too. This is also the reason that it's difficult to create function objects (that wrap arbitrary methods as well as free functions) especially without allocating memory on the heap (it's <em>just</em> possible using <a href="https://stackoverflow.com/a/4300544/21475">template sorcery</a>).</p>
<p>So, by using function pointers in your interface, it becomes unpractical for the plugin authors to pass back method pointers to your framework, even if they're using the same compiler. This might be an acceptable constraint; more on this later.</p>
<p>Since there's no guarantee that function pointers will be the same size from one compiler to the next, by registering function pointers you're limiting the plugin authors to compilers that implement function pointers having the same size as your compiler does. This wouldn't necessarily be so bad in practice, since function pointer sizes tend to be stable across compiler versions (and may even be the same for multiple compilers).</p>
<p>The real problems start to arise when you want to call the functions pointed to by the function pointers; you can't safely call the function at all if you don't know its true signature (you <em>will</em> get poor results ranging from "not working" to segmentation faults). So, the plugin authors would be further limited to registering only <code>void</code> functions that take no parameters.</p>
<p>It gets worse: the way a function call actually works at the assembler level depends on more than just the signature and function pointer size. There's also the calling convention, the way exceptions are handled (the stack needs to be properly unwound when an exception is thrown), and the actual interpretation of the bytes of function pointer (if it's larger than a data pointer, what do the extra bytes signify? In what order?). At this point, the plugin author is pretty much limited to using the same compiler (and version!) that you are, and needs to be careful to match the calling convention and exception handling options (with the MSVC++ compiler, for example, exception handling is only explicitly enabled with the <a href="http://msdn.microsoft.com/en-us/library/1deeycx5%28v=vs.110%29.aspx" rel="nofollow noreferrer"><code>/EHsc</code></a> option), as well as use only normal function pointers with the exact signature you define.</p>
<p>All the restrictions so far <em>can</em> be considered reasonable, if a bit limiting. But we're not done yet.</p>
<p>If you throw in <code>std::string</code> (or almost any part of the STL), things get even worse though, because even with the same compiler (and version), there are several different flags/macros that control the STL; these flags can affect the size and meaning of the bytes representing string objects. It is, in effect, like having two <em>different</em> struct declarations in separate files, each with the same name, and hoping they'll be interchangeable; obviously, this doesn't work. An example flag is <code>_HAS_ITERATOR_DEBUGGING</code>. Note that these options can even change between debug and release mode! These types of errors don't always manifest themselves immediately/consistently and can be very difficult to track down.</p>
<p>You also have to be very careful with dynamic memory management across modules, since <code>new</code> in one project may be defined differently from <code>new</code> in another project (e.g. it may be overloaded). When deleting, you might have a pointer to an interface with a virtual destructor, meaning the <code>vtable</code> is needed to properly <code>delete</code> the object, and different compilers all implement the <code>vtable</code> stuff differently. In general, you want the module that allocates an object to be the one to deallocate it; more specifically, you want the <em>code</em> that deallocates an object to have been compiled under the exact same conditions as the code that allocated it. This is one reason <code>std::shared_ptr</code> can take a "deleter" argument when it is constructed -- because even with the same compiler and flags (the only guaranteed safe way to share <code>shared_ptr</code>s between modules), <code>new</code> and <code>delete</code> may not be the same everywhere the <code>shared_ptr</code> can get destroyed. With the deleter, the code that creates the shared pointer controls how it is eventually destroyed too. (I just threw this paragraph in for good measure; you don't seem to be sharing objects across module boundaries.)</p>
<p>All of this is a consequence of C++ having no standard binary interface (<a href="https://stackoverflow.com/questions/7492180/c-abi-issues-list">ABI</a>); it's a free-for-all, where it is very easy to shoot yourself in the foot (sometimes without realising it).</p>
<p>So, is there any hope? You betcha! You can expose a C API to your plugins instead, and have your plugins also expose a C API. This is quite nice because a C API can be interoperated with from virtually any language. You don't have to worry about exceptions, apart from making sure they can't bubble up above the plugin functions (that's the authors' concern), and it's stable no matter the compiler/options (assuming you don't pass STL containers and the like). There's only one standard calling convention (<code>cdecl</code>), which is the default for functions declared <code>extern "C"</code>. <code>void*</code>, in practice, will be the same across all compilers on the same platform (e.g. 8 bytes on x64).</p>
<p>You (and the plugin authors) can still write your code in C++, as long as all the external communication between the two uses a C API (i.e. pretends to be a C module for the purposes of interop).</p>
<p>C function pointers are also likely compatible between compilers in practice, though if you'd rather not depend on this you could have the plugin register a function <em>name</em> (<code>const char*</code>) instead of address, and then you could extract the address yourself using, e.g., <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms684175%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>LoadLibrary</code></a> with <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms683212%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>GetProcAddress</code></a> for Windows (similarly, Linux and Mac OS X have <code>dlopen</code> and <code>dlsym</code>). This works because <a href="https://stackoverflow.com/questions/1314743/what-is-name-mangling-and-how-does-it-work">name-mangling</a> is disabled for functions declared with <code>extern "C"</code>.</p>
<p>Note that there's no direct way around restricting the registered functions to be of a single prototype type (otherwise, as I've said, you can't call them properly). If you need to give a particular parameter to a plugin function (or get a value back), you'll need to register and call the different functions with different prototypes separately (though you could collapse all the function pointers down to a common function pointer type internally, and only cast back at the last minute).</p>
<p>Finally, while you cannot directly support method pointers (which don't even exist in a C API, but are of variable size even with a C++ API and thus cannot be easily stored), you can allow the plugins to supply a "user-data" opaque pointer when registering their function, which is passed to the function whenever it's called; this gives the plugin authors an easy way to write function wrappers around methods and store the object to apply the method to in the user-data parameter. The user-data parameter can also be used for anything else the plugin author wants, which makes your plugin system much easier to interface with and extend. Another example use is to adapt between different function prototypes using a wrapper and extra arguments stored in the user-data.</p>
<p>These suggestions lead to code something like this (for Windows -- the code is very similar for other platforms):</p>
<pre><code>// Shared header
extern "C" {
typedef void (*plugin_function)(void*);
bool registerFunction(int plugin_id, const char* function_name, void* user_data);
}
// Your plugin registration code
hModule = LoadLibrary(pluginDLLPath);
// Your plugin function registration code
auto pluginFunc = (plugin_function)GetProcAddress(hModule, function_name);
// Store pluginFunc and user_data in a map keyed to function_name
// Calling a plugin function
pluginFunc(user_data);
// Declaring a plugin function
extern "C" void aPluginFunction(void*);
class Foo { void doSomething() { } };
// Defining a plugin function
void aPluginFunction(void* user_data)
{
static_cast<Foo*>(user_data)->doSomething();
}
</code></pre>
<p>Sorry for the length of this reply; most of it can be summed up with "the C++ standard doesn't extend to interoperation; use C instead since it at least has <em>de facto</em> standards."</p>
<hr>
<p>Note: Sometimes it's simplest just to design a normal C++ API (with function pointers or interfaces or whatever you like best) under the assumption that the plugins will be compiled under exactly the same circumstances; this is reasonable if you expect all the plugins to be developed by yourself (i.e. the DLLs are part of the project core). This could also work if your project is open-source, in which case everybody can independently choose a cohesive environment under which the project and the plugins are compiled -- but then this makes it hard to distribute plugins except as source code.</p>
<hr>
<p><strong>Update</strong>: As pointed out by ern0 in the comments, it's possible to abstract the details of the module interoperation (via a C API) so that both the main project and the plugins deal with a simpler C++ API. What follows is an outline of such an implementation:</p>
<pre><code>// iplugin.h -- shared between the project and all the plugins
class IPlugin {
public:
virtual void register() { }
virtual void initialize() = 0;
// Your application-specific functionality here:
virtual void onCheeseburgerEatenEvent() { }
};
// C API:
extern "C" {
// Returns the number of plugins in this module
int getPluginCount();
// Called to register the nth plugin of this module.
// A user-data pointer is expected in return (may be null).
void* registerPlugin(int pluginIndex);
// Called to initialize the nth plugin of this module
void initializePlugin(int pluginIndex, void* userData);
void onCheeseBurgerEatenEvent(int pluginIndex, void* userData);
}
// pluginimplementation.h -- plugin authors inherit from this abstract base class
#include "iplugin.h"
class PluginImplementation {
public:
PluginImplementation();
};
// pluginimplementation.cpp -- implements C API of plugin too
#include <vector>
struct LocalPluginRegistry {
static std::vector<PluginImplementation*> plugins;
};
PluginImplementation::PluginImplementation() {
LocalPluginRegistry::plugins.push_back(this);
}
extern "C" {
int getPluginCount() {
return static_cast<int>(LocalPluginRegistry::plugins.size());
}
void* registerPlugin(int pluginIndex) {
auto plugin = LocalPluginRegistry::plugins[pluginIndex];
plugin->register();
return (void*)plugin;
}
void initializePlugin(int pluginIndex, void* userData) {
auto plugin = static_cast<PluginImplementation*>(userData);
plugin->initialize();
}
void onCheeseBurgerEatenEvent(int pluginIndex, void* userData) {
auto plugin = static_cast<PluginImplementation*>(userData);
plugin->onCheeseBurgerEatenEvent();
}
}
// To declare a plugin in the DLL, just make a static instance:
class SomePlugin : public PluginImplementation {
virtual void initialize() { }
};
SomePlugin plugin; // Will be created when the DLL is first loaded by a process
// plugin.h -- part of the main project source only
#include "iplugin.h"
#include <string>
#include <vector>
#include <windows.h>
class PluginRegistry;
class Plugin : public IPlugin {
public:
Plugin(PluginRegistry* registry, int index, int moduleIndex)
: registry(registry), index(index), moduleIndex(moduleIndex)
{
}
virtual void register();
virtual void initialize();
virtual void onCheeseBurgerEatenEvent();
private:
PluginRegistry* registry;
int index;
int moduleIndex;
void* userData;
};
class PluginRegistry {
public:
registerPluginsInModule(std::string const& modulePath);
~PluginRegistry();
public:
std::vector<Plugin*> plugins;
private:
extern "C" {
typedef int (*getPluginCountFunc)();
typedef void* (*registerPluginFunc)(int);
typedef void (*initializePluginFunc)(int, void*);
typedef void (*onCheeseBurgerEatenEventFunc)(int, void*);
}
struct Module {
getPluginCountFunc getPluginCount;
registerPluginFunc registerPlugin;
initializePluginFunc initializePlugin;
onCheeseBurgerEatenEventFunc onCheeseBurgerEatenEvent;
HMODULE handle;
};
friend class Plugin;
std::vector<Module> registeredModules;
}
// plugin.cpp
void Plugin::register() {
auto func = registry->registeredModules[moduleIndex].registerPlugin;
userData = func(index);
}
void Plugin::initialize() {
auto func = registry->registeredModules[moduleIndex].initializePlugin;
func(index, userData);
}
void Plugin::onCheeseBurgerEatenEvent() {
auto func = registry->registeredModules[moduleIndex].onCheeseBurgerEatenEvent;
func(index, userData);
}
PluginRegistry::registerPluginsInModule(std::string const& modulePath) {
// For Windows:
HMODULE handle = LoadLibrary(modulePath.c_str());
Module module;
module.handle = handle;
module.getPluginCount = (getPluginCountFunc)GetProcAddr(handle, "getPluginCount");
module.registerPlugin = (registerPluginFunc)GetProcAddr(handle, "registerPlugin");
module.initializePlugin = (initializePluginFunc)GetProcAddr(handle, "initializePlugin");
module.onCheeseBurgerEatenEvent = (onCheeseBurgerEatenEventFunc)GetProcAddr(handle, "onCheeseBurgerEatenEvent");
int moduleIndex = registeredModules.size();
registeredModules.push_back(module);
int pluginCount = module.getPluginCount();
for (int i = 0; i < pluginCount; ++i) {
auto plugin = new Plugin(this, i, moduleIndex);
plugins.push_back(plugin);
}
}
PluginRegistry::~PluginRegistry() {
for (auto it = plugins.begin(); it != plugins.end(); ++it) {
delete *it;
}
for (auto it = registeredModules.begin(); it != registeredModules.end(); ++it) {
FreeLibrary(it->handle);
}
}
// When discovering plugins (e.g. by loading all DLLs in a "plugins" folder):
PluginRegistry registry;
registry.registerPluginsInModule("plugins/cheeseburgerwatcher.dll");
for (auto it = registry.plugins.begin(); it != registry.plugins.end(); ++it) {
(*it)->register();
}
for (auto it = registry.plugins.begin(); it != registry.plugins.end(); ++it) {
(*it)->initialize();
}
// And then, when a cheeseburger is actually eaten:
for (auto it = registry.plugins.begin(); it != registry.plugins.end(); ++it) {
auto plugin = *it;
plugin->onCheeseBurgerEatenEvent();
}
</code></pre>
<p>This has the benefit of using a C API for compatibility, but also offering a higher level of abstraction for plugins written in C++ (and for the main project code, which is C++). Note that it lets multiple plugins be defined in a single DLL. You could also eliminate some of the duplication of function names by using macros, but I chose not to for this simple example.</p>
<hr>
<p>All of this, by the way, assumes plugins that have no interdependencies -- if plugin A affects (or is required by) plugin B, you need to devise a safe method for injecting/constructing dependencies as needed, since there's no way of guaranteeing what order the plugins will be loaded in (or initialized). A two-step process would work well in that case: Load and register all plugins; during registration of each plugin, let them register any services they provide. During initialization, construct requested services as needed by looking at the registered service table. This ensures that all services offered by all plugins are registered <em>before</em> any of them are attempted to be used, no matter what order plugins get registered or initialized in.</p> |
14,364,144 | Android video frame processing | <p>I am working on application that does some real time image processing on camera frames. For that, I use preview callback's method <code>onPreviewFrame</code>. <br>This works fine for cameras that support preview frames that have resolution at least 640x480 or larger. But when camera does not support such large camera preview resolution, application is programmed to refuse processing such frames. Now, the problem I have is with phones like <code>Sony Xperia</code> Go. It is a very nice device that can record video up to resolution 1280x720, but unfortunately maximum camera preview size is 480x320, which is too small for my needs.</p>
<p>What I would like to know is how to obtain these <code>larger camera frames</code> (up to 1280x720 or more)? Obviously it has to be possible because camera application has the ability to record videos in that resolution - therefore this application somehow must be able to access those larger frames. How to do the same from my application?</p>
<p>Application has to support Android 2.1 and later, but I would be very happy even if I find the solution for my problem only for Android 4.0 or newer.</p>
<p>This question is similar to <code>http://stackoverflow.com/questions/8839109/processing-android-video-frame-by-frame-while-recording</code>, but I don't need to save the video - I only need those high resolution video frames...</p> | 22,061,500 | 4 | 4 | null | 2013-01-16 17:24:46.347 UTC | 10 | 2021-08-15 14:18:34.877 UTC | 2020-12-26 12:33:25.647 UTC | null | 6,296,561 | null | 213,057 | null | 1 | 17 | android|video|image-processing|camera|computer-vision | 7,483 | <p>It seems the only thing you can do is decoding frames from MediaRecoder data.
You may use ffmpeg to decode recoreder data from LocalSocket.</p>
<p>Hope the following open source projects may help:</p>
<p>ipcamera-for-android: <a href="https://code.google.com/p/ipcamera-for-android/">https://code.google.com/p/ipcamera-for-android/</a></p>
<p>spydroid-ipcamera: <a href="https://code.google.com/p/spydroid-ipcamera/">https://code.google.com/p/spydroid-ipcamera/</a></p> |
14,543,245 | Browser back button handling | <p>I am trying to handle browser back button event but i could not find any solution. </p>
<p>I want to ask user if he clicks on browser back button using "confirm box" if he chooses ok i have to allow back button action else i have to stop back button action.</p>
<p>Can any one help me in implementing this.</p> | 14,548,415 | 2 | 5 | null | 2013-01-27 00:46:04.48 UTC | 6 | 2017-01-10 01:09:10.953 UTC | null | null | null | null | 1,185,238 | null | 1 | 31 | javascript|jquery|html|browser | 121,613 | <p>Warn/confirm User if Back button is Pressed is as below.</p>
<pre><code>window.onbeforeunload = function() { return "Your work will be lost."; };
</code></pre>
<p>You can get more information using below mentioned links.</p>
<p><a href="http://viralpatel.net/blogs/disable-back-button-browser-javascript/" rel="noreferrer"><strong>Disable Back Button in Browser using JavaScript</strong></a></p>
<p>I hope this will help to you.</p> |
14,677,060 | 400x Sorting Speedup by Switching a.localeCompare(b) to (a<b?-1:(a>b?1:0)) | <p>By switching a javascript sort function from</p>
<pre><code>myArray.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
</code></pre>
<p>to</p>
<pre><code>myArray.sort(function (a, b) {
return (a.name < b.name ? -1 : (a.name > b.name ? 1 : 0));
});
</code></pre>
<p>I was able to cut the time to sort a ~1700 element array in Chrome from 1993 milliseconds to 5 milliseconds. Almost a 400x speedup. Unfortunately this is at the expense of correctly sorting non-english strings.</p>
<p>Obviously I can't have my UI blocking for 2 seconds when I try to do a sort. Is there anything I can do to avoid the horribly slow localeCompare but still maintain support for localized strings?</p> | 52,369,951 | 5 | 6 | null | 2013-02-03 20:40:57.033 UTC | 14 | 2021-06-24 06:08:50.933 UTC | 2017-02-22 01:12:03.25 UTC | null | 2,054,072 | null | 899,365 | null | 1 | 55 | javascript|google-chrome|sorting | 29,984 | <p>A great performance improvement can be obtained by declaring the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator" rel="noreferrer">collator</a> object beforehand and using it's compare method. EG:</p>
<pre><code>const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' });
arrayOfObjects.sort((a, b) => {
return collator.compare(a.name, b.name);
});
</code></pre>
<p>NOTE: This doesn't work ok if the elements are floats. See explanation here: <a href="https://stackoverflow.com/questions/40107588/intl-collator-and-natural-sort-with-numeric-option-sorts-incorrectly-with-decima">Intl.Collator and natural sort with numeric option sorts incorrectly with decimal numbers</a></p>
<p>Here's a benchmark script comparing the 3 methods:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [];
for (let i = 0; i < 2000; i++) {
arr.push(`test-${Math.random()}`);
}
const arr1 = arr.slice();
const arr2 = arr.slice();
const arr3 = arr.slice();
console.time('#1 - localeCompare');
arr1.sort((a, b) => a.localeCompare(
b,
undefined, {
numeric: true,
sensitivity: 'base'
}
));
console.timeEnd('#1 - localeCompare');
console.time('#2 - collator');
const collator = new Intl.Collator('en', {
numeric: true,
sensitivity: 'base'
});
arr2.sort((a, b) => collator.compare(a, b));
console.timeEnd('#2 - collator');
console.time('#3 - non-locale');
arr3.sort((a, b) => (a < b ? -1 : (a > b ? 1 : 0)));
console.timeEnd('#3 - non-locale');</code></pre>
</div>
</div>
</p> |
14,594,121 | Express res.sendfile throwing forbidden error | <p>I have this code:</p>
<pre><code>res.sendfile( '../../temp/index.html' )
</code></pre>
<p>However, it throws this error:</p>
<pre><code>Error: Forbidden
at SendStream.error (/Users/Oliver/Development/Personal/Reader/node_modules/express/node_modules/send/lib/send.js:145:16)
at SendStream.pipe (/Users/Oliver/Development/Personal/Reader/node_modules/express/node_modules/send/lib/send.js:307:39)
at ServerResponse.res.sendfile (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/response.js:339:8)
at exports.boot (/Users/Oliver/Development/Personal/Reader/server/config/routes.js:18:9)
at callbacks (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:161:37)
at param (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:135:11)
at pass (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:142:5)
at Router._dispatch (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:170:5)
at Object.router (/Users/Oliver/Development/Personal/Reader/node_modules/express/lib/router/index.js:33:10)
at next (/Users/Oliver/Development/Personal/Reader/node_modules/express/node_modules/connect/lib/proto.js:199:15)
</code></pre>
<p>Can anyone tell me why this might be?</p> | 14,594,282 | 4 | 4 | null | 2013-01-29 23:37:25.073 UTC | 21 | 2021-05-22 08:59:23.567 UTC | null | null | null | user1082754 | null | null | 1 | 186 | node.js|express | 81,823 | <p>I believe it's because of the relative path; the "../" is considered malicious. Resolve the local path first, then call <code>res.sendfile</code>. You can resolve the path with <code>path.resolve</code> beforehand.</p>
<pre><code>var path = require('path');
res.sendFile(path.resolve('temp/index.html'));
</code></pre> |
25,306,168 | What is the purpose of .bin folder in node_modules? | <p>Today one colleague explained me how to create nodejs projects and I notice that in ./node_modules there is an invisible folder named .bin. I must said that I discovered this after adding to the project "bootcamp" and "bower" tools. What's .bin purpose? What is it created for?</p> | 25,306,331 | 2 | 0 | null | 2014-08-14 10:46:22.187 UTC | 11 | 2020-04-22 08:56:33.71 UTC | 2017-09-08 14:28:05.64 UTC | null | 1,000,551 | null | 3,921,285 | null | 1 | 53 | node.js|bower | 31,091 | <p>That is a folder where binaries (executables) from your node modules are located.</p>
<p><a href="https://docs.npmjs.com/files/folders#executables" rel="noreferrer">NPM site states</a>:</p>
<blockquote>
<p>Executables When in global mode, executables are linked into
{prefix}/bin on Unix, or directly into {prefix} on Windows.</p>
<p>When in local mode, executables are linked into ./node_modules/.bin so
that they can be made available to scripts run through npm. (For
example, so that a test runner will be in the path when you run npm
test.)</p>
</blockquote> |
2,623,957 | How to display a JTable in a JPanel with Java? | <p>How to display a JTable in a JPanel with Java?</p> | 2,623,987 | 2 | 0 | null | 2010-04-12 17:20:28.873 UTC | 4 | 2012-05-20 05:35:43.56 UTC | 2012-01-18 20:08:33.267 UTC | null | 918,414 | null | 328,256 | null | 1 | 6 | java|swing|jtable|jpanel | 55,462 | <p>Imports and table model left as an exercise to the user of this code. Also, the panel layout is arbitrarily chosen for simplicity.</p>
<pre><code>public class JTableDisplay {
public JTableDisplay() {
JFrame frame = new JFrame("JTable Test Display");
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JTable table = new JTable();
JScrollPane tableContainer = new JScrollPane(table);
panel.add(tableContainer, BorderLayout.CENTER);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new JTableDisplay();
}
}
</code></pre>
<p>The scroll pane is fairly important to note. Without it, your table won't have a header or scroll if the content becomes larger than the display.</p> |
2,492,020 | how to view contents of STL containers using GDB 7.x | <p>I have been using the macro solution, as it is outlined <a href="https://stackoverflow.com/questions/2463198/printing-stl-containers-with-gdb-7-0">here</a>. However, there is a mention on how to view them without macros. I am referring to GDB version 7 and above.</p>
<p>Would someone illustrate how?</p>
<p>Thanks </p> | 2,492,341 | 2 | 2 | null | 2010-03-22 12:06:32.7 UTC | 15 | 2013-04-19 11:20:31.167 UTC | 2017-05-23 10:29:21.527 UTC | anon | -1 | null | 149,045 | null | 1 | 13 | c++|stl|gdb | 14,691 | <p>Get the python viewers from SVN </p>
<pre><code>svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
</code></pre>
<p>Add the following to your <code>~/.gdbinit</code></p>
<pre><code>python
import sys
sys.path.insert(0, '/path/to/pretty-printers/dir')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (None)
end
</code></pre>
<p>Then print should just work:</p>
<pre><code>std::map<int, std::string> the_map;
the_map[23] = "hello";
the_map[1024] = "world";
</code></pre>
<p>In gdb:</p>
<pre><code>(gdb) print the_map
$1 = std::map with 2 elements = { [23] = "hello", [1024] = "world" }
</code></pre>
<p>To get back to the old view use <code>print /r</code> (<code>/r</code> is for raw).</p>
<p>See also: <a href="http://sourceware.org/gdb/wiki/STLSupport" rel="noreferrer">http://sourceware.org/gdb/wiki/STLSupport</a></p> |
1,431,999 | Java and Kerberos authentication krb5.conf versus System.setProperty | <p>Please help me on a kerberos+Java problem. I have a simple Java program to authenticate to a Windows Active Directory using Kerberos. The following java code works fine without any problems and prints true-</p>
<pre><code>public class KerberosAuthenticator {
public static void main(String[] args) {
String jaasConfigFilePath = "/myDir/jaas.conf";
System.setProperty("java.security.auth.login.config", jaasConfigFilePath);
System.setProperty("java.security.krb5.realm", "ENG.TEST.COM");
System.setProperty("java.security.krb5.kdc","winsvr2003r2.eng.test.com");
boolean success = auth.KerberosAuthenticator.authenticate("testprincipal", "testpass");
System.out.println(success);
}
}
</code></pre>
<p>Bue when I specify the path to the krb5.conf file instead of manually specifying the realm and kdc, it errors out saying "Null realm name (601) - default realm not specified". Following is the code-</p>
<pre><code>public class KerberosAuthenticator {
public static void main(String[] args) {
String jaasConfigFilePath = "/myDir/jaas.conf";
System.setProperty("java.security.auth.login.config", jaasConfigFilePath);
String krb5ConfigFilePath = "/etc/krb5/krb5.conf";
System.setProperty("java.security.krb5.conf", krb5ConfigFilePath);
boolean success = auth.KerberosAuthenticator.authenticate("testprincipal", "testpass");
System.out.println(success);
}
}
</code></pre>
<p>The contents of krb5.conf is as follows-</p>
<pre><code>[libdefault]
default_realm = ENG.TEST.COM
[realms]
ENG.TEST.COM = {
kdc = winsvr2003r2.eng.test.com
kpasswd_server = winsvr2003r2.eng.test.com
admin_server = winsvr2003r2.eng.test.com
kpasswd_protocol = SET_CHANGE
}
[domain_realm]
.eng.test.com = ENG.TEST.COM
eng.test.com = ENG.TEST.COM
[logging]
default = FILE:/var/krb5/kdc.log
kdc = FILE:/var/krb5/kdc.log
kdc_rotate = {
period = 1d
versions = 10
}
[appdefaults]
kinit = {
renewable = true
forwardable = true
}
</code></pre> | 1,435,044 | 1 | 1 | null | 2009-09-16 09:40:54.707 UTC | 6 | 2009-09-16 19:38:48.46 UTC | null | null | null | null | 155,684 | null | 1 | 18 | java|kerberos|jaas | 43,375 | <p>Your krb5.conf is wrong. It's <strong>[libdefaults]</strong>, not [libdefault].</p> |
1,876,664 | Find/replace across workspace in eclipse | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/3376440/eclipse-replace-text-in-all-classes">Eclipse Replace text in all Classes?</a> </p>
</blockquote>
<p>I want to replace all instances of Foo.bar() with Foo across all files in my workspace in eclipse. Is there a way of doing this?</p> | 1,876,676 | 1 | 1 | null | 2009-12-09 20:29:14.223 UTC | 6 | 2009-12-09 20:37:39.623 UTC | 2017-05-23 12:02:32.97 UTC | null | -1 | null | 228,276 | null | 1 | 37 | eclipse | 26,584 | <p>When you do a text-based search in eclipse (using the flashlight button at the top of the screen and selecting the right tab) there's a "Replace..." button at the bottom of the dialog. Press that, instead of search, and you can do a global find and replace.</p>
<p>Alternatively, you can use the refactoring feature to change it to something else.</p> |
21,809,216 | What is the definition of 'Idiomatic' as in Idiomatic Javascript? | <p>In Anders first talk on TypeScript, he uses the phrase 'idiomatic javascript" several times.</p>
<p>What is the definition of idiomatic as it is used here?</p>
<p>I have looked this up on Wikipedia, SO search etc, but still feel I don't fully understand what the word means in this context.</p>
<p>Greg</p> | 21,809,245 | 1 | 0 | null | 2014-02-16 09:01:26.14 UTC | 5 | 2014-02-16 09:04:40.733 UTC | null | null | null | null | 425,823 | null | 1 | 28 | javascript|typescript | 7,018 | <p>Idiomatic here means "How people who write JavaScript write JavaScript".</p>
<p>It means "Natural to the native speaker".</p>
<p>For example, returning an object is considered by some idiomatic JavaScript:</p>
<pre><code>function foo(){
return {x:3,y:5};
}
var point = foo();
</code></pre>
<p>While "out parameters" are considered less idiomatic:</p>
<pre><code>function foo(out){
out.point = {x:3,y:5}
}
var out = {};
foo(out);
point = out.point;
</code></pre>
<p>Another example of idiomatic JavaScript is the use of closures.</p> |
35,326,710 | Stripe Currency - Are all amounts in cents / 100ths, or does it depend on currency? | <p>I am currently writing the code to migrate to Stripe from a different payment processor.</p>
<p>I know that when the currency is USD, stripe uses cents. So stripe(1000 USD) == $10.00. Same for Euros I assume stripe(1000 EUR) == € 10.00. </p>
<p>But what about JPY? 100 JPY is roughly $1. So do I send Stripe 10000 JPY to get 100 Yen ~= $1. Do I send Stripe 100 JPY to get 100 Yen ~= $1?</p>
<p>Is there a special divisor? Is everything denominated in 100/ths for any currency? I can't find an answer in the documentation, and I don't want to charge Japanese people $0.1 or $1000 for a $10 USD service.</p>
<p>How is AED denominated. They use 1/10ths as the smallest unit / coinage. Should I multiply by 10?</p> | 35,326,901 | 1 | 0 | null | 2016-02-10 21:53:40.097 UTC | 4 | 2016-02-11 01:33:20.803 UTC | 2016-02-11 01:33:20.803 UTC | null | 20,512 | null | 20,512 | null | 1 | 34 | stripe-payments | 17,131 | <p>All amounts are in the "smallest common currency unit". While in most places this would be cents, in Japan there is no decimal for their currency so amount=1 (1 JPY), since ¥1 is the smallest currency unit.</p>
<p>Additional info can be found at <a href="https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support" rel="noreferrer">this doc</a>.</p> |
38,715,001 | How to make web workers with TypeScript and webpack | <p>I'm having some issues with properly compiling my typescript when I attempt to use web workers with Webpack.</p>
<p>I have a worker defined like this:</p>
<pre><code>onmessage = (event:MessageEvent) => {
var files:FileList = event.data;
for (var i = 0; i < files.length; i++) {
postMessage(files[i]);
}
};
</code></pre>
<p>In another part of my application i'm using the webpack worker loader to load my worker like this: <code>let Worker = require('worker!../../../workers/uploader/main');</code></p>
<p>I'm however having some issues with making the typescript declarations not yell at me when the application has to be transpiled.
According to my research i have to add another standard lib to my tsconfig file to expose the global variables the worker need access to. These i have specified like so:</p>
<pre><code>{
"compilerOptions": {
"lib": [
"webworker",
"es6",
"dom"
]
}
}
</code></pre>
<p>Now, when i run webpack to have it build everything i get a bunch of errors like these: <code> C:/Users/hanse/Documents/Frontend/node_modules/typescript/lib/lib.webworker.d.ts:1195:13 Subsequent variable declarations must have the same type. Variable 'navigator' must be of type 'Navigator', but here has type 'WorkerNavigator'.</code></p>
<p>So my question is: How do I specify so the webworker uses the lib.webworker.d.ts definitions and everything else follows the normal definitions?</p> | 40,276,284 | 4 | 0 | null | 2016-08-02 08:06:46.76 UTC | 14 | 2022-03-17 09:18:18.207 UTC | 2022-03-17 09:18:18.207 UTC | null | 712,334 | null | 3,950,006 | null | 1 | 44 | typescript|webpack|web-worker | 45,926 | <p>In your <code>tsconfig.json</code> file, in <code>compilerOptions</code> set this:</p>
<pre><code>{
"compilerOptions": {
"target": "es5",
//this config for target "es5"
"lib": ["webworker", "es5", "scripthost"]
//uncomment this for target "es6"
//"lib": ["webworker", "es6", "scripthost"]
}
}
</code></pre>
<p>Web workers can't access to DOM, <code>window</code>, <code>document</code> and <code>parent</code> objects (full list supported objects here: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers" rel="noreferrer">Functions and classes available to Web Workers</a>); the <code>dom</code> lib of TypeScript is not compatible and redefine some elements that are define in <code>lib.webworker.d.ts</code></p> |
40,570,716 | swift 3 filter array of dictionaries by string value of key in dictionary | <p>I have a class such as this</p>
<pre><code>class FoundItem : NSObject {
var id : String!
var itemName : String!
var itemId : Int!
var foundBy : String!
var timeFound : String!
init(id: String,
itemName: String,
itemId: Int,
foundBy: String,
timeFound: String)
{
self.id = id
self.itemName = itemName
self.itemId = itemId
self.foundBy = foundBy
self.timeFound = timeFound
}
</code></pre>
<p>and I reference it on my </p>
<pre><code>class MapViewVC: UIViewController, MKMapViewDelegate {
var found = [FoundItem]()
var filterItemName : String()
}
</code></pre>
<p>My <code>FoundItem</code> are generated by into an array of dictionaries from my class of <code>FoundItem</code> from a firebase query. I then get a string of that <code>itemName</code> that is generated from an another view controller that is a collection view on the <code>didSelection</code> function. I want to take that string and then filter or search the arrays with the string <code>itemName</code> that is equal from the <code>itemName</code> string from my previous <code>viewController</code>. Then removed the array of dictionaries that are not equal to the <code>itemName</code>. Not just the objects, but the entire array that contains non-equal key, value pair. I have looked for days, and I am stuck on filtering an array of dictionaries created from a class. I have looked and tried NSPredicates, for-in loops, but all that ends up happening is creating a new array or bool that finds my values or keys are equal. Here is the current function I have written. </p>
<pre><code>func filterArrayBySearch() {
if self.filterItemName != nil {
dump(found)
let namePredicate = NSPredicate(format: "itemName like %@", "\(filterItemName)")
let nameFilter = found.filter { namePredicate.evaluate(with: $0) }
var crossRefNames = [String: [FoundItem]]()
for nameItemArr in found {
let listName = nameItem.itemName
let key = listName
if crossRefNames.index(forKey: key!) != nil {
crossRefNames[key!]?.append(nameItemArr)
if !("\(key)" == "\(filterItemName!)") {
print("------------- Success have found [[[[[[ \(key!) ]]]]]] and \(filterItemName!) to be equal!!")
// crossRefNames[key!]?.append(nameItemArr)
} else {
print("!! Could not find if \(key!) and \(filterItemName!) are equal !!")
}
} else {
crossRefNames[key!] = [nameItemArr]
}
}
} else {
print("No Data from Search/FilterVC Controller")
}
}
</code></pre>
<p>Can anyone help? It seems like it would be the simple task to find the value and then filter out the dictionaries that are not equal to the <code>itemName</code> string, but I keep hitting a wall. And running into for-in loops myself :P trying different things to achieve the same task. </p> | 40,570,891 | 4 | 0 | null | 2016-11-13 04:53:42.497 UTC | 3 | 2021-06-11 20:27:55.783 UTC | 2017-08-26 08:41:47.55 UTC | null | 3,607,051 | null | 6,749,074 | null | 1 | 12 | ios|arrays|swift|dictionary|filter | 40,907 | <p>I hope I understood what you were asking. You mention an "array of dictionaries" but you don't actually have an array of dictionaries anywhere in the code you've posted.</p>
<p>As far as I can tell, you are asking how to find all the entries in the <code>found</code> array for which <code>itemName</code> equals the <code>filterItemName</code> property.</p>
<p>If so, all you should need to do is:</p>
<p><code>let foundItems = found.filter { $0.itemName == filterItemName }</code></p>
<p>That's it.</p>
<hr>
<p>Some other ideas:</p>
<p>If you want to search for items where <code>filterItemName</code> is contained in the <code>itemName</code>, you could do something like this:</p>
<p><code>let foundItems = found.filter { $0.itemName.contains(filterItemName) }</code></p>
<p>You could also make use of the <code>lowercased()</code> function if you want to do case-insensitive search.</p>
<p>You could also return properties of your found elements into an array:</p>
<p><code>let foundIds = found.filter { $0.itemName == filterItemName }.map { $0.itemId }</code></p> |
40,582,161 | How to properly use Bearer tokens? | <p>I'm making an authorization system in <code>PHP</code>, and I came across this Bearer scheme of passing JWT tokens, I read [RFC 6750][1]. I've got the following doubts:</p>
<ol>
<li>How is this improving the security?</li>
<li>The server responses the client with a JWT token in its body after a successful authorization and login, and now when the client makes another request, I am not clear how to actually do that, I want to send token from client in Authorization header in the request, so now should I just prefix "Bearer" to the token which I received in the previous response from the server and If yes, then server on receiving the Authorization header, should just split the string with space, and take the second value from the obtained array and then decode it? For example <code>Authorization: Bearer fdbghfbfgbjhg_something</code>, how is server supposed to handle this, <code>decodeFunc(explode(" ", $this->getRequest()->getHeader("Authorization"))[1])</code>?
[1]: <a href="https://www.rfc-editor.org/rfc/rfc6750" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc6750</a></li>
</ol> | 40,582,472 | 2 | 0 | null | 2016-11-14 05:03:54.553 UTC | 23 | 2021-12-31 05:17:28.44 UTC | 2021-10-07 07:34:52.683 UTC | null | -1 | null | 4,976,422 | null | 1 | 51 | php|authentication|oauth|http-headers|bearer-token | 81,393 | <p>1.Improving the security because if token is not sent in the header that sent in url, it will be logged by the network system, the server log ....</p>
<p>2.A good function to get Bearer tokens</p>
<pre><code>/**
* Get header Authorization
* */
function getAuthorizationHeader(){
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* */
function getBearerToken() {
$headers = getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
return null;
}
</code></pre> |
14,352,791 | Read data from excel sheet in php | <p>I am using this code for reading data from any file but if i want to read data from excel sheet then what should i do? </p>
<pre><code><?php
if(isset($_POST['submit'])){
$cir="certificate";
if(!is_dir($cir)){
mkdir($cir);
}
$image1=$_FILES['cir']['name'];
$image=$_FILES['cir']['tmp_name'];
$server_path=$cir.'/'.basename($_FILES['cir']['name']);
$s=move_uploaded_file($image,$server_path);
if($s){
//echo "successfully uploaded.";
$file_open=fopen("$cir/$image1","r");
$file_read=fread($file_open,filesize("$cir/$image1"));
echo $file_read;
//$data = substr(strrchr("$cir/$file_read", ","),5 );
echo $file_read;
}else{
echo "problem in uploading.";
}
}
?>
<html>
<body>
<form name="form" method="post" enctype="multipart/form-data">
<input type="file" name="cir" /><br />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
</code></pre>
<p>Excel sheet containing various shells like Name-XYZ, s.no-123 etc. I want that xyz should be put on a variable and 123 should be on another variable. What will be code in PHP? </p> | 14,352,862 | 2 | 0 | null | 2013-01-16 06:50:45.13 UTC | 1 | 2017-11-21 14:47:32.977 UTC | 2013-01-16 06:57:18.723 UTC | null | 1,915,402 | null | 1,977,139 | null | 1 | 0 | php | 44,157 | <p>If your site involves reading excel files extensively then go for a library like <a href="https://github.com/PHPOffice/PHPExcel" rel="nofollow noreferrer">https://github.com/PHPOffice/PHPExcel</a> . It supports both xls and xlsx types. </p> |
39,052,337 | Run two commands at the same time in Elm | <p>In <code>Elm</code>, and specifically with the <a href="http://guide.elm-lang.org/architecture/">Elm Architecture</a> when the app first starts the <code>init</code> function can return a <code>Cmd Msg</code> that is executed. We can use this for sending http requests or send a message to native Javascript via <a href="http://guide.elm-lang.org/interop/javascript.html">Elm ports</a>.</p>
<p>My question is, how can I send multiple commands that should be executed in <code>init</code>?</p>
<p>For example I can do something like:</p>
<pre><code>init : (Model, Cmd Msg)
init =
(Model "" [], (Ports.messageToJs "Hello JS"))
</code></pre>
<p>And I can do something like:</p>
<pre><code>url : String
url =
"http://some-api-url.com"
...
fetchCmd : Cmd Msg
fetchCmd =
Task.perform FetchError FetchSuccess fetchTask
init : (Model, Cmd Msg)
init =
(Model "" [], fetchCmd)
</code></pre>
<p><strong>How can I return both commands at same time from <code>init</code>?</strong></p>
<p>I have seen <code>Task.sequence</code> and even <code>Task.parallel</code> but they appear to be good for running multiple tasks, not specifically commands.</p> | 39,052,711 | 2 | 0 | null | 2016-08-20 09:00:06.587 UTC | 4 | 2022-03-06 05:42:46.433 UTC | null | null | null | null | 1,167,223 | null | 1 | 31 | javascript|elm | 6,678 | <p>Use <code>Platform.Cmd.batch</code> (<a href="https://package.elm-lang.org/packages/elm/core/latest/Platform-Cmd#batch" rel="nofollow noreferrer">docs</a>):</p>
<pre><code>init : (Model, Cmd Msg)
init =
( Model "" []
, Cmd.batch [fetchCmd, Ports.messageToJs "Hello JS")]
)
</code></pre> |
2,717,196 | Forwarding an email with python smtplib | <p>I'm trying to put together a script that automatically forwards certain emails that match a specific criteria to another email.</p>
<p>I've got the downloading and parsing of messages using imaplib and email working, but I can't figure out how to forward an entire email to another address. Do I need to build a new message from scratch, or can I somehow modify the old one and re-send it?</p>
<p>Here's what I have so far (client is an imaplib.IMAP4 connection, and id is a message ID):</p>
<pre><code>import smtplib, imaplib
smtp = smtplib.SMTP(host, smtp_port)
smtp.login(user, passw)
client = imaplib.IMAP4(host)
client.login(user, passw)
client.select('INBOX')
status, data = client.fetch(id, '(RFC822)')
email_body = data[0][1]
mail = email.message_from_string(email_body)
# ...Process message...
# This doesn't work
forward = email.message.Message()
forward.set_payload(mail.get_payload())
forward['From'] = '[email protected]'
forward['To'] = '[email protected]'
smtp.sendmail(user, ['[email protected]'], forward.as_string())
</code></pre>
<p>I'm sure there's something slightly more complicated I need to be doing with regard to the MIME content of the message. Surely there's some simple way of just forwarding the entire message though?</p>
<pre><code># This doesn't work either, it just freezes...?
mail['From'] = '[email protected]'
mail['To'] = '[email protected]'
smtp.sendmail(user, ['[email protected]'], mail.as_string())
</code></pre> | 4,566,267 | 1 | 4 | null | 2010-04-26 21:54:34.007 UTC | 15 | 2011-03-20 11:43:21.007 UTC | 2010-04-28 05:39:45.713 UTC | null | 279,089 | null | 279,089 | null | 1 | 13 | python|email|smtp|imap|smtplib | 22,151 | <p>I think the part you had wrong was how to replace the headers in the message, and the fact that you don't need to make a copy of the message, you can just operate directly on it after creating it from the raw data you fetched from the IMAP server.</p>
<p>You did omit some detail so here's my complete solution with all details spelled out. Note that I'm putting the SMTP connection in STARTTLS mode since I need that and note that I've separated the IMAP phase and the SMTP phase from each other. Maybe you thought that altering the message would somehow alter it on the IMAP server? If you did, this should show you clearly that that doesn't happen.</p>
<pre><code>import smtplib, imaplib, email
imap_host = "mail.example.com"
smtp_host = "mail.example.com"
smtp_port = 587
user = "xyz"
passwd = "xyz"
msgid = 7
from_addr = "[email protected]"
to_addr = "[email protected]"
# open IMAP connection and fetch message with id msgid
# store message data in email_data
client = imaplib.IMAP4(imap_host)
client.login(user, passwd)
client.select('INBOX')
status, data = client.fetch(msgid, "(RFC822)")
email_data = data[0][1]
client.close()
client.logout()
# create a Message instance from the email data
message = email.message_from_string(email_data)
# replace headers (could do other processing here)
message.replace_header("From", from_addr)
message.replace_header("To", to_addr)
# open authenticated SMTP connection and send message with
# specified envelope from and to addresses
smtp = smtplib.SMTP(smtp_host, smtp_port)
smtp.starttls()
smtp.login(user, passwd)
smtp.sendmail(from_addr, to_addr, message.as_string())
smtp.quit()
</code></pre>
<p>Hope this helps even if this answer comes quite late.</p> |
38,785,622 | How to I tell a Springdata-repository's delete method to not throw an exception if an entity does not exists? | <p>I am using SpringData's repository. If I try to delete an entity via an ID which does not exist or never existed it throws an exception. Since I do not want to check whether the entity exists before I delete it, it would be nice that it would fail silently. It would make it easier because the observable behavior is the same - after the call the entity does not exists anymore. Whether it has been deleted or never existed, I do not care.</p>
<p>Is there a way to modify default behavior of <code>delete(EntityId)</code> so it won't throw an exception, if entity does not exsist?</p>
<p><a href="http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#delete-java.lang.Iterable" rel="noreferrer">Documentation of SpringData's delete</a> says that it will throw an exception if an entity does not exist.</p> | 38,785,858 | 10 | 2 | null | 2016-08-05 09:17:13.857 UTC | 2 | 2022-07-13 12:29:35.75 UTC | 2016-08-07 14:28:04.647 UTC | null | 430,035 | null | 430,035 | null | 1 | 42 | java|spring|spring-data | 40,408 | <p><strong>Updated Answer (after downvotes)</strong></p>
<p>My original answer (below) is actually wrong: my understanding of the question was influenced also by the missing reference to the <code>EmptyResultDataAccessException</code> in the official JavaDoc (as reported by Adrian Baker in his comment).</p>
<p>So a better solution to this issue could be the one suggested by Yamashiro Rion</p>
<pre><code>if (repository.existsById(entityId)) {
repository.deleteById(entityId);
}
</code></pre>
<p>or this one (without the <code>if</code>, but probably worse performing):</p>
<pre><code>repository.findById(entityId)
.map(repository::delete)
</code></pre>
<hr>
<p><strong>Original (Wrong) Answer</strong></p>
<p>JavaDocs says that an <code>IllegalArgumentException</code> will be thrown if the provided argument (id, entity, <code>Iterable<T></code>) is null and not <em>if entity does not exsits</em>.</p>
<p>If you need to avoid the <code>IllegalArgumentException</code> you could implement a custom delete method that checks <code>id != null</code>:</p>
<pre><code>public void customDelete(ID id) {
if(id != null){
this.delete(id);
}
}
</code></pre>
<p>Take a look to <a href="http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations" rel="noreferrer">this docs section</a> if you don't know how to add <em>"Custom implementations for Spring Data repositories"</em></p> |
32,374,907 | tmux mouse copy-mode jumps to bottom | <p>I am using tmux in a ssh session.
I am using multiple panes and windows.</p>
<p>I have mouse-mode enabled which works great so far.</p>
<p>When I select text it gets automatically copied to the tmux-buffer and the window jumps to the end.
So if i scroll up and click on something it jumps to the end...
When I switch between panes a copy command is triggered and the output goes to the end.
I really dislike this behaviour and I'd rather have to press a button to copy or click q to finish copy mode or something.</p>
<p>Is it possible to disable auto-copy // auto jump to the end on mouse button release?</p>
<p>I am running tmux 2.0 on the server through ssh. In Terminator on the client.</p>
<pre><code># config
#{{{
# 0 is too far from ` ;)
set -g base-index 1
# Automatically set window title
# set-window-option -g automatic-rename on
# set-option -g set-titles on
set -g default-terminal screen-256color
set -g history-limit 10000
set -g status-keys vi
setw -g mode-keys vi
setw -g mode-mouse on
set -g mouse-select-window on
set -g mouse-select-pane on
set -g mouse-resize-pane on
# No delay for escape key press
set -sg escape-time 0
#}}}
# bind keys
#{{{
# Reload tmux config
bind r source-file ~/.tmux.conf
# remap prefix to Control + a
set -g prefix C-a
# bind 'C-a C-a' to type 'C-a'
bind C-a send-prefix
unbind C-b
# switch tabs with <b n>
bind b previous-window
# vi like paste
bind-key p paste-buffer
# quick pane cycling
unbind a
bind a select-pane -t :.+
bind-key v split-window -h
bind-key s split-window -v
bind-key J resize-pane -D 10
bind-key K resize-pane -U 10
bind-key H resize-pane -L 10
bind-key L resize-pane -R 10
bind-key M-j resize-pane -D 2
bind-key M-k resize-pane -U 2
bind-key M-h resize-pane -L 2
bind-key M-l resize-pane -R 2
# Vim style pane selection
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind -n M-Down select-pane -D
# find asci keycodes with "sudo showkey -a" - works only tmux >1.7
# us-keyboard like [ ]
bind-key -r 0xc3 display 'c3 prefix binding hack'
bind-key -r 0xb6 copy-mode # ö
bind-key -r 0xa3 paste-buffer # ä
# us { }
bind-key -r 0x96 swap-pane -U # Ö - swap pane to prev position
bind-key -r 0x84 swap-pane -D # Ä - to next pos
#}}}
</code></pre> | 46,205,850 | 6 | 0 | null | 2015-09-03 11:54:01.537 UTC | 9 | 2020-12-11 15:44:43.883 UTC | 2020-12-11 15:44:43.883 UTC | null | 3,802,813 | null | 2,111,994 | null | 1 | 27 | scroll|ssh|copy|mouse|tmux | 5,457 | <p>As of tmux 2.5 you should use</p>
<pre><code>unbind -T copy-mode-vi MouseDragEnd1Pane
</code></pre> |
24,527,485 | Route traffic to a docker container based on subdomain | <p>I have wildcard dns pointed to my server e.g. *.domain.com</p>
<p>I'd like to route each subdomain to it's own docker container.
So that box1.domain.com goes to the appropriate docker container.
This should work for any traffic primarily HTTP and SSH.</p>
<p>Or perhaps the port can be part of the subdomain e.g. 80.box1.domain.com.
I will have lots of docker containers so the solution should be dynamic not hard-coded for every container.</p> | 31,023,661 | 4 | 0 | null | 2014-07-02 09:28:13.92 UTC | 13 | 2016-12-01 12:46:41.873 UTC | null | null | null | null | 329,624 | null | 1 | 32 | docker|wildcard-subdomain | 33,830 | <p>I went with <a href="https://github.com/ehazlett/interlock" rel="noreferrer">interlock</a> to route http traffic using the <a href="https://github.com/ehazlett/interlock/tree/master/plugins/nginx" rel="noreferrer">nginx plugin</a>.
I settled on using a random port for each SSH connection as I couldn't get it work using the subdomain alone.</p> |
35,764,510 | How to Implement dynamic routing in routes.js for generated menu items in sidebar in universal react redux boilerplate by erikras | <p>I am currently working on a CMS based project.</p>
<p>For which i am using the universal react redux boilerplate by erikras</p>
<p>I really need suggestions on handling dynamic routing</p>
<p>Lets take a simple scenario form the boilerplate...</p>
<p>In <strong>routes.js</strong></p>
<pre><code><Route path="about" component={About}/>
<Route path="login" component={Login}/>
<Route path="survey" component={Survey}/>
<Route path="widgets" component={Widgets}/>
</code></pre>
<p><strong>data.js</strong></p>
<pre><code>export const data = [
{id: 1, property: 'Dashboard', link: '/'},
{id: 2, property: 'Login', link: '/login'},
{id: 3, property: 'About Us', link: '/About'},
];
</code></pre>
<p>now, let say on the basis of user role, the properties in json data will change</p>
<p><em>let say new property: is</em></p>
<pre><code>{id: 4, property: 'test page', link: '/test'}
</code></pre>
<p>When react will render the components, how it would know the route link .. as it is not defined in the routes.js</p>
<p>I am not getting the right way to implement it</p>
<p>We need a sidebar made of specific menu content as per the user role .</p>
<p>Let say we are building a reservation system , there can be different user roles like admin, maintenance mode, assistant role
.</p>
<p>So different role will have different properties, accordingly we need to generate the menu on the basis it, as the properties will definitely differ as per user role.</p>
<p>Thanks!!</p> | 35,790,812 | 2 | 0 | null | 2016-03-03 06:11:46.057 UTC | 11 | 2017-04-25 12:55:56.223 UTC | 2016-03-03 06:53:41.503 UTC | null | 6,011,540 | null | 6,011,540 | null | 1 | 26 | reactjs|menuitem|react-router | 26,481 | <p>It is not clear from your example which component should be rendered for <code>/test</code> url? I suppose it is value of <code>property</code> key, right?</p>
<h3>First option</h3>
<p>You can do is something like this:</p>
<pre><code><Route path="/:page" component={Page}/>
</code></pre>
<p>It will allow you to render <code>Page</code> component for each url, that starts from <code>/</code> and this component will have page url inside <code>this.props.routeParams.page</code>. It allows you to find needed component inside <code>Page#render</code>:</p>
<pre><code>render() {
const url = this.props.routeParams.page;
const PageComponent = data.find(page => page.link === url).property;
render <PageComponent />;
}
</code></pre>
<h3>Second option</h3>
<p>You can generate Routes dynamically, but I'm not sure if it works (you can check it). You just should replace this part:</p>
<pre><code><Route path="about" component={About}/>
<Route path="login" component={Login}/>
<Route path="survey" component={Survey}/>
<Route path="widgets" component={Widgets}/>
</code></pre>
<p>with </p>
<pre><code> data.map(page => <Route path={page.link} component={page.property} key={page.id}/>)
</code></pre> |
24,942,037 | Mongoose schema optional fields | <p>I have a user schema with mongoose in nodejs like this</p>
<pre><code>userschema = mongoose.Schema({
org: String,
username: String,
fullname: String,
password: String,
email: String
});
</code></pre>
<p>Except sometimes I need to add some more fields.</p>
<p><strong>The main question is: Can I have optional fields in a monogoose schema?</strong></p> | 24,942,596 | 2 | 0 | null | 2014-07-24 19:11:13.16 UTC | 10 | 2017-11-26 17:38:01.357 UTC | 2017-08-17 06:37:12.573 UTC | null | 2,327,544 | null | 3,802,339 | null | 1 | 51 | node.js|mongodb|mongoose|schema | 35,918 | <p>All fields in a mongoose schema are optional by default (besides <code>_id</code>, of course).</p>
<p>A field is only required if you add <a href="http://mongoosejs.com/docs/api.html#schematype_SchemaType-required"><code>required: true</code></a> to its definition.</p>
<p>So define your schema as the superset of all possible fields, adding <code>required: true</code> to the fields that are required.</p> |
25,340,606 | What does the Hibernate proxy object contain? | <p>All I could gather from Google is that:</p>
<ul>
<li><p>Hibernate uses a proxy object to implement lazy loading.
When we request to load the Object from the database, and the fetched Object has a reference to another concrete object, Hibernate returns a proxy instead of the concrete associated object.</p></li>
<li><p>Hibernate creates a proxy object using bytecode instrumentation (provided by javassist). Hibernate creates a subclass of our entity class at runtime using the code generation library and replaces the actual object with the newly created proxy.</p></li>
</ul>
<p>So, what exactly does the Proxy object contain? </p>
<p>Does it contain a skeleton object reference object with only the id field set? Others field will be set when we call the get method? </p>
<p>Does the Proxy object contain the JDBC statement to fetch all data required to fully populate the referenced object.</p>
<p>Is there something else I might be missing?</p>
<p>I am not asking for spoon feeding but if you can provide any link with information that would be great.</p>
<p>Any correction to above description will also be welcomed.</p>
<p>Example.</p>
<pre><code>class Address {
String city;
String country;
}
class Person{
int id;
String name;
Address address;
}
</code></pre>
<p>When we try to load the Person object, Hibernate will subclass Person class like:</p>
<pre><code>class ProxyPerson extends Person {
int id;
String name;
Address proxyCGLIBObject;
}
</code></pre>
<p>and return a ProxyPerson object. Object of ProxyPerson will have a value for id and name but proxy for Address.</p>
<p>Am I correct?</p>
<p>What can I expect from adding a toString() method on the proxy object?</p> | 25,340,780 | 1 | 0 | null | 2014-08-16 13:24:42.22 UTC | 19 | 2021-01-08 15:33:58.513 UTC | 2016-08-31 07:51:16.34 UTC | null | 1,063,716 | null | 3,181,322 | null | 1 | 54 | java|hibernate|orm|proxy|hibernate-mapping | 32,864 | <p>The Hibernate Proxy is used to substitute an actual entity POJO (Plain Old Java Object).</p>
<p>The Proxy class is generated at runtime and it extends the original entity class.</p>
<p>Hibernate uses Proxy objects for entities is for to allow [lazy loading][1].</p>
<p>When accessing basic properties on the Proxy, it simply delegates the call to the original entity.</p>
<p>Every <code>List</code>, <code>Set</code>, <code>Map</code> type in the entity class is substituted by a <code>PersistentList</code>, <code>PersistentSet</code>, <code>PersistentMap</code>. These classes are responsible for intercepting a call to an uninitialized collection.</p>
<p>The Proxy doesn't issue any SQL statement. It simply triggers an <a href="https://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/event/InitializeCollectionEvent.html" rel="noreferrer">InitializeCollectionEvent</a>, which is handled by the associated listener, that knows which initialization query to issue (depends on the configured fetch plan).</p> |
34,849,873 | What are the semantics of different RxJS subjects? | <p>Documentation for the topic is sparse and it's hard to discover an "entry-point" there. </p> | 34,860,777 | 1 | 0 | null | 2016-01-18 08:09:30.913 UTC | 11 | 2018-02-26 16:24:09.533 UTC | 2018-02-26 16:24:09.533 UTC | null | 3,743,222 | null | 2,546,882 | null | 1 | 23 | javascript|rxjs|rxjs5 | 15,844 | <p>Semantics differ according to the type of subjects. I will divide them in two kinds : vanilla (<code>Rx.Subject</code>), and special-purpose subjects (the other three). The special-purpose subjects share part of the semantics of the vanilla subject with a few caveats due to their specialization (for instance, completion/reconnection behaviour).</p>
<p><strong>Vanilla Rx.Subject semantics</strong></p>
<ol>
<li><p>Key features </p>
<ul>
<li>subjects implement the observer, observable interface (and the disposable interface as they have a <code>dispose</code> handler on their prototype). That means, among other things, they have:
<ul>
<li>observer interface : <code>onNext</code>, <code>onError</code>, <code>onComplete</code> method</li>
<li>observable interface : <code>subscribe</code> method</li>
</ul></li>
<li>you can cast a subject to an observer or to an observable, hiding the implementation of the extra interfaces (cf. <a href="http://xgrommx.github.io/rx-book/content/observer/observer_instance_methods/asobserver.html" rel="noreferrer"><code>.asObserver()</code></a>, and <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/asobservable.md" rel="noreferrer"><code>.asObservable()</code></a>) if need be</li>
<li>the subject being an observable, you can subscribe several observers to it. That observable will then broadcast its data to all its observers. Internally the subject maintains an array of observers.</li>
<li>the subject being an observer, you can subscribe it to any observable</li>
<li>the observer and the observable which compose the subject being two distinct entities, you can use them independently of the other if that's your use case.</li>
<li><code>dispose</code>ing a subject will <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/subject.md#rxsubjectprototypedispose" rel="noreferrer">unsubscribe all observers and release resources.</a></li>
<li>Subjects do not take a scheduler but rather assume that <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md" rel="noreferrer">all serialization and grammatical correctness are handled by the caller of the subject.</a> </li>
<li>The default behaviour of subjects is to emit <strong>synchronously</strong> their values to the observers, <strong>starting with the first subscribed observer to the last</strong>. In most cases, order will not matter, in others it will.</li>
</ul></li>
</ol>
<p>I quote a key aspect of <a href="https://github.com/Reactive-Extensions/RxJS/tree/master/doc/designguidelines#31-the-rxjs-grammar" rel="noreferrer">Rxjs contract and grammar</a> :</p>
<blockquote>
<p>This grammar allows observable sequences to send any amount (0 or more) of onNext messages to the subscribed observer instance, optionally followed by a single success (onCompleted) or failure (onError) message.</p>
</blockquote>
<ul>
<li><p>a vanilla subject (created with <code>new Rx.Subject()</code>) implements that grammar : when <code>onCompleted</code> has been called once, all subsequent calls to <code>onNext</code> are ignored. Second call of <code>onCompleted</code> on the same observer is also ignored. If an observer subscribes to the observable side of the subject, its <code>onComplete</code> callback will immediately be called (<a href="http://jsfiddle.net/cLf6Lqsn/1/" rel="noreferrer">http://jsfiddle.net/cLf6Lqsn/1/</a>).</p>
<ol start="2">
<li><p>Creation</p>
<ul>
<li><code>new Rx.Subject()</code></li>
</ul></li>
</ol>
<p>Returns a subject which connects its observer to its observable (<a href="http://jsfiddle.net/ehffnbky/1/" rel="noreferrer">jsfiddle</a>). This example is taken from the official <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md" rel="noreferrer">documentation</a> and portrays how to use subjects as proxies. The subject is subscribed to a source (observer side), and is also listened on by observers (observable side). Any call to <code>onNext</code> (observer side) results in the observable side calling <code>onNext</code> with the same value for each of its observers.</p>
<ul>
<li><code>Rx.Subject.create(observer, observable)</code></li>
</ul>
<p>Creates a subject from the specified observer and observable. Those two are not necessarily connected. A good example can be seen in the implementation of <a href="https://github.com/Reactive-Extensions/RxJS-DOM/blob/master/src/dom/websocket.js" rel="noreferrer"><code>Rx.Dom.fromWebSocket</code></a> which returns a subject used to send and receive data from a socket. The observer side of the subject sends data to the socket. The observable side is used to listen on incoming data from the socket. Also, a subject created this way does NOT have a <code>dispose</code> method.</p></li>
</ul>
<p><strong>Specialized Rx.Subject semantics</strong></p>
<ul>
<li>This <a href="http://reactivex.io/documentation/subject.html" rel="noreferrer"><code>reactivex.io</code> documentation</a> covers pretty well most of the semantics of the specialized subjects.</li>
<li>The other interesting points to mention concern behavior past completion.</li>
<li>Sample code illustrating the behaviour are here for <a href="http://jsfiddle.net/8k4rzf65/2/" rel="noreferrer">async</a>, <a href="http://jsfiddle.net/kLqv43ad/1/" rel="noreferrer">behavior</a>, <a href="http://jsfiddle.net/huaqvtma/1/" rel="noreferrer">replay</a></li>
</ul>
<p>Hopefully I did not get too much wrong. I'll be happy to be corrected. Last note, this should be valid for RxJS v4.</p>
<p>For a detailed explanation of the behaviour of cold/hot observables, one can refer to : <a href="https://stackoverflow.com/questions/32190445/hot-and-cold-observables-are-there-hot-and-cold-operators/34669444#34669444">Hot and Cold observables : are there 'hot' and 'cold' operators?</a></p> |
47,645,634 | bootstrap 4 making dropdown scrollable | <p>I have a problem with my drop down menu on smaller devices. i cannot make it scroll able when i tried the solution here (that is <strong><em>overflow:auto/ overflow-y:scroll</em></strong>) it's not working even if i use <strong><em>!important</em></strong>. What i'm able to scroll was my main page even if the drop down is open.
<a href="https://i.stack.imgur.com/5Xxf3.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/5Xxf3.jpg" alt="enter image description here"></a></p>
<pre><code><nav class="navbar navbar-toggleable-sm ">
<button class="navbar-toggler navbar-toggler-right main-navbar-toggler" type="button" data-toggle="collapse" data-target="#main-nav-collapse" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
<span class="fa fa-bars"></span>
</button>
<a class="navbar-brand animation" data-animation ="fadeInLeft" href="#"><img src="/093017/img/logo-tmi.png" alt="logo"/></a>
<div class="collapse navbar-collapse" id = "main-nav-collapse" >
<ul class="nav navbar-nav navbar-main mr-auto mt-2 mt-md-0 animation" data-animation = "fadeInRight">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Vehicles</a>
<div class="dropdown-menu default-menu main-menu sm-main-menu animation" data-animation = "fadeIn">
<!-- Nav tabs -->
<div class="sm-main-nav" >
<a class="dropdown-item" href="#">Cars</a><hr>
<a class="dropdown-item" href="#">Vans & Pickup</a><hr>
<a class="dropdown-item" href="#">SUVs & Crossover</a><hr>
<a class="dropdown-item" href="#">MPVs</a><hr>
<a class="dropdown-item" href="#">Hybrid</a><hr>
<a class="dropdown-item" href="#">Performance</a>
</div>
</div>
</li>
<li class="nav-item">
<a class="nav-link " href="#">Owners</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Shop</a>
</li>
<li class="nav-item">
<a class="nav-link " href="#">Promotions</a>
</li>
</ul>
</div>
</code></pre> | 47,646,286 | 4 | 1 | null | 2017-12-05 03:31:46.607 UTC | null | 2021-11-24 15:38:46.273 UTC | 2019-04-09 04:37:42.307 UTC | null | 6,108,882 | null | 6,545,383 | null | 1 | 15 | html|twitter-bootstrap|css | 39,052 | <p>just you can use @media in your css</p>
<pre class="lang-css prettyprint-override"><code>@media (max-width: 500px) {
.dropdown-menu{
height:200px;
overflow-y:auto;
}
}
</code></pre> |
54,954,544 | How do I show the "up" and "down" arrow keyboard key in GitHub markdown? | <p>How do I show the "up" and "down" arrow keyboard keys (←, ↑, → and ↓) in GitHub markdown? So far I am able to show <kbd>up</kbd> and <kbd>down</kbd>. But how do I show the arrow symbol instead the text "up" and "down"?</p> | 54,954,721 | 5 | 0 | null | 2019-03-02 02:02:08.197 UTC | 17 | 2021-05-20 08:17:02.757 UTC | 2019-03-02 02:57:14.733 UTC | null | 117,259 | null | 5,722,359 | null | 1 | 43 | github|github-flavored-markdown | 41,964 | <p>As mentioned in "<a href="https://stackoverflow.com/a/36616878/6309">Unicode in Github markdown</a>", you need to use the decimal value of the characters you want.</p>
<p>In your case, the <a href="https://unicode-table.com/en/sets/arrows-symbols/" rel="noreferrer">arrow symbols</a>, as <a href="https://www.toptal.com/designers/htmlarrows/arrows/" rel="noreferrer">shown here</a>:</p>
<ul>
<li><a href="http://www.fileformat.info/info/unicode/char/2190/index.htm" rel="noreferrer">left arrow</a>: ← <code>&#8592;</code></li>
<li><a href="http://www.fileformat.info/info/unicode/char/2191/index.htm" rel="noreferrer">upward arrow</a>: ↑ <code>&#8593;</code></li>
<li><a href="http://www.fileformat.info/info/unicode/char/2191/index.htm" rel="noreferrer">right arrow</a>: → <code>&#8594;</code></li>
<li><a href="http://www.fileformat.info/info/unicode/char/2191/index.htm" rel="noreferrer">downward arrow</a>: ↓ <code>&#8595;</code></li>
</ul> |
42,032,634 | What does the status "CG" mean in SLURM? | <p>On a SLURM cluster one can use <code>squeue</code> to get information about jobs on the system.</p>
<p>I know that "R" means <strong>r</strong>unning; and "PD" meaning <strong>p</strong>en<strong>d</strong>ing, but what is "CG"?</p>
<p>I understand it to be "canceling" or "failing" from experience, but does "CG" apply when a job successfully <strong>c</strong>loses? What is the <strong>G</strong>?</p> | 42,033,056 | 2 | 0 | null | 2017-02-03 20:37:13.547 UTC | 6 | 2017-05-01 17:35:08.183 UTC | 2017-02-03 21:14:16.457 UTC | null | 1,072,229 | null | 1,493,707 | null | 1 | 34 | jobs|slurm | 36,598 | <p>"CG" stands for "<strong>c</strong>ompletin<strong>g</strong>" and it happens to a job that cannot be terminated, probably because of an I/O operation.</p>
<p>More detailed info in the <a href="https://slurm.schedmd.com/troubleshoot.html#completing" rel="noreferrer">Slurm Troubleshooting Guide</a></p> |
39,313,536 | Missing routes.php File in New Laravel Project | <p>I downloaded Composer, installed Laravel, and started my first Laravel project to begin learning Laravel using the lessons on laracast (great lessons). Lesson two covers routes. My new project does not have a routes.php file.</p>
<p>I deleted composer and started again. Same thing. Tried two different computers. Same thing. I was using NetBeans so I tried using PHP Storm. Same thing. I tried making my own routes.php file but it doesn't seem to work right because I know nothing about Laravel at this point. I tried creating and saving the project in htdocs, and then PHPStorm project folder, again - no routes.php file.</p>
<p>Composer is saved here- C:\Users\myName\AppData\Roaming\Composer\vendor\bin. I used composer global require "laravel/installer" in command prompt to install laravel. Any ideas?</p> | 39,313,633 | 7 | 0 | null | 2016-09-04 04:26:37.553 UTC | 19 | 2021-12-18 11:00:42.983 UTC | 2018-02-22 04:43:58.413 UTC | null | 4,908,847 | null | 6,389,167 | null | 1 | 57 | laravel|laravel-5.3 | 58,093 | <h1>The lastest version of Laravel doesn't have a routes.php file.</h1>
<p>This 'routes.php' file was located in \app\Http in the older versions.</p>
<p>In the newer version, Laravel 5.3, we have a folder named 'routes', where we can find the following files:</p>
<ul>
<li>api.php</li>
<li>console.php</li>
<li>web.php</li>
</ul>
<p>For this new version, the routes for your controllers, you can put inside web.php file</p>
<p>See the documentation about routing here</p>
<p><a href="https://laravel.com/docs/5.3/routing#basic-routing" rel="noreferrer">https://laravel.com/docs/5.3/routing#basic-routing</a></p>
<p>The video lesson you are watching may be outdated.</p> |
3,040,645 | Populating JavaScript Array from JSP List | <p>Ok so perhaps someone can help me with a problem I'm trying to solve. Essentially I have a JSP page which gets a list of Country objects (from the method referenceData() from a Spring Portlet SimpleFormController, not entirely relevant but just mentioning in case it is). Each Country object has a Set of province objects and each province and country have a name field:</p>
<pre><code>public class Country {
private String name;
private Set<Province> provinces;
//Getters and setters
}
public class Province {
private String name;
//Getters and setters
}
</code></pre>
<p>Now I have two drop down menus in my JSP for countries and provinces and I want to filter the provinces by country. I've been following this <a href="http://bonrouge.com/~chain_select_js" rel="noreferrer">tutorial/guide</a> to make a chain select in JavaScript.</p>
<p>Now I need a dynamic way to create the JavaScript array from my content. And before anyone mentions AJAX this is out of the question since our project uses portlets and we'd like to stay away from using frameworks like DWR or creating a servlet. Here is the JavaScript/JSP I have so far but it is not populating the Array with anything:</p>
<pre><code>var countries = new Array();
<c:forEach items="${countryList}" var="country" varStatus="status">
countries[status.index] = new Array();
countries[status.index]['country'] = ${country.name};
countries[status.index]['provinces'] =
[
<c:forEach items="${country.provinces}" var="province" varStatus="provinceStatus">
'${province.name}'
<c:if test="${!provinceStatus.last}">
,
</c:if>
</c:forEach>
];
</c:forEach>
</code></pre>
<p>Does anyone know how to create an JavaScript array in JSP in the case above or what the 'best-practice' would be considered in this case? Thanks in advance!</p> | 3,040,719 | 4 | 0 | null | 2010-06-14 20:25:33.103 UTC | 4 | 2022-05-28 09:59:53.92 UTC | 2010-06-15 00:25:48.513 UTC | null | 157,882 | null | 91,866 | null | 1 | 14 | javascript|arrays|jsp|jstl | 46,668 | <pre><code>var countries = new Array();
<c:forEach items="${countryList}" var="country" varStatus="status">
countryDetails = new Object();
countryDetails.country = ${country.name};
var provinces = new Array();
<c:forEach items="${country.provinces}" var="province" varStatus="provinceStatus">
provinces.push(${province.name});
</c:forEach>
countryDetails.provinces = provinces;
countries.push(countryDetails);
</c:forEach>
</code></pre>
<p>now what you have is something like this in javascript</p>
<pre><code>var countries = [
{country:"USA",
provinces: [
"Ohio",
"New York",
"California"
]},
{country:"Canada",
provinces: [
"Ontario",
"Northern Territory",
"Sascetchewan"
]},
]
</code></pre>
<p>The other option would be to make your output look like the javascript I posted.</p>
<pre><code>var countries = [
<c:forEach items="${countryList}" var="country" varStatus="status">
{country: '${country.name}',
provinces : [
<c:forEach items="${country.provinces}" var="province" varStatus="provinceStatus">
'${province.name}'
<c:if test="${!provinceStatus.last}">
,
</c:if>
</c:forEach>
]}
<c:if test="${!status.last}">
,
</c:if>
</c:forEach>
];
</code></pre> |
2,530,880 | Why use ASP.NET MVC 2 for REST services? Why not WCF? | <p>So I see that MVC 2 now supports <code>[HttpPut]</code> and <code>[HttpDelete]</code> as well as <code>[HttpGet]</code> and <code>[HttpPost]</code>, making it possible to do a full RESTful Web service using it.</p>
<p>I've been using the REST toolkit for WCF for a while and find it fairly powerful, but I'd be interested to find out what (if any) advantages there are using the MVC 2 approach. </p>
<p>Links, war stories, or even pure hear-say are welcome.</p> | 2,530,964 | 4 | 1 | null | 2010-03-27 20:48:39.92 UTC | 16 | 2012-12-21 13:26:55.487 UTC | null | null | null | null | 3,546 | null | 1 | 19 | wcf|rest|asp.net-mvc-2 | 7,496 | <p>I'm pretty sure ASP.NET MVC has supported all the HTTP verbs since the beginning. At least the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.httpverbs.aspx" rel="nofollow noreferrer">HttpVerb Enumeration</a> has had them from the beginning. The only thing that's new in V2 is that they are attributes.</p>
<pre><code>// V1
[AcceptVerbs( HttpVerbs.Delete )]
// V2
[HttpDelete]
</code></pre>
<p>Six of one, half a dozen of the other. As to whether you want to expose functionality through WCF or ASP.NET MVC, it would come down to how you think of your application.</p>
<ul>
<li><p>If you think of it as a thick client app that just happens to be written in JavaScript and calls out to restful services for <strong>data</strong> (then formats it client side) then WCF would feel like a more correct solution (even though you could do it using either). </p></li>
<li><p>However if you think of your application as a server app that returns <strong>content</strong> in some form or another for consumption, then using a RESTful API for your actions would make more sense. Your actions would return fully formatted content that would be displayed in the browser without a need for further processing. You <em>could</em> return formatted content (HTML or otherwise) from a web service, but that would somehow feel wrong.</p></li>
</ul>
<p>At least that kind of distinction makes sense in my head =). You may also be interested in Phil Haack's post on <a href="http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx" rel="nofollow noreferrer">How a Method Becomes an Action</a>.</p>
<hr>
<p>There's now another option, <a href="http://www.asp.net/web-api" rel="nofollow noreferrer">Web API</a>. <a href="http://weblogs.asp.net/scottgu/archive/2012/02/23/asp-net-web-api-part-1.aspx" rel="nofollow noreferrer">ScottGu</a> has a brief introduction in his blog and there's an interesting blog post discussing creating APIs using the Web API vs controllers <a href="http://encosia.com/asp-net-web-api-vs-asp-net-mvc-apis/" rel="nofollow noreferrer">here</a>. </p> |
2,788,326 | MySQL 'user_id' in where clause is ambiguous problem | <p>How can I correct the problem I keep getting from the code below which states <code>'user_id' in where clause is ambiguous</code>. Thanks for the help in advance.</p>
<p>Here is the mysql table.</p>
<pre><code>SELECT user.*, user_info.*
FROM user
INNER JOIN user_info ON user.user_id = user_info.user_id
WHERE user_id=1
</code></pre> | 2,788,333 | 4 | 0 | null | 2010-05-07 11:59:32.847 UTC | 0 | 2022-01-16 08:21:13.76 UTC | 2022-01-16 08:20:23.4 UTC | null | 285,587 | null | 335,408 | null | 1 | 19 | mysql|mysql-error-1052 | 78,672 | <p>You simply need to specify which <code>user_id</code> to use, since both the <code>user_info</code> and <code>user</code> table have a field called <code>user_id</code>:</p>
<pre><code>... WHERE user.user_id=1
</code></pre>
<p>SQL wouldn't tolerate this ambiguity, since for what it knows, both fields can represent totally different data.</p> |
29,089,925 | Pass variables to base layout from extending pug/jade template | <p>I would like to set a class on the body tag by declaring a variable in a template that extends a base layout.</p>
<p>When I try, the <code>body_class</code> variable is <code>undefined</code> in the layout.</p>
<p>It appears the layout is executed before the extending template, or they are executed in different scopes or something.</p>
<p>Is there another way? Would a mixin work here?</p>
<p><strong>_layout.jade:</strong></p>
<pre><code>doctype html
html(lang="en-au")
head
meta(charset="utf-8")
block css
body(class=(body_class || "it-did-not-work"))
block header
block content
block footer
</code></pre>
<p><strong>home.jade:</strong></p>
<pre><code>var body_class = 'i-am-the-home-page'
extends _layout
block header
h1 home
</code></pre> | 29,089,926 | 1 | 1 | null | 2015-03-17 01:35:23.823 UTC | 4 | 2017-03-01 13:04:15.273 UTC | 2017-02-16 10:07:07.357 UTC | null | 1,053,103 | null | 1,053,103 | null | 1 | 32 | javascript|node.js|pug | 11,529 | <p>Ah ha! Figured it out.</p>
<p>Create a block at the top of the base layout and add your variables in there.</p>
<p><strong>_layout.jade:</strong></p>
<pre><code>block variables
doctype html
html(lang="en-au")
head
meta(charset="utf-8")
block css
body(class=(body_class || "it-did-not-work"))
block header
block content
block footer
</code></pre>
<p><strong>home.jade:</strong></p>
<pre><code>extends _layout
block variables
- var body_class = 'i-am-the-home-page'
block header
h1 home
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.