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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,795,470 | How do I get just real time value from 'time' command? | <p>I would like to make a script that outputs only the real time value from the time command so I can plot the results. For example <code>time command</code> outputs</p>
<pre><code>real 1m0.001s
user 1m0.000s
sys 0m0.001s
</code></pre>
<p>I want to write a script that outputs</p>
<pre><code>60.001
</code></pre>
<p>How do I get just real time value from 'time' command in seconds?</p> | 3,795,634 | 4 | 0 | null | 2010-09-25 20:33:07.913 UTC | 11 | 2019-10-11 16:17:53.54 UTC | null | null | null | null | 136,418 | null | 1 | 58 | bash|scripting|shell | 29,027 | <p>If you're using the Bash builtin <code>time</code>, set the <code>TIMEFORMAT</code> variable to <code>%R</code>:</p>
<pre><code>$ TIMEFORMAT=%R
$ time sleep 1
1.022
</code></pre> |
3,860,184 | Excel: how do I remove all carriage returns from a cell? | <p>I want to get rid of all the carriage returns in my cell. How do I do this?</p> | 3,860,275 | 5 | 1 | null | 2010-10-05 00:47:36.547 UTC | 9 | 2017-09-23 05:53:58.907 UTC | 2015-04-01 00:21:11.283 UTC | null | 641,067 | null | 117,700 | null | 1 | 23 | excel|excel-formula | 101,629 | <p><code>=CLEAN(A1)</code></p>
<p>Clean removes all nonprintable characters from text. -- Excel Help Documentation</p> |
3,551,527 | 'At' symbol before variable name in PHP: @$_POST | <p>I've seen function calls preceded with an at symbol to switch off warnings. Today I was skimming some code and found this:</p>
<pre><code>$hn = @$_POST['hn'];
</code></pre>
<p>What good will it do here?</p> | 3,551,540 | 5 | 2 | null | 2010-08-23 20:43:15.45 UTC | 11 | 2022-05-11 06:16:07.593 UTC | 2015-12-10 19:58:36.1 UTC | null | 63,550 | null | 66,580 | null | 1 | 59 | php|error-handling|operators | 40,581 | <p>The <code>@</code> is the error suppression operator in PHP.</p>
<blockquote>
<p>PHP supports one error control
operator: the at sign (@). When
prepended to an expression in PHP, any
error messages that might be generated
by that expression will be ignored.</p>
</blockquote>
<p><strong>See:</strong></p>
<ul>
<li><a href="http://php.net/manual/en/language.operators.errorcontrol.php" rel="noreferrer">Error Control Operators</a></li>
<li><a href="http://michelf.com/weblog/2005/bad-uses-of-the-at-operator/" rel="noreferrer">Bad uses of the @ operator</a></li>
</ul>
<h3>Update:</h3>
<p><strong><em>In your example</em></strong>, it is used before the variable name to avoid the <code>E_NOTICE</code> error there. If in the <code>$_POST</code> array, the <code>hn</code> key is not set; it will throw an <code>E_NOTICE</code> message, but <code>@</code> is used there to avoid that <code>E_NOTICE</code>.</p>
<p>Note that you can also put this line on top of your script to avoid an <code>E_NOTICE</code> error:</p>
<pre><code>error_reporting(E_ALL ^ E_NOTICE);
</code></pre> |
3,903,018 | How can I have a UIBarButtonItem with both image and text? | <p>When I try to use an image for a UIBarButtonItem, the text isn't shown. Is there a way to show both the text and the image?</p> | 3,903,348 | 6 | 0 | null | 2010-10-11 01:35:28.91 UTC | 9 | 2019-01-28 13:59:16.487 UTC | 2018-02-20 13:09:29.543 UTC | null | 3,151,675 | null | 404,020 | null | 1 | 44 | objective-c|cocoa-touch|uibarbuttonitem | 35,096 | <p>You can init the UIBarButtonItem with a custom view that has both image and text. Here's a sample that uses a UIButton.</p>
<pre><code>UIImage *chatImage = [UIImage imageNamed:@"08-chat.png"];
UIButton *chatButton = [UIButton buttonWithType:UIButtonTypeCustom];
[chatButton setBackgroundImage:chatImage forState:UIControlStateNormal];
[chatButton setTitle:@"Chat" forState:UIControlStateNormal];
chatButton.frame = (CGRect) {
.size.width = 100,
.size.height = 30,
};
UIBarButtonItem *barButton= [[[UIBarButtonItem alloc] initWithCustomView:chatButton] autorelease];
self.toolbar.items = [NSArray arrayWithObject:barButton];
</code></pre> |
3,953,922 | Is it possible to write custom text on Google Maps API v3? | <p>Is it possible to write a custom text on Google Maps API v3 next to the marker, or I can use only the info window to do that?</p> | 3,955,258 | 6 | 2 | null | 2010-10-17 15:40:55.003 UTC | 13 | 2020-02-07 22:32:58.863 UTC | 2018-11-27 06:29:10.467 UTC | null | 4,366,533 | null | 198,003 | null | 1 | 45 | google-maps|google-maps-api-3|google-maps-markers | 81,025 | <p>To show custom text you need to create a custom overlay. Below is an example adapted from official Google documentation. You could also use <a href="http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries" rel="noreferrer">this library</a> for more "stylish" info windows</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><html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script>
//adapded from this example http://code.google.com/apis/maps/documentation/javascript/overlays.html#CustomOverlays
//text overlays
function TxtOverlay(pos, txt, cls, map) {
// Now initialize all properties.
this.pos = pos;
this.txt_ = txt;
this.cls_ = cls;
this.map_ = map;
// We define a property to hold the image's
// div. We'll actually create this div
// upon receipt of the add() method so we'll
// leave it null for now.
this.div_ = null;
// Explicitly call setMap() on this overlay
this.setMap(map);
}
TxtOverlay.prototype = new google.maps.OverlayView();
TxtOverlay.prototype.onAdd = function() {
// Note: an overlay's receipt of onAdd() indicates that
// the map's panes are now available for attaching
// the overlay to the map via the DOM.
// Create the DIV and set some basic attributes.
var div = document.createElement('DIV');
div.className = this.cls_;
div.innerHTML = this.txt_;
// Set the overlay's div_ property to this DIV
this.div_ = div;
var overlayProjection = this.getProjection();
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
div.style.left = position.x + 'px';
div.style.top = position.y + 'px';
// We add an overlay to a map via one of the map's panes.
var panes = this.getPanes();
panes.floatPane.appendChild(div);
}
TxtOverlay.prototype.draw = function() {
var overlayProjection = this.getProjection();
// Retrieve the southwest and northeast coordinates of this overlay
// in latlngs and convert them to pixels coordinates.
// We'll use these coordinates to resize the DIV.
var position = overlayProjection.fromLatLngToDivPixel(this.pos);
var div = this.div_;
div.style.left = position.x + 'px';
div.style.top = position.y + 'px';
}
//Optional: helper methods for removing and toggling the text overlay.
TxtOverlay.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
TxtOverlay.prototype.hide = function() {
if (this.div_) {
this.div_.style.visibility = "hidden";
}
}
TxtOverlay.prototype.show = function() {
if (this.div_) {
this.div_.style.visibility = "visible";
}
}
TxtOverlay.prototype.toggle = function() {
if (this.div_) {
if (this.div_.style.visibility == "hidden") {
this.show();
} else {
this.hide();
}
}
}
TxtOverlay.prototype.toggleDOM = function() {
if (this.getMap()) {
this.setMap(null);
} else {
this.setMap(this.map_);
}
}
var map;
function init() {
var latlng = new google.maps.LatLng(37.9069, -122.0792);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
customTxt = "<div>Blah blah sdfsddddddddddddddd ddddddddddddddddddddd<ul><li>Blah 1<li>blah 2 </ul></div>"
txt = new TxtOverlay(latlng, customTxt, "customBox", map)
}
</script>
<style>
.customBox {
background: yellow;
border: 1px solid black;
position: absolute;
}
</style>
</head>
<body onload="init()">
<div id="map" style="width: 600px; height: 600px;">
</div>
</body>
</html></code></pre>
</div>
</div>
</p> |
3,409,598 | Need .NET code to execute only when in debug configuration | <p>I have some code that access an API out on the web. One of the API's parameters allows me to let them know that I am testing.</p>
<p>I would like to only set this parameter in my code when I am testing. Currently, I just comment the code out when I do a release build. </p>
<p>Is there an automatic way of doing this based on the build configuration?</p> | 3,409,640 | 8 | 0 | null | 2010-08-04 20:33:42.58 UTC | 17 | 2022-02-16 13:04:03.353 UTC | 2013-11-22 20:18:33.94 UTC | null | 297,823 | null | 64,334 | null | 1 | 43 | c#|.net|vb.net|visual-studio|debugging | 31,588 | <h1>Solutions</h1>
<p>You can use one of the following—</p>
<h1>1: <code>Conditional</code> attribute</h1>
<p>The <a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute" rel="nofollow noreferrer"><code>Conditional</code></a> attribute indicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined.</p>
<p>Code example:</p>
<pre><code>[Conditional("DEBUG")]
static void Method() { }
</code></pre>
<h2>1b: <code>Conditional</code> attribute on local function (C# 9)</h2>
<p>Since C# 9, you may use attribute on a local function.</p>
<p>Code example:</p>
<pre><code>static void Main(string[] args)
{
[Conditional("DEBUG")]
static void Method() { }
Method();
}
</code></pre>
<h1>2: <code>#if</code> preprocessor directive</h1>
<p>When the C# compiler encounters an <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if" rel="nofollow noreferrer"><code>#if</code></a> <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/" rel="nofollow noreferrer">preprocessor directive</a>, followed eventually by an #endif directive, it compiles the code between the directives only if the specified symbol is defined. Unlike C and C++, you cannot assign a numeric value to a symbol. The #if statement in C# is Boolean and only tests whether the symbol has been defined or not.</p>
<p>Code example:</p>
<pre><code>#if DEBUG
static int testCounter = 0;
#endif
</code></pre>
<h1>3: <code>Debug.Write</code> methods</h1>
<p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.write" rel="nofollow noreferrer"><code>Debug.Write</code></a> (and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.writeline" rel="nofollow noreferrer"><code>Debug.WriteLine</code></a>) writes information about the debug to the trace listeners in the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.listeners?view=netframework-4.7.2#System_Diagnostics_Debug_Listeners" rel="nofollow noreferrer">Listeners</a> collection.</p>
<p>See also <a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.writeif" rel="nofollow noreferrer"><code>Debug.WriteIf</code></a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.writelineif" rel="nofollow noreferrer"><code>Debug.WriteLineIf</code></a>.</p>
<p>Code example:</p>
<pre><code>Debug.Write("Something to write in Output window.");
</code></pre>
<h1>Notes</h1>
<p>Beware of using <code>#if</code> directive since it can produce unintended situations in non-Debug (e.g. Release) build. For example, see:</p>
<pre><code> string sth = null;
#if DEBUG
sth = "oh, hi!";
#endif
Console.WriteLine(sth);
</code></pre>
<p>In this case, non-Debug build will print a blank message. But, this potentially may raise <code>NullReferenceException</code> in a different case.</p>
<h1>Read more</h1>
<ul>
<li>Eric Lippert. <a href="http://ericlippert.com/2009/09/10/whats-the-difference-between-conditional-compilation-and-the-conditional-attribute/" rel="nofollow noreferrer">What's the difference between conditional compilation and the conditional attribute?</a></li>
<li>C# Programmer's Reference: Conditional Methods Tutorial (<a href="https://web.archive.org/web/20110812082835/http://msdn.microsoft.com/en-us/library/aa288458(VS.71).aspx" rel="nofollow noreferrer">archive.org mirror</a>)</li>
<li>Bill Wagner. <a href="https://rads.stackoverflow.com/amzn/click/com/0321245660" rel="nofollow noreferrer" rel="nofollow noreferrer">Effective C#: 50 Specific Ways to Improve Your C#</a> (book), chapter: <em>Use Conditional Attributes Instead of #if</em></li>
<li>John Robbins. Assertions and Tracing in .NET (<a href="https://web.archive.org/web/20140418085730/msdn.microsoft.com/en-us/magazine/cc301363.aspx" rel="nofollow noreferrer">archive.org mirror</a>)</li>
<li>Sam Allen. <em>Dot Not Perls</em>:
<ul>
<li><a href="https://www.dotnetperls.com/conditional" rel="nofollow noreferrer">C# Conditional Attribute</a></li>
<li><a href="https://www.dotnetperls.com/debug-write" rel="nofollow noreferrer">C# Debug.Write</a></li>
</ul>
</li>
</ul>
<h1>See also</h1>
<p>There is also a tool, <a href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx" rel="nofollow noreferrer">DebugView</a>, which allow to capture debug information from external applications.</p> |
3,697,542 | Is there a wildcard selector for identifiers (id)? | <p>If I have an unknown amount of identifiers sharing a specific naming-scheme, is there a way to grab them all at once using jQuery?</p>
<pre><code>// These are the IDs I'd like to select
#instance1
#instance2
#instance3
#instance4
// What do I need to add or how do I need to modify this jQuery selector in order to select all the IDs above?
("#instanceWILDCARD").click(function(){}
</code></pre> | 3,697,550 | 9 | 1 | null | 2010-09-13 02:20:13.453 UTC | 17 | 2017-10-23 19:06:08.713 UTC | 2017-10-23 19:06:08.713 UTC | null | 4,033,913 | null | 223,367 | null | 1 | 76 | jquery|jquery-selectors|wildcard | 104,300 | <p>The <a href="http://api.jquery.com/attribute-starts-with-selector/" rel="noreferrer">attribute starts-with selector (<code>'^=</code>)</a> will work for your IDs, like this:</p>
<pre><code>$("[id^=instance]").click(function() {
//do stuff
});
</code></pre>
<p>However, consider giving your elements a common class, for instance (I crack myself up) <code>.instance</code>, and use that selector:</p>
<pre><code>$(".instance").click(function() {
//do stuff
});
</code></pre> |
3,684,923 | JavaScript variables declare outside or inside loop? | <p>In AS3 I believe you should initialise all variables outside loops for increased performance. Is this the case with JavaScript as well? Which is better / faster / best-practice?</p>
<pre><code>var value = 0;
for (var i = 0; i < 100; i++)
{
value = somearray[i];
}
</code></pre>
<p>or</p>
<pre><code>for (var i = 0 ; i < 100; i++)
{
var value = somearray[i];
}
</code></pre> | 3,685,090 | 12 | 11 | null | 2010-09-10 13:25:53.527 UTC | 59 | 2021-04-30 17:09:59.29 UTC | 2015-04-12 08:01:22.96 UTC | null | 4,285,056 | null | 219,609 | null | 1 | 225 | javascript|performance | 102,526 | <p>There is <strong>absolutely no difference</strong> in meaning or performance, in JavaScript or ActionScript.</p>
<p><code>var</code> is a directive for the parser, and <em>not</em> a command executed at run-time. If a particular identifier has been declared <code>var</code> once or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable. It makes no difference whether <code>value</code> is declared to be <code>var</code> inside the loop, outside the loop, or both.</p>
<p>Consequently you should write whichever you find most readable. I disagree with Crockford that putting all the vars at the top of a function is always the best thing. For the case where a variable is used temporarily in a section of code, it's better to declare <code>var</code> in that section, so the section stands alone and can be copy-pasted. Otherwise, copy-paste a few lines of code to a new function during refactoring, without separately picking out and moving the associated <code>var</code>, and you've got yourself an accidental global.</p>
<p>In particular:</p>
<pre><code>for (var i; i<100; i++)
do something;
for (var i; i<100; i++)
do something else;
</code></pre>
<p>Crockford will recommend you remove the second <code>var</code> (or remove both <code>var</code>s and do <code>var i;</code> above), and jslint will whinge at you for this. But IMO it's more maintainable to keep both <code>var</code>s, keeping all the related code together, instead of having an extra, easily-forgotten bit of code at the top of the function.</p>
<p>Personally I tend to declare as <code>var</code> the first assignment of a variable in an independent section of code, whether or not there's another separate usage of the same variable name in some other part of the same function. For me, having to declare <code>var</code> at all is an undesirable JS wart (it would have been better to have variables default to local); I don't see it as my duty to duplicate the limitations of [an old revision of] ANSI C in JavaScript as well.</p>
<p>(*: other than in nested function bodies)</p> |
3,611,457 | Android: Temporarily disable orientation changes in an Activity | <p>My main activity has some code that makes some database changes that should not be interrupted. I'm doing the heavy lifting in another thread, and using a progress dialog which I set as non-cancellable. However, I noticed that if I rotate my phone it restarts the activity which is REALLY bad for the process that was running, and I get a Force Close. </p>
<p>What I want to do is programatically disable screen orientation changes until my process completes, at which time orientation changes are enabled.</p> | 3,614,089 | 17 | 3 | null | 2010-08-31 17:11:27.327 UTC | 48 | 2017-08-11 09:33:07.537 UTC | 2013-07-23 12:51:28.573 UTC | null | 1,765,573 | null | 413,414 | null | 1 | 125 | android|screen-orientation|android-orientation | 85,545 | <p>As explained by Chris in his <a href="https://stackoverflow.com/questions/3611457/android-temporarily-disable-orientation-changes-in-an-activity/3611554#3611554">self-answer</a>, calling</p>
<pre><code>setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
</code></pre>
<p>and then</p>
<pre><code>setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
</code></pre>
<p>really works like charm... on real devices !</p>
<p>Don't think that it's broken when testing on the emulator, the ctrl+F11 shortcut ALWAYS change the screen orientation, without emulating sensors moves.</p>
<p>EDIT: this was not the best possible answer. As explained in the comments, there are issues with this method. <a href="https://stackoverflow.com/questions/3821423/background-task-progress-dialog-orientation-change-is-there-any-100-working/3821998#3821998">The real answer is here</a>.</p> |
8,339,305 | Using HttpContext.Current.Server.MapPath in Window Application? | <p>Can i do something like this in window Application?</p>
<pre><code>HttpContext.Current.Server.MapPath("Email/ForgotPassword.txt"));
</code></pre>
<p>This project is a web based application.</p>
<p>And my next project is basically a window service...</p>
<p>Seeking for advice.</p> | 8,339,684 | 4 | 0 | null | 2011-12-01 09:50:12.777 UTC | 1 | 2017-01-04 13:06:17.033 UTC | 2014-03-24 03:59:25.467 UTC | null | 883,398 | null | 883,398 | null | 1 | 4 | c#|.net | 44,743 | <p>To get the path that the Exe is running at (which is a good location to add paths like "Email"), use:</p>
<pre><code>string filePath = Application.StartupPath + "\\Email\\ForgotPassword.txt";
</code></pre>
<p>This path is the ..\bin\debug\Email path when you run it on VS and ..\Email path when you run it after installation.</p>
<p>There are few alternates to do this like these to access the directory path:</p>
<pre><code>string appPath = Path.GetDirectoryName(Application.ExecutablePath);
</code></pre>
<p>or</p>
<pre><code>using System.IO;
using System.Reflection;
string path = Path.GetDirectoryName(
Assembly.GetAssembly(typeof(MyClass)).CodeBase);
</code></pre>
<p>you can do manipulation with the <a href="http://msdn.microsoft.com/en-us/library/system.io.path.aspx" rel="noreferrer">Path</a> class like get the full path, directory name etc etc.. </p>
<p>Check this MSDN forum thread <a href="http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/cc0cfbc5-5824-4b2e-9e9c-11facad95b46" rel="noreferrer">How to get the current directory path c# winfows for application</a> for details.</p>
<blockquote>
<p>As you expecting to do windows application as like web.. It is not
possible.</p>
</blockquote> |
8,132,016 | how to install hiphop for php? | <p>The most of devepolers know something about Facebook's Hiphop for php, I want to use it in my scripts but have no idea where to start.</p>
<p>Should I speak with my server provider? or Do I need to add some codes into my scripts?</p> | 8,132,054 | 4 | 0 | null | 2011-11-15 05:45:03.31 UTC | 11 | 2014-08-01 11:44:35.11 UTC | null | null | null | null | 823,030 | null | 1 | 10 | php|hiphop | 7,767 | <p>HipHop is very difficult to install, but luckily for you I've just been through it!</p>
<p>You need a dedicated server, easiest to install on Red Hat or CentOS, or Amazon Linux. You cannot install it on a shared host, you need root access.</p>
<p>It's also easier to install on a clean server (just the OS).</p>
<p>I recommend you get a clean Instance from Amazon Web Services and install it on that, you can turn it off whenever you don't need it. It's not expensive.</p>
<p>This will install it on an AWS Instance, put it into SSH one line at a time:</p>
<pre><code><!-- language: sh -->
sudo su -
export LDFLAGS="$LDFLAGS -lrt"
export CMAKE_PREFIX_PATH=/home/ec2-user/hiphop/local
export HPHP_HOME=/home/ec2-user/hiphop/hiphop-php
export HPHP_LIB=/home/ec2-user/hiphop/hiphop-php/bin
ldconfig
yum -y install git cmake boost pcre-devel libicu-devel libmcrypt-devel oniguruma-devel mysql-devel gd-devel boost-devel libxml2-devel libcap-devel binutils-devel flex bison expat-devel patch gcc gcc-c++ bzip2 bzip2-devel memcached openldap openldap-devel readline-devel libc-client-devel pam-devel
mkdir /home/ec2-user/hiphop
cd /home/ec2-user/hiphop
git clone git://github.com/facebook/hiphop-php.git
wget "http://downloads.sourceforge.net/project/re2c/re2c/0.13.5/re2c-0.13.5.tar.gz?use_mirror=cdnetworks-us-2"
wget "http://www.threadingbuildingblocks.org/uploads/77/142/2.2/tbb22_20090809oss_src.tgz"
wget http://curl.haxx.se/download/curl-7.20.0.tar.bz2
wget http://www.monkey.org/~provos/libevent-1.4.14-stable.tar.gz
wget http://launchpad.net/libmemcached/1.0/0.48/+download/libmemcached-0.48.tar.gz
tar xvjf curl-7.20.0.tar.bz2
tar xvzf libevent-1.4.14-stable.tar.gz
tar xvzf re2c-0.13.5.tar.gz
tar xvzf tbb22_20090809oss_src.tgz
tar xvzf libmemcached-0.48.tar.gz
export LDFLAGS="$LDFLAGS -lrt"
export CMAKE_PREFIX_PATH=/home/ec2-user/hiphop/local
cd /home/ec2-user/hiphop/tbb22_20090809oss
gmake
cp -Rp include/tbb/ /usr/include/
cp /home/ec2-user/hiphop/tbb22_20090809oss/build/*_release/*.so /usr/lib/
cp /home/ec2-user/hiphop/tbb22_20090809oss/build/*_release/*.so.2 /usr/lib/
ldconfig
cd /home/ec2-user/hiphop/re2c-0.13.5
./configure --prefix=/home/ec2-user/hiphop/local
make install
cd /home/ec2-user/hiphop/libevent-1.4.14-stable
cp /home/ec2-user/hiphop/hiphop-php/src/third_party/libevent-1.4.14.fb-changes.diff .
patch < libevent-1.4.14.fb-changes.diff
./configure --prefix=/home/ec2-user/hiphop/local
make install
cd /home/ec2-user/hiphop/curl-7.20.0
cp /home/ec2-user/hiphop/hiphop-php/src/third_party/libcurl.fb-changes.diff .
patch -p1 < libcurl.fb-changes.diff
./configure --prefix=/home/ec2-user/hiphop/local
make install
cd /home/ec2-user/hiphop/libmemcached-0.48
./configure --prefix=/home/ec2-user/hiphop/local
make install
cd /home/ec2-user/hiphop/hiphop-php
git submodule init
git submodule update
export HPHP_HOME=/home/ec2-user/hiphop/hiphop-php
export HPHP_LIB=/home/ec2-user/hiphop/hiphop-php/bin
cmake .
make
alias hphp=/home/ec2-user/hiphop/hiphop-php/src/hphp/hphp
</code></pre>
<p>Then every time you login to SSH, paste this:</p>
<pre><code><!-- language: sh -->
sudo su -
cd /home/ec2-user
export LDFLAGS="$LDFLAGS -lrt"
export CMAKE_PREFIX_PATH=/home/ec2-user/hiphop/local
export HPHP_HOME=/home/ec2-user/hiphop/hiphop-php
export HPHP_LIB=/home/ec2-user/hiphop/hiphop-php/bin
ldconfig
alias hphp=/home/ec2-user/hiphop/hiphop-php/src/hphp/hphp
</code></pre>
<p>Oh, I should add that you will need HipHop installed on the server you want to run the compiled scripts on. So with all this considered, it's probably not what you want.</p> |
7,995,559 | VirtualTreeView: properly handling selection changes | <p>This question will seem obvious to those who haven't encountered the problem themselves.</p>
<p>I need to handle selection changes in VTV. I have a flat list of nodes. I need to do stuff with all currently selected nodes whenever</p>
<ol>
<li>User clicks a node;</li>
<li>User Shift/Ctrl-clicks a node;</li>
<li>User uses arrow keys to navigate the list;</li>
<li>User creates selection by dragging the mouse</li>
<li>User removes selection by clicking on empty space or Ctrl-clicking the only selected node</li>
</ol>
<p>etc. It's the most common and expected behavior, just like Windows Explorer: when you select files with mouse and/or keyboard, the information panel shows their properties. I need nothing more than that.
And this is where I get stuck.</p>
<p>Some of my research follows.</p>
<hr>
<p>At first I used OnChange. It seemed to work well, but I noticed some strange flickering and I found that in the most common scenario (one node is selected, the user clicks another one) OnChange is fired twice:</p>
<ol>
<li>When the old node is deselected. At this time the selection is empty. I refresh my GUI to show "nothing is selected" label in place of all the properties.</li>
<li>When the new node is selected. I refresh my GUI again to show the properties of new node. Hence the flickering.</li>
</ol>
<p>This problem was googleable, so I found that people use OnFocusChange and OnFocusChanging instead of OnChange. But this way only works for single selection. With multiple selection, drag-selection and navigation keys this doesn't work. In some cases Focus events don't even fire at all (e.g. when selection is removed by clicking empty space).</p>
<p>I did some debug output study to learn how these handlers are fired in different scenarios. What I found out is a total mess without any visible sense or pattern.</p>
<pre><code>C OnChange
FC OnFocusChange
FCg OnFocusChanging
- nil parameter
* non-nil parameter
! valid selection
Nodes User action Handlers fired (in order)
selected
0 Click node FCg-* C*!
1 Click same FCg**
1 Click another C- FCg** C*! FC*
1 Ctlr + Click same FCg** C*!
1 Ctrl + Click another FCg** C*! FC*
1 Shift + Click same FCg** C*!
1 Shift + Click another FCg** C-! FC*
N Click focused selected C-! FCg**
N Click unfocused selected C-! FCg** FC*
N Click unselected C- FCg** C*! FC*
N Ctrl + Click unselected FCg** C*! FC*
N Ctrl + Click focused FCg** C*!
N Shift + Click unselected FCg** C-! FC*
N Shift + Click focused FCg** C-!
1 Arrow FCg** FC* C- C*!
1 Shift + Arrow FCg** FC* C*!
N Arrow FCg** FC* C- C*!
N Shift + Arrow (less) C*! FCg** FC*
N Shift + Arrow (more) FCg** FC* C*!
Any Ctrl/Shift + Drag (more) C*! C-!
0 Click empty -
1/N Click Empty C-!
N Ctrl/Shift + Drag (less) C-!
1 Ctrl/Shift + Drag (less) C-!
0 Arrow FCg** FC* C*!
</code></pre>
<p>This is quite hard to read. In the nutshell it says that depending on the specific user action, the three handlers (OnChange, OnFocusChange and OnFocusChanging) are called in random order with random parameters. FC and FCg are sometimes never called when I still need the event handled, so it is obvious I have to use OnChange.</p>
<p>But the next task is: inside OnChange I can't know if I should use this call or wait for the next one. Sometimes the set of selected nodes is intermediate and non-useful, and processing it will cause GUI flickering and/or unwanted heavy calculations.</p>
<p>I only need the calls that are marked with "!" in the table above. But there is no way to distinguish them from inside. E.g.: if I'm in "C-" (OnChange, Node = nil, SelectedCount = 0) it could mean that user removed selection (then I need to handle it) or that they clicked another node (then I need to wait for the next OnChange call when new selection is formed).</p>
<hr>
<p>Anyway, I hope my research was unnecessary. I hope that I'm missing out something that would make the solution simple and clear, and that you, guys, are going to point it out for me. Solving this puzzle using what I have so far would generate some terribly unreliable and complex logic.</p>
<p>Thanks in advance!</p> | 7,996,113 | 4 | 0 | null | 2011-11-03 13:18:39.953 UTC | 8 | 2019-05-18 10:18:11.667 UTC | 2011-11-03 13:32:59.937 UTC | null | 1,027,604 | null | 1,027,604 | null | 1 | 12 | delphi|user-interface|virtualtreeview | 3,964 | <p>Set the <code>ChangeDelay</code> property to an appropriate, greater than zero value in milliseconds, e.g. <code>100</code>. This implements the one-shot timer Rob Kennedy suggests in his answer.</p> |
8,106,637 | UIButton with GradientLayer obscures image and darkens gradient | <p>I have an UIButton here where I'd like to have a gradient as the background below the image (symbol with transparent background), but I'm facing two different problems.</p>
<p>First of the CAGradientLayer seems to overlay on top of the image no matter how I try to add it, obscuring the image completely.</p>
<p>Secondly the gradient itself seems to be darkened a lot, like the button was disabled, which it isn't.</p>
<p>Here's my code:</p>
<pre><code>self.backButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 35, 28, 28)];
[backButton addTarget:self
action:@selector(goBack)
forControlEvents:UIControlEventTouchUpInside];
[backButton setBackgroundColor:[UIColor clearColor]];
CAGradientLayer *buttonGradient = [CAGradientLayer layer];
buttonGradient.frame = backButton.bounds;
buttonGradient.colors = [NSArray arrayWithObjects:
(id)[[UIColor colorWithRed:.0
green:.166
blue:.255
alpha:1] CGColor],
(id)[[UIColor colorWithRed:.0
green:.113
blue:.255
alpha:1] CGColor],
nil];
[buttonGradient setCornerRadius:backButton.frame.size.width / 2];
[backButton.layer insertSublayer:buttonGradient
atIndex:0];
[backButton setImage:[UIImage imageNamed:@"backarrow.png"]
forState:UIControlStateNormal];
[backButton setEnabled:NO];
[topbarView addSubview:backButton];
</code></pre> | 8,261,015 | 4 | 0 | null | 2011-11-12 18:37:20.757 UTC | 6 | 2018-08-20 21:13:22.417 UTC | null | null | null | null | 527,741 | null | 1 | 34 | ios|uibutton|calayer|cagradientlayer | 8,963 | <p>So I managed to get around this by doing a [button bringSubviewToFront:button.imageView] after adding the gradient. Seems that no matter what I do the new layer will add on top of the imageView, so I need to push that to the front afterwards.</p>
<p><strong>Objective-C:</strong></p>
<pre><code>[button bringSubviewToFront:button.imageView]
</code></pre>
<p><strong>Swift 4.1:</strong></p>
<pre><code>button.bringSubview(toFront:button.imageView!)
</code></pre> |
7,723,549 | Getting and removing the first character of a string | <p>I would like to do some 2-dimensional walks using strings of characters by assigning different values to each character. I was planning to 'pop' the first character of a string, use it, and repeat for the rest of the string.</p>
<p>How can I achieve something like this?</p>
<pre><code>x <- 'hello stackoverflow'
</code></pre>
<p>I'd like to be able to do something like this:</p>
<pre><code>a <- x.pop[1]
print(a)
'h'
print(x)
'ello stackoverflow'
</code></pre> | 7,723,722 | 7 | 0 | null | 2011-10-11 08:55:19.577 UTC | 17 | 2022-01-26 00:18:00.977 UTC | 2011-10-12 01:04:06.553 UTC | null | 390,278 | null | 489,010 | null | 1 | 123 | string|r | 250,875 | <p>See <a href="https://www.rdocumentation.org/packages/base/topics/substr"><code>?substring</code></a>.</p>
<pre><code>x <- 'hello stackoverflow'
substring(x, 1, 1)
## [1] "h"
substring(x, 2)
## [1] "ello stackoverflow"
</code></pre>
<hr>
<p>The idea of having a <code>pop</code> method that both returns a value and has a side effect of updating the data stored in <code>x</code> is very much a concept from object-oriented programming. So rather than defining a <code>pop</code> function to operate on character vectors, we can make a <a href="https://www.rdocumentation.org/packages/methods/topics/ReferenceClasses">reference class</a> with a <code>pop</code> method.</p>
<pre><code>PopStringFactory <- setRefClass(
"PopString",
fields = list(
x = "character"
),
methods = list(
initialize = function(x)
{
x <<- x
},
pop = function(n = 1)
{
if(nchar(x) == 0)
{
warning("Nothing to pop.")
return("")
}
first <- substring(x, 1, n)
x <<- substring(x, n + 1)
first
}
)
)
x <- PopStringFactory$new("hello stackoverflow")
x
## Reference class object of class "PopString"
## Field "x":
## [1] "hello stackoverflow"
replicate(nchar(x$x), x$pop())
## [1] "h" "e" "l" "l" "o" " " "s" "t" "a" "c" "k" "o" "v" "e" "r" "f" "l" "o" "w"
</code></pre> |
7,755,214 | Merge maps by key | <p>Say I have two maps:</p>
<pre><code>val a = Map(1 -> "one", 2 -> "two", 3 -> "three")
val b = Map(1 -> "un", 2 -> "deux", 3 -> "trois")
</code></pre>
<p>I want to merge these maps by key, applying some function to collect the values (in this particular case I want to collect them into a seq, giving:</p>
<pre><code>val c = Map(1 -> Seq("one", "un"), 2 -> Seq("two", "deux"), 3 -> Seq("three", "trois"))
</code></pre>
<p>It feels like there should be a nice, idiomatic way of doing this.</p> | 7,758,300 | 8 | 1 | null | 2011-10-13 13:55:43.023 UTC | 12 | 2019-11-27 11:54:30.227 UTC | 2019-06-08 08:11:46.543 UTC | null | 9,297,144 | null | 340,251 | null | 1 | 28 | scala|functional-programming|maps|scalaz | 26,731 | <p><a href="http://www.scala-lang.org/api/current/scala/collection/immutable/IntMap.html"><code>scala.collection.immutable.IntMap</code></a> has an <code>intersectionWith</code> method that does precisely what you want (I believe):</p>
<pre><code>import scala.collection.immutable.IntMap
val a = IntMap(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four")
val b = IntMap(1 -> "un", 2 -> "deux", 3 -> "trois")
val merged = a.intersectionWith(b, (_, av, bv: String) => Seq(av, bv))
</code></pre>
<p>This gives you <code>IntMap(1 -> List(one, un), 2 -> List(two, deux), 3 -> List(three, trois))</code>. Note that it correctly ignores the key that only occurs in <code>a</code>.</p>
<p>As a side note: I've often found myself wanting the <code>unionWith</code>, <code>intersectionWith</code>, etc. functions from <a href="http://hackage.haskell.org/packages/archive/containers/0.4.2.0/doc/html/Data-Map.html">Haskell's <code>Data.Map</code></a> in Scala. I don't think there's any principled reason that they should only be available on <code>IntMap</code>, instead of in the base <code>collection.Map</code> trait.</p> |
7,867,537 | How to select a drop-down menu value with Selenium using Python? | <p>I need to select an element from a <strong>drop-down</strong> menu.</p>
<p>For example: </p>
<pre class="lang-html prettyprint-override"><code><select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
</code></pre>
<p><strong>1)</strong> First I have to click on it. I do this: </p>
<pre><code>inputElementFruits = driver.find_element_by_xpath("//select[id='fruits']").click()
</code></pre>
<p><strong>2)</strong> After that I have to select the good element, lets say <code>Mango</code>.</p>
<p>I tried to do it with <code>inputElementFruits.send_keys(...)</code> but it did not work.</p> | 7,972,225 | 18 | 0 | null | 2011-10-23 16:40:46.767 UTC | 104 | 2022-08-14 18:29:33.143 UTC | 2020-07-20 20:11:12.22 UTC | null | 7,429,447 | null | 963,003 | null | 1 | 301 | python|selenium|selenium-webdriver|webdriver|html-select | 499,846 | <p>Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.</p>
<p>Just find the element and then enumerate the options, selecting the option(s) you want.</p>
<p>Here is an example:</p>
<pre><code>from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()
</code></pre>
<p>You can read more in: <br />
<a href="https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver">https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver</a></p> |
8,033,550 | Convert an integer to an array of digits | <p>I try to convert an integer to an array. For example, 1234 to <code>int[] arr = {1,2,3,4};</code>.</p>
<p>I've written a function:</p>
<pre><code>public static void convertInt2Array(int guess) {
String temp = Integer.toString(guess);
String temp2;
int temp3;
int [] newGuess = new int[temp.length()];
for(int i=0; i<=temp.length(); i++) {
if (i!=temp.length()) {
temp2 = temp.substring(i, i+1);
} else {
temp2 = temp.substring(i);
//System.out.println(i);
}
temp3 = Integer.parseInt(temp2);
newGuess[i] = temp3;
}
for(int i=0; i<=newGuess.length; i++) {
System.out.println(newGuess[i]);
}
}
</code></pre>
<p>But an exception is thrown:</p>
<blockquote>
<p>Exception in thread "main" java.lang.NumberFormatException: For input string: "" <br/>
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) <br/>
<br/>
at java.lang.Integer.parseInt(Integer.java:504) <br/>
at java.lang.Integer.parseInt(Integer.java:527) <br/>
at q4.test.convertInt2Array(test.java:28) <br/>
at q4.test.main(test.java:14) <br/>
Java Result: 1 <br/></p>
</blockquote>
<p>How can I fix this?</p> | 8,033,593 | 24 | 2 | null | 2011-11-07 06:57:43.273 UTC | 33 | 2022-08-04 18:20:11.073 UTC | 2020-11-07 16:38:20.327 UTC | null | 63,550 | null | 925,552 | null | 1 | 71 | java|integer | 435,249 | <p>The immediate problem is due to you using <code><= temp.length()</code> instead of <code>< temp.length()</code>. However, you can achieve this a lot more simply. Even if you use the string approach, you can use:</p>
<pre><code>String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}
</code></pre>
<p>You need to make the same change to use <code>< newGuess.length()</code> when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use <code>newGuess[4]</code>. The vast majority of <code>for</code> loops I write use <code><</code> in the condition, rather than <code><=</code>.</p> |
4,680,024 | Remove last character of a string (VB.NET 2008) | <p>I am trying to remove a last character of a string. This last character is a newline (System.Environment.NewLine).</p>
<p>I have tried some things, but I can not remove it.</p>
<p>Example:</p>
<pre><code>myString.Remove(sFP.Length - 1)
</code></pre>
<p>Example 2:</p>
<pre><code>myString= Replace(myString, Environment.NewLine, "", myString.Length - 1)
</code></pre>
<p>How I can do it?</p> | 4,680,049 | 3 | 0 | null | 2011-01-13 12:30:21.393 UTC | 2 | 2017-11-06 09:01:31.317 UTC | 2016-12-10 13:57:06.753 UTC | null | 63,550 | null | 181,984 | null | 1 | 8 | vb.net|string | 51,201 | <p>If your newline is CR LF, it's actually two consecutive characters. Try your <code>Remove</code> call with <code>Length - 2</code>.</p>
<p>If you want to remove all "\n" and "\r" characters at the end of string, try calling <code>TrimEnd</code>, passing the characters:</p>
<pre><code>str.TrimEnd(vbCr, vbLf)
</code></pre>
<p>To remove all the whitespace characters (newlines, tabs, spaces, ...) just call <code>TrimEnd</code> without passing anything.</p> |
4,443,476 | Optimal bcrypt work factor | <p>What would be an ideal bcrypt work factor for password hashing.</p>
<p>If I use a factor of 10, it takes approx .1s to hash a password on my laptop. If we end up with a very busy site, that turns into a good deal of work just checking people's passwords.</p>
<p>Perhaps it would be better to use a work factor of 7, reducing the total password hash work to about .01s per laptop-login?</p>
<p>How do you decide the tradeoff between brute force safety and operational cost?</p> | 4,766,811 | 3 | 3 | null | 2010-12-14 19:46:33.18 UTC | 37 | 2021-04-23 17:01:04.943 UTC | null | null | null | null | 534,246 | null | 1 | 89 | bcrypt | 22,440 | <p>Remember that the value is stored in the password: <code>$2a$(2 chars work)$(22 chars salt)(31 chars hash)</code>. It is not a fixed value.</p>
<p>If you find the load is too high, just make it so the next time they log in, you crypt to something faster to compute. Similarly, as time goes on and you get better servers, if load isn't an issue, you can upgrade the strength of their hash when they log in.</p>
<p>The trick is to keep it taking roughly the same amount of time forever into the future along with Moore's Law. <strong>The number is log2, so every time computers double in speed, add 1 to the default number.</strong></p>
<p>Decide how long you want it to take to brute force a user's password. For some common dictionary word, for instance, your account creation probably already warned them their password was weak. If it's one of 1000 common words, say, and it takes an attacker 0.1s to test each, that buys them 100s (well, some words are more common...). If a user chose 'common dictionary word' + 2 numbers, that's over two hours. If your password database is compromised, and the attacker can only get a few hundred passwords a day, you've bought most of your users hours or days to safely change their passwords. It's a matter of buying them time.</p>
<p><a href="http://www.postgresql.org/docs/8.3/static/pgcrypto.html" rel="noreferrer">http://www.postgresql.org/docs/8.3/static/pgcrypto.html</a> has some times for cracking passwords for you to consider. Of course, the passwords they list there are random letters. Dictionary words... Practically speaking you can't save the guy whose password is 12345.</p> |
4,616,646 | Specifying relative file location in web.config for use by standard C# class library | <p>I'm struggling to find a way of specifying a file location in <code>web.config</code> appSettings that avoids using hard-coded paths but allows a non-'web aware' C# library to find a file.</p>
<p>The C# library uses standard <code>File.Open</code>, <code>File.Exists</code> methods, etc. to operate on a data file, which is stored in my web application (ASP.NET MVC) tree, e.g. under:</p>
<pre><code>\content\data\MyDataFile.txt
</code></pre>
<p>Requirements:</p>
<ul>
<li>I want to be able to specify my path like, e.g.:</li>
</ul>
<pre>
<appSettings>
this--> <add key="MyFileLocation" value="~\content\data\MyDataFile.txt" />
not --> <add key="MyFileLocation" value="c:\inetpub\wwwroot\foo\content\data\MyDataFile.txt" />
</appSettings>
</pre>
<ul>
<li>I don't want the C# library to be aware of the web application it's being used in, as it is used in other software, and the web application has no need to know about the configuration of the C# library so I don't really want to pass config info between the layers if possible.</li>
</ul>
<p>Any suggestions on how I can do this cleanly? Thanks!</p> | 4,617,253 | 4 | 0 | null | 2011-01-06 15:38:35.343 UTC | 5 | 2017-04-26 17:55:11.017 UTC | null | null | null | null | 164,861 | null | 1 | 17 | c#|asp.net | 60,860 | <p>You could use <code>Path.Combine</code> to combine <code>AppDomain.CurrentDomain.BaseDirectory</code> and your relative path.</p>
<p>This will give you a path relative to the ASP.NET root directory (~/) in an ASP.NET app, or a path relative to the directory containing the executable in a WinForms or Console application.</p> |
4,445,883 | node-websocket-server: possible to have multiple, separate "broadcasts" for a single node.js process? | <p>I'd like to know if it's possible to broadcast on different websocket "connections" running from the same <a href="https://github.com/miksago/node-websocket-server" rel="noreferrer">node-websocket-server</a> app instance. Imagine a chatroom server with multiple rooms, only broadcasting messages to the participants specific to each room, on a single node.js server process. I've successfully implemented a one-chatroom-per-process solution, but I want to take it to the next level.</p> | 4,446,178 | 4 | 0 | null | 2010-12-15 01:14:23.38 UTC | 64 | 2014-07-05 12:54:33.56 UTC | 2014-07-05 12:54:33.56 UTC | null | 314,166 | null | 166,137 | null | 1 | 62 | node.js|websocket | 57,117 | <p>You would probably like to try Push-it: <a href="http://github.com/aaronblohowiak/Push-It" rel="noreferrer">http://github.com/aaronblohowiak/Push-It</a> which is built on top of Socket.IO. Design adheres to the Bayeux Protocol.</p>
<p>However, if you need something that uses redis pubsub you can check <a href="http://github.com/shripadk/Socket.IO-PubSub" rel="noreferrer">http://github.com/shripadk/Socket.IO-PubSub</a></p>
<p>Specifically answering your question: You can maintain an array of all the clients connected to the websocket server. And probably just broadcast to a subset of those clients? The broadcast method does essentially that under the hood. node-websocket-server/Socket.IO maintains an array of all the clients connected and just loops through all of them "send"ing a message to each of the clients. Gist of the code:</p>
<pre><code>// considering you storing all your clients in an array, should be doing this on connection:
clients.push(client)
// loop through that array to send to each client
Client.prototype.broadcast = function(msg, except) {
for(var i in clients) {
if(clients[i].sessionId !== except) {
clients[i].send({message: msg});
}
}
}
</code></pre>
<p>So if you want to relay messages only to specific channels, just maintain a list of all the channels subscribed by the client. Here is a simple example (to just get you started) :</p>
<pre><code>clients.push(client);
Client.prototype.subscribe = function(channel) {
this.channel = channel;
}
Client.prototype.unsubscribe = function(channel) {
this.channel = null;
}
Client.prototype.publish = function(channel, msg) {
for(var i in clients) {
if(clients[i].channel === channel) {
clients[i].send({message: msg});
}
}
}
</code></pre>
<p>To make it even easier use EventEmitters. So in node-websocket-server/Socket.IO see where the messages are being received and parse the message to check the type (subscribe/unsubscribe/publish) and emit the event with the message depending on the type. Example:</p>
<pre><code>Client.prototype._onMessage = function(message) {
switch(message.type) {
case 'subscribe':
this.emit('subscribe', message.channel);
case 'unsubscribe':
this.emit('unsubscribe', message.channel);
case 'publish':
this.emit('publish', message.channel, message.data);
default:
}
}
</code></pre>
<p>Listen to the events emitted in your app's on('connection') :</p>
<pre><code>client.on('subscribe', function(channel) {
// do some checks here if u like
client.subscribe(channel);
});
client.on('unsubscribe', function(channel) {
client.unsubscribe(channel);
});
client.on('publish', function(channel, message) {
client.publish(channel, message);
});
</code></pre>
<p>Hope this helps.</p> |
4,173,384 | How to make sure a function is only called once | <p>Suppose I have a function named caller, which will call a function named callee:</p>
<pre><code>void caller()
{
callee();
}
</code></pre>
<p>Now caller might be called many times in the application, and you want to make sure callee is only called once. (kind of lazy initialization), you could implement it use a flag:</p>
<pre><code>void caller()
{
static bool bFirst = true;
if(bFirst)
{
callee();
bFirst = false;
}
}
</code></pre>
<p>My opinion for this is it needs more code, and it needs one more check in every call of function caller.<br>
A better solution to me is as follow: (suppose callee returns int)</p>
<pre><code>void caller()
{
static int ret = callee();
}
</code></pre>
<p>But this can't handle the case if callee returns void, my solution is using the comma expression:</p>
<pre><code>void caller()
{
static int ret = (callee(), 1);
}
</code></pre>
<p>But the problem with this is that comma expression is not popular used and people may get confused when see this line of code, thus cause problems for maintainance.</p>
<p>Do you have any good idea to make sure a function is only called once?</p> | 4,173,576 | 5 | 7 | null | 2010-11-13 16:01:15.857 UTC | 10 | 2014-12-01 10:25:41.67 UTC | null | null | null | null | 70,198 | null | 1 | 26 | c++ | 15,768 | <p>Thread-safe:</p>
<pre><code> static boost::once_flag flag = BOOST_ONCE_INIT;
boost::call_once([]{callee();}, flag);
</code></pre> |
4,290,081 | Fitting data to distributions? | <p>I am not a statistician (more of a researchy web developer) but I've been hearing a lot about <a href="http://www.scipy.org/" rel="noreferrer">scipy</a> and <a href="http://www.r-project.org/" rel="noreferrer">R</a> these days. So out of curiosity I wanted to ask this question (though it might sound silly to the experts around here) because I am not sure of the advances in this area and want to know how people without a sound statistics background approach these problems. </p>
<p>Given a set of real numbers observed from an experiment, let us say they belong to one of the many distributions out there (like Weibull, Erlang, Cauchy, Exponential etc.), are there any automated ways of finding the right distribution and the distribution parameters for the data? Are there any good tutorials that walk me through the process? </p>
<p><strong>Real-world Scenario:</strong>
For instance, let us say I initiated a small survey and recorded information about how many people a person talks to every day for say 300 people and I have the following information:</p>
<pre><code>1 10
2 5
3 20
...
...
</code></pre>
<p>where X Y tells me that person X talked to Y people during the period of the survey. Now using the information from the 300 people, I want to fit this into a model. The question boils down to are there any automated ways of finding out the right distribution and distribution parameters for this data or if not, is there a good step-by-step procedure to achieve the same?</p> | 4,290,214 | 6 | 3 | null | 2010-11-27 04:10:10.937 UTC | 29 | 2013-05-05 22:15:09.24 UTC | 2010-11-27 04:35:36.73 UTC | null | 184,046 | null | 184,046 | null | 1 | 29 | python|r|statistics|scipy | 13,944 | <p>This is a complicated question, and there are no perfect answers. I'll try to give you an overview of the major concepts, and point you in the direction of some useful reading on the topic. </p>
<p>Assume that you a one dimensional set of data, and you have a finite set of probability distribution functions that you think the data may have been generated from. You can consider each distribution independently, and try to find parameters that are reasonable given your data.
There are two methods for setting parameters for a probability distribution function given data:</p>
<ol>
<li><a href="http://en.wikipedia.org/wiki/Least_squares" rel="noreferrer">Least Squares</a></li>
<li><a href="http://en.wikipedia.org/wiki/Maximum_likelihood" rel="noreferrer">Maximum Likelihood</a></li>
</ol>
<p>In my experience, Maximum Likelihood has been preferred in recent years, although this may not be the case in every field. </p>
<p>Here's a concrete example of how to estimate parameters in R. Consider a set of random points generated from a Gaussian distribution with mean of 0 and standard deviation of 1:</p>
<pre><code>x = rnorm( n = 100, mean = 0, sd = 1 )
</code></pre>
<p>Assume that you know the data were generated using a Gaussian process, but you've forgotten (or never knew!) the parameters for the Gaussian. You'd like to use the data to give you reasonable estimates of the mean and standard deviation. In R, there is a standard library that makes this very straightforward:</p>
<pre><code>library(MASS)
params = fitdistr( x, "normal" )
print( params )
</code></pre>
<p>This gave me the following output:</p>
<pre><code> mean sd
-0.17922360 1.01636446
( 0.10163645) ( 0.07186782)
</code></pre>
<p>Those are fairly close to the right answer, and the numbers in parentheses are confidence intervals around the parameters. Remember that every time you generate a new set of points, you'll get a new answer for the estimates.</p>
<p>Mathematically, this is using maximum likelihood to estimate both the mean and standard deviation of the Gaussian. Likelihood means (in this case) "probability of data given values of the parameters." Maximum likelihood means "the values of the parameters that maximize the probability of generating my input data." Maximum likelihood estimation is the algorithm for finding the values of the parameters which maximize the probability of generating the input data, and for some distributions it can involve <a href="http://en.wikipedia.org/wiki/Optimization_(mathematics)" rel="noreferrer">numerical optimization</a> algorithms. In R, most of the work is done by <a href="http://stat.ethz.ch/R-manual/R-devel/library/MASS/html/fitdistr.html" rel="noreferrer">fitdistr</a>, which in certain cases will call <a href="http://sekhon.berkeley.edu/stats/html/optim.html" rel="noreferrer">optim</a>.</p>
<p>You can extract the log-likelihood from your parameters like this:</p>
<pre><code>print( params$loglik )
[1] -139.5772
</code></pre>
<p>It's more common to work with the log-likelihood rather than likelihood to avoid rounding errors. Estimating the joint probability of your data involves multiplying probabilities, which are all less than 1. Even for a small set of data, the joint probability approaches 0 very quickly, and adding the log-probabilities of your data is equivalent to multiplying the probabilities. The likelihood is maximized as the log-likelihood approaches 0, and thus more negative numbers are worse fits to your data. </p>
<p>With computational tools like this, it's easy to estimate parameters for any distribution. Consider this example:</p>
<pre><code>x = x[ x >= 0 ]
distributions = c("normal","exponential")
for ( dist in distributions ) {
print( paste( "fitting parameters for ", dist ) )
params = fitdistr( x, dist )
print( params )
print( summary( params ) )
print( params$loglik )
}
</code></pre>
<p>The exponential distribution doesn't generate negative numbers, so I removed them in the first line. The output (which is stochastic) looked like this:</p>
<pre><code>[1] "fitting parameters for normal"
mean sd
0.72021836 0.54079027
(0.07647929) (0.05407903)
Length Class Mode
estimate 2 -none- numeric
sd 2 -none- numeric
n 1 -none- numeric
loglik 1 -none- numeric
[1] -40.21074
[1] "fitting parameters for exponential"
rate
1.388468
(0.196359)
Length Class Mode
estimate 1 -none- numeric
sd 1 -none- numeric
n 1 -none- numeric
loglik 1 -none- numeric
[1] -33.58996
</code></pre>
<p>The exponential distribution is actually slightly more likely to have generated this data than the normal distribution, likely because the exponential distribution doesn't have to assign any probability density to negative numbers.</p>
<p>All of these estimation problems get worse when you try to fit your data to more distributions. Distributions with more parameters are more flexible, so they'll fit your data better than distributions with less parameters. Also, some distributions are special cases of other distributions (for example, the <a href="http://en.wikipedia.org/wiki/Exponential_distribution" rel="noreferrer">Exponential</a> is a special case of the <a href="http://en.wikipedia.org/wiki/Gamma_distribution" rel="noreferrer">Gamma</a>). Because of this, it's very common to use prior knowledge to constrain your choice models to a subset of all possible models.</p>
<p>One trick to get around some problems in parameter estimation is to generate a lot of data, and leave some of the data out for <a href="http://en.wikipedia.org/wiki/Cross-validation" rel="noreferrer">cross-validation</a>. To cross-validate your fit of parameters to data, leave some of the data out of your estimation procedure, and then measure each model's likelihood on the left-out data. </p> |
4,549,151 | C++ Double Address Operator? (&&) | <p>I'm reading STL source code and I have no idea what <code>&&</code> address operator is supposed to do. Here is a code example from <code>stl_vector.h</code>:</p>
<pre><code>vector&
operator=(vector&& __x) // <-- Note double ampersands here
{
// NB: DR 675.
this->clear();
this->swap(__x);
return *this;
}
</code></pre>
<p>Does "Address of Address" make any sense? Why does it have two address operators instead of just one?</p> | 4,549,167 | 6 | 5 | null | 2010-12-28 20:14:10.91 UTC | 76 | 2022-04-21 08:02:04.07 UTC | 2017-04-19 00:00:31.297 UTC | null | 773,263 | null | 556,384 | null | 1 | 210 | c++|stl|operator-keyword|memory-address | 162,816 | <p>This is <a href="https://stackoverflow.com/tags/c%2b%2b11/info">C++11</a> code. In C++11, the <code>&&</code> token can be used to mean an "rvalue reference".</p> |
4,223,141 | Using jQuery to delete all elements with a given id | <p>I have a form with several spans with <code>id="myid"</code>. I'd like to be able to remove all elements with this id from the DOM, and I think jQuery is the best way to do it. I figured out how to use the <code>$.remove()</code> method to remove one instance of this id, by simply doing:</p>
<pre><code>$('#myid').remove()
</code></pre>
<p>but of course that only removes the first instance of myid. How do I iterate over ALL instances of myid and remove them all? I thought the jQuery <code>$.each()</code> method might be the way, but I can't figure out the syntax to iterate over all instances of myid and remove them all.</p>
<p>If there's a clean way to do this with regular JS (not using jQuery) I'm open to that too. Maybe the problem is that id's are supposed to be unique (i.e. you're not supposed to have multiple elements with <code>id="myid"</code>)?</p> | 4,223,155 | 7 | 2 | null | 2010-11-19 08:09:26.903 UTC | 7 | 2021-04-02 14:21:10.787 UTC | 2021-04-02 14:20:34.873 UTC | null | 9,193,372 | null | 501,312 | null | 1 | 49 | javascript|jquery|getelementbyid | 113,316 | <p><code>.remove()</code> should remove all of them. I think the problem is that you're using an ID. There's only supposed to be <em>one</em> HTML element with a particular ID on the page, so jQuery is optimizing and not searching for them all. Use a <em>class</em> instead.</p> |
4,161,332 | How can I include python script in a HTML file? | <p>How do I put this python script:</p>
<pre><code>a = ['f','d','s','a']
x = -1
scope = vars()
for i in a:
scope['x']+=1
print a[x]
</code></pre>
<p>inside of a html file?</p> | 4,161,411 | 10 | 4 | null | 2010-11-12 03:17:35.9 UTC | 5 | 2022-08-23 15:48:15.55 UTC | 2014-01-01 19:23:34.873 UTC | null | 793,607 | null | 565,074 | null | 1 | 12 | python|html | 92,230 | <p>Something like this, if you want to create an html, not necessarily display it:</p>
<pre><code> html_file = open('namehere.html','w')
a = ['f','d','s','a']
x = -1
scope = vars()
data = ''
for i in a: #TIP: use a generator
scope['x']+=1
data += a[x]
data += '\n'
html_file.write(data)
html_file.close()
</code></pre> |
4,276,566 | How can you loop over the properties of a class? | <p>Is there a way in c# to loop over the properties of a class?</p>
<p>Basically I have a class that contains a large number of property's (it basically holds the results of a large database query).
I need to output these results as a CSV file so need to append each value to a string.</p>
<p>The obvious way it to manually append each value to a string, but is there a way to effectively loop over the results object and add the value for each property in turn?</p> | 4,276,597 | 11 | 0 | null | 2010-11-25 11:34:32.097 UTC | 19 | 2022-06-23 19:07:18.35 UTC | 2015-03-23 16:12:35.99 UTC | null | 5,552 | null | 178,570 | null | 1 | 58 | c#|reflection | 84,037 | <p>Sure; you can do that in many ways; starting with reflection (note, this is slowish - OK for moderate amounts of data though):</p>
<pre><code>var props = objectType.GetProperties();
foreach(object obj in data) {
foreach(var prop in props) {
object value = prop.GetValue(obj, null); // against prop.Name
}
}
</code></pre>
<p>However; for larger volumes of data it would be worth making this more efficient; for example here I use the <code>Expression</code> API to pre-compile a delegate that looks writes each property - the advantage here is that no reflection is done on a per-row basis (this should be significantly faster for large volumes of data):</p>
<pre><code>static void Main()
{
var data = new[] {
new { Foo = 123, Bar = "abc" },
new { Foo = 456, Bar = "def" },
new { Foo = 789, Bar = "ghi" },
};
string s = Write(data);
}
static Expression StringBuilderAppend(Expression instance, Expression arg)
{
var method = typeof(StringBuilder).GetMethod("Append", new Type[] { arg.Type });
return Expression.Call(instance, method, arg);
}
static string Write<T>(IEnumerable<T> data)
{
var props = typeof(T).GetProperties();
var sb = Expression.Parameter(typeof(StringBuilder));
var obj = Expression.Parameter(typeof(T));
Expression body = sb;
foreach(var prop in props) {
body = StringBuilderAppend(body, Expression.Property(obj, prop));
body = StringBuilderAppend(body, Expression.Constant("="));
body = StringBuilderAppend(body, Expression.Constant(prop.Name));
body = StringBuilderAppend(body, Expression.Constant("; "));
}
body = Expression.Call(body, "AppendLine", Type.EmptyTypes);
var lambda = Expression.Lambda<Func<StringBuilder, T, StringBuilder>>(body, sb, obj);
var func = lambda.Compile();
var result = new StringBuilder();
foreach (T row in data)
{
func(result, row);
}
return result.ToString();
}
</code></pre> |
4,486,034 | Get root view from current activity | <p>I know how to get the root view with <a href="http://developer.android.com/reference/android/view/View.html#getRootView%28%29">View.getRootView()</a>. I am also able to get the view from a button's <code>onClick</code> event where the argument is a <a href="http://developer.android.com/reference/android/view/View.html">View</a>. But how can I get the <strong>view</strong> in an <a href="http://developer.android.com/reference/android/app/Activity.html">activity</a>?</p> | 4,488,149 | 12 | 3 | null | 2010-12-20 00:40:33.51 UTC | 196 | 2020-06-03 19:28:28.687 UTC | 2017-04-23 11:24:50.88 UTC | null | 596,013 | null | 297,119 | null | 1 | 712 | android|android-activity|view | 627,175 | <p>If you need root view of your activity (so you can add your contents there) use</p>
<pre><code>findViewById(android.R.id.content).getRootView()
</code></pre>
<p>Also it was reported that on some devices you have to use </p>
<pre><code>getWindow().getDecorView().findViewById(android.R.id.content)
</code></pre>
<p>instead.</p>
<p>Please note that as Booger reported, this may be behind navigation bar (with back button etc.) on some devices (but it seems on most devices it is not).</p>
<p>If you need to get view that you added to your activity using <code>setContentView()</code> method then as pottedmeat wrote you can use</p>
<pre><code>final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
</code></pre>
<p>But better just set id to this view in your xml layout and use this id instead.</p> |
4,067,809 | How can I find whitespace in a String? | <p>How can I check to see if a String contains a whitespace character, an empty space or " ". If possible, please provide a Java example. </p>
<p>For example: <code>String = "test word";</code> </p> | 4,067,825 | 14 | 2 | null | 2010-11-01 09:38:32.267 UTC | 13 | 2021-04-27 04:31:16.39 UTC | 2019-05-24 00:12:58.81 UTC | null | 6,558,660 | null | 428,390 | null | 1 | 65 | java|string|space | 289,270 | <p>For checking if a string <em>contains whitespace</em> use a <a href="https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html" rel="nofollow noreferrer"><code>Matcher</code></a> and call its find method.</p>
<pre><code>Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
</code></pre>
<p>If you want to check if it <em>only consists of whitespace</em> then you can use <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)" rel="nofollow noreferrer"><code>String.matches</code></a>:</p>
<pre><code>boolean isWhitespace = s.matches("^\\s*$");
</code></pre> |
4,674,850 | Converting a sentence string to a string array of words in Java | <p>I need my Java program to take a string like:</p>
<pre><code>"This is a sample sentence."
</code></pre>
<p>and turn it into a string array like:</p>
<pre><code>{"this","is","a","sample","sentence"}
</code></pre>
<p>No periods, or punctuation (preferably). By the way, the string input is always one sentence.</p>
<p>Is there an easy way to do this that I'm not seeing? Or do we really have to search for spaces a lot and create new strings from the areas between the spaces (which are words)?</p> | 4,674,887 | 18 | 1 | null | 2011-01-12 22:44:07.153 UTC | 23 | 2021-09-02 06:57:56.6 UTC | null | null | null | null | 498,680 | null | 1 | 63 | java|string|spaces|words | 332,383 | <p><a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)" rel="noreferrer">String.split()</a> will do most of what you want. You may then need to loop over the words to pull out any punctuation.</p>
<p>For example:</p>
<pre><code>String s = "This is a sample sentence.";
String[] words = s.split("\\s+");
for (int i = 0; i < words.length; i++) {
// You may want to check for a non-word character before blindly
// performing a replacement
// It may also be necessary to adjust the character class
words[i] = words[i].replaceAll("[^\\w]", "");
}
</code></pre> |
4,227,223 | Convert a list to a data frame | <p>I have a nested list of data. Its length is 132 and each item is a list of length 20. Is there a <em>quick</em> way to convert this structure into a data frame that has 132 rows and 20 columns of data?</p>
<p>Here is some sample data to work with:</p>
<pre><code>l <- replicate(
132,
as.list(sample(letters, 20)),
simplify = FALSE
)
</code></pre> | 4,227,273 | 26 | 6 | null | 2010-11-19 16:40:52.897 UTC | 258 | 2022-02-07 08:07:27.78 UTC | 2020-11-11 20:02:10.32 UTC | null | 121,332 | null | 155,406 | null | 1 | 615 | r|list|dataframe | 1,127,376 | <p><strong>Update July 2020:</strong></p>
<p>The default for the parameter <code>stringsAsFactors</code> is now <code>default.stringsAsFactors()</code> which in turn yields <code>FALSE</code> as its default.</p>
<hr />
<p>Assuming your list of lists is called <code>l</code>:</p>
<pre><code>df <- data.frame(matrix(unlist(l), nrow=length(l), byrow=TRUE))
</code></pre>
<p>The above will convert all character columns to factors, to avoid this you can add a parameter to the data.frame() call:</p>
<pre><code>df <- data.frame(matrix(unlist(l), nrow=132, byrow=TRUE),stringsAsFactors=FALSE)
</code></pre> |
14,430,944 | I can't find my MinGW shell after installing with GUI installer | <p>I used Mingw_get_inst and installed the MinGW compiler suite following the instructions on the howto page. I used the GUI installer. I then changed the path to include C:\MingW; . When I go to Start menu -> all programs -> MingW the only file that exists inside of there is a uninstaller. The howto page says a shell should be there... can someone help me get this working? </p>
<p>Howto page on Mingw.org: <a href="http://www.mingw.org/wiki/Getting_Started">http://www.mingw.org/wiki/Getting_Started</a></p> | 14,432,368 | 5 | 1 | null | 2013-01-21 00:27:45.77 UTC | 5 | 2021-02-19 09:02:33.587 UTC | 2014-01-12 00:13:05.473 UTC | user1131435 | null | null | 1,524,907 | null | 1 | 35 | shell|mingw | 57,563 | <p>Look at the install logs for your Mingw.</p>
<p>I have 2 bin dirs in my (single) installation of Mingw</p>
<pre><code>C:\MinGW\msys\1.0\bin
</code></pre>
<p>and</p>
<pre><code>C:\MinGW\bin
</code></pre>
<p>A lot has changed about Mingw in the last 2-3 years and I think some documentation you might find easily via google is out-of-date.</p>
<p>Try asking for help at <a href="http://mingw.5.n7.nabble.com/">mingw mail groups via Nabble (very easy to use)</a></p>
<p>IHTH</p> |
21,018,256 | Can I automatically create a table in PostgreSQL from a csv file with headers? | <p>I'm running PostgreSQL 9.2.6 on OS X 10.6.8. I would like to import data from a CSV file with column headers into a database. I can do this with the <code>COPY</code> statement, but only if I first manually create a table with a column for each column in the CSV file. Is there any way to automatically create this table based on the headers in the CSV file?</p>
<p>Per <a href="https://stackoverflow.com/questions/17662631/how-to-copy-from-csv-file-to-postgresql-table-with-headers-in-csv-file">this question</a> I have tried</p>
<p><code>COPY test FROM '/path/to/test.csv' CSV HEADER;</code></p>
<p>But I just get this error:</p>
<p><code>ERROR: relation "test" does not exist</code></p>
<p>And if I first create a table with no columns:</p>
<p><code>CREATE TABLE test ();</code></p>
<p>I get:</p>
<p><code>ERROR: extra data after last expected column</code></p>
<p>I can't find anything in the PostgreSQL <a href="http://www.postgresql.org/docs/9.2/static/sql-copy.html" rel="noreferrer">COPY documentation</a> about automatically creating a table. Is there some other way to automatically create a table from a CSV file with headers?</p> | 21,018,420 | 10 | 0 | null | 2014-01-09 10:57:21.98 UTC | 33 | 2022-05-03 05:03:09.207 UTC | 2017-05-23 11:54:31.18 UTC | null | -1 | null | 2,144,514 | null | 1 | 85 | postgresql|csv | 118,250 | <p>You can't find anything in the <a href="http://www.postgresql.org/docs/current/interactive/sql-copy.html"><code>COPY</code></a> documentation, because COPY <strong>cannot</strong> create a table for you.<br>
You need to do that before you can <code>COPY</code> to it.</p> |
3,024,321 | Run a macro in all buffers in vim | <p>I know about the <code>:bufdo</code> command, and was trying to combine it with a macro I had recorded (<code>@a</code>) to add a #include in the proper spot of each of the header files I'd loaded. However, I couldn't find an easy way to run the macro on each buffer. Is there a way to execute a macro through ex mode, which is what <code>:bufdo</code> requires? Or is there another command I'm missing?</p> | 3,024,430 | 3 | 2 | null | 2010-06-11 16:03:55 UTC | 15 | 2010-06-11 16:19:35.757 UTC | null | null | null | null | 9,876 | null | 1 | 43 | vim|macros | 7,618 | <p>You can do it like this:</p>
<pre><code>:bufdo execute "normal @a" | write
</code></pre>
<p>The normal command will run the macro, but it has to be run using :execute, otherwise the pipe character will be interpreted as a normal-mode character.</p> |
2,429,226 | Case Statements versus coded if statements | <p>What is more efficient - handling with case statements in sql or handling the same data using if statements in code. I'm asking because my colleague has a huge query that has many case statements. I advised her to take stress off of the DB by coding the case statements. I've found that it is more efficient...but why?</p> | 2,430,665 | 4 | 2 | null | 2010-03-11 22:32:55.08 UTC | 6 | 2014-01-08 22:52:33.22 UTC | 2011-11-19 05:17:17.733 UTC | null | 50,776 | null | 103,617 | null | 1 | 22 | sql|asp-classic|case-statement | 47,446 | <p>There's a more fundamental question that's not being asked here: What are these <code>CASE</code> statements actually doing?</p>
<p>Forget performance for a minute. If <code>CASE</code> is only being used to transform the final output of a query, and it's actually possible to replace the same functionality with an <code>if</code> or <code>select case</code> in ASP, then it probably means that the database query/procedure is trying to do things that the UI should be responsible for, such as formatting. The separation-of-concerns issue is more serious than any possible performance issue.</p>
<p>If you have a query like this:</p>
<pre><code>SELECT InvoiceID, InvoiceDate,
CASE WHEN PaidStatus = 0 THEN 'Unpaid' ELSE 'Paid' END
FROM ...
</code></pre>
<p>This is just silly, because the UI, or whatever layer does the data-to-domain mapping, should know how to convert a status in the database to its corresponding description. It makes no sense to be including this logic in the query itself.</p>
<p>On the other hand, if the <code>CASE</code> construct is an essential part of the query, like:</p>
<pre><code>SELECT
SUM(CASE WHEN PaidStatus = 0 THEN Amount ELSE 0 END) AS TotalUnpaid,
SUM(CASE WHEN PaidStatus = 1 THEN Amount ELSE 0 END) AS TotalPaid
FROM ...
</code></pre>
<p>Don't even try to move this kind logic to the UI, because the database is <em>much</em> better at it. And the <code>CASE</code> is semantically a part of the query ("compute total paid and unpaid amounts for <em>x</em>"), it's not taking over any UI function.</p>
<p>Worry first about where the logic actually belongs based on what it's intending to accomplish. Performance concerns should only enter into the discussion if you are actually noticing significant performance <em>problems</em>.</p> |
3,048,012 | Eventlet or gevent or Stackless + Twisted, Pylons, Django and SQL Alchemy | <p>We're using Twisted extensively for apps requiring a great deal of asynchronous io. There are some cases where stuff is cpu bound instead and for that we spawn a pool of processes to do the work and have a system for managing these across multiple servers as well - all done in Twisted. Works great. The problem is that it's hard to bring new team members up to speed. Writing asynchronous code in Twisted requires a near vertical learning curve. It's as if humans just don't think that way naturally.</p>
<p>We're considering a mixed approach perhaps. Maybe keep the xmlrpc server part and process management in Twisted and implement the other stuff in code that at least looks synchronous to some extent while not being as such. Then again I like explicit over implicit so I have to think about this a bit more. Anyway onto greenlets - how well does that stuff work? So there's Stackless and as you can see from my Gallentean avatar I'm well aware of the tremendous success in it's use for CCP's flagship EVE Online game first hand. What about Eventlet or gevent? Well for now only Eventlet works with Twisted. However gevent claims to be faster as it's not a pure python implementation but rather relies upon libevent instead. It also claims to have fewer idiosyncrasies and defects. <a href="http://www.gevent.org/" rel="nofollow noreferrer">gevent</a> It's maintained by 1 guy as far as I can tell. This makes me somewhat leery but all great projects start this way so... Then there's <a href="http://codespeak.net/pypy/dist/pypy/doc/" rel="nofollow noreferrer">PyPy</a> - I haven't even finished reading about that one yet - just saw it in this thread: <a href="https://stackoverflow.com/questions/588958/what-are-the-drawbacks-of-stackless-python">Drawbacks of Stackless</a>.</p>
<p>So confusing - I'm wondering what the heck to do - sounds like Eventlet is probably the best bet but is it really stable enough? Anyone out there have any experience with it? Should we go with Stackless instead as it's been around and is proven technology - just like Twisted is as well - and they do work together nicely. But still I hate having to have a separate version of Python to do this. what to do....</p>
<p>This somewhat obnoxious blog entry hit the nail on the head for me though: <a href="http://teddziuba.com/2010/02/eventlet-asynchronous-io-for-g.html" rel="nofollow noreferrer">Asynchronous IO for Grownups</a> I don't get the Twisted is being like Java remark as to me Java is typically where you are in the threading mindset but whatever. Nevertheless if that monkey patch thing really works just like that then wow. Just wow!</p> | 3,050,700 | 4 | 6 | null | 2010-06-15 18:32:50.2 UTC | 24 | 2013-01-29 18:29:56.167 UTC | 2017-05-23 11:45:36.473 UTC | null | -1 | null | 348,576 | null | 1 | 36 | python|gevent|pypy|eventlet|python-stackless | 21,008 | <p>You might want to check out:</p>
<ul>
<li><a href="http://blog.gevent.org/2010/02/27/why-gevent/" rel="noreferrer">Comparing gevent to eventlet</a></li>
<li><a href="http://groups.google.com/group/gevent/browse_thread/thread/4de9703e5dca8271" rel="noreferrer">Reports from users who moved from twisted or eventlet to gevent</a></li>
</ul>
<p>Eventlet and gevent are not really comparable to Stackless, because Stackless ships with a standard library that is not aware of tasklets. There are implementations of <a href="http://code.google.com/p/stacklessexamples/wiki/StacklessNonblockModules" rel="noreferrer">socket for Stackless</a> but there isn't anything as comprehensive as <a href="http://www.gevent.org/gevent.monkey.html" rel="noreferrer">gevent.monkey</a>. CCP does not use bare bones Stackless, it has something called Stackless I/O which AFAIK is windows-only and was never open sourced (?).</p>
<p>Both eventlet and gevent could be made to run on Stackless rather than on greenlet. At some point we even tried to do this as a <a href="http://blog.gevent.org/2010/03/16/google-summer-of-code/" rel="noreferrer">GSoC project</a> but did not find a student.</p> |
3,216,020 | How to use DockStyle.Fill for standard controls in WPF? | <p>I'm used from windows forms, that I create a panel, place controls inside it and give them <code>DockStyle.Fill</code> to max out their size to the surrounding panel.</p>
<p>In WPF I want to have the same. I have a TabControl and I want its size to fill as much of the form as possible.
I have a ribbon control (RibbonControlsLibrary) and want the rest of the form to be filled with the TabControl at max size.</p>
<p>(I do not want to dock controls like docking in Visual Studio, just old docking mechanisms)</p> | 3,224,039 | 4 | 0 | null | 2010-07-09 19:46:08.87 UTC | 29 | 2018-10-06 08:55:21.757 UTC | 2018-10-06 08:55:21.757 UTC | null | 1,506,454 | null | 225,808 | null | 1 | 96 | c#|wpf|tabcontrol|docking | 84,861 | <p>The WPF equivalent of WinForms' DockStyle.Fill is:</p>
<pre><code>HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
</code></pre>
<p>This is the default for almost controls, so <strong>in general you don't have to do anything at all to have a WPF control fill its parent container</strong>: They do so automatically. This is true for all containers that don't squeeze their children to minimum size.</p>
<p><strong>Common Mistakes</strong></p>
<p>I will now explain several common mistakes that prevent <code>HorizontalAlignment="Stretch" VerticalAlignment="Stretch"</code> from working as expected.</p>
<p><strong>1. Explicit Height or Width</strong></p>
<p>One common mistake is to explicitly specify a Width or Height for a control. So if you have this:</p>
<pre><code><Grid>
<Button Content="Why am I not filling the window?" Width="200" Height="20" />
...
</Grid>
</code></pre>
<p>Just remove the Width and Height attributes:</p>
<pre><code><Grid>
<Button Content="Ahhh... problem solved" />
...
</Grid>
</code></pre>
<p><strong>2. Containing panel squeezes control to minimum size</strong></p>
<p>Another common mistake is to have the containing panel squeezing your control as tight as it will go. For example a vertical StackPanel will always squeeze its contents vertically as small as they will go:</p>
<pre><code><StackPanel>
<Button Content="Why am I squished flat?" />
</StackPanel>
</code></pre>
<p>Change to another Panel and you'll be good to go:</p>
<pre><code><DockPanel>
<Button Content="I am no longer squished." />
</DockPanel>
</code></pre>
<p>Also, any Grid row or column whose height is "Auto" will similarly squeeze its content in that direction.</p>
<p>Some examples of containers that don't squeeze their children are:</p>
<ul>
<li>ContentControls never squeeze their children (this includes Border, Button, CheckBox, ScrollViewer, and many others)</li>
<li>Grid with a single row and column</li>
<li>Grid with "*" sized rows and columns</li>
<li>DockPanel doesn't squeeze its last child</li>
<li>TabControl doesn't squeeze its content</li>
</ul>
<p>Some examples of containers that do squeeze their children are:</p>
<ul>
<li>StackPanel squeezes in its Orientation direction</li>
<li>Grid with an "Auto" sized row or column squeezes in that direction</li>
<li>DockPanel squeezes all but its last child in their dock direction</li>
<li>TabControl squeezes its header (what is displayed on the tab)</li>
</ul>
<p><strong>3. Explicit Height or Width further out</strong></p>
<p>It's amazing how many times I see Grid or DockPanel given an explicit height and width, like this:</p>
<pre><code><Grid Width="200" Height="100">
<Button Content="I am unnecessarily constrainted by my containing panel" />
</Grid>
</code></pre>
<p>In general you never want to give any Panel an explicit Height or Width. My first step when diagnosing layout problems is to remove every explicit Height or Width I can find.</p>
<p><strong>4. Window is SizeToContent when it shouldn't be</strong></p>
<p>When you use SizeToContent, your content will be squeezed to minimum size. In many applications this is very useful and is the correct choice. But if your content has no "natural" size then you'll probably want to omit SizeToContent.</p> |
2,526,033 | Why specify @charset "UTF-8"; in your CSS file? | <p>I've been seeing this instruction as the very first line of numerous CSS files that have been turned over to me:</p>
<pre><code>@charset "UTF-8";
</code></pre>
<p>What does it do, and is this at-rule necessary? </p>
<p>Also, if I include this meta tag in my "head" element, would that eliminate the need to have it also present within my CSS files?</p>
<pre><code><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</code></pre> | 2,526,055 | 4 | 0 | null | 2010-03-26 19:16:44.007 UTC | 44 | 2018-12-14 03:14:57.867 UTC | 2017-04-26 22:22:54.92 UTC | null | 552,067 | null | 223,134 | null | 1 | 181 | css|character-encoding | 134,960 | <p>It tells the browser to read the css file as UTF-8. This is handy if your CSS contains unicode characters and not only ASCII.</p>
<p>Using it in the meta tag is fine, but only for pages that include that meta tag.</p>
<p>Read about the rules for character set resolution of CSS files at the <a href="http://www.w3.org/TR/CSS2/syndata.html#charset" rel="noreferrer">w3c spec</a> for CSS 2.</p> |
3,201,991 | Auto Log Off once the session expires | <p>Our application logs off after 30 min and gets redirected to login page,i am specifying session timeout in web.xml and using a requestProcessor for redirecting.I want to show to the user a message saying your session got expired once the session expires,how can i do that.Auto log off ?
I would like to prompt the error message on the page"The session is timeout, please login again" . Then how could I detect the session is timeout? will any methods trigger automatically?</p> | 3,203,250 | 5 | 0 | null | 2010-07-08 08:58:46.32 UTC | 9 | 2019-09-11 01:34:43.86 UTC | 2014-05-24 00:02:55.233 UTC | null | 759,866 | null | 230,237 | null | 1 | 5 | java|servlets|jakarta-ee | 14,638 | <p>Create an activity checker which checks every minute if any user activity has taken place (mouseclick, keypress) and performs a heartbeat to the server side to keep the session alive when the user is active and does nothing when the user is not active. When there is no activity for 30 minutes (or whatever default session timeout is been set on server side), then perform a redirect.</p>
<p>Here's a kickoff example with little help of <a href="http://jquery.com" rel="noreferrer">jQuery</a> to bind click and keypress events and fire ajax request.</p>
<pre class="lang-html prettyprint-override"><code><script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$.active = false;
$('body').bind('click keypress', function() { $.active = true; });
checkActivity(1800000, 60000, 0); // timeout = 30 minutes, interval = 1 minute.
});
function checkActivity(timeout, interval, elapsed) {
if ($.active) {
elapsed = 0;
$.active = false;
$.get('heartbeat');
}
if (elapsed < timeout) {
elapsed += interval;
setTimeout(function() {
checkActivity(timeout, interval, elapsed);
}, interval);
} else {
window.location = 'http://example.com/expired'; // Redirect to "session expired" page.
}
}
</script>
</code></pre>
<p>Create a <code>Servlet</code> which listens on <code>/heartbeat</code> and does basically just the following:</p>
<pre><code>@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
request.getSession();
}
</code></pre>
<p>to keep the session alive.</p>
<p>When you store the logged-in user in the session, it will be "automagically" logged out whenever the session expires. So you don't need to manually logout the user.</p> |
40,543,372 | set withCredentials to the new ES6 built-in HTTP request API : Fetch | <p>How to set <code>withCredentials=true</code> to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch" rel="noreferrer"><code>fetch</code></a> which return promise.
Is the following correct : </p>
<pre><code>fetch(url,{
method:'post',
headers,
withCredentials: true
});
</code></pre>
<p>I think the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch" rel="noreferrer">MDN documentation</a> talked about everything about http-requesting except this point: <code>withCredentials</code> </p> | 40,543,547 | 1 | 0 | null | 2016-11-11 07:46:30.373 UTC | 3 | 2018-09-11 02:57:53.867 UTC | 2018-09-11 02:57:53.867 UTC | null | 747,579 | null | 747,579 | null | 1 | 44 | javascript|ecmascript-6|xmlhttprequest|fetch-api | 37,667 | <p>Got it <a href="https://github.com/github/fetch" rel="noreferrer">here</a> : </p>
<pre><code> credentials: 'include'
</code></pre>
<p>and not </p>
<pre><code> withCredentials: true
</code></pre> |
27,804,342 | How do I filter and extract raw log event data from Amazon Cloudwatch | <p>Is there any way to 1) filter and 2) retrieve the raw log data out of Cloudwatch via the API or from the CLI? I need to extract a subset of log events from Cloudwatch for analysis.</p>
<p>I don't need to create a metric or anything like that. This is for historical research of a specific event in time.</p>
<p>I have gone to the log viewer in the console but I am trying to pull out specific lines to tell me a story around a certain time. The log viewer would be nigh-impossible to use for this purpose. If I had the actual log file, I would just grep and be done in about 3 seconds. But I don't.</p>
<p><strong>Clarification</strong></p>
<p>In the description of <a href="http://aws.amazon.com/about-aws/whats-new/2014/07/10/introducing-amazon-cloudwatch-logs/" rel="noreferrer">Cloudwatch Logs</a>, it says, "You can view the original log data <em>(only in the web view?)</em> to see the source of the problem if needed. Log data can be stored and accessed <em>(only in the web view?)</em> for as long as you need using highly durable, low-cost storage so you don’t have to worry about filling up hard drives." --italics are mine</p>
<p>If this console view is the only way to get at the source data, then storing logs via Cloudwatch is not an acceptable solution for my purposes. I need to get at the actual data with sufficient flexibility to search for patterns, not click through dozens of pages lines and copy/paste. It appears a better way to get to the source data may not be available however.</p> | 33,636,237 | 5 | 0 | null | 2015-01-06 17:55:40.157 UTC | 10 | 2017-08-30 11:04:28.813 UTC | 2017-03-21 13:03:49.317 UTC | null | 1,558,022 | null | 309,711 | null | 1 | 27 | amazon-web-services|logging|amazon-cloudwatch | 54,797 | <p>For using AWSCLI (plain one as well as with <code>cwlogs</code> plugin) see <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/SearchDataFilterPattern.html" rel="noreferrer">http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/SearchDataFilterPattern.html</a></p>
<p>For pattern syntax (<code>plain text</code>, <code>[space separated]</code> as as <code>{JSON syntax}</code>) see: <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/FilterAndPatternSyntax.html" rel="noreferrer">http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/FilterAndPatternSyntax.html</a></p>
<p>For python command line utility <code>awslogs</code> see <a href="https://github.com/jorgebastida/awslogs" rel="noreferrer">https://github.com/jorgebastida/awslogs</a>.</p>
<h1>AWSCLI: aws logs filter-log-events</h1>
<p>AWSCLI is official CLI for AWS services and now it supports logs too.</p>
<p>To show help:</p>
<pre><code>$ aws logs filter-log-events help
</code></pre>
<p>The filter can be based on:</p>
<ul>
<li>log group name <code>--log-group-name</code> (only last one is used)</li>
<li>log stream name <code>--log-stream-name</code> (can be specified multiple times)</li>
<li>start time <code>--start-time</code></li>
<li>end time <code>--end-time</code> (not <code>--stop-time</code>)</li>
<li>filter patter <code>--filter-pattern</code></li>
</ul>
<p>Only <code>--log-group-name</code> is obligatory.</p>
<p>Times are expressed as epoch using milliseconds (not seconds).</p>
<p>The call might look like this:</p>
<pre><code>$ aws logs filter-log-events \
--start-time 1447167000000 \
--end-time 1447167600000 \
--log-group-name /var/log/syslog \
--filter-pattern ERROR \
--output text
</code></pre>
<p>It prints 6 columns of tab separated text:</p>
<ul>
<li>1st: <code>EVENTS</code> (to denote, the line is a log record and not other information)</li>
<li>2nd: <code>eventId</code></li>
<li>3rd: <code>timestamp</code> (time declared by the record as event time)</li>
<li>4th: <code>logStreamName</code></li>
<li>5th: <code>message</code></li>
<li>6th: <code>ingestionTime</code></li>
</ul>
<p>So if you have Linux command line utilities at hand and care only about log record messages for interval from <code>2015-11-10T14:50:00Z</code> to <code>2015-11-10T15:00:00Z</code>, you may get it as follows:</p>
<pre><code>$ aws logs filter-log-events \
--start-time `date -d 2015-11-10T14:50:00Z +%s`000 \
--end-time `date -d 2015-11-10T15:00:00Z +%s`000 \
--log-group-name /var/log/syslog \
--filter-pattern ERROR \
--output text| grep "^EVENTS"|cut -f 5
</code></pre>
<h1>AWSCLI with cwlogs plugin</h1>
<p>The <code>cwlogs</code> AWSCLI plugin is simpler to use:</p>
<pre><code>$ aws logs filter \
--start-time 2015-11-10T14:50:00Z \
--end-time 2015-11-10T15:00:00Z \
--log-group-name /var/log/syslog \
--filter-pattern ERROR
</code></pre>
<p>It expects human readable date-time and always returns text output with (space delimited) columns:</p>
<ul>
<li>1st: <code>logStreamName</code></li>
<li>2nd: <code>date</code></li>
<li>3rd: <code>time</code></li>
<li>4th till the end: <code>message</code></li>
</ul>
<p>On the other hand, it is a bit more difficult to install (few more steps to do plus current <code>pip</code> requires to declare the installation domain as trusted one).</p>
<pre><code>$ pip install awscli-cwlogs --upgrade \
--extra-index-url=http://aws-cloudwatch.s3-website-us-east-1.amazonaws.com/ \
--trusted-host aws-cloudwatch.s3-website-us-east-1.amazonaws.com
$ aws configure set plugins.cwlogs cwlogs
</code></pre>
<p>(if you make typo in last command, just correct it in <code>~/.aws/config</code> file)</p>
<h1><code>awslogs</code> command from <code>jorgebastida/awslogs</code></h1>
<p>This become my favourite one - easy to install, powerful, easy to use.</p>
<p>Installation:</p>
<pre><code>$ pip install awslogs
</code></pre>
<p>To list available log groups:</p>
<pre><code>$ awslogs groups
</code></pre>
<p>To list log streams</p>
<pre><code>$ awslogs streams /var/log/syslog
</code></pre>
<p>To get the records and follow them (see new ones as they come):</p>
<pre><code>$ awslogs get --watch /var/log/syslog
</code></pre>
<p>And you may filter the records by time range:</p>
<pre><code>$ awslogs get /var/log/syslog -s 2015-11-10T15:45:00 -e 2015-11-10T15:50:00
</code></pre>
<p>Since version 0.2.0 you have there also the <code>--filter-pattern</code> option.</p>
<p>The output has columns:</p>
<ul>
<li>1st: log group name</li>
<li>2nd: log stream name</li>
<li>3rd: <code>message</code></li>
</ul>
<p>Using <code>--no-group</code> and <code>--no-stream</code> you may switch the first two columns off.</p>
<p>Using <code>--no-color</code> you may get rid of color control characters in the output.</p>
<p><strong>EDIT</strong>: as <code>awslogs</code> version 0.2.0 adds <code>--filter-pattern</code>, text updated.</p> |
50,390,836 | Understanding darknet's yolo.cfg config files | <p>I have searched around the internet but found very little information around this, I don't understand what each variable/value represents in yolo's <code>.cfg</code> files. So I was hoping some of you could help, I don't think I'm the only one having this problem, so if anyone knows 2 or 3 variables please post them so that people who needs such info in the future might find them.</p>
<p>The main one that I'd like to know are : </p>
<ul>
<li>batch</li>
<li><p>subdivisions</p></li>
<li><p>decay</p></li>
<li><p>momentum</p></li>
<li><p>channels</p></li>
<li><p>filters</p></li>
<li><p>activation</p></li>
</ul> | 50,696,918 | 4 | 0 | null | 2018-05-17 11:55:16.503 UTC | 24 | 2020-06-17 00:17:08.77 UTC | null | null | null | null | 6,234,311 | null | 1 | 45 | yolo|darknet | 44,878 | <p>Here is my current understanding of some of the variables. Not necessarily correct though:</p>
<h1>[net]</h1>
<ul>
<li>batch: That many images+labels are used in the forward pass to compute a gradient and update the weights via backpropagation.</li>
<li>subdivisions: The batch is subdivided in this many "blocks". The images of a block are ran in parallel on the gpu.</li>
<li>decay: Maybe a term to diminish the weights to avoid having large values. For stability reasons I guess.</li>
<li>channels: Better explained in this image :</li>
</ul>
<p>On the left we have a single channel with 4x4 pixels, The reorganization layer reduces the size to half then creates 4 channels with adjacent pixels in different channels.
<a href="https://i.stack.imgur.com/238m5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/238m5.png" alt="figure"></a></p>
<ul>
<li>momentum: I guess the new gradient is computed by <em>momentum</em> * <em>previous_gradient</em> + (1-<em>momentum</em>) * <em>gradient_of_current_batch</em>. Makes the gradient more stable.</li>
<li>adam: Uses the adam optimizer? Doesn't work for me though</li>
<li>burn_in: For the first x batches, slowly increase the learning rate until its final value (your <em>learning_rate</em> parameter value). Use this to decide on a learning rate by monitoring until what value the loss decreases (before it starts to diverge).</li>
<li>policy=steps: Use the steps and scales parameters below to adjust the learning rate during training</li>
<li>steps=500,1000: Adjust the learning rate after 500 and 1000 batches</li>
<li>scales=0.1,0.2: After 500, multiply the LR by 0.1, then after 1000 multiply again by 0.2</li>
<li>angle: augment image by rotation up to this angle (in degree)</li>
</ul>
<h1>layers</h1>
<ul>
<li>filters: How many convolutional kernels there are in a layer.</li>
<li>activation: Activation function, relu, leaky relu, etc. See src/activations.h</li>
<li>stopbackward: Do backpropagation until this layer only. Put it in the panultimate convolution layer before the first yolo layer to train only the layers behind that, e.g. when using pretrained weights.</li>
<li>random: Put in the yolo layers. If set to 1 do data augmentation by resizing the images to different sizes every few batches. Use to generalize over object sizes.</li>
</ul>
<p>Many things are more or less self-explanatory (size, stride, batch_normalize, max_batches, width, height). If you have more questions, feel free to comment. </p>
<p>Again, please keep in mind that I am not 100% certain about many of those.</p> |
30,091,608 | How can I remove apps from Organizer in Xcode? | <p>If I log in to my iOS Developer account to Xcode, it autoloads all my applications to the Organizer window (Window -> Organizer). Now, when I log out from my account, my apps still persist in Organizer. How can I remove them?</p>
<p><a href="https://i.stack.imgur.com/mzjEr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mzjEr.png" alt="apps are still in Organizer"></a></p> | 30,637,676 | 10 | 0 | null | 2015-05-07 03:53:28.01 UTC | 29 | 2021-12-03 14:19:19.3 UTC | 2018-04-04 17:21:16.14 UTC | null | 3,151,675 | null | 1,639,366 | null | 1 | 99 | xcode | 26,168 | <p>Yes, you can delete all iOS Apps from Products.</p>
<p>So, go to this path: </p>
<p><code>~/Library/Developer/Xcode/Products</code></p>
<p>and remove any apps.</p>
<p>Be sure to remove any related archives in</p>
<p><code>~/Library/Developer/Xcode/Archives</code></p>
<p>which are divided by date archived.</p>
<p>If you have any difficulty to get the Library folder all you need to do is hit Command+Shift+G from the Mac desktop and type in ~/Library to temporarily access the Library directory in the Finder.</p> |
49,752,151 | TypeScript keyof returning specific type | <p>If I have the following type</p>
<pre><code>interface Foo {
bar: string;
baz: number;
qux: string;
}
</code></pre>
<p>can I use <code>typeof</code> to type a parameter such that it only takes keys of <code>Foo</code> that return <code>string</code> (<code>'bar'</code> or <code>'qux'</code>)?</p> | 49,752,227 | 1 | 0 | null | 2018-04-10 11:11:55.533 UTC | 7 | 2022-01-21 16:51:50.473 UTC | null | null | null | null | 1,068,266 | null | 1 | 34 | typescript|types | 4,410 | <h2>Typescript 4.1 and above</h2>
<p>With the addition of the <code>as</code> clause in mapped types we can now simplify the original type to:</p>
<pre><code>type KeyOfType<T, V> = keyof {
[P in keyof T as T[P] extends V? P: never]: any
}
</code></pre>
<p><a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGIHt3IN4FgBQyRyARnFAFzIDOYUoA5gNwHGlwBeVIArgLYloLQsQCOPAB5Va9EMwIBfAgTABPAA4oA0hFXUA8jAAqGiAB4jAGmQA1AHzIAvMgDWu9DBytiAbQAKyKCu7p5GyHDUyEb+ALrIEBKQIAAmkTYA-Mh+3BAAbtAxVHAgqorK+AA2EGDI6CAVqgDKdIzUVDp6hiaaZhjo1jKMdsJ1Dc2yDJHOAORkHNPIAPSL8VBQ6FAEo00tclPIs+QLy7Uu5VU12wBy-IJQbcgdBsamvZjWvALQw1v1qjdfe5OA5zY4rdBnfDXW7QfaHKBg1brKDIIA" rel="noreferrer">Playground Link</a></p>
<h2>Original answer</h2>
<p>You can use conditional types in Tyepscript 2.8 :</p>
<pre><code>type KeysOfType<T, TProp> = { [P in keyof T]: T[P] extends TProp? P : never }[keyof T];
let onlyStrings: KeysOfType<Foo, string>;
onlyStrings = 'baz' // error
onlyStrings = 'bar' // ok
let onlyNumbers: KeysOfType<Foo, number>;
onlyNumbers = 'baz' // ok
onlyNumbers = 'bar' // error
</code></pre>
<p><a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGIHt3IN4FgBQyRyARnFAFzIDOYUoA5gNwHGlwBeVIArgLYloLQsQCOPAB5Va9EMwIBfAgTABPAA4oA0hFXUA8jAAqGiAB4jAGmRGAClHTqAfMgC8OZAG1byUMgDWuugwNgC6VEbeocgQEpAgACbUNvaOAPzIPtwQAG7QyAqegarBYcIEADYQYMjoIBWqAMp0jNRUOnqGJppmGOjWMoxOwnUNzbIMye4A5GQc08gA9IsxUA5QBKNNLXJTyLPkC8u1-sr4VTVbAHL8glBtyB0Gxqa9mNa8AtDDm-WqN197m59nMjit0Kd8NdbtA9gcoGDVutkEA" rel="noreferrer">Playground Link</a></p> |
22,688,651 | golang - how to sort string or []byte? | <p>I am looking for a function, that can sort <code>string</code> or <code>[]byte</code>:</p>
<pre><code>"bcad" to "abcd"
or
[]byte("bcad") to []byte("abcd")
</code></pre>
<p>The string only contains letters - but sorting should also work for letters and numbers.</p>
<p>I found sort package but not the function I want.</p> | 22,698,017 | 4 | 0 | null | 2014-03-27 13:08:17.297 UTC | 10 | 2022-03-15 02:36:31.973 UTC | 2022-03-15 02:36:31.973 UTC | null | 2,671,470 | null | 1,078,503 | null | 1 | 35 | string|sorting|go|byte | 42,512 | <p>It feels wasteful to create a string for each character just to <code>Join</code> them.</p>
<p>Here's one that is a little less wasteful, but with more boiler plate. <a href="http://play.golang.org/p/XEckr_rpr8" rel="noreferrer">playground://XEckr_rpr8</a></p>
<pre><code>type sortRunes []rune
func (s sortRunes) Less(i, j int) bool {
return s[i] < s[j]
}
func (s sortRunes) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortRunes) Len() int {
return len(s)
}
func SortString(s string) string {
r := []rune(s)
sort.Sort(sortRunes(r))
return string(r)
}
func main() {
w1 := "bcad"
w2 := SortString(w1)
fmt.Println(w1)
fmt.Println(w2)
}
</code></pre> |
47,908,158 | How to set local web server in Visual Studio Code | <p>I am new in VS code and working in typescript.Just I am trying to set local server path to open my HTML file.how to set that and when I was trying to set always I am getting error. I can not use this (NPM install) and (NPM start) command in terminal.If I use this command I am getting error.
Any proxy issue? How to resolve this issue in VS code?</p>
<p>Folder structure:</p>
<pre><code>TsDemo--folder name
.vscode
->launch.json
->tasks.json
out
->app.js
->app.js.map
app.ts
index.html
tsconfig.json
</code></pre>
<p>i follwed this link:<a href="https://blogs.msdn.microsoft.com/cdndevs/2016/01/24/visual-studio-code-and-local-web-server/" rel="noreferrer">https://blogs.msdn.microsoft.com/cdndevs/2016/01/24/visual-studio-code-and-local-web-server/</a>
but not working.
If I use this command: D:\TsDemo>NPM install</p>
<pre><code> D:\TsDemo>npm install
npm ERR! code ETIMEDOUT
npm ERR! errno ETIMEDOUT
npm ERR! network request to https://registry.npmjs.org/lite-server failed, reason: connect ETIMEDOUT 10.232.192.45:8080
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly. See: 'npm help config'
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\AppData\Roaming\npm-cache\_logs\2017-12-20T14_16_49_680Z-debug.log
</code></pre>
<p>If I use this command: D:\TsDemo>NPM start</p>
<pre><code> D:\TsDemo>npm start
>[email protected] start D:\TsDemo
> npm run lite
npm WARN invalid config loglevel="notice"
> [email protected] lite D:\TsDemo
>lite-server --port 10001
'lite-server' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] lite: `lite-server --port 10001`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] lite script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\411732\AppData\Roaming\npm-cache\_logs\2017-12-20T14_07_41_636Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `npm run lite`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\AppData\Roaming\npm-cache\_logs\2017-12-20T14_07_41_694Z-debug.log
</code></pre> | 47,924,544 | 1 | 0 | null | 2017-12-20 14:24:31.957 UTC | 4 | 2017-12-21 12:14:25.963 UTC | 2017-12-20 14:30:00.177 UTC | null | 8,829,948 | null | 8,829,948 | null | 1 | 23 | typescript|typescript1.8 | 67,975 | <p>Just use the Live Server Extension. Install it from VS Code directly and you will be fine. You'll then have a link in the bottom of your editor to start and run the server automatically and also view your HTML immediately.</p>
<p>Also check: <a href="https://github.com/ritwickdey/live-server-web-extension" rel="noreferrer">live-server-web-extension</a>
and <a href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer" rel="noreferrer">Live Server</a></p> |
37,500,118 | Laravel 5.2 method to check is view exists? | <p>Is there any method to check if view exists? </p>
<p>Like PHP file_exists, but using internal laravel method for convenience</p>
<p>i want to code like this:</p>
<pre><code>if(__ifViewExist__($view)){
return view($view)->render();
}
return "Page tidak ditemukan";
</code></pre> | 37,500,250 | 4 | 0 | null | 2016-05-28 14:22:15.113 UTC | 2 | 2019-05-02 14:04:11.82 UTC | null | null | null | null | 5,389,282 | null | 1 | 33 | laravel|view | 19,551 | <p>Yes, an exists() method is available.</p>
<pre><code>if(view()->exists($view)){
return view($view)->render();
}
return "Page tidak ditemukan";
</code></pre> |
32,199,658 | Create & Find GeoLocation in mongoose | <p>I'm trying to save the longitude/latitude of a location in my user Model and query it with <code>$geoNear</code>. I've looked at almost any page I could find on that topic, but still I'm not sure how to 1) create the model appropriately and how to query it.</p>
<p>here's the part of my model:</p>
<pre><code>loc: {
//type: 'Point', // see 1
//type: String, // see 2
coordinates: [Number],
index: '2dsphere' // see 3
},
</code></pre>
<p>@1: According the documentation the type must be 'Point' if I want to store a point, but it throws</p>
<pre><code>TypeError: Undefined type `Point` at `loc`
Did you try nesting Schemas? You can only nest using refs or arrays.
</code></pre>
<p>which makes sense, since I guess it should be a <code>String</code></p>
<p>@2: this doesn't immediately throw an error, but when I try to store a user I get:</p>
<pre><code>name: 'ValidationError',
errors:
{ loc:
{ [CastError: Cast to String failed for value "[object Object]" at path "loc"]
</code></pre>
<p>@3: if I want to create the index like that I get the error:</p>
<pre><code>TypeError: Undefined type `2dsphere` at `loc.index`
Did you try nesting Schemas? You can only nest using refs or arrays.
</code></pre>
<p>so I tried to store the index to what felt a little bit more appropriate to me like this:</p>
<pre><code>userSchema.index({'loc': '2dsphere'});
</code></pre>
<p>which throws the following error when I try to save a new user:</p>
<pre><code>- { [MongoError: Can't extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }]
name: 'MongoError',
message: 'Can\'t extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }',
ok: 1,
n: 0,
code: 16572,
errmsg: 'Can\'t extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }',
writeConcernError:
{ code: 16572,
errmsg: 'Can\'t extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }' } }
MongoError: Can't extract geo keys from object, malformed geometry?:{ coordinates: [ -73.97, 40.77 ] }
</code></pre>
<hr>
<p>When I updated my model on the database to to a <code>$geoNear</code> command I updated my user like this:</p>
<pre><code>loc: {coordinates: [-73.97, 40.77]}
</code></pre>
<p>and could successfully query it like this:</p>
<pre><code> mongoose.model('users').db.db.command({
"geoNear": users,
"near": [
<latitude>,
<longitude>
],
"spherical": true,
"distanceMultiplier": 6378.1, // multiplier for kilometres
"maxDistance": 100 / 6378.1, // every user within 100 km
"query": { }
</code></pre>
<p>(I used db.command since from what I've read <code>$geoNear</code> is not available when using <code>find()</code>)</p>
<p>Everything I tried so far got me nowhere, so my question now is:</p>
<ul>
<li>how should my mongoose model look like?</li>
<li>how can I store a user with his or her location in my database</li>
</ul>
<p>Any help would be much appreciated!</p> | 32,200,007 | 2 | 0 | null | 2015-08-25 08:55:38.933 UTC | 14 | 2022-06-29 04:37:43.33 UTC | 2016-08-21 07:22:38.33 UTC | null | 811,335 | null | 2,657,252 | null | 1 | 22 | node.js|mongodb|mongoose|mongodb-query|geospatial | 25,600 | <p>If you want a schema to support GeoJSON, the you first need to construct that properly:</p>
<pre class="lang-js prettyprint-override"><code>var userSchema = new Schema({
loc: {
type: { type: String },
coordinates: [Number],
}
});
</code></pre>
<p>That makes sure there is no confusion with the "type" keyword of the schema defintition. If you really want to support the whole range of GeoJSON types, then you can make that a bit looser:</p>
<pre class="lang-js prettyprint-override"><code>var userSchema = new Schema({
loc: {
type: { type: String },
coordinates: []
}
});
</code></pre>
<p>Next you want to tie an index to the shema:</p>
<pre class="lang-js prettyprint-override"><code>userSchema.index({ "loc": "2dsphere" });
</code></pre>
<p>Then of course define a model and store things correctly:</p>
<pre class="lang-js prettyprint-override"><code>var User = mongoose.model( "User", userSchema );
var user = new User({
"loc": {
"type": "Point",
"coordinates": [-73.97, 40.77]
}
});
</code></pre>
<p>Noting that your data must be in <strong>longitude</strong> then <strong>latitude</strong> order as supported by GeoJSON and all MongoDB geospatial query forms.</p>
<p>Next, rather than dig into obscure usages of database commands directly on the raw driver method, use things instead that are directly supported, and better. Such as <a href="http://docs.mongodb.org/manual/reference/operator/aggregation/geoNear/" rel="noreferrer"><strong><code>$geoNear</code></strong></a> for the <code>.aggregate()</code> method:</p>
<pre class="lang-js prettyprint-override"><code>User.aggregate(
[
{ "$geoNear": {
"near": {
"type": "Point",
"coordinates": [<long>,<lat>]
},
"distanceField": "distance",
"spherical": true,
"maxDistance": 10000
}}
],
function(err,results) {
}
)
</code></pre>
<p>And now because the data is GeoJSON, the distances are already converted to meters so there is no need to do other conversion work.</p>
<p>Also note that is you have been messing around with this, unless you drop the collection any index you tried will still be there and that will likely cause problems.</p>
<p>You can drop all indexes from the collection in the mongodb shell with ease:</p>
<pre class="lang-js prettyprint-override"><code>db.users.dropIndexes();
</code></pre>
<p>Or since you likely need to do some data re-shaping, then drop the collection and start again:</p>
<pre class="lang-js prettyprint-override"><code>db.users.drop();
</code></pre>
<p>Set things up properly and you will have no problems.</p> |
24,636,332 | Amazon Web Services EC2 to RDS Connectivity with VPC | <p>I have been trying to set up an AWS Free Tier account using an EC2 instance and an RDS database running MySQL. Unfortunately, I cannot figure out how to grant access to the database from the EC2 instance. I have read all of the AWS documentation, but it is unfortunately out of date as are all the questions posted on StackOverflow. All of the documentation states that I should go to the Security Groups section of the RDS Dashboard. However, when I do so, this is what I'm confronted with.</p>
<p><img src="https://i.stack.imgur.com/Imz19.png" alt="enter image description here"></p>
<p>** I would have included the image but I don't have the reputation for it.</p>
<p>Okay, I understand that I am not using the EC2-Classic platform and that I must make these changes to the Security Group in the EC2 Dashboard, but how?! I do not want public access to port 3306, I only want the EC2 instance to be able to communicate with the RDS database on a private subnet. Any help would be greatly appreciated.</p>
<p>The links to "AWS Documentation on Supported Platforms" and "Using RDS in VPC" are not helpful. They are outdated and also keep referring me back to Security Groups under the RDS Dashboard, which then only shows me this message.</p> | 24,673,904 | 1 | 0 | null | 2014-07-08 15:52:26.66 UTC | 9 | 2019-02-19 18:20:44.2 UTC | 2015-02-17 15:53:09.6 UTC | null | 1,306,419 | null | 3,817,137 | null | 1 | 6 | amazon-ec2|amazon-rds|amazon-vpc | 5,898 | <p><strong>A rule of thumb:</strong> When you are setting up resources in VPC, use <strong>ONLY VPC Security Groups</strong>. The individual RDS, Redshift...etc. security groups work only in case of ec2-classic. Meaning, when you are not setting up things in VPC.</p>
<p>Go to the VPC console and then on the left hand side menu, you will find security groups. These are the security groups which should control access to your AWS resources deployed inside a VPC.</p>
<p>I can't elaborate much as I am unaware of your VPC configuration and which subnet (public/private) you are setting these up.</p>
<h2>Example</h2>
<p>Here is the hypothetical scenario...</p>
<pre><code>VPC: 10.0.0.0/16
1 public subnet: 10.0.0.0/24
1 Private Subnet: 10.0.1.0/24
</code></pre>
<ul>
<li>Assume you put your EC2 instance in Public Subnet </li>
<li>Assume you put your RDS instance in Private Subnet</li>
<li>And you want EC2 instance be accessible on 80,443 from the world and RDS instance should be accessible only via EC2 instance.</li>
</ul>
<p>So, these are the security groups settings:</p>
<p><strong>for EC2 instance Security group:</strong></p>
<pre><code>Inbound: port 80, 443 : from 0.0.0.0/0
Outbound: port 3306 : to 10.0.1.0/24
</code></pre>
<p><strong>For RDS security group:</strong></p>
<pre><code>Inbound: port 3306: from 10.0.0.0/24
</code></pre>
<h2><strong>Explanation</strong></h2>
<pre><code>Inbound: port 80, 443 : from 0.0.0.0/0
</code></pre>
<p>This will allow EC2 instance be accessible on port 80 and 443 from the Internet.</p>
<hr>
<pre><code>Outbound: port 3306 : to 10.0.1.0/24
</code></pre>
<p>This allows EC2 instance to send the traffic on port 3306 only to the private subnet which is 10.0.1.0/24</p>
<hr>
<pre><code>Inbound: port 3306: from 10.0.0.0/24
</code></pre>
<p>This allows the RDS instance to accept traffic on port 3306 from the public subnet which is 10.0.0.0/24. Your EC2 instance resides in Public subnet so inherently RDS will accept traffic from Ec2 instance on port 3306</p>
<p><strong>NOTE:</strong> Above setup presumes that you have set your Routing tables for the public/private subnets accordingly.</p>
<p>Hope this helps.</p> |
24,785,084 | issue with string_agg with distinct in postgres | <p>I am getting error for below query. Basically to use <code>||</code> & <code>distinct</code> together.</p>
<pre><code>select string_agg( 'pre' || distinct user.col, 'post')
</code></pre>
<p>It works fine like this</p>
<pre><code>select string_agg( 'pre' || user.col, 'post')
</code></pre>
<p>& this</p>
<pre><code>select string_agg(distinct user.col, 'post')
</code></pre> | 24,785,122 | 3 | 0 | null | 2014-07-16 15:42:56.297 UTC | 2 | 2020-06-24 08:13:40.483 UTC | null | null | null | null | 1,298,426 | null | 1 | 29 | postgresql | 33,304 | <pre><code>select string_agg(distinct 'pre' || user.col, 'post')
</code></pre>
<p>As the above will deny the use of an index in the <code>distinct</code> aggregation take the <code>'pre'</code> out</p>
<pre><code>select 'pre' || string_agg(distinct user.col, 'postpre')
</code></pre> |
35,405,412 | How to use npm installed requireJS for browser | <p>While <code>requirejs</code> is capable of using <a href="http://requirejs.org/docs/node.html#2">npm-installed modules</a>, how do I use <code>requirejs</code> in first place if itself is installed via <code>npm install requirejs</code>?</p>
<p>I have read examples of using <code>requirejs</code> listed in the <a href="http://requirejs.org/docs/start.html#examples">example-section</a>. They all seems to assume <code>require.js</code> is downloaded into a specific location. Since the <a href="http://requirejs.org/docs/node.html#2">documentation</a> specifically said </p>
<blockquote>
<p>do not do something like require("./node_modules/foo/foo").</p>
</blockquote>
<p>I guess it is not right to put in <code>index.html</code> something like:</p>
<pre><code><html>
<head>
<script data-main="scripts" src="node_modules/requirejs/require.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
</code></pre>
<p>What is the recommended way to use requirejs if it is npm-installed? If I missed something from the documentation please let me know. Thank you</p> | 35,409,155 | 1 | 0 | null | 2016-02-15 09:17:28.07 UTC | 3 | 2016-02-15 12:15:58.873 UTC | null | null | null | null | 2,829,759 | null | 1 | 33 | javascript|npm|requirejs | 20,828 | <p>It looks like you are conflating a bunch of different uses of RequireJS:</p>
<ol>
<li><p>How can you use a RequireJS installed through Node in the browser?</p>
<p>You can just install it with <code>npm install requirejs</code>, and then you have your HTML file have a <code>script</code> element that points to <code>node_modules/requirejs/require.js</code>. Exactly as you show in your code snippet. That's all there is to it. This being said, I don't like to have <code>node_modules</code> in what I deploy, so I typically have my build process copy <code>require.js</code> elsewhere.</p></li>
<li><p>How can you load npm-installed modules with RequireJS in Node?</p>
<p>Suppose without RequireJS you would load the module <code>foo</code> by doing <code>require('foo')</code>. You install RequireJS and load it as <code>requirejs</code>. How do you load <code>foo</code> using RequireJS? You can just do <code>requirejs('foo')</code>. So long as RequireJS does not find it through its own configuration, it will issue as a last resort a call to Node's own <code>require</code>, and will load it this way? Here's an illustration. Install RequireJS with <code>npm install requirejs</code>. Create this file:</p>
<pre><code>var requirejs = require("requirejs");
var fs = requirejs("fs");
console.log(fs);
</code></pre>
<p>Then run it. You'll get on the console Node's <code>fs</code> module.</p></li>
<li><p>How can you load npm-installed modules with RequireJS in a browser?</p>
<p><strong>It depends on the modules.</strong> RequireJS does not contain code that will magically make a npm-installed module work in the browser. It ultimately depends on how the modules are structured. Some cases: </p>
<p>A. Some npm-installed modules can be loaded with RequireJS without modification. There's one library I've authored which is distributed through npm and yet is a collection of AMD modules. It is trivial to load them with RequireJS in the browser.</p>
<p>B. It may require being wrapped in <code>define</code> calls. I've recently loaded <a href="https://github.com/schnittstabil/merge-options" rel="noreferrer"><code>merge-options</code></a> in one of my projects with <a href="https://github.com/phated/gulp-wrap-amd" rel="noreferrer"><code>gulp-wrap-amd</code></a>. <code>merge-options</code> is a CommonJS module. It does not support RequireJS out-of-the-box but if you wrap it with a <code>define</code> call, it will work.</p>
<p>C. It may require something more complex before it will be loaded in a browser. For instance, if a module relies on Node's <code>fs</code> module, you'll have to provide a replacement for <code>fs</code> that runs in a browser. It will presumably present a fake filesystem to your code.</p></li>
</ol> |
35,546,956 | What is AtomicLong in Java used for? | <p>Can some one explain what AtomicLong is used for? For example, what's the difference in the below statements?</p>
<pre><code>private Long transactionId;
private AtomicLong transactionId;
</code></pre> | 35,547,532 | 1 | 0 | null | 2016-02-22 06:18:58.557 UTC | 9 | 2018-12-01 13:29:56.547 UTC | 2017-12-26 18:25:25.89 UTC | null | 1,079,354 | null | 1,233,600 | null | 1 | 46 | java|atomic-long | 25,723 | <p>There are <strong><em>significant</em></strong> differences between these two objects, although the net result is the same, they are definitely very different and used under very different circumstances.</p>
<p>You use a basic <code>Long</code> object when:</p>
<ul>
<li>You need the wrapper class</li>
<li>You are working with a collection</li>
<li>You only want to deal with objects and not primitives (which kinda works out)</li>
</ul>
<p>You use an <code>AtomicLong</code> when:</p>
<ul>
<li>You have to guarantee that the value can be used in a concurrent environment</li>
<li>You don't need the wrapper class (as this class will not autobox)</li>
</ul>
<p><code>Long</code> by itself doesn't allow for thread interopability since two threads could both see and update the same value, but with an <code>AtomicLong</code>, there are pretty decent guarantees around the value that multiple threads will see.</p>
<p>Effectively, unless you ever bother working with threads, you won't need to use <code>AtomicLong</code>.</p> |
38,437,162 | What's the difference between RSpec's subject and let? When should they be used or not? | <p><a href="http://betterspecs.org/#subject" rel="noreferrer">http://betterspecs.org/#subject</a> has some info about <code>subject</code> and <code>let</code>. However, I am still unclear on the difference between them. Furthermore, the SO post <a href="https://stackoverflow.com/questions/12869026/what-is-the-argument-against-using-before-let-and-subject-in-rspec-tests">What is the argument against using before, let and subject in RSpec tests?</a> said it is better to not use either <code>subject</code> or <code>let</code>. Where shall I go? I am so confused.</p> | 38,459,039 | 3 | 0 | null | 2016-07-18 12:49:04.573 UTC | 44 | 2016-08-18 12:04:43.033 UTC | 2017-05-23 11:47:25.103 UTC | null | -1 | null | 2,251,303 | null | 1 | 110 | ruby|unit-testing|rspec | 52,447 | <p>Summary: RSpec's subject is a special variable that refers to the object being tested. Expectations can be set on it implicitly, which supports one-line examples. It is clear to the reader in some idiomatic cases, but is otherwise hard to understand and should be avoided. RSpec's <code>let</code> variables are just lazily instantiated (memoized) variables. They aren't as hard to follow as the subject, but can still lead to tangled tests so should be used with discretion.</p>
<h1>The subject</h1>
<h2>How it works</h2>
<p>The subject is the object being tested. RSpec has an explicit idea of the subject. It may or may not be defined. If it is, RSpec can call methods on it without referring to it explicitly.</p>
<p>By default, if the first argument to an outermost example group (<code>describe</code> or <code>context</code> block) is a class, RSpec creates an instance of that class and assigns it to the subject. For example, the following passes:</p>
<pre><code>class A
end
describe A do
it "is instantiated by RSpec" do
expect(subject).to be_an(A)
end
end
</code></pre>
<p>You can define the subject yourself with <code>subject</code>:</p>
<pre><code>describe "anonymous subject" do
subject { A.new }
it "has been instantiated" do
expect(subject).to be_an(A)
end
end
</code></pre>
<p>You can give the subject a name when you define it:</p>
<pre><code>describe "named subject" do
subject(:a) { A.new }
it "has been instantiated" do
expect(a).to be_an(A)
end
end
</code></pre>
<p>Even if you name the subject, you can still refer to it anonymously:</p>
<pre><code>describe "named subject" do
subject(:a) { A.new }
it "has been instantiated" do
expect(subject).to be_an(A)
end
end
</code></pre>
<p>You can define more than one named subject. The most recently defined named subject is the anonymous <code>subject</code>.</p>
<p>However the subject is defined,</p>
<ol>
<li><p>It's instantiated lazily. That is, the implicit instantiation of the described class or the execution of the block passed to <code>subject</code> doesn't happen until <code>subject</code> or the named subject is referred to in an example. If you want your explict subject to be instantiated eagerly (before an example in its group runs), say <code>subject!</code> instead of <code>subject</code>.</p></li>
<li><p>Expectations can be set on it implicitly (without writing <code>subject</code> or the name of a named subject):</p>
<pre><code>describe A do
it { is_expected.to be_an(A) }
end
</code></pre>
<p>The subject exists to support this one-line syntax.</p></li>
</ol>
<h2>When to use it</h2>
<p>An implicit <code>subject</code> (inferred from the example group) is hard to understand because</p>
<ul>
<li>It's instantiated behind the scenes.</li>
<li>Whether it's used implicitly (by calling <code>is_expected</code> without an explicit receiver) or explicitly (as <code>subject</code>), it gives the reader no information about the role or nature of the object on which the expectation is being called.</li>
<li>The one-liner example syntax doesn't have an example description (the string argument to <code>it</code> in the normal example syntax), so the only information the reader has about the purpose of the example is the expectation itself.</li>
</ul>
<p>Therefore, <strong>it's only helpful to use an implicit subject when the context is likely to be well understood by all readers and there is really no need for an example description</strong>. The canonical case is testing ActiveRecord validations with shoulda matchers:</p>
<pre><code>describe Article do
it { is_expected.to validate_presence_of(:title) }
end
</code></pre>
<p>An explict anonymous <code>subject</code> (defined with <code>subject</code> without a name) is a little better, because the reader can see how it's instantiated, but</p>
<ul>
<li>it can still put the instantiation of the subject far from where it's used (e.g. at the top of an example group with many examples that use it), which is still hard to follow, and</li>
<li>it has the other problems that the implicit subject does.</li>
</ul>
<p>A named subject provides an intention-revealing name, but the only reason to use a named subject instead of a <code>let</code> variable is if you want to use the anonymous subject some of the time, and we just explained why the anonymous subject is hard to understand.</p>
<p>So, <strong>legitimate uses of an explicit anonymous <code>subject</code> or a named subject are very rare</strong>.</p>
<h1><code>let</code> variables</h1>
<h2>How they work</h2>
<p><code>let</code> variables are just like named subjects except for two differences:</p>
<ul>
<li>they're defined with <code>let</code>/<code>let!</code> instead of <code>subject</code>/<code>subject!</code></li>
<li>they do not set the anonymous <code>subject</code> or allow expectations to be called on it implicitly.</li>
</ul>
<h2>When to use them</h2>
<p><strong>It's completely legitimate to use <code>let</code> to reduce duplication among examples. However, do so only when it doesn't sacrifice test clarity.</strong> The safest time to use <code>let</code> is when the <code>let</code> variable's purpose is completely clear from its name (so that the reader doesn't have to find the definition, which could be many lines away, to understand each example) and it is used in the same way in every example. If either of those things isn't true, consider defining the object in a plain old local variable or calling a factory method right in the example.</p>
<p><strong><code>let!</code> is risky, because it's not lazy.</strong> If someone adds an example to the example group that contains the <code>let!</code>, but the example doesn't need the <code>let!</code> variable,</p>
<ul>
<li>that example will be hard to understand, because the reader will see the <code>let!</code> variable and wonder whether and how it affects the example</li>
<li>the example will be slower than it needs to be, because of the time taken to create the <code>let!</code> variablle</li>
</ul>
<p>So use <code>let!</code>, if at all, only in small, simple example groups where it's less likely that future example writers will fall into that trap.</p>
<h1>The single-expectation-per-example fetish</h1>
<p>There is a common overuse of subjects or <code>let</code> variables that's worth discussing separately. Some people like to use them like this:</p>
<pre><code>describe 'Calculator' do
describe '#calculate' do
subject { Calculator.calculate }
it { is_expected.to be >= 0 }
it { is_expected.to be <= 9 }
end
end
</code></pre>
<p>(This is a simple example of a method that returns a number for which we need two expectations, but this style can have many more examples/expectations if the method returns a more complicated value that needs many expectations and/or has many side effects that all need expectations.)</p>
<p>People do this because they've heard that one should have only one expectation per example (which is mixed up with the valid rule that one should only test one method call per example) or because they're in love with RSpec trickiness. Don't do it, whether with an anonymous or named subject or a <code>let</code> variable! This style has several problems:</p>
<ul>
<li>The anonymous subject isn't the subject of the examples — the <em>method</em> is the subject. Writing the test this way screws up the language, making it harder to think about.</li>
<li>As always with one-line examples, there isn't any room to explain the meaning of the expectations.</li>
<li>The subject has to be constructed for each example, which is slow.</li>
</ul>
<p>Instead, write a single example:</p>
<pre><code>describe 'Calculator' do
describe '#calculate' do
it "returns a single-digit number" do
result = Calculator.calculate
expect(result).to be >= 0
expect(result).to be <= 9
end
end
end
</code></pre> |
435,668 | Code for a simple thread pool in C# | <p>Looking for some sample code (C#) for a simple thread pool implementation.</p>
<p>I found one on codeproject, but the codebase was just huge and I don't need all that functionality.</p>
<p>This is more for educational purposes anyways.</p> | 435,691 | 2 | 3 | null | 2009-01-12 15:00:13.263 UTC | 23 | 2019-12-08 18:06:38.773 UTC | 2009-01-12 15:11:59.823 UTC | Rich B | 5,640 | Blankman | 39,677 | null | 1 | 62 | c#|.net|multithreading|threadpool | 88,890 | <p>There is no need to implement your own, since it is not very hard to use the existing .NET implementation.</p>
<p>From <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool.queueuserworkitem?view=netframework-4.8#System_Threading_ThreadPool_QueueUserWorkItem_System_Threading_WaitCallback_System_Object_" rel="nofollow noreferrer">ThreadPool Documentation</a>:</p>
<pre><code>using System;
using System.Threading;
public class Fibonacci
{
public Fibonacci(int n, ManualResetEvent doneEvent)
{
_n = n;
_doneEvent = doneEvent;
}
// Wrapper method for use with thread pool.
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("thread {0} started...", threadIndex);
_fibOfN = Calculate(_n);
Console.WriteLine("thread {0} result calculated...", threadIndex);
_doneEvent.Set();
}
// Recursive method that calculates the Nth Fibonacci number.
public int Calculate(int n)
{
if (n <= 1)
{
return n;
}
return Calculate(n - 1) + Calculate(n - 2);
}
public int N { get { return _n; } }
private int _n;
public int FibOfN { get { return _fibOfN; } }
private int _fibOfN;
private ManualResetEvent _doneEvent;
}
public class ThreadPoolExample
{
static void Main()
{
const int FibonacciCalculations = 10;
// One event is used for each Fibonacci object
ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
Random r = new Random();
// Configure and launch threads using ThreadPool:
Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
for (int i = 0; i < FibonacciCalculations; i++)
{
doneEvents[i] = new ManualResetEvent(false);
Fibonacci f = new Fibonacci(r.Next(20,40), doneEvents[i]);
fibArray[i] = f;
ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
}
// Wait for all threads in pool to calculation...
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("All calculations are complete.");
// Display the results...
for (int i= 0; i<FibonacciCalculations; i++)
{
Fibonacci f = fibArray[i];
Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
}
}
}
</code></pre> |
3,133,711 | SELECT last id, without INSERT | <p>I'm trying to retrieve the id of one table A to insert into another table B. I cannot use last_insert_id() as i have not inserted anything into A. Any ideas on how to do this nicely?</p>
<p><code>$n = mysql_query("SELECT max(id) FROM tablename");</code> doesn't seem to work, nor does</p>
<pre><code>$n = mysql_query("SELECT max(id) FROM tablename GROUP BY id");
</code></pre> | 3,133,783 | 5 | 6 | null | 2010-06-28 15:24:00.443 UTC | 8 | 2019-08-28 06:41:14.547 UTC | null | null | null | null | 213,248 | null | 1 | 17 | mysql|lastinsertid | 126,092 | <p>In MySQL, this does return the highest value from the <code>id</code> column:</p>
<pre><code>SELECT MAX(id) FROM tablename;
</code></pre>
<p>However, this does not put that id into <code>$n</code>:</p>
<pre><code>$n = mysql_query("SELECT max(id) FROM tablename");
</code></pre>
<p>To get the value, you need to do this:</p>
<pre><code>$result = mysql_query("SELECT max(id) FROM tablename");
if (!$result) {
die('Could not query:' . mysql_error());
}
$id = mysql_result($result, 0, 'id');
</code></pre>
<p>If you want to get the last insert ID from A, and insert it into B, you can do it with one command:</p>
<pre><code>INSERT INTO B (col) SELECT MAX(id) FROM A;
</code></pre> |
2,413,391 | How to convert a timedelta object into a datetime object | <p>What is the proper way to convert a timedelta object into a datetime object?</p>
<p>I immediately think of something like <code>datetime(0)+deltaObj</code>, but that's not very nice... Isn't there a <code>toDateTime()</code> function or something of the sort?</p> | 2,413,400 | 5 | 0 | null | 2010-03-09 23:22:45.333 UTC | 8 | 2022-08-04 06:39:23.843 UTC | 2018-10-25 03:11:29.587 UTC | null | 63,550 | null | 154,510 | null | 1 | 37 | python|datetime|timedelta | 74,307 | <p>It doesn't make sense to convert a timedelta into a datetime, but it does make sense to pick an initial or starting datetime and add or subtract a timedelta from that.</p>
<pre><code>>>> import datetime
>>> today = datetime.datetime.today()
>>> today
datetime.datetime(2010, 3, 9, 18, 25, 19, 474362)
>>> today + datetime.timedelta(days=1)
datetime.datetime(2010, 3, 10, 18, 25, 19, 474362)
</code></pre> |
3,186,760 | Change a Nullable column to NOT NULL with Default Value | <p>I came across an old table today with a datetime column called 'Created' which allows nulls. Now, I'd want to change this so that it is NOT NULL, and also include a constraint to add in a default value (getdate()).</p>
<p>So far I've got the following script, which works fine provided that i've cleaned up all the nulls beforehand:</p>
<pre><code>ALTER TABLE dbo.MyTable ALTER COLUMN Created DATETIME NOT NULL
</code></pre>
<p>Is there any way to also specify the default value as well on the ALTER statement?</p> | 3,186,949 | 5 | 2 | null | 2010-07-06 13:50:08.887 UTC | 7 | 2022-02-08 13:01:22.713 UTC | 2022-02-08 13:01:22.713 UTC | null | 9,205,413 | null | 195,583 | null | 1 | 83 | sql|sql-server|default-value|alter-table|alter-column | 182,214 | <p>I think you will need to do this as three separate statements. I've been looking around and everything i've seen seems to suggest you can do it if you are <em>adding</em> a column, but not if you are altering one.</p>
<pre><code>ALTER TABLE dbo.MyTable
ADD CONSTRAINT my_Con DEFAULT GETDATE() for created
UPDATE MyTable SET Created = GetDate() where Created IS NULL
ALTER TABLE dbo.MyTable
ALTER COLUMN Created DATETIME NOT NULL
</code></pre> |
2,774,947 | Using Raw SQL with Doctrine | <p>I have some extremely complex queries that I need to use to generate a report in my application. I'm using symfony as my framework and doctrine as my ORM. </p>
<p>My question is this:</p>
<p>What is the best way to pass in highly-complex sql queries directly to Doctrine without converting them to the Doctrine Query Language? I've been reading about the <code>Raw_SQL</code> extension but it appears that you still need to pass the query in sections (like <code>from()</code>). Is there anything for just dumping in a bunch of raw sql commands?</p> | 2,777,020 | 6 | 2 | null | 2010-05-05 16:13:57.113 UTC | 18 | 2013-01-19 09:58:34.01 UTC | null | null | null | null | 122,164 | null | 1 | 44 | sql|symfony1|doctrine | 58,783 | <pre><code>$q = Doctrine_Manager::getInstance()->getCurrentConnection();
$result = $q->execute(" -- RAW SQL HERE -- ");
</code></pre>
<p>See the Doctrine API documentation for different execution methods.</p> |
3,024,819 | How do I check if an email address is valid without sending anything to it? | <p>I have a client with 5000 emails from an old list he has that he wants to promote his services to. He wants to know which emails on the list are still valid. I want to check them for him - without sending out 5K emails randomly and then being listed as a spammer or something. Ideas?</p> | 3,025,082 | 7 | 2 | null | 2010-06-11 17:22:05.623 UTC | 6 | 2017-07-04 02:03:37.117 UTC | null | null | null | null | 344,308 | null | 1 | 13 | email | 41,470 | <p><a href="https://stackoverflow.com/questions/3024819/how-do-i-check-if-an-email-address-is-valid-without-sending-anything-to-it/3024903#3024903">bucabay's</a> answer is the way forward. What a library like that essentially does is checking for existing DNS record for (mail) servers at specified domains (A, MX, or AAAA). After that, it do what's termed callback verification. That's where you connect to the mail server, tell it you want to send to a particular email address and see if they say OK.</p>
<p>For callback verification, you should note greylisting servers say OK to everything so there is no 100% guarantee possible without actually sending the emails out. Here's some code I used when I did this manually. It's a patch onto the email address parser from <a href="http://code.iamcal.com/php/rfc822/" rel="nofollow noreferrer">here</a>.</p>
<pre><code> #
# Email callback verification
# Based on http://uk2.php.net/manual/en/function.getmxrr.php
#
if (strlen($bits['domain-literal'])){
$records = array($bits['domain-literal']);
}elseif (!getmxrr($bits['domain'], $mx_records, $mx_weight)){
$records = array($bits['domain']);
}else{
$mxs = array();
for ($i = 0; $i < count($mx_records); $i++){
$mxs[$mx_records[$i]] = $mx_weight[$i];
}
asort($mxs);
$records = array_keys($mxs);
}
$user_okay = false;
for ($j = 0; $j < count($records) && !$user_okay; $j++){
$fp = @fsockopen($records[$j], 25, $errno, $errstr, 2);
if($fp){
$ms_resp = "";
$ms_resp .= send_command($fp, "HELO ******.com");
$ms_resp .= send_command($fp, "MAIL FROM:<>");
$rcpt_text = send_command($fp, "RCPT TO:<" . $email . ">");
$ms_resp .= $rcpt_text;
$ms_code = intval(substr($rcpt_text, 0, 3));
if ($ms_code == 250 || $ms_code == 451){ // Accept all user account on greylisting server
$user_okay = true;
}
$ms_resp .= send_command($fp, "QUIT");
fclose($fp);
}
}
return $user_okay ? 1 : 0;
</code></pre> |
2,867,607 | MySQL - SELECT * INTO OUTFILE LOCAL ? | <p>MySQL is awesome! I am currently involved in a major server migration and previously, our small database used to be hosted on the same server as the client. <BR>So we used to do this : <code>SELECT * INTO OUTFILE .... LOAD DATA INFILE ....</code></p>
<p>Now, we moved the database to a different server and <code>SELECT * INTO OUTFILE ....</code> no longer works, understandable - security reasons I believe.
But, interestingly <code>LOAD DATA INFILE ....</code> can be changed to <code>LOAD DATA LOCAL INFILE ....</code> and bam, it works.</p>
<p>I am not complaining nor am I expressing disgust towards MySQL. The alternative to that added 2 lines of extra code and a system call form a .sql script. All I wanted to know is why <code>LOAD DATA LOCAL INFILE</code> works and why is there no such thing as <code>SELECT INTO OUTFILE LOCAL</code>?</p>
<p>I did my homework, couldn't find a direct answer to my questions above. I couldn't find a feature request @ MySQL either. If someone can clear that up, that had be awesome! </p>
<p>Is MariaDB capable of handling this problem?</p> | 2,970,539 | 7 | 1 | null | 2010-05-19 16:46:16.67 UTC | 8 | 2020-08-14 13:59:21.783 UTC | 2014-03-31 13:37:27.733 UTC | null | 1,504,392 | null | 235,310 | null | 1 | 46 | mysql|sql|mariadb|into-outfile | 122,837 | <p>From the manual: <code>The SELECT ... INTO OUTFILE</code> statement is intended primarily to let you very quickly dump a table to a text file on the server machine. If you want to create the resulting file on some client host other than the server host, you cannot use <code>SELECT ... INTO OUTFILE</code>. In that case, you should instead use a command such as <code>mysql -e "SELECT ..." > file_name</code> to generate the file on the client host." </p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/select.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/select.html</a></p>
<p>An example:</p>
<pre><code>mysql -h my.db.com -u usrname--password=pass db_name -e 'SELECT foo FROM bar' > /tmp/myfile.txt
</code></pre> |
2,940,916 | How do I embed an AppleScript in a Python script? | <p>I am trying to embed an AppleScript in a Python script. I don't want to have to save the AppleScript as a file and then load it in my Python script. Is there a way to enter the AppleScript as a string in Python and have Python execute the AppleScript? Thanks a bunch.</p>
<p>Here is my script:
import subprocess
import re
import os</p>
<pre><code>def get_window_title():
cmd = """osascript<<END
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
end tell
tell application frontApp
if the (count of windows) is not 0 then
set window_name to name of front window
end if
end tell
return window_name
END"""
p = subprocess.Popen(cmd, shell=True)
p.terminate()
return p
def get_class_name(input_str):
re_expression = re.compile(r"(\w+)\.java")
full_match = re_expression.search(input_str)
class_name = full_match.group(1)
return class_name
print get_window_title()
</code></pre> | 2,941,735 | 9 | 1 | null | 2010-05-31 01:08:23.97 UTC | 9 | 2020-12-31 00:48:30.873 UTC | 2018-07-06 14:50:24.703 UTC | null | 179,352 | null | 179,352 | null | 1 | 15 | python|macos|applescript | 24,303 | <p>Use <a href="http://docs.python.org/library/subprocess.html" rel="noreferrer">subprocess</a>:</p>
<pre><code>from subprocess import Popen, PIPE
scpt = '''
on run {x, y}
return x + y
end run'''
args = ['2', '2']
p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
print (p.returncode, stdout, stderr)
</code></pre> |
3,112,882 | How many classes are there in Java standard edition? | <p>I am curious how many classes are there in Java standard library. Perhaps someone knows an approximate number?</p> | 3,112,919 | 9 | 3 | null | 2010-06-24 18:32:56.413 UTC | 11 | 2020-05-16 23:55:56.613 UTC | null | null | null | null | 80,237 | null | 1 | 46 | java | 29,178 | <p>By counting entries in the 'all classes' frame of the javadoc API:</p>
<ul>
<li><code>4569</code> in <a href="https://docs.oracle.com/en/java/javase/14/docs/api/allclasses-index.html" rel="noreferrer">java 14</a></li>
<li><code>4545</code> in <a href="https://docs.oracle.com/en/java/javase/13/docs/api/allclasses-index.html" rel="noreferrer">java 13</a></li>
<li><code>4433</code> in <a href="https://docs.oracle.com/en/java/javase/12/docs/api/" rel="noreferrer">java 12</a></li>
<li><code>4411</code> in <a href="https://docs.oracle.com/en/java/javase/11/docs/api/" rel="noreferrer">java 11</a></li>
<li><code>6002</code> in <a href="http://docs.oracle.com/javase/10/docs/api/index.html?overview-summary.html" rel="noreferrer">java 10</a></li>
<li><code>6005</code> in <a href="http://docs.oracle.com/javase/9/docs/api/index.html?overview-summary.html" rel="noreferrer">java 9</a></li>
<li><code>4240</code> in <a href="http://docs.oracle.com/javase/8/docs/api/" rel="noreferrer">java 8</a></li>
<li><code>4024</code> in <a href="http://docs.oracle.com/javase/7/docs/api/" rel="noreferrer">java 7</a></li>
<li><code>3793</code> in <a href="http://docs.oracle.com/javase/6/docs/api/" rel="noreferrer">java 6</a></li>
<li><code>3279</code> in <a href="http://docs.oracle.com/javase/1.5.0/docs/api/" rel="noreferrer">java 5.0</a></li>
<li><code>2723</code> in <a href="http://docs.oracle.com/javase/1.4.2/docs/api/" rel="noreferrer">java 1.4.2</a>*</li>
<li><code>1840</code> in <a href="http://docs.oracle.com/javase/1.3/docs/api/" rel="noreferrer">java 1.3.1</a>*</li>
</ul>
<p>* Javadocs prior to 5.0 are now offline.</p> |
2,353,666 | PHP: Is mysql_real_escape_string sufficient for cleaning user input? | <p>Is <code>mysql_real_escape_string</code> sufficient for cleaning user input in most situations?</p>
<p>::EDIT::</p>
<p>I'm thinking mostly in terms of preventing SQL injection but I ultimately want to know if I can trust user data after I apply mysql_real_escape_string or if I should take extra measures to clean the data before I pass it around the application and databases. </p>
<p>I see where cleaning for HTML chars is important but I wouldn't consider it necessary for trusting user input.</p>
<p>T</p> | 2,353,687 | 10 | 5 | null | 2010-03-01 03:06:08.883 UTC | 19 | 2012-05-11 21:29:30.983 UTC | 2010-03-01 03:29:13.737 UTC | null | 164,468 | null | 164,468 | null | 1 | 58 | php|security | 30,746 | <p><code>mysql_real_escape_string</code> is not sufficient in all situations but it is definitely very good friend. The <strong>better</strong> solution is using <strong><a href="http://php.net/manual/en/pdo.prepared-statements.php" rel="noreferrer">Prepared Statements</a></strong></p>
<pre><code>//example from http://php.net/manual/en/pdo.prepared-statements.php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
</code></pre>
<p>Also, not to forget <strong><a href="http://htmlpurifier.org/" rel="noreferrer">HTMLPurifier</a></strong> that can be used to discard any invalid/suspicious characters.</p>
<p>...........</p>
<p><strong>Edit:</strong>
Based on the comments below, I need to post this link (I should have done before sorry for creating confusion)</p>
<p><strong><a href="http://ilia.ws/archives/103-mysql_real_escape_string-versus-Prepared-Statements.html" rel="noreferrer">mysql_real_escape_string() versus Prepared Statements</a></strong></p>
<p><strong>Quoting:</strong></p>
<blockquote>
<p>mysql_real_escape_string() prone to
the same kind of issues affecting
addslashes().</p>
</blockquote>
<p><strong>Chris Shiflett</strong> (Security Expert)</p> |
2,338,035 | Installing a configuration profile on iPhone - programmatically | <p>I would like to ship a configuration profile with my iPhone application, and install it if needed. </p>
<p>Mind you, we're talking about a configuration profile, not a provisioning profile.</p>
<p>First off, such a task is possible. If you place a config profile on a Web page and click on it from Safari, it will get installed. If you e-mail a profile and click the attachment, it will install as well. "Installed" in this case means "The installation UI is invoked" - but I could not even get that far.</p>
<p>So I was working under the theory that initiating a profile installation involves navigating to it as a URL. I added the profile to my app bundle.</p>
<p><strong>A)</strong> First, I tried [sharedApp openURL] with the file:// URL into my bundle. No such luck - nothing happens.</p>
<p><strong>B)</strong> I then added an HTML page to my bundle that has a link to the profile, and loaded it into a UIWebView. Clicking on the link does nothing. Loading an identical page from a Web server in Safari, however, works fine - the link is clickable, the profile installs. I provided a UIWebViewDelegate, answering YES to every navigation request - no difference.</p>
<p><strong>C)</strong> Then I tried to load the same Web page from my bundle in Safari (using [sharedApp openURL] - nothing happens. I guess, Safari cannot see files inside my app bundle.</p>
<p><strong>D)</strong> Uploading the page and the profile on a Web server is doable, but a pain on the organizational level, not to mention an extra source of failures (what if no 3G coverage? etc.).</p>
<p><strong>So my big question is: **how do I install a profile programmatically?</strong></p>
<p>And the little questions are: what can make a link non-clickable within a UIWebView? Is it possible to load a file:// URL from <em>my</em> bundle in Safari? If not, is there a local location on iPhone where I can place files and Safari can find them?</p>
<p><strong>EDIT on B):</strong> the problem is somehow in the fact that we're linking to a profile. I renamed it from .mobileconfig to .xml ('cause it's really XML), altered the link. And the link worked in my UIWebView. Renamed it back - same stuff. It looks as if UIWebView is reluctant to do application-wide stuff - since installation of the profile closes the app. I tried telling it that it's OK - by means of UIWebViewDelegate - but that did not convince. Same behavior for mailto: URLs within UIWebView.</p>
<p><strong>For mailto:</strong> URLs the common technique is to translate them into [openURL] calls, but that doesn't quite work for my case, see scenario A.</p>
<p>For itms: URLs, however, UIWebView works as expected...</p>
<p><strong>EDIT2:</strong> tried feeding a data URL to Safari via [openURL] - does not work, see here: <a href="https://stackoverflow.com/questions/641461/iphone-open-data-url-in-safari">iPhone Open DATA: Url In Safari</a></p>
<p><strong>EDIT3:</strong> found a lot of info on how Safari does not support file:// URLs. UIWebView, however, very much does. Also, Safari on the simulator open them just fine. The latter bit is the most frustrating.</p>
<hr>
<p><strong>EDIT4:</strong> I never found a solution. Instead, I put together a two-bit Web interface where the users can order the profile e-mailed to them.</p> | 9,854,934 | 10 | 9 | null | 2010-02-25 22:07:19.777 UTC | 66 | 2016-11-30 05:30:41.06 UTC | 2017-05-23 12:02:36.45 UTC | null | -1 | null | 219,159 | null | 1 | 76 | iphone|cocoa-touch|ios-simulator|configuration-files | 50,029 | <p>1) Install a local server like <a href="https://github.com/mattstevens/RoutingHTTPServer" rel="noreferrer">RoutingHTTPServer</a><br /><br />
2) Configure the custom header : </p>
<pre><code>[httpServer setDefaultHeader:@"Content-Type" value:@"application/x-apple-aspen-config"];
</code></pre>
<p>3) Configure the local root path for the mobileconfig file (Documents):</p>
<pre><code>[httpServer setDocumentRoot:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
</code></pre>
<p>4) In order to allow time for the web server to send the file, add this :</p>
<pre><code>Appdelegate.h
UIBackgroundTaskIdentifier bgTask;
Appdelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
[application endBackgroundTask:self->bgTask];
self->bgTask = UIBackgroundTaskInvalid;
});
}];
}
</code></pre>
<p>5) In your controller, call safari with the name of the mobileconfig stored in Documents :</p>
<pre><code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://localhost:12345/MyProfile.mobileconfig"]];
</code></pre> |
2,422,946 | javascript check for not null | <p>Below is a code snippet, where we retrieve a form value.
Before further processing check if the value is not null..</p>
<pre><code>var val = document.FileList.hiddenInfo.value;
alert("val is " + val); // this prints null which is as expected
if (val != null)
{
alert("value is "+val.length); // this returns 4
}
else
{
alert("value* is null");
}
</code></pre>
<p>Any ideas why it happens so.. ??</p> | 2,422,956 | 11 | 4 | 2010-03-11 06:13:46.61 UTC | 2010-03-11 06:10:42.62 UTC | 27 | 2022-09-03 17:27:55.593 UTC | 2014-06-16 14:05:15.407 UTC | null | 1,018,200 | null | 23,414 | null | 1 | 170 | javascript | 519,027 | <p>It's because val is not <code>null</code>, but contains <code>'null'</code> as a string.</p>
<p>Try to check with 'null'</p>
<pre><code>if ('null' != val)
</code></pre>
<p>For an explanation of when and why this works, see <a href="https://stackoverflow.com/a/34817844/884640">the details below</a>.</p> |
2,948,484 | How to get MVC action to return 404 | <p>I have an action that takes in a string that is used to retrieve some data. If this string results in no data being returned (maybe because it has been deleted), I want to return a 404 and display an error page. </p>
<p>I currently just use return a special view that display a friendly error message specific to this action saying that the item was not found. This works fine, but would ideally like to return a 404 status code so search engines know that this content no longer exists and can remove it from the search results.</p>
<p>What is the best way to go about this?</p>
<p>Is it as simple as setting Response.StatusCode = 404?</p> | 2,948,501 | 12 | 1 | null | 2010-06-01 09:14:15.557 UTC | 21 | 2017-05-16 11:04:59.923 UTC | null | null | null | null | 246,396 | null | 1 | 149 | asp.net-mvc|error-handling|http-status-code-404 | 109,565 | <p>There are multiple ways to do it,</p>
<ol>
<li>You are right in common aspx code it can be assigned in your specified way</li>
<li><code>throw new HttpException(404, "Some description");</code></li>
</ol> |
2,814,002 | Private IP Address Identifier in Regular Expression | <p>I'm wondering if this is the best way to match a string that starts with a private IP address (Perl-style Regex):</p>
<pre><code>(^127\.0\.0\.1)|(^192\.168)|(^10\.)|(^172\.1[6-9])|(^172\.2[0-9])|(^172\.3[0-1])
</code></pre>
<p>Thanks much!</p> | 2,814,102 | 13 | 3 | null | 2010-05-11 19:55:09.053 UTC | 9 | 2022-05-15 16:38:31.84 UTC | 2014-01-09 10:10:18.72 UTC | null | 352,176 | null | 143,201 | null | 1 | 42 | regex|ip-address|private | 63,321 | <p>I'm assuming you want to match these ranges:</p>
<pre>
127. 0.0.0 – 127.255.255.255 127.0.0.0 /8
10. 0.0.0 – 10.255.255.255 10.0.0.0 /8
172. 16.0.0 – 172. 31.255.255 172.16.0.0 /12
192.168.0.0 – 192.168.255.255 192.168.0.0 /16
</pre>
<p>You are missing some dots that would cause it to accept for example <code>172.169.0.0</code> even though this should not be accepted. I've fixed it below. Remove the new lines, it's just for readability.</p>
<pre><code>(^127\.)|
(^10\.)|
(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|
(^192\.168\.)
</code></pre>
<p>Also note that this assumes that the IP addresses have already been validated - it accepts things like <code>10.foobar</code>.</p> |
2,878,136 | VS2010 error: Unable to start debugging on the web server | <p>I get error message "Unable to start debugging on the web server" in Visual Studio 2010. I clicked the Help button and followed the related suggestions without success.</p>
<p>This happens with a newly created local ASP.Net project when modified to use IIS instead of Cassini (which works for debugging). It prompts to set debug="true" in the web.config and then immediately pops up the error. Nothing shows up in the Event Viewer.</p>
<p>I am able to attach to w3wp to debug. It works but is not as convenient as F5.</p>
<p>I also have a similar problem with VS2008 on the same PC. Debugging used to work for both.</p>
<p>I have re-registered Framework 4 (aspnet_regiis -i). I ran the VS2010 repair (this is the RTM version). I am running on a Windows Server 2008 R2 x64 box.</p>
<p>I do have Resharper V5 installed.</p>
<p>There must be some configuration setting or registry value that survives the repair causing the problem.</p>
<p>I'd appreciate any ideas.</p> | 8,233,645 | 27 | 3 | null | 2010-05-20 21:54:58.897 UTC | 12 | 2017-05-16 11:36:40.103 UTC | 2012-11-27 13:31:33.047 UTC | null | 64,976 | null | 234,004 | null | 1 | 17 | asp.net|debugging|visual-studio-2010|iis-7.5 | 59,241 | <p>I got a new PC with <code>Windows 7</code>. I installed <code>VS2010</code> and my development environment and hoped my F5 debug problem would be gone, but it still failed to start the debugger. </p>
<p>This was a good clue since it ruled out the install of software.</p>
<p>I finally traced it down to my HOSTS file. I had an entry for some of my local websites which I can access like "<a href="http://testsite.lcl" rel="nofollow noreferrer">http://testsite.lcl</a>" but the IP I had assigned was my machine's IP instead of using <code>127.0.0.1</code> so it looked like a remote server to VS2010. Changing back to <code>127.0.0.1</code> resolved the issue.</p>
<p>Thanks for everyone's help on this.</p> |
40,685,562 | How to convert a string to number | <p>I can't figure it out how to convert this string <code>82144251</code> to a number.</p>
<p>Code:</p>
<pre><code>var num = "82144251";
</code></pre>
<p>If I try the code below the <code>.toFixed()</code> function converts my number back to a string...</p>
<p>Question update:
I'm using the Google Apps Script editor and that must be the issue...</p>
<pre><code>num = parseInt(num).toFixed() // if I just do parseInt(num) it returns 8.2144251E7
</code></pre> | 40,685,642 | 6 | 16 | null | 2016-11-18 20:38:18.697 UTC | 6 | 2022-09-15 03:13:54.027 UTC | 2022-09-15 03:13:54.027 UTC | null | 1,595,451 | null | 4,737,546 | null | 1 | 27 | javascript|google-apps-script|string-conversion | 121,134 | <p>You can convert a string to number using unary operator '+' or parseInt(number,10) or Number()</p>
<p>check these snippets</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var num1a = "1";
console.log(+num1a);
var num1b = "2";
num1b=+num1b;
console.log(num1b);
var num3 = "3"
console.log(parseInt(num3,10));
var num4 = "4";
console.log(Number(num4));</code></pre>
</div>
</div>
</p>
<p>Hope it helps</p> |
40,225,683 | How to simply add a column level to a pandas dataframe | <p>let say I have a dataframe that looks like this:</p>
<pre><code>df = pd.DataFrame(index=list('abcde'), data={'A': range(5), 'B': range(5)})
df
Out[92]:
A B
a 0 0
b 1 1
c 2 2
d 3 3
e 4 4
</code></pre>
<p>Asumming that this dataframe already exist, how can I simply add a level 'C' to the column index so I get this:</p>
<pre><code> df
Out[92]:
A B
C C
a 0 0
b 1 1
c 2 2
d 3 3
e 4 4
</code></pre>
<p>I saw SO anwser like this <a href="https://stackoverflow.com/questions/15989281/python-pandas-how-to-combine-two-dataframes-into-one-with-hierarchical-column-i">python/pandas: how to combine two dataframes into one with hierarchical column index?</a> but this concat different dataframe instead of adding a column level to an already existing dataframe.</p>
<p>-</p> | 40,225,796 | 6 | 0 | null | 2016-10-24 19:03:52.743 UTC | 15 | 2022-05-26 07:55:47.86 UTC | 2017-05-23 12:02:50.75 UTC | null | -1 | null | 5,626,112 | null | 1 | 79 | python|pandas|dataframe|multi-level | 62,938 | <p>As suggested by @StevenG himself, a better answer:</p>
<pre><code>df.columns = pd.MultiIndex.from_product([df.columns, ['C']])
print(df)
# A B
# C C
# a 0 0
# b 1 1
# c 2 2
# d 3 3
# e 4 4
</code></pre> |
39,956,497 | Pandoc convert docx to markdown with embedded images | <p>When converting .docx file to markdown, the embedded image is not extracted from the docx archive, yet the output contains <code>{width="6.291666666666667in"
height="3.1083333333333334in"}</code> </p>
<p>Is there a parameter that needs to be set in order to get the embedded pictures extracted?</p> | 39,961,440 | 2 | 0 | null | 2016-10-10 10:45:40.96 UTC | 18 | 2022-01-25 09:48:59.083 UTC | null | null | null | null | 5,986,754 | null | 1 | 63 | pandoc | 35,809 | <pre><code>pandoc --extract-media ./myMediaFolder input.docx -o output.md
</code></pre>
<p>From the <a href="https://pandoc.org/MANUAL.html#option--extract-media" rel="noreferrer">manual</a>:</p>
<blockquote>
<p><code>--extract-media=DIR</code> Extract images and other media contained in or linked from the source document to the path DIR, creating it if necessary, and adjust the images references in the document so they point to the extracted files. Media are downloaded, read from the file system, or extracted from a binary container (e.g. docx), as needed. The original file paths are used if they are relative paths not containing <code>..</code>. Otherwise filenames are constructed from the SHA1 hash of the contents.</p>
</blockquote> |
10,735,282 | python - get list of tuples first index? | <p>What's the most compact way to return the following:</p>
<p>Given a list of tuples, return a list consisting of the tuples first (or second, doesn't matter) elements.</p>
<p>For:</p>
<pre><code>[(1,'one'),(2,'two'),(3,'three')]
</code></pre>
<p>returned list would be</p>
<pre><code>[1,2,3]
</code></pre> | 10,735,413 | 5 | 0 | null | 2012-05-24 10:03:41.15 UTC | 7 | 2018-08-15 14:22:10.887 UTC | 2015-08-25 13:28:15.223 UTC | null | 2,932,052 | null | 1,413,824 | null | 1 | 35 | python|list|tuples | 36,268 | <p>use zip if you need both </p>
<pre><code>>>> r=(1,'one'),(2,'two'),(3,'three')
>>> zip(*r)
[(1, 2, 3), ('one', 'two', 'three')]
</code></pre> |
10,741,190 | Currency Formatting MVC | <p>I'm trying to format an Html.EditorFor textbox to have currency formatting, I am trying to base it off of this thread <a href="https://stackoverflow.com/questions/6963497/string-format-for-currency-on-a-textboxfor">String.Format for currency on a TextBoxFor</a>. However, my text just still shows up as 0.00 with no currency formatting.</p>
<pre><code><div class="editor-field">
@Html.EditorFor(model => model.Project.GoalAmount, new { @class = "editor- field", Value = String.Format("{0:C}", Model.Project.GoalAmount) })
</code></pre>
<p>There is the code for what I am doing, and here is the html for that field in the website itself contained within the editor-field div of course.</p>
<pre><code><input class="text-box single-line valid" data-val="true"
data-val-number="The field Goal Amount must be a number."
data-val-required="The Goal Amount field is required."
id="Project_GoalAmount" name="Project.GoalAmount" type="text" value="0.00">
</code></pre>
<p>Any help would be appreciated, thanks!</p> | 10,741,233 | 1 | 0 | null | 2012-05-24 16:05:13.123 UTC | 5 | 2018-10-12 10:13:27.043 UTC | 2017-05-23 12:10:38.81 UTC | null | -1 | null | 1,030,289 | null | 1 | 37 | asp.net-mvc-3|razor|string.format | 81,454 | <p>You could decorate your <code>GoalAmount</code> view model property with the <code>[DisplayFormat]</code> attribute:</p>
<pre><code>[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public decimal GoalAmount { get; set; }
</code></pre>
<p>and in the view simply:</p>
<pre><code>@Html.EditorFor(model => model.Project.GoalAmount)
</code></pre>
<p>The second argument of the EditorFor helper doesn't do at all what you think it does. It allows you to pass additional ViewData to the editor template, it's not htmlAttributes.</p>
<p>Another possibility is to write a custom editor template for currency (<code>~/Views/Shared/EditorTemplates/Currency.cshtml</code>):</p>
<pre><code>@Html.TextBox(
"",
string.Format("{0:c}", ViewData.Model),
new { @class = "text-box single-line" }
)
</code></pre>
<p>and then:</p>
<pre><code>@Html.EditorFor(model => model.Project.GoalAmount, "Currency")
</code></pre>
<p>or use <code>[UIHint]</code>:</p>
<pre><code>[UIHint("Currency")]
public decimal GoalAmount { get; set; }
</code></pre>
<p>and then:</p>
<pre><code>@Html.EditorFor(model => model.Project.GoalAmount)
</code></pre> |
10,394,479 | Eclipse cursor changes to crosshair | <p>I was working in Eclipse Java EE IDE. While using it, mouse cursor changes to cross-hair. Now its displaying as cross-hair in editors. Where to change it?</p> | 10,394,490 | 4 | 0 | null | 2012-05-01 06:45:31.463 UTC | 7 | 2022-07-30 10:55:47.027 UTC | 2021-12-22 19:30:16.89 UTC | null | 4,294,399 | null | 420,613 | null | 1 | 98 | java|eclipse|editor|mouse-cursor | 46,326 | <p>Most likely this is the block edit mode. Try pressing <kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>A</kbd>.</p> |
5,937,373 | Using Apache POI HSSF, how can I refresh all formula cells at once? | <p>I am filling cells of an Excel file using Apache POI, and there are a lot of formula cells in the document. However, their values are not refreshed when I open the document in Excel.</p>
<p>It's my understanding that I need to use a <code>FormulaEvaluator</code> to refresh formula cells. Is there a way, though, to update all formula cells at once? There are a <em>lot</em> of them, and while making an exhaustive list is not out of question, it's certainly not something I'm very willing to do.</p> | 5,937,590 | 2 | 0 | null | 2011-05-09 13:13:23.127 UTC | 13 | 2020-08-27 11:02:49.353 UTC | 2011-05-09 13:14:25.763 UTC | null | 21,234 | null | 251,153 | null | 1 | 39 | java|apache-poi | 29,447 | <p>Sure. Refreshing all the formulas in a workbook is possibly the more typical use case anyway.</p>
<p>If you're using HSSF, call <a href="http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFFormulaEvaluator.html#evaluateAllFormulaCells(org.apache.poi.hssf.usermodel.HSSFWorkbook)" rel="noreferrer">evaluatorAllFormulaCells</a>:</p>
<pre><code> HSSFFormulaEvaluator.evaluateAllFormulaCells(hssfWorkbook)
</code></pre>
<p>If you're using XSSF, call <a href="http://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.html#evaluateAllFormulaCells(org.apache.poi.xssf.usermodel.XSSFWorkbook)" rel="noreferrer">evaluatorAllFormulaCells</a>:</p>
<pre><code> XSSFFormulaEvaluator.evaluateAllFormulaCells(xssfWorkbook)
</code></pre>
<p>More details are available on the <a href="http://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.html#evaluateAllFormulaCells(org.apache.poi.xssf.usermodel.XSSFWorkbook)" rel="noreferrer">poi website</a></p> |
5,912,980 | Turning off the WebFormViewEngine when using razor? | <p>I downloaded <a href="http://www.getglimpse.com/">Glimpse</a> this morning to try it out and noticed this when I click on the views tab:</p>
<p><img src="https://i.stack.imgur.com/7Ubq5.png" alt="Glimpse Views Tab"></p>
<p>It checks all of the loaded view engines. I found where the <code>RazorViewEngine</code> is specified in web.config, but I couldn't find where the <code>WebFormViewEngine</code> was. Since I know my project will never have an web form view in it, </p>
<ol>
<li>Is it ok/safe to turn off <code>WebFormViewEngine</code>?</li>
<li>How can I turn off <code>WebFormViewEngine</code>?</li>
</ol> | 5,913,327 | 2 | 0 | null | 2011-05-06 14:38:34.033 UTC | 11 | 2018-08-29 12:51:18.067 UTC | 2011-05-06 14:56:46.783 UTC | null | 178,082 | null | 178,082 | null | 1 | 47 | asp.net-mvc|configuration|webforms|razor | 8,645 | <p>It is perfectly OK to remove the web forms view engine if you are not using it. You can do it like:</p>
<pre><code>public class Global : HttpApplication
{
public void Application_Start()
{
// Clears all previously registered view engines.
ViewEngines.Engines.Clear();
// Registers our Razor C# specific view engine.
// This can also be registered using dependency injection through the new IDependencyResolver interface.
ViewEngines.Engines.Add(new RazorViewEngine());
}
}
</code></pre>
<p>The above method calls go in your <code>global.asax</code> file.</p>
<p>source of <a href="http://web.archive.org/web/20110217183120/http://www.waynehaffenden.com/Blog/ASPNET-MVC-3-Razor-CSharp-View-Engine" rel="nofollow noreferrer">code</a></p> |
19,654,195 | $http request before AngularJS app initialises? | <p>In order to determine if a user's session is authenticated, I need to make a $http request to the server before the first route is loaded. Before each route is loaded, an authentication service checks the status of the user and the access level required by the route, and if the user isn't authenticated for that route, it redirects to a login page. When the app is first loaded however, it has no knowledge of the user, so even if they have an authenticated session it will always redirect to the login page. So to fix this I'm trying to make a request to the server for the users status as a part of the app initialisation. The issue is that obviously $http calls are asynchronous, so how would I stop the app running until the request has finished?</p>
<p>I'm very new to Angular and front-end development in general, so my issue maybe a misunderstanding of javascript rather than of Angular. </p> | 19,654,889 | 2 | 0 | null | 2013-10-29 09:25:15.26 UTC | 8 | 2014-08-29 09:31:04.733 UTC | 2013-10-29 10:45:15.307 UTC | null | 1,744,013 | null | 1,744,013 | null | 1 | 19 | javascript|angularjs | 11,177 | <p>You could accomplish that by using <code>resolve</code> in your routingProvider.</p>
<p>This allows you to wait for some promises to be resolved before the controller will be initiated.</p>
<p>Quote from the docs:</p>
<blockquote>
<p>resolve - {Object.=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired.</p>
</blockquote>
<h3>Simple example</h3>
<pre><code> app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: 'home.html', controller: 'MyCtrl',resolve: {
myVar: function($q,$http){
var deffered = $q.defer();
// make your http request here and resolve its promise
$http.get('http://example.com/foobar')
.then(function(result){
deffered.resolve(result);
})
return deffered.promise;
}
}}).
otherwise({redirectTo: '/'});
}]);
</code></pre>
<p>myVar will then be injected to your controller, containing the promise data.</p>
<h3>Avoiding additional DI parameter</h3>
<p>You could also avoid the additional DI parameter by returning a service you were going to inject anyways:</p>
<pre><code>app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: 'home.html', controller: 'MyCtrl',resolve: {
myService: function($q,$http,myService){
var deffered = $q.defer();
/* make your http request here
* then, resolve the deffered's promise with your service.
*/
deffered.resolve(myService),
return deffered.promise;
}
}}).
otherwise({redirectTo: '/'});
}]);
</code></pre>
<p>Obviously, you will have to store the result from your request anywhere in a shared service when doing things like that.</p>
<hr>
<p>Have a look at <a href="http://docs.angularjs.org/api/ngRoute.$routeProvider" rel="noreferrer"><strong>Angular Docs / routeProvider</strong></a></p>
<p>I have learned most of that stuff from that guy at <a href="http://egghead.io/lessons/angularjs-resolve" rel="noreferrer"><strong>egghead.io</strong></a></p> |
19,574,286 | How to merge contents of SQLite 3.7 WAL file into main database file | <p>With <a href="http://www.sqlite.org/wal.html">WAL (Write-Ahead-Logging)</a> enabled in SQLite 3.7 (which is the default for Core Data on iOS 7), how do I merge/commit the content from the -wal file back into the main database file?</p> | 19,575,935 | 3 | 0 | null | 2013-10-24 18:58:00.597 UTC | 13 | 2020-01-17 07:47:27.643 UTC | null | null | null | null | 171,933 | null | 1 | 30 | sqlite|ios7|wal | 17,887 | <p>Do a <a href="http://www.sqlite.org/wal.html#ckpt" rel="noreferrer">checkpoint</a>, i.e., execute <a href="http://www.sqlite.org/pragma.html#pragma_wal_checkpoint" rel="noreferrer">PRAGMA wal_checkpoint</a>.</p> |
32,328,179 | OpenCV 3.0 LineIterator | <p>I want to use the <a href="http://docs.opencv.org/3.0-beta/modules/imgproc/doc/drawing_functions.html#lineiterator" rel="noreferrer">LineIterator</a> in OpenCV 3.0 using Python, is it still available with OpenCV 3.0 built for Python? It seems that the answers on the internet are all pointing to <code>cv.InitLineIterator</code> which is part of the <code>cv</code> module. I've tried importing this module but it seems like it is not included with the current build. Has it been renamed or strictly just removed?</p> | 32,857,432 | 6 | 0 | null | 2015-09-01 09:35:29.81 UTC | 13 | 2022-01-16 12:55:16.427 UTC | 2019-11-12 09:24:57.767 UTC | null | 7,851,470 | null | 3,098,020 | null | 1 | 49 | python|opencv|opencv3.0 | 23,513 | <p>I've solved my own problem. Line iterator seems to be unavailable in the cv2 library. Therefore, I made my own line iterator. No loops are used, so it should be pretty fast. Here is the code if anybody needs it:</p>
<pre><code>def createLineIterator(P1, P2, img):
"""
Produces and array that consists of the coordinates and intensities of each pixel in a line between two points
Parameters:
-P1: a numpy array that consists of the coordinate of the first point (x,y)
-P2: a numpy array that consists of the coordinate of the second point (x,y)
-img: the image being processed
Returns:
-it: a numpy array that consists of the coordinates and intensities of each pixel in the radii (shape: [numPixels, 3], row = [x,y,intensity])
"""
#define local variables for readability
imageH = img.shape[0]
imageW = img.shape[1]
P1X = P1[0]
P1Y = P1[1]
P2X = P2[0]
P2Y = P2[1]
#difference and absolute difference between points
#used to calculate slope and relative location between points
dX = P2X - P1X
dY = P2Y - P1Y
dXa = np.abs(dX)
dYa = np.abs(dY)
#predefine numpy array for output based on distance between points
itbuffer = np.empty(shape=(np.maximum(dYa,dXa),3),dtype=np.float32)
itbuffer.fill(np.nan)
#Obtain coordinates along the line using a form of Bresenham's algorithm
negY = P1Y > P2Y
negX = P1X > P2X
if P1X == P2X: #vertical line segment
itbuffer[:,0] = P1X
if negY:
itbuffer[:,1] = np.arange(P1Y - 1,P1Y - dYa - 1,-1)
else:
itbuffer[:,1] = np.arange(P1Y+1,P1Y+dYa+1)
elif P1Y == P2Y: #horizontal line segment
itbuffer[:,1] = P1Y
if negX:
itbuffer[:,0] = np.arange(P1X-1,P1X-dXa-1,-1)
else:
itbuffer[:,0] = np.arange(P1X+1,P1X+dXa+1)
else: #diagonal line segment
steepSlope = dYa > dXa
if steepSlope:
slope = dX.astype(np.float32)/dY.astype(np.float32)
if negY:
itbuffer[:,1] = np.arange(P1Y-1,P1Y-dYa-1,-1)
else:
itbuffer[:,1] = np.arange(P1Y+1,P1Y+dYa+1)
itbuffer[:,0] = (slope*(itbuffer[:,1]-P1Y)).astype(np.int) + P1X
else:
slope = dY.astype(np.float32)/dX.astype(np.float32)
if negX:
itbuffer[:,0] = np.arange(P1X-1,P1X-dXa-1,-1)
else:
itbuffer[:,0] = np.arange(P1X+1,P1X+dXa+1)
itbuffer[:,1] = (slope*(itbuffer[:,0]-P1X)).astype(np.int) + P1Y
#Remove points outside of image
colX = itbuffer[:,0]
colY = itbuffer[:,1]
itbuffer = itbuffer[(colX >= 0) & (colY >=0) & (colX<imageW) & (colY<imageH)]
#Get intensities from img ndarray
itbuffer[:,2] = img[itbuffer[:,1].astype(np.uint),itbuffer[:,0].astype(np.uint)]
return itbuffer
</code></pre> |
61,927,814 | How to disable open browser in CRA? | <p>I've created a React app using <code>create-react-app</code> but whenever I start the dev server (using <code>npm start</code>), it opens up my browser. I want to make it so that it doesn't open my browser whenever I start my dev server.</p>
<p>How can I accomplish this?</p> | 61,928,659 | 5 | 0 | null | 2020-05-21 05:23:00.987 UTC | 8 | 2022-08-08 15:58:31.65 UTC | 2020-05-21 05:31:38.953 UTC | null | 5,069,505 | null | 13,579,293 | null | 1 | 111 | reactjs|configuration|create-react-app | 32,899 | <p>Create <code>.env</code> file in the root directory where your <code>package.json</code> file resides. And add the following:</p>
<pre><code>BROWSER=none
</code></pre>
<p>Now run <code>npm start</code>.</p> |
35,439,611 | Could not open Hibernate Session for transaction, JavaConfig | <p>Can't find error ((</p>
<p>Spring MVC + Hibernate, JavaConfig</p>
<p>WebAppConfig:</p>
<pre><code>package com.sprhib.init;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
@Configuration
@ComponentScan("com.sprhib")
@EnableWebMvc
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class WebAppConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
@Resource
private Environment env;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
</code></pre>
<p>User</p>
<pre><code>package com.sprhib.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
private Boolean isAdmin;
private Timestamp createdDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getAdmin() {
return isAdmin;
}
public void setAdmin(Boolean admin) {
isAdmin = admin;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
}
package com.sprhib.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sprhib.model.User;
@Repository
public class UserDAOImpl implements UserDAO {
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addUser(User user) {
getCurrentSession().save(user);
}
public void updateUser(User user) {
User userUpdate = getUser(user.getId());
userUpdate.setName(user.getName());
userUpdate.setAge(user.getAge());
userUpdate.setAdmin(user.getAdmin());
userUpdate.setCreatedDate(user.getCreatedDate());
getCurrentSession().update(userUpdate);
}
public User getUser(int id) {
return (User)getCurrentSession().get(User.class,id);
}
public void deleteUser(int id) {
User user = getUser(id);
if (user!=null)
getCurrentSession().delete(user);
}
public List<User> getUsers() {
System.out.println("zzz");
return getCurrentSession().createQuery("FROM User").list();
}
}
</code></pre>
<p>UserDAOImpl:</p>
<pre><code>package com.sprhib.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sprhib.model.User;
@Repository
public class UserDAOImpl implements UserDAO {
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public void addUser(User user) {
getCurrentSession().save(user);
}
public void updateUser(User user) {
User userUpdate = getUser(user.getId());
userUpdate.setName(user.getName());
userUpdate.setAge(user.getAge());
userUpdate.setAdmin(user.getAdmin());
userUpdate.setCreatedDate(user.getCreatedDate());
getCurrentSession().update(userUpdate);
}
public User getUser(int id) {
return (User)getCurrentSession().get(User.class,id);
}
public void deleteUser(int id) {
User user = getUser(id);
if (user!=null)
getCurrentSession().delete(user);
}
public List<User> getUsers() {
return getCurrentSession().createQuery("FROM User").list();
}
}
</code></pre>
<p>UserController:</p>
<pre><code>package com.sprhib.controller;
import java.util.List;
import com.sprhib.model.User;
import com.sprhib.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value="/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value="/add", method=RequestMethod.GET)
public ModelAndView addUserPage()
{
ModelAndView modelAndView = new ModelAndView("add-user-form");
modelAndView.addObject("user",new User());
return modelAndView;
}
@RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView addingUser(@ModelAttribute User user) {
ModelAndView modelAndView = new ModelAndView("home");
userService.addUser(user);
String message = "User was successfully added.";
modelAndView.addObject("message", message);
return modelAndView;
}
@RequestMapping(value="/list")
public ModelAndView listOfUsers() {
ModelAndView modelAndView = new ModelAndView("list-of-users");
List<User> users = userService.getUsers();
modelAndView.addObject("users", users);
return modelAndView;
}
@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
public ModelAndView editUserPage(@PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("edit-user-form");
User user = userService.getUser(id);
modelAndView.addObject("user",user);
return modelAndView;
}
@RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
public ModelAndView edditingUser(@ModelAttribute User user, @PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("home");
userService.updateUser(user);
String message = "User was successfully updated.";
modelAndView.addObject("message", message);
return modelAndView;
}
@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ModelAndView deleteUser(@PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("home");
userService.deleteUser(id);
String message = "User was successfully deleted.";
modelAndView.addObject("message", message);
return modelAndView;
}
}
</code></pre>
<p>application.properties:</p>
<pre><code>#DB properties:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/test
db.username=root
db.password=root
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=com.sprhib.model
</code></pre>
<p>When i try to get users in a browser:</p>
<blockquote>
<p>HTTP Status 500 - Request processing failed; nested exception is
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext</p>
<p>type Exception report</p>
<p>message Request processing failed; nested exception is
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext</p>
<p>description The server encountered an internal error that prevented it
from fulfilling this request.</p>
<p>exception</p>
<p>org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:977)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:856)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:841)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)</p>
<p>root cause</p>
<p>org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:544)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy34.getUsers(Unknown Source)
com.sprhib.controller.UserController.listOfUsers(UserController.java:44)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:856)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:841)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)</p>
<p>root cause</p>
<p>java.lang.NoClassDefFoundError:
org/hibernate/engine/transaction/spi/TransactionContext
org.springframework.orm.hibernate4.HibernateTransactionManager.isSameConnectionForEntireSession(HibernateTransactionManager.java:711)
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:445)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy34.getUsers(Unknown Source)
com.sprhib.controller.UserController.listOfUsers(UserController.java:44)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:856)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:841)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)</p>
<p>root cause</p>
<p>java.lang.ClassNotFoundException:
org.hibernate.engine.transaction.spi.TransactionContext
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1308)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1142)
org.springframework.orm.hibernate4.HibernateTransactionManager.isSameConnectionForEntireSession(HibernateTransactionManager.java:711)
org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:445)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:463)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy34.getUsers(Unknown Source)
com.sprhib.controller.UserController.listOfUsers(UserController.java:44)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:856)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:841)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)</p>
</blockquote>
<p>I'am traning to <a href="http://fruzenshtein.com/spring-mvc-hibernate-maven-crud/" rel="noreferrer">this</a> example...</p> | 35,440,128 | 1 | 1 | null | 2016-02-16 17:48:48.32 UTC | 1 | 2016-06-05 18:19:00.537 UTC | null | null | null | null | 5,935,651 | null | 1 | 9 | java|spring|hibernate|spring-mvc | 49,927 | <p>You use <code>org.springframework.orm.hibernate4.HibernateTransactionManager</code> for Hibernate 4. This class using <code>TransactionContext</code> from Hibernate 4. </p>
<p>Looks like you use Hibernate 5. Just change</p>
<pre><code>import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
</code></pre>
<p>to this </p>
<pre><code>import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
</code></pre>
<p>You need to use corresponding Spring libraries of course. For an example <a href="http://mvnrepository.com/artifact/org.springframework/spring-orm/4.2.4.RELEASE" rel="noreferrer">4.2.4.RELEASE</a>. </p> |
18,818,381 | Xcode 5: Code signing entitlement errors | <p>I've build a new application which is going to support IOS 7. I got the new XCode 5 GM and tried to sign my apps using my fresh provisioning profile and distribution certificate, but i'm having trouble with distribution. I constantly get the following error:</p>
<blockquote>
<p>"Invalid Code Signing Entitlements. The entitlements in your app
bundle signature do not match the ones that are contained in the
provisioning profile. According to the provisioning profile, the
bundle contains a key value that is not allowed:
'[XXXX.com.sample.company ]' for the key 'keychain-access-groups".</p>
</blockquote>
<p>Also the same error for a key value called <code>application-identifier</code>.</p>
<p>Screenshot of the errror: </p>
<p><img src="https://i.stack.imgur.com/wrSZf.png" alt="enter image description here"></p> | 18,818,382 | 21 | 0 | null | 2013-09-15 23:05:56.77 UTC | 25 | 2016-06-16 06:41:40.653 UTC | null | null | null | null | 1,845,040 | null | 1 | 150 | objective-c|xcode|macos|code-signing|xcode5 | 79,821 | <p>The solution lies in the new option in Xcode 5 which says provisioning profile. Just set the project target's provisioning profile to the right one and it'll work.</p>
<p><img src="https://i.stack.imgur.com/2Hm5T.png" alt="enter image description here"></p> |
30,134,652 | AlamoFire Download in Background Session | <p>I am using Alamofire within a new app (A Download Manager Sample based on Alamofire)
I need some clarifications about downloading files using the background session.
I need to override SessionDelegate to get it works?
Or just <code>backgroundCompletionHandler</code>?</p>
<p>Typically what are the steps to handle downloads in background using Alamofire?
And how can I handle the case where my app is relauch, with downloads in flux.</p> | 30,269,642 | 3 | 1 | null | 2015-05-09 00:21:28.743 UTC | 21 | 2020-03-05 14:27:53.03 UTC | 2018-12-13 19:39:27.61 UTC | null | 5,236,226 | null | 2,327,367 | null | 1 | 43 | ios|swift|network-programming|alamofire | 29,553 | <h3>Update</h3>
<p>Based on <a href="https://medium.com/swift-programming/learn-nsurlsession-using-swift-part-2-background-download-863426842e21" rel="noreferrer">this amazing tutorial</a>, I have put together an example project available on <a href="https://github.com/jozsef-vesza/swift-lessons/tree/master/Networking" rel="noreferrer">GitHub</a>. It has an example for background session management.</p>
<p>According to Apple's <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW26" rel="noreferrer">URL Loading System Programming Guide</a>:</p>
<blockquote>
<p>In both iOS and OS X, when the user relaunches your app, your app
should immediately create background configuration objects with the
same identifiers as any sessions that had outstanding tasks when your
app was last running, then create a session for each of those
configuration objects. These new sessions are similarly automatically
reassociated with ongoing background activity.</p>
</blockquote>
<p>So apparently by using the appropriate background session configuration instances, your downloads will never be "in flux".</p>
<p>I have also found <a href="https://stackoverflow.com/a/21359684/1832052">this answer</a> really helpful.</p>
<h3>Original answer</h3>
<p>From Alamofire's <a href="https://github.com/Alamofire/Alamofire#creating-a-manager-with-background-configuration" rel="noreferrer">GitHub page</a>: </p>
<blockquote>
<p>Applications can create managers for background and ephemeral
sessions, as well as new managers that customize the default session
configuration, such as for default headers (HTTPAdditionalHeaders) or
timeout interval (timeoutIntervalForRequest).</p>
</blockquote>
<p>By default, top level methods use a shared <code>Manager</code> instance with default session configuration. You can however create a manager with background session configuration like so:</p>
<pre><code>let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.example.app.background")
let manager = Alamofire.Manager(configuration: configuration)
</code></pre>
<p>You can then make requests using this <code>Manager</code> instance. </p>
<pre><code>manager.startRequestsImmediately = true
let request = NSURLRequest(URL: NSURL(string: "your.url.here")!)
manager.request(request)
</code></pre>
<p>By looking at its implementation, it also has a property called <code>backgroundCompletionHandler</code>, so you can add a completion block:</p>
<pre><code>manager.backgroundCompletionHandler = {
// do something when the request has finished
}
</code></pre> |
30,083,719 | Logstash optional fields in logfile | <p>I'm trying to parse a logfile using grok</p>
<p>Each line of the logfile has fields separated by commas:</p>
<pre><code>13,home,ABC,Get,,Private, Public,1.2.3 ecc...
</code></pre>
<p>I'm using match like this:
<code>match => [ "message", "%{NUMBER:requestId},%{WORD:ServerHost},%{WORD:Service},</code>...</p>
<p>My question is: Can I allow optional field?
At times some of the fileds might be empty <code>,,</code></p>
<p>Is there a pattern that matches a string like this <code>2.3.5</code> ?
( a kind of version number )</p> | 30,085,151 | 1 | 1 | null | 2015-05-06 17:30:52.373 UTC | 7 | 2019-04-17 07:14:30.04 UTC | null | null | null | null | 1,483,090 | null | 1 | 31 | regex|logstash|logstash-grok | 40,385 | <p>At it's base, grok is based on regular expressions, so you can surround a pattern with <code>()?</code> to make it optional -- for example <code>(%{NUMBER:requestId})?,</code></p>
<p>If there isn't a grok pattern that suits your needs, you can always create a named extraction like this: <code>(?<version>[\d\.]+)</code> which would extract into version, a string that has any number of digits and dots in it.</p> |
51,579,546 | How to format DateTime in Flutter | <p>I am trying to display the current <code>DateTime</code> in a <code>Text</code> widget after tapping on a button. The following works, but I'd like to change the format.</p>
<p><strong>Current approach</strong></p>
<pre><code>DateTime now = DateTime.now();
currentTime = new DateTime(now.year, now.month, now.day, now.hour, now.minute);
Text('$currentTime'),
</code></pre>
<p><strong>Result</strong></p>
<p><code>YYYY-MM-JJ HH-MM:00.000</code></p>
<p><strong>Question</strong></p>
<p>How can I remove the <code>:00.000</code> part?</p> | 51,579,740 | 16 | 0 | null | 2018-07-29 10:54:30.24 UTC | 41 | 2022-08-05 22:29:21.03 UTC | 2021-12-04 19:24:21.753 UTC | null | 4,853,133 | null | 9,611,719 | null | 1 | 219 | android|ios|flutter|datetime|dart | 305,900 | <p>You can use <code>DateFormat</code> from <strong><a href="https://pub.dev/packages/intl" rel="noreferrer">intl</a></strong> package.</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:intl/intl.dart';
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
</code></pre> |
8,973,037 | Handling onchange event in HTML.DropDownList Razor MVC | <p>I'm handling an <code>onchange</code> event with a selected value by simple HTML like this: </p>
<pre><code><select onchange="location = this.value;">
<option value="/product/categoryByPage?PageSize=15" selected="selected">15</option>
<option value="/product/categoryByPage?PageSize=30" selected="selected">30</option>
<option value="/product/categoryByPage?PageSize=50" selected="selected">50</option>
</select>
</code></pre>
<p>Doing it like this:</p>
<pre><code>List<SelectListItem> items = new List<SelectListItem>();
string[] itemArray = {"15","30","50"};
for (int i = 0; i < itemArray.Count(); i++)
{
items.Add(new SelectListItem
{
Text = itemArray[i],
Value = "/product/categoryByPage?pageSize=" + itemArray[i]
});
}
ViewBag.CategoryID = items;
@Html.DropDownList("CategoryID")
</code></pre>
<p>How can I handle <code>onchange</code> with <code>@Html.DropDownList()</code></p> | 8,973,082 | 2 | 0 | null | 2012-01-23 14:17:49.927 UTC | 5 | 2016-03-17 15:24:55.04 UTC | 2013-05-17 15:08:45.227 UTC | null | 271,200 | null | 1,157,903 | null | 1 | 39 | asp.net-mvc|asp.net-mvc-3|razor|html-helper | 137,528 | <h3>Description</h3>
<p>You can use another overload of the <code>DropDownList</code> method. Pick the one you need and pass in
a object with your html attributes. </p>
<h3>Sample</h3>
<pre><code>@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
</code></pre>
<h3>More Information</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlist.aspx" rel="noreferrer">MSDN - SelectExtensions.DropDownList Method</a></li>
</ul> |
30,494,520 | Alternatives to nested ifelse statements in R | <p>Suppose we have the following data. The rows represent a country and the columns (<code>in05:in09</code>) indicate whether that country was present in a database of interest in the given year (<code>2005:2009</code>).</p>
<pre><code>id <- c("a", "b", "c", "d")
in05 <- c(1, 0, 0, 1)
in06 <- c(0, 0, 0, 1)
in07 <- c(1, 1, 0, 1)
in08 <- c(0, 1, 1, 1)
in09 <- c(0, 0, 0, 1)
df <- data.frame(id, in05, in06, in07, in08, in09)
</code></pre>
<p>I want to create a variable <code>firstyear</code> which indicates the first year in which the country was present in the database. Right now I do the following:</p>
<pre><code>df$firstyear <- ifelse(df$in05==1,2005,
ifelse(df$in06==1,2006,
ifelse(df$in07==1, 2007,
ifelse(df$in08==1, 2008,
ifelse(df$in09==1, 2009,
0)))))
</code></pre>
<p>The above code is already not very nice, and my dataset contains many more years. Is there an alternative, using <code>*apply</code> functions, loops or something else, to create this <code>firstyear</code> variable? </p> | 30,494,641 | 7 | 0 | null | 2015-05-27 22:58:27.88 UTC | 11 | 2018-01-21 06:46:51.417 UTC | 2016-02-29 14:33:50.687 UTC | null | 3,576,984 | null | 4,946,409 | null | 1 | 28 | r|loops|if-statement|nested-loops | 10,466 | <p>You can vectorize using <code>max.col</code></p>
<pre><code>indx <- names(df)[max.col(df[-1], ties.method = "first") + 1L]
df$firstyear <- as.numeric(sub("in", "20", indx))
df
# id in05 in06 in07 in08 in09 firstyear
# 1 a 1 0 1 0 0 2005
# 2 b 0 0 1 1 0 2007
# 3 c 0 0 0 1 0 2008
# 4 d 1 1 1 1 1 2005
</code></pre> |
30,483,977 | Python - Get Yesterday's date as a string in YYYY-MM-DD format | <p>As an input to an API request I need to get yesterday's date as a string in the format <code>YYYY-MM-DD</code>. I have a working version which is:</p>
<pre><code>yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
</code></pre>
<p>There must be a more elegant way to do this, interested for educational purposes as much as anything else!</p> | 30,484,112 | 5 | 1 | null | 2015-05-27 13:29:57.027 UTC | 20 | 2022-05-14 11:37:06.063 UTC | 2016-11-18 08:15:17.633 UTC | null | 2,867,928 | null | 1,865,336 | null | 1 | 105 | python|python-2.7|python-3.x|date|datetime | 166,438 | <p>You Just need to subtract one day from today's date. In Python <code>datetime.timedelta</code> object lets you create specific spans of time as a <a href="https://docs.python.org/3.5/library/datetime.html#datetime.timedelta" rel="noreferrer"><code>timedelta</code> object</a>.</p>
<p><code>datetime.timedelta(1)</code> gives you the duration of "one day" and is subtractable from a <code>datetime</code> object. After you subtracted the objects you can use <a href="https://docs.python.org/3.5/library/datetime.html#datetime.datetime.strptime" rel="noreferrer"><code>datetime.strftime</code></a> in order to convert the result --which is a date object-- to string format based on your <a href="https://docs.python.org/3.5/library/datetime.html#strftime-and-strptime-behavior" rel="noreferrer">format of choice</a>:</p>
<pre><code>>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
</code></pre>
<p>Note that instead of calling the <code>datetime.strftime</code> function, you can also directly use <code>strftime</code> method of <code>datetime</code> objects:</p>
<pre><code>>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
</code></pre>
<p>As a function:</p>
<pre><code>from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
</code></pre>
<p>example:</p>
<pre><code>In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
</code></pre> |
1,285,034 | Custom SQL query without Corresponding Table | <p>I have a SQL query that isn't table-specific and I don't know how to handle it with Ruby On Rails.</p>
<p>Here my SQL query (you don't need to understand it):</p>
<pre>SELECT type, actor_id, events.created_at, photo_id, photos.user_id FROM
(SELECT 'comment' AS type, user_id AS actor_id, created_at, photo_id FROM comments
UNION
SELECT 'classification' AS type, user_id AS actor_id, created_at, photo_id FROM classifications)
AS events
INNER JOIN photos ON photo_id = photos.id
WHERE user_id = #{@user.id}
ORDER BY created_at DESC
LIMIT 9</pre>
<p>I tried to create a model and use a find_by_sql:</p>
<pre><code>
class RecentActivity ActiveRecord::Base
attr_accessor :type, :actor_id, :created_at, :photo_id, :user_id
end
</code></pre>
<p>I get:</p>
<pre>Mysql::Error: Table 'mysite_development.recent_activities' doesn't exist: SHOW FIELDS FROM `recent_activities`</pre>
<p>How can I avoid this message? Is there any alternative solution?</p> | 1,285,117 | 3 | 2 | null | 2009-08-16 18:51:04.767 UTC | 15 | 2012-08-01 05:47:09.88 UTC | null | null | null | null | 51,387 | null | 1 | 17 | ruby-on-rails|activerecord | 11,781 | <p>You can grab a db connection directly from ActiveRecord::Base, but it's not as useful as extending AR::Base, because helpful methods like sanitize_sql are protected.</p>
<pre><code>class ComplexQueries < ActiveRecord::Base
def self.my_query
# Notice how you can, and should, still sanitize params here.
self.connection.execute(sanitize_sql(["select * from foo limit ?", 10]))
end
end
results = ComplexQueries.my_query
results.each_hash{|h| puts h.inspect}
</code></pre> |
1,203,725 | Three Way Merge Algorithms for Text | <p>So I've been working on a wiki type site. What I'm trying to decide on is what the best algorithm for merging an article that is simultaneously being edited by two users. </p>
<p>So far I'm considering using Wikipedia's method of merging the documents if two unrelated areas are edited, but throwing away the older change if two commits conflict.</p>
<p>My question is as follows: If I have the original article, and two changes to it, what are the best algorithms to merge them and then deal with conflicts as they arise? </p> | 1,208,641 | 3 | 0 | null | 2009-07-29 23:54:06.107 UTC | 21 | 2013-08-12 20:13:22.613 UTC | null | null | null | null | 1,063 | null | 1 | 28 | algorithm|merge|diff|revision | 14,063 | <p>Bill Ritcher's excellent paper "<a href="http://www.guiffy.com/SureMergeWP.html" rel="noreferrer">A Trustworthy 3-Way Merge</a>" talks about some of the common gotchas with three way merging and clever solutions to them that commercial SCM packages have used.</p>
<p>The 3-way merge will automatically apply all the changes (which are not overlapping) from each version. The trick is to automatically handle as many almost overlapping regions as possible.</p> |
708,649 | Python comments: # vs. strings | <p>Regarding the "standard" way to put comments inside Python source code:</p>
<pre><code>def func():
"Func doc"
... <code>
'TODO: fix this'
#badFunc()
... <more code>
def func():
"Func doc"
... <code>
#TODO: fix this
#badFunc()
... <more code>
</code></pre>
<p>I prefer to write general comments as strings instead of prefixing #'s.
The official Python style guide doesn't mention using strings as comments (If I didn't miss it while reading it).</p>
<p>I like it that way mainly because I think the <code>#</code> character looks ugly with comment blocks. As far as I know these strings don't do anything.</p>
<p>Are there disadvantages in doing this?</p> | 708,674 | 3 | 0 | null | 2009-04-02 07:24:59.553 UTC | 8 | 2020-02-26 12:20:43.22 UTC | 2017-01-08 15:38:13.047 UTC | null | 63,550 | bigmonachus | 63,119 | null | 1 | 29 | python | 9,112 | <p>Don't misuse strings (no-op statements) as comments. Docstrings, e.g. the first string in a module, class or function, are special and definitely recommended.</p>
<p>Note that <strong>docstrings are documentation</strong>, and documentation and comments are two different things!</p>
<ul>
<li>Documentation is important to understand <em>what</em> the code does.</li>
<li>Comments explain <em>how</em> the code does it.</li>
</ul>
<p>Documentation is read by people who <em>use</em> your code, comments by people who want to <em>understand</em> your code, e.g. to maintain it.</p>
<p>Using strings for commentation has the following (potential) disadvantages:</p>
<ul>
<li>It confuses people who don't know that the string does nothing.</li>
<li>Comments and string literals are highlighted differently in code editors, so your style may make your code harder to read.</li>
<li>It might affect performance and/or memory usage (if the strings are not removed during bytecode compilation, removing comments is done on the scanner level so it's definitively cheaper)</li>
</ul>
<p>Most important for Python programmers: It is not pythonic:</p>
<blockquote>
<p>There should be one—and preferably only one—obvious way to do it.</p>
</blockquote>
<p>Stick to the standards, use comments.</p> |
42,045,362 | Change contrast of image in PIL | <p>I have a program that's supposed to change the contrast, but I feel like it's not really changing the contrast.It changes some areas to red whereas I don't want it to. If you could tell me how to remove them, thank you.
Here is the code:</p>
<pre><code>from PIL import Image
def change_contrast(img, level):
img = Image.open("C:\\Users\\omar\\Desktop\\Site\\Images\\obama.png")
img.load()
factor = (259 * (level+255)) / (255 * (259-level))
for x in range(img.size[0]):
for y in range(img.size[1]):
color = img.getpixel((x, y))
new_color = tuple(int(factor * (c-128) + 128) for c in color)
img.putpixel((x, y), new_color)
return img
result = change_contrast('C:\\Users\\omar\\Desktop\\Site\\Images\\test_image1.jpg', 100)
result.save('C:\\Users\\omar\\Desktop\\Site\\Images\\test_image1_output.jpg')
print('done')
</code></pre>
<p>And here is the image and its result:</p>
<p><a href="https://i.stack.imgur.com/j5UID.png" rel="noreferrer"><img src="https://i.stack.imgur.com/j5UID.png" alt="obama.png"></a>
<a href="https://i.stack.imgur.com/hONkZ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/hONkZ.jpg" alt="obama modified"></a></p>
<p>If this is the actual contrast method, feel free to tell me</p> | 42,054,155 | 2 | 2 | null | 2017-02-04 20:40:33.85 UTC | 5 | 2018-11-27 14:29:09.837 UTC | null | null | null | null | 7,453,178 | null | 1 | 16 | python|python-3.x|python-imaging-library | 37,995 | <p>I couldn't reproduce your bug. On my platform (debian) only the Pillow fork is available, so if you are using the older PIL package, that might be the cause.</p>
<p>In any case, there's a built in method <a href="http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.point" rel="noreferrer"><code>Image.point()</code></a> for doing this kind of operation. It will map over each pixel in each channel, which should be faster than doing three nested loops in python.</p>
<pre><code>def change_contrast(img, level):
factor = (259 * (level + 255)) / (255 * (259 - level))
def contrast(c):
return 128 + factor * (c - 128)
return img.point(contrast)
change_contrast(Image.open('barry.png'), 100)
</code></pre>
<p><img src="https://i.stack.imgur.com/qQR6a.png" alt="output"></p>
<p>Your output looks like you have a overflow in a single channel (red). I don't see any reason why that would happen. But if your <code>level</code> is higher than 259, the output is inverted. Something like that is probably the cause of the initial bug.</p>
<pre><code>def change_contrast_multi(img, steps):
width, height = img.size
canvas = Image.new('RGB', (width * len(steps), height))
for n, level in enumerate(steps):
img_filtered = change_contrast(img, level)
canvas.paste(img_filtered, (width * n, 0))
return canvas
change_contrast_multi(Image.open('barry.png'), [-100, 0, 100, 200, 300])
</code></pre>
<p><img src="https://i.stack.imgur.com/jPpa3.png" alt="another output"></p>
<p>A possible fix is to make sure the contrast filter only return values within the range [0-255], since the bug seems be caused by negative values overflowing somehow.</p>
<pre><code>def change_contrast(img, level):
factor = (259 * (level + 255)) / (255 * (259 - level))
def contrast(c):
value = 128 + factor * (c - 128)
return max(0, min(255, value))
return img.point(contrast)
</code></pre> |
19,453,338 | Opening pdf file | <p>I wanna open pdf file from python console, I can do it with <code>os.system(filename)</code>, it will open in adobe reader, but the problem is that <code>os.system</code> also opens a command prompt, is there another way that won't open command prompt?</p> | 19,453,630 | 4 | 0 | null | 2013-10-18 15:27:21.48 UTC | 6 | 2022-09-13 07:37:48.417 UTC | 2020-02-12 11:37:55.607 UTC | null | 5,922,435 | null | 2,208,597 | null | 1 | 28 | python | 94,270 | <p>Try:</p>
<pre><code>import subprocess
subprocess.Popen([file],shell=True)
</code></pre> |
19,547,031 | How to get the 1st value before delimiter in sql server | <p>In one of the column i am getting 2 values with a delimiter between it
How to extract both the values </p>
<p>I have some thing like this Column <code>TRN02</code> is <code>115679-5757</code></p>
<p>I need to take values before delimiter and after delimter into 2 separate columns again.</p>
<p>Can some one help me on this</p> | 19,547,129 | 4 | 0 | null | 2013-10-23 16:18:23.923 UTC | 5 | 2022-04-03 17:51:38.13 UTC | 2018-10-16 12:30:19.003 UTC | null | 680,068 | null | 2,731,160 | null | 1 | 21 | sql-server | 81,502 | <p>You can use <code>SUBSTRING</code> to do this:</p>
<pre><code>SELECT
SUBSTRING(TRN02, 0, CHARINDEX('-', TRN02)) AS [First]
SUBSTRING(TRN02, CHARINDEX('-', TRN02) + 1, LEN(TRN02)) AS [Second]
FROM TABLE
</code></pre> |
3,043,154 | Combining multiple condition in single case statement in Sql Server | <p>According to the following description I have to frame a <code>CASE...END</code> statement in SQL server , help me to frame a complex <code>CASE...END</code> statement to fulfill the following condition.</p>
<pre><code>if PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null then display display 'Favor'
if PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL is equal to No, display 'Error'
if PAT_ENTRY.EL is Yes and DS.DES is equal to null or OFF, display 'Active'
if DS.DES is equal to N, display 'Early Term'
if DS.DES is equal to Y, display 'Complete'
</code></pre>
<p>Thanks in advance.</p> | 3,043,185 | 2 | 0 | null | 2010-06-15 07:06:48.533 UTC | 1 | 2021-03-23 06:54:44.59 UTC | 2013-10-03 16:35:29.297 UTC | null | 866,618 | null | 366,979 | null | 1 | 13 | sql-server|sql-server-2005 | 135,344 | <p>You can put the condition after the <code>WHEN</code> clause, like so:</p>
<pre><code>SELECT
CASE
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
WHEN DS.DES = 'N' THEN 'Early Term'
WHEN DS.DES = 'Y' THEN 'Complete'
END
FROM
....
</code></pre>
<p>Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...</p> |
2,803,132 | .NET 4.0 Fails When sending emails with attachments larger than 3MB | <p>I recently had an issue after upgrading my .net framework to 4.0 from 3.5:</p>
<blockquote>
<p>System.Net.Mail.SmtpException: Failure sending mail. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.Net.Base64Stream.EncodeBytes(Byte[] buffer, Int32 offset, Int32 count, Boolean dontDeferFinalBytes, Boolean shouldAppendSpaceToCRLF) at System.Net.Base64Stream.Write(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Mime.MimePart.Send(BaseWriter writer) at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer) at System.Net.Mail.Message.Send(BaseWriter writer, Boolean sendEnvelope) at System.Net.Mail.SmtpClient.Send(MailMessage message) --- End of inner exception stack trace ---</p>
</blockquote>
<p>I read this connect bug listing here: <a href="http://connect.microsoft.com/VisualStudio/feedback/details/544562/cannot-send-e-mails-with-large-attachments-system-net-mail-smtpclient-system-net-mail-mailmessage" rel="noreferrer">http://connect.microsoft.com/VisualStudio/feedback/details/544562/cannot-send-e-mails-with-large-attachments-system-net-mail-smtpclient-system-net-mail-mailmessage</a>.</p>
<p>If anyone cares about this issue, please vote for it on Connect, so it will be fixed sooner.</p> | 3,671,215 | 2 | 6 | null | 2010-05-10 13:57:51.127 UTC | 8 | 2012-08-08 18:44:21.173 UTC | 2010-05-10 14:01:34.927 UTC | null | 76,337 | null | 41,543 | null | 1 | 28 | .net|.net-4.0|smtpclient | 13,936 | <p>The bug has been patched: <a href="https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=30226" rel="noreferrer">https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=30226</a></p>
<blockquote>
<p><strong>Title</strong>: KB2183292</p>
<p><strong>Release Date</strong>: 7/21/2010</p>
<p><strong>Size</strong>: 8.58 MB</p>
<p><strong>Version</strong>: Hotfix</p>
<p><strong>Category</strong>: Build</p>
<p><strong>Description</strong> QFE: System.Net.Mail - SmtpClient class throws exceptions if file attachment is > over 3MB</p>
</blockquote> |
3,200,526 | What is a segmentation fault on Linux? | <p>In Linux:</p>
<p>What is a segmentation fault? I know it crashes programs, but is that some sort of memory leak problem, or something completely unrelated? Also, how do you deal with these?
Is this typically a problem with the computer set-up, or within the application itself?</p>
<p>Also, does this happen in other OS's as well?</p> | 3,200,536 | 2 | 4 | null | 2010-07-08 03:39:28.037 UTC | 10 | 2016-06-01 02:40:01.967 UTC | 2016-06-01 02:40:01.967 UTC | null | 15,168 | null | 362,011 | null | 1 | 35 | segmentation-fault | 76,313 | <p>A segmentation fault is when your program attempts to access memory it has either not been assigned by the operating system, or is otherwise not allowed to access.</p>
<p>"segmentation" is the concept of each process on your computer having its own distinct <em>virtual</em> address space. Thus, when Process A reads memory location 0x877, it reads information residing at a <em>different</em> physical location in RAM than when Process B reads its own 0x877.</p>
<p>All modern operating systems support and use segmentation, and so all can produce a segmentation fault.</p>
<p>To deal with a segmentation fault, fix the code causing it. It is generally indicative of poor programming, especially boundary-condition errors, incorrect pointer manipulation, or invalid assumptions about shared libraries. Sometimes segfaults, like any problem, may be caused by faulty hardware, but this is usually not the case.</p> |
39,514,915 | Hitting Tab in Visual Studio selects block instead of adding indentation | <p>I am using Visual Studio 2015 and ReSharper 2016.2 and I have this strange behavior, that I probably activated (accidentally). When having the cursor in a line before the first word, hitting the Tab-key indents the line correctly:</p>
<p><a href="https://i.stack.imgur.com/PxgwF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PxgwF.png" alt="enter image description here"></a></p>
<p>When the cursor is inside of any word inside the line, hitting the Tab-key selects the word or block.</p>
<p><a href="https://i.stack.imgur.com/vR0Xe.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vR0Xe.png" alt="enter image description here"></a></p>
<p>But the desired behavior would be to indent at the cursor (e.g. split a word into two words, if the cursor was inside of the word Stream after the letter r):</p>
<p><a href="https://i.stack.imgur.com/lnhM3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lnhM3.png" alt="enter image description here"></a></p>
<p>Does anyone know how this 'feature' is called? Does it come from ReSharper? Where can it be enabled or disabled?</p> | 39,515,014 | 3 | 0 | null | 2016-09-15 15:27:25.13 UTC | 6 | 2020-04-14 12:53:41.633 UTC | null | null | null | null | 448,357 | null | 1 | 49 | visual-studio-2015|resharper|indentation|keyboard-events | 4,981 | <p>Go to Resharper -> Options, in the left treeview select Editor Behavior and uncheck the last option <strong>Use Tab/Shift Tab keys for structural navigation</strong>.</p>
<p><a href="https://i.stack.imgur.com/4ZR7g.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4ZR7g.png" alt="enter image description here"></a></p>
<blockquote>
<p>Update for Resharper 2016.3.1. </p>
</blockquote>
<p><strong>Thanks to @Jordan for pointing this out!</strong></p>
<p><a href="https://i.stack.imgur.com/E6NJy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/E6NJy.png" alt="Updated for Resharper 2016.3.1"></a></p> |
23,151,246 | iterrows pandas get next rows value | <p>I have a df in pandas</p>
<pre><code>import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
</code></pre>
<p>I want to iterate over rows in df. For each row i want row<code>s value and next row</code>s value
Something like(it does not work):</p>
<pre><code>for i, row in df.iterrows():
print row['value']
i1, row1 = next(df.iterrows())
print row1['value']
</code></pre>
<p>As a result I want </p>
<pre><code>'AA'
'BB'
'BB'
'CC'
'CC'
*Wrong index error here
</code></pre>
<p>At this point i have mess way to solve this</p>
<pre><code>for i in range(0, df.shape[0])
print df.irow(i)['value']
print df.irow(i+1)['value']
</code></pre>
<p>Is there more efficient way to solve this issue? </p> | 23,151,722 | 5 | 0 | null | 2014-04-18 09:26:44.67 UTC | 18 | 2019-05-30 11:35:39.807 UTC | null | null | null | null | 2,968,805 | null | 1 | 40 | python|pandas|next | 124,941 | <p>Firstly, your "messy way" is ok, there's nothing wrong with using indices into the dataframe, and this will not be too slow. iterrows() itself isn't terribly fast.</p>
<p>A version of your first idea that would work would be:</p>
<pre><code>row_iterator = df.iterrows()
_, last = row_iterator.next() # take first item from row_iterator
for i, row in row_iterator:
print(row['value'])
print(last['value'])
last = row
</code></pre>
<p>The second method could do something similar, to save one index into the dataframe:</p>
<pre><code>last = df.irow(0)
for i in range(1, df.shape[0]):
print(last)
print(df.irow(i))
last = df.irow(i)
</code></pre>
<p>When speed is critical you can always try both and time the code.</p> |
29,965,362 | Setting JAVA_HOME and JRE_HOME path | <p>I have been allocated a Linux box in which has java available</p>
<pre><code># java -version
java version "1.7.0_09-icedtea"
OpenJDK Runtime Environment (rhel-2.3.4.1.el6_3-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)
# ls -l /usr/bin/java
lrwxrwxrwx. 1 root root 22 Feb 8 2013 /usr/bin/java -> /etc/alternatives/java
</code></pre>
<p>I am new to Java and not sure if JRE is installed in ths box but based upon search:</p>
<pre><code># rpm -q jre
package jre is not installed
# find / -iname java -print 2>/dev/null
/usr/lib/java
/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.9.x86_64/jre/bin/java
/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/jre/bin/java
/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre/bin/java
/usr/bin/java
/usr/share/java
/var/lib/alternatives/java
/etc/alternatives/java
/etc/java
/etc/pki/java
</code></pre>
<p>But</p>
<pre><code># echo $JAVA_HOME
# echo $JRE_HOME
</code></pre>
<p>So is JAVA is installed and JRE also - am I correct but what value I should set for JAVA_HOME and JRE_HOME env variables?</p> | 29,965,528 | 5 | 0 | null | 2015-04-30 10:31:20.12 UTC | 3 | 2019-06-07 06:47:00.36 UTC | null | null | null | null | 304,974 | null | 1 | 8 | java | 52,151 | <p>firstly try to get out of root user if possible than after that change below in your <code>~/.bash_profile</code></p>
<pre><code>JAVA_HOME=/usr/java/<Java version 7 jdk>; export JAVA_HOME // you can also try JAVA_HOME=/usr/java/jdk 7 version/bin/java
PATH=$JAVA_HOME/bin:$PATH; export PATH
</code></pre>
<p>save it and then</p>
<p>now <code>source ~/.bashrc</code></p>
<p>after that try </p>
<p><code>echo $JAVA_HOME</code> it will produce the expected result.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.