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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32,342,392 | String Interpolation vs String.Format | <p>Is there a noticable performance difference between using string interpolation:</p>
<pre><code>myString += $"{x:x2}";
</code></pre>
<p>vs String.Format()?</p>
<pre><code>myString += String.Format("{0:x2}", x);
</code></pre>
<p>I am only asking because Resharper is prompting the fix, and I have been fooled before.</p> | 63,904,747 | 7 | 10 | null | 2015-09-01 23:26:11.463 UTC | 25 | 2022-01-15 21:23:33.54 UTC | 2019-02-21 20:41:06.62 UTC | null | 3,214,889 | null | 3,214,889 | null | 1 | 155 | c#|string|performance|resharper|string-interpolation | 52,222 | <p>The answer is both yes and no. <code>ReSharper</code> <em>is</em> fooling you by not showing a <em>third</em> variant, which is also the most performant. The two listed variants produce equal IL code, but the following will indeed give a boost:</p>
<pre class="lang-cs prettyprint-override"><code>myString += $"{x.ToString("x2")}";
</code></pre>
<h2>Full test code</h2>
<pre class="lang-cs prettyprint-override"><code>using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Diagnostics.Windows;
using BenchmarkDotNet.Running;
namespace StringFormatPerformanceTest
{
[Config(typeof(Config))]
public class StringTests
{
private class Config : ManualConfig
{
public Config() => AddDiagnoser(MemoryDiagnoser.Default, new EtwProfiler());
}
[Params(42, 1337)]
public int Data;
[Benchmark] public string Format() => string.Format("{0:x2}", Data);
[Benchmark] public string Interpolate() => $"{Data:x2}";
[Benchmark] public string InterpolateExplicit() => $"{Data.ToString("x2")}";
}
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<StringTests>();
}
}
}
</code></pre>
<h2>Test results</h2>
<pre><code>| Method | Data | Mean | Gen 0 | Allocated |
|-------------------- |----- |----------:|-------:|----------:|
| Format | 42 | 118.03 ns | 0.0178 | 56 B |
| Interpolate | 42 | 118.36 ns | 0.0178 | 56 B |
| InterpolateExplicit | 42 | 37.01 ns | 0.0102 | 32 B |
| Format | 1337 | 117.46 ns | 0.0176 | 56 B |
| Interpolate | 1337 | 113.86 ns | 0.0178 | 56 B |
| InterpolateExplicit | 1337 | 38.73 ns | 0.0102 | 32 B |
</code></pre>
<p>The <code>InterpolateExplicit()</code> method is faster since we now explicitly tell the compiler to use a <code>string</code>. No need to <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/boxing-and-unboxing" rel="noreferrer">box</a> the <em>object</em> to be formatted. Boxing is indeed very costly. Also, note that we reduced the allocations a bit.</p> |
13,532,947 | References for depth of field implementation in a raytracer? | <p>I have a basic raytracer and I want to implement depth of field. Can you please
recommend me resources I can use, books and code?</p>
<p>Thanks</p> | 13,686,064 | 1 | 0 | null | 2012-11-23 16:41:49.247 UTC | 10 | 2012-12-03 15:11:52.463 UTC | null | null | null | null | 1,796,942 | null | 1 | 5 | game-physics|raytracing | 3,627 | <p>I figured it out from the little bit of information on this page: <a href="http://cg.skeelogy.com/depth-of-field-using-raytracing/" rel="noreferrer">http://cg.skeelogy.com/depth-of-field-using-raytracing/</a>, specifically the diagrams near the bottom. I think I did it a little bit differently then how it's shown, but the concept is pretty simple.</p>
<p>I can explain the general idea of what is going on and how to implement it (I'll try to be concise). Light reflects off of any given point in all directions (generally speaking), so it's not actually a single ray going between the render-pt and your eye, it's a cone of light leaving the render-pt and expanding towards the eye. The lens of your eye/camera will tend to bend these light rays such that the cone stops expanding and starts contracting again. For things to be perfectly in focus, the cone should contract to a point on your retina/frame, but this only works at one specific distance from the lens: a distance indicated by the "focal plane" in the referenced page (though I think it should really be a sphere centered on the eye, not a plane).</p>
<p>For anything in front of the focal plane, the cone of light will be bent more: it will focus to a point in front of the retina/frame, and then start expanding again so by the time it reaches the frame, it is no longer a point, but a circle. Similarly, for points behind the focal plane, the cone will be bent less and will not yet have converged to a point when it reaches the frame. In both cases, the effect is that a single point is the scene ends up smeared out across multiple pixels.</p>
<p>For implementation, you can kind of turn this idea on it's head: in stead of rendering every point in the scene to several pixels, you can render several nearby points to a single pixel, which is of course what would really happen since the "smeared out" light circles from neighboring points will end up overlapping and therefore each contribute to a pixel.</p>
<p><strong>So here's how I implemented it:</strong></p>
<p>First, define an <em>aperture</em>: a planar area center on your eye and parallel to the retina/frame. The bigger the aperture, the more DOF effect will be evident. Aperture's are typically just circles, in which case it is easily defined by its radius. Other shapes can lead to different lighting effects.</p>
<p>Also define a "focal distance". I don't think that's actually the correct term for it, but it's the distance from the eye at which things will be perfectly in focus.</p>
<p>To render each pixel:</p>
<ol>
<li>Start by casting a ray like normal from the eye through the pixel out into the scene. Instead of intersecting it with objects in the scene, though, you just want to find the point on the ray for which the distance from the eye is equal to the selected focal distance. Call this point the focal point for the pixel.</li>
<li>Now select a random starting point on the aperture. For a circular aperture, it's pretty easy, you can select a random polar angle and a random radius (no greater than the radius of the aperture). You want a uniform distribution over the entire aperture, don't try to bias it towards the center or anything.</li>
<li>Cast a ray from your selected point on the aperture through the <em>focal point</em>. Note that it will not necessarily pass through the same pixel, that's ok.</li>
<li>Render this ray the way your normally would (e.g., path tracing, or just finding the nearest point of intersection, etc.).</li>
<li>Repeat steps 2, 3, and 4 some number of times, using different a random starting point on the aperture each time, but always casting it through the focal point. Sum up the rendered color values from all of the rays and use that as the value for this pixel (as usual, divide by a constant attenuation factor if necessary).</li>
</ol>
<p>The more rays you use for each pixel, the better the quality will be, of course. I've been using about 150 rays per pixel to get decent but not great quality. You can see the effect with quite a bite fewer (say like 50 or 60 rays), but fewer rays will tend to produce a graininess in the image, especially for things that are very out of focus. The number of rays you need also depends on the aperture size: a smaller aperture won't require as many rays, but you won't get as much blurring effect.</p>
<p>Obviously, you're greatly increasing your work load by doing this, essentially multiplying it by the number of rays per pixel, so if you have any optimizations left to make in your raytracer, now would be a good time to do it. The good news if you happen to have multiple processors available, is that this is embarrassingly parallel once you found the focal point for a pixel.</p>
<p><strong>A little more explanation</strong></p>
<p>The image below should give you an idea of what's happening, and why it works out to be equivalent to what really occurs in an eye or camera. It shows two pixels being rendered, one pixel illustrated in red, the other in blue. The dashed lines extending from the eye through each pixel to the focal "plane" are the rays you cast at the beginning to determine the focal point for the pixel. The semi-transparent cones indicate the complete set of rays which could possibly be selected at random to render each pixel (red cone for pixel-1, blue cone for pixel 2). Notice that since all rays pass through the focal point, each cone converges to a point exactly at the focal point.</p>
<p>The overlapping areas of the cones represent points in the scene which could end up being rendered to both pixel-1 and pixel-2: in other words, smeared out. Since every cone is a point on the focal "plane", there is no overlap between cones here, so points at this distance are only rendered to a single pixel: they are perfectly in focus. Meanwhile, the further you get away from the focal "plane" (either forwards or backwards), the more the cones spread out, so the more cones will overlap at any given point. Therefore, points that are very close or very far away will tend to be rendered to a large number of different pixels, so they will be very out of focus.</p>
<p><img src="https://i.stack.imgur.com/qLdsO.png" alt="Model of DOF implementation for raytracing."></p> |
37,908,795 | How do you block users on Firebase? | <p>I'm using Firebase for my app and was wondering how to block certain users. I see on the Auth tab of the console, there are "delete" and "disable" options. What do those do? I haven't been able to find documentation on that. Will one of those allow me to block a user?</p>
<p>What I mean by blocking a user is for the <code>".read": "auth != null"</code> rule to prevent him from accessing data on the database</p> | 37,909,567 | 1 | 3 | null | 2016-06-19 15:22:03.353 UTC | 9 | 2021-03-17 23:10:54.77 UTC | 2016-06-19 18:46:53.903 UTC | null | 1,736,127 | null | 5,666,216 | null | 1 | 5 | firebase|firebase-security|firebase-authentication | 11,925 | <p>The <strong>disable</strong> feature consist in preventing that user to authenticate. So if he tries to authenticate he will fail with error code <code>INVALID_CREDENTIALS</code> and he won't have access to the data that has the <code>".read": "auth != null"</code> rule. It works like he is deleted but the admin still have the power to reactivate the user account.</p>
<p>If you want to build a list of "blocked users" that will be <strong>able to authenticate but will have restricted access</strong>, you can store the blocked ids in a node on your firebase database like <code>/databaseRoot/blockedUsers</code> and then work with the <code>security and rules</code>.</p>
<pre><code>".read": "auth != null && !root.child('blockedUsers').hasChild(auth.uid)"
</code></pre>
<hr>
<p><strong>blockedUsers</strong> could look like the tree bellow but you could also add some other info under the userId such as the date this user was blocked.</p>
<pre><code>/databaseRoot
/blockedUsers
userId1 : true
userId2 : true
</code></pre>
<p>Adding the user to this list will depend on your necessity. You can do it manually by accessing the firebase console and adding the user id to the node. Or, if you want to block an user based on an event on the application, you could simply call something like</p>
<pre><code>ref.child('blockedUsers').child(userIdToBlock).set(true);
</code></pre> |
35,703,317 | Docker exec - Write text to file in container | <p>I want to write a line of text to a textfile INSIDE a running docker container. Here's what I've tried so far:</p>
<pre><code>docker exec -d app_$i eval echo "server.url=$server_url" >> /home/app/.app/app.config
</code></pre>
<p>Response:</p>
<pre><code>/home/user/.app/app.config: No such file or directory
</code></pre>
<p>Second try:</p>
<pre><code>cfg_add="echo 'server.url=$server_url' >> /home/user/.app/app.config"
docker exec -i app_$i eval $cfg_add
</code></pre>
<p>Response:</p>
<pre><code>exec: "eval": executable file not found in $PATH
</code></pre>
<p>Any ideas?</p> | 35,714,149 | 3 | 3 | null | 2016-02-29 15:29:10.383 UTC | 3 | 2021-06-05 01:27:38.993 UTC | 2016-02-29 15:34:44.223 UTC | null | 4,366,957 | null | 4,366,957 | null | 1 | 30 | bash|docker | 46,084 | <p><code>eval</code> is a shell <em>builtin</em>, whereas <code>docker exec</code> requires an <em>external utility</em> to be called, so using <code>eval</code> is <em>not</em> an option.</p>
<p>Instead, invoke a shell executable in the container (<code>bash</code>) <em>explicitly</em>, and pass it the command to execute as a <em>string</em>, via its <code>-c</code> option:</p>
<pre><code>docker exec "app_$i" bash -c "echo 'server.url=$server_url' >> /home/app/.app/app.config"
</code></pre>
<p>By using a <em>double-quoted</em> string to pass to <code>bash -c</code>, you ensure that the <em>current</em> shell performs string interpolation first, whereas the container's <code>bash</code> instance then sees the expanded result as a <em>literal</em>, as part of the embedded <em>single-quoted</em> string.</p>
<hr>
<p>As for <strong>your symptoms</strong>:</p>
<ul>
<li><p><code>/home/user/.app/app.config: No such file or directory</code> was reported, because the redirection you intended to happen <em>in the container</em> actually happened in <em>your host's shell</em> - and because dir. <code>/home/user/.app</code> apparently doesn't exist in your host's filesystem, the command failed <em>fundamentally</em>, <em>before</em> your host's shell even attempted to execute the command (<code>bash</code> will abort command execution if an output redirection cannot be performed).</p>
<ul>
<li>Thus, even though your first command also contained <code>eval</code>, its use didn't surface as a problem until your second command, which actually <em>did</em> get executed.</li>
</ul></li>
<li><p><code>exec: "eval": executable file not found in $PATH</code> happened, because, as stated, <code>eval</code> is not an <em>external utility</em>, but a <em>shell builtin</em>, and <code>docker exec</code> can only execute external utilities.</p></li>
</ul> |
21,274,930 | USB Debugging not working, adb ignores Nexus 7 | <p>For several weeks, I was able to connect my Nexus 7 2 to my computer running Windows 7, and Eclipse would recognize it, allowing me to run apps on it. The device also showed up when I ran the <code>adb devices</code> command. Every time I plugged the Nexus 7 into the computer, the tablet asked if I wanted to allow USB debugging at that time. (Oddly, it never asked me whether I wanted to always allow it from that computer, but I didn't care.)</p>
<p>I recently updated the tablet to Android 4.4.2. I also updated the Android SDKs through the Android SDK manager. Now, when I plug the tablet in, I do not get prompt about USB debugging on the tablet, and neither Eclipse nor adb can see that it is there.</p>
<p>Here is a list of things I tried to do, gathering ideas from various forums around the web.</p>
<ul>
<li>Re-download the Asus drivers for the Nexus 7 and update the driver. However, Windows does not even recognize this as the right drivers for this device.</li>
<li>Turn USB Debugging off and on on the tablet, and also revoke all USB debugging permissions.</li>
<li>Change the connection mode from media device to camera</li>
<li>Switch the runtime from Dalvik to ART</li>
<li>Type adb kill-server followed by adb start-server in the command line</li>
<li>Delete eclipse and all the Android SDK and download them all over again</li>
</ul>
<p>None of this worked. Any other ideas on what to try?</p> | 21,297,060 | 8 | 6 | null | 2014-01-22 05:29:10.177 UTC | 1 | 2015-08-12 10:27:56.787 UTC | null | null | null | null | 985,802 | null | 1 | 10 | android|eclipse|debugging|nexus-7 | 54,200 | <p>It turns out that the Nexus 7 definitely needs the Google USB Driver. Finding, downloading, and installing this driver worked perfectly.</p>
<p>Because <a href="http://developer.android.com/tools/extras/oem-usb.html">Google's Android OEM drivers page</a> does not include the Nexus 7 in its list of devices that need the Google USB driver, I had been trying the driver from Asus, which did not work. I did not try the Google USB driver because for some reason my SDK manager said it had downloaded the driver, but the driver was not to be found.</p>
<p>Finally I found I could <a href="http://developer.android.com/sdk/win-usb.html">download the Google USB driver from this page</a>, which clarifies that all Google Nexus devices need this driver. Now I have successfully re-connected the tablet to ADB.</p>
<p>I submitted a <a href="https://code.google.com/p/android/issues/detail?id=65119&thanks=65119&ts=1390436681">documentation bug report to Google here</a> in hopes that the OEM drivers page can be updated to reflect that all Google Nexus devices need the Google USB driver.</p> |
23,051,973 | What is the `zero` value for time.Time in Go? | <p>In an error condition, I tried to return <code>nil</code>, which throws the error:</p>
<pre><code>cannot use nil as type time.Time in return argument
</code></pre>
<p>What is the <code>zero</code> value for <code>time.Time</code>?</p> | 23,051,997 | 4 | 2 | null | 2014-04-14 04:29:54.45 UTC | 26 | 2022-07-11 15:43:48.067 UTC | null | null | null | null | 1,246,262 | null | 1 | 246 | time|go|null | 183,441 | <p>Invoking an empty <code>time.Time</code> struct literal will return Go's zero date. Thus, for the following print statement:</p>
<pre><code>fmt.Println(time.Time{})
</code></pre>
<p>The output is:</p>
<pre><code>0001-01-01 00:00:00 +0000 UTC
</code></pre>
<p>For the sake of completeness, the <a href="http://golang.org/pkg/time/#Time">official documentation</a> explicitly states:</p>
<blockquote>
<p>The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.</p>
</blockquote> |
1,615,419 | What is the reason for these PMD rules? | <blockquote>
<p>DataflowAnomalyAnalysis: Found
'DD'-anomaly for variable 'variable'
(lines 'n1'-'n2').</p>
<p>DataflowAnomalyAnalysis: Found
'DU'-anomaly for variable 'variable'
(lines 'n1'-'n2').</p>
</blockquote>
<p>DD and DU sound familiar...I want to say in things like testing and analysis relating to weakest pre and post conditions, but I don't remember the specifics.</p>
<blockquote>
<p>NullAssignment: Assigning an Object to
null is a code smell. Consider
refactoring.</p>
</blockquote>
<p>Wouldn't setting an object to <code>null</code> assist in garbage collection, if the object is a local object (not used outside of the method)? Or is that a myth?</p>
<blockquote>
<p>MethodArgumentCouldBeFinal: Parameter
'param' is not assigned and could be
declared final</p>
<p>LocalVariableCouldBeFinal: Local
variable 'variable' could be declared
final</p>
</blockquote>
<p>Are there any advantages to using <code>final</code> parameters and variables?</p>
<blockquote>
<p>LooseCoupling: Avoid using
implementation types like
'LinkedList'; use the interface
instead</p>
</blockquote>
<p>If I know that I specifically need a <code>LinkedList</code>, why would I not use one to make my intentions explicitly clear to future developers? It's one thing to return the class that's highest up the class path that makes sense, but why would I not declare my variables to be of the strictest sense?</p>
<blockquote>
<p>AvoidSynchronizedAtMethodLevel: Use
block level rather than method level
synchronization</p>
</blockquote>
<p>What advantages does block-level synchronization have over method-level synchronization?</p>
<blockquote>
<p>AvoidUsingShortType: Do not use the
short type</p>
</blockquote>
<p>My first languages were C and C++, but in the Java world, why should I not use the type that best describes my data?</p> | 1,615,477 | 6 | 0 | null | 2009-10-23 19:22:51.707 UTC | 12 | 2015-09-27 01:52:15.42 UTC | 2015-09-27 01:52:15.42 UTC | null | 1,677,912 | null | 572 | null | 1 | 36 | java|pmd | 35,567 | <ul>
<li><p>DD and DU anomalies (if I remember correctly—I use FindBugs and the messages are a little different) refer to assigning a value to a local variable that is never read, usually because it is reassigned another value before ever being read. A typical case would be initializing some variable with <code>null</code> when it is declared. <a href="https://stackoverflow.com/questions/110083/which-loop-has-better-performance-why/110389#110389">Don't declare the variable until it's needed.</a></p></li>
<li><p>Assigning <code>null</code> to a local variable in order to "assist" the garbage collector is a myth. PMD is letting you know this is just counter-productive clutter.</p></li>
<li><p>Specifying final on a local variable <em>should</em> be very useful to an optimizer, but I don't have any concrete examples of current JITs taking advantage of this hint. I have found it useful in reasoning about the correctness of my own code.</p></li>
<li><p>Specifying interfaces in terms of… well, <em>interfaces</em> is a great design practice. You can easily change implementations of the collection without impacting the caller at all. That's what interfaces are all about.</p></li>
<li><p>I can't think of many cases where a caller would <em>require</em> a <code>LinkedList</code>, since it doesn't expose any API that isn't declared by some interface. If the client relies on that API, it's available through the correct interface.</p></li>
<li><p>Block level synchronization allows the critical section to be smaller, which allows as much work to be done concurrently as possible. Perhaps more importantly, it allows the use of a lock object that is privately controlled by the enclosing object. This way, you can guarantee that no deadlock can occur. Using the instance itself as a lock, anyone can synchronize on it incorrectly, causing deadlock.</p></li>
<li><p>Operands of type <code>short</code> are promoted to <code>int</code> in any operations. This rule is letting you know that this promotion is occurring, and you might as well use an <code>int</code>. However, using the <code>short</code> type can save memory, so if it is an instance member, I'd probably ignore that rule.</p></li>
</ul> |
1,513,972 | How to generate a Java class which implements Serializable interface from xsd using JAXB? | <p>I would like to introduce caching into an existing Spring project which uses JAXB to expose WebServices. Caching will be done on the level of end points. In order to do that classes generated from XSD using JAXB need to implement <code>Serializable</code> interface and override <code>Object</code>'s <code>toString()</code> method.</p>
<p>How to instruct the xjc tool using XSD to generate source with needed properties?</p> | 1,514,030 | 6 | 2 | null | 2009-10-03 15:01:07.357 UTC | 13 | 2020-05-16 22:44:29.117 UTC | 2015-07-16 17:26:47.447 UTC | null | 64,046 | null | 32,090 | null | 1 | 46 | java|xsd|jaxb|xjc | 56,000 | <h2>Serializable</h2>
<p>Use <code>xjc:serializable</code> in a custom bindings file to add the <code>java.io.Serializable</code> interface to your classes along with a <code>serialVersionUID</code>: </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xsi:schemaLocation="
http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"
version="2.1">
<globalBindings>
<serializable uid="1" />
</globalBindings>
</bindings>
</code></pre>
<h2>toString()</h2>
<p>Use a superclass (see <code>xjc:superClass</code>) from which all your bound classes will inherit. This class won’t be generated by xjc so you are free to create it as you please (here with a <code>toString()</code> implementation): </p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns="http://java.sun.com/xml/ns/jaxb"
xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xsi:schemaLocation="
http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"
version="2.1">
<globalBindings>
<serializable uid="1" />
<xjc:superClass name="the.package.to.my.XmlSuperClass" />
</globalBindings>
</bindings>
</code></pre> |
1,598,773 | Is there a standard function in C that would return the length of an array? | <p>Is there a standard function in C that would return the length of an array? </p> | 1,598,827 | 7 | 1 | null | 2009-10-21 04:50:52.3 UTC | 23 | 2020-02-07 15:14:44.917 UTC | 2009-10-21 04:58:07.853 UTC | null | 170,443 | null | 133,466 | null | 1 | 27 | c|arrays | 12,372 | <p>Often the technique described in other answers is encapsulated in a macro to make it easier on the eyes. Something like:</p>
<pre><code>#define COUNT_OF( arr) (sizeof(arr)/sizeof(0[arr]))
</code></pre>
<p>Note that the macro above uses a small trick of putting the array name in the index operator ('<code>[]</code>') instead of the <code>0</code> - this is done in case the macro is mistakenly used in C++ code with an item that overloads <code>operator[]()</code>. The compiler will complain instead of giving a bad result.</p>
<p>However, also note that if you happen to pass a pointer instead of an array, the macro will silently give a bad result - this is one of the major problems with using this technique.</p>
<p>I have recently started to use a more complex version that I stole from Google Chromium's codebase:</p>
<pre><code>#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
</code></pre>
<p>In this version if a pointer is mistakenly passed as the argument, the compiler will complain in some cases - specifically if the pointer's size isn't evenly divisible by the size of the object the pointer points to. In that situation a divide-by-zero will cause the compiler to error out. Actually at least one compiler I've used gives a warning instead of an error - I'm not sure what it generates for the expression that has a divide by zero in it. </p>
<p>That macro doesn't close the door on using it erroneously, but it comes as close as I've ever seen in straight C.</p>
<p>If you want an even safer solution for when you're working in C++, take a look at <a href="https://stackoverflow.com/questions/1500363/compile-time-sizeofarray-without-using-a-macro/1500917#1500917">Compile time sizeof_array without using a macro</a> which describes a rather complex template-based method Microsoft uses in <code>winnt.h</code>.</p> |
2,103,322 | VARCHAR as foreign key/primary key in database good or bad? | <p>Is it better if I use ID nr:s instead of VARCHARS as foreign keys?
And is it better to use ID nr:s isntead of VARCHARS as Primary Keys?
By ID nr I mean INT!</p>
<p><strong>This is what I have now:</strong></p>
<pre><code>category table:
cat_id ( INT ) (PK)
cat_name (VARCHAR)
category options table:
option_id ( INT ) (PK)
car_id ( INT ) (FK)
option_name ( VARCHAR )
</code></pre>
<p><strong>I COULD HAVE THIS I THINK:</strong></p>
<pre><code>category table:
cat_name (VARCHAR) (PK)
category options table:
cat_name ( VARCHAR ) (FK)
option_name ( VARCHAR ) ( PK )
</code></pre>
<p>Or am I thinking completely wrong here?</p> | 2,103,355 | 7 | 6 | null | 2010-01-20 17:09:50.217 UTC | 14 | 2012-10-20 22:25:18.387 UTC | null | null | null | user188962 | null | null | 1 | 48 | sql|mysql|database|search|indexing | 54,478 | <p>The problem with VARCHAR being used for any KEY is that they can hold WHITE SPACE. White space consists of ANY non-screen-readable character, like spaces tabs, carriage returns etc. Using a VARCHAR as a key can make your life difficult when you start to hunt down why tables aren't returning records with extra spaces at the end of their keys.</p>
<p>Sure, you <strong>CAN</strong> use VARCHAR, but you do have to be very careful with the input and output. They also take up more space and are likely slower when doing a Queries.</p>
<p>Integer types have a small list of 10 characters that are valid, <strong>0,1,2,3,4,5,6,7,8,9</strong>. They are a much better solution to use as keys.</p>
<p>You could always use an integer-based key and use VARCHAR as a UNIQUE value if you wanted to have the advantages of faster lookups.</p> |
2,251,019 | How to direct the mouse wheel input to control under cursor instead of focused? | <p>I use a number of scrolling controls: TTreeViews, TListViews, DevExpress cxGrids and cxTreeLists, etc. When the mouse wheel is spun, the control with focus receives the input no matter what control the mouse cursor is over.</p>
<p>How do you direct the mouse wheel input to whatever control the mouse cursor is over? The Delphi IDE works very nicely in this regard.</p> | 2,251,642 | 8 | 2 | null | 2010-02-12 10:13:47.6 UTC | 23 | 2016-11-05 10:26:40.36 UTC | 2014-02-24 06:50:31.757 UTC | null | 77,764 | null | 37,660 | null | 1 | 42 | delphi|mousewheel | 23,337 | <p>Try overriding your form's <code>MouseWheelHandler</code> method like this (I have not tested this thoroughly):</p>
<pre><code>procedure TMyForm.MouseWheelHandler(var Message: TMessage);
var
Control: TControl;
begin
Control := ControlAtPos(ScreenToClient(SmallPointToPoint(TWMMouseWheel(Message).Pos)), False, True, True);
if Assigned(Control) and (Control <> ActiveControl) then
begin
Message.Result := Control.Perform(CM_MOUSEWHEEL, Message.WParam, Message.LParam);
if Message.Result = 0 then
Control.DefaultHandler(Message);
end
else
inherited MouseWheelHandler(Message);
end;
</code></pre> |
1,745,691 | LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria | <p>Consider the IEnumerable extension methods <code>SingleOrDefault()</code> and <code>FirstOrDefault()</code></p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb342451.aspx" rel="noreferrer">MSDN documents that <code>SingleOrDefault</code></a>:</p>
<blockquote>
<p>Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.</p>
</blockquote>
<p>whereas <a href="http://msdn.microsoft.com/en-us/library/bb340482.aspx" rel="noreferrer"><code>FirstOrDefault</code> from MSDN</a> (presumably when using an <code>OrderBy()</code> or <code>OrderByDescending()</code> or none at all),</p>
<blockquote>
<p>Returns the first element of a sequence</p>
</blockquote>
<p>Consider a handful of example queries, it's not always clear when to use these two methods:</p>
<pre><code>var someCust = db.Customers
.SingleOrDefault(c=>c.ID == 5); //unlikely(?) to be more than one, but technically COULD BE
var bobbyCust = db.Customers
.FirstOrDefault(c=>c.FirstName == "Bobby"); //clearly could be one or many, so use First?
var latestCust = db.Customers
.OrderByDescending(x=> x.CreatedOn)
.FirstOrDefault();//Single or First, or does it matter?
</code></pre>
<p><strong>Question</strong></p>
<p><strong>What conventions do you follow or suggest</strong> when deciding to use <code>SingleOrDefault()</code> and <code>FirstOrDefault()</code> in your LINQ queries?</p> | 1,745,716 | 16 | 0 | null | 2009-11-16 23:59:33.02 UTC | 127 | 2021-03-31 05:21:22.583 UTC | 2009-11-17 02:24:35.283 UTC | null | 23,199 | null | 23,199 | null | 1 | 583 | .net|linq|linq-to-sql | 372,079 | <p>Whenever you use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.singleordefault" rel="noreferrer"><code>SingleOrDefault</code></a>, you clearly state that the query should result in at most a <em>single</em> result. On the other hand, when <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault" rel="noreferrer"><code>FirstOrDefault</code></a> is used, the query can return any amount of results but you state that you only want the first one.</p>
<p>I personally find the semantics very different and using the appropriate one, depending on the expected results, improves readability.</p> |
1,839,668 | What is the best way to combine two lists into a map (Java)? | <p>It would be nice to use <code>for (String item: list)</code>, but it will only iterate through one list, and you'd need an explicit iterator for the other list. Or, you could use an explicit iterator for both.</p>
<p>Here's an example of the problem, and a solution using an indexed <code>for</code> loop instead:</p>
<pre><code>import java.util.*;
public class ListsToMap {
static public void main(String[] args) {
List<String> names = Arrays.asList("apple,orange,pear".split(","));
List<String> things = Arrays.asList("123,456,789".split(","));
Map<String,String> map = new LinkedHashMap<String,String>(); // ordered
for (int i=0; i<names.size(); i++) {
map.put(names.get(i), things.get(i)); // is there a clearer way?
}
System.out.println(map);
}
}
</code></pre>
<p>Output:</p>
<pre><code>{apple=123, orange=456, pear=789}
</code></pre>
<p>Is there a clearer way? Maybe in the collections API somewhere?</p> | 1,839,695 | 18 | 6 | null | 2009-12-03 12:46:01.703 UTC | 26 | 2021-02-01 18:24:12.02 UTC | 2019-08-01 21:42:46.353 UTC | null | 6,505,685 | null | 50,979 | null | 1 | 89 | java|data-structures|collections | 113,721 | <p>Since the key-value relationship is implicit via the list index, I think the for-loop solution that uses the list index explicitly is actually quite clear - and short as well.</p> |
33,754,935 | Read a base 64 encoded image from memory using OpenCv python library | <p>I'm working on an app that to do some facial recognition from a webcam stream. I get base64 encoded data uri's of the canvas and want to use it to do something like this:</p>
<pre><code>cv2.imshow('image',img)
</code></pre>
<p>The data URI looks something like this:</p>
<pre><code> data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7
</code></pre>
<p>So, for clarity I've shown what the image looks like so the base64 string is not broken.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7"></code></pre>
</div>
</div>
</p>
<p>The <a href="http://docs.opencv.org/3.0-beta/modules/imgcodecs/doc/reading_and_writing_images.html" rel="noreferrer">official doc</a> says, that <code>imread</code> accepts a file path as the argument. From <a href="https://stackoverflow.com/a/16214280/1083314">this</a> SO answer, if I do something like:</p>
<pre><code> import base64
imgdata = base64.b64decode(imgstring) #I use imgdata as this variable itself in references below
filename = 'some_image.jpg'
with open(filename, 'wb') as f:
f.write(imgdata)
</code></pre>
<p>The above code snippet works and the image file gets generated properly. However I don't think so many File IO operations are feasible considering I'd be doing this for every frame of the stream. I want to be able to read the image into the memory directly creating the <code>img</code> object.</p>
<p>I have tried two solutions that seem to be working for some people.</p>
<ol>
<li><p>Using PIL <a href="https://stackoverflow.com/a/11601466/1083314">reference</a>:</p>
<pre><code>pilImage = Image.open(StringIO(imgdata))
npImage = np.array(pilImage)
matImage = cv.fromarray(npImage)
</code></pre>
<p>I get <code>cv</code> not defined as I have openCV3 installed which is available to me as <code>cv2</code> module. I tried <code>img = cv2.imdecode(npImage,0)</code>, this returns nothing.</p></li>
<li><p>Getting the bytes from decoded string and converting it into an numpy array of sorts</p>
<pre><code>file_bytes = numpy.asarray(bytearray(imgdata), dtype=numpy.uint8)
img = cv2.imdecode(file_bytes, 0) #Here as well I get returned nothing
</code></pre></li>
</ol>
<p>The documentation doesn't really mention what the <code>imdecode</code> function returns. However, from the errors that I encountered, I guess it is expecting a <code>numpy array</code> or a <code>scalar</code> as the first argument. How do I get a handle on that image in memory so that I can do <code>cv2.imshow('image',img)</code> and all kinds of cool stuff thereafter.</p>
<p>I hope I was able to make myself clear.</p> | 37,914,122 | 4 | 4 | null | 2015-11-17 10:45:24.173 UTC | 8 | 2022-02-28 11:11:28.753 UTC | 2017-05-23 12:10:34.053 UTC | null | -1 | null | 1,083,314 | null | 1 | 28 | python|opencv|numpy|encoding|base64 | 36,299 | <p>You can just use both cv2 and pillow like this:</p>
<pre><code>import base64
from PIL import Image
import cv2
from StringIO import StringIO
import numpy as np
def readb64(base64_string):
sbuf = StringIO()
sbuf.write(base64.b64decode(base64_string))
pimg = Image.open(sbuf)
return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR)
cvimg = readb64('R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7')
cv2.imshow(cvimg)
</code></pre> |
46,241,088 | How to create AWS Glue table where partitions have different columns? ('HIVE_PARTITION_SCHEMA_MISMATCH') | <p>As per this <a href="https://forums.aws.amazon.com/thread.jspa?messageID=805011" rel="noreferrer">AWS Forum Thread</a>, does anyone know how to use AWS Glue to create an AWS Athena table whose partitions contain different schemas (in this case different subsets of columns from the table schema)?</p>
<p>At the moment, when I run the crawler over this data and then make a query in Athena, I get the error <code>'HIVE_PARTITION_SCHEMA_MISMATCH'</code></p>
<p>My use case is:</p>
<ul>
<li>Partitions represent days</li>
<li>Files represent events</li>
<li>Each event is a json blob in a single s3 file</li>
<li>An event contains a subset of columns (dependent on the type of event)</li>
<li>The 'schema' of the entire table is the full set of columns for all the event types (this is correctly put together by Glue crawler)</li>
<li>The 'schema' of each partition is the subset of columns for the event types that occurred on that day (hence in Glue each partition potentially has a different subset of columns from the table schema)</li>
<li>This inconsistency causes the error in Athena I think</li>
</ul>
<p>If I were to manually write a schema I could do this fine as there would just be one table schema, and keys which are missing in the JSON file would be treated as Nulls.</p>
<p>Thanks in advance!</p> | 48,664,826 | 4 | 3 | null | 2017-09-15 13:44:53.64 UTC | 11 | 2021-03-02 12:27:16.93 UTC | null | null | null | null | 3,052,692 | null | 1 | 41 | amazon-web-services|amazon-s3|amazon-athena|aws-glue | 13,685 | <p>I had the same issue, solved it by configuring crawler to update table metadata for preexisting partitions:</p>
<p><a href="https://i.stack.imgur.com/y7fLf.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/y7fLf.jpg" alt="enter image description here"></a></p> |
15,972,224 | How to create DateTimePicker in Razor MVC4? | <p>I am creating a web-based task scheduling application using QUARTZ.NET and RAZOR(MVC4).
For more details <a href="https://stackoverflow.com/questions/15802755/how-to-implement-a-task-scheduler-service-using-quartz-net-for-multiple-servers/15854689?noredirect=1#15854689">Click Here</a> as given bellow</p>
<p><img src="https://i.stack.imgur.com/i599H.png" alt="Form to add scheduler"></p>
<p>Please give me some code or any reference to implement DateTimePicker in RAZOR(MVC4).</p>
<p><strong>Thanks for your precious Help in Advance.</strong></p> | 15,973,048 | 2 | 1 | null | 2013-04-12 13:07:14.673 UTC | 2 | 2013-06-01 01:12:32.893 UTC | 2017-05-23 12:13:54.573 UTC | null | -1 | null | 2,239,742 | null | 1 | 4 | asp.net-mvc-4|razor|datetimepicker|quartz.net | 46,187 | <p>See this basic blog for datepicker with jquery UI.
<a href="http://www.asp.net/mvc/tutorials/javascript/using-the-html5-and-jquery-ui-datepicker-popup-calendar-with-aspnet-mvc/using-the-html5-and-jquery-ui-datepicker-popup-calendar-with-aspnet-mvc-part-1">http://www.asp.net/mvc/tutorials/javascript/using-the-html5-and-jquery-ui-datepicker-popup-calendar-with-aspnet-mvc/using-the-html5-and-jquery-ui-datepicker-popup-calendar-with-aspnet-mvc-part-1</a></p>
<p>See my extending blog for localization support
<a href="http://locktar.wordpress.com/2012/09/10/localization-validation-in-mvc/">http://locktar.wordpress.com/2012/09/10/localization-validation-in-mvc/</a></p> |
57,683,206 | What is the reverse of "kubectl apply"? | <p>I was playing around in minikube and installed the wrong version of istio. I ran:</p>
<pre><code>kubectl apply -f install/kubernetes/istio-demo-auth.yaml
</code></pre>
<p>instead of:</p>
<pre><code>kubectl apply -f install/kubernetes/istio-demo.yaml
</code></pre>
<p>I figured I would just undo it and install the right one.</p>
<p>But I cannot seem to find an <code>unapply</code> command.</p>
<p><strong>How do I <em>undo</em> a "kubectl apply" command?</strong></p> | 57,683,241 | 3 | 4 | null | 2019-08-27 23:09:19.307 UTC | 10 | 2021-08-11 11:56:07.193 UTC | null | null | null | null | 16,241 | null | 1 | 91 | kubernetes | 39,981 | <p>One way would be <a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#delete" rel="noreferrer"><code>kubectl delete -f <filename></code></a> but it implies few things:</p>
<ol>
<li><p>The resources were first created. It simply removes all of those, if you really want to "revert to the previous state" I'm not sure there are built-in tools in Kubernetes to do that (so you really would restore from a backup, if you have one)</p></li>
<li><p>The containers did not modify the host machines: containers may mount root filesystem and change it, or kernel subsystems (iptables, etc). The <code>delete</code> command would not revert it either, and in that case you really need to check the documentation for the product to see if they offer any official way to guarantees a proper cleanup</p></li>
</ol> |
5,539,823 | What are the benefits of a stateless web application? | <p>It seems some web architects aim to have a stateless web application. Does that mean basically not storing user sessions? Or is there more to it?</p>
<p>If it is just the user session storing, what is the benefit of not doing that?</p> | 5,539,862 | 2 | 1 | null | 2011-04-04 14:20:17.057 UTC | 16 | 2018-06-25 18:06:26.687 UTC | null | null | null | null | 478,573 | null | 1 | 30 | session|session-state|session-variables|stateless | 16,863 | <ol>
<li><strong>Reduces memory usage</strong>. Imagine if google stored session information about every one of their users</li>
<li><strong>Easier to support server farms</strong>. If you need session data and you have more than 1 server, you need a way to sync that session data across servers. Normally this is done using a database. </li>
<li><strong>Reduce session expiration problems</strong>. Sometimes expiring sessions cause issues that are hard to find and test for. Sessionless applications don't suffer from these.</li>
<li><strong>Url linkability</strong>. Some sites store the ID of what the user is looking at in the sessions. This makes it impossible for users to simply copy and paste the URL or send it to friends.</li>
</ol>
<p>NOTE: session data is really cached data. This is what it should be used for. If you have an expensive query which is going to be reused, then save it into session. Just remember that you cannot assume it will be there when you try and get it later. Always check if it exists before retrieving.</p> |
1,076,257 | Returning data from forked processes | <p>If I do </p>
<pre><code>Process.fork do
x
end
</code></pre>
<p>how can I know what x returned (e.g. true/fase/string) ? </p>
<p>(Writing to a file/database is not an option...)</p> | 1,281,846 | 7 | 0 | 2009-07-02 19:32:17.807 UTC | 2009-07-02 19:32:17.807 UTC | 8 | 2016-05-18 12:38:05.75 UTC | 2016-05-18 12:38:05.75 UTC | null | 3,257,186 | null | 110,333 | null | 1 | 29 | ruby|process|fork | 11,578 | <p>I wrapped all the solutions I found along the way (some other problems like user exiting + piping-buffers) into <a href="http://github.com/grosser/parallel" rel="noreferrer">ruby parallel gem</a>. Now it is as easy as:</p>
<pre><code>results = Parallel.map([1,2,3],:in_processes=>4) do |i|
execute_something(i)
end
</code></pre>
<p>or</p>
<pre><code>results = Parallel.map([1,2,3],:in_threads=>4) do |i|
execute_something(i)
end
</code></pre> |
798,221 | C Macros to create strings | <blockquote>
<p><strong>Alternative Titles (to aid search)</strong></p>
<ul>
<li>Convert a preprocessor token to a string</li>
<li>How to make a char string from a <strong>C</strong> macro's value?</li>
</ul>
</blockquote>
<h1>Original Question</h1>
<p>I would like to use <strong>C</strong> <code>#define</code> to build literal strings at compile time.</p>
<p>The string are domains that change for debug, release etc.</p>
<p>I would like to some some thing like this:</p>
<pre><code>#ifdef __TESTING
#define IV_DOMAIN example.org //in house testing
#elif __LIVE_TESTING
#define IV_DOMAIN test.example.com //live testing servers
#else
#define IV_DOMAIN example.com //production
#endif
// Sub-Domain
#define IV_SECURE "secure.IV_DOMAIN" //secure.example.org etc
#define IV_MOBILE "m.IV_DOMAIN"
</code></pre>
<p>But the preprocessor doesn't evaluate anything within ""</p>
<ol>
<li>Is there a way around this?</li>
<li>Is this even a good idea?</li>
</ol> | 798,275 | 7 | 1 | null | 2009-04-28 14:21:01.177 UTC | 9 | 2022-07-11 10:16:48.99 UTC | 2022-07-11 10:16:27.043 UTC | null | 1,145,388 | null | 89,035 | null | 1 | 33 | c|macros|c-preprocessor|stringification | 26,271 | <p>In C, string literals are concatenated automatically. For example,</p>
<pre><code>const char * s1 = "foo" "bar";
const char * s2 = "foobar";
</code></pre>
<p><code>s1</code> and <code>s2</code> are the same string.</p>
<p>So, for your problem, the answer (without token pasting) is</p>
<pre><code>#ifdef __TESTING
#define IV_DOMAIN "example.org"
#elif __LIVE_TESTING
#define IV_DOMAIN "test.example.com"
#else
#define IV_DOMAIN "example.com"
#endif
#define IV_SECURE "secure." IV_DOMAIN
#define IV_MOBILE "m." IV_DOMAIN
</code></pre> |
683,275 | How can I position a web page in the middle of the screen? | <p>How can I position a web page in the middle of the screen? like the pages on stackoverflow web site?
I'm writing the masterpage of my website and I want to use HTML and css to position the master page in the middleof the screen and then build the inside positioning block using css. But I can't get my page to be visualized in the middle!</p>
<p>Thank you!</p> | 683,291 | 8 | 0 | null | 2009-03-25 20:18:53.953 UTC | null | 2018-11-22 19:27:47.6 UTC | null | null | null | Uince81 | 80,128 | null | 1 | 9 | html|css | 66,677 | <p>You can use margins to position it in the center horizontally.</p>
<p>Given this html:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<div id="page"> ... content ... </div>
</body>
</html>
</code></pre>
<p>The CSS can be as simple as:</p>
<pre><code>#page {
margin-left:auto;
margin-right:auto;
width:960px;
}
</code></pre>
<p>You also need to make sure you have a valid doctype for this to work.</p> |
1,142,003 | Set "Homepage" in Asp.Net MVC | <p>In asp.net MVC the "homepage" (ie the route that displays when hitting www.foo.com) is set to Home/Index .</p>
<ul>
<li>Where is this value stored? </li>
<li>How can I change the "homepage"? </li>
<li>Is there anything more elegant than using RedirectToRoute() in the Index action of the home controller?</li>
</ul>
<p>I tried grepping for Home/Index in my project and couldn't find a reference, nor could I see anything in IIS (6). I looked at the default.aspx page in the root, but that didn't seem to do anything relevent.</p>
<p>Thanks</p> | 1,142,016 | 8 | 0 | null | 2009-07-17 08:22:56.717 UTC | 14 | 2019-04-16 03:26:26.223 UTC | 2013-04-05 15:28:07.083 UTC | null | 806,975 | null | 39,643 | null | 1 | 108 | c#|asp.net-mvc|asp.net-mvc-routing | 143,405 | <p>Look at the <code>Default.aspx/Default.aspx.cs</code> and the Global.asax.cs</p>
<p>You can set up a default route:</p>
<pre><code> routes.MapRoute(
"Default", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index"} // Parameter defaults
);
</code></pre>
<p>Just change the Controller/Action names to your desired default. That should be the last route in the Routing Table.</p> |
1,236,067 | test if event handler is bound to an element in jQuery | <p>Is it possible to determine whether an element has a click handler, or a change handler, or any kind of event handler bound to it using jQuery?</p>
<p>Furthermore, is it possible to determine how many click handlers (or whatever kind of event handlers) it has for a given type of event, and what functions are in the event handlers?</p> | 1,236,080 | 11 | 0 | null | 2009-08-05 22:19:32.807 UTC | 52 | 2018-10-25 07:13:42.023 UTC | 2013-02-05 09:36:02.523 UTC | null | 1,939,046 | null | 28,324 | null | 1 | 193 | javascript|jquery | 147,756 | <p>You can get this information from the data cache.</p>
<p>For example, log them to the console (firebug, ie8):</p>
<pre><code>console.dir( $('#someElementId').data('events') );
</code></pre>
<p>or iterate them:</p>
<pre><code>jQuery.each($('#someElementId').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
console.log( handler.toString() );
});
});
</code></pre>
<p>Another way is you can use the following <a href="http://www.sprymedia.co.uk/article/Visual+Event" rel="nofollow noreferrer">bookmarklet</a> but obviously this does not help at runtime.</p> |
1,214,621 | Securing your Data Layer in a C# Application | <p>I was thinking about how to secure the Data Layer in a C# Application, the layer could in this case be either a LINQ to SQL Model Diagram stored with the Application itself containg the connection string to the SQL Server Database.</p>
<p>Or it could be connectivity between the application and webservices.</p>
<p>Either you need to impement some sort of security, for instance, the Connection String in a Application can easily be reverse engineered and Webservices can easily be tracked and used for other reasons than the applications original purpose.</p>
<p>So my question is in a shorter way: <strong>How do you solve the security issues when handling Webservices and/or direct connection to a SQL Server From a Windows Forms Application?</strong></p> | 1,216,254 | 12 | 1 | null | 2009-07-31 20:13:28.637 UTC | 15 | 2022-04-11 09:10:12.397 UTC | 2009-08-01 09:07:32.65 UTC | null | 39,106 | null | 39,106 | null | 1 | 12 | c#|security|architecture | 5,640 | <p>In your case there are two main attack possibilities:</p>
<ul>
<li>Steal the connection string and then access the database directly</li>
<li>Call methods in your C# code directly without using the UI</li>
</ul>
<p>For the connection string you need to store it in an encrypted form in a config file. Problem is that there need to be enough information in the winforms app so that it can decrypt and use it.</p>
<p>For accessing the code directly you can use code access security and obfuscation.</p>
<p>In your case I would not give the windows app direct access to the database. Let the windows app call a WCF service, the the WCF service would access the database.</p>
<p>The user's user account is allowed to call the WCF service, the WCF service is running under an account that is allowed to access the database, the user's user account has no rights to the database.</p>
<p>Windows App with 3 Layers:</p>
<ul>
<li>UI </li>
<li>Business (Security check what UI should be shown to the user)</li>
<li>Proxy</li>
</ul>
<p>WCF Service with 2 Layers:</p>
<ul>
<li>Facade / Business Layer (Security check is user allowed to call this method with this data)</li>
<li>Entity Framework datamodel</li>
</ul>
<p>Common dll's to both Layers</p>
<ul>
<li>Contracts / WCF Interfaces</li>
<li>Data Transfer Objects</li>
</ul>
<p>For info on proxy, contracts and DTO's see this video:</p>
<p><a href="http://www.dnrtv.com/default.aspx?showNum=103" rel="noreferrer">http://www.dnrtv.com/default.aspx?showNum=103</a></p> |
435,379 | C# Clear all items in ListView | <p>I try to clear my listview but the clear method doesn't work:</p>
<pre><code>myListView.Items.Clear();
</code></pre>
<p>This doen't work. When i put a breakpoint at this line, the line is executed, but my listview isn't empty. How come??</p>
<p>I fill my listview by setting it's datasource to a datatable.</p>
<p>My solution now is to set the datasource to an empty datatable.</p>
<p>I just wonder why clear don't do the trick?</p>
<p>I use a master page. Here some code of a content page when a button is pressed.
The method SearchTitle fills the ListView.</p>
<p>Relevant code:</p>
<pre><code> protected void Zoek()
{
// Clear listbox
ListView1.DataSource = new DataTable();
ListView1.DataBind();
switch (ddlSearchType.SelectedValue)
{
case "Trefwoorden":
SearchKeyword();
break;
case "Titel":
SearchTitle();
break;
case "Inhoud":
SearchContent();
break;
}
}
</code></pre>
<p>Method that fills the ListView</p>
<pre><code> private void SearchTitle()
{
// Make panel visible
pnlResult.Visible = true;
pnlKeyword.Visible = false;
Search Search = new Search(txtSearchFor.Text);
ListView1.DataSource = Search.SearchTitle();
ListView1.DataBind();
}
</code></pre> | 435,528 | 12 | 1 | null | 2009-01-12 13:18:50.613 UTC | 3 | 2019-10-18 20:32:24.56 UTC | 2013-11-25 15:54:33.15 UTC | Martijn | 321,731 | Martijn | 40,676 | null | 1 | 30 | c#|listview | 124,063 | <p>How about</p>
<pre><code>DataSource = null;
DataBind();
</code></pre> |
396,439 | Radio/checkbox alignment in HTML/CSS | <p>What is the cleanest way to align properly radio buttons / checkboxes with text? The only reliable solution which I have been using so far is table based:</p>
<pre><code><table>
<tr>
<td><input type="radio" name="opt"></td>
<td>Option 1</td>
</tr>
<tr>
<td><input type="radio" name="opt"></td>
<td>Option 2</td>
</tr>
</table>
</code></pre>
<p>This may be frown upon by some. I’ve just spent some time (again) investigating a tableless solution but failed. I’ve tried various combinations of floats, absolute/relative positioning and similar approaches. Not only that they mostly relied silently on an estimated height of the radio buttons / checkboxes, but they also behaved differently in different browsers. Ideally, I would like to find a solution which does not assume anything about sizes or special browser quirks. I’m fine with using tables, but I wonder where there is another solution.</p> | 890,463 | 13 | 3 | null | 2008-12-28 17:40:07.32 UTC | 28 | 2017-06-22 10:31:43.013 UTC | 2009-05-20 21:57:13.653 UTC | Jan Zich | 73,603 | Jan Zich | 15,716 | null | 1 | 79 | html|css|checkbox|radio-button | 257,937 | <p>I think I have finally solved the problem. One commonly recommended solution is to use vertical-align: middle:</p>
<pre><code><input type="radio" style="vertical-align: middle"> Label
</code></pre>
<p>The problem, however, is that this still produces visible misalignments even though it should theoretically work. The CSS2 specification says that:</p>
<blockquote>
<p><strong>vertical-align: middle:</strong> Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.</p>
</blockquote>
<p>So it should be in the perfect centre (the x-height is the height of the character x). However, the problem seems to be caused by the fact browsers commonly add some random uneven margins to radio buttons and checkboxes. One can check, for instance in Firefox using Firebug, that the default checkbox margin in Firefox is <code>3px 3px 0px 5px</code>. I'm not sure where it comes from, but the other browsers seem to have similar margins as well. So to get a perfect alignment, one needs to get rid of these margins:</p>
<pre><code><input type="radio" style="vertical-align: middle; margin: 0px;"> Label
</code></pre>
<p>It is still interesting to note that in the table based solution the margins are somehow eaten and everything aligns nicely.</p> |
116,654 | Non-C++ languages for generative programming? | <p>C++ is probably the most popular language for <a href="https://stackoverflow.com/questions/112277/best-intro-to-c-static-metaprogramming">static metaprogramming</a> and <a href="https://stackoverflow.com/questions/112320/is-static-metaprogramming-possible-in-java">Java doesn't support it</a>.</p>
<p>Are there any other languages besides C++ that support generative programming (programs that create programs)?</p> | 116,661 | 15 | 2 | null | 2008-09-22 18:34:53.573 UTC | 11 | 2020-08-16 10:05:48.677 UTC | 2017-05-23 12:06:49.553 UTC | Chris | -1 | jwfearn | 10,559 | null | 1 | 24 | haskell|lisp|clojure|metaprogramming|boo | 3,921 | <p>The alternative to template style meta-programming is Macro-style that you see in various Lisp implementations. I would suggest downloading <a href="http://www.paulgraham.com/onlisp.html" rel="noreferrer">Paul Graham's <em>On Lisp</em></a> and also taking a look at <a href="http://clojure.org" rel="noreferrer">Clojure</a> if you're interested in a Lisp with macros that runs on the JVM.</p>
<p>Macros in Lisp are much more powerful than C/C++ style and constitute a language in their own right -- they are meant for meta-programming.</p> |
1,276 | How big can a MySQL database get before performance starts to degrade | <p>At what point does a MySQL database start to lose performance?</p>
<ul>
<li>Does physical database size matter?</li>
<li>Do number of records matter?</li>
<li>Is any performance degradation linear or exponential?</li>
</ul>
<p>I have what I believe to be a large database, with roughly 15M records which take up almost 2GB. Based on these numbers, is there any incentive for me to clean the data out, or am I safe to allow it to continue scaling for a few more years?</p> | 1,338 | 15 | 0 | null | 2008-08-04 14:31:11.41 UTC | 115 | 2020-07-27 16:27:23.98 UTC | 2016-01-27 23:40:20.297 UTC | null | 3,664,960 | null | 30 | null | 1 | 332 | mysql|database|database-performance | 212,244 | <p>The physical database size doesn't matter. The number of records don't matter.</p>
<p>In my experience the biggest problem that you are going to run in to is not size, but the number of queries you can handle at a time. Most likely you are going to have to move to a master/slave configuration so that the read queries can run against the slaves and the write queries run against the master. However if you are not ready for this yet, you can always tweak your indexes for the queries you are running to speed up the response times. Also there is a lot of tweaking you can do to the network stack and kernel in Linux that will help.</p>
<p>I have had mine get up to 10GB, with only a moderate number of connections and it handled the requests just fine.</p>
<p>I would focus first on your indexes, then have a server admin look at your OS, and if all that doesn't help it might be time to implement a master/slave configuration.</p> |
604,831 | Collection was modified; enumeration operation may not execute | <p>I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur.</p>
<blockquote>
<p>Collection was modified; enumeration operation may not execute</p>
</blockquote>
<p>Below is the code.</p>
<p>This is a WCF server in a Windows service. The method <code>NotifySubscribers()</code> is called by the service whenever there is a data event (at random intervals, but not very often - about 800 times per day).</p>
<p>When a Windows Forms client subscribes, the subscriber ID is added to the subscribers dictionary, and when the client unsubscribes, it is deleted from the dictionary. The error happens when (or after) a client unsubscribes. It appears that the next time the <code>NotifySubscribers()</code> method is called, the <code>foreach()</code> loop fails with the error in the subject line. The method writes the error into the application log as shown in the code below. When a debugger is attached and a client unsubscribes, the code executes fine.</p>
<p>Do you see a problem with this code? Do I need to make the dictionary thread-safe?</p>
<pre><code>[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class SubscriptionServer : ISubscriptionServer
{
private static IDictionary<Guid, Subscriber> subscribers;
public SubscriptionServer()
{
subscribers = new Dictionary<Guid, Subscriber>();
}
public void NotifySubscribers(DataRecord sr)
{
foreach(Subscriber s in subscribers.Values)
{
try
{
s.Callback.SignalData(sr);
}
catch (Exception e)
{
DCS.WriteToApplicationLog(e.Message,
System.Diagnostics.EventLogEntryType.Error);
UnsubscribeEvent(s.ClientId);
}
}
}
public Guid SubscribeEvent(string clientDescription)
{
Subscriber subscriber = new Subscriber();
subscriber.Callback = OperationContext.Current.
GetCallbackChannel<IDCSCallback>();
subscribers.Add(subscriber.ClientId, subscriber);
return subscriber.ClientId;
}
public void UnsubscribeEvent(Guid clientId)
{
try
{
subscribers.Remove(clientId);
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Unsubscribe Error " +
e.Message);
}
}
}
</code></pre> | 604,843 | 16 | 2 | null | 2009-03-03 02:01:58.987 UTC | 192 | 2021-01-27 13:50:32.38 UTC | 2020-06-29 22:58:59.81 UTC | null | 1,127,428 | cdonner | 58,880 | null | 1 | 1,112 | c#|wcf|concurrency|dictionary|thread-safety | 874,516 | <p>What's likely happening is that <code>SignalData</code> is indirectly changing the subscribers dictionary under the hood during the loop and leading to that message. You can verify this by changing</p>
<pre><code>foreach(Subscriber s in subscribers.Values)
</code></pre>
<p>To</p>
<pre><code>foreach(Subscriber s in subscribers.Values.ToList())
</code></pre>
<p>If I'm right, the problem will disappear.</p>
<p>Calling <code>subscribers.Values.ToList()</code> copies the values of <code>subscribers.Values</code> to a separate list at the start of the <code>foreach</code>. Nothing else has access to this list (it doesn't even have a variable name!), so nothing can modify it inside the loop.</p> |
187,998 | Row Offset in SQL Server | <p>Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it's possible to do:</p>
<pre><code>SELECT * FROM MyTable OFFSET 50 LIMIT 25
</code></pre>
<p>to get results 51-75. This construct does not appear to exist in SQL Server. </p>
<p>How can I accomplish this without loading all the rows I don't care about? Thanks! </p> | 188,044 | 17 | 1 | null | 2008-10-09 16:13:03.757 UTC | 70 | 2021-08-29 00:22:54.803 UTC | 2017-05-25 17:35:44.043 UTC | null | 5,969,411 | null | 420 | null | 1 | 143 | sql|sql-server | 239,998 | <p>I would avoid using <code>SELECT *</code>. Specify columns you actually want even though it may be all of them.</p>
<p><strong>SQL Server 2005+</strong></p>
<pre><code>SELECT col1, col2
FROM (
SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
FROM MyTable
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow
</code></pre>
<p><strong>SQL Server 2000</strong></p>
<p><a href="https://web.archive.org/web/20210506081930/http://www.4guysfromrolla.com/webtech/041206-1.shtml" rel="noreferrer">Efficiently Paging Through Large Result Sets in SQL Server 2000</a></p>
<p><a href="https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml" rel="noreferrer">A More Efficient Method for Paging Through Large Result Sets</a></p> |
368,351 | What's the best way to select the minimum value from several columns? | <p>Given the following table in SQL Server 2005:</p>
<pre><code>ID Col1 Col2 Col3
-- ---- ---- ----
1 3 34 76
2 32 976 24
3 7 235 3
4 245 1 792
</code></pre>
<p>What is the best way to write the query that yields the following result (i.e. one that yields the final column - a column containing the minium values out of Col1, Col2, and Col 3 <strong>for each row</strong>)?</p>
<pre><code>ID Col1 Col2 Col3 TheMin
-- ---- ---- ---- ------
1 3 34 76 3
2 32 976 24 24
3 7 235 3 3
4 245 1 792 1
</code></pre>
<p><strong><em>UPDATE:</em></strong></p>
<p>For clarification (as I have said in the coments) in the real scenario the database is <strong>properly normalized</strong>. These "array" columns are not in an actual table but are in a result set that is required in a report. And the new requirement is that the report also needs this MinValue column. I can't change the underlying result set and therefore I was looking to T-SQL for a handy "get out of jail card".</p>
<p>I tried the CASE approach mentioned below and it works, although it is a bit cumbersome. It is also more complicated than stated in the answers because you need to cater for the fact that there are two min values in the same row.</p>
<p>Anyway, I thought I'd post my current solution which, given my constraints, works pretty well. It uses the UNPIVOT operator:</p>
<pre><code>with cte (ID, Col1, Col2, Col3)
as
(
select ID, Col1, Col2, Col3
from TestTable
)
select cte.ID, Col1, Col2, Col3, TheMin from cte
join
(
select
ID, min(Amount) as TheMin
from
cte
UNPIVOT (Amount for AmountCol in (Col1, Col2, Col3)) as unpvt
group by ID
) as minValues
on cte.ID = minValues.ID
</code></pre>
<p>I'll say upfront that I don't expect this to offer the best performance, but given the circumstances (I can't redesign all the queries just for the new MinValue column requirement), it is a pretty elegant "get out of jail card".</p> | 368,381 | 20 | 2 | null | 2008-12-15 13:27:23.257 UTC | 22 | 2021-07-19 23:43:12.853 UTC | 2016-11-25 10:09:20.317 UTC | stucampbell | 87,015 | stucampbell | 21,379 | null | 1 | 105 | sql|sql-server|tsql|sql-server-2005|min | 307,498 | <p>There are likely to be many ways to accomplish this. My suggestion is to use Case/When to do it. With 3 columns, it's not too bad. </p>
<pre><code>Select Id,
Case When Col1 < Col2 And Col1 < Col3 Then Col1
When Col2 < Col1 And Col2 < Col3 Then Col2
Else Col3
End As TheMin
From YourTableNameHere
</code></pre> |
302,122 | jQuery Event Keypress: Which key was pressed? | <p>With jQuery, how do I find out which key was pressed when I bind to the keypress event?</p>
<pre><code>$('#searchbox input').bind('keypress', function(e) {});
</code></pre>
<p>I want to trigger a submit when <kbd>ENTER</kbd> is pressed.</p>
<p><strong>[Update]</strong></p>
<p>Even though I found the (or better: one) answer myself, there seems to be some room for variation ;)</p>
<p>Is there a difference between <code>keyCode</code> and <code>which</code> - especially if I'm just looking for <kbd>ENTER</kbd>, which will never be a unicode key?</p>
<p>Do some browsers provide one property and others provide the other one? </p> | 302,161 | 24 | 9 | null | 2008-11-19 14:59:19.133 UTC | 206 | 2021-07-12 15:55:14.037 UTC | 2016-05-04 17:55:55.01 UTC | BlaM | 6,273,193 | BlaM | 999 | null | 1 | 729 | javascript|jquery|events|bind|keypress | 846,228 | <p>Actually this is better:</p>
<pre><code> var code = e.keyCode || e.which;
if(code == 13) { //Enter keycode
//Do something
}
</code></pre> |
6,818,875 | New Line on PHP CLI | <p>I have a php CLI script and cannot get the output to break on new lines. I do</p>
<pre><code>echo 'this is my text\r\n';
echo 'next line';
</code></pre>
<p>This gives</p>
<pre><code>this is my text\r\nnext line
</code></pre>
<p>Any ideas about how to get the output on different lines?</p> | 6,818,900 | 4 | 1 | null | 2011-07-25 15:54:33.833 UTC | 15 | 2018-04-04 10:14:56.95 UTC | 2011-07-25 16:00:26.577 UTC | null | 280,598 | null | 671,639 | null | 1 | 126 | php | 104,590 | <p>Use double quotes <code>"</code>.</p>
<pre><code>echo "next line\n";
</code></pre>
<p>Additional you can use the system-dependent constant <code>PHP_EOL</code></p>
<pre><code>echo "this is my text" . PHP_EOL;
</code></pre> |
6,894,322 | How to make git-diff and git log ignore new and deleted files? | <p>Sometimes there's a couple of changed files together with some new, deleted and/or renamed files. When doing <code>git diff</code> or <code>git-log</code> I'd like to omit them, so I can better spot the modifications.</p>
<p>Actually, listing the names of the new and deleted files without their content would be best. For "old" renamed to "new" I'd like to optionally get the difference between "old" and "new".</p> | 6,896,699 | 4 | 0 | null | 2011-08-01 04:50:25.423 UTC | 29 | 2022-02-19 23:30:09.5 UTC | null | null | null | null | 581,205 | null | 1 | 205 | git|git-diff | 39,748 | <p>The <code>--diff-filter</code> option works with both <code>diff</code> and log.</p>
<p>I use <code>--diff-filter=M</code> a lot which restricts diff outputs to only content modifications.</p>
<p>To detect renames and copies and use these in the diff output, you can use <code>-M</code> and <code>-C</code> respectively, together with the <code>R</code> and <code>C</code> options to <code>--diff-filter</code>.</p> |
6,920,175 | How to generate java classes from WSDL file | <p>I am working towards an android application. I need to use a web service. I have a wsdl file but I want to convert that into java so that I can use its functions in my Java programs.
Is there any way of converting a wsdl file into Java?</p> | 6,920,255 | 8 | 1 | null | 2011-08-03 00:01:31.717 UTC | 12 | 2018-12-10 11:49:26.793 UTC | 2011-08-03 00:09:10.533 UTC | null | 5,640 | null | 833,590 | null | 1 | 26 | java|android|web-services|wsdl | 118,228 | <p>Yes you can use:</p>
<p><a href="http://sourceforge.net/projects/wsdl2javawizard/" rel="noreferrer">Wsdl2java eclipse plugin</a></p>
<p>With this all you will need is to supply the wsdl, and the client which is the Java classes will be automatically generated for you.</p> |
6,843,951 | Which way is best for creating an object in JavaScript? Is `var` necessary before an object property? | <p>So far I saw three ways for creating an object in JavaScript. Which way is best for creating an object and why?</p>
<p>I also saw that in all of these examples the keyword <code>var</code> is not used before a property — why? Is it not necessary to declare <code>var</code> before the name of a property as it mentioned that properties are variables?</p>
<p>In the second and third way, the name of the object is in upper-case whereas in the first way the name of the object is in lower-case. What case should we use for an object name?</p>
<h3>First way:</h3>
<pre><code>function person(fname, lname, age, eyecolor){
this.firstname = fname;
this.lastname = lname;
this.age = age;
this.eyecolor = eyecolor;
}
myFather = new person("John", "Doe", 50, "blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</code></pre>
<h3>Second way:</h3>
<pre><code>var Robot = {
metal: "Titanium",
killAllHumans: function(){
alert("Exterminate!");
}
};
Robot.killAllHumans();
</code></pre>
<h3>Third way — JavaScript objects using array syntax:</h3>
<pre><code>var NewObject = {};
NewObject['property1'] = value;
NewObject['property2'] = value;
NewObject['method'] = function(){ /* function code here */ }
</code></pre> | 6,844,046 | 8 | 6 | null | 2011-07-27 12:03:18.877 UTC | 119 | 2019-06-23 02:42:03.667 UTC | 2018-09-17 08:40:26.69 UTC | null | 4,642,212 | null | 368,035 | null | 1 | 180 | javascript|object | 170,618 | <p>There is no <em>best</em> way, it depends on your use case.</p>
<ul>
<li>Use <em>way 1</em> if you want to create several similar objects. In your example, <code>Person</code> (you should start the name with a capital letter) is called the <em>constructor function</em>. This is similar to <em>classes</em> in other OO languages.</li>
<li>Use <em>way 2</em> if you only need <em>one object</em> of a kind (like a singleton). If you want this object to inherit from another one, then you have to use a constructor function though.</li>
<li>Use <em>way 3</em> if you want to initialize properties of the object depending on other properties of it or if you have dynamic property names.</li>
</ul>
<p><strong>Update:</strong> As requested examples for the third way.</p>
<p>Dependent properties:</p>
<p>The following does not work as <code>this</code> does <strong>not</strong> refer to <code>book</code>. There is no way to initialize a property with values of other properties in a object literal:</p>
<pre><code>var book = {
price: somePrice * discount,
pages: 500,
pricePerPage: this.price / this.pages
};
</code></pre>
<p>instead, you could do:</p>
<pre><code>var book = {
price: somePrice * discount,
pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;
</code></pre>
<p>Dynamic property names:</p>
<p>If the property name is stored in some variable or created through some expression, then you have to use bracket notation:</p>
<pre><code>var name = 'propertyName';
// the property will be `name`, not `propertyName`
var obj = {
name: 42
};
// same here
obj.name = 42;
// this works, it will set `propertyName`
obj[name] = 42;
</code></pre> |
6,846,191 | Connecting Tomcat server to Eclipse | <p>I am trying to use Tomcat 6.0 as a web development server within SpringSource Tool Suite 2.7.1. I create a runtime, download tomcat, create a server, etc as per these instructions <a href="http://www.ibm.com/developerworks/opensource/library/os-eclipse-tomcat/index.html#N10148" rel="noreferrer">http://www.ibm.com/developerworks/opensource/library/os-eclipse-tomcat/index.html#N10148</a></p>
<p>When I try to run a web app on the server though I get the following error:</p>
<pre><code>The archive: /Servers/Tomcat/bin/bootstrap.jar which is referenced
by the classpath, does not exist.
</code></pre>
<p>I know this bootstrap.jar file does exist in the exact place it says it should be yet it still causes an error. Any ideas?</p> | 8,123,995 | 12 | 5 | null | 2011-07-27 14:36:29.503 UTC | 2 | 2019-04-04 16:10:43.583 UTC | 2011-07-27 15:51:52.21 UTC | null | 308,474 | null | 308,474 | null | 1 | 12 | eclipse|tomcat | 56,052 | <p>The trick here was that the location of the jar was inside the Eclipse/STS project directory. STS stores its server configurations inside the /Servers folder and I had decided to store the tomcat runtimes here as well for neatness. Placing the runtimes elsewhere and trying again solves this issue.</p> |
42,378,987 | Configure CORS for Azure Functions Local Host | <p>I'm testing an Azure Functions app locally with the Azure Functions CLI tooling. Is there any way I can configure CORS settings for the local host? </p> | 42,750,529 | 4 | 6 | null | 2017-02-21 22:13:12.563 UTC | 7 | 2019-09-08 11:30:19.273 UTC | 2017-11-30 15:33:57.273 UTC | null | 1,878,728 | null | 7,532 | null | 1 | 40 | azure|cors|azure-functions | 22,755 | <p>You can start the host like this</p>
<pre><code>func host start --cors *
</code></pre>
<p>You can also be more specific and provide a comma delimited list of allowed urls</p>
<p>More here: <a href="https://github.com/Azure/azure-webjobs-sdk-script/issues/1012" rel="noreferrer">https://github.com/Azure/azure-webjobs-sdk-script/issues/1012</a></p> |
42,530,261 | JavaScript button onclick not working | <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="hello()">Hello</button>
<script>
function hello() {
alert('Hello');
}
</script></code></pre>
</div>
</div>
</p>
<p>This is my code. But it's not working. When I click on the button nothing happens.</p> | 42,530,289 | 9 | 15 | null | 2017-03-01 11:16:00.19 UTC | 2 | 2022-09-20 14:37:41.047 UTC | 2017-03-01 11:41:49.353 UTC | null | 19,068 | null | 5,538,535 | null | 1 | 9 | javascript|html|function|button|onclick | 119,548 | <p>How about this?</p>
<pre><code><button id="hellobutton">Hello</button>
<script>
function hello() {
alert('Hello');
}
document.getElementById("hellobutton").addEventListener("click", hello);
</script>
</code></pre>
<p>P.S. You should place hello() above of the button.</p> |
15,861,669 | Using "constexpr" to use string literal for template parameter | <p>I have written some code to cast <code>const char*</code> to <code>int</code> by using <code>constexpr</code> and thus I can use a <code>const char*</code> as a template argument. Here is the code:</p>
<pre><code>#include <iostream>
class conststr
{
public:
template<std::size_t N>
constexpr conststr(const char(&STR)[N])
:string(STR), size(N-1)
{}
constexpr conststr(const char* STR, std::size_t N)
:string(STR), size(N)
{}
constexpr char operator[](std::size_t n)
{
return n < size ? string[n] : 0;
}
constexpr std::size_t get_size()
{
return size;
}
constexpr const char* get_string()
{
return string;
}
//This method is related with Fowler–Noll–Vo hash function
constexpr unsigned hash(int n=0, unsigned h=2166136261)
{
return n == size ? h : hash(n+1,(h * 16777619) ^ (string[n]));
}
private:
const char* string;
std::size_t size;
};
// output function that requires a compile-time constant, for testing
template<int N> struct OUT
{
OUT() { std::cout << N << '\n'; }
};
int constexpr operator "" _const(const char* str, size_t sz)
{
return conststr(str,sz).hash();
}
int main()
{
OUT<"A dummy string"_const> out;
OUT<"A very long template parameter as a const char*"_const> out2;
}
</code></pre>
<p>In this example code, type of <code>out</code> is <code>OUT<1494474505></code> and type of <code>out2</code> is <code>OUT<106227495></code>. Magic behind this code is <code>conststr::hash()</code> it is a <code>constexpr</code> recursion that uses <a href="http://isthe.com/chongo/tech/comp/fnv/" rel="noreferrer">FNV Hash function</a>. And thus it creates an integral hash for const char* which is hopefully a unique one.
<br><br>
I have some questions about this method:<br></p>
<ol>
<li>Is this a safe approach to use? Or can this approach be an evil in a specific use?</li>
<li>Can you write a better hash function that creates different integer for each string without being limited to a number of chars? (in my method, the length is long enough)</li>
<li>Can you write a code that implicitly casts <code>const char*</code> to <code>int constexpr</code> via <code>conststr</code> and thus we will not need aesthetically ugly (and also time consumer) <code>_const</code> user-defined string literal? For example <code>OUT<"String"></code> will be legal (and cast "String" to integer).</li>
</ol>
<p>Any help will be appreciated, thanks a lot.</p> | 15,862,594 | 2 | 2 | null | 2013-04-07 11:05:24.067 UTC | 12 | 2017-07-15 08:06:28.837 UTC | 2013-04-07 13:26:35.727 UTC | null | 1,970,249 | null | 1,970,249 | null | 1 | 27 | c++|templates|c++11|string-literals|constexpr | 16,990 | <p>Although your method is very interesting, it is not really a way to pass a string literal as a template argument. In fact, it is a generator of template argument based on string literal, which is not the same: you cannot retrieve <code>string</code> from <code>hashed_string</code>... It kinda defeats the whole interest of string literals in templates.</p>
<p><strong>EDIT</strong> : the following was right when the hash used was the weighted sum of the letters, which is not the case after the edit of the OP.</p>
<blockquote>
<p>You can also have problems with your <a href="https://stackoverflow.com/questions/34595/what-is-a-good-hash-function">hash function</a>, as stated by mitchnull's answer. This may be another big problem with your method, the collisions. For example:</p>
<pre><code>// Both outputs 3721
OUT<"0 silent"_const> out;
OUT<"7 listen"_const> out2;
</code></pre>
</blockquote>
<p>As far as I know, you cannot pass a string literal in a template argument straightforwardly in the current standard. However, you can "fake" it. Here's what I use in general:</p>
<pre><code>struct string_holder //
{ // All of this can be heavily optimized by
static const char* asString() // the compiler. It is also easy to generate
{ // with a macro.
return "Hello world!"; //
} //
}; //
</code></pre>
<p>Then, I pass the "fake string literal" via a type argument:</p>
<pre><code>template<typename str>
struct out
{
out()
{
std::cout << str::asString() << "\n";
}
};
</code></pre>
<p><strong>EDIT2</strong>: you said in the comments you used this to distinguish between several specializations of a class template. The method you showed is valid for that, but you can also use tags:</p>
<pre><code>// tags
struct myTag {};
struct Long {};
struct Float {};
// class template
template<typename tag>
struct Integer
{
// ...
};
template<> struct Integer<Long> { /* ... */ };
// use
Integer<Long> ...; // those are 2
Integer<Float> ...; // different types
</code></pre> |
15,505,607 | Diagonal labels orientation on x-axis in heatmap(s) | <p>Creating heatmaps in R has been a topic of many posts, discussions and iterations. My main problem is that it's tricky to combine visual flexibility of solutions available in lattice <code>levelplot()</code> or basic graphics <code>image()</code>, with effortless clustering of basic's <code>heatmap()</code>, pheatmap's <code>pheatmap()</code> or gplots' <code>heatmap.2()</code>. It's a tiny detail I want to change - diagonal orientation of labels on x-axis. Let me show you my point in the code.</p>
<pre><code>#example data
d <- matrix(rnorm(25), 5, 5)
colnames(d) = paste("bip", 1:5, sep = "")
rownames(d) = paste("blob", 1:5, sep = "")
</code></pre>
<p>You can change orientation to diagonal easily with <code>levelplot()</code>:</p>
<pre><code>require(lattice)
levelplot(d, scale=list(x=list(rot=45)))
</code></pre>
<p><img src="https://i.stack.imgur.com/rRjDm.png" alt="enter image description here"></p>
<p>but applying the clustering seems pain. So does other visual options like adding borders around heatmap cells. </p>
<p>Now, shifting to actual <code>heatmap()</code> related functions, clustering and all basic visuals are super-simple - almost no adjustment required:</p>
<pre><code>heatmap(d)
</code></pre>
<p><img src="https://i.stack.imgur.com/mWk7J.png" alt="enter image description here"></p>
<p>and so is here:</p>
<pre><code>require(gplots)
heatmap.2(d, key=F)
</code></pre>
<p><img src="https://i.stack.imgur.com/79s3i.png" alt="enter image description here"></p>
<p>and finally, my favourite one:</p>
<pre><code>require(pheatmap)
pheatmap(d)
</code></pre>
<p><img src="https://i.stack.imgur.com/G171E.png" alt="enter image description here"></p>
<p>But all of those have <strong>no option to rotate the labels</strong>. Manual for <code>pheatmap</code> suggests that I can use <code>grid.text</code> to custom-orient my labels. What a joy it is - especially when clustering and changing the ordering of displayed labels. Unless I'm missing something here... </p>
<p>Finally, there is an old good <code>image()</code>. I can rotate labels, in general it' most customizable solution, but no clustering option.</p>
<pre><code>image(1:nrow(d),1:ncol(d), d, axes=F, ylab="", xlab="")
text(1:ncol(d), 0, srt = 45, labels = rownames(d), xpd = TRUE)
axis(1, label=F)
axis(2, 1:nrow(d), colnames(d), las=1)
</code></pre>
<p><img src="https://i.stack.imgur.com/JaShF.png" alt="enter image description here"></p>
<p>So what should I do to get my ideal, quick heatmap, with clustering and orientation and nice visual features hacking? My best bid is changing <code>heatmap()</code> or <code>pheatmap()</code> somehow because those two seem to be most versatile in adjustment. But any solutions welcome. </p> | 15,506,652 | 6 | 4 | null | 2013-03-19 16:50:28.907 UTC | 12 | 2019-02-28 06:50:03.823 UTC | null | null | null | null | 618,825 | null | 1 | 30 | r|label|data-visualization|heatmap|lattice | 39,740 | <p>To fix <code>pheatmap</code>, all you really want to do is to go into <code>pheatmap:::draw_colnames</code> and tweak a couple of settings in its call to <code>grid.text()</code>. Here's one way to do that, using <code>assignInNamespace()</code>. (It may need additional adjustments, but you get the picture ;):</p>
<pre><code>library(grid) ## Need to attach (and not just load) grid package
library(pheatmap)
## Your data
d <- matrix(rnorm(25), 5, 5)
colnames(d) = paste("bip", 1:5, sep = "")
rownames(d) = paste("blob", 1:5, sep = "")
## Edit body of pheatmap:::draw_colnames, customizing it to your liking
draw_colnames_45 <- function (coln, ...) {
m = length(coln)
x = (1:m)/m - 1/2/m
grid.text(coln, x = x, y = unit(0.96, "npc"), vjust = .5,
hjust = 1, rot = 45, gp = gpar(...)) ## Was 'hjust=0' and 'rot=270'
}
## For pheatmap_1.0.8 and later:
draw_colnames_45 <- function (coln, gaps, ...) {
coord = pheatmap:::find_coordinates(length(coln), gaps)
x = coord$coord - 0.5 * coord$size
res = textGrob(coln, x = x, y = unit(1, "npc") - unit(3,"bigpts"), vjust = 0.5, hjust = 1, rot = 45, gp = gpar(...))
return(res)}
## 'Overwrite' default draw_colnames with your own version
assignInNamespace(x="draw_colnames", value="draw_colnames_45",
ns=asNamespace("pheatmap"))
## Try it out
pheatmap(d)
</code></pre>
<p><a href="https://i.stack.imgur.com/9gNfN.png"><img src="https://i.stack.imgur.com/9gNfN.png" alt="enter image description here"></a></p> |
15,889,371 | Difference between HttpResponse: SetCookie, AppendCookie, Cookies.Add | <p>there are some different ways to create multi value cookies in ASP.NET:</p>
<pre><code>var cookie = new HttpCookie("MyCookie");
cookie["Information 1"] = "value 1";
cookie["Information 2"] = "value 2";
// first way
Response.Cookies.Add(cookie);
// second way
Response.AppendCookie(cookie);
// third way
Response.SetCookie(cookie);
</code></pre>
<p>When should I use which way? I've read that <code>SetCookie</code> method updates the cookie, if it already exits. Doesn't the other ways update the existing cookie as well?</p>
<p>And is the following code best practice for writing single value cookies?</p>
<p><code>Response.Cookies["MyCookie"].Value = "value";</code></p> | 15,890,244 | 3 | 0 | null | 2013-04-08 21:31:24.103 UTC | 2 | 2017-01-16 12:58:57.817 UTC | 2013-04-08 22:48:01.983 UTC | null | 1,336 | null | 932,492 | null | 1 | 33 | c#|asp.net|cookies | 19,803 | <blockquote>
<p>When should I use which way?</p>
</blockquote>
<p>It's depends on what Cookie operation you want to do.</p>
<p>Note that <code>Add</code> and <code>AppendCookie</code> are doing the same functionality except the fact that with <code>AppendCookie</code> you're not referencing the <code>Cookies</code> property of the <code>Response</code> <code>class</code> and it's doing it for you.</p>
<ul>
<li><code>Response.Cookies.Add</code> - <strong>Adds</strong> the specified cookie to the cookie
collection.</li>
<li><code>Response.AppendCookie</code> - <strong>Adds</strong> an HTTP cookie to the
<strong>intrinsic</strong> cookie collection</li>
<li><code>Response.SetCookie</code> - <strong>Updates</strong> an existing cookie in the cookie
collection.</li>
</ul>
<p><code>Exceptions</code> will not be thrown when duplicates cookies are added or when attempting to update not-exist cookie.</p>
<p>The main <code>exception</code> of these methods is: <code>HttpException</code> (<em>A cookie is appended after the HTTP headers have been sent.</em>)</p>
<p>The Add method allows duplicate cookies in the cookie collection. Use the Set method to ensure the uniqueness of cookies in the cookie collection.</p>
<p>Thanks for <a href="http://msdn.microsoft.com/">MSDN</a>!</p> |
15,707,201 | What database does PhoneGap use and what is the size limit? | <p>I wrote an HTML5 database that abstracts localStorage, indexedDB, and WebSQL. Using straight HTML5 my database options look like this:</p>
<ul>
<li><strong>IE10</strong> - indexedDB - 1GB max</li>
<li><strong>FireFox</strong> - indexedDB - unlimited </li>
<li><strong>Safari</strong> - WebSQL - 50MB max</li>
<li><strong>Chrome</strong> - IndexedDB (or Web SQL) - unlimited (with the HTML5 Quota API <a href="https://developers.google.com/chrome/whitepapers/storage" rel="nofollow noreferrer">ref1</a>, <a href="http://updates.html5rocks.com/2011/11/Quota-Management-API-Fast-Facts" rel="nofollow noreferrer">ref2</a>)</li>
<li><strong>Opera</strong> - WebSQL (until they switch to webkit?) - unlimited</li>
</ul>
<p>I would like to expand the maximum database size using PhoneGap or the Quota API. From PhoneGap's documentation it looks like the current <a href="http://docs.phonegap.com/en/1.2.0/phonegap_storage_storage.md.html" rel="nofollow noreferrer">PhoneGap database ecosphere</a> is:</p>
<ul>
<li><strong>WebSQL</strong> - Android, Blackberry, iPhone, and webOS</li>
<li><strong>localStorage</strong> - Windows Phone 7</li>
<li><strong>indexedDB</strong> - <a href="https://stackoverflow.com/questions/14624482/phonegap-sqlite-or-indexed-db">Windows Phone 8</a> and, i am guessing, everywhere indexedDB is available but WebSQL isn't.</li>
</ul>
<p>There are also the PhoneGap SqlLite plugins. <a href="https://github.com/brodyspark/PhoneGap-sqlitePlugin-iOS" rel="nofollow noreferrer">iOS</a>, <a href="https://github.com/brodyspark/PhoneGap-SQLitePlugin-Android" rel="nofollow noreferrer">Android</a>, <a href="https://github.com/marcucio/Cordova-WP-SqlitePlugin" rel="nofollow noreferrer">Windows Phone 8+</a></p>
<hr>
<p><strong>QUESTION 1</strong> - Is my understanding of what database PhoneGap will use accurate?</p>
<p><strong>QUESTION 2</strong> - Is there any solid documentation about how much data a PhoneGap database of a given type will store? *If it is a PhoneGap database and not the browsers database implementation.</p>
<p><strong>QUESTION 3</strong> - Does PhoneGap have plans to adhere to the the <a href="http://www.w3.org/TR/webstorage/" rel="nofollow noreferrer">Web Storage standards</a> thereby dropping WebSQL in favor of indexedDB? If so, will I still be able to use my existing WebSQL code (via a built in PhoneGap-polyfill) once the switch to indexedDB is made?</p>
<p><strong>QUESTION 4</strong> - In situations where database size is limited and cannot be expanded by either PhoneGap or the Quota API, but access to the file system is available, is it reasonable to assume that "extra" data could be stored on the device's file system or on a SD card?</p> | 15,812,335 | 3 | 2 | null | 2013-03-29 16:24:09.013 UTC | 32 | 2016-08-20 00:14:07.417 UTC | 2017-05-23 12:09:47.823 UTC | null | -1 | null | 1,873,073 | null | 1 | 67 | cordova|mobile|offline | 34,665 | <blockquote>
<p>Is my understanding of what database PhoneGap will use accurate?</p>
</blockquote>
<p>Yes it is. PhoneGap can use LocalStorage, SessionStorage, or SQLite databases. You can also, alternatively use PhoneGap to connect to the devices native classes via a plugin, and pass the native class data, that it will then store on the device. </p>
<blockquote>
<p>Is there any solid documentation about how much data a PhoneGap database of a given type will store? If it is a PhoneGap database and not the browsers database implementation.</p>
</blockquote>
<ol>
<li>LocalStorage :: 10MB</li>
<li>SessionStorage :: 10MB</li>
<li>SQLite Database :: 50MB-80MB (depends on the device)</li>
<li>Native Database using plugin call :: Unlimited data amount</li>
<li>IndexedDB :: 5MB. Still existant. But very buggy, <a href="http://caniuse.com/indexeddb" rel="nofollow noreferrer">theres a list of devices/OS's that run it here</a></li>
</ol>
<blockquote>
<p>Does PhoneGap have plans to adhere to the the Web Storage standards thereby dropping WebSQL in favor of indexedDB? If so, will I still be able to use my existing WebSQL code (via a built in PhoneGap-polyfill) once the switch to indexedDB is made?</p>
</blockquote>
<p>WebSQL is slowly being deprecated. Its replacement is IndexedDB or SQLite. The best option for you, however, is either SQLite or the Native Database (for example Core Data on the iOS)</p>
<blockquote>
<p>In situations where database size is limited and cannot be expanded by either PhoneGap or the Quota API, but access to the file system is available, is it reasonable to assume that "extra" data could be stored on the device's file system or on a SD card?</p>
</blockquote>
<p>It is definitely possible. </p>
<ul>
<li>On Android you can specify the location of the database, and therefore push data to an external database. </li>
<li>On iOS, you can use the native database call to store data on CoreData, there is no external memory. </li>
<li>In all cases of all OS's, you can create a flat database file, like a Text file, store your data in key-value lists, and then pull those into your app at first run. Beware of the memory management in this case. </li>
</ul>
<p>I've added an explanation of how to go about coding for the SQLite and LocalStorage databases in <a href="https://stackoverflow.com/questions/12005042/phonegap-offline-database/15811728#15811728">my answer</a>.</p> |
50,932,518 | How to modify request body before reaching controller in spring boot | <p>I have a spring boot application.
I change the request body of every post request.
Is it possible to modify the request body before the request reaches the controller.
Please include an example.</p> | 50,933,530 | 6 | 2 | null | 2018-06-19 15:58:32.737 UTC | 14 | 2022-07-06 11:44:24.38 UTC | 2018-06-19 16:42:21.873 UTC | null | 453,005 | null | 9,020,593 | null | 1 | 21 | java|spring|spring-boot | 40,722 | <p><strong>Short Answer</strong><br>
Yes, but not easily.</p>
<p><strong>Details</strong><br>
I know of three options to change the body of a request
"before" it arrives at the handler method in the controller;</p>
<ol>
<li>Use AOP to change the request before the method is called.</li>
<li>Create an HTTP filter.</li>
<li>Create a custom Spring HandlerInterceptor.</li>
</ol>
<p>Since you are already using spring-boot,
option 3, custom Spring HandlerInterceptor,
seems like the best option for you.</p>
<p>Here is a link to a <a href="http://www.baeldung.com/spring-mvc-handlerinterceptor" rel="noreferrer">Baeldung Article</a> covering spring HandlerInterceptors.</p>
<p>The Baeldung article is not the full answer for your problem
because you can only read the <code>InputStrem</code> returned by <code>HttpServletRequest</code> one time.</p>
<p>You will need to create a wrapper class that extends <code>HttpServletRequest</code>
and wrap every request in your wrapper class within your custom HandlerInterceptor or in a custom Filter (Filter might be the way to go here).</p>
<p><strong><em>Wrapper Class</em></strong></p>
<ol>
<li>Read the <code>HttpServletRequest</code> InputStream in the wrapper class constructor</li>
<li>Modify the body per your requirements.</li>
<li>Write the modified body to a <code>ByteArrayOutputStream</code>.</li>
<li>Use <code>toByteArray</code> to retrieve the actual <code>byte[]</code> from the stream.</li>
<li>Close the ByteArrayOutputStream (try-with-resources is good for this).</li>
<li>Override the <code>getInputStream</code> method.</li>
<li>Wrap the <code>byte[]</code> in a ByteArrayInputStream every time the <code>getInputStream</code> is called. Return this stream.</li>
</ol>
<p><strong>How To Wrap the Request</strong></p>
<ol>
<li>In your Filter, instantiate your wrapper class and pass in the original request (which is a parameter to the doFilter method).</li>
<li>Pass the wrapper to the chain.doFilter method (not the original request).</li>
</ol> |
50,907,542 | Download a file from asset folder when clicking on a button | <p>I am working on an angular2 project, I have a file in assets folder and I have created a button to download the file while running the app. </p>
<p>I see there are quite a many solutions to the above problem so i got confused. Can you please help.</p>
<pre class="lang-xml prettyprint-override"><code><button pButton type="button" (click)="f1()" label="Download Sample Defaults
XML File"></button>
</code></pre>
<p>I need code for f1() which can help me download the file to my Download folder when clicking on above button. Help appreciated. Thanks</p> | 50,907,707 | 5 | 2 | null | 2018-06-18 10:33:56.16 UTC | 2 | 2021-05-18 03:32:09.037 UTC | 2019-09-17 12:34:45.313 UTC | null | 430,885 | null | 2,537,297 | null | 1 | 21 | angular|angular2-services|angular-http | 53,989 | <p>You can either style an anchor element to look like a button and set it's href to assets/file</p>
<pre class="lang-xml prettyprint-override"><code><a href="assets/file">Download here</a>
</code></pre>
<p>Or create an anchor element on the fly, set it's href element and click it.</p>
<p>Something like:</p>
<pre class="lang-typescript prettyprint-override"><code>let link = document.createElement('a');
link.setAttribute('type', 'hidden');
link.href = 'assets/file';
link.download = path;
document.body.appendChild(link);
link.click();
link.remove();
</code></pre> |
10,306,673 | Securing a password in a properties file | <p>I have a java application that connects to a database.<br>
The user name and password for the database are stored in a properties file.<br>
What is the common practice to avoid storing the password in cleartext in the properties file while still retaining the option to let the user change it?<br>
The main motivation here is to prevent someone looking over the admin's shoulder and seeing the password while the admin is editing the properties file.<br>
I read <a href="https://stackoverflow.com/q/4155187/162056">here</a> that there's a built in way to do it in C#.<br>
Knowing java, I don't expect to find a built in solution but I'd like to hear what other people are doing.<br>
If I don't find any good choice then I am probably going to encrypt it with a constant password that will be kept in the code. But I'd hate to do it this way because it feels wrong.</p>
<p><strong>Edit Dec 12th 2012</strong>
Looks like there is no magic and I must store the password in the code or something similar.
At the end we implemented something very similar to what Jasypt that was mentioned in one of the answers does.
So I'm accepting the Jasypt answer because it is the closest thing to a definite answer.</p> | 10,307,724 | 4 | 10 | null | 2012-04-24 22:01:32.103 UTC | 45 | 2017-03-20 14:54:29.417 UTC | 2017-05-23 11:47:13.56 UTC | null | -1 | null | 162,056 | null | 1 | 73 | java|security | 149,098 | <h1><a href="http://www.jasypt.org" rel="noreferrer"><img src="https://i.stack.imgur.com/oEt2m.png" alt="enter image description here"></a></h1>
<p><strong>Jasypt provides the <a href="http://www.jasypt.org/api/jasypt/1.8/org/jasypt/properties/EncryptableProperties.html" rel="noreferrer">org.jasypt.properties.EncryptableProperties</a> class for loading, managing and transparently decrypting encrypted values in .properties files, allowing the mix of both encrypted and not-encrypted values in the same file.</strong></p>
<p><a href="http://www.jasypt.org/encrypting-configuration.html" rel="noreferrer">http://www.jasypt.org/encrypting-configuration.html</a></p>
<blockquote>
<p>By using an org.jasypt.properties.EncryptableProperties object, an
application would be able to correctly read and use a .properties file
like this:</p>
</blockquote>
<pre><code>datasource.driver=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://localhost/reportsdb
datasource.username=reportsUser
datasource.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm)
</code></pre>
<blockquote>
<p>Note that
the database password is encrypted (in fact, any other property could
also be encrypted, be it related with database configuration or not).</p>
<p>How do we read this value? like this:</p>
</blockquote>
<pre><code>/*
* First, create (or ask some other component for) the adequate encryptor for
* decrypting the values in our .properties file.
*/
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("jasypt"); // could be got from web, env variable...
/*
* Create our EncryptableProperties object and load it the usual way.
*/
Properties props = new EncryptableProperties(encryptor);
props.load(new FileInputStream("/path/to/my/configuration.properties"));
/*
* To get a non-encrypted value, we just get it with getProperty...
*/
String datasourceUsername = props.getProperty("datasource.username");
/*
* ...and to get an encrypted value, we do exactly the same. Decryption will
* be transparently performed behind the scenes.
*/
String datasourcePassword = props.getProperty("datasource.password");
// From now on, datasourcePassword equals "reports_passwd"...
</code></pre> |
22,599,069 | What is the content compression resistance and content hugging of a UIView? | <p>What is the content compression resistance and content hugging of a UIView? How do these relate to the intrinsic content size of a view?</p> | 22,599,070 | 1 | 2 | null | 2014-03-24 00:25:31.653 UTC | 67 | 2016-02-09 09:13:49.523 UTC | null | null | null | null | 796,419 | null | 1 | 63 | ios|cocoa-touch|uiview|autolayout | 41,351 | <p>Taken from <a href="http://www.objc.io" rel="noreferrer">objc.io</a>'s excellent <a href="http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html" rel="noreferrer">Advanced Auto Layout Toolbox article</a>:</p>
<blockquote>
<p><strong>Intrinsic Content Size</strong></p>
<p>The intrinsic content size is the size a view prefers to have for a specific content it displays. For example, UILabel has a preferred height based on the font, and a preferred width based on the font and the text it displays. A UIProgressView only has a preferred height based on its artwork, but no preferred width. A plain UIView has neither a preferred width nor a preferred height.</p>
<p><strong>Compression Resistance and Content Hugging</strong></p>
<p>Each view has content
compression resistance priorities and content hugging priorities
assigned for both dimensions. These properties only take effect for
views which define an intrinsic content size, otherwise there is no
content size defined that could resist compression or be hugged.</p>
<p>Behind the scenes, the intrinsic content size and these priority
values get translated into constraints. For a label with an intrinsic
content size of { 100, 30 }, horizontal/vertical compression
resistance priority of 750, and horizontal/vertical content hugging
priority of 250, four constraints will be generated:</p>
<pre><code>H:[label(<=100@250)]
H:[label(>=100@750)]
V:[label(<=30@250)]
V:[label(>=30@750)]
</code></pre>
<p>If you’re not familiar with the visual format language for the
constraints used above, you can read up about it in Apple’s
documentation. Keeping in mind that these additional constraints are
generated implicitly helps to understand Auto Layout’s behavior and to
make better sense of its error messages.</p>
</blockquote>
<p>Here's another StackOverflow question that addresses the difference between content compression resistance & content hugging:
<a href="https://stackoverflow.com/questions/15850417/cocoa-autolayout-content-hugging-vs-content-compression-resistance-priority">Cocoa Autolayout: content hugging vs content compression resistance priority</a></p> |
13,235,306 | Method called after release Exception Camera preview | <p>I have one activity class(CameraActivity) which is using my CameraPreview class. In "OnResume" the camera and preview are initiated. In "OnPause", i am releasing camera resources. When application is started, everything works fine inside the "OnResume" but when i start another activity through intent (E.g. open url in browser) and then come back to my activity then exception is occured inside "OnResume" originating CamerPreview class. Please find below the code:</p>
<p><strong>//CameraActivity class</strong></p>
<pre><code>public void onResume(){
super.onResume();
Log.d("inside onResume, camera==="+mCamera, "inside onResume");
try {
if(mCamera==null)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
autoFocusHandler = new Handler();
mCamera = getCameraInstance();
int rotation = this.getWindowManager().getDefaultDisplay().getRotation();
scanner = new ImageScanner();
scanner.setConfig(0, Config.X_DENSITY, 3);
scanner.setConfig(0, Config.Y_DENSITY, 3);
mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
preview.addView(mPreview);
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("onResume",Log.getStackTraceString(e));
}
public void onPause{
try {
super.onPause();
if (mCamera != null) {
previewing = false;
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
mPreview=null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("releaseCamera",Log.getStackTraceString(e));
}
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open();
} catch (Exception e){
Log.e("getCameraInstance",Log.getStackTraceString(e));
}
return c;
}
</code></pre>
<p><strong>// Following is CameraPreview Class:</strong></p>
<pre><code>public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
Camera mCamera;
PreviewCallback previewCallback;
AutoFocusCallback autoFocusCallback;
private int rotation;
public int getRotation() {
return rotation;
}
public void setRotation(int rotation) {
this.rotation = rotation;
}
public CameraPreview(Context context, Camera camera,
PreviewCallback previewCb,
AutoFocusCallback autoFocusCb) {
super(context);
mCamera = camera;
previewCallback = previewCb;
autoFocusCallback = autoFocusCb;
/*
* Set camera to continuous focus if supported, otherwise use
* software auto-focus. Only works for API level >=9.
*/
/*
Camera.Parameters parameters = camera.getParameters();
for (String f : parameters.getSupportedFocusModes()) {
if (f == Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) {
mCamera.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
autoFocusCallback = null;
break;
}
}
*/
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
if(mCamera==null){
mCamera=Camera.open();
}
mCamera.setPreviewDisplay(holder);
} catch (IOException e) {
Log.d("DBG", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Camera preview released in activity
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
/*
* If your preview can change or rotate, take care of those events here.
* Make sure to stop the preview before resizing or reformatting it.
*/
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.setPreviewCallback(previewCallback);
mCamera.startPreview();
mCamera.autoFocus(autoFocusCallback);
} catch (Exception e){
Log.d("DBG", "Error starting camera preview: " + e.getMessage());
}
}
}
</code></pre>
<p><strong>This is from logCat:</strong></p>
<pre><code>11-05 10:14:34.585: E/AndroidRuntime(7864): FATAL EXCEPTION: main
11-05 10:14:34.585: E/AndroidRuntime(7864): java.lang.RuntimeException: Method called after release()
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.hardware.Camera.setPreviewDisplay(Native Method)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.hardware.Camera.setPreviewDisplay(Camera.java:393)
11-05 10:14:34.585: E/AndroidRuntime(7864): at com.intagleo.qraugmented.detection.camera.CameraPreview.surfaceCreated(CameraPreview.java:74)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.SurfaceView.updateWindow(SurfaceView.java:552)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:215)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.ViewRoot.performTraversals(ViewRoot.java:790)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.os.Looper.loop(Looper.java:130)
11-05 10:14:34.585: E/AndroidRuntime(7864): at android.app.ActivityThread.main(ActivityThread.java:3687)
11-05 10:14:34.585: E/AndroidRuntime(7864): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 10:14:34.585: E/AndroidRuntime(7864): at java.lang.reflect.Method.invoke(Method.java:507)
11-05 10:14:34.585: E/AndroidRuntime(7864): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-05 10:14:34.585: E/AndroidRuntime(7864): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-05 10:14:34.585: E/AndroidRuntime(7864): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p><strong>EDIT</strong></p>
<p>I updated "surfaceDestroyed" and put logs as suggested but now i am getting exception in "onPause" --> onSurfaceDestroyed. Initially onPause was executing fine. </p>
<p>1- The camera instance is created in "onResume" of activity class through method "getCameraInstance" and passes mCamera instance to CameraPreview Class. I tried to change it so that camera instance is created only onside "onSurfaceCreated" and assigned back the mCamera instance to the activity class but it did not work. I also noticed through debug that previewCallBack member of "CameraPreview" class is valid the first time but second time the "previewCallBack" member of "CameraPreview" class is null.</p>
<p>Note that first time when "onResume" is called, everything works fine but when it runs second time after onPause then exception is occured originally although code is the same in onResume.</p>
<pre><code>11-06 01:25:28.375: I/onResume(4332): INITIATED
// Workinf fine till now. Now opening another intent activity
11-06 01:26:23.500: I/onPause(4332): INITIATED
11-06 01:26:23.804: "OnSurfaceDestroyed": "Initiated"
11-06 01:26:23.945: E/AndroidRuntime(4332): FATAL EXCEPTION: main
11-06 01:26:23.945: E/AndroidRuntime(4332): java.lang.RuntimeException: Method called after release()
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.hardware.Camera.stopPreview(Native Method)
11-06 01:26:23.945: E/AndroidRuntime(4332): at com.intagleo.qraugmented.detection.camera.CameraPreview.surfaceDestroyed(CameraPreview.java:85)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.SurfaceView.reportSurfaceDestroyed(SurfaceView.java:596)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.SurfaceView.updateWindow(SurfaceView.java:490)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:215)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.ViewRoot.performTraversals(ViewRoot.java:790)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.os.Handler.dispatchMessage(Handler.java:99)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.os.Looper.loop(Looper.java:130)
11-06 01:26:23.945: E/AndroidRuntime(4332): at android.app.ActivityThread.main(ActivityThread.java:3687)
11-06 01:26:23.945: E/AndroidRuntime(4332): at java.lang.reflect.Method.invokeNative(Native Method)
11-06 01:26:23.945: E/AndroidRuntime(4332): at java.lang.reflect.Method.invoke(Method.java:507)
11-06 01:26:23.945: E/AndroidRuntime(4332): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-06 01:26:23.945: E/AndroidRuntime(4332): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-06 01:26:23.945: E/AndroidRuntime(4332): at dalvik.system.NativeStart.main(Native Method)
</code></pre> | 16,487,366 | 7 | 5 | null | 2012-11-05 15:33:58.443 UTC | 11 | 2017-04-03 06:12:24.887 UTC | 2012-11-06 06:21:27.493 UTC | null | 420,613 | null | 420,613 | null | 1 | 11 | android|camera | 20,164 | <p>As you have added the camera to the FrameLayout, like this:</p>
<pre><code>FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
preview.addView(mPreview);
</code></pre>
<p>The <code>surfaceCreated</code> method will be called and so <code>mCamera.setPreviewDisplay(holder);</code> will be called.</p>
<p>When you create/open a new camera, the <code>FrameLayout</code> still has your previous camera and so its <code>surfaceCreated</code> will be called in addition to your new camera.</p>
<p>What you should do, is remove your previous camera from <code>FrameLayout</code> when you release your camera (on <code>onPause()</code> method) like this:</p>
<pre><code>preview.removeView(mPreview);
</code></pre>
<p>Hope it helps.</p> |
13,361,489 | Differences between an array and any collection from the java Collection framework? | <p>As the title say I am looking into the "Differences between an array and any collection from the java Collection framework".</p>
<p>Thought it's high level enough to provide some good understanding to a few (or many) of us who know too little about this or need to think far too long to come up with a interesting answer</p>
<p>So far, I have come up with:</p>
<ol>
<li>Collection framework classes either use array underneath or use more complex data structure. When an array is simply...an array</li>
<li>Array does not have methods (no API) such as the ones provided by Collection classes.</li>
</ol>
<p>Please correct me if these were incorrect assumptions, and of course add your own answers</p> | 13,380,073 | 4 | 5 | null | 2012-11-13 13:23:45.117 UTC | 9 | 2018-08-15 18:50:45.15 UTC | null | null | null | null | 759,452 | null | 1 | 16 | java|arrays|collections | 36,484 | <p>They are virtually unreleated, except to say they both store a group of values. </p>
<p>From a capability perspective, while both can store references to objects:</p>
<ul>
<li>Arrays can store primitives</li>
<li>Collections can <strong>not</strong> store primitives (although they can store the primitive wrapper classes, such as <code>Integer</code> etc)</li>
</ul>
<p>One important difference, commonly not understood by programmers new to java, is one of usability and convenience, especially given that Collections automatically expand in size when needed:</p>
<ul>
<li>Arrays - Avoid using them unless you <em>have</em> to</li>
<li>Collections - Use them in preference to arrays</li>
</ul>
<p>Arrays are ultimately the only way of storing a group of primitives/references in one object, but they are the most basic option. Although arrays may give you some speed advantages, unless you <em>need</em> super-fast code, Collections are preferred because they have so much convenience.</p> |
13,447,882 | Python 2.7 creating a multidimensional list | <p>In Python I want an intuitive way to create a 3 dimensional list.</p>
<p>I want an (n by n) list. So for n = 4 it should be:</p>
<pre><code>x = [[[],[],[],[]],[[],[],[],[]],[[],[],[],[]],[[],[],[],[]]]
</code></pre>
<p>I've tried using:</p>
<pre><code>y = [n*[n*[]]]
y = [[[]]* n for i in range(n)]
</code></pre>
<p>Which both appear to be creating copies of a reference.
I've also tried naive application of the list builder with little success:</p>
<pre><code>y = [[[]* n for i in range(n)]* n for i in range(n)]
y = [[[]* n for i in range(1)]* n for i in range(n)]
</code></pre>
<p>I've also tried building up the array iteratively using loops, with no success. I also tried this:</p>
<pre><code>y = []
for i in range(0,n):
y.append([[]*n for i in range(n)])
</code></pre>
<p>Is there an easier or more intuitive way of doing this?</p> | 13,448,022 | 13 | 1 | null | 2012-11-19 04:56:18.197 UTC | 7 | 2021-05-29 14:34:32.807 UTC | 2016-04-18 19:44:33.693 UTC | null | 445,131 | null | 1,506,079 | null | 1 | 19 | python|list|python-2.7|list-comprehension | 98,712 | <p>I think your list comprehension versions were very close to working. You don't need to do any list multiplication (which doesn't work with empty lists anyway). Here's a working version:</p>
<pre><code>>>> y = [[[] for i in range(n)] for i in range(n)]
>>> print y
[[[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], [], []]]
</code></pre> |
13,369,829 | Access my entire browsing history via Javascript | <p>If i click on the history tab on my browser I can reach a folder with all of the links ive visited organized by date.</p>
<p>How can I access this programmatically with Javascript? I'm still new to Javascript but I want something like:</p>
<pre><code>var aListOfDateLinkPairs = window.history.some_get_list_function;
</code></pre>
<p>I'm sure this is a big privacy issue for some arbitrary entity but what If I want to implement this (programmatically) for myself in my own browser?</p>
<p>Thanks!</p> | 13,369,907 | 4 | 5 | null | 2012-11-13 22:16:49.327 UTC | 6 | 2022-01-19 00:01:47.267 UTC | null | null | null | null | 648,927 | null | 1 | 20 | javascript | 76,869 | <p>In general history is protected by the browser against javascript accessing it except through back and forward functionality. There are some hacks that can view some amount of history, but they are just that--hacks.</p>
<p>If you want to view/modify history programatically, you could do so via browser plugins. For example, Chrome plugins can use <a href="http://developer.chrome.com/extensions/history.html" rel="noreferrer">this API</a></p>
<p>EDIT</p>
<p>Mozilla also has some info about history modification available to Javascript <a href="https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history" rel="noreferrer">here</a>.</p>
<p>It also looks like <a href="https://stackoverflow.com/questions/12901076/accessing-history-in-a-firefox-addon">this question</a> talks about some of the same things you need.</p> |
13,388,586 | This app failed to launch because of an issue with its license | <p>I'm happily in the middle of coding then I try to launch my app in debug mode but I get this error message.</p>
<blockquote>
<p>Unable to activate Windows Store app</p>
<p>This app failed to launch because of an issue with its license</p>
</blockquote>
<p>The app was launching fine a few minutes earlier so this came as a surprise. I tried restarting Visual Studio but doing so did not help.</p>
<p>I got the annoying "renew your developer license" dialog yesterday I think. It had renewed without issue.</p>
<p>How do I make this error message go away so i can debug my app?</p> | 13,388,697 | 7 | 0 | null | 2012-11-14 22:36:32.177 UTC | 3 | 2015-12-16 06:02:29.297 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 122,781 | null | 1 | 30 | visual-studio-2012|windows-store-apps | 7,611 | <p>Well, I got it working by deleting the main project's 'bin' and 'obj' folders. Cleaning and Rebuilding wasn't enough. Hope this answer saves someone else the few minutes of confusion I just experienced. </p> |
13,503,079 | How to create a copy of a python function | <p>Is there a possibility to create real copies of python functions? The most obvious choice was <a href="http://docs.python.org/2/library/copy.html">http://docs.python.org/2/library/copy.html</a> but there I read:</p>
<blockquote>
<p>It does “copy” functions and classes (shallow and deeply), by
returning the original object unchanged;</p>
</blockquote>
<p>I need a real copy, because I might change some attributes of the function.</p>
<p><strong>Update:</strong></p>
<p>I'm aware of all the possibilities which are mentioned in the comments. My use case is based on meta programming where I construct classes out of some declarative specifications. Complete details would be too long for SO, but basically I have a function like</p>
<pre><code>def do_something_usefull(self,arg):
self.do_work()
</code></pre>
<p>I will add this method to various classes. Thoses classes can be completly unrelated. Using mixin classes is not an option: I will have many such functions and would end up adding a base class for each function. My current "workaround" would be to wrap this function in a "factory" like this:</p>
<pre><code>def create_do_something():
def do_something_usefull(self,arg):
self.do_work()
</code></pre>
<p>That way I always get a new do_something_useful function, but I have to wrap all my functions like this.</p>
<p>You can trust me, that I'm aware, that this is no "normal" OO programming. I know how to solve something like that "normally". But this is a dynamic code generator and I would like to keep everything as lightweight and simple as possible. And as python functions are quite normal objects, I don't think it's too strange to ask how to copy them!?</p> | 13,503,277 | 1 | 11 | null | 2012-11-21 22:26:19.903 UTC | 6 | 2019-02-19 13:11:00.937 UTC | 2012-11-21 22:46:37.317 UTC | null | 110,963 | null | 110,963 | null | 1 | 34 | python|deep-copy | 24,495 | <p>In <strong>Python3</strong>:</p>
<pre><code>import types
import functools
def copy_func(f):
"""Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)"""
g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__,
argdefs=f.__defaults__,
closure=f.__closure__)
g = functools.update_wrapper(g, f)
g.__kwdefaults__ = f.__kwdefaults__
return g
def f(arg1, arg2, arg3, kwarg1="FOO", *args, kwarg2="BAR", kwarg3="BAZ"):
return (arg1, arg2, arg3, args, kwarg1, kwarg2, kwarg3)
f.cache = [1,2,3]
g = copy_func(f)
print(f(1,2,3,4,5))
print(g(1,2,3,4,5))
print(g.cache)
assert f is not g
</code></pre>
<p>yields</p>
<pre><code>(1, 2, 3, (5,), 4, 'BAR', 'BAZ')
(1, 2, 3, (5,), 4, 'BAR', 'BAZ')
[1, 2, 3]
</code></pre>
<hr>
<p>In <strong>Python2</strong>:</p>
<pre><code>import types
import functools
def copy_func(f):
"""Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)"""
g = types.FunctionType(f.func_code, f.func_globals, name=f.func_name,
argdefs=f.func_defaults,
closure=f.func_closure)
g = functools.update_wrapper(g, f)
return g
def f(x, y=2):
return x,y
f.cache = [1,2,3]
g = copy_func(f)
print(f(1))
print(g(1))
print(g.cache)
assert f is not g
</code></pre>
<p>yields</p>
<pre><code>(1, 2)
(1, 2)
[1, 2, 3]
</code></pre> |
13,350,938 | Attempt to present * on * whose view is not in the window hierarchy | <p>I'm trying to make a modal view controller in my app delegate (I created a function called showLoginView). But whenever I try to call it I get a warning in XCode:</p>
<pre><code>Warning: Attempt to present <PSLoginViewController: 0x1fda2b40> on <PSViewController: 0x1fda0720> whose view is not in the window hierarchy!
</code></pre>
<p>Here's the method code:</p>
<pre><code>- (void)showLoginView
{
PSLoginViewController *loginViewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:NULL] instantiateViewControllerWithIdentifier:@"PSLoginViewController"];
[self.window.rootViewController presentViewController:loginViewController animated:NO completion:nil];
}
</code></pre>
<p>How can I add the view to the window hierarchy? Or maybe I'm doing something very wrong?</p> | 13,350,989 | 7 | 0 | null | 2012-11-12 20:20:41.957 UTC | 8 | 2018-05-08 13:06:51.213 UTC | 2012-11-13 05:44:27.167 UTC | null | 893,113 | null | 1,297,756 | null | 1 | 36 | objective-c|ios|cocoa-touch|ios6 | 50,276 | <p>You can't display a modal view controller from the appDelegate. You need to display a modal ViewController from whichever viewController is currently displaying full-screen. In other words, you need to put that code into your root view controller, or whichever one you want to display the modal vc from...</p>
<p>Also, you'll want to use the method "presentModalViewController" to present the modal. You can set properties on the modal vc such as:</p>
<pre><code>vC.modalPresentationStyle = UIModalPresentationFormSheet;
vC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:vC animated:YES];
</code></pre> |
39,871,883 | systemctl status shows inactive dead | <p>I am trying to write my own (simple) systemd service which does something simple.( Like writing numbers 1 to 10 to a file, using the shell script).
My service file looks like below.</p>
<pre><code>[Unit]
Description=NandaGopal
Documentation=https://google.com
After=multi-user.target
[Service]
Type=forking
RemainAfterExit=yes
ExecStart=/usr/bin/hello.sh &
[Install]
RequiredBy = multi-user.target
</code></pre>
<p>This is my shell script.</p>
<pre><code>#!/usr/bin/env bash
source /etc/profile
a=0
while [ $a -lt 10 ]
do
echo $a >> /var/log//t.txt
a=`expr $a + 1`
done
</code></pre>
<p>For some reason, the service doesn't come up and systemctl is showing the below output.</p>
<pre><code>root@TARGET:~ >systemctl status -l hello
* hello.service - NandaGopal
Loaded: loaded (/usr/lib/systemd/system/hello.service; disabled; vendor preset: enabled)
Active: inactive (dead)
Docs: https://google.com
</code></pre>
<p>Been trying to figure out what went wrong for the last 2 days.</p> | 39,874,893 | 2 | 4 | null | 2016-10-05 10:45:37.043 UTC | 8 | 2020-11-18 16:33:24.987 UTC | 2020-11-18 16:33:24.987 UTC | null | 124,486 | null | 1,386,864 | null | 1 | 29 | linux|sh|systemd|systemctl | 107,974 | <ul>
<li>You have set <code>Type=Forking</code>, but your service doesn't work. Try <code>
Type=oneshot</code></li>
<li>You have a "&" your <code>ExecStart</code> line, which is not necessary. </li>
<li>The service is <code>disabled</code>, which means it was not <code>enabled</code> to start at boot. You should run <code>systemctl enable hello</code> to set it to start at boot.</li>
</ul>
<p>You can check <code>man systemd.directives</code> to find an index of all the directives that you can use in your <code>unit</code> files.</p> |
9,122,592 | ElementName Binding is failing | <p>I have the following XAML:</p>
<pre><code><Grid>
<Grid.RowDefinitions>
...
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" ...>
<DataGrid.Columns>
...
</DataGrid.Columns>
</DataGrid>
<DockPanel Grid.Row="2">
<CheckBox x:Name="DisplayMarkers" DockPanel.Dock="Top" Content="Display Data Points?"
Margin="8,5,0,5" d:LayoutOverrides="Height" HorizontalAlignment="Left" IsChecked="False" />
<vf:Chart DockPanel.Dock="Top" ScrollingEnabled="False" ZoomingEnabled="True" ToolBarEnabled="True">
<vf:DataSeries AxisYType="Secondary" RenderAs="Line" DataSource="{Binding CdTeRoughnessList}"
XValueType="DateTime"
MarkerEnabled="{Binding ElementName=DisplayMarkers, Path=IsChecked}" Color="Navy"
LegendText="Roughness Std. Dev.">
</code></pre>
<p>This binding is failing: <code>MarkerEnabled="{Binding ElementName=DisplayMarkers, Path=IsChecked}"</code></p>
<p>I'm trying to bind to the IsChecked property on my Checkbox named 'DisplayMarkers". When I run this, in debug mode in VS 2010, the output window shows the binding is failing. It can't find the element named 'Checkbox'. Could anyone tell me why?</p>
<p>The error I'm getting from VS is:</p>
<pre><code>System.Windows.Data Error: 4 : Cannot find source for binding with reference
'ElementName=DisplayMarkers'. BindingExpression:Path=IsChecked; DataItem=null; target element is 'DataSeries' (Name=''); target property is 'MarkerEnabled' (type 'Nullable`1')
</code></pre> | 9,122,644 | 3 | 2 | null | 2012-02-03 01:34:42.947 UTC | 18 | 2021-03-03 14:14:20.04 UTC | 2012-02-03 01:43:31.513 UTC | null | 546,730 | null | 418,384 | null | 1 | 45 | wpf|xaml|data-binding | 27,789 | <p>You might not have a namescope where you try to bind, you could try to replace the <code>ElementName</code> construct with <code>Source={x:Reference DisplayMarkers}</code>.</p>
<p>The gist of it is that if you have elements in XAML which are not in the visual or logical tree you will not be able to use certain bindings like <code>RelativeSource</code> and <code>ElementName</code>, I suspect that <code>DataSeries</code> is not in any tree either (it sure sounds like it's abstract).</p>
<p>For a workaround for potential cyclical dependency errors see: <a href="https://stackoverflow.com/a/6858917/546730">https://stackoverflow.com/a/6858917/546730</a></p> |
16,205,788 | jQuery append text inside of an existing paragraph tag | <p>I am trying to add additional text to the end of a paragraph using jQuery. My thought was to produce a structure like this:</p>
<p><strong>Judging by my answers I will clarify. I need to create this structure first. And this is the part that I find difficult, not the second end result. So how do I dynamically create this:</strong></p>
<pre><code><p>old-dynamic-text<span id="add_here"></span></p>
</code></pre>
<p>And then after adding the new text it would look like this:</p>
<pre><code><p>old-dynamic-text<span id="add_here">new-dynamic-text</span></p>
</code></pre>
<p>I've been playing with the .wrapAll() method, but I can't quite get the desired effect. Is this the best way to do this (and if so how), or is there another way to append new text to the end of an existing paragraph (that needs to be wrapped in some type of tag since I need to style it differently)?</p> | 16,205,824 | 4 | 0 | null | 2013-04-25 03:18:23.017 UTC | 7 | 2018-11-08 10:15:36.353 UTC | 2013-04-25 03:26:23.867 UTC | null | 1,888,503 | null | 1,888,503 | null | 1 | 23 | jquery|append|wrapall | 121,230 | <p>Try this...</p>
<pre><code>$('p').append('<span id="add_here">new-dynamic-text</span>');
</code></pre>
<p>OR if there is an existing span, do this.</p>
<pre><code>$('p').children('span').text('new-dynamic-text');
</code></pre>
<p><a href="http://jsfiddle.net/maheshsapkal/xXCFv/" rel="noreferrer"><strong>DEMO</strong></a></p> |
16,459,954 | Understanding the "additionalProperties" keyword in JSON Schema draft version 4 | <p>Link to the specification: <a href="http://json-schema.org/latest/json-schema-validation.html#anchor64">http://json-schema.org/latest/json-schema-validation.html#anchor64</a></p>
<p>Section 5.4.4.2 states:</p>
<blockquote>
<p>Successful validation of an object instance against these three keywords depends on the value of "additionalProperties": if its value is boolean true or a schema, validation succeeds; ...</p>
</blockquote>
<p>Section 5.4.4.3 states:</p>
<blockquote>
<p>If "additionalProperties" is absent, it may be considered present with an empty schema as a value.</p>
</blockquote>
<p>Ok, so if "additionalProperties" is absent, it counts as being present with an empty schema. And if it's a schema (of any kind), then the object validates successfully regardless of any other consideration.</p>
<p>But this is contradicted by the assertion in section 5.4.4.5, "Example", that the given instance fails to validate against the given schema (which doesn't specify anything for "additionalProperties").</p>
<p>Can someone explain where and in what way I'm misinterpreting the specification?</p> | 17,339,316 | 1 | 1 | null | 2013-05-09 10:47:01.057 UTC | 6 | 2014-07-01 10:08:44.77 UTC | null | null | null | null | 340,819 | null | 1 | 35 | json|validation|specifications|jsonschema | 40,611 | <p>You have found an error in the spec, so your not actually misinterpreting something.</p>
<p>There is an updated version (from two days later) of the internet draft on the IETF website, where this example is different.</p>
<p>see: <a href="https://datatracker.ietf.org/doc/html/draft-fge-json-schema-validation-00#page-13" rel="noreferrer">https://datatracker.ietf.org/doc/html/draft-fge-json-schema-validation-00#page-13</a></p>
<p>As the document is an internet draft, most likely the version on <a href="http://datatracker.ietf.org/" rel="noreferrer">http://datatracker.ietf.org/</a> is the correct version.</p>
<blockquote>
<p><strong>Status of This Memo</strong></p>
<p>This Internet-Draft is submitted in full conformance with the<br />
provisions of BCP 78 and BCP 79.</p>
<p><strong>Internet-Drafts</strong> are working documents of the <strong>Internet Engineering<br />
Task Force (IETF)</strong>. Note that other groups may also distribute<br />
working documents as Internet-Drafts. The list of current Internet-<br />
Drafts is at <a href="http://datatracker.ietf.org/drafts/current/" rel="noreferrer">http://datatracker.ietf.org/drafts/current/</a>.</p>
<p>Internet-Drafts are working documents of the Internet Engineering<br />
Task Force (IETF).</p>
</blockquote>
<p>Additionally, the two versions have different dates, and expiry dates:</p>
<ul>
<li>version you link - written: <strong>January 30, 2013</strong> and Expires: <strong>August 3, 2013</strong>.</li>
<li>version on ietf - written on: <strong>February 1, 2013</strong> and Expires: <strong>August 5, 2013</strong></li>
</ul>
<p>On the IETF version:</p>
<blockquote>
<p>This schema will be used as an example:</p>
<pre><code> {
"properties": {
"p1": {}
},
"patternProperties": {
"p": {},
"[0-9]": {}
},
"additionalProperties": false
</code></pre>
<p>This is the instance to validate:</p>
<p>{
"p1": true,
"p2": null,
"a32&o": "foobar",
"": [],
"fiddle": 42,
"apple": "pie" }</p>
<p>The three property sets are:</p>
<pre><code> s [ "p1", "p2", "a32&o", "", "fiddle", "apple" ]
p [ "p1" ]
pp [ "p", "[0-9]" ]
</code></pre>
<p>Applying the two steps of the algorithm:</p>
<pre><code> after the first step, "p1" is removed from "s";
after the second step, "p2" (matched by "p"), "a32&o" (matched by
"[0-9]") and "apple" (matched by "p") are removed from "s".
</code></pre>
<p>The set "s" still contains two elements, "" and "fiddle". Validation
therefore fails.</p>
</blockquote> |
24,723,180 | C convert floating point to int | <p>I'm using <strong>C</strong> (not C++).</p>
<p>I need to convert a float number into an <code>int</code>. I do not want to round to the the nearest number, I simply want to eliminate what is after the integer part. Something like</p>
<pre>4.9 -> 4<strike>.9</strike> -> 4</pre> | 24,723,189 | 5 | 4 | null | 2014-07-13 13:28:01.71 UTC | 6 | 2020-08-29 21:29:47.82 UTC | 2014-07-13 13:44:39.087 UTC | null | 2,886,891 | null | 3,453,682 | null | 1 | 40 | c|casting|floating-point|int|type-conversion | 231,876 | <pre><code>my_var = (int)my_var;
</code></pre>
<p>As simple as that.
Basically you don't need it if the variable is int.</p> |
21,958,155 | modify existing contents of file in c | <pre><code>int main()
{
FILE *ft;
char ch;
ft=fopen("abc.txt","r+");
if(ft==NULL)
{
printf("can not open target file\n");
exit(1);
}
while(1)
{
ch=fgetc(ft);
if(ch==EOF)
{
printf("done");
break;
}
if(ch=='i')
{
fputc('a',ft);
}
}
fclose(ft);
return 0;
}
</code></pre>
<p>As one can see that I want to edit <code>abc.txt</code> in such a way that <code>i</code> is replaced by <code>a</code> in it.<br>
The program works fine but when I open <code>abc.txt</code> externally, it seemed to be unedited.<br>
Any possible reason for that?</p>
<p>Why in this case the character after <code>i</code> is not replace by <code>a</code>, as the answers suggest?</p> | 21,958,378 | 3 | 3 | null | 2014-02-22 18:00:07.78 UTC | 8 | 2014-02-22 19:10:49.65 UTC | 2014-02-22 18:57:20.737 UTC | null | 3,315,585 | null | 3,315,585 | null | 1 | 8 | c|edit|file-handling | 55,457 | <h2>Analysis</h2>
<p>There are multiple problems:</p>
<ol>
<li><p><code>fgetc()</code> returns an <code>int</code>, not a <code>char</code>; it has to return every valid <code>char</code> value plus a separate value, EOF. As written, you can't reliably detect EOF. If <code>char</code> is an unsigned type, you'll never find EOF; if <code>char</code> is a signed type, you'll misidentify some valid character (often ÿ, y-umlaut, U+00FF, LATIN SMALL LETTER Y WITH DIAERESIS) as EOF.</p></li>
<li><p>If you switch between input and output on a file opened for update mode, you must use a file positioning operation (<code>fseek()</code>, <code>rewind()</code>, nominally <code>fsetpos()</code>) between reading and writing; and you must use a positioning operation or <code>fflush()</code> between writing and reading.</p></li>
<li><p>It is a good idea to close what you open (now fixed in the code).</p></li>
<li><p>If your writes worked, you'd overwrite the character after the <code>i</code> with <code>a</code>.</p></li>
</ol>
<h2>Synthesis</h2>
<p>These changes lead to:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *ft;
char const *name = "abc.txt";
int ch;
ft = fopen(name, "r+");
if (ft == NULL)
{
fprintf(stderr, "cannot open target file %s\n", name);
exit(1);
}
while ((ch = fgetc(ft)) != EOF)
{
if (ch == 'i')
{
fseek(ft, -1, SEEK_CUR);
fputc('a',ft);
fseek(ft, 0, SEEK_CUR);
}
}
fclose(ft);
return 0;
}
</code></pre>
<p>There is room for more error checking.</p>
<h2>Exegesis</h2>
<h3>Input followed by output requires seeks</h3>
<p>The <code>fseek(ft, 0, SEEK_CUR);</code> statement is required by the C standard.</p>
<blockquote>
<h3>ISO/IEC 9899:2011 §7.21.5.3 The <code>fopen</code> function</h3>
<p>¶7 When a file is opened with update mode ('+' as the second or third character in the
above list of mode argument values), both input and output may be performed on the
associated stream. <em>However, output shall not be directly followed by input without an
intervening call to the <code>fflush</code> function or to a file positioning function (<code>fseek</code>,
<code>fsetpos</code>, or <code>rewind</code>), and input shall not be directly followed by output without an
intervening call to a file positioning function, unless the input operation encounters end-of-
file.</em> Opening (or creating) a text file with update mode may instead open (or create) a
binary stream in some implementations.</p>
</blockquote>
<p>(Emphasis added.)</p>
<h3><code>fgetc()</code> returns an <code>int</code></h3>
<p>Quotes from ISO/IEC 9899:2011, the current C standard.</p>
<blockquote>
<p><strong>§7.21 Input/output <code><stdio.h></code></strong></p>
<p><strong>§7.21.1 Introduction</strong></p>
<p><code>EOF</code> which expands to an integer constant expression, with type int and a negative value, that
is returned by several functions to indicate end-of-file, that is, no more input from a
stream;</p>
<p><strong>§7.21.7.1 The <code>fgetc</code> function</strong></p>
<p><code>int fgetc(FILE *stream);</code></p>
<p>¶2 If the end-of-file indicator for the input stream pointed to by stream is not set and a
next character is present, the <code>fgetc</code> function obtains that character as an <code>unsigned char</code> converted to an <code>int</code> and advances the associated file position indicator for the
stream (if defined).</p>
<p><strong>Returns</strong></p>
<p>¶3 If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-file indicator for the stream is set and the <code>fgetc</code> function returns EOF. Otherwise, the
<code>fgetc</code> function returns the next character from the input stream pointed to by stream.
If a read error occurs, the error indicator for the stream is set and the <code>fgetc</code> function
returns EOF.<sup>289)</sup></p>
<p><sup>289)</sup> An end-of-file and a read error can be distinguished by use of the <code>feof</code> and <code>ferror</code> functions.</p>
</blockquote>
<p>So, <code>EOF</code> is a negative integer (conventionally it is -1, but the standard does not require that). The <code>fgetc()</code> function either returns EOF or the value of the character as an <code>unsigned char</code> (in the range 0..UCHAR_MAX, usually 0..255).</p>
<blockquote>
<p><strong>§6.2.5 Types</strong></p>
<p>¶3 An object declared as type <code>char</code> is large enough to store any member of the basic
execution character set. If a member of the basic execution character set is stored in a
<code>char</code> object, its value is guaranteed to be nonnegative. If any other character is stored in
a <code>char</code> object, the resulting value is implementation-defined but shall be within the range
of values that can be represented in that type.</p>
<p>¶5 An object declared as type <code>signed char</code> occupies the same amount of storage as a
‘‘plain’’ <code>char</code> object.</p>
<p>§6 For each of the signed integer types, there is a corresponding (but different) unsigned
integer type (designated with the keyword <code>unsigned</code>) that uses the same amount of
storage (including sign information) and has the same alignment requirements.</p>
<p>§15 The three types <code>char</code>, <code>signed char</code>, and <code>unsigned char</code> are collectively called
the character types. The implementation shall define <code>char</code> to have the same range,
representation, and behavior as either <code>signed char</code> or <code>unsigned char</code>.<sup>45)</sup></p>
<p><sup>45)</sup> <code>CHAR_MIN</code>, defined in <code><limits.h></code>, will have one of the values <code>0</code> or <code>SCHAR_MIN</code>, and this can be
used to distinguish the two options. Irrespective of the choice made, <code>char</code> is a separate type from the
other two and is not compatible with either.</p>
</blockquote>
<p>This justifies my assertion that plain <code>char</code> can be a signed or an unsigned type.</p>
<p>Now consider:</p>
<pre><code>char c = fgetc(fp);
if (c == EOF)
…
</code></pre>
<p>Suppose <code>fgetc()</code> returns EOF, and plain <code>char</code> is an unsigned (8-bit) type, and EOF is <code>-1</code>. The assignment puts the value 0xFF into <code>c</code>, which is a positive integer. When the comparison is made, <code>c</code> is promoted to an <code>int</code> (and hence to the value 255), and 255 is not negative, so the comparison fails.</p>
<p>Conversely, suppose that plain <code>char</code> is a signed (8-bit) type and the character set is ISO 8859-15. If <code>fgetc()</code> returns ÿ, the value assigned will be the bit pattern 0b11111111, which is the same as <code>-1</code>, so in the comparison, <code>c</code> will be converted to <code>-1</code> and the comparison <code>c == EOF</code> will return true even though a valid character was read.</p>
<p>You can tweak the details, but the basic argument remains valid while <code>sizeof(char) < sizeof(int)</code>. There are DSP chips where that doesn't apply; you have to rethink the rules. Even so, the basic point remains; <code>fgetc()</code> returns an <code>int</code>, not a <code>char</code>.</p>
<p>If your data is truly ASCII (7-bit data), then all characters are in the range 0..127 and you won't run into the misinterpretation of ÿ problem. However, if your <code>char</code> type is unsigned, you still have the 'cannot detect EOF' problem, so your program will run for a long time. If you need to consider portability, you will take this into account. These are the professional grade issues that you need to handle as a C programmer. You can kludge your way to programs that work on your system for your data relatively easily and without taking all these nuances into account. But your program won't work on other people's systems.</p> |
19,625,563 | matplotlib: change the current axis instance (i.e., gca()) | <p>I use a trick to <a href="http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#colorbar-whose-height-or-width-in-sync-with-the-master-axes">draw a colorbar whose height matches the master axes</a>. The code is like</p>
<pre><code>import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
ax = plt.subplot(111)
im = ax.imshow(np.arange(100).reshape((10,10)))
# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
</code></pre>
<p>This trick works good. However, since a new axis is appended, the current instance of the figure becomes cax - the appended axis. As a result, if one performs operations like</p>
<pre><code>plt.text(0,0,'whatever')
</code></pre>
<p>the text will be drawn on cax instead of ax - the axis to which im belongs.</p>
<p>Meanwhile, gcf().axes shows both axes.</p>
<p>My question is: How to make the current axis instance (returned by gca()) the original axis to which im belongs.</p> | 19,625,774 | 1 | 5 | null | 2013-10-28 00:44:13.35 UTC | 6 | 2018-12-06 19:46:58.657 UTC | null | null | null | null | 795,201 | null | 1 | 56 | python|python-2.7|matplotlib | 37,102 | <p>Use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.sca" rel="noreferrer"><code>plt.sca(ax)</code></a> to set the current axes, where <code>ax</code> is the <code>Axes</code> object you'd like to become active.</p> |
19,464,962 | Understanding how actually drawRect or drawing coordinates work in Android | <p>I am trying to draw a rectangle over a canvas and I am facing troubles to understand the in-depth of rectangle draw of Android. I've read tutorials and every possible but I am stuck.</p>
<p>Here in the image , the red rectangle is my target.
<img src="https://i.stack.imgur.com/GDrf7.png" alt="enter image description here"></p>
<p>Irrespective of any rectangle size I need to draw the red rectangle bit above the base and in the middle of the rectangle. The worst nightmare I am facing here is understanding the X,Y Width and Height coordinates.</p>
<p>Can anyone explain how that math works, sometime we go up , Y reaches to very small but same width coordinates are higher. And I am never able to justify red inner rectangle properly.In some screen it works well in some other it fails. The red rectangle sometimes come out of the parent rectangle.</p>
<p><strong>Agenda is to understand how coordinates work and ensure the integrity of inner red rectangle</strong></p>
<p>It'll be great to get an explanation based on an example. I am using-</p>
<pre><code>void drawRect(float left, float top, float right, float bottom, Paint paint)
</code></pre>
<p>to drawing the rectangle </p> | 19,465,601 | 5 | 7 | null | 2013-10-19 10:21:59.797 UTC | 10 | 2019-07-31 11:54:38.957 UTC | 2013-10-19 10:27:59.02 UTC | null | 552,521 | null | 552,521 | null | 1 | 39 | android|android-layout|android-canvas | 43,004 | <p>X runs horizontally, from left to right. Y runs vertically, from top to bottom. It's exactly the same as on your graphics. So (0/0) is at top left.</p>
<p>When you go "up" Y will of course get smaller, as it grows from top to bottom.</p>
<p>You have to pay attention to laying out elements like ListViews, these will give a partial (or new, you cannot tell) canvas to your views that are drawn. These views will have 0x0 at <strong>their own</strong> top/left position. If you need the absolute you have to subsequently call <code>View.getLocationOnScreen()</code> and calculate offsets yourself.</p> |
17,312,831 | What does request.user refer to in Django? | <p>I have confusion regarding what does <strong>request.user</strong> refers to in Django?
Does it refer to <strong>username</strong> field in the <strong>auth_user</strong> table or does it refer to User model instance?</p>
<p>I had this doubt because I was not able to access email field in the template using <code>{{request.user.username}}</code> or <code>{{user.username}}</code>.</p>
<p>So instead I did following in views file:</p>
<pre><code>userr = User.objects.get(username=request.user)
</code></pre>
<p>And passed <code>userr</code> to the template and accessed email field as <code>{{ userr.email }}</code>.</p>
<p>Although its working but I wanted to have some clarity about it.</p> | 17,313,293 | 4 | 0 | null | 2013-06-26 06:16:25.217 UTC | 6 | 2019-05-16 10:20:02.553 UTC | 2019-05-16 10:20:02.553 UTC | null | 9,609,843 | null | 2,396,413 | null | 1 | 31 | python|django|email|django-templates|django-views | 81,754 | <p>If your template is receiving <a href="https://docs.djangoproject.com/en/1.2/topics/auth/#django.contrib.auth.models.AnonymousUser" rel="noreferrer">AnonymousUser</a>, the reference to <code>{{request.user.email}}</code> will not be found. Previously, you must ask if <code>{{request.user.is_authenticated }}</code>.</p>
<p>You must check if it is included <code>django.core.context_processors.auth</code> context processor in <code>TEMPLATE_CONTEXT_PROCESSORS</code> section of settings. If you are using Django 1.4 or latest, then context processor is <code>django.contrib.auth.context_processors.auth</code>. This context processor is responsible to include user object in every request.</p> |
17,312,545 | Type conversion - unsigned to signed int/char | <p>I tried the to execute the below program:</p>
<pre><code>#include <stdio.h>
int main() {
signed char a = -5;
unsigned char b = -5;
int c = -5;
unsigned int d = -5;
if (a == b)
printf("\r\n char is SAME!!!");
else
printf("\r\n char is DIFF!!!");
if (c == d)
printf("\r\n int is SAME!!!");
else
printf("\r\n int is DIFF!!!");
return 0;
}
</code></pre>
<p>For this program, I am getting the output: </p>
<blockquote>
<p>char is DIFF!!!
int is SAME!!!</p>
</blockquote>
<p>Why are we getting different outputs for both?<br>
Should the output be as below ?</p>
<blockquote>
<p>char is SAME!!!
int is SAME!!! </p>
</blockquote>
<p>A <a href="http://codepad.org/vpBuIbTQ" rel="noreferrer">codepad link</a>.</p> | 17,312,930 | 5 | 2 | null | 2013-06-26 05:58:07.583 UTC | 35 | 2015-03-11 09:48:53.833 UTC | 2015-03-11 09:48:53.833 UTC | null | 183,120 | null | 2,522,685 | null | 1 | 74 | c|types|type-conversion|integer-promotion|signedness | 32,705 | <p>This is because of the various implicit type conversion rules in C. There are two of them that a C programmer must know: <em><a href="http://c0x.coding-guidelines.com/6.3.1.8.html">the usual arithmetic conversions</a></em> and the <em>integer promotions</em> (the latter are part of the former).</p>
<p>In the char case you have the types <code>(signed char) == (unsigned char)</code>. These are both <em>small integer types</em>. Other such small integer types are <code>bool</code> and <code>short</code>. The <em>integer promotion rules</em> state that whenever a small integer type is an operand of an operation, its type will get promoted to <code>int</code>, which is signed. This will happen no matter if the type was signed or unsigned. </p>
<p>In the case of the <code>signed char</code>, the sign will be preserved and it will be promoted to an <code>int</code> containing the value -5. In the case of the <code>unsigned char</code>, it contains a value which is 251 (0xFB ). It will be promoted to an <code>int</code> containing that same value. You end up with </p>
<pre><code>if( (int)-5 == (int)251 )
</code></pre>
<hr>
<p>In the integer case you have the types <code>(signed int) == (unsigned int)</code>. They are not small integer types, so the integer promotions do not apply. Instead, they are balanced by <em>the usual arithmetic conversions</em>, which state that if two operands have the same "rank" (size) but different signedness, the signed operand is converted to the same type as the unsigned one. You end up with</p>
<pre><code>if( (unsigned int)-5 == (unsigned int)-5)
</code></pre> |
36,882,149 | ERROR 1067 (42000): Invalid default value for 'created_at' | <p>When I tried to alter the table it showed the error:</p>
<pre><code>ERROR 1067 (42000): Invalid default value for 'created_at'
</code></pre>
<p>I googled for this error but all I found was as if they tried to alter the timestamp so it occurred. However here I am trying to add a new column and I am getting this error:</p>
<pre><code>mysql> ALTER TABLE investments ADD bank TEXT;
ERROR 1067 (42000): Invalid default value for 'created_at'
</code></pre>
<p>and my table's last two columns are <code>created_at</code> and <code>updated_at</code>.</p>
<p>Here is my table structure:</p>
<p><a href="https://i.stack.imgur.com/BGZon.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BGZon.png" alt="enter image description here"></a></p> | 37,696,251 | 17 | 4 | null | 2016-04-27 06:37:51.277 UTC | 41 | 2022-01-11 05:29:22.277 UTC | 2020-02-11 13:13:50.04 UTC | null | 2,477,990 | null | 3,134,504 | null | 1 | 133 | mysql | 271,806 | <p>The problem is because of <strong>sql_modes</strong>.
Please check your current sql_modes by command:</p>
<pre><code>show variables like 'sql_mode' ;
</code></pre>
<p>And remove the sql_mode "<strong>NO_ZERO_IN_DATE,NO_ZERO_DATE</strong>" to make it work.
This is the default sql_mode in mysql new versions.</p>
<p>You can set sql_mode globally as root by command: </p>
<pre><code>set global sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
</code></pre> |
18,488,680 | Makefile Grammar | <p>Is there anywhere a <em>precise</em> makefile grammar definition? Or at least some common subset since I guess that there are some flavors. Such a grammar that could be used for writing a parser.</p>
<p><a href="http://www.gnu.org/software/make/manual/make.html">GNU Make manual</a> doesn't seem to be that precise. It would require some guessing and trial-and-error to write a parser for makefile based on that document.</p>
<p>I also found a <a href="http://www.antlr3.org/pipermail/antlr-interest/2006-December/018856.html">similar question on ANTLR mail list</a>. But it remained unanswered which kind of suggests the answer...</p> | 18,491,666 | 2 | 1 | null | 2013-08-28 13:00:30.397 UTC | 9 | 2019-02-28 17:03:05.73 UTC | 2013-09-02 07:34:31 UTC | null | 422,489 | null | 422,489 | null | 1 | 26 | makefile|format | 4,306 | <p>It seems there is no official grammar for gnu make, and ...</p>
<blockquote>
<p>It would be tricky to write a grammar for make, since the grammar is
extremely context-dependent.</p>
</blockquote>
<p>As said by Paul D. Smith in <a href="http://www.mail-archive.com/[email protected]/msg02778.html">a message in the gnu make mailing list</a>. Paul D. Smith is the official maintainer of gnu make.</p> |
18,283,199 | Java Main Game Loop | <p>I am writing a game loop, I found the code in the example below <a href="http://www.java-gaming.org/index.php?topic=24220.0" rel="noreferrer">here</a>. I have also looked at other ways to do a game loop, such as from <a href="https://dewitters.com/dewitters-gameloop/" rel="noreferrer">this article</a>. I couldn't get any of those ones working though. So I kept with the one from the first link.</p>
<p>What I would like to know:</p>
<ul>
<li>Is the way I wrote my game loop a good way to do this?
<ul>
<li>Any suggestions?</li>
</ul></li>
<li>Should I be using <code>Thread.sleep();</code> in my game loop?</li>
</ul>
<p>Here is my current code:</p>
<pre><code>public void run(){
long lastLoopTime = System.nanoTime();
final int TARGET_FPS = 60;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
long lastFpsTime = 0;
while(true){
long now = System.nanoTime();
long updateLength = now - lastLoopTime;
lastLoopTime = now;
double delta = updateLength / ((double)OPTIMAL_TIME);
lastFpsTime += updateLength;
if(lastFpsTime >= 1000000000){
lastFpsTime = 0;
}
this.updateGame(delta);
this.repaint();
try{
Room.gameTime = (lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000;
System.out.println(Room.gameTime);
Thread.sleep(Room.gameTime);
}catch(Exception e){
}
}
</code></pre> | 18,283,279 | 3 | 1 | null | 2013-08-16 22:44:45.907 UTC | 15 | 2021-08-18 02:26:22.597 UTC | 2020-03-30 22:24:51.31 UTC | null | 1,529,709 | null | 1,778,465 | null | 1 | 20 | java|game-engine | 66,136 | <p>Eventually you'll want to move to something like <a href="http://www.lwjgl.org/" rel="noreferrer">LWJGL</a>, but let me stress, keep doing what you're doing here for now. It will teach you fundamentals.</p>
<p>Good job on your loop. Looks nice, let me offer a few pointers:</p>
<ul>
<li><p>Repaint will not render the screen immediately. It tells the <a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/RepaintManager.html" rel="noreferrer">RepaintManager</a> to render when its ready. Use <strike>invalidate</strike> <a href="http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#paintImmediately%28int,%20int,%20int,%20int%29" rel="noreferrer">paintImmediately</a> instead. <code>paintImmediately</code> will block execution until the component has been redrawn so you can measure rendering time.</p></li>
<li><p><code>Thread.sleep</code> typically has a few milliseconds drift. You should be using it to keep your loop from using too much CPU, but make sure you understand if you sleep 10 milliseconds you might sleep 5 milliseconds or you might sleep 20.</p></li>
<li><p>Lastly:</p>
<pre><code>double delta = updateLength / ((double)OPTIMAL_TIME);
</code></pre>
<p>If <code>updateLength</code> is less than OPTIMAL_TIME, don't call update. In other words, if delta is less than one, don't update. <a href="http://gafferongames.com/game-physics/fix-your-timestep/" rel="noreferrer">This tutorial</a> explains why better than I ever could.</p></li>
</ul> |
26,379,446 | Padding zeros to the left in postgreSQL | <p>I am relatively new to PostgreSQL and I know how to pad a number with zeros to the left in SQL Server but I'm struggling to figure this out in PostgreSQL.</p>
<p>I have a number column where the maximum number of digits is 3 and the min is 1: if it's one digit it has two zeros to the left, and if it's 2 digits it has 1, e.g. 001, 058, 123.</p>
<p>In SQL Server I can use the following:</p>
<pre><code>RIGHT('000' + cast([Column1] as varchar(3)), 3) as [Column2]
</code></pre>
<p>This does not exist in PostgreSQL. Any help would be appreciated.</p> | 26,379,561 | 4 | 3 | null | 2014-10-15 09:50:09.737 UTC | 18 | 2022-03-10 15:18:20.12 UTC | 2022-03-10 15:18:20.12 UTC | null | 792,066 | null | 2,232,418 | null | 1 | 147 | sql|postgresql | 144,337 | <p>You can use the <code>rpad</code> and <code>lpad</code> functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use <code>::char</code> or <code>::text</code> to cast them:</p>
<pre><code>SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
LPAD(numcol::text, 3, '0') -- Zero-pads to the left up to the length of 3
FROM my_table
</code></pre> |
23,325,389 | Spring Boot enable http requests logging (access logs) | <p>How to enable access logs in an embedded <strong>tomcat</strong> server provided by <strong>spring boot</strong>? I've tried this in <code>application.properties</code> but it doesn't create file, neither logs to console.</p>
<pre><code>server.tomcat.access-log-enabled=true
server.tomcat.access-log-pattern=%a asdasd
logging.file=/home/mati/mylog.log
</code></pre> | 23,333,789 | 5 | 8 | null | 2014-04-27 15:42:25.46 UTC | 9 | 2021-10-06 14:44:16.817 UTC | 2020-05-25 12:43:29.953 UTC | null | 8,718,377 | null | 987,889 | null | 1 | 39 | java|http|tomcat|logging|spring-boot | 45,979 | <p>Try</p>
<pre><code>server.tomcat.accessLogEnabled=true
server.tomcat.accessLogPattern=%a asdasd
</code></pre>
<p>and look in <code>/tmp/tomcat.<random>.<port>/logs</code> for the output files. Set <code>server.tomcat.basedir</code> property to change the directory.</p> |
31,898,311 | Celery difference between concurrency, workers and autoscaling | <p>In my <code>/etc/defaults/celeryd</code> config file, I've set:</p>
<pre><code>CELERYD_NODES="agent1 agent2 agent3 agent4 agent5 agent6 agent7 agent8"
CELERYD_OPTS="--autoscale=10,3 --concurrency=5"
</code></pre>
<p>I understand that the daemon spawns 8 celery workers, but I'm fully not sure what <code>autoscale</code> and <code>concurrency</code> do together. I thought that concurrency was a way to specify the max number of threads that a worker can use and autoscale was a way for the worker to scale up and down child workers, if necessary. </p>
<p>The tasks have a largish payload (some 20-50kB) and there are like 2-3 million such tasks, but each task runs in less than a second. I'm seeing memory usage spike up because the broker distributes the tasks to every worker, thus replicating the payload multiple times. </p>
<p>I think the issue is in the config and that the combination of workers + concurrency + autoscaling is excessive and I would like to get a better understanding of what these three options do.</p> | 32,046,332 | 2 | 12 | null | 2015-08-08 20:35:37.73 UTC | 16 | 2022-05-24 17:09:20.473 UTC | null | null | null | null | 5,206,959 | null | 1 | 86 | python|concurrency|celery | 65,124 | <p>Let's distinguish between workers and worker processes. You spawn a celery worker, this then spawns a number of processes (depending on things like <code>--concurrency</code> and <code>--autoscale</code>, the default is to spawn as many processes as cores on the machine). There is no point in running more than one worker on a particular machine unless you want to do routing.</p>
<p>I would suggest running only 1 worker per machine with the default number of processes. This will reduce memory usage by eliminating the duplication of data between workers. </p>
<p>If you still have memory issues then save the data to a store and pass only an id to the workers. </p> |
5,433,570 | Access a Remote Directory from C# | <p>I am trying to access a remote network share from a C# program in asp.net. What I need is something like</p>
<pre><code>function download(dirname)
{
directory = (This is the part I don't know how to do)
for dir in directory:
download(dir);
for file in directory:
copyfile(file);
}
</code></pre>
<p>My problem is that the directory requires a username and password for access and I don't know how to provide them. Thanks for any help you can offer.</p> | 5,433,640 | 3 | 2 | null | 2011-03-25 14:09:41.387 UTC | 11 | 2020-12-24 15:55:52.37 UTC | 2011-11-22 00:45:20.637 UTC | null | 3,043 | null | 623,552 | null | 1 | 18 | c#|asp.net|file-transfer|network-share | 59,021 | <p>Use this class to authenticate and than just use simple file operations:</p>
<pre><code>/// <summary>
/// Represents a network connection along with authentication to a network share.
/// </summary>
public class NetworkConnection : IDisposable
{
#region Variables
/// <summary>
/// The full path of the directory.
/// </summary>
private readonly string _networkName;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NetworkConnection"/> class.
/// </summary>
/// <param name="networkName">
/// The full path of the network share.
/// </param>
/// <param name="credentials">
/// The credentials to use when connecting to the network share.
/// </param>
public NetworkConnection(string networkName, NetworkCredential credentials)
{
_networkName = networkName;
var netResource = new NetResource
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName.TrimEnd('\\')
};
var result = WNetAddConnection2(
netResource, credentials.Password, credentials.UserName, 0);
if (result != 0)
{
throw new Win32Exception(result);
}
}
#endregion
#region Events
/// <summary>
/// Occurs when this instance has been disposed.
/// </summary>
public event EventHandler<EventArgs> Disposed;
#endregion
#region Public methods
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Protected methods
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
var handler = Disposed;
if (handler != null)
handler(this, EventArgs.Empty);
}
WNetCancelConnection2(_networkName, 0, true);
}
#endregion
#region Private static methods
/// <summary>
///The WNetAddConnection2 function makes a connection to a network resource. The function can redirect a local device to the network resource.
/// </summary>
/// <param name="netResource">A <see cref="NetResource"/> structure that specifies details of the proposed connection, such as information about the network resource, the local device, and the network resource provider.</param>
/// <param name="password">The password to use when connecting to the network resource.</param>
/// <param name="username">The username to use when connecting to the network resource.</param>
/// <param name="flags">The flags. See http://msdn.microsoft.com/en-us/library/aa385413%28VS.85%29.aspx for more information.</param>
/// <returns></returns>
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NetResource netResource,
string password,
string username,
int flags);
/// <summary>
/// The WNetCancelConnection2 function cancels an existing network connection. You can also call the function to remove remembered network connections that are not currently connected.
/// </summary>
/// <param name="name">Specifies the name of either the redirected local device or the remote network resource to disconnect from.</param>
/// <param name="flags">Connection type. The following values are defined:
/// 0: The system does not update information about the connection. If the connection was marked as persistent in the registry, the system continues to restore the connection at the next logon. If the connection was not marked as persistent, the function ignores the setting of the CONNECT_UPDATE_PROFILE flag.
/// CONNECT_UPDATE_PROFILE: The system updates the user profile with the information that the connection is no longer a persistent one. The system will not restore this connection during subsequent logon operations. (Disconnecting resources using remote names has no effect on persistent connections.)
/// </param>
/// <param name="force">Specifies whether the disconnection should occur if there are open files or jobs on the connection. If this parameter is FALSE, the function fails if there are open files or jobs.</param>
/// <returns></returns>
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags, bool force);
#endregion
/// <summary>
/// Finalizes an instance of the <see cref="NetworkConnection"/> class.
/// Allows an <see cref="System.Object"></see> to attempt to free resources and perform other cleanup operations before the <see cref="System.Object"></see> is reclaimed by garbage collection.
/// </summary>
~NetworkConnection()
{
Dispose(false);
}
}
#region Objects needed for the Win32 functions
#pragma warning disable 1591
/// <summary>
/// The net resource.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public ResourceScope Scope;
public ResourceType ResourceType;
public ResourceDisplaytype DisplayType;
public int Usage;
public string LocalName;
public string RemoteName;
public string Comment;
public string Provider;
}
/// <summary>
/// The resource scope.
/// </summary>
public enum ResourceScope
{
Connected = 1,
GlobalNetwork,
Remembered,
Recent,
Context
} ;
/// <summary>
/// The resource type.
/// </summary>
public enum ResourceType
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}
/// <summary>
/// The resource displaytype.
/// </summary>
public enum ResourceDisplaytype
{
Generic = 0x0,
Domain = 0x01,
Server = 0x02,
Share = 0x03,
File = 0x04,
Group = 0x05,
Network = 0x06,
Root = 0x07,
Shareadmin = 0x08,
Directory = 0x09,
Tree = 0x0a,
Ndscontainer = 0x0b
}
#pragma warning restore 1591
#endregion
</code></pre>
<p>Usage:</p>
<pre><code>using(new NetworkConnection(_directoryPath, new NetworkCredential(_userName, _password)))
{
File.Copy(localPath, _directoryPath);
}
</code></pre> |
5,062,032 | Audio analysis to detect human voice, gender, age and emotion -- any prior open-source work done? | <p>Is there prior open-source work done in the field of 'Audio analysis' to detect human-voice (say in spite of some background noise), determine speaker's gender, possibly determine no. of speakers, age of speaker(s), and the emotion of speakers?</p>
<p>My hunch is that the speech recognition software like CMU Sphinx could be a good place to start, but if there's something better, it'd be great.</p> | 5,227,143 | 3 | 3 | null | 2011-02-21 03:39:16.297 UTC | 21 | 2012-04-13 13:29:52.047 UTC | 2012-04-13 13:29:52.047 UTC | null | 869,458 | null | 625,927 | null | 1 | 25 | speech-recognition|analysis|speech|emotion | 24,269 | <p>I'm a graduate student doing speech recognition research. These are open research problems, and, unfortunately, I'm not aware of open-source packages that can do these things out of the box. </p>
<p>If you have some background in implementing signal-processing or machine-learning algorithms, you could try looking up academic papers using some of these search terms:</p>
<ul>
<li>gender identification (sometimes called gender recognition): predicting the gender of the speaker from the speech utterance</li>
<li>age identification: predicting the age of the speaker</li>
<li>speaker identification: predicting, from a set of possible speakers, the most likely speaker in a speech utterance</li>
<li>speaker verification: accepting or rejecting an utterance as belonging to a speaker (imagine a "voiceprint"-type authorization system)</li>
<li>speaker diarization: taking an audio file with multiple files and labeling which segments of speech belong to which speaker</li>
<li>emotion recognition: predicting the speaker's emotion from a speech utterance (a very new area of research). </li>
</ul>
<p>According to <a href="http://cmusphinx.sourceforge.net/sphinx4/doc/Sphinx4-faq.html#speaker_identification" rel="noreferrer">http://cmusphinx.sourceforge.net/sphinx4/doc/Sphinx4-faq.html#speaker_identification</a>, CMU Sphinx, which is probably the leading open-source speech recognizer out there, does not support speaker identification (<a href="http://cmusphinx.sourceforge.net/sphinx4/doc/Sphinx4-faq.html#speaker_identification" rel="noreferrer">http://cmusphinx.sourceforge.net/sphinx4/doc/Sphinx4-faq.html#speaker_identification</a>); I'm doubtful that it has any of the other capabilities described above. </p>
<p>Some academic researchers post their code online, and/or might be willing to share it with you. A search of Google Scholar reveals many people who've written Master's or PhD theses using Sphinx, so that could be a good place to start. </p>
<p>Lastly, you could try to implement a very crude gender-recognition algorithm without getting into the speech recognizer itself, if you know a little bit of signal processing. Basically, male and female voices differ in their fundamental frequency - according to Wikipedia (<a href="http://en.wikipedia.org/wiki/Voice_frequency" rel="noreferrer">http://en.wikipedia.org/wiki/Voice_frequency</a>), male voices are between 85-180Hz, while female voices are 165Hz-255Hz. You could use something like <code>sox</code> to determine the frequency spectrum (using something called the fast Fourier transform) of an utterance and classify speech as "male" or "female" depending on some summary statistic like the average frequency (see <a href="http://classicalconvert.com/tag/sox/" rel="noreferrer">http://classicalconvert.com/tag/sox/</a>). To make this work robustly (i.e. with many speakers, microphones, or recording environments), there are plenty of things that you can do. I'm not sure if I can predict how much time and effort would be required to get 70% accuracy, since it would depend on the nature of your task; my sense is that 90%+ would definitely be very hard.</p>
<p>Good luck!</p> |
5,462,040 | What is a ViewModelLocator and what are its pros/cons compared to DataTemplates? | <p>Can someone give me a quick summary of what a ViewModelLocator is, how it works, and what the pros/cons are for using it compared to DataTemplates?</p>
<p>I have tried finding info on Google but there seems to be many different implementations of it and no striaght list as to what it is and the pros/cons of using it.</p> | 5,462,324 | 3 | 0 | null | 2011-03-28 16:24:48.427 UTC | 50 | 2020-05-07 19:30:37.537 UTC | 2012-05-09 14:55:46.84 UTC | null | 50,079 | null | 302,677 | null | 1 | 116 | wpf|mvvm|datatemplate|mvvm-light|viewmodellocator | 48,547 | <h2>Intro</h2>
<p>In MVVM the usual practice is to have the Views find their ViewModels by resolving them from a <a href="http://martinfowler.com/articles/injection.html" rel="noreferrer">dependency injection</a> (DI) container. This happens automatically when the container is asked to provide (resolve) an instance of the View class. The container <em>injects</em> the ViewModel into the View by calling a constructor of the View which accepts a ViewModel parameter; this scheme is called <em>inversion of control</em> (IoC).</p>
<h2>Benefits of DI</h2>
<p>The main benefit here is that the container can be configured <strong>at run time</strong> with instructions on how to resolve the types that we request from it. This allows for greater testability by instructing it to resolve the types (Views and ViewModels) we use when our application actually runs, but instructing it differently when running the unit tests for the application. In the latter case the application will not even have a UI (it's not running; just the tests are) so the container will resolve <a href="http://en.wikipedia.org/wiki/Mock_object" rel="noreferrer">mocks</a> in place of the "normal" types used when the application runs.</p>
<h2>Problems stemming from DI</h2>
<p>So far we have seen that the DI approach allows easy testability for the application by adding an abstraction layer over the creation of application components. There is one problem with this approach: <strong>it doesn't play well with visual designers</strong> such as Microsoft Expression Blend.</p>
<p>The problem is that in both normal application runs and unit test runs, someone has to <em>set up</em> the container with instructions on what types to resolve; additionally, someone has to <em>ask</em> the container to resolve the Views so that the ViewModels can be injected into them.</p>
<p>However, <em>in design time there is no code of ours running</em>. The designer attempts to use reflection to create instances of our Views, which means that:</p>
<ul>
<li>If the View constructor requires a ViewModel instance the designer won't be able to instantiate the View at all -- it will error out in some controlled manner</li>
<li>If the View has a parameterless constructor the View will be instantiated, but its <code>DataContext</code> will be <code>null</code> so we 'll get an "empty" view in the designer -- which is not very useful</li>
</ul>
<h2>Enter ViewModelLocator</h2>
<p>The ViewModelLocator is an additional abstraction used like this:</p>
<ul>
<li>The View itself instantiates a ViewModelLocator as part of its <a href="http://msdn.microsoft.com/en-us/library/ms750613.aspx" rel="noreferrer">resources</a> and databinds its DataContext to the ViewModel property of the locator</li>
<li>The locator somehow <em>detects if we are in design mode</em></li>
<li>If not in design mode, the locator returns a ViewModel that it resolves from the DI container, as explained above</li>
<li>If in design mode, the locator returns a fixed "dummy" ViewModel using its own logic (remember: there is no container in design time!); this ViewModel typically comes prepopulated with dummy data</li>
</ul>
<p>Of course this means that the View must have a parameterless constructor to begin with (otherwise the designer won't be able to instantiate it).</p>
<h2>Summary</h2>
<p>ViewModelLocator is an idiom that lets you keep the benefits of DI in your MVVM application while also allowing your code to play well with visual designers. This is sometimes called the "blendability" of your application (referring to Expression Blend).</p>
<p>After digesting the above, see a practical example <a href="http://blog.roboblob.com/2010/01/17/wiring-up-view-and-viewmodel-in-mvvm-and-silverlight-4-blendability-included/" rel="noreferrer">here</a>.</p>
<p>Finally, using data templates is not an alternative to using ViewModelLocator, but an alternative to using explicit View/ViewModel pairs for parts of your UI. Often you may find that there's no need to define a View for a ViewModel because you can use a data template instead.</p> |
9,036,969 | Do something AFTER the page has loaded completely | <p>I'm using some embed codes that insert HTML to the page dynamically and since I have to modify that dynamically inserted HTML, I want a jquery function to wait until the page has loaded, I tried <code>delay</code> but it doesnt seem to work.</p>
<p>So for example, the dynamically inserted HTMl has an element <code>div#abc</code></p>
<p>and I have this jquery:</p>
<pre><code>if ( $('#abc')[0] ) {
alert("yes");
}
</code></pre>
<p>the alert doesn't show up.</p>
<p>I'd appreciate any help</p>
<p>Thanks</p> | 9,036,991 | 8 | 3 | null | 2012-01-27 16:48:40.517 UTC | 7 | 2019-09-24 04:10:22.547 UTC | 2014-09-08 07:32:07.61 UTC | null | 763,246 | null | 172,637 | null | 1 | 28 | javascript|jquery|load | 103,153 | <pre><code>$(window).load(function () {
....
});
</code></pre>
<p>If you have to wait for an iframe (and don't care about the assets, just the DOM) - try this:</p>
<pre><code>$(document).ready(function() {
$('iframe').load(function() {
// do something
});
});
</code></pre> |
9,489,061 | Understanding "median of medians" algorithm | <p>I want to understand "median of medians" algorithm on the following example:</p>
<p>We have 45 distinct numbers divided into 9 group with 5 elements each.</p>
<pre><code>48 43 38 33 28 23 18 13 8
49 44 39 34 29 24 19 14 9
50 45 40 35 30 25 20 15 10
51 46 41 36 31 26 21 16 53
52 47 42 37 32 27 22 17 54
</code></pre>
<ol>
<li>The first step is sorting every group (in this case they are already sorted)</li>
<li><p>Second step recursively, find the "true" median of the medians (<code>50 45 40 35 30 25 20 15 10</code>) i.e. the set will be divided into 2 groups:</p>
<pre><code>50 25
45 20
40 15
35 10
30
</code></pre>
<p>sorting these 2 groups</p>
<pre><code>30 10
35 15
40 20
45 25
50
</code></pre></li>
</ol>
<p>the medians is 40 and 15 (in case the numbers are even we took left median)
so the returned value is 15 however "true" median of medians (<code>50 45 40 35 30 25 20 15 10</code>) is 30, moreover there are 5 elements less then 15 which are much less than 30% of 45 which are mentioned in <a href="http://en.wikipedia.org/wiki/Selection_algorithm#Linear%5Fgeneral%5Fselection%5Falgorithm%5F-%5F.22Median%5Fof%5FMedians%5Falgorithm.22">wikipedia</a></p>
<p>and so <code>T(n) <= T(n/5) + T(7n/10) + O(n)</code> fails.</p>
<p>By the way in the Wikipedia example, I get result of recursion as 36. However, the true median is 47.</p>
<p>So, I think in some cases this recursion may not return true median of medians. I want to understand where is my mistake. </p> | 9,489,246 | 2 | 5 | null | 2012-02-28 20:18:31.077 UTC | 23 | 2016-04-25 14:45:52.487 UTC | 2016-04-25 14:45:52.487 UTC | null | 2,636,873 | null | 827,753 | null | 1 | 65 | algorithm|selection|median-of-medians | 59,324 | <p>The problem is in the step where you say to find the true median of the medians. In your example, you had these medians:</p>
<pre><code>50 45 40 35 30 25 20 15 10
</code></pre>
<p>The true median of this data set is 30, not 15. You don't find this median by splitting the groups into blocks of five and taking the median of those medians, but instead by recursively calling the selection algorithm on this smaller group. The error in your logic is assuming that median of this group is found by splitting the above sequence into two blocks</p>
<pre><code>50 45 40 35 30
</code></pre>
<p>and</p>
<pre><code>25 20 15 10
</code></pre>
<p>then finding the median of each block. Instead, the median-of-medians algorithm will recursively call itself on the complete data set <code>50 45 40 35 30 25 20 15 10</code>. Internally, this will split the group into blocks of five and sort them, etc., but it does so to determine the partition point for the partitioning step, and it's in this partitioning step that the recursive call will find the true median of the medians, which in this case will be 30. If you use 30 as the median as the partitioning step in the original algorithm, you do indeed get a very good split as required.</p>
<p>Hope this helps!</p> |
14,971,766 | Load content with ajax in bootstrap modal | <p>I am trying to have my bootstrap modal retrieve data using ajax:</p>
<pre><code><a href="{{ path('ajax_get_messages', { 'superCategoryID': 35, 'sex': sex }) }}" data-toggle="modal" data-target="#birthday-modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
</code></pre>
<p>My modal:</p>
<pre><code><div id="birthday-modal" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h3>Birthdays and Anniversaries</h3>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>
{#<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>#}
</div>
</div>
</code></pre>
<p>When I click on the link, the modal is shown but the body is empty. Besides, I don't see any ajax request being made.
I am using Bootstrap 2.1.1</p>
<p>What am I doing wrong?</p> | 14,975,843 | 3 | 0 | null | 2013-02-20 03:25:42.323 UTC | 13 | 2021-01-25 14:00:38.967 UTC | null | null | null | null | 1,273,077 | null | 1 | 23 | jquery|twitter-bootstrap|modal-dialog | 112,698 | <p>Here is how I solved the issue, might be useful to some:</p>
<p>Ajax modal doesn't seem to be available with boostrap 2.1.1</p>
<p>So I ended up coding it myself:</p>
<pre><code>$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
//var modal_id = $(this).attr('data-target');
$.get(url, function(data) {
$(data).modal();
});
});
</code></pre>
<p>Example of a link that calls a modal:</p>
<pre><code><a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
</code></pre>
<p>I now send the whole modal markup through ajax.</p>
<p>Credits to <a href="https://gist.github.com/drewjoh/1688900">drewjoh</a></p> |
15,236,238 | Current state of Haskell soft real-time | <p>I'm considering Haskell for a soft real-time app. I will likely use actors, for what it's worth. I'm wondering if anyone has insight into the current state of real-time with Haskell. Specifically, issues with the GC pausing the app. I've Googled extensively, and I've found a great deal of discussions from 2+ years ago, but nothing current. Here are a couple of the references I've found:</p>
<p><a href="https://stackoverflow.com/questions/1263711/using-haskell-for-sizable-real-time-systems-how-if">Using Haskell for sizable real-time systems: how (if?)?</a></p>
<p><a href="https://stackoverflow.com/questions/4482987/how-about-haskells-gc-performance-for-soft-realtime-application-like-games">How about Haskell's GC performance for soft realtime application like games?</a></p>
<p>Much of the older stuff I've read suggests that the situation was (at the time) thought to be improving. Has it?</p>
<p>Even 2+ years ago, there were a few comments suggesting Haskell apps could be tuned to reliably keep GC pauses down to a millisecond or two. Does this seem realistic?</p> | 15,243,682 | 4 | 3 | null | 2013-03-05 23:37:05.287 UTC | 18 | 2017-08-24 21:13:33.733 UTC | 2017-05-23 12:01:03.273 UTC | null | -1 | null | 284,681 | null | 1 | 31 | haskell|garbage-collection|real-time | 5,469 | <p>So the concern for "real time" is the latency introduced by GC collections.</p>
<p>GHC uses a multicore garbage collector (and there is <a href="http://hackage.haskell.org/trac/ghc/wiki/Status/May11" rel="nofollow noreferrer">a branch</a> with <a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/parallel/local-gc.pdf" rel="nofollow noreferrer">per-thread local heaps</a>). Originally developed to improve multcore performance (each core <a href="http://hackage.haskell.org/trac/ghc/blog/2010/9#new-gc-preview" rel="nofollow noreferrer">can collect independently</a>) by reducing the cost of frequent stop-the-world synchronisation, this happens to also benefit soft-real time for the same reason. However, as of 2013, the per-thread local heap has not yet been merged into main GHC, although the parallel GC has been.</p>
<p>For a game you should be able to exploit this, by using threads, and thus reducing the need for stop-the-world local collections.</p>
<p>For long lived objects, in the global heap, you still risk some (ms) GC. However, careful profiling with e.g. <a href="http://www.haskell.org/haskellwiki/ThreadScope#Features" rel="nofollow noreferrer">ThreadScope</a> will remove obstacles here. I've seen real time 1080p video streamed through a GHC-managed network stack without noticeable GC pauses.</p>
<p>And even without these tuneups, things "might just work". Frag needed almost no optimization, and was soft realtime nearly 10 years ago now.</p>
<p>Finally, there are many tools and GHC flags to improve performance:</p>
<ul>
<li><a href="http://hackage.haskell.org/package/ghc-gc-tune" rel="nofollow noreferrer">ghc-gc-tune</a> - get graphical breakdown of optimal GC flags</li>
<li><a href="https://stackoverflow.com/a/3172704/83805">Advice on throughput</a></li>
<li>Options for <a href="http://www.haskell.org/ghc/docs/latest/html/users_guide/runtime-control.html#rts-options-gc" rel="nofollow noreferrer">garbage collection</a> - (-Iseconds can be useful)</li>
</ul>
<p>And then there is coding: use unboxed types (no GC), minimize lazy structure allocation. Keep long lived data around in packed form. Test and benchmark.</p>
<p>I think you'll be fine.</p> |
15,143,306 | remove a blank option of select field that was generated by SimpleForm | <p>I have this piece of code:</p>
<pre><code>= f.input :category, :as => :select, :label => false, :collection => Choices["Categories"]
</code></pre>
<p>Choices["Categories"] is just a hash of key=>value pairs.</p>
<p>SimpleForm generates a select field with all needed options, but it also makes the first option blank.<br/> This blank option is present in all select fields that were generated by SimpleForm.</p>
<p>But I don't want to have a blank option. Is there a way to get rid of it?</p>
<p>Something like <code>:allow_blank_option => false</code>?</p>
<p>I tried to make a presence validation of this attribute hoping that SimpleForm will detect it, but it didn't help.</p> | 15,143,426 | 3 | 0 | null | 2013-02-28 18:48:27.617 UTC | 7 | 2021-05-26 17:33:07.63 UTC | 2021-05-26 17:33:07.63 UTC | null | 74,089 | null | 1,988,673 | null | 1 | 57 | ruby-on-rails | 35,938 | <p>You can pass a <code>include_blank: false, include_hidden: false</code> option:</p>
<pre><code>= f.input :category, :as => :select, :label => false, :collection => Choices["Categories"], include_blank: false, include_hidden: false
</code></pre> |
8,357,568 | Do twitter access token expire? | <p>I am building a web app from where the user can manage his twitter account. I've created the twitter app and once the user authenticates himself the application gets the access token from twitter. Does this access token expire or I can store it and make request, on user's behalf, without asking from him to log in again ?</p> | 8,357,636 | 2 | 0 | null | 2011-12-02 14:09:04.903 UTC | 8 | 2018-11-22 16:29:12.543 UTC | null | null | null | null | 816,192 | null | 1 | 43 | api|twitter|access-token | 18,562 | <p>Here is what they saying in there development page</p>
<blockquote>
<p><strong><em>Question: How long does an access token last?</em></strong></p>
<p>Access tokens are not explicitly expired. An access token will be
invalidated if a user explicitly revokes an application in the their
Twitter account settings, or if Twitter suspends an application. If an
application is suspended, there will be a note in the Twitter app
dashboard stating that it has been suspended.</p>
</blockquote>
<p>More details can be found here</p>
<p><a href="https://developer.twitter.com/en/docs/basics/authentication/FAQ" rel="noreferrer">FAQ Twitter</a></p> |
23,533,695 | Convert bytes[] to 'File' in Java | <p>I have an array of bytes</p>
<pre><code>bytes[] doc
</code></pre>
<p>How can I create an instance of <code>new File</code> from those bytes?</p> | 23,533,769 | 3 | 9 | null | 2014-05-08 05:49:43.02 UTC | null | 2021-08-31 13:18:50.847 UTC | 2021-08-31 13:14:41.75 UTC | null | 63,550 | null | 465,137 | null | 1 | 5 | java|file|byte | 69,167 | <pre><code> try (FileOutputStream fileOuputStream = new FileOutputStream("filename")){
fileOuputStream.write(byteArray);
}
</code></pre> |
8,729,236 | Solution to "cannot perform a DML operation inside a query"? | <p>I am using a Data Analysis tool and the requirement I have was to accept a value from the user, pass that as a parameter and store it in a table. Pretty straighforward so I sat to write this</p>
<pre><code>create or replace
procedure complex(datainput in VARCHAR2)
is
begin
insert into dumtab values (datainput);
end complex;
</code></pre>
<p>I executed this in <strong>SQL Developer</strong> using the following statement</p>
<pre><code>begin
complex('SomeValue');
end;
</code></pre>
<p>It worked fine, and the value was inserted into the table. However, the above statements are not supported in the Data Analysis tool, so I resorted to use a function instead. The following is the code of the function, it compiles.</p>
<pre><code>create or replace
function supercomplex(datainput in VARCHAR2)
return varchar2
is
begin
insert into dumtab values (datainput);
return 'done';
end supercomplex;
</code></pre>
<p>Once again I tried executing it in <strong>SQL Developer</strong>, but I got <strong>cannot perform a DML operation inside a query</strong> upon executing the following code</p>
<pre><code>select supercomplex('somevalue') from dual;
</code></pre>
<p>My question is
- I need a statement that can run the mentioned function in <strong>SQL Developer</strong> or
- A function that can perform what I am looking for which can be executed by the select statement.
- If it is not possible to do what I'm asking, I would like a reason so I can inform my manager as I am very new (like a week old?) to PL/SQL so I am not aware of the rules and syntaxes.</p>
<p>P.S. How I wish this was C++ or even Java :(</p>
<p><strong>EDIT</strong></p>
<p>I need to run the function on SQL Developer because before running it in DMine (which is the tool) in order to test if it is valid or not. Anything invalid in SQL is also invalid in DMine, but not the other way around.</p>
<p>Thanks for the help, I understood the situation and as to why it is illegal/not recommended </p> | 8,729,553 | 3 | 3 | null | 2012-01-04 15:20:16.1 UTC | 10 | 2019-11-03 14:47:52.86 UTC | 2012-01-05 07:50:48.417 UTC | null | 1,130,185 | null | 1,130,185 | null | 1 | 28 | sql|oracle|function|stored-procedures|plsql | 83,394 | <p>You could use the directive <code>pragma autonomous_transaction</code>. This will run the function into an independant transaction that will be able to perform DML without raising the ORA-14551. </p>
<p>Be aware that since the <a href="http://docs.oracle.com/cd/B19306_01/server.102/b14220/transact.htm#CNCPT417">autonomous transaction</a> is independent, the results of the DML will be commited outside of the scope of the parent transaction. In most cases that would not be an acceptable workaround.</p>
<pre><code>SQL> CREATE OR REPLACE FUNCTION supercomplex(datainput IN VARCHAR2)
2 RETURN VARCHAR2 IS
3 PRAGMA AUTONOMOUS_TRANSACTION;
4 BEGIN
5 INSERT INTO dumtab VALUES (datainput);
6 COMMIT;
7 RETURN 'done';
8 END supercomplex;
9 /
Function created
SQL> SELECT supercomplex('somevalue') FROM dual;
SUPERCOMPLEX('SOMEVALUE')
--------------------------------------------------------------------------------
done
SQL> select * from dumtab;
A
--------------------------------------------------------------------------------
somevalue
</code></pre>
<p>Tom Kyte <a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:1547006324238#12928321943595">has a nice explanation</a> about why the error is raised in the first place. It is not safe because it may depend upon the order in which the rows are processed. Furthermore, Oracle doesn't guarantee that the function will be executed at least once and at most once per row.</p> |
8,692,742 | Cannot convert from an IEnumerable<T> to an ICollection<T> | <p>I have defined the following:</p>
<pre><code>public ICollection<Item> Items { get; set; }
</code></pre>
<p>When I run this code:</p>
<pre><code>Items = _item.Get("001");
</code></pre>
<p>I get the following message:</p>
<pre><code>Error 3
Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<Storage.Models.Item>' to
'System.Collections.Generic.ICollection<Storage.Models.Item>'.
An explicit conversion exists (are you missing a cast?)
</code></pre>
<p>Can someone explain what I am doing wrong. I am very confused about the
difference between Enumerable, Collections and using the ToList()</p>
<p><strong>Added information</strong></p>
<p>Later in my code I have the following:</p>
<pre><code>for (var index = 0; index < Items.Count(); index++)
</code></pre>
<p>Would I be okay to define Items as an IEnumerable?</p> | 8,692,796 | 3 | 3 | null | 2012-01-01 10:48:19.07 UTC | 7 | 2014-08-26 14:05:09.37 UTC | 2012-01-02 08:08:29.967 UTC | null | 280,222 | null | 975,566 | null | 1 | 114 | c#|.net | 101,667 | <p><code>ICollection<T></code> inherits from <code>IEnumerable<T></code> so to assign the result of</p>
<pre><code>IEnumerable<T> Get(string pk)
</code></pre>
<p>to an <code>ICollection<T></code> there are two ways.</p>
<pre><code>// 1. You know that the referenced object implements `ICollection<T>`,
// so you can use a cast
ICollection<T> c = (ICollection<T>)Get("pk");
// 2. The returned object can be any `IEnumerable<T>`, so you need to
// enumerate it and put it into something implementing `ICollection<T>`.
// The easiest is to use `ToList()`:
ICollection<T> c = Get("pk").ToList();
</code></pre>
<p>The second options is more flexible, but has a much larger performance impact. Another option is to store the result as an <code>IEnumerable<T></code> unless you need the extra functionality added by the <code>ICollection<T></code> interface.</p>
<h2>Additional Performance Comment</h2>
<p>The loop you have</p>
<pre><code>for (var index = 0; index < Items.Count(); index++)
</code></pre>
<p>works on an <code>IEnumerable<T></code> but it is inefficient; each call to <code>Count()</code> requires a <em>complete</em> enumeration of all elements. Either use a collection and the <code>Count</code> property (without the parenthesis) or convert it into a foreach loop:</p>
<pre><code>foreach(var item in Items)
</code></pre> |
4,868,593 | What Are The Most Important Parts Of ELisp To Learn If You Want To Programme Emacs? | <p>I use Emacs everyday as it is the standard editor for Erlang.</p>
<p>I decided as my New Years Resolution to learn to programme eLisp. I decided that writing a book about eLisp was the best way to learn.</p>
<p>I have make pretty good progress:
<a href="http://learn-elisp-for-emacs.org/" rel="noreferrer">Learn eLisp For Emacs</a></p>
<p>The strategic structure of the book is</p>
<ul>
<li>getting started/basics</li>
<li>more advanced eLisp</li>
<li>writing a minor mode</li>
<li>writing a major mode</li>
</ul>
<p>I have got through the basics (ie the first of these 4 points), covering:</p>
<ul>
<li>evaluating expressions</li>
<li>debugging</li>
<li>adding menu items/toolbars</li>
<li>loading your own emacs files</li>
<li>etc, etc</li>
</ul>
<p>If you are writing a book about a programming language you usually start by knowing the language well - well I don't - so my major problem now is a completeness problem:</p>
<ul>
<li><em>How do I know that I have covered all the features that an Emacs programmer should have mastered?</em></li>
<li><em>How do I ensure that there aren't gaps in the content?</em></li>
</ul>
<p>So I thought I would address these by asking the community here. My question is <em>What Is Missing From My Table Of Contents?</em> (in particular what should the <em>more advanced eLisp</em> Section contain).</p> | 4,869,160 | 4 | 5 | null | 2011-02-01 22:15:16.75 UTC | 9 | 2013-10-14 16:00:51.793 UTC | null | null | null | null | 58,594 | null | 1 | 18 | emacs|elisp | 1,258 | <p>Now that's an interesting way to learn a language...</p>
<p>I think you've probably skipped a bunch of the fundamentals in the getting started/basics section. If you've not already read it, I recommend reading <a href="http://www.gnu.org/software/emacs/emacs-lisp-intro/html_node/index.html" rel="nofollow noreferrer">"An Introduction To Programming In Emacs Lisp"</a> (at <a href="http://www.gnu.org" rel="nofollow noreferrer">gnu.org</a>), which covers what I'd expect to see in the "basics" portion. I won't bother cut/paste the table of contents.</p>
<p>As far as knowing when you've written a complete book... Well, once you've re-written the <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/index.html" rel="nofollow noreferrer">Emacs Lisp manual</a> in "how to" form, you know you're done. Alternatively, if you've written a book that can be used to answer/interpret all of the <a href="https://stackoverflow.com/questions/tagged/elisp">elisp</a> and <a href="https://stackoverflow.com/questions/tagged/emacs">emacs</a> questions, then you've probably got decent coverage.</p>
<p>What advanced features could you write about? There's <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Advising-Functions.html#Advising-Functions" rel="nofollow noreferrer">advice</a>, <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Processes.html#Processes" rel="nofollow noreferrer">process communication</a>, <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Non_002dASCII-Characters.html#Non_002dASCII-Characters" rel="nofollow noreferrer">non-ASCII text</a>, <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Syntax-Tables.html#Syntax-Tables" rel="nofollow noreferrer">syntax tables</a>, <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Abbrevs.html#Abbrevs" rel="nofollow noreferrer">abbrevs</a>, <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Text-Properties.html#Text-Properties" rel="nofollow noreferrer">text properties</a>, <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Byte-Compilation.html#Byte-Compilation" rel="nofollow noreferrer">byte compilation</a>, <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Display-Tables.html#Display-Tables" rel="nofollow noreferrer">display tables</a>, <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Images.html#Images" rel="nofollow noreferrer">images</a>, and a bunch more in the <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/index.html" rel="nofollow noreferrer">manual</a>.</p>
<p>Note: The proper capitalization of elisp is either all lowercase, or possibly an uppercase E. The GNU documentation doesn't use "elisp" very much at all (mostly as a directory name, all lowercase), it prefers "Emacs Lisp."</p>
<p>Note: In the current version of your book, you treat global variables negatively. It's probably worth reading the <a href="http://www.gnu.org/software/emacs/emacs-paper.html" rel="nofollow noreferrer">RMS paper</a> to gain some insight into the design decisions made, specifically on <a href="http://www.gnu.org/software/emacs/emacs-paper.html#SEC16" rel="nofollow noreferrer">global variables</a> as well as <a href="http://www.gnu.org/software/emacs/emacs-paper.html#SEC17" rel="nofollow noreferrer">dynamic binding</a> (the latter which you've yet to cover, which is a key (basic) concept which you've already gotten wrong in your book).</p> |
4,978,740 | how do you uninstall an xampp installation that refuses to uninstall? | <p>I downloaded xampp 1.7.3 (32) on windows 7 (64) in the programs(86) folder. both MySql and Apache refuse to run, they start and then instantly turn of. All ports are free.</p>
<p>So I decide to uninstall however, when i run the uninstaller I receive the following error</p>
<pre><code>"Input Error: Can not find script file "C:\Program Files (x86)\xampp\uninst.temp\xampp_uninstall.vbs" XAMPP uninstall not OK
</code></pre>
<p>Why is there spaces in the above line and does this matter "C:\Program Files (x86)" ?</p>
<p>Can somebody please help me to understand the problem & uninstall xampp (or get it to work). It does not show in the control panel so I am stuck. The documentation clearly states the uninstaller should be used.</p>
<p>I have asked this question on serverfault but since ive had so much help here, i was wondering if anybody here knows what the problem could be?
All help is greatly appreciated. Thank you.</p> | 4,984,210 | 5 | 2 | null | 2011-02-12 15:05:03.637 UTC | 1 | 2022-01-04 10:38:18.41 UTC | null | null | null | null | 1,648,577 | null | 1 | 1 | windows-7|installation|xampp|uninstallation | 76,953 | <p>Never install xampp to the x86 folder on windows 7.</p>
<p>directly to the C drive works fine.</p>
<p>Solution for the time being:
System Restore or delete the folder and pretend it never happened.</p> |
5,198,856 | pass array to oracle procedure | <p>I want to send two arrays form java to oracle stored procedures.
The first Array is array of strings and the second is array of chars
how can I make this??</p> | 5,199,629 | 6 | 0 | null | 2011-03-04 20:22:50.14 UTC | 10 | 2018-04-25 12:26:51.527 UTC | null | null | null | null | 2,067,571 | null | 1 | 15 | java|oracle|stored-procedures | 51,896 | <p>Here's an example of how to do it.</p>
<p>The following script sets up a table, a type and a stored procedure in the database. The procedure takes a parameter of the array type and inserts each row of the array into the table:</p>
<pre><code>CREATE TABLE strings (s VARCHAR(4000));
CREATE TYPE t_varchar2_array AS TABLE OF VARCHAR2(4000);
/
CREATE OR REPLACE PROCEDURE p_array_test(
p_strings t_varchar2_array
)
AS
BEGIN
FOR i IN 1..p_strings.COUNT
LOOP
INSERT INTO strings (s) VALUES (p_strings(i));
END LOOP;
END;
/
</code></pre>
<p>The Java code then demonstrates passing an array into this stored procedure:</p>
<pre><code>import java.sql.*;
import oracle.jdbc.*;
import oracle.sql.*;
public class ArrayTest {
public static void main(String[] args) throws Exception {
DriverManager.registerDriver(new OracleDriver());
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "user", "pass");
CallableStatement stmt = conn.prepareCall("BEGIN p_array_test(?); END;");
// The first parameter here should be the name of the array type.
// It's been capitalised here since I created it without using
// double quotes.
ArrayDescriptor arrDesc =
ArrayDescriptor.createDescriptor("T_VARCHAR2_ARRAY", conn);
String[] data = { "one", "two", "three" };
Array array = new ARRAY(arrDesc, conn, data);
stmt.setArray(1, array);
stmt.execute();
conn.commit();
conn.close();
}
}
</code></pre>
<p>If you run the SQL script and then the Java class, and then query the table <code>strings</code>, you should find that all of the data has been inserted into the table.</p>
<p>When you say 'an array of chars', I'm guessing that you mean an array of Java <code>char</code>s. If I've guessed right, then I think you'd be best off converting the <code>char</code>s to <code>String</code>s and then using the same approach as above.</p> |
5,183,801 | Black Background for XAML Editor | <p>I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!</p>
<p>I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.</p>
<p>Does anyone know how this can be done?</p> | 5,185,385 | 6 | 4 | null | 2011-03-03 16:49:20.443 UTC | 9 | 2022-09-01 11:37:41.847 UTC | null | null | null | null | 249,933 | null | 1 | 17 | wpf|silverlight|visual-studio-2010 | 9,078 | <p>In your XAML, set your background to black. Then in your user control, use the DesignerProperties to set the background at runtime:</p>
<p><strong>XAML</strong></p>
<pre><code><UserControl .... Background="Black" .... >
</code></pre>
<p><strong>Code Behind</strong></p>
<pre><code>public YourUserControl()
{
InitializeComponent();
if( !System.ComponentModel.DesignerProperties.GetIsInDesignMode( this ) )
{
this.Background = Brushes.Transparent;
}
}
</code></pre>
<p><br /></p>
<hr>
<h2><strong>Alternate Method</strong></h2>
<p><strong>UserControl:</strong></p>
<p>In your user control, do not declare a background color:</p>
<pre><code><UserControl ... namespaces ...>
</code></pre>
<p><strong>UserControl Code Behind:</strong></p>
<p>In your user control's constructor, use the DesignTime method as above, but check to see if it is Design Mode (opposite check from other method):</p>
<pre><code>public YourUserControl()
{
InitializeComponent();
if( System.ComponentModel.DesignerProperties.GetIsInDesignMode( this ) )
{
this.Background = Brushes.Black;
}
}
</code></pre>
<p><strong>App.xaml:</strong></p>
<p>Finally, in your App.xaml, add a style to set a background color for UserControls:</p>
<pre><code><Application.Resources>
<Style TargetType="{x:Type UserControl}">
<Setter Property="Background" Value="Black" />
</Style>
</Application.Resources>
</code></pre>
<p>Here's what's happening: </p>
<ol>
<li>The App.xaml will effect the UserControl at design time because a typed style is applied on an object automatically, but it is <strong>not</strong> applied to a derived object (UserControl in this case). So, at design time, VS thinks it should apply the style, but at runtime, it will be ignored.</li>
<li>The <code>GetIsInDesignMode</code> check will effect the UserControl when viewing the control in a Window that is using the UserControl because VS is compiling the UserControl at design time in order to render it in the Visual Designer.</li>
</ol>
<p>HTH's</p> |
5,300,947 | How do I switch between the header and implementation file in Xcode 4? | <p>How do I switch between the header and implementation file in Xcode 4?</p>
<p>In XCode 3 it was cmd and right or left (I think)</p> | 5,300,985 | 7 | 2 | null | 2011-03-14 15:46:22.627 UTC | 26 | 2015-11-30 12:32:49.603 UTC | null | null | null | null | 351,126 | null | 1 | 106 | xcode | 39,987 | <p><kbd>Ctrl</kbd>+<kbd>Cmd</kbd>+<kbd>Up</kbd> or <kbd>Down</kbd>, but the shortcut seems a bit finicky and sometimes stops working, not yet sure when and why.</p>
<hr />
<h1>Be sure to FIRST click ON the actual code window...</h1>
<p>that's the critical tip to ensure it works. Click anywhere at all on the actual code. (If you're active in one of the other many panes of Xcode, the keystroke combo has no, or different, meaning(s).)</p> |
4,941,004 | Putting images with options in a dropdown list | <p>I was trying to insert images in a drop down list. I tried the following code but its not working. What is the best way to achieve this?</p>
<pre><code><select>
<option value="volvo"><IMG src="a.jpg"HEIGHT="15" WIDTH="15" BORDER="0"align="center">Volvo</option>
<option value="saab"><IMG src="b.jpg"HEIGHT="15" WIDTH="15" BORDER="0"align="center">Saab</option>
<option value="mercedes"><IMG src="c.jpg"HEIGHT="15" WIDTH="15" BORDER="0"align="center">Mercedes</option>
<option value="audi"><IMG src="d.jpg"HEIGHT="15" WIDTH="15" BORDER="0"align="center">Audi</option>
</select>
</code></pre> | 6,979,780 | 8 | 1 | null | 2011-02-09 03:23:38.66 UTC | 4 | 2020-09-11 00:43:57.777 UTC | 2019-12-06 12:50:13.047 UTC | null | 4,684,797 | null | 1,272,852 | null | 1 | 63 | html|html-select | 374,750 | <p>This code will work only in Firefox:</p>
<pre><code><select>
<option value="volvo" style="background-image:url(images/volvo.png);">Volvo</option>
<option value="saab" style="background-image:url(images/saab.png);">Saab</option>
<option value="honda" style="background-image:url(images/honda.png);">Honda</option>
<option value="audi" style="background-image:url(images/audi.png);">Audi</option>
</select>
</code></pre>
<hr>
<p><strong>Edit (April 2018):</strong></p>
<blockquote>
<p><strong>Firefox does not support this anymore.</strong></p>
</blockquote> |
5,451,135 | Embed SVG in SVG? | <p>I have an SVG document, and I would like to include an external svg image within it, i.e. something like:</p>
<pre><code><object data="logo.svgz" width="100" height="100" x="200" y="400"/>
</code></pre>
<p>("object" is just an example - the outer document will be SVG rather than xhtml).</p>
<p>Any ideas? Is this even possible? Or is the best thing for me to simply slap the logo.svg xml into my outer SVG document?</p> | 5,451,238 | 8 | 0 | null | 2011-03-27 17:59:10.947 UTC | 35 | 2021-07-02 16:53:49.303 UTC | null | null | null | null | 21,640 | null | 1 | 126 | xml|svg|embedding | 122,105 | <p>Use the <a href="http://www.w3.org/TR/SVG/struct.html#ImageElement" rel="noreferrer"><code>image</code></a> element and reference your SVG file. For fun, save the following as <code>recursion.svg</code>:</p>
<pre><code><svg width="100%" height="100%" viewBox="-100 -100 200 200" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<circle cx="-50" cy="-50" r="30" style="fill:red" />
<image x="10" y="20" width="80" height="80" href="recursion.svg" />
</svg>
</code></pre> |
5,141,863 | How to get distinct characters? | <p>I have a code like</p>
<pre><code>string code = "AABBDDCCRRFF";
</code></pre>
<p>In this code, I want to retrieve only distinct characters</p>
<p>The Output should be like:</p>
<pre><code>ANS: ABDCRF
</code></pre> | 5,141,900 | 9 | 0 | null | 2011-02-28 12:18:35.727 UTC | 3 | 2020-01-12 12:54:38.69 UTC | 2019-12-31 15:05:58.217 UTC | null | 5,180,017 | null | 579,688 | null | 1 | 29 | c# | 55,367 | <pre><code>string code = "AABBDDCCRRFF";
string answer = new String(code.Distinct().ToArray());
</code></pre> |
5,091,057 | How to find a whole word in a String in Java? | <p>I have a String that I have to parse for different keywords.
For example, I have the String:</p>
<blockquote>
<p>"I will come and meet you at the 123woods"</p>
</blockquote>
<p>And my keywords are</p>
<blockquote>
<p>'123woods'<br />
'woods'</p>
</blockquote>
<p>I should report whenever I have a match and where. Multiple occurrences should also be accounted for.</p>
<p>However, for this one, I should get a match only on <em>'123woods'</em>, not on <em>'woods'</em>. This eliminates using <code>String.contains()</code> method. Also, I should be able to have a list/set of keywords and check at the same time for their occurrence. In this example, if I have <em>'123woods'</em> and <em>'come'</em>, I should get two occurrences. Method execution should be somewhat fast on large texts.</p>
<p>My idea is to use <code>StringTokenizer</code> but I am unsure if it will perform well. Any suggestions?</p> | 5,091,147 | 14 | 2 | null | 2011-02-23 12:43:15.54 UTC | 16 | 2022-08-18 09:47:13.213 UTC | 2021-07-29 22:38:31.897 UTC | null | 814,702 | null | 487,649 | null | 1 | 31 | java|string|pattern-matching|stringtokenizer | 239,320 | <p>The example below is based on your comments. It uses a List of keywords, which will be searched in a given String using word boundaries. It uses StringUtils from Apache Commons Lang to build the regular expression and print the matched groups.</p>
<pre><code>String text = "I will come and meet you at the woods 123woods and all the woods";
List<String> tokens = new ArrayList<String>();
tokens.add("123woods");
tokens.add("woods");
String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
</code></pre>
<p>If you are looking for more performance, you could have a look at <a href="http://johannburkard.de/software/stringsearch/" rel="noreferrer">StringSearch</a>: high-performance pattern matching algorithms in Java.</p> |
41,650,965 | CLEARTEXT communication not supported on Retrofit | <p>I'm trying to connect to https server on android using Retrofit. Here's my <code>OkHttpClient</code></p>
<pre><code>@Provides
public OkHttpClient provideContactClient(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(CipherSuite.TLS_RSA_WITH_DES_CBC_SHA,
CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
.build();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
SSLSocketFactory sslSocketFactory = null;
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
sslSocketFactory = sslContext.getSocketFactory();
}catch (GeneralSecurityException e){
e.printStackTrace();
}
return new OkHttpClient.Builder()
.addInterceptor(interceptor)
.connectionSpecs(Collections.singletonList(spec))
.sslSocketFactory(sslSocketFactory)
.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
if(responseCount(response) >= 5){
return null;
}
String credential = Credentials.basic("user", "pass");
return response.request().newBuilder().header("Authorization", credential).build();
}
})
.build();
}
</code></pre>
<p>However I keep getting <code>CLEARTEXT communication not supported:</code> exception</p>
<p>While debugging the <code>RealConnection</code> class I notice <code>route.address()</code> member does not have the <code>sslSocketFactory</code> despite it being assigned in Bulider.</p> | 53,349,252 | 5 | 5 | null | 2017-01-14 14:17:36.123 UTC | 5 | 2020-01-23 08:19:55.093 UTC | 2017-01-14 15:47:19.127 UTC | null | 4,853,459 | null | 1,248,742 | null | 1 | 49 | android|http|ssl|retrofit | 53,549 | <p>According to Network security configuration </p>
<blockquote>
<p><strong>The guidance in this section applies only to apps that target Android 8.1 (API level 27) or lower. Starting with Android 9 (API
level 28), cleartext support is disabled by default.</strong></p>
</blockquote>
<p>Create file res/xml/network_security_config.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
</domain-config>
</network-security-config>
</code></pre>
<p>AndroidManifest.xml </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...>
...
</application>
</manifest>
</code></pre>
<p>OR you can directly set in application in manifest like this.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
</code></pre> |
12,183,942 | Link (Href) to a hidden (display:none) html element | <p>I've a problem with anchor tags :/</p>
<p>I've got the following code:</p>
<pre><code><div name="divA">
<a name="A"> A</a>
</div>
<div name="divB" style="display: none;">
<a name="B"> B</a>
</div>
<div name="divHrefB">
<a href="#B">B</a>
</div>
</code></pre>
<p>My goal is that when i click on B (divHrefB) the application go to "divB" but since this element hidden it doesn't work.</p>
<p>Please note, that i don't want to show divB (i want a link to the place where div are... is that possible?</p>
<p>At this point, i'm thinking on generate dynamically the href value (in this case, i would generate the following div)</p>
<pre><code><div name="divHrefB">
<a href="#A">B</a>
</div>
</code></pre>
<p>Thanks a lot.</p> | 12,183,976 | 3 | 0 | null | 2012-08-29 18:06:38.41 UTC | 4 | 2022-07-04 14:01:05.773 UTC | 2022-07-04 14:01:05.773 UTC | null | 1,106,986 | null | 1,106,986 | null | 1 | 7 | html|href|hidden | 79,388 | <p>just don't apply display: none, just add this css for the hidden div.</p>
<pre><code><div name="divHrefB" style="height: 0px;width: 0px;overflow:hidden;">
<a href="#A">B</a>
</div>
</code></pre> |
12,081,523 | Understanding hexadecimals and bytes in C# | <p>I seem to lack a fundemental understanding of calculating and using hex and byte values in C# (or programming in general).</p>
<p>I'd like to know how to calculate hex values and bytes (0x--) from sources such as strings and RGB colors (like how do I figure out what the 0x code is for R255 G0 B0 ?)</p>
<p>Why do we use things like FF, is it to compensate for the base 10 system to get a number like 10? </p> | 12,081,587 | 4 | 2 | null | 2012-08-22 21:15:49.067 UTC | 12 | 2018-06-27 17:09:06.45 UTC | null | null | null | null | 767,215 | null | 1 | 11 | c#|binary|hex|byte | 30,703 | <p>Hexadecimal is base 16, so instead of counting from 0 to 9, we count from 0 to F. And we generally prefix hex constants with <code>0x</code>. Thus,</p>
<pre class="lang-none prettyprint-override"><code>Hex Dec
-------------
0x00 = 0
0x09 = 9
0x0A = 10
0x0F = 15
0x10 = 16
0x200 = 512
</code></pre>
<p>A byte is the typical unit of storage for values on a computer, and on most all modern systems, a byte contains 8 bits. Note that <code>bit</code> actually means <code>binary digit</code>, so from this, we gather that a byte has a maximum value of 11111111 binary. That is 0xFF hex, or 255 decimal. Thus, one byte can be represented by a minimum of two hexadecimal characters. A typical 4-byte <code>int</code> is then 8 hex characters, like <code>0xDEADBEEF</code>.</p>
<p>RGB values are typically packed with 3 byte values, in that order, RGB. Thus,</p>
<pre><code>R=255 G=0 B=0 => R=0xFF G=0x00 B=0x00 => 0xFF0000 or #FF0000 (html)
R=66 G=0 B=248 => R=0x42 G=0x00 B=0xF8 => 0x4200F8 or #4200F8 (html)
</code></pre>
<p>For my hex calculations, I like to use python as my calculator:</p>
<pre class="lang-none prettyprint-override"><code>>>> a = 0x427FB
>>> b = 700
>>> a + b
273079
>>>
>>> hex(a + b)
'0x42ab7'
>>>
>>> bin(a + b)
'0b1000010101010110111'
>>>
</code></pre>
<p>For the RGB example, I can demonstrate how we could use <a href="http://en.wikipedia.org/wiki/Logical_shift" rel="noreferrer">bit-shifting</a> to easily calculate those values:</p>
<pre><code>>>> R=66
>>> G=0
>>> B=248
>>>
>>> hex( R<<16 | G<<8 | B )
'0x4200f8'
>>>
</code></pre> |
12,186,568 | getline() skipping first even after clear() | <p>So I have a function that keeps skipping over the first getline and straight to the second one. I tried to clear the buffer but still no luck, what's going on?</p>
<pre><code>void getData(char* strA, char* strB)
{
cout << "Enter String 1: "; // Shows this line
cin.clear();
cin.getline(strA, 50); // 50 is the character limit, Skipping Input
cout << endl << "Enter String 2: "; // Showing This Line
cin.clear();
cin.getline(strB, 50); // Jumps Straight to this line
}
</code></pre> | 12,186,605 | 5 | 1 | null | 2012-08-29 21:09:13.19 UTC | 3 | 2021-05-15 09:11:23.693 UTC | null | null | null | null | 1,337,447 | null | 1 | 12 | c++|arrays|char|buffer|getline | 38,673 | <p>Make sure you didn't use <code>cin >> str</code>. before calling the function. If you use <code>cin >> str</code> and then want to use <code>getline(cin, str)</code>, you must call <code>cin.ignore()</code> before.</p>
<pre><code>string str;
cin >> str;
cin.ignore(); // ignores \n that cin >> str has lefted (if user pressed enter key)
getline(cin, str);
</code></pre>
<p>In case of using c-strings:</p>
<pre><code>char buff[50];
cin.get(buff, 50, ' ');
cin.ignore();
cin.getline(buff, 50);
</code></pre>
<p><strong>ADD</strong>: Your wrong is not probably in the function itself, but rather <em>before</em> calling the function. The stream <code>cin</code> have to read only a new line character <code>\n'</code> in first <code>cin.getline</code>.</p> |
12,429,185 | Linq To Entities - Any VS First VS Exists | <p>I am using Entity Framework and I need to check if a product with name = "xyz" exists ... </p>
<p>I think I can use Any(), Exists() or First().</p>
<p>Which one is the best option for this kind of situation? Which one has the best performance?</p>
<p>Thank You,</p>
<p>Miguel</p> | 12,431,073 | 5 | 0 | null | 2012-09-14 17:20:43.347 UTC | 1 | 2020-05-19 03:49:10.317 UTC | null | null | null | null | 577,805 | null | 1 | 19 | entity-framework|ef-code-first|exists|any | 45,874 | <p>Any translates into "Exists" at the database level. First translates into Select Top 1 ... Between these, Exists will out perform First because the actual object doesn't need to be fetched, only a Boolean result value. </p>
<p>At least you didn't ask about .Where(x => x.Count() > 0) which requires the entire match set to be evaluated and iterated over before you can determine that you have one record. Any short-circuits the request and can be significantly faster.</p> |
12,265,234 | How to plot 2d math vectors with matplotlib? | <p>How can we plot 2D math vectors with <code>matplotlib</code>? Does anyone have an example or suggestion about that? </p>
<p>I have a couple of vectors stored as 2D <code>numpy</code> arrays, and I would like to plot them as directed edges. </p>
<p>The vectors to be plotted are constructed as below:</p>
<pre><code>import numpy as np
# a list contains 3 vectors;
# each list is constructed as the tail and the head of the vector
a = np.array([[0, 0, 3, 2], [0, 0, 1, 1], [0, 0, 9, 9]])
</code></pre>
<hr>
<p><strong>Edit:</strong></p>
<p>I just added the plot of the final answer of <code>tcaswell</code> for anyone interested in the output and want to plot 2d vectors with matplotlib:
<img src="https://i.stack.imgur.com/BkIId.png" alt="enter image description here"></p> | 12,267,492 | 2 | 5 | null | 2012-09-04 14:06:55.377 UTC | 16 | 2018-05-01 15:10:21.14 UTC | 2015-03-25 17:20:06.87 UTC | null | 3,924,118 | null | 277,809 | null | 1 | 21 | python|math|matplotlib|visualization | 68,496 | <p>The suggestion in the comments by halex is correct, you want to use quiver (<a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.quiver" rel="noreferrer">doc</a>), but you need to tweak the properties a bit.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
soa = np.array([[0, 0, 3, 2], [0, 0, 1, 1], [0, 0, 9, 9]])
X, Y, U, V = zip(*soa)
plt.figure()
ax = plt.gca()
ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1)
ax.set_xlim([-1, 10])
ax.set_ylim([-1, 10])
plt.draw()
plt.show()
</code></pre> |
12,279,601 | Are there any tricks to use std::cin to initialize a const variable? | <p><strong>Common std::cin usage</strong></p>
<pre><code>int X;
cin >> X;
</code></pre>
<p>The main disadvantage of this is that X cannot be <code>const</code>. It can easily introduce bugs; and I am looking for some trick to be able to create a const value, and write to it just once.</p>
<p><strong>The naive solution</strong></p>
<pre><code>// Naive
int X_temp;
cin >> X_temp;
const int X = X_temp;
</code></pre>
<p>You could obviously improve it by changing X to <code>const&</code>; still, the original variable can be modified.</p>
<p>I'm looking for a short and clever solution of how to do this. I am sure I am not the only one who will benefit from a good answer to this question.</p>
<p><strong>// EDIT:</strong> I'd like the solution to be easily extensible to the other types (let's say, all PODs, <code>std::string</code> and movable-copyable classes with trivial constructor) (if it doesn't make sense, please let me know in comments).</p> | 12,280,095 | 6 | 10 | null | 2012-09-05 10:40:36.673 UTC | 17 | 2018-03-30 19:32:10.717 UTC | 2012-09-05 15:22:45.963 UTC | null | 385,478 | null | 752,976 | null | 1 | 50 | c++|c++11|iostream | 17,296 | <p>I'd probably opt for returning an <code>optional</code>, since the streaming could fail. To test if it did (in case you want to assign another value), use <code>get_value_or(default)</code>, as shown in the example.</p>
<pre><code>template<class T, class Stream>
boost::optional<T> stream_get(Stream& s){
T x;
if(s >> x)
return std::move(x); // automatic move doesn't happen since
// return type is different from T
return boost::none;
}
</code></pre>
<p><a href="http://liveworkspace.org/code/0feaa0fac77c5ec1a3f3057f44b6769d">Live example.</a></p>
<p>To further ensure that the user gets no wall-of-overloads presented when <code>T</code> is not input-streamable, you can write a trait class that checks if <code>stream >> T_lvalue</code> is valid and <code>static_assert</code> if it's not:</p>
<pre><code>namespace detail{
template<class T, class Stream>
struct is_input_streamable_test{
template<class U>
static auto f(U* u, Stream* s = 0) -> decltype((*s >> *u), int());
template<class>
static void f(...);
static constexpr bool value = !std::is_void<decltype(f<T>(0))>::value;
};
template<class T, class Stream>
struct is_input_streamable
: std::integral_constant<bool, is_input_streamable_test<T, Stream>::value>
{
};
template<class T, class Stream>
bool do_stream(T& v, Stream& s){ return s >> v; }
} // detail::
template<class T, class Stream>
boost::optional<T> stream_get(Stream& s){
using iis = detail::is_input_streamable<T, Stream>;
static_assert(iis::value, "T must support 'stream >> value_of_T'");
T x;
if(detail::do_stream(x, s))
return std::move(x); // automatic move doesn't happen since
// return type is different from T
return boost::none;
}
</code></pre>
<p><a href="http://liveworkspace.org/code/f1f8bcca190d3736e5d2d68e76d6e7f6">Live example.</a></p>
<p>I'm using a <code>detail::do_stream</code> function, since otherwise <code>s >> x</code> would still be parsed inside <code>get_stream</code> and you'd still get the wall-of-overloads that we wanted to avoid when the <code>static_assert</code> fires. Delegating this operation to a different function makes this work.</p> |
12,159,342 | Set upper case for TextView | <p>I have TextView. I would like to show text in upper case mode.
Is there attributed for upper case?
Just I have text in strings.xml and I need use the line in several place as lower case and upper case.</p> | 12,159,375 | 13 | 0 | null | 2012-08-28 12:35:09.033 UTC | 10 | 2022-09-23 15:51:23.767 UTC | null | null | null | null | 827,306 | null | 1 | 56 | android|android-layout | 86,972 | <p>Use <code>String</code> class method while setting the text to <code>TextView</code> as</p>
<pre><code>tv.setText(strings.toUpperCase());
</code></pre>
<p>Have a look at <a href="https://stackoverflow.com/q/3286343/593709">this</a> post for detail discussion.</p>
<p><strong>EDIT:</strong> This was answered way back before API 14. As other answer mentioned here, <code>textView.isAllCaps = true</code> and its java methods were introduced from <code>TextView</code>. Please use those.</p> |
18,880,737 | How do I use $rootScope in Angular to store variables? | <p>How do I use <code>$rootScope</code> to store variables in a controller I want to later access in another controller? For example:</p>
<pre><code>angular.module('myApp').controller('myCtrl', function($scope) {
var a = //something in the scope
//put it in the root scope
});
angular.module('myApp').controller('myCtrl2', function($scope) {
var b = //get var a from root scope somehow
//use var b
});
</code></pre>
<p>How would I do this?</p> | 18,881,189 | 8 | 6 | null | 2013-09-18 19:31:51.36 UTC | 75 | 2017-06-09 15:20:30.727 UTC | 2013-09-18 19:32:44.113 UTC | null | 239,879 | null | 2,057,814 | null | 1 | 219 | angularjs|angularjs-scope|angularjs-controller|rootscope | 388,375 | <p>Variables set at the root-scope are available to the controller scope via prototypical inheritance.</p>
<p>Here is a modified version of @Nitish's demo that shows the relationship a bit clearer:
<a href="http://jsfiddle.net/TmPk5/6/" rel="noreferrer">http://jsfiddle.net/TmPk5/6/</a></p>
<p>Notice that the rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently (the <code>change</code> function). Also, the rootScope's value can be updated too (the <code>changeRs</code> function in <code>myCtrl2</code>)</p>
<pre><code>angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.change = function() {
$scope.test = new Date();
};
$scope.changeRs = function() {
$rootScope.test = new Date();
};
$scope.getOrig = function() {
return $rootScope.test;
};
});
</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.