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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
39,934,635 | Python - While-Loop until list is empty | <p>I'm working with Django and I have a queryset of objects that has been converted to a list (<code>unpaid_sales</code>). I'm executing a process that iterates through this list and operates on each item until either the list is empty, or a given integer (<code>bucket</code>) reaches zero.</p>
<p>This is how I set it up:</p>
<pre><code>while unpaid_sales:
while bucket > 0:
unpaid_sale = unpaid_sales.pop(0)
...do stuff
</code></pre>
<p>In some cases, I am getting the following error: </p>
<blockquote>
<p>pop from empty list</p>
</blockquote>
<p>What's wrong with my logic?</p> | 39,934,685 | 3 | 3 | null | 2016-10-08 16:21:32.32 UTC | 3 | 2021-12-10 11:16:11.44 UTC | null | null | null | null | 4,928,578 | null | 1 | 8 | python | 75,786 | <p>Your end criteria must be formulated a little differently: run the loop while there are items and the <code>bucket</code> is positive. <code>or</code> is not the right operation here.</p>
<pre><code>while unpaid_sales and bucket > 0:
unpaid_sale = unpaid_sales.pop(0)
#do stuff
</code></pre> |
40,093,655 | How do I add attributes to existing HTML elements in TypeScript/JSX? | <p>Anyone know how to properly add/extend all native HTML element attributes with custom ones?</p>
<p>With <a href="http://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-interfaces" rel="noreferrer">the TypeScript documentation for merging interfaces</a>, I thought that I could just do this:</p>
<pre><code>interface HTMLElement {
block?: BEM.Block;
element?: BEM.Element;
modifiers?: BEM.Modifiers;
}
<div block="foo" />; // error
</code></pre>
<p>But I get the following Intellisense error in vscode 1.6.1 (latest):</p>
<blockquote>
<p>[ts] Property 'block' does not exist on type 'HTMLProps'.</p>
</blockquote>
<p>The <code>HTMLProps</code> to which they are referring is <code>React.HTMLProps<T></code> and the <code>div</code> element is declared to use it like so:</p>
<pre><code>namespace JSX {
interface IntrinsicElements {
div: React.HTMLProps<HTMLDivElement>
}
}
</code></pre>
<p>I tried redeclaring the <code>div</code>, but to no avail.</p>
<p>Related: <a href="https://github.com/Microsoft/TypeScript/issues/11684" rel="noreferrer">https://github.com/Microsoft/TypeScript/issues/11684</a></p>
<p><strong>Edit:</strong> Here's what ended up working for me:</p>
<pre><code>declare module 'react' {
interface HTMLAttributes<T> extends DOMAttributes<T> {
block?: string
element?: string
modifiers?: Modifiers // <-- custom interface
}
}
</code></pre> | 42,085,876 | 7 | 5 | null | 2016-10-17 18:55:08.267 UTC | 5 | 2022-06-23 03:44:28.167 UTC | 2017-09-22 05:07:22.15 UTC | null | 129,847 | null | 129,847 | null | 1 | 32 | typescript|jsx | 32,387 | <p>Looks like in older versions of type definition files (v0.14) the interfaces were simply declared under a global React namespace, so previously you could use the standard merging syntax.</p>
<pre><code>declare namespace React {
interface HTMLProps<T> extends HTMLAttributes, ClassAttributes<T> {
}
}
</code></pre>
<p>However the new version of d.ts file (v15.0) have declared everything inside a module. Since modules do not support merging, to the best of my knowledge the only option right now seems to be <code>module augmentation</code>:
<a href="https://www.typescriptlang.org/docs/handbook/declaration-merging.html" rel="noreferrer">https://www.typescriptlang.org/docs/handbook/declaration-merging.html</a></p>
<p>I did the following experiment and it worked for me:</p>
<pre><code>import * as React from 'react';
declare module 'react' {
interface HTMLProps<T> {
block?:string;
element?:string;
modifiers?:string;
}
}
export const Foo = () => {
return (
<div block="123" element="456">
</div>
)
};
</code></pre>
<p>Obviously this is quite tedious, you could put the augmentation code in another file as shown in the example from the typescript handbook, and import it:</p>
<pre><code>import * as React from 'react';
import './react_augmented';
</code></pre>
<p>But it's still quite dirty. So maybe it's best to address the issue with the contributors of the type definition file.</p> |
5,243,614 | 3D Carousel effect on the iPad | <p>I am trying to implement a 3D Carousel on the iPad, consisting of UIViews, an effect like what is shown over <a href="http://activeden.net/item/ultimate-3d-carousel-as2/full_screen_preview/49322" rel="noreferrer">here</a>.</p>
<p>I have gone through many similar questions on SO, but didn't find any staisfactory answers or no answers at all. </p>
<p>I am trying to achieve the effect through modifying the coverflow animation but it just doesn't give that slick effect.</p>
<p>Has anyone implemented this?(open for suggestions through quartz and openGL both)</p> | 5,264,614 | 2 | 0 | null | 2011-03-09 09:21:02.733 UTC | 23 | 2011-11-28 04:21:05.83 UTC | null | null | null | null | 286,116 | null | 1 | 13 | ipad|ios|opengl-es|quartz-graphics|ios-4.2 | 16,216 | <p>No need to dive into Quartz or OpenGL, assuming you don't mind foregoing the blur. The page you link to gets the perspective wrong (that's why the images in the background appear to move more quickly than those in the foreground), so the maths can be a little bit of smoke and mirrors.</p>
<p>There's full example code at the bottom. What I've done is used sine and cosine to move some views about. The basic theory behind it is that the point at angle a on the outside of a circle of radius r positioned on the origin is at (a*sin(r), a*cos(r)). That's a simple polar to Cartesian conversion, and should be clear from the trigonometry most countries teach to their teens; consider a right angled triangle with a hypotenuse of length a — what lengths are the other two sides?</p>
<p>What you can then do is reduce the radius of the y part to convert the circle into an ellipse. And an ellipse looks a bit like a circle that you're looking at from an angle. That ignores the possibility of perspective, but go with it.</p>
<p>I then fake perspective by making size proportional to the y coordinate. And I'm adjusting alpha in a way like the site you link to does blur, in the hope that's good enough for your application.</p>
<p>I effect position and scale by adjusting the affine transform of the UIViews I want to manipulate. I set the alpha directly on the UIView. I also adjust the zPosition on the view's layers (which is why QuartzCore is imported). The zPosition is like the CSS z position; it doesn't affect scale, only drawing order. So by setting it equal to the scale I've computed, it just says "draw larger things on top of smaller things", giving us the correct draw order.</p>
<p>Finger tracking is done by following one UITouch at a time through the touchesBegan/touchesMoved/touchesEnded cycle. If no finger is being tracked and some touches begin, one of them becomes the finger being tracked. If it moves then the carousel is rotated.</p>
<p>To create inertia, I have a little method that attaches to a timer keeps track of the current angle versus the angle one tick before. That difference is used like a velocity and simultaneously scaled downward to produce inertia.</p>
<p>The timer is started on finger up, since that's when the carousel should start spinning of its own volition. It is stopped either if the carousel comes to a standstill or a new finger is placed down.</p>
<p>Leaving you to fill in the blanks, my code is:</p>
<pre><code>#import <QuartzCore/QuartzCore.h>
@implementation testCarouselViewController
- (void)setCarouselAngle:(float)angle
{
// we want to step around the outside of a circle in
// linear steps; work out the distance from one step
// to the next
float angleToAdd = 360.0f / [carouselViews count];
// apply positions to all carousel views
for(UIView *view in carouselViews)
{
float angleInRadians = angle * M_PI / 180.0f;
// get a location based on the angle
float xPosition = (self.view.bounds.size.width * 0.5f) + 100.0f * sinf(angleInRadians);
float yPosition = (self.view.bounds.size.height * 0.5f) + 30.0f * cosf(angleInRadians);
// get a scale too; effectively we have:
//
// 0.75f the minimum scale
// 0.25f the amount by which the scale varies over half a circle
//
// so this will give scales between 0.75 and 1.25. Adjust to suit!
float scale = 0.75f + 0.25f * (cosf(angleInRadians) + 1.0);
// apply location and scale
view.transform = CGAffineTransformScale(CGAffineTransformMakeTranslation(xPosition, yPosition), scale, scale);
// tweak alpha using the same system as applied for scale, this time
// with 0.3 the minimum and a semicircle range of 0.5
view.alpha = 0.3f + 0.5f * (cosf(angleInRadians) + 1.0);
// setting the z position on the layer has the effect of setting the
// draw order, without having to reorder our list of subviews
view.layer.zPosition = scale;
// work out what the next angle is going to be
angle += angleToAdd;
}
}
- (void)animateAngle
{
// work out the difference between the current angle and
// the last one, and add that again but made a bit smaller.
// This gives us inertial scrolling.
float angleNow = currentAngle;
currentAngle += (currentAngle - lastAngle) * 0.97f;
lastAngle = angleNow;
// push the new angle into the carousel
[self setCarouselAngle:currentAngle];
// if the last angle and the current one are now
// really similar then cancel the animation timer
if(fabsf(lastAngle - currentAngle) < 0.001)
{
[animationTimer invalidate];
animationTimer = nil;
}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
// create views that are an 80x80 rect, centred on (0, 0)
CGRect frameForViews = CGRectMake(-40, -40, 80, 80);
// create six views, each with a different colour.
carouselViews = [[NSMutableArray alloc] initWithCapacity:6];
int c = 6;
while(c--)
{
UIView *view = [[UIView alloc] initWithFrame:frameForViews];
// We don't really care what the colours are as long as they're different,
// so just do anything
view.backgroundColor = [UIColor colorWithRed:(c&4) ? 1.0 : 0.0 green:(c&2) ? 1.0 : 0.0 blue:(c&1) ? 1.0 : 0.0 alpha:1.0];
// make the view visible, also add it to our array of carousel views
[carouselViews addObject:view];
[self.view addSubview:view];
}
currentAngle = lastAngle = 0.0f;
[self setCarouselAngle:currentAngle];
/*
Note: I've omitted viewDidUnload for brevity; remember to implement one and
clean up after all the objects created here
*/
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// if we're not already tracking a touch then...
if(!trackingTouch)
{
// ... track any of the new touches, we don't care which ...
trackingTouch = [touches anyObject];
// ... and cancel any animation that may be ongoing
[animationTimer invalidate];
animationTimer = nil;
lastAngle = currentAngle;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// if our touch moved then...
if([touches containsObject:trackingTouch])
{
// use the movement of the touch to decide
// how much to rotate the carousel
CGPoint locationNow = [trackingTouch locationInView:self.view];
CGPoint locationThen = [trackingTouch previousLocationInView:self.view];
lastAngle = currentAngle;
currentAngle += (locationNow.x - locationThen.x) * 180.0f / self.view.bounds.size.width;
// the 180.0f / self.view.bounds.size.width just says "let a full width of my view
// be a 180 degree rotation"
// and update the view positions
[self setCarouselAngle:currentAngle];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// if our touch ended then...
if([touches containsObject:trackingTouch])
{
// make sure we're no longer tracking it
trackingTouch = nil;
// and kick off the inertial animation
animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(animateAngle) userInfo:nil repeats:YES];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
// treat cancelled touches exactly like ones that end naturally
[self touchesEnded:touches withEvent:event];
}
@end
</code></pre>
<p>So relevant member variables are a mutable array, 'carouselViews', a timer, 'animationTimer', two floats, 'currentAngle' and 'lastAngle', and a UITouch, 'trackingTouch'. Obviously you'd probably want to use views that aren't just coloured squares and you might want to adjust the numbers I've pulled out of thin air for positioning. Otherwise, it should just work.</p>
<p>EDIT: I should say, I wrote and tested this code using the iPhone 'View-based application' template in Xcode. Create that template, dump my stuff into the created view controller and add the necessary member variables to test. However, I've realised that the touch tracking assumes 180 degrees is the full width of your view, but the setCarouselAngle: method forces the carousel always to be 280 points across (that's the 100 multiplier on xPosition times two, plus the width of a view). So the finger tracking will appear to be far too slow if you run it on an iPad. The solution is obviously not to assume the view width is 180 degrees but that's left as an exercise!</p> |
5,356,862 | SqlParameter with default value set to 0 doesn't work as expected | <p>I was doing something like this:</p>
<pre><code>SqlParameter param = new SqlParameter("@Param", 0) { SqlDbType = SqlDbType.Int };
private void TestParam(SqlParameter param) {
string test = param.Value.ToString(); // Getting NullReferenceException here
}
</code></pre>
<p>But I stop getting the exception when I put it like this:</p>
<pre><code>SqlParameter param = new SqlParameter("@Param", SqlDbType.Int) { Value = 0 };
private void TestParam(SqlParameter param) {
string test = param.Value.ToString(); // Everything OK
}
</code></pre>
<p>Can anyone tell me why SqlParameter assumes 0 is the same as null?</p>
<p><strong>Edit:</strong> MSDN Explains this here: <a href="http://msdn.microsoft.com/en-us/library/0881fz2y%28v=VS.80%29.aspx">SqlParameter Constructor</a></p> | 5,356,889 | 2 | 1 | null | 2011-03-18 19:23:54.49 UTC | 5 | 2011-05-11 12:46:32.333 UTC | 2011-05-11 12:46:32.333 UTC | null | 382,059 | null | 382,059 | null | 1 | 31 | c#|.net|.net-3.5|sqlparameter | 10,222 | <blockquote>
<p>Use caution when you use this overload
of the SqlParameter constructor to
specify integer parameter values.
Because this overload takes a value of
type Object, you must convert the
integral value to an Object type when
the value is zero, as the following C#
example demonstrates.</p>
<pre><code>Parameter = new SqlParameter("@pname", Convert.ToInt32(0));
</code></pre>
<p>If you do not perform this conversion,
the compiler assumes that you are
trying to call the SqlParameter
(string, SqlDbType) constructor
overload.</p>
</blockquote>
<p>Thanks <a href="http://msdn.microsoft.com/en-us/library/0881fz2y.aspx">Msdn</a> :)</p> |
16,213,566 | Check if a generated license is valid | <p>I have a PHP script that generates some strings which will be used as license keys:</p>
<pre><code>function KeyGen(){
$key = md5(microtime());
$new_key = '';
for($i=1; $i <= 25; $i ++ ){
$new_key .= $key[$i];
if ( $i%5==0 && $i != 25) $new_key.='-';
}
return strtoupper($new_key);
}
$x = 0;
while($x <= 10) {
echo KeyGen();
echo "<br />";
$x++;
}
</code></pre>
<p>After running the script once, I got these:</p>
<pre><code>8B041-EC7D2-0B9E3-09846-E8C71
C8D82-514B9-068BC-8BF80-05061
A18A3-E05E5-7DED7-D09ED-298C4
FB1EC-C9844-B9B20-ADE2F-0858F
E9AED-945C8-4BAAA-6938D-713ED
4D284-C5A3B-734DF-09BD6-6A34C
EF534-3BAE4-860B5-D3260-1CEF8
D84DB-B8C72-5BDEE-1B4FE-24E90
93AF2-80813-CD66E-E7A5E-BF0AE
C3397-93AA3-6239C-28D9F-7A582
D83B8-697C6-58CD1-56F1F-58180
</code></pre>
<p>What I now am trying to do is change it so that I have another function that will check if the key has been generated using my script. Currently, what I am thinking is setting the <code>$key</code> to the MD5 of one specific string (for example, <code>test</code>) but, of course, that returns all the strings the same. </p>
<p>Can anyone help?</p> | 16,215,513 | 5 | 6 | null | 2013-04-25 11:29:13.877 UTC | 9 | 2014-12-18 23:41:17.58 UTC | 2013-04-25 14:51:52.483 UTC | null | 338,665 | null | 2,078,412 | null | 1 | 9 | php|security|function|license-key | 11,843 | <p><strong>Note:</strong></p>
<p>This solution is on the assumption you want your licence key to always be in <code>fixed format</code> (see below) and still <code>self authenticated</code></p>
<pre><code> FORMAT : XXXXX-XXXXX-XXXXX-XXXXX-XXXX
</code></pre>
<p>If that is not the case refer to <code>@ircmaxell</code> for a better solution </p>
<p><strong>Introduction</strong></p>
<p>Self authenticated serial is tricky solution because:</p>
<ul>
<li>Limited Size of Serial </li>
<li>It need to authenticate it self without Database or any storage</li>
<li>If private key is leaked .. it can easily be reversed</li>
</ul>
<p><strong>Example</strong> </p>
<pre><code>$option = new CheckProfile();
$option->name = "My Application"; // Application Name
$option->version = 0.9; // Application Version
$option->username = "Benedict Lewis"; // you can limit the key to per user
$option->uniqid = null; // add if any
$checksum = new Checksum($option);
$key = $checksum->generate();
var_dump($key, $checksum->check($key));
</code></pre>
<p>Output </p>
<pre><code>string '40B93-C7FD6-AB5E6-364E2-3B96F' (length=29)
boolean true
</code></pre>
<p>Please note that any modification in the Options would change the key and make it invalid;</p>
<p><strong>Checking for collision</strong> </p>
<p>I just ran this simple test </p>
<pre><code>set_time_limit(0);
$checksum = new Checksum($option);
$cache = array();
$collision = $error = 0;
for($i = 0; $i < 100000; $i ++) {
$key = $checksum->generate();
isset($cache[$key]) and $collision ++;
$checksum->check($key) or $error ++;
$cache[$key] = true;
}
printf("Fond %d collision , %d Errors in 100000 entries", $collision, $error);
</code></pre>
<p>Output </p>
<pre><code> Fond 0 collision , 0 Errors in 100000 entries
</code></pre>
<p><strong>Better Security</strong> </p>
<p>By default the script uses <code>sha1</code> but <code>PHP</code> has a lot of better <code>hash functions</code> you can get that with the following code </p>
<pre><code>print_r(hash_algos());
</code></pre>
<p>Example </p>
<pre><code>$checksum = new Checksum($option, null, "sha512");
</code></pre>
<p><strong>Class Used</strong> </p>
<pre><code>class Checksum {
// Used used binaray in Hex format
private $privateKey = "ec340029d65c7125783d8a8b27b77c8a0fcdc6ff23cf04b576063fd9d1273257"; // default
private $keySize = 32;
private $profile;
private $hash = "sha1";
function __construct($option, $key = null, $hash = "sha1") {
$this->profile = $option;
$this->hash = $hash;
// Use Default Binary Key or generate yours
$this->privateKey = ($key === null) ? pack('H*', $this->privateKey) : $key;
$this->keySize = strlen($this->privateKey);
}
private function randString($length) {
$r = 0;
switch (true) {
case function_exists("openssl_random_pseudo_bytes") :
$r = bin2hex(openssl_random_pseudo_bytes($length));
break;
case function_exists("mcrypt_create_ivc") :
default :
$r = bin2hex(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM));
break;
}
return strtoupper(substr($r, 0, $length));
}
public function generate($keys = false) {
// 10 ramdom char
$keys = $keys ? : $this->randString(10);
$keys = strrev($keys); // reverse string
// Add keys to options
$this->profile->keys = $keys;
// Serialise to convert to string
$data = json_encode($this->profile);
// Simple Random Chr authentication
$hash = hash_hmac($this->hash, $data, $this->privateKey);
$hash = str_split($hash);
$step = floor(count($hash) / 15);
$i = 0;
$key = array();
foreach ( array_chunk(str_split($keys), 2) as $v ) {
$i = $step + $i;
$key[] = sprintf("%s%s%s%s%s", $hash[$i ++], $v[1], $hash[$i ++], $v[0], $hash[$i ++]);
$i ++; // increment position
}
return strtoupper(implode("-", $key));
}
public function check($key) {
$key = trim($key);
if (strlen($key) != 29) {
return false;
}
// Exatact ramdom keys
$keys = implode(array_map(function ($v) {
return $v[3] . $v[1];
}, array_map("str_split", explode("-", $key))));
$keys = strrev($keys); // very important
return $key === $this->generate($keys);
}
}
</code></pre> |
799,655 | ASP.Net FindControl is not working - How come? | <p>I have used <code>FindControl</code> in the past, prior to .NET 2.0/3.0. It seems like now, for some reason, the ID's of my controls get a funky named assigned. For example I assigned an id "cbSelect" to a checkbox, but FindControl does not find it. When I view the HTML it was assigned <code>ctl00_bodyPlaceHolder_ctl02_cbSelect</code>.</p>
<p>I have not found one example of FindControl that mentions that. In fact everyone seems to just use find control like normal.</p>
<p>So, am I doing something wrong? Did .Net change? Can anyone shed some light onto this for me, it is really frustrating!</p> | 799,678 | 7 | 0 | null | 2009-04-28 20:21:20.687 UTC | 7 | 2018-10-02 01:40:12.28 UTC | 2009-04-28 20:35:46.983 UTC | null | 33,226 | null | 80,088 | null | 1 | 30 | c#|.net|asp.net|findcontrol | 60,200 | <p>You are probably using a MasterPage or user controls (ascx) and this is the reason the for client ids change. Imagine you have a control in the master page with the same id as one in the page. This would result in clashes. The id changes ensures all ClientID properties are unique on a page. </p>
<p>FindControl needs some special attention when working with MasterPages. Have a look at <a href="http://west-wind.com/weblog/posts/5127.aspx" rel="noreferrer">ASP.NET 2.0 MasterPages and FindControl()</a>. The FindControl works inside a <a href="http://www.asp.net/LEARN/master-pages/tutorial-05-vb.aspx" rel="noreferrer">naming container</a>. The MastePage and the page are different naming containers.</p> |
688,039 | How can I build a std::vector<std::string> and then sort them? | <p>I have a bunch of strings that I need to sort. I think a std::vector would be the easiest way to do this. However, I've never used vectors before and so would like some help.</p>
<p>I just need to sort them alphanumerically, nothing special. Indeed, the string::compare function would work.</p>
<p>After that, how can I iterate through them to verify that they're sorted?</p>
<p>Here's what I have so far:</p>
<pre><code>std::sort(data.begin(), data.end(), std::string::compare);
for(std::vector<std::string>::iterator i = data.begin(); i != data.end(); ++i)
{
printf("%s\n", i.c_str);
}
</code></pre> | 688,068 | 7 | 1 | null | 2009-03-27 00:19:25.1 UTC | 4 | 2018-03-17 05:24:16.227 UTC | 2009-03-27 00:44:13.527 UTC | samoz | 39,036 | samoz | 39,036 | null | 1 | 40 | c++|string|sorting|vector | 75,347 | <p>You can just do </p>
<pre><code>std::sort(data.begin(), data.end());
</code></pre>
<p>And it will sort your strings. Then go through them checking whether they are in order</p>
<pre><code>if(names.empty())
return true; // empty vector sorted correctly
for(std::vector<std::string>::iterator i=names.begin(), j=i+1;
j != names.end();
++i, ++j)
if(*i > *j)
return false;
return true; // sort verified
</code></pre>
<p>In particular, <code>std::string::compare</code> couldn't be used as a comparator, because it doesn't do what <code>sort</code> wants it to do: Return true if the first argument is less than the second, and return false otherwise. If you use <code>sort</code> like above, it will just use <code>operator<</code>, which will do exactly that (i.e <code>std::string</code> makes it return <code>first.compare(second) < 0</code>).</p> |
652,432 | Compare compiled .NET assemblies? | <p>Are there any good programs out there to compare to compile .NET assemblies? </p>
<p>For example I have HelloWorld.dll (1.0.0.0) and HelloWorld.dll (2.0.0.0), and I want to compare differences how can I do this?</p>
<p>I know I can use .NET Reflector and use the Assembly Diff plugin. Are there any other good tools out there to do this?</p> | 652,459 | 7 | 4 | null | 2009-03-16 22:46:13.69 UTC | 18 | 2022-03-16 06:45:29.89 UTC | null | null | null | Danny G | 76,302 | null | 1 | 51 | c#|.net|vb.net|debugging|reverse-engineering | 33,556 | <p><a href="http://immitev.blogspot.com/2008/10/ways-to-compare-net-assemblies.html" rel="nofollow noreferrer">Ways to Compare .NET Assemblies</a> suggests</p>
<p>Commercial:</p>
<ul>
<li><a href="http://www.ndepend.com/" rel="nofollow noreferrer">NDepend</a></li>
</ul>
<p>Free:</p>
<ul>
<li><a href="http://www.telerik.com/justassembly" rel="nofollow noreferrer">JustAssembly</a> (only shows differences in API)</li>
<li><a href="https://github.com/grennis/bitdiffer" rel="nofollow noreferrer">BitDiffer</a> (same)</li>
<li><a href="http://www.codingsanity.com/diff.htm" rel="nofollow noreferrer">Reflector Diff Add-in</a> (which you've already discovered, but not available anymore)</li>
</ul>
<hr />
<p>Existing compare tools like Beyond Compare (commercial) can do this by special configuration. Here's how to do this for Beyond Compare:</p>
<ul>
<li>Go to <kbd>Tools</kbd> → <kbd>Options</kbd></li>
<li>Click <kbd>New..</kbd>, select "Text format", click <kbd>OK</kbd></li>
<li>Give it a name (say, EXE, or DLL), and specify the mask as <code>*.exe</code> or <code>*.dll</code></li>
<li>Click on tab <kbd>Conversion</kbd> and select "External program (Unicode filenames)"</li>
<li>Under "Loading", specify the path to <code>ildasm</code> and add <code> %s /OUT:%t /NOBAR</code> (i.e.: <code>C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\ildasm.exe %s /OUT:%t /NOBAR</code>)</li>
<li>Make sure to check <kbd>disable editing</kbd>.</li>
<li>Click <kbd>Save</kbd>, then <kbd>Close</kbd></li>
<li>Restart BC and open two <code>exe</code> files to compare, it should decompile into <code>ilasm</code> automatically now.</li>
</ul>
<p>You can also add syntax highlighting to this new format. I plan to send the syntax file to them so that it'll <a href="https://www.scootersoftware.com/download.php?zz=kb_moreformatsv3" rel="nofollow noreferrer">become available to share</a>.</p> |
154,441 | Set up an HTTP proxy to insert a header | <p>I need to test some HTTP interaction with a client I'd rather not modify. What I need to test is the behavior of the server when the client's requests include a certain, static header.</p>
<p>I'm thinking the easiest way to run this test is to set up an HTTP proxy that inserts the header on every request. What would be the simplest way to set this up?</p> | 154,641 | 7 | 0 | null | 2008-09-30 18:55:33.663 UTC | 16 | 2017-12-03 09:58:18.473 UTC | 2015-02-12 17:16:16.283 UTC | null | 4,560,278 | Logan | 3,518 | null | 1 | 58 | apache|proxy|http-headers|proxypass | 124,882 | <p>I do something like this in my development environment by configuring Apache on port 80 as a proxy for my application server on port 8080, with the following Apache config:</p>
<pre><code>NameVirtualHost *
<VirtualHost *>
<Proxy http://127.0.0.1:8080/*>
Allow from all
</Proxy>
<LocationMatch "/myapp">
ProxyPass http://127.0.0.1:8080/myapp
ProxyPassReverse http://127.0.0.1:8080/myapp
Header add myheader "myvalue"
RequestHeader set myheader "myvalue"
</LocationMatch>
</VirtualHost>
</code></pre>
<p>See <a href="http://httpd.apache.org/docs/current/mod/core.html#locationmatch" rel="noreferrer">LocationMatch</a> and <a href="http://httpd.apache.org/docs/current/mod/mod_headers.html#requestheader" rel="noreferrer">RequestHeader</a> documentation.</p>
<p>This adds the header <em>myheader: myvalue</em> to requests going to the application server.</p> |
842,557 | How to prevent a block of code from being interrupted by KeyboardInterrupt in Python? | <p>I'm writing a program that caches some results via the pickle module. What happens at the moment is that if I hit ctrl-c at while the <code>dump</code> operation is occurring, <code>dump</code> gets interrupted and the resulting file is corrupted (i.e. only partially written, so it cannot be <code>load</code>ed again.</p>
<p>Is there a way to make <code>dump</code>, or in general a block of code, uninterruptable? My current workaround looks something like this:</p>
<pre><code>try:
file = open(path, 'w')
dump(obj, file)
file.close()
except KeyboardInterrupt:
file.close()
file.open(path,'w')
dump(obj, file)
file.close()
raise
</code></pre>
<p>It seems silly to restart the operation if it is interrupted, so I am searching for a way to defer the interrupt. How do I do this?</p> | 842,567 | 7 | 0 | null | 2009-05-09 02:47:10.727 UTC | 27 | 2022-04-26 20:57:48.48 UTC | null | null | null | null | 37,984 | null | 1 | 71 | python | 26,855 | <p>Put the function in a thread, and wait for the thread to finish.</p>
<p>Python threads cannot be interrupted except with a special C api.</p>
<pre><code>import time
from threading import Thread
def noInterrupt():
for i in xrange(4):
print i
time.sleep(1)
a = Thread(target=noInterrupt)
a.start()
a.join()
print "done"
0
1
2
3
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\test.py", line 11, in <module>
a.join()
File "C:\Python26\lib\threading.py", line 634, in join
self.__block.wait()
File "C:\Python26\lib\threading.py", line 237, in wait
waiter.acquire()
KeyboardInterrupt
</code></pre>
<p>See how the interrupt was deferred until the thread finished?</p>
<p>Here it is adapted to your use:</p>
<pre><code>import time
from threading import Thread
def noInterrupt(path, obj):
try:
file = open(path, 'w')
dump(obj, file)
finally:
file.close()
a = Thread(target=noInterrupt, args=(path,obj))
a.start()
a.join()
</code></pre> |
1,066,589 | Iterate through a HashMap | <p>What's the best way to iterate over the items in a <a href="https://docs.oracle.com/javase/10/docs/api/java/util/HashMap.html" rel="noreferrer"><code>HashMap</code></a>?</p> | 1,066,603 | 7 | 2 | null | 2009-06-30 23:24:14.333 UTC | 1,037 | 2019-11-08 08:09:08.57 UTC | 2019-10-29 16:00:24.963 UTC | null | 10,795,151 | null | 84,916 | null | 1 | 3,693 | java|loops|hashmap|iteration | 4,285,682 | <p>Iterate through the <a href="http://www.java2s.com/Code/JavaAPI/java.util/HashtableentrySet.htm" rel="noreferrer"><code>entrySet()</code></a> like so:</p>
<pre><code>public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
</code></pre>
<p>Read more about <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Map.html" rel="noreferrer"><code>Map</code></a>.</p> |
4,949 | Version control PHP Web Project | <p>We have a PHP project that we would like to version control. Right now there are three of us working on a development version of the project which resides in an external folder to which all of our Eclipse IDEs are linked, and thus no version control.</p>
<p>What is the right way and the best way to version control this?</p>
<p>We have an SVN set up, but we just need to find a good way to check in and out that allows us to test on the development server. Any ideas?</p> | 4,965 | 8 | 0 | null | 2008-08-07 16:46:32.507 UTC | 12 | 2019-01-18 10:58:13.427 UTC | 2019-01-18 10:58:13.427 UTC | Ryan Fox | 567,854 | null | 673 | null | 1 | 36 | php|svn|version-control|cvs | 8,606 | <p>We were in a similar situation, and here's what we ended up doing:</p>
<ul>
<li>Set up two branches -- the release and development branch.</li>
<li>For the development branch, include a post-commit hook that deploys the repository to the dev server, so you can test.</li>
<li>Once you're ready, you merge your changes into the release branch. I'd also suggest putting in a post-commit hook for deployment there.</li>
</ul>
<p>You can also set up individual development servers for each of the team members, on their workstations. I find that it speeds things up a bit, although you do have some more setup time.</p>
<p>We had to use a single development server, because we were using a proprietary CMS and ran into licensing issues. So our post-commit hook was a simple FTP bot.</p> |
84,855 | What is the best choice for .NET inter-process communication? | <p>Should I use Named Pipes, or .NET Remoting to communicate with a running process on my machine?</p> | 84,893 | 8 | 1 | null | 2008-09-17 16:05:21.953 UTC | 25 | 2022-07-27 14:04:34.707 UTC | 2014-02-25 15:45:36.873 UTC | jjnguy | 321,731 | mrbradleyt | 2,744 | null | 1 | 84 | c#|.net|process|ipc | 90,921 | <p>WCF is the best choice. It supports <a href="https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-3.0/ms733769%28v=vs.85%29" rel="nofollow noreferrer">a number of different transport mechanisms</a> (<a href="https://web.archive.org/web/20121019154711/http://blogs.charteris.com:80/blogs/chrisdi/archive/2008/05/19/exploring-the-wcf-named-pipe-binding-part-1.aspx" rel="nofollow noreferrer">including</a> <a href="https://web.archive.org/web/20110919020547/http://blogs.charteris.com:80/blogs/chrisdi/archive/2008/06/16/exploring-the-wcf-named-pipe-binding-part-2.aspx" rel="nofollow noreferrer">Named</a> <a href="https://web.archive.org/web/20131017152044/http://blogs.charteris.com:80/blogs/chrisdi/archive/2008/06/23/exploring-the-wcf-named-pipe-binding-part-3.aspx" rel="nofollow noreferrer">Pipes</a>) and can be completely configuration driven. I would highly recommend that you take a look at WCF.</p>
<p>Here is a blog that does a <a href="https://web.archive.org/web/20201031045150/http://geekswithblogs.net/marcel/archive/2007/09/26/115651.aspx" rel="nofollow noreferrer">WCF vs Remoting performance comparison</a>.</p>
<p>A quote from the blog:</p>
<blockquote>
<p>The WCF and .NET Remoting are really comparable in performance. The differences are so small (measuring client latency) that it does not matter which one is a bit faster. WCF though has much better server throughput than .NET Remoting. If I would start completely new project I would chose the WCF. Anyway the WCF does much more than Remoting and for all those features I love it.</p>
</blockquote>
<p><a href="https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-3.5/ms735119%28v=vs.90%29" rel="nofollow noreferrer">MSDN Section for WCF</a></p> |
502,238 | Google-like Search Engine in PHP/mySQL | <p>We have OCRed thousands of pages of newspaper articles. The newspaper, issue, date, page number and OCRed text of each page has been put into a mySQL database. </p>
<p>We now want to build a Google-like search engine in PHP to find the pages given a query. It's got to be fast, and take no more than a second for any search. </p>
<p>How should we do it?</p> | 502,305 | 9 | 5 | null | 2009-02-02 05:10:04.463 UTC | 13 | 2014-05-13 15:19:54.34 UTC | null | null | null | lkessler | 30,176 | null | 1 | 23 | php|mysql|search-engine | 46,275 | <p>You can also try out <a href="http://www.sphinxsearch.com/" rel="noreferrer">SphinxSearch</a>. Craigslist uses sphinx and it can connect to both mysql and postgresql.</p> |
1,101,841 | How to perform .Max() on a property of all objects in a collection and return the object with maximum value | <p>I have a list of objects that have two int properties. The list is the output of another linq query. The object:</p>
<pre><code>public class DimensionPair
{
public int Height { get; set; }
public int Width { get; set; }
}
</code></pre>
<p>I want to find and return the object in the list which has the largest <code>Height</code> property value.</p>
<p>I can manage to get the highest value of the <code>Height</code> value but not the object itself.</p>
<p>Can I do this with Linq? How?</p> | 1,101,979 | 9 | 2 | null | 2009-07-09 04:29:53.663 UTC | 62 | 2019-08-06 16:07:26.707 UTC | 2019-08-06 16:07:26.707 UTC | null | 107,625 | null | 105,916 | null | 1 | 331 | c#|linq|object|max | 448,792 | <p>We have an <a href="https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/MaxBy.cs" rel="noreferrer">extension method</a> to do exactly this in <a href="https://github.com/morelinq/MoreLINQ" rel="noreferrer">MoreLINQ</a>. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.</p>
<p>In your case you'd do something like:</p>
<pre><code>var item = items.MaxBy(x => x.Height);
</code></pre>
<p>This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as <code>MaxBy</code>):</p>
<ul>
<li>It's O(n) unlike the <a href="https://stackoverflow.com/a/1101848/16587">previous accepted answer</a> which finds the maximum value on every iteration (making it O(n^2))</li>
<li>The ordering solution is O(n log n)</li>
<li>Taking the <code>Max</code> value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion.</li>
<li>It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element</li>
</ul> |
345,997 | Better way to revert to a previous SVN revision of a file? | <p>I accidentally committed too many files to an SVN repository and changed some things I didn't mean to. (Sigh.) In order to revert them to their prior state, the best I could come up with was </p>
<pre><code>svn rm l3toks.dtx
svn copy -r 854 svn+ssh://<repository URL>/l3toks.dtx ./l3toks.dtx
</code></pre>
<p>Jeez! Is there no better way? Why can't I just write something like this: </p>
<pre><code>svn revert -r 854 l3toks.dtx
</code></pre>
<p>Okay, I'm only using v1.4.4, but I skimmed over the changes list for the 1.5 branch and I couldn't see anything directly related to this. Did I miss anything?</p>
<hr>
<p>Edit: I guess I wasn't clear enough. I don't think I want to reverse merge, because then I'll lose the changes that I <em>did</em> want to make! Say that <code>fileA</code> and <code>fileB</code> were both modified but I only wanted to commit <code>fileA</code>; accidentally typing </p>
<pre><code>svn commit -m "small change"
</code></pre>
<p>commits both files, and now I want to roll back <code>fileB</code>. Reverse merging makes this task no easier (as far as I can tell) than the steps I outlined above.</p> | 346,120 | 9 | 1 | null | 2008-12-06 06:03:35.853 UTC | 74 | 2016-02-05 16:33:44.57 UTC | 2009-10-25 10:09:18.79 UTC | Will Robertson | 4,161 | Will Robertson | 4,161 | null | 1 | 167 | svn | 275,601 | <pre><code>svn merge -r 854:853 l3toks.dtx
</code></pre>
<p>or</p>
<pre><code>svn merge -c -854 l3toks.dtx
</code></pre>
<p>The two commands <a href="http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.merge.html" rel="noreferrer">are equivalent</a>.</p> |
1,192,070 | Good Readings on Unix/Linux Socket Programming? | <p>though I haven't worked with sockets professionally, I find them interesting. I read some part of Unix Network Programming by Richard Stevens (considered to be the Bible I suppose as it is referred by everyone I ask) but the problem is the examples require a universal header unp.h which is a PIA to use.</p>
<p>Can some of you suggest a good reading for socket programming in Unix/Linux? Considering I am relatively experienced C/C++ coder.</p> | 1,192,074 | 10 | 0 | null | 2009-07-28 05:28:08.177 UTC | 14 | 2012-10-28 11:34:03.81 UTC | 2009-07-28 06:13:21.813 UTC | null | 111,896 | null | 126,691 | null | 1 | 12 | c++|linux|sockets | 7,222 | <p>The canonical reference is <em>UNIX Network Programming</em> by W. Richard Stevens. upn.h is really just a helper header, to make the book examples clearer - it doesn't do anything particularly magic.</p>
<p>To get up and running very quickly, it's hard to go past <a href="http://beej.us/guide/bgnet/" rel="noreferrer">Beej's Guide To Network Programming using Internet Sockets</a>.</p> |
292,682 | Understanding Dijkstra's Mozart programming style | <p>I came across <a href="http://www.catonmat.net/blog/edsger-dijkstra-discipline-in-thought/" rel="nofollow noreferrer">this article</a> about programming styles, seen by Edsger Dijsktra. To quickly paraphrase, the main difference is Mozart, when the analogy is made to programming, fully understood (debatable) the problem before writing anything, while Beethoven made his decisions as he wrote the notes out on paper, creating many revisions along the way. With Mozart programming, version 1.0 would be the only version for software that should aim to work with no errors and maximum efficiency. Also, Dijkstra says software not at that level of refinement and stability should not be released to the public.</p>
<p>Based on his views, two questions. Is Mozart programming even possible? Would the software we write today really benefit if we adopted the Mozart style instead? </p>
<p>My thoughts. It seems, to address the increasing complexity of software, we've moved on from this method to things like agile development, public beta testing, and constant revisions, methods that define web development, where speed matters most. But when I think of all the revisions web software can go through, especially during maintenance, when often patches are applied over patches, to then be refined through a tedious refactoring process—the Mozart way seems very attractive. It would at least lessen those annoying software updates, e.g. Digsby, Windows, iTunes, etc., many the result of unforeseen vulnerabilities that require a new and immediate release.</p>
<p>Edit: Refer to <a href="https://stackoverflow.com/questions/292682/understanding-dijkstras-mozart-programming-style#292955">the response below</a> for a more accurate explanation of Dijsktra's views.</p> | 292,757 | 10 | 2 | null | 2008-11-15 15:41:28.767 UTC | 24 | 2015-06-19 20:13:16.453 UTC | 2017-05-23 12:26:29.543 UTC | pixelwando | -1 | pixelwando | 65,465 | null | 1 | 20 | coding-style|dijkstra | 4,382 | <p><strong>It doesn't scale.</strong></p>
<p>I can figure out a line of code in my head, a routine, and even a small program. But a medium program? There are probably some guys that can do it, but how many, and how much do they cost? And should they really write the next payroll program? That's like wasting Mozart on muzak.</p>
<p>Now, try to imagine a team of Mozarts. Just for a few seconds. </p>
<hr>
<p>Still it is a powerful instrument. If you can figure out a whole line in your head, do it. If you can figure out a small routine with all its funny cases, do it. </p>
<p>On the surface, it avoids going back to the drawing board because you didn't think of one edge case that requires a completely different interface altogether. </p>
<p>The deeper meaning (<a href="http://www.associatedcontent.com/article/604505/life_lessons_and_the_randy_pausch_head.html" rel="nofollow noreferrer">head fake</a>?) can be explained by learning another human language. For a long time you thinking which words represent your thoughts, and how to order them into a valid sentence - that transcription costs a lot of foreground cycles.<br>
One day you will notice the liberating feeling that you just talk. It may feel like "thinking in a foregin language", or as if "the words come naturally". You will sometimes stumble, looking for a particular word or idiom, but most of the time translation <strong>runs in the vast ressources of the "subconcious CPU"</strong>. </p>
<hr>
<p>The "high goal" is developing a mental model of the solution that is (mostly) independent of the implementation language, to separate <em>solution</em> of a problem from <em>transcribing</em> the problem. Transcription is easy, repetetive and easily trained, and abstract solutions can be reused.</p>
<p>I have no idea how this could be taught, but "figuring out as much as possible before you start to write it" sounds like good programming practice towards that goal.</p> |
1,119,505 | How to think in SQL? | <p>How do I stop thinking every query in terms of cursors, procedures and functions and start using SQL as it should be? Do we make the transition to thinking in SQL just by practise or is there any magic to learning the set based query language? What did you do to make the transition?</p> | 1,119,562 | 10 | 0 | null | 2009-07-13 13:39:53.207 UTC | 15 | 2018-10-21 06:31:29.643 UTC | 2009-07-22 10:34:47.84 UTC | null | 120,457 | null | 37,450 | null | 1 | 27 | sql|database|rdbms | 12,321 | <p>A few examples of what should come to your mind first if you're real <code>SQL</code> geek:</p>
<ul>
<li><p><a href="http://en.wikipedia.org/wiki/Bible_concordance" rel="noreferrer"><strong>Bible concordance</strong></a> is a <code>FULLTEXT</code> index to the <code>Bible</code></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/Luca_Pacioli" rel="noreferrer"><strong>Luca Pacioli</strong></a>'s <em>Summa de arithmetica</em> which describes double-entry bookkeeping is in fact a normalized database schema</p></li>
<li><p>When <code>Xerxes I</code> counted his army by walling an area that <code>10,000</code> of his men occupied and then marching the other men through this enclosure, he used <code>HASH AGGREGATE</code> method.</p></li>
<li><p><code>The House That Jack Built</code> should be rewritten using a self-join.</p></li>
<li><p><code>The Twelve Days of Christmas</code> should be rewritten using a self-join and a <code>ROWNUM</code></p></li>
<li><p><code>There Was An Old Woman Who Swallowed a Fly</code> should be rewritten using <code>CTE</code>'s</p></li>
<li><p>If the <code>European Union</code> were called <code>European Union All</code>, we would see <code>27</code> spellings for the word <code>euro</code> on a <a href="http://en.wikipedia.org/wiki/File:EUR_500_reverse_(2002_issue).jpg" rel="noreferrer"><strong>Euro banknote</strong></a>, instead of <code>2</code>.</p></li>
</ul>
<p>And finally you can read a lame article in my blog on how <em>I</em> stopped worrying and learned to love <code>SQL</code> (I almost forgot I wrote it):</p>
<ul>
<li><a href="http://explainextended.com/2009/06/21/click/" rel="noreferrer"><strong>Click</strong></a></li>
</ul>
<p>And one more article just on the subject:</p>
<ul>
<li><a href="http://explainextended.com/2009/07/12/double-thinking-in-sql/" rel="noreferrer"><strong>Double-thinking in SQL</strong></a></li>
</ul> |
226,784 | How to create a simple proxy in C#? | <p>I have downloaded Privoxy few weeks ago and for the fun I was curious to know how a simple version of it can be done.</p>
<p>I understand that I need to configure the browser (client) to send request to the proxy. The proxy send the request to the web (let say it's a http proxy). The proxy will receive the answer... but how can the proxy send back the request to the browser (client)?</p>
<p>I have search on the web for C# and http proxy but haven't found something that let me understand how it works behind the scene correctly. (I believe I do not want a reverse proxy but I am not sure).</p>
<p>Does any of you have some explication or some information that will let me continue this small project?</p>
<h2>Update</h2>
<p>This is what I understand (see graphic below).</p>
<p><strong>Step 1</strong> I configure the client (browser) for all request to be send to 127.0.0.1 at the port the Proxy listen. This way, request will be not sent to the Internet directly but will be processed by the proxy.</p>
<p><strong>Step2</strong> The proxy see a new connection, read the HTTP header and see the request he must executes. He executes the request.</p>
<p><strong>Step3</strong> The proxy receive an answer from the request. Now he must send the answer from the web to the client but how???</p>
<p><img src="https://i.stack.imgur.com/zNWDc.png" alt="alt text" /></p>
<h3>Useful link</h3>
<p><a href="http://www.mentalis.org/soft/projects/proxy/" rel="noreferrer">Mentalis Proxy</a> : I have found this project that is a proxy (but more that I would like). I might check the source but I really wanted something basic to understand more the concept.</p>
<p><a href="http://www.codeproject.com/KB/aspnet/asproxy.aspx" rel="noreferrer">ASP Proxy</a> : I might be able to get some information over here too.</p>
<p><a href="http://bartdesmet.net/blogs/bart/archive/2007/02/22/httplistener-for-dummies-a-simple-http-request-reflector.aspx" rel="noreferrer">Request reflector</a> : This is a simple example.</p>
<p>Here is a <a href="https://github.com/MrDesjardins/SimpleHttpProxy" rel="noreferrer">Git Hub Repository with a Simple Http Proxy</a>.</p> | 226,795 | 10 | 1 | 2008-11-03 16:09:27.91 UTC | 2008-10-22 17:31:20.507 UTC | 88 | 2019-09-26 15:27:52.76 UTC | 2020-06-20 09:12:55.06 UTC | Joel Coehoorn | -1 | Daok | 13,913 | null | 1 | 150 | c#|.net|.net-2.0|proxy | 182,755 | <p>You can build one with the <a href="http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx" rel="noreferrer"><code>HttpListener</code></a> class to listen for incoming requests and the <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx" rel="noreferrer"><code>HttpWebRequest</code></a> class to relay the requests.</p> |
967,047 | How to perform a binary search on IList<T>? | <p>Simple question - given an <code>IList<T></code> how do you perform a binary search without writing the method yourself and without copying the data to a type with build-in binary search support. My current status is the following.</p>
<ul>
<li><code>List<T>.BinarySearch()</code> is not a member of <code>IList<T></code></li>
<li>There is no equivalent of the <a href="http://msdn.microsoft.com/en-us/library/system.collections.arraylist.adapter.aspx" rel="noreferrer"><code>ArrayList.Adapter()</code></a> method for <code>List<T></code></li>
<li><code>IList<T></code> does not inherit from <code>IList</code>, hence using <code>ArrayList.Adapter()</code> is not possible</li>
</ul>
<p>I tend to believe that is not possible with build-in methods, but I cannot believe that such a basic method is missing from the BCL/FCL.</p>
<p>If it is not possible, who can give the shortest, fastest, smartest, or most beatiful binary search implementation for <code>IList<T></code>?</p>
<p><strong>UPDATE</strong></p>
<p>We all know that a list must be sorted before using binary search, hence you can assume that it is. But I assume (but did not verify) it is the same problem with sort - how do you sort <code>IList<T></code>?</p>
<p><strong>CONCLUSION</strong></p>
<p>There seems to be no build-in binary search for <code>IList<T></code>. One can use <code>First()</code> and <code>OrderBy()</code> LINQ methods to search and sort, but it will likly have a performance hit. Implementing it yourself (as an extension method) seems the best you can do.</p> | 967,098 | 11 | 8 | null | 2009-06-08 21:09:09.183 UTC | 9 | 2019-10-04 18:31:34.633 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 77,507 | null | 1 | 45 | .net|generics|list|interface|binary-search | 19,858 | <p>I doubt there is a general purpose binary search method in .NET like that, except for the one being present in some base classes (but apparently not in the interfaces), so here's my general purpose one.</p>
<pre><code>public static Int32 BinarySearchIndexOf<T>(this IList<T> list, T value, IComparer<T> comparer = null)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
comparer = comparer ?? Comparer<T>.Default;
Int32 lower = 0;
Int32 upper = list.Count - 1;
while (lower <= upper)
{
Int32 middle = lower + (upper - lower) / 2;
Int32 comparisonResult = comparer.Compare(value, list[middle]);
if (comparisonResult == 0)
return middle;
else if (comparisonResult < 0)
upper = middle - 1;
else
lower = middle + 1;
}
return ~lower;
}
</code></pre>
<p>This of course assumes that the list in question is already sorted, according to the same rules that the comparer will use.</p> |
118,260 | How to start IDLE (Python editor) without using the shortcut on Windows Vista? | <p>I'm trying to teach Komodo to fire up <a href="http://en.wikipedia.org/wiki/IDLE_(Python)" rel="noreferrer">IDLE</a> when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appears to be a failure as IDLE doesn't start up.</p>
<p>I thought I'd avoid the shortcut and just use the exact path. I go to the start menu, find the shortcut for IDLE, right click to look at the properties. The target is grayed out, but says "Python 2.5.2". The "Start in" is set to, "C:\Python25\". The "Open File Location" button is also grayed out.</p>
<p>How do I find out where this shortcut is really pointing? I have tried starting python.exe and pythonw.exe both in C:\Python25, but neither starts up IDLE.</p> | 118,275 | 13 | 3 | null | 2008-09-22 23:44:21.877 UTC | 7 | 2022-08-24 20:17:27.9 UTC | 2010-05-18 05:41:24.063 UTC | null | 211,160 | Jason Dagit | 5,113 | null | 1 | 50 | python|python-idle|komodo|pywin | 178,088 | <p>There's a file called <code>idle.py</code> in your Python installation directory in <code>Lib\idlelib\idle.py</code>.</p>
<p>If you run that file with Python, then IDLE should start.</p>
<blockquote>
<p>c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py</p>
</blockquote> |
1,275,109 | What features should a C#/.NET profiler have? | <p>This could be a borderline advertisement, not to mention subjective, but the question is an honest one. For the last two months, I've been developing a new open source profiler for .NET called SlimTune Profiler (<a href="http://code.google.com/p/slimtune/" rel="noreferrer">http://code.google.com/p/slimtune/</a>).</p>
<p>It's a relatively new effort, but when I looked at the range of profilers available I was not terribly impressed. I've done some initial work based on existing products, but I felt this would be a good place to ask: what exactly do you WANT from a profiler?</p>
<p>I come from real time graphics and games, so it's important to me that a profiler be as fast as possible. Otherwise, the game becomes unplayable and profiling an unplayable slow game tends not to be very enlightening. I'm willing to sacrifice some accuracy as a result. I don't even care about exceptions. But I'm not very familiar with what developers for other types of applications are interested in. Are there any make or break features for you? Where do existing tools fall down?</p>
<p>Again, I apologize if this is just way off base for StackOverflow, but it's always been an incredibly useful resource to me and there's a very wide range of developers here.</p> | 1,275,177 | 14 | 4 | null | 2009-08-13 22:58:17.71 UTC | 16 | 2019-04-13 22:49:00.553 UTC | 2009-08-14 05:45:44.13 UTC | null | 91,405 | null | 91,405 | null | 1 | 32 | c#|.net|performance|profiler | 1,830 | <p>My requirements:</p>
<ul>
<li>Collect stats without impact to application - e.g. don't fill up memory, allow data to be collected away from apps under question</li>
<li>Ability to specify measurements simply and repeatably (data driven)</li>
<li>Automatable so that I can repeat measurements without point and click, and without UI</li>
<li>Enable us to understand issues related to the WPF and other declarative technologies such as DLR or WF</li>
<li>No installation - no gac, msi etc, even better if can be run over a network</li>
<li>Support 64 bit from outset</li>
<li>Don't try to know all the the analysis that could be done - encourage an ecosystem. If the raw stats can be analysed using other tools so much the better. </li>
<li>UI if any should be good - but its the stats that matter. So don't spend time on that, get the core profiling good.
<ul>
<li>Support profiling of apps that are not straight exe's like services and web applications simply.</li>
</ul></li>
</ul>
<p>would likes:</p>
<ul>
<li>Consider cross app support - big apps often need to understand apps performance behavior across many executables. If your profiler allows easy correlation of this data then so much the better</li>
</ul> |
47,903 | UDP vs TCP, how much faster is it? | <p>For general protocol message exchange, which can tolerate some packet loss. How much more efficient is UDP over TCP?</p> | 47,929 | 14 | 6 | null | 2008-09-06 22:46:36.373 UTC | 118 | 2019-11-14 06:44:50.097 UTC | 2014-05-14 14:16:19.143 UTC | marcio | 1,710,392 | null | 4,946 | null | 1 | 218 | networking|tcp|udp | 256,920 | <p>UDP is faster than TCP, and the simple reason is because its non-existent acknowledge packet (ACK) that permits a continuous packet stream, instead of TCP that acknowledges a set of packets, calculated by using the TCP window size and round-trip time (RTT).</p>
<p>For more information, I recommend the simple, but very comprehensible <a href="http://www.skullbox.net/tcpudp.php" rel="noreferrer">Skullbox explanation (TCP vs. UDP)</a></p> |
643,137 | How do I spool to a CSV formatted file using SQLPLUS? | <p>I want to extract some queries to a CSV output format. Unfortunately, I can't use any fancy SQL client or any language to do it. I must use SQLPLUS.</p>
<p>How do I do it?</p> | 42,236,970 | 16 | 0 | null | 2009-03-13 15:05:29.21 UTC | 78 | 2020-07-16 08:43:57.537 UTC | 2009-03-13 18:19:00.163 UTC | marc_s | 13,302 | Daniel | 53,013 | null | 1 | 160 | sql|oracle|csv|sqlplus | 619,934 | <p>If you are using 12.2, you can simply say</p>
<pre><code>set markup csv on
spool myfile.csv
</code></pre> |
757,684 | Enum "Inheritance" | <p>I have an enum in a low level namespace. I'd like to provide a class or enum in a mid level namespace that "inherits" the low level enum.</p>
<pre><code>namespace low
{
public enum base
{
x, y, z
}
}
namespace mid
{
public enum consume : low.base
{
}
}
</code></pre>
<p>I'm hoping that this is possible, or perhaps some kind of class that can take the place of the enum consume which will provide a layer of abstraction for the enum, but still let an instance of that class access the enum.</p>
<p>Thoughts?</p>
<p>EDIT:
One of the reasons I haven't just switched this to consts in classes is that the low level enum is needed by a service that I must consume. I have been given the WSDLs and the XSDs, which define the structure as an enum. The service cannot be changed.</p> | 757,762 | 16 | 3 | null | 2009-04-16 19:27:07.667 UTC | 64 | 2022-07-06 02:36:41.353 UTC | 2009-04-16 20:04:57.233 UTC | null | 72,858 | null | 72,858 | null | 1 | 454 | c#|.net|enums | 296,282 | <p>This is not possible. Enums cannot inherit from other enums. In fact all enums must actually inherit from <code>System.Enum</code>. C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.enum.</p>
<p>See section 8.5.2 of the <a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf" rel="noreferrer">CLI spec</a> for the full details. Relevant information from the spec</p>
<ul>
<li>All enums must derive from <code>System.Enum</code></li>
<li>Because of the above, all enums are value types and hence sealed</li>
</ul> |
1,085,709 | What does 'synchronized' mean? | <p>I have some questions regarding the usage and significance of the <code>synchronized</code> keyword. </p>
<ul>
<li>What is the significance of the <code>synchronized</code> keyword?</li>
<li>When should methods be <code>synchronized</code>?</li>
<li>What does it mean programmatically and logically?</li>
</ul> | 1,085,745 | 17 | 5 | null | 2009-07-06 06:47:23.96 UTC | 340 | 2022-01-12 18:14:11.647 UTC | 2016-01-26 23:14:25.943 UTC | null | 207,421 | null | 124,339 | null | 1 | 1,102 | java|multithreading|keyword|synchronized | 534,585 | <p>The <code>synchronized</code> keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun:</p>
<blockquote>
<p><code>synchronized</code> methods enable a simple
strategy for preventing thread
interference and memory consistency
errors: if an object is visible to
more than one thread, all reads or
writes to that object's variables are
done through synchronized methods.</p>
</blockquote>
<p><em>In a very, very small nutshell:</em> When you have two threads that are reading and writing to the same 'resource', say a variable named <code>foo</code>, you need to ensure that these threads access the variable in an atomic way. Without the <code>synchronized</code> keyword, your thread 1 may not see the change thread 2 made to <code>foo</code>, or worse, it may only be half changed. This would not be what you logically expect.</p>
<p>Again, this is a non-trivial topic in Java. To learn more, explore topics here on SO and the Interwebs about:</p>
<ul>
<li><a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html" rel="noreferrer">Concurrency</a></li>
<li><a href="http://en.wikipedia.org/wiki/Java_Memory_Model" rel="noreferrer">Java Memory Model</a></li>
</ul>
<p>Keep exploring these topics until the name <em>"Brian Goetz"</em> becomes permanently associated with the term <em>"concurrency"</em> in your brain. </p> |
252,203 | Checking if a variable is not nil and not zero in ruby | <p>I am using the following code to check if a variable is not nil and not zero</p>
<pre><code>if(discount != nil && discount != 0)
...
end
</code></pre>
<p>Is there a better way to do this?</p> | 252,253 | 18 | 3 | null | 2008-10-31 00:05:57.393 UTC | 47 | 2020-09-25 11:09:50.03 UTC | 2015-08-11 21:42:14.337 UTC | null | 1,090,562 | hectorsq | 14,755 | null | 1 | 309 | ruby | 562,674 | <pre>
unless discount.nil? || discount == 0
# ...
end
</pre> |
1,184,624 | Convert form data to JavaScript object with jQuery | <p>How do I convert all elements of my form to a JavaScript object? </p>
<p>I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element. I do not want a string, as returned by <code>$('#formid').serialize();</code>, nor do I want the map returned by <code>$('#formid').serializeArray();</code></p> | 1,186,309 | 55 | 1 | 2013-10-06 15:16:51.937 UTC | 2009-07-26 13:39:54.98 UTC | 589 | 2022-08-03 19:06:16.96 UTC | 2018-08-25 04:17:19.52 UTC | null | 5,490,782 | null | 35,091 | null | 1 | 1,733 | javascript|jquery|json|serialization | 1,068,992 | <p><a href="http://api.jquery.com/serializeArray/" rel="noreferrer">serializeArray</a> already does exactly that. You just need to massage the data into your required format:</p>
<pre class="lang-js prettyprint-override"><code>function objectifyForm(formArray) {
//serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}
</code></pre>
<p>Watch out for hidden fields which have the same name as real inputs as they will get overwritten.</p> |
38,296,756 | What is the idiomatic way in CMAKE to add the -fPIC compiler option? | <p>I've come across at least 3 ways to do this and I'm wondering which is the idiomatic way. This needs to be done almost universally to any static library. I'm surprised that the Makefile generator in CMake doesn't automatically add this to static libraries. (unless I'm missing something?)</p>
<pre><code>target_compile_options(myLib PRIVATE -fPIC)
add_compile_options(-fPIC)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fpic")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fpic")
</code></pre>
<p>I believe there might also be other variations. (please edit my question if you find one)</p>
<p>If you happen to know the answer to this question, do you also know if there is a way to cause a 3rd party CMake project to be compiled with this flag without modifying its CMakeLists.txt file? I have run across static libraries missing that flag. It causes problems when compiling a static library into a dynamic library. </p>
<p>You get:</p>
<pre><code>relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
</code></pre> | 38,297,422 | 2 | 2 | null | 2016-07-10 21:50:25.557 UTC | 40 | 2022-09-18 21:41:20.49 UTC | null | null | null | null | 451,007 | null | 1 | 194 | c++|c|cmake | 96,782 | <p>You can set the position independent code property on all targets:</p>
<pre><code>set(CMAKE_POSITION_INDEPENDENT_CODE ON)
</code></pre>
<p>or in a specific library:</p>
<pre><code>add_library(lib1 lib1.cpp)
set_property(TARGET lib1 PROPERTY POSITION_INDEPENDENT_CODE ON)
</code></pre>
<p>Reference:</p>
<ul>
<li><a href="https://cmake.org/cmake/help/latest/variable/CMAKE_POSITION_INDEPENDENT_CODE.html" rel="nofollow noreferrer"><code>CMAKE_POSITION_INDEPENDENT_CODE</code></a></li>
<li><a href="https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#compatible-interface-properties" rel="nofollow noreferrer">cmake build system: "Compatible Interface Properties"</a></li>
</ul> |
15,727,420 | Using logging in multiple modules | <p>I have a small python project that has the following structure - </p>
<pre><code>Project
-- pkg01
-- test01.py
-- pkg02
-- test02.py
-- logging.conf
</code></pre>
<p>I plan to use the default logging module to print messages to stdout and a log file.
To use the logging module, some initialization is required - </p>
<pre><code>import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('pyApp')
logger.info('testing')
</code></pre>
<p>At present, I perform this initialization in every module before I start logging messages. Is it possible to perform this initialization only once in one place such that the same settings are reused by logging all over the project?</p> | 15,735,146 | 12 | 4 | null | 2013-03-31 07:39:09.28 UTC | 168 | 2021-11-02 18:06:51.663 UTC | 2020-02-14 19:37:18.453 UTC | null | 355,230 | null | 1,186,878 | null | 1 | 375 | python|logging|config | 278,882 | <p>Best practice is, in each module, to have a logger defined like this:</p>
<pre><code>import logging
logger = logging.getLogger(__name__)
</code></pre>
<p>near the top of the module, and then in other code in the module do e.g.</p>
<pre><code>logger.debug('My message with %s', 'variable data')
</code></pre>
<p>If you need to subdivide logging activity inside a module, use e.g.</p>
<pre><code>loggerA = logging.getLogger(__name__ + '.A')
loggerB = logging.getLogger(__name__ + '.B')
</code></pre>
<p>and log to <code>loggerA</code> and <code>loggerB</code> as appropriate.</p>
<p>In your main program or programs, do e.g.:</p>
<pre><code>def main():
"your program code"
if __name__ == '__main__':
import logging.config
logging.config.fileConfig('/path/to/logging.conf')
main()
</code></pre>
<p>or </p>
<pre><code>def main():
import logging.config
logging.config.fileConfig('/path/to/logging.conf')
# your program code
if __name__ == '__main__':
main()
</code></pre>
<p>See <a href="http://docs.python.org/howto/logging.html#logging-from-multiple-modules">here</a> for logging from multiple modules, and <a href="http://docs.python.org/howto/logging.html#configuring-logging-for-a-library">here</a> for logging configuration for code which will be used as a library module by other code.</p>
<p><strong>Update:</strong> When calling <code>fileConfig()</code>, you may want to specify <code>disable_existing_loggers=False</code> if you're using Python 2.6 or later (see <a href="http://docs.python.org/2/library/logging.config.html#logging.config.fileConfig">the docs</a> for more information). The default value is <code>True</code> for backward compatibility, which causes all existing loggers to be disabled by <code>fileConfig()</code> unless they or their ancestor are explicitly named in the configuration. With the value set to <code>False</code>, existing loggers are left alone. If using Python 2.7/Python 3.2 or later, you may wish to consider the <code>dictConfig()</code> API which is better than <code>fileConfig()</code> as it gives more control over the configuration.</p> |
32,613,064 | format date from "MMM dd, yyyy HH:mm:ss a" to "MM.dd | <p>I want to format date from "MMM dd, yyyy HH:mm:ss a" to "MM.dd".
I have following code</p>
<pre><code>SimpleDateFormat ft = new SimpleDateFormat ("MMM dd, yyyy hh:mm:ss a");
t = ft.parse(date); //Date is Sep 16, 2015 10:34:23 AM and of type string.
ft.applyPattern("MM.dd");
</code></pre>
<p>but I am getting exception at <code>t = ft.parse(date);</code> </p>
<p>Please help</p> | 32,613,523 | 2 | 7 | null | 2015-09-16 15:39:11.443 UTC | 1 | 2015-09-30 08:06:33.76 UTC | 2015-09-16 15:54:20.767 UTC | null | 1,469,259 | null | 1,307,255 | null | 1 | 7 | java|datetime | 46,416 | <p>Three possible explanations:</p>
<ol>
<li>your default locale is incompatible with the input date - e.g. it can't understand <code>Sep</code> as a month name</li>
<li>there's something wrong with the input string, or</li>
<li><code>t</code> is the wrong type (e.g. <code>java.sql.Date</code> instead of <code>java.util.Date</code>, or some other type altogether), or is not declared.</li>
</ol>
<p>You should include details of the exception in your question to figure out which it is, but here's a working example using basically your own code, with the addition of a specific <code>Locale</code>.</p>
<pre><code>SimpleDateFormat ft = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
java.util.Date t=ft.parse("Sep 16, 2015 10:34:23 AM");
ft.applyPattern("MM.dd");
System.out.println(ft.format(t));
</code></pre>
<p>output:</p>
<pre><code>09.16
</code></pre> |
10,853,529 | Locking an object from being accessed by multiple threads - Objective-C | <p>I have a question regarding thread safety in Objective-C. I've read a couple of other answers, some of the Apple documentation, and still have some doubts regarding this, so thought I'd ask my own question.</p>
<p>My question is <strong>three fold</strong>:</p>
<p>Suppose I have an array, <code>NSMutableArray *myAwesomeArray;</code></p>
<p><strong>Fold 1:</strong> </p>
<p>Now correct me if I'm mistaken, but from what I understand, using <code>@synchronized(myAwesomeArray){...}</code> will prevent two threads from accessing the same block of code. So, basically, if I have something like:</p>
<pre><code>-(void)doSomething {
@synchronized(myAwesomeArray) {
//some read/write operation on myAwesomeArray
}
}
</code></pre>
<p>then, if two threads access the <strong>same</strong> method at the <strong>same</strong> time, that block of code will be thread safe. I'm guessing I've understood this part properly.</p>
<p><strong>Fold 2:</strong></p>
<p>What do I do if <code>myAwesomeArray</code> is being accessed by multiple threads from different methods?
If I have something like:</p>
<pre><code>- (void)readFromArrayAccessedByThreadOne {
//thread 1 reads from myAwesomeArray
}
- (void)writeToArrayAccessedByThreadTwo {
//thread 2 writes to myAwesomeArray
}
</code></pre>
<p>Now, both the methods are accessed by two different threads at the same time. How do I ensure that <code>myAwesomeArray</code> won't have problems? Do I use something like NSLock or NSRecursiveLock?</p>
<p><strong>Fold 3:</strong></p>
<p>Now, in the above two cases, <code>myAwesomeArray</code> was an iVar in memory. What if I have a database file, that I don't always keep in memory. I create a <code>databaseManagerInstance</code> whenever I want to perform database operations, and release it once I'm done. Thus, basically, different classes can access the database. Each class creates its own instance of <code>DatabaseManger</code>, but basically, they are all using the same, single database file. How do I ensure that data is not corrupted due to race conditions in such a situation?</p>
<p>This will help me clear out some of my fundamentals.</p> | 10,853,903 | 3 | 3 | null | 2012-06-01 15:51:37.62 UTC | 20 | 2017-12-01 08:58:32.723 UTC | 2017-12-01 08:58:32.723 UTC | null | 3,885,376 | null | 931,031 | null | 1 | 37 | objective-c|ios|multithreading | 29,861 | <p><strong>Fold 1</strong>
Generally your understanding of what <code>@synchronized</code> does is correct. However, technically, it doesn't make any code "thread-safe". It prevents different threads from aquiring the same lock at the same time, however you need to ensure that you always use the same synchronization token when performing critical sections. If you don't do it, you can still find yourself in the situation where two threads perform critical sections at the same time. <a href="http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html#//apple_ref/doc/uid/10000057i-CH8-SW3" rel="noreferrer">Check the docs</a>.</p>
<p><strong>Fold 2</strong>
Most people would probably advise you to use NSRecursiveLock. If I were you, I'd use GCD. <a href="http://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW3" rel="noreferrer">Here is a great document showing how to migrate from thread programming to GCD programming</a>, I think this approach to the problem is a lot better than the one based on NSLock. In a nutshell, you create a serial queue and dispatch your tasks into that queue. This way you ensure that your critical sections are handled serially, so there is only one critical section performed at any given time.</p>
<p><strong>Fold 3</strong>
This is the same as <em>Fold 2</em>, only more specific. Data base is a resource, by many means it's the same as the array or any other thing. <a href="https://github.com/ccgus/fmdb" rel="noreferrer">If you want to see the GCD based approach in database programming context, take a look at fmdb implementation</a>. It does exactly what I described in <em>Fold2</em>.</p>
<p>As a side note to <em>Fold 3</em>, I don't think that instantiating <em>DatabaseManager</em> each time you want to use the database and then releasing it is the correct approach. I think you should create one single database connection and retain it through your application session. This way it's easier to manage it. Again, fmdb is a great example on how this can be achieved.</p>
<p><strong>Edit</strong>
If don't want to use GCD then yes, you will need to use some kind of locking mechanism, and yes, <code>NSRecursiveLock</code> will prevent deadlocks if you use recursion in your methods, so it's a good choice (it is used by <code>@synchronized</code>). However, there may be one catch. If it's possible that many threads will wait for the same resource and the order in which they get access is relevant, then <code>NSRecursiveLock</code> is not enough. You may still manage this situation with <code>NSCondition</code>, but trust me, you will save a lot of time using GCD in this case. If the order of the threads is not relevant, you are safe with locks.</p> |
10,779,187 | What does the Unorderable Type error mean in Python? | <pre><code>from urllib.request import urlopen
page1 = urlopen("http://www.beans-r-us.biz/prices.html")
page2 = urlopen("http://www.beans-r-us.biz/prices-loyalty.html")
text1 = page1.read().decode("utf8")
text2 = page2.read().decode("utf8")
where = text2.find(">$")
start_of_price = where + 2
end_of_price = where + 6
price_loyal = text2[start_of_price:end_of_price]
price = text1[234:238]
password = 5501
p = input("Loyalty Customers Password? : ")
passkey = int(p)
if passkey == password:
while price_loyal > 4.74:
if price_loyal < 4.74:
print("Here is the loyal customers price :) :")
print(price_loyal)
else:
print( "Price is too high to make a profit, come back later :) ")
else:
print("Sorry incorrect password :(, here is the normal price :")
print(price)
input("Thanks for using our humble service, come again :), press enter to close this window.")
</code></pre>
<p>The problem I'm having is that it runs until I get the the 4.74 part. Then it stops and complains about an unorderable type. I'm completely confused as to what that means.</p> | 10,779,212 | 2 | 4 | null | 2012-05-28 03:58:16.077 UTC | null | 2012-05-28 04:46:48.973 UTC | 2012-05-28 04:16:47.013 UTC | null | 500,584 | null | 1,021,011 | null | 1 | 7 | python|python-3.x | 56,605 | <p><code>price_loyal</code> is a string (even if it contains numbers that you have found with <code>find</code>) that you are trying to compare to a numeric value (4.75)? For your comparison try </p>
<p><code>float(price_loyal)</code></p>
<p><strong>UPDATE</strong> (thanks @agf):</p>
<p>With Python <strong><em>v 3.x</em></strong> you get the error message you mentioned.</p>
<pre><code>>>> price_loyal = '555.5'
>>> price_loyal > 5000.0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
price_loyal > 5000.0
TypeError: unorderable types: str() > float()
>>>
</code></pre>
<p>whereas</p>
<pre><code>>>> float(price_loyal) > 5000.0
False
</code></pre>
<p>The version of Python makes a difference in this case, so probably a good idea to always mention what version one is working with. <em>Previously ... with Python <strong>v 2.x</em></strong></p>
<p>Your comparisons will be off without converting your <code>string</code> to a <code>float</code> first. E.g.,</p>
<pre><code>price_loyal
'555.5'
</code></pre>
<p>This comparison with string and float gives <code>True</code></p>
<pre><code>price_loyal > 5000.0
True
</code></pre>
<p>This comparison with float and float gives <code>False</code> as it should</p>
<pre><code>float(price_loyal) > 5000.0
False
</code></pre>
<p>There might be other problems, but this looks like one.</p> |
10,840,357 | String literal with triple quotes in function definitions | <p>I am following the Python tutorial and at some point they talk about how the 1st statement of a function can be a String Literal. As far as the example goes, this String Literal seems to be done with three <code>"</code>s, giving in the <a href="http://docs.python.org/release/2.7.3/tutorial/controlflow.html#defining-functions" rel="noreferrer">example</a></p>
<pre><code>"""Print a Fibonacci series up to n."""
</code></pre>
<p>According to this documentation, this would be used mainly to create some kind of automatically produced documentation.</p>
<p>So I am wondering if someone here could explain to me what are these string literals exactly?</p> | 10,840,410 | 6 | 4 | null | 2012-05-31 19:52:52.353 UTC | 17 | 2022-02-23 20:38:34.627 UTC | 2017-04-01 17:48:19.217 UTC | null | 2,301,450 | null | 1,079,301 | null | 1 | 61 | python|string|literals | 86,375 | <p>What you're talking about (I think) are called <a href="http://docs.python.org/tutorial/controlflow.html#documentation-strings" rel="noreferrer">docstrings</a> (Thanks Boud for the link).</p>
<pre><code>def foo():
"""This function does absolutely nothing"""
</code></pre>
<p>Now, if you type <code>help(foo)</code> from the interpreter, you'll get to see the string that I put in the function. You can also access that string by <code>foo.__doc__</code></p>
<p>Of course, string literals are just that -- literal strings.</p>
<pre><code>a = "This is a string literal" #the string on the right side is a string literal, "a" is a string variable.
</code></pre>
<p>or</p>
<pre><code>foo("I'm passing this string literal to a function")
</code></pre>
<p>They can be defined in a bunch of ways:</p>
<pre><code>'single quotes'
"double quotes"
""" triple-double quotes """ #This can contain line breaks!
</code></pre>
<p>or even </p>
<pre><code>#This can contain line breaks too! See?
''' triple-single
quotes '''
</code></pre> |
35,667,775 | State in redux/react app has a property with the name of the reducer | <p>I am creating an app using Redux and React. I run into a problem where I cannot map state to component properties since the state has a property that matches the name of the reducer I used.</p>
<p>The root reducer is created with <code>combineReducers</code> method </p>
<pre><code>const rootReducer = combineReducers({
appReducer
});
</code></pre>
<p>The initial state is </p>
<pre><code>const initialState = {
sources: [],
left: {},
right: {},
diff: {}
}
</code></pre>
<p>However in the component function <code>mapStateToProps</code>:</p>
<pre><code>function mapStateToProps(state) {
return {
sources: state.sources
}
}
</code></pre>
<p>The <code>state.sources</code> is <code>undefined</code> because the value of <code>state</code> parameter is </p>
<pre><code>{
appReducer: {
sources: [],
left: {},
right: {},
diff: {}
}
}
</code></pre>
<p>Is this a feature of redux? So when I use more reducers, all of them will add new property to <code>state</code> variable? Or is there something wrong on my side (I never noticed this behavior in redux tutorials).</p>
<p>Thanks</p> | 35,674,297 | 2 | 6 | null | 2016-02-27 09:00:42.373 UTC | 9 | 2018-04-09 17:19:07.413 UTC | 2018-04-09 17:19:07.413 UTC | null | 978,728 | null | 325,322 | null | 1 | 17 | javascript|reactjs|state|redux | 8,505 | <p>If you only have a single reducer, you don’t need <code>combineReducers()</code>. Just use it directly:</p>
<pre><code>const initialState = {
sources: [],
left: {},
right: {}
}
function app(state = initialState, action) {
switch (action.type) {
case 'ADD_SOURCE':
return Object.assign({}, state, {
sources: [...state.sources, action.newSource]
})
case 'ADD_SOURCE_TO_LEFT':
return Object.assign({}, state, {
left: Object.assign({}, state.left, {
[action.sourceId]: true
})
})
case 'ADD_SOURCE_TO_RIGHT':
return Object.assign({}, state, {
right: Object.assign({}, state.right, {
[action.sourceId]: true
})
})
default:
return state
}
}
</code></pre>
<p>Now you can create a store with that reducer:</p>
<pre><code>import { createStore } from 'redux'
const store = createStore(app)
</code></pre>
<p>And connect a component to it:</p>
<pre><code>const mapStateToProps = (state) => ({
sources: state.sources
})
</code></pre>
<p>However your reducer is hard to read because it update many different things at once. Now, <strong>this</strong> is the moment you want to split it into several independent reducers:</p>
<pre><code>function sources(state = [], action) {
switch (action.type) {
case 'ADD_SOURCE':
return [...state.sources, action.newSource]
default:
return state
}
}
function left(state = {}, action) {
switch (action.type) {
case 'ADD_SOURCE_TO_LEFT':
return Object.assign({}, state, {
[action.sourceId]: true
})
default:
return state
}
}
function right(state = {}, action) {
switch (action.type) {
case 'ADD_SOURCE_TO_RIGHT':
return Object.assign({}, state, {
[action.sourceId]: true
})
default:
return state
}
}
function app(state = {}, action) {
return {
sources: sources(state.sources, action),
left: left(state.left, action),
right: right(state.right, action),
}
}
</code></pre>
<p>This is easier to maintain and understand, and it also makes it easier to change and test reducers independently.</p>
<p>Finally, as the last step, we can use <code>combineReducers()</code> to generate the root <code>app</code> reducer instead of writing it by hand:</p>
<pre><code>// function app(state = {}, action) {
// return {
// sources: sources(state.sources, action),
// left: left(state.left, action),
// right: right(state.right, action),
// }
// }
import { combineReducers } from 'redux'
const app = combineReducers({
sources,
left,
right
})
</code></pre>
<p>There is no large benefit to using <code>combineReducers()</code> instead of writing the root reducer by hand except that it’s slightly more efficient and will likely save you a few typos. Also, you can apply this pattern more than once in your app: it’s fine to combine unrelated reducers into a single reducer several times in a nested way.</p>
<p>All this refactoring would have no effect on the components.</p>
<p>I would suggest you to watch my <a href="https://egghead.io/series/getting-started-with-redux">free Egghead course on Redux</a> which covers this pattern of <strong>reducer composition</strong> and shows how <code>combineReducers()</code> is implemented.</p> |
35,747,957 | Promise callbacks returning promises | <p>With regard to these great two sources: <a href="https://github.com/nzakas/understandinges6/blob/master/manuscript/11-Promises.md#returning-promises-in-promise-chains">NZakas - Returning Promises in Promise Chains</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">MDN Promises</a>, I would like to ask the following:</p>
<p>Each time that we return a value from a promise fulfillment handler, how is that value passed to the new promise returned from that same handler?</p>
<p>For instance,</p>
<pre><code>let p1 = new Promise(function(resolve, reject) {
resolve(42);
});
let p2 = new Promise(function(resolve, reject) {
resolve(43);
});
let p3 = p1.then(function(value) {
// first fulfillment handler
console.log(value); // 42
return p2;
});
p3.then(function(value) {
// second fulfillment handler
console.log(value); // 43
});
</code></pre>
<p>In this example, <code>p2</code> is a promise. <code>p3</code> is also a promise originating from <code>p1</code>'s fulfillment handler. However <code>p2 !== p3</code>. Instead <code>p2</code> somehow magically resolves to <code>43</code> (how?) and that value is then passed to <code>p3</code>'s fulfillment handler. Even the sentence here is confusing.</p>
<p>Could you please explain to me what exactly is going on here? I am totally confused over this concept.</p> | 35,748,696 | 4 | 6 | null | 2016-03-02 13:00:08.53 UTC | 23 | 2016-07-09 15:38:35.897 UTC | 2016-03-02 17:46:33.633 UTC | null | 1,048,572 | null | 178,728 | null | 1 | 57 | javascript|node.js|promise|es6-promise | 38,828 | <p>Let’s say that throwing inside <code>then()</code> callback rejects the result promise with a failure, and returning from <code>then()</code> callback fulfills the result promise with a success value.</p>
<pre><code>let p2 = p1.then(() => {
throw new Error('lol')
})
// p2 was rejected with Error('lol')
let p3 = p1.then(() => {
return 42
})
// p3 was fulfilled with 42
</code></pre>
<p>But sometimes, even inside the continuation, we don’t know whether we have succeeded or not. We need more time.</p>
<pre><code>return checkCache().then(cachedValue => {
if (cachedValue) {
return cachedValue
}
// I want to do some async work here
})
</code></pre>
<p>However, if I do async work there, it would be too late to <code>return</code> or <code>throw</code>, wouldn’t it?</p>
<pre><code>return checkCache().then(cachedValue => {
if (cachedValue) {
return cachedValue
}
fetchData().then(fetchedValue => {
// Doesn’t make sense: it’s too late to return from outer function by now.
// What do we do?
// return fetchedValue
})
})
</code></pre>
<p>This is why Promises wouldn’t be useful if you couldn’t <strong>resolve to another Promise</strong>.</p>
<p>It doesn’t mean that in your example <code>p2</code> would <em>become</em> <code>p3</code>. They are separate Promise objects. However, by returning <code>p2</code> from <code>then()</code> that produces <code>p3</code> you are saying <strong>“I want <code>p3</code> to resolve to whatever <code>p2</code> resolves, whether it succeeds or fails”.</strong></p>
<p>As for <em>how</em> this happens, it’s implementation-specific. Internally you can think of <code>then()</code> as creating a new Promise. The implementation will be able to fulfill or reject it whenever it likes. Normally, it will automatically fulfill or reject it when you return:</p>
<pre><code>// Warning: this is just an illustration
// and not a real implementation code.
// For example, it completely ignores
// the second then() argument for clarity,
// and completely ignores the Promises/A+
// requirement that continuations are
// run asynchronously.
then(callback) {
// Save these so we can manipulate
// the returned Promise when we are ready
let resolve, reject
// Imagine this._onFulfilled is an internal
// queue of code to run after current Promise resolves.
this._onFulfilled.push(() => {
let result, error, succeeded
try {
// Call your callback!
result = callback(this._result)
succeeded = true
} catch (err) {
error = err
succeeded = false
}
if (succeeded) {
// If your callback returned a value,
// fulfill the returned Promise to it
resolve(result)
} else {
// If your callback threw an error,
// reject the returned Promise with it
reject(error)
}
})
// then() returns a Promise
return new Promise((_resolve, _reject) => {
resolve = _resolve
reject = _reject
})
}
</code></pre>
<p>Again, this is very much pseudo-code but shows the idea behind how <code>then()</code> might be implemented in Promise implementations.</p>
<p>If we want to add support for resolving to a Promise, we just need to modify the code to have a special branch if the <code>callback</code> you pass to <code>then()</code> returned a Promise:</p>
<pre><code> if (succeeded) {
// If your callback returned a value,
// resolve the returned Promise to it...
if (typeof result.then === 'function') {
// ...unless it is a Promise itself,
// in which case we just pass our internal
// resolve and reject to then() of that Promise
result.then(resolve, reject)
} else {
resolve(result)
}
} else {
// If your callback threw an error,
// reject the returned Promise with it
reject(error)
}
})
</code></pre>
<p>Let me clarify again that this is not an actual Promise implementation and has big holes and incompatibilities. However it should give you an intuitive idea of how Promise libraries implement resolving to a Promise. After you are comfortable with the idea, I would recommend you to take a look at how actual Promise implementations <a href="https://github.com/zloirock/core-js/blob/master/modules/es6.promise.js#L87-L90" rel="noreferrer">handle this</a>.</p> |
13,329,853 | reading server file with javascript | <p>I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:</p>
<pre><code><IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>
</code></pre>
<p>and (with file_inhoud, lines defined elsewhere)</p>
<pre><code>function readFile() {
func="readFile=";
debug2("0");
var x=document.getElementById("myframe");
debug2("1");
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2("1a"+doc);
var file_inhoud=doc.document.body;
debug2("2:");
lines = file_inhoud.split("\n");
debug2("3");
fileloaded();
debug2("4");
}
</code></pre>
<p>Debug function shows:</p>
<pre><code>readFile=0//readFile=1//readFile=1a[object HTMLDocument]//
</code></pre>
<p>So statement that stops the program is:</p>
<pre><code>var file_inhoud=doc.document.body;
</code></pre>
<p>What is wrong? What is correct (or best) way to read this file?</p>
<p>Note: I see that the file is read and displayed in the frame.</p>
<p>Thanks!</p> | 13,329,895 | 2 | 4 | null | 2012-11-11 09:10:28.24 UTC | 7 | 2012-11-11 10:38:40.56 UTC | null | null | null | null | 1,798,023 | null | 1 | 7 | javascript|file | 52,142 | <p>The usual way to retrieve a text file (or any other server side resource) is to use <a href="https://developer.mozilla.org/en/docs/AJAX" rel="noreferrer">AJAX</a>. Here is an example of how you could alert the contents of a text file:</p>
<pre><code>var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();
</code></pre>
<p>The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it <a href="http://www.html5rocks.com/en/tutorials/file/dndfiles/" rel="noreferrer">here</a>.</p> |
13,323,993 | PHP 5.4: disable warning "Creating default object from empty value" | <p>I want to migrate code from PHP 5.2 to 5.4. This worked fine so far except that all the code I use makes extensive use of just using an object with a member without any initialisation, like:</p>
<pre><code>$MyObject->MyMember = "Hello";
</code></pre>
<p>which results in the warning: "Creating default object from empty value"</p>
<p>I know that the solution would be to use:</p>
<pre><code>$MyObject = new stdClass();
$MyObject->MyMember = "Hello";
</code></pre>
<p>but it would be A LOT OF WORK to change this in all my code, because I use this many times in different projects. I know, it's not good style, but unfortunately I'm not able to spend the next weeks adding this to all of my code.</p>
<p>I know I could set the php error_reporting to not reporting warnings, but I want to be able to still get other warnings and notices. This warning doesn't seem to be effected by enable or disable E_STRICT at all. So is there a way to just disable this warning?!</p> | 13,324,030 | 4 | 3 | null | 2012-11-10 16:53:47.767 UTC | 3 | 2014-02-04 18:28:12.533 UTC | 2013-04-26 20:26:57.29 UTC | null | 367,456 | null | 540,428 | null | 1 | 10 | php|error-reporting | 54,977 | <p>Technically you <em>could</em> do this by <a href="http://php.net/manual/en/function.set-error-handler.php">installing your own error handler</a> for warnings. From inside the handler check the string error message; if it's the one you want to suppress then <code>return true</code>, otherwise <code>return false</code> to let the default error handler do its thing.</p>
<p>However I would still recommend doing the right thing and manually fixing your code wherever this misuse does appear because, if nothing else, it gets you into the correct habit. Unless this is paid work (in which case there usually are concerns that override purity of implementation), consider this as a lesson and do the right thing.</p> |
13,331,722 | how to sort numerically in hadoop's shuffle/sort phase? | <p>The data looks like this, first field is a number,</p>
<pre><code>3 ...
1 ...
2 ...
11 ...
</code></pre>
<p>And I want to sort these lines according to the first field numerically instead of alphabetically, which means after sorting it should look like this,</p>
<pre><code>1 ...
2 ...
3 ...
11 ...
</code></pre>
<p>But hadoop keeps giving me this,</p>
<pre><code>1 ...
11 ...
2 ...
3 ...
</code></pre>
<p>How do correct it?</p> | 13,342,944 | 3 | 0 | null | 2012-11-11 13:52:07.88 UTC | 10 | 2018-10-15 12:05:22.493 UTC | null | null | null | null | 888,051 | null | 1 | 16 | sorting|hadoop | 11,194 | <p>Assuming you are using <strong>Hadoop Streaming</strong>, you need to use the <strong>KeyFieldBasedComparator</strong> class.</p>
<ol>
<li><p>-D mapred.output.key.comparator.class=org.apache.hadoop.mapred.lib.KeyFieldBasedComparator should be added to streaming command</p></li>
<li><p>You need to provide type of sorting required using mapred.text.key.comparator.options. Some useful ones are -n : numeric sort, -r : reverse sort</p></li>
</ol>
<p><strong>EXAMPLE</strong> : </p>
<p>Create an identity mapper and reducer with the following code</p>
<p>This is the <strong>mapper.py</strong> & <strong>reducer.py</strong> </p>
<pre><code>#!/usr/bin/env python
import sys
for line in sys.stdin:
print "%s" % (line.strip())
</code></pre>
<p>This is the <strong>input.txt</strong></p>
<pre><code>1
11
2
20
7
3
40
</code></pre>
<p>This is the <strong>Streaming</strong> command</p>
<pre><code>$HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar
-D mapred.output.key.comparator.class=org.apache.hadoop.mapred.lib.KeyFieldBasedComparator
-D mapred.text.key.comparator.options=-n
-input /user/input.txt
-output /user/output.txt
-file ~/mapper.py
-mapper ~/mapper.py
-file ~/reducer.py
-reducer ~/reducer.py
</code></pre>
<p>And you will get the required output </p>
<pre><code>1
2
3
7
11
20
40
</code></pre>
<p><strong>NOTE</strong> :</p>
<ol>
<li><p>I have used a simple one key input. If however you have multiple keys and/or partitions, you will have to edit mapred.text.key.comparator.options as needed. Since I do not know your use case , my example is limited to this</p></li>
<li><p>Identity mapper is needed since you will need atleast one mapper for a MR job to run.</p></li>
<li><p>Identity reducer is needed since shuffle/sort phase will not work if it is a pure map only job.</p></li>
</ol> |
13,604,655 | Tell AngularJs to return a new instance via Dependency Injection | <p>The use case is simple: I have two controllers sharing the same dependency <code>MyService</code>. This service is holding some state, lets sat <code>myVariable</code>. If I set it from <code>ControllerOne</code>, then it will be also spotted by <code>ControllerTwo</code>.</p>
<p>What I want is for each controller to have it's own instance of <code>MyService</code>, so that <code>myVariable</code> can be changed by each Controller without affecting the other.</p>
<p>To put it in another words - I want <strong>new instance</strong> to be returned by Dependency Injection, <strong>rather than singleton</strong>.</p> | 13,610,435 | 2 | 1 | null | 2012-11-28 12:04:07.89 UTC | 9 | 2015-02-04 23:38:09.447 UTC | null | null | null | null | 218,592 | null | 1 | 22 | javascript|angularjs | 11,778 | <p>Not as directly has you might hope. Service instances are created the first time they're retrieved by the injector and maintained by the injector... in other words, they're always singletons. <a href="https://github.com/angular/angular.js/blob/master/src/auto/injector.js">The magic happens in here</a>, particularly look at the <code>provider</code> function, which puts the provider instance in the providerCache object.</p>
<p>But don't lose hope, you could just as easily add constructors for whatever it is you want to share in a Service, if you so chose:</p>
<pre><code>app.factory('myService', [function() {
var i = 1;
function Foo() {
this.bar = "I'm Foo " + i++;
};
return {
Foo: Foo
};
}]);
app.controller('Ctrl1', function($scope, myService) {
$scope.foo = new myService.Foo();
console.log($scope.foo.bar) //I'm Foo 1
});
app.controller('Ctrl2', function($scope, myService) {
$scope.foo = new myService.Foo();
console.log($scope.foo.bar) //I'm Foo 2
});
</code></pre>
<p>EDIT: as the OP pointed out, there is also the <a href="http://docs.angularjs.org/api/AUTO.%24injector">$injector.instantiate</a>, which you can use to call JavaScript constructors outside of your controller. I'm not sure what the implications are of the testability here, but it does give you another way to inject code that will construct a new object for you.</p> |
13,703,823 | A custom ostream | <p>I need some guidance or pointers understanding how to implement a custom ostream. My requirements are:</p>
<ol>
<li>A class with a '<<' operator for several data types.</li>
<li>The intention is to send output to database. Each "line" should go to a separate record.</li>
<li>Each record most important field would be the text (or blob), but some other fields such as time, etc. can be mostly deduced automatically</li>
<li>buffering is important, as I don't want to go to database for every record.</li>
</ol>
<p>First, does it worth deriving from ostream? What do I get by deriving from ostream? What if my class simply implements few <code>operator<<</code> methods (including some custom data types). Which functionality do I get from ostream?</p>
<p>Assuming what I want is a class derived from ostream, I need some guidance understanding the relationship between the ostream and the streambuf classes. Which one do I need to implement? Looking at some samples, it appears that I don't need to derive from ostream at all, and just give the ostream constructor a custom streambuf. Is that true? is that the canonical approach?</p>
<p>Which virtual functions at the custom streambuf do i need to implement? I've seen some samples (including this site: <a href="https://stackoverflow.com/q/760301/341971">here</a> and <a href="https://stackoverflow.com/q/4366904/341971">here</a>, and few more), some override the <code>sync</code> method, and other override the <code>overflow</code> method. Which one should I override? Also, looking at the stringbuf and filebuf sources (Visual Studio or GCC) both those buffer classes implement many methods of the streambuf.</p>
<p>If a custom class derived from streambuf is required, would there be any benefit deriving from stringbuf (or any other class) instead of directly from streambuf?</p>
<p>As for "lines". I would like at least when my users of the class using the 'endl' manipulator to be a new line (i.e. record in database). Maybe - depends on effort - every '\n' character should be considered as a new record as well. Who do my custom ostream and/or streambuf get notified for each?</p> | 14,232,652 | 4 | 3 | null | 2012-12-04 13:15:19.117 UTC | 6 | 2017-11-01 11:06:33.09 UTC | 2017-05-23 10:31:31.273 UTC | null | -1 | null | 341,971 | null | 1 | 29 | c++ | 20,693 | <p>A custom destination for ostream means implementing your own ostreambuf. If you want your streambuf to actually buffer (i.e. don't connect to the database after each character), the easiest way to do that is by creating a class inheriting from <code>std::stringbuf</code>. The <strong>only</strong> function that you'll need to override is the <code>sync()</code> method, which is being called whenever the stream is flushed.</p>
<pre><code>class MyBuf : public std::stringbuf
{
public:
virtual int sync() {
// add this->str() to database here
// (optionally clear buffer afterwards)
}
};
</code></pre>
<p>You can then create a <code>std::ostream</code> using your buffer:</p>
<pre><code>MyBuf buff;
std::ostream stream(&buf)
</code></pre>
<p>Most people advised against redirecting the stream to a database, but they ignored my description that the database basically has a single blob field where all text is going to.
In rare cases, I might send data to a different field. This can be facilitated with custom attributes understood by my stream. For example:</p>
<pre><code>MyStream << "Some text " << process_id(1234) << "more text" << std::flush
</code></pre>
<p>The code above will create a record in the database with:</p>
<pre><code>blob: 'Some text more text'
process_id: 1234
</code></pre>
<p><code>process_id()</code> is a method returning a structure <code>ProcessID</code>. Then, in the implementation of my ostream, I have an <code>operator<<(ProcessID const& pid)</code>, which stores the process ID until it gets written. Works great!</p> |
13,444,800 | "undefined reference" to Virtual Base class destructor | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix">What is an undefined reference/unresolved external symbol error and how do I fix it?</a> </p>
</blockquote>
<p>I have some experience with Java, and am now doing a C++ course. I wanted to try writing an interface, but I have run into some trouble with destructors which I have not been able to resolve, even with the help on the Internet... Here's my code:</p>
<pre><code> class Force {
public:
virtual ~Force();
virtual VECTOR eval(VECTOR x, double t);
};
class InvSquare : public Force {
public:
InvSquare(double A) {
c = A;
}
~InvSquare(){};
VECTOR eval(VECTOR x, double t) { // omitted stuff }
private:
double c;
};
</code></pre>
<p>I have tried to declare a virtual destructor for the base class, and a non-virtual one for the derived class, but I get an error saying "undefined reference to `Force::~Force()'". What does it mean, and how can I fix it?</p>
<p>Forgive me if this is a silly question!</p>
<p>Thank you very much for your help,
noctilux</p> | 13,444,839 | 1 | 0 | null | 2012-11-18 21:29:24.703 UTC | 4 | 2012-11-18 21:46:45.947 UTC | 2017-05-23 12:03:08.86 UTC | null | -1 | null | 1,291,686 | null | 1 | 35 | c++|abstract-class|undefined-reference | 38,713 | <p>You've declared the destructor, but not defined it. Change the declaration to:</p>
<pre><code>virtual ~Force() {}
</code></pre>
<p>to define it to do nothing.</p>
<p>You also want to make all the functions in the abstract interface <em>pure virtual</em>, otherwise they will need to be defined too:</p>
<pre><code>virtual VECTOR eval(VECTOR x, double t) = 0;
</code></pre> |
13,783,759 | Concatenate network path + variable | <p>How can I concatenate this path with this variable?</p>
<pre><code>$file = "My file 01.txt" #The file name contains spaces
$readfile = gc "\\server01\folder01\" + ($file) #It doesn't work
</code></pre>
<p>Thanks</p> | 13,783,881 | 1 | 0 | null | 2012-12-09 01:22:18.347 UTC | 4 | 2020-02-25 18:29:15.16 UTC | null | null | null | null | 1,182,880 | null | 1 | 63 | powershell | 106,051 | <p>There are a couple of ways. The most simple:</p>
<pre><code>$readfile = gc \\server01\folder01\$file
</code></pre>
<p>Your approach was close:</p>
<pre><code>$readfile = gc ("\\server01\folder01\" + $file)
</code></pre>
<p>You can also use <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/join-path?view=powershell-7" rel="noreferrer">Join-Path</a> e.g.:</p>
<pre><code>$path = Join-Path \\server01\folder01 $file
$readfile = gc $path
</code></pre> |
3,520,622 | How to use fn:replace(string,pattern,replace) in XSLT | <p>How to use </p>
<pre><code> fn:replace(string,pattern,replace)
</code></pre>
<p>in XSLT</p>
<p>is it like < fn:replace(...)/>??</p> | 3,521,168 | 2 | 0 | null | 2010-08-19 10:00:26.28 UTC | 2 | 2019-12-17 10:45:53.807 UTC | null | null | null | null | 336,940 | null | 1 | 8 | xml|xslt | 43,983 | <p>The function is specified as follows:</p>
<pre><code>fn:replace($input, $pattern, $replacement, [$flags])
$input xs:string? the string to change
$pattern xs:string regular expression to match the areas to be replaced
$replacement xs:string the replacement string
$flags xs:string flags for multiline mode, case insensitivity, etc
return value xs:string
</code></pre>
<p>Note that <code>$pattern</code> is a <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a>, and the replacement string also has some special substitution syntax.</p>
<p>Here are some examples:</p>
<pre><code># simple replacement
replace('query', 'r', 'as') queasy
# character class
replace('query', '[ry]', 'l') quell
# capturing group substitution
replace('abc123', '([a-z])', '$1x') axbxcx123
# practical example
replace('2315551212', (231) 555-1212
'(\d{3})(\d{3})(\d{4})',
'($1) $2-$3'
)
</code></pre>
<h3>References</h3>
<ul>
<li><a href="http://www.xqueryfunctions.com/xq/c0008.html" rel="noreferrer">xqueryfunctions.com - Strings</a> - <a href="http://www.xqueryfunctions.com/xq/fn_replace.html" rel="noreferrer"><code>fn:replace</code></a></li>
<li><a href="http://www.w3.org/TR/xpath-functions/" rel="noreferrer">w3.org/XPath Functions</a> - <a href="http://www.w3.org/TR/xpath-functions/#func-replace" rel="noreferrer"><code>fn:replace</code></a>, <a href="http://www.w3.org/TR/xpath-functions/#func-replace" rel="noreferrer">Flags</a></li>
<li><a href="http://www.regular-expressions.info/" rel="noreferrer">regular-expressions.info</a> - a good tutorial</li>
</ul> |
3,900,740 | Android SQLite database shared between activities | <p>What is the best way to share one SQLite DB between several activities? Tables from the DB are shown in ListView, and also deleting/inserting records is to be performed. I heard something about Services, but did not find any example for my problem. Now I have SQLiteOpenHelper class for opening the DB. I close the DB in OnPause() and open it in onResume(). But I can't insert data to the DB from sub-activity, something goes wrong.</p> | 3,901,198 | 2 | 0 | null | 2010-10-10 14:40:03.79 UTC | 11 | 2019-02-03 23:26:21.017 UTC | 2019-02-03 23:26:21.017 UTC | null | 7,125,393 | user468311 | null | null | 1 | 10 | android|sqlite | 23,132 | <p>Create an Application class for your app. This will remain active in memory for as long as any part of your App is running. You can create your DB from the onCreate method and clean it up in the onTerminate method. (Note that there is no guarantee that onTerminate will be called, so you should be careful about what you depend upon here. However, since a SQLite database is just a file, and is agressively flushed, the close operation is a courtesy more than a necessity.)</p>
<p>You can access the application from any Activity via "getApplication", so the DB will always be available to you.</p>
<p>For more info, see <a href="http://developer.android.com/guide/appendix/faq/framework.html#3" rel="noreferrer">http://developer.android.com/guide/appendix/faq/framework.html#3</a>.</p>
<p>Update:</p>
<p>As requested, here's an example of using getApplication. It's really incredibly simple.</p>
<pre><code> SQLiteDatabase mDB;
@Override protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDB = ((MyApplication)getApplication()).mDB;
}
</code></pre>
<p>If every activity includes this code, then every activity will have its own mDB field which references the same underlying shared DB object.</p> |
3,893,626 | How to use AsyncTask to show a ProgressDialog while doing background work in Android? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/4591878/updating-progress-dialog-in-activity-from-asynctask">Updating progress dialog in Activity from AsyncTask</a> </p>
</blockquote>
<p>I am developing my first Android App and I need a ProgressDialog to be showed while a background task, in this case just a http call on the server, happens.
I did a bit of studying on this and also have already checked other threads related to this subject. </p>
<p><a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="nofollow noreferrer">http://developer.android.com/reference/android/os/AsyncTask.html</a></p>
<p><a href="https://stackoverflow.com/questions/3160205/android-show-progressdialog-until-activity-ui-finished-loading">Android show ProgressDialog until activity UI finished loading</a></p>
<p><a href="https://stackoverflow.com/questions/1979524/android-splashscreen">Android SplashScreen</a></p>
<p><a href="http://android-developers.blogspot.com/2009/05/painless-threading.html" rel="nofollow noreferrer">http://android-developers.blogspot.com/2009/05/painless-threading.html</a></p>
<p>Among others.</p>
<p>Than I got to write a bit of code: </p>
<p>1) In My Activity I declare a variable to be of type ProgressDialog</p>
<pre><code>public class LoginActivity extends Activity {
public static final String TAG = "LoginActivity";
protected ProgressDialog progressDialog;
...
</code></pre>
<p>2) I have also written an inner class to extend AsyncTask as required, here in the doInBackGround is where I call a static method which actually do the POST http request to the server, in the server side I have blocked the server response 20s to validate the progress dialog.</p>
<pre><code>class EfetuaLogin extends AsyncTask<Object, Void, String> {
private final static String TAG = "LoginActivity.EfetuaLogin";
@Override
protected void onPreExecute()
{
Log.d(TAG, "Executando onPreExecute de EfetuaLogin");
}
@SuppressWarnings("unchecked")
@Override
protected String doInBackground(Object... parametros) {
Log.d(TAG, "Executando doInBackground de EfetuaLogin");
Object[] params = parametros;
HttpClient httpClient = (HttpClient) params[0];
List<NameValuePair> listaParametros = (List<NameValuePair>) params[1];
String result = null;
try{
result = HttpProxy.httpPost(AnototudoMetadata.URL_AUTENTICACAO, httpClient, listaParametros);
}catch (IOException e) {
Log.e(TAG, "IOException, Sem conectividade com o servidor do Anototudo! " + e.getMessage());
e.printStackTrace();
return result;
}
return result;
}
@Override
protected void onPostExecute(String result)
{
progressDialog.dismiss();
}
}
</code></pre>
<p>3) When the button is pressed I than build the ProgressDialog anc call the AsyncTask I have created: </p>
<pre><code> OnClickListener loginListener = new OnClickListener() {
public void onClick(View v) {
//next line should start progress dialog in main thread ?????
progressDialog = ProgressDialog.show(LoginActivity.this, "Login in", "Wait a moment please", true, false);
//next couple of lines should do an ascyn call to server
EfetuaLogin efetuaLogin = new EfetuaLogin();
efetuaLogin.execute(params);
try {
//recover the server response and sets time out to be 25seconds
sResposta = efetuaLogin.get(25, TimeUnit.SECONDS);
</code></pre>
<p>Well, this is it, I believe this was suppose to show a progress dialog while the AsyncTask would query the server in background, but what I get is NO progress bar until server response arrives and than for a fraction of time(less than 1 second) the progress shows and the next Activity is called.</p>
<p>As I mentioned I have re-checked this code and simply can't find where I got it wrong.
Any suggestions?</p>
<p>Thank you in advance.</p>
<p>Hi, as suggested by Charlie Sheen(???) in the first answer for this thread I have tryied changing a bit of my code and now it is like(Unfortunatelly it is not working as expected so far): </p>
<pre><code>OnClickListener loginListener = new OnClickListener() {
public void onClick(View v) {
//async call????????
new EfetuaLogin().execute(params);
...
</code></pre>
<p>And than do all the work to deal with response in the AsyncTask: </p>
<pre><code>class EfetuaLogin extends AsyncTask<Object, Void, String> {
private final static String TAG = "LoginActivity.EfetuaLogin";
@Override
protected void onPreExecute()
{
super.onPreExecute();
Log.d(TAG, "Executando onPreExecute de EfetuaLogin");
//inicia diálogo de progresso, mostranto processamento com servidor.
progressDialog = ProgressDialog.show(LoginActivity.this, "Autenticando", "Contactando o servidor, por favor, aguarde alguns instantes.", true, false);
}
@SuppressWarnings("unchecked")
@Override
protected String doInBackground(Object... parametros) {
Log.d(TAG, "Executando doInBackground de EfetuaLogin");
Object[] params = parametros;
HttpClient httpClient = (HttpClient) params[0];
List<NameValuePair> listaParametros = (List<NameValuePair>) params[1];
String result = null;
try{
result = HttpProxy.httpPost(AnototudoMetadata.URL_AUTENTICACAO, httpClient, listaParametros);
}catch (IOException e) {
Log.e(TAG, "IOException, Sem conectividade com o servidor do Anototudo! " + e.getMessage());
e.printStackTrace();
return result;
}
return result;
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if (result == null || result.equals("")) {
progressDialog.dismiss();
Alerta
.popupAlertaComBotaoOK(
"Dados incorretos",
"Os dados informados não foram encontrados no Sistema! Informe novamente ou cadastre-se antes pela internet.",
LoginActivity.this);
return;
}
Log.d(TAG, "Login passou persistindo info de login local no device");
ContentValues contentValues = new ContentValues();
contentValues.put(AnototudoMetadata.LOGIN_EMAIL, sLogin);
contentValues.put(AnototudoMetadata.LOGIN_SENHA, sSenha);
contentValues.put(AnototudoMetadata.LOGIN_SENHA_GERADA, result);
LoginDB loginDB = new LoginDB();
loginDB.addLogin(LoginActivity.this, contentValues);
Log.d(TAG, "Persistiu info de login no device, redirecionando para menu principal do Anototudo");
Log.d(TAG, "O retorno da chamada foi ==>> " + result);
// tudo ok chama menu principal
Log.d(TAG, "Device foi corretametne autenticado, chamando tela do menu principal do Anototudo.");
String actionName = "br.com.anototudo.intent.action.MainMenuView";
Intent intent = new Intent(actionName);
LoginActivity.this.startActivity(intent);
progressDialog.dismiss();
}
}
</code></pre>
<p>Complete OnClickListener: </p>
<pre><code>OnClickListener loginListener = new OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "Usuario logado, chamando menu principal");
TextView tLogin = (TextView) findViewById(R.id.loginText);
TextView tSenha = (TextView) findViewById(R.id.senhaText);
String sLogin = tLogin.getText().toString();
String sSenha = tSenha.getText().toString();
if (sLogin.equals("") | sSenha.equals("")) {
Alerta.popupAlertaComBotaoOK("Campos Obrigatórios",
"Os campos Login e Senha são obrigatórios para autenticação do Anototudo.", LoginActivity.this);
return;
} else {
Pattern regEx = Pattern.compile(".+@.+\\.[a-z]+");
Matcher matcher = regEx.matcher(sLogin);
if (!matcher.matches()) {
Alerta.popupAlertaComBotaoOK("Formato e-mail inválido", "O formato do campo e-mail está inválido",
LoginActivity.this);
return;
}
}
List<NameValuePair> listaParametros = new ArrayList<NameValuePair>();
listaParametros.add(new BasicNameValuePair("login", sLogin));
listaParametros.add(new BasicNameValuePair("senha", sSenha));
Log.d(TAG, "valores recuperados dos campos de login e senha: " + sLogin + " | " + sSenha);
// Reutiliza cliente HttpClient disponibilizado pela Aplicação.
AnototudoApp atapp = (AnototudoApp) LoginActivity.this.getApplication();
HttpClient httpClient = atapp.getHttpClient();
//prepara lista de parametros para fazer chamada asíncrona no servidor para autenticar.
Object[] params = new Object[2];
params[0] = httpClient;
params[1] = listaParametros;
//faz chamada assincrona
new EfetuaLogin().execute(params);
}
};
</code></pre> | 3,893,691 | 2 | 0 | null | 2010-10-08 19:18:46.427 UTC | 10 | 2018-04-04 13:34:46.46 UTC | 2017-05-23 12:25:19.91 UTC | null | -1 | null | 442,041 | null | 1 | 21 | android|android-asynctask|progressdialog | 74,318 | <p>Place your <code>ProgressDialog</code> in <code>onPreExecute</code>, sample code below:</p>
<pre><code>private ProgressDialog pdia;
@Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(yourContext);
pdia.setMessage("Loading...");
pdia.show();
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pdia.dismiss();
}
</code></pre>
<p>and in your <code>onClickListener</code>, just put this line inside:</p>
<pre><code>new EfetuaLogin().execute(null, null , null);
</code></pre> |
9,535,224 | Concatenate Two Values On Insert - SQL | <p>I'm attempting to accomplish what seems to be something simple, but I'm unable to find a solution - I'm probably wording it incorrectly.</p>
<p>I have a third party software that outputs date and time as two separate values, one for date and the other for time, and I need to be able to <code>INSERT</code> that data as one <code>datetime</code> field into SQL. </p>
<p>The third party software is built on a proprietary language based on .NET, and using SQL Server 2005.</p>
<p>Here are my two values in the software: </p>
<pre><code>let cbdate1 = cbdate
let cbtime1 = cbhr & ":" & cbmn & ":00 " & ampm
</code></pre>
<p>And then the SQL would go as:</p>
<pre><code>DOSQL "INSERT INTO Leads (DateTimeField) VALUES (cbdate1 + ' ' + cbtime1)"
</code></pre>
<p>So essentially, I am attempting to join the two values upon insert into the table. That does not work, and I'm unable to direct myself to find an appropriate answer.</p>
<p><strong>Additional Information:</strong> </p>
<p>The Date (cbdate1) is presented as "MM/DD/YYYY" and the Time is simply joined as presented "HH:MM:00 AM"</p> | 9,535,281 | 3 | 2 | null | 2012-03-02 14:50:00.08 UTC | 1 | 2012-03-02 16:25:38.173 UTC | 2012-03-02 15:18:20.457 UTC | null | 570,508 | null | 570,508 | null | 1 | 3 | sql|sql-server|syntax|insert | 39,226 | <p>You are currently using double quotes you should instead use single quotes since that is a valid string in SQL.</p>
<pre><code> DOSQL "INSERT INTO Leads (DateTimeField) VALUES (cbdate1 + ' ' + cbtime1)"
</code></pre>
<p><b>Edit:</b><br></p>
<p>Now if you get further problems it might be because your <code>DateTimeField</code> is a <code>datetime</code> datatype. Now you could then after concatenating convert or cast the string to the <b><a href="http://msdn.microsoft.com/en-us/library/ms187928.aspx" rel="nofollow">correct format</a></b>.</p>
<p><b>Like:</b></p>
<pre><code> DOSQL "INSERT INTO Leads (DateTimeField) VALUES (Convert(datetime, cbdate1 + ' ' + cbtime1))"
</code></pre>
<p><b>Edit #2:</b><br></p>
<p>Without a 24 hour part you would need a mon dd yyyy format ex: Oct 22 2012. Otherwise you might have to try and get the time part into a 24 hour format. </p> |
16,513,969 | Ruby Uninitialized Constant NameError for Class Name | <p>I want to inherit a sub-class from a parent-class.</p>
<p>Here is my code. 3 classes are created in 3 separate files.</p>
<pre><code>class Transportation
#codes
end
class Plane < Transportation
#codes
end
class Boat < Transportation
#codes
end
</code></pre>
<p>And when I was running this code, I got the error for Boat, but no issue for Plane when I only have Plane created:</p>
<pre><code>uninitialized constant Transportation (NameError)
</code></pre>
<p>Can anyone help me with this issue?</p>
<p>Thanks</p> | 16,514,057 | 1 | 4 | null | 2013-05-13 02:04:48.167 UTC | 3 | 2018-01-28 17:50:09.41 UTC | 2013-05-15 00:26:04.36 UTC | null | 1,684,830 | null | 1,684,830 | null | 1 | 24 | ruby | 62,982 | <p>There is no reason for this code to fail, unless the definition of <code>Transportation</code> is in another file.</p>
<p>If that is the case, and these are in different files, don't forget to require the file with the <code>Transportation</code> class before the other file with the usage in it.</p>
<p>As you mentioned, there are three different files.</p>
<p>You can create a file that has the required libraries. Perhaps it is in your <code>bin/transport_simulator.rb</code> file.</p>
<pre><code>require 'transportation'
require 'boat'
require 'plane'
</code></pre>
<p>Now they will be required in the proper order, and the files with the classes that subclass Transportation will know about that class.</p> |
16,265,733 | "Failure Delivering Result " - onActivityForResult | <p>I have a <code>LoginActivity</code> (User Logs in). It is basically its own <code>Activity</code> that is themed like a dialog (to appear as if a dialog). It appears over a <code>SherlockFragmentActivity</code>. What I want is: If there is a successful login, there should be two <code>FragmentTransaction</code>'s to update the view. Here is the code:</p>
<p>In <code>LoginActivity</code>, if successful login,</p>
<pre><code>setResult(1, new Intent());
</code></pre>
<p>In <code>SherlockFragmentActivity</code>:</p>
<pre><code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 1) {
LoggedStatus = PrefActivity.getUserLoggedInStatus(this);
FragmentTransaction t = MainFragmentActivity.this.getSupportFragmentManager().beginTransaction();
SherlockListFragment mFrag = new MasterFragment();
t.replace(R.id.menu_frame, mFrag);
t.commit();
// Set up Main Screen
FragmentTransaction t2 = MainFragmentActivity.this.getSupportFragmentManager().beginTransaction();
SherlockListFragment mainFrag = new FeaturedFragment();
t2.replace(R.id.main_frag, mainFrag);
t2.commit();
}
}
</code></pre>
<p>It crashes on the first commit, with this LogCat:</p>
<pre><code>E/AndroidRuntime(32072): Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
E/AndroidRuntime(32072): at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1299)
E/AndroidRuntime(32072): at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1310)
E/AndroidRuntime(32072): at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:541)
E/AndroidRuntime(32072): at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:525)
E/AndroidRuntime(32072): at com.kickinglettuce.rate_this.MainFragmentActivity.onActivityResult(MainFragmentActivity.java:243)
E/AndroidRuntime(32072): at android.app.Activity.dispatchActivityResult(Activity.java:5293)
E/AndroidRuntime(32072): at android.app.ActivityThread.deliverResults(ActivityThread.java:3315)
</code></pre> | 18,345,899 | 5 | 1 | null | 2013-04-28 17:39:55.787 UTC | 54 | 2018-02-18 03:06:04.053 UTC | 2018-02-18 03:06:04.053 UTC | null | 3,478,852 | null | 1,078,678 | null | 1 | 76 | android|android-intent|android-activity|android-fragmentactivity | 43,769 | <p>First of all, you should read my <a href="http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html" rel="noreferrer"><strong>blog post</strong></a> for more information (it talks about why this exception happens and what you can do to prevent it).</p>
<p>Calling <code>commitAllowingStateLoss()</code> is more of a hack than a fix. State loss is bad and should be avoided at all costs. At the time that <code>onActivityResult()</code> is called, the activity/fragment's state may not yet have been restored, and therefore any transactions that happen during this time will be lost as a result. This is a very important bug which must be addressed! (Note that the bug only happens when your <code>Activity</code> is coming back after having been killed by the system... which, depending on how much memory the device has, can sometimes be rare... so this sort of bug is not something that is very easy to catch while testing).</p>
<p>Try moving your transactions into <code>onPostResume()</code> instead (note that <code>onPostResume()</code> is always called after <code>onResume()</code> and <code>onResume()</code> is always called after <code>onActivityResult()</code>):</p>
<pre><code>private boolean mReturningWithResult = false;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mReturningWithResult = true;
}
@Override
protected void onPostResume() {
super.onPostResume();
if (mReturningWithResult) {
// Commit your transactions here.
}
// Reset the boolean flag back to false for next time.
mReturningWithResult = false;
}
</code></pre>
<p>This might seem a little weird, but doing this sort of thing is necessary to ensure that your <code>FragmentTransaction</code>s are always committed <em>after</em> the <code>Activity</code>'s state has been restored to its original state (<code>onPostResume()</code> is guaranteed to be called after the <code>Activity</code>'s state has been restored).</p> |
17,568,470 | Holding android bluetooth connection through multiple activities | <p>I am building an Android app that communicates with an Arduino board via bluetooth, I have the bluetooth code in a class of it's own called BlueComms. To connect to the device I use the following methord: </p>
<pre><code>public boolean connectDevice() {
CheckBt();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, "Connecting to ... " + device);
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
outStream = btSocket.getOutputStream();
Log.d(TAG, "Connection made.");
return true;
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "Unable to end the connection");
return false;
}
Log.d(TAG, "Socket creation failed");
}
return false;
}
private void CheckBt() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
System.out.println("Bt dsbld");
}
if (mBluetoothAdapter == null) {
System.out.println("Bt null");
}
}
</code></pre>
<p>This connects fine but as soon as I leave the activity I connected through it drops the connection, showing this through LogCat, </p>
<pre><code> D/dalvikvm(21623): GC_CONCURRENT freed 103K, 10% free 2776K/3056K, paused 5ms+2ms, total 35ms
</code></pre>
<p>I can no longer connect to the device, but if I call killBt() it throws a fatal error and if I try to send data I get a 'Socket creation failed' error. My send message code is as follows: </p>
<pre><code>public void sendData(String data, int recvAct) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "Bug BEFORE Sending stuff", e);
}
String message = data;
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "Bug while sending stuff", e);
}
}
</code></pre>
<p>How should I go about preventing the connection from being paused by the activity I connect with when I switch a different activity, I am switching activities with this code: </p>
<pre><code>Intent myIntent = new Intent(v.getContext(), Timelapse.class);
startActivityForResult(myIntent, 0);
</code></pre>
<p>Many Thanks,
Rozz</p> | 17,569,897 | 4 | 0 | null | 2013-07-10 10:38:08.517 UTC | 9 | 2017-05-04 09:06:38.033 UTC | null | null | null | null | 2,167,664 | null | 1 | 6 | android|android-intent|android-activity|bluetooth|onpause | 22,009 | <p>Where did you store the instance of your BlueComms class? If you put it in the first activity then the class instance would have been killed when that activity was destroyed as you left it and moved to the next activity (NB activities also get destroyed on screen rotation)</p>
<p>So you need to find a way to keep the instance of BlueComms class alive for as long as you need it. You could pass it between activities via public properties and store it in onRetainNonConfigurationInstance() during rotations.</p>
<p>An easier trick is to create a class that extends <code>Application</code> use it as the application delegate for your app and add public property to it to store the instance of BlueComms class within it. That way the instance of BlueComms class would be alive for the lifetime of you app.</p>
<p>Extend Application</p>
<pre><code>import android.app.Application;
public class cBaseApplication extends Application {
public BlueComms myBlueComms;
@Override
public void onCreate()
{
super.onCreate();
myBlueComms = new BlueComms();
}
}
</code></pre>
<p>Make your class the application delegate in the app manifest</p>
<pre><code><application
android:name="your.app.namespace.cBaseApplication"
android:icon="@drawable/icon"
android:label="@string/app_name" >
</code></pre>
<p>Access the base app from any of your Activities like this</p>
<pre><code>((cBaseApplication)this.getApplicationContext()).myBlueComms.SomeMethod();
</code></pre> |
17,420,558 | How to optimize OpenCL code for neighbors accessing? | <p><strong>Edit</strong>: Proposed solutions results are added at the end of the question.</p>
<p>I'm starting to program with OpenCL, and I have created a naive implementation of my problem.</p>
<p>The theory is: I have a 3D grid of elements, where each elements has a bunch of information (around 200 bytes). Every step, every element access its neighbors information and accumulates this information to prepare to update itself. After that there is a step where each element updates itself with the information gathered before. This process is executed iteratively.</p>
<p>My OpenCL implementation is: I create an OpenCL buffer of 1 dimension, fill it with structs representing the elements, which have an "int neighbors<a href="http://developer.amd.com/wordpress/media/2012/10/Optimizations-ImageConvolution1.pdf" rel="nofollow noreferrer"> 6 </a> " where I store the index of the neighbors in the Buffer. I launch a kernel that consults the neighbors and accumulate their information into element variables not consulted in this step, and then I launch another kernel that uses this variables to update the elements. These kernels use __global variables only.</p>
<p>Sample code:</p>
<pre><code>typedef struct{
float4 var1;
float4 var2;
float4 nextStepVar1;
int neighbors[8];
int var3;
int nextStepVar2;
bool var4;
} Element;
__kernel void step1(__global Element *elements, int nelements){
int id = get_global_id(0);
if (id >= nelements){
return;
}
Element elem = elements[id];
for (int i=0; i < 6; ++i){
if (elem.neighbors[i] != -1){
//Gather information of the neighbor and accumulate it in elem.nextStepVars
}
}
elements[id] = elem;
}
__kernel void step2(__global Element *elements, int nelements){
int id = get_global_id(0);
if (id >= nelements){
return;
}
Element elem = elements[id];
//update elem variables by using elem.nextStepVariables
//restart elem.nextStepVariables
}
</code></pre>
<p>Right now, my OpenCL implementation takes basically the same time than my C++ implementation.</p>
<p>So, the question is: How would you (the experts :P) address this problem?
I have read about 3D images, to store the information and change the neighborhood accessing pattern by changing the NDRange to a 3D one. Also, I have read about __local memory, to first load all the neighborhood in a workgroup, synchronize with a barrier and then use them, so that accesses to memory are reduced.</p>
<p>Could you give me some tips to optimize a process like the one I described, and if possible, give me some snippets?</p>
<p><strong>Edit</strong>: Third and fifth optimizations proposed by <a href="https://stackoverflow.com/users/1470092/huseyin-tugrul-buyukisik">Huseyin Tugrul</a> were already in the code. As mentioned <a href="https://stackoverflow.com/questions/8994219/i-need-help-understanding-data-alignment-in-opencls-buffers">here</a>, to make structs behave properly, they need to satisfy some restrictions, so it is worth understanding that to avoid headaches.</p>
<p><strong>Edit 1</strong>: Applying the seventh optimization proposed by <a href="https://stackoverflow.com/users/1470092/huseyin-tugrul-buyukisik">Huseyin Tugrul</a> performance increased from 7 fps to 60 fps. In a more general experimentation, the performance gain was about x8.</p>
<p><strong>Edit 2</strong>: Applying the first optimization proposed by <a href="https://stackoverflow.com/users/1470092/huseyin-tugrul-buyukisik">Huseyin Tugrul</a> performance increased about x1.2 . I think that the real gain is higher, but hides because of another bottleneck not yet solved.</p>
<p><strong>Edit 3</strong>: Applying the 8th and 9th optimizations proposed by <a href="https://stackoverflow.com/users/1470092/huseyin-tugrul-buyukisik">Huseyin Tugrul</a> didn't change performance, because of the lack of significant code taking advantage of these optimizations, worth trying in other kernels though.</p>
<p><strong>Edit 4</strong>: Passing invariant arguments (such as n_elements or workgroupsize) to the kernels as #DEFINEs instead of kernel args, as mentioned <a href="http://developer.amd.com/wordpress/media/2012/10/Optimizations-ImageConvolution1.pdf" rel="nofollow noreferrer">here</a>, increased performance around x1.33. As explained in the document, this is because of the aggressive optimizations that the compiler can do when knowing the variables at compile-time.</p>
<p><strong>Edit 5</strong>: Applying the second optimization proposed by <a href="https://stackoverflow.com/users/1470092/huseyin-tugrul-buyukisik">Huseyin Tugrul</a>, but using 1 bit per neighbor and using bitwise operations to check if neighbor is present (so, if neighbors & 1 != 0, top neighbor is present, if neighbors & 2 != 0, bot neighbor is present, if neighbors & 4 != 0, right neighbor is present, etc), increased performance by a factor of x1.11. I think this was mostly because of the data transfer reduction, because the data movement was, and keeps being my bottleneck. Soon I will try to get rid of the dummy variables used to add padding to my structs.</p>
<p><strong>Edit 6</strong>: By eliminating the structs that I was using, and creating separated buffers for each property, I eliminated the padding variables, saving space, and was able to optimize the global memory access and local memory allocation. Performance increased by a factor of x1.25, which is very good. Worth doing this, despite the programmatic complexity and unreadability.</p> | 17,422,055 | 1 | 30 | null | 2013-07-02 08:10:42.343 UTC | 11 | 2020-08-08 00:57:36.393 UTC | 2020-08-08 00:57:36.393 UTC | null | 214,143 | null | 1,162,522 | null | 1 | 11 | optimization|opencl|gpgpu|memory-access | 3,894 | <p>According to your step1 and step2, you are not making your gpu core work hard. What is your kernel's complexity? What is your gpu usage? Did you check with monitoring programs like afterburner? Mid-range desktop gaming cards can get 10k threads each doing 10k iterations.</p>
<p>Since you are working with only neighbours, data size/calculation size is too big and your kernels may be bottlenecked by vram bandiwdth. Your main system ram could be as fast as your pci-e bandwidth and this could be the issue.</p>
<p><strong>1) Use of Dedicated Cache</strong> could be getting you thread's actual grid cell into private registers that is fastest. Then neighbours into __local array so the comparisons/calc only done in chip.</p>
<p>Load current cell into __private</p>
<p>Load neighbours into __local</p>
<p>start looping for local array</p>
<p>get next neighbour into __private from __local</p>
<p>compute</p>
<p>end loop</p>
<p>(if it has many neighbours, lines after "Load neighbours into __local" can be in another loop that gets from main memory by patches)</p>
<p>What is your gpu? Nice it is GTX660. You should have 64kB controllable cache per compute unit. CPUs have only registers of 1kB and not addressable for array operations.</p>
<p><strong>2) Shorter Indexing</strong> could be using a single byte as index of neighbour stored instead of int. Saving precious L1 cache space from "id" fetches is important so that other threads can hit L1 cache more! </p>
<p>Example: </p>
<pre><code> 0=neighbour from left
1=neighbour from right
2=neighbour from up
3=neighbour from down
4=neighbour from front
5=neighbour from back
6=neighbour from upper left
...
...
</code></pre>
<p>so you can just derive neighbour index from a single byte instead of 4-byte int which decreases main memory accessing for at least neighbour accessing. Your kernel will derive neighbour index from upper table using its compute power, not memory power because you would make this from core registers(__privates). If your total grid size is constant, this is very easy such as just adding 1 actual cell id, adding 256 to id or adding 256*256 to id or so.</p>
<p><strong>3) Optimum Object Size</strong> could be making your struct/cell-object size a multiple of 4 bytes. If your total object size is around 200-bytes, you can pad it or augment it with some empty bytes to make exactly 200 bytes, 220Bytes or 256 bytes.</p>
<p><strong>4) Branchless Code</strong> (<strong>Edit:</strong> depends!) using less if-statements. Using if-statement makes computation much slower. Rather than checking for -1 as end of neightbour index , you can use another way . Becuase lightweight core are not as capable of heavyweight. You can use surface-buffer-cells to wrap the surface so computed-cells will have always have 6-neighbours so you get rid of if (elem.neighbors[i] != -1) . Worth a try especially for GPU.</p>
<p>Just computing all neighbours are faster rather than doing if-statement. Just multiply the result change with zero when it is not a valid neighbour. How can we know that it is not a valid neighbour? By using a byte array of 6-elements per cell(parallel to neighbour id array)(invalid=0, valid=1 -->multiply the result with this) </p>
<p>The if-statement is inside a loop which counting for six times. Loop unrolling gives similar speed-up if the workload in the loop is relatively easy.</p>
<p>But, if all threads within same warp goes into same if-or-else branch, they don't lose performance. So this depends wheter your code diverges or not.</p>
<p><strong>5) Data Elements Reordering</strong> you can move the int[8] element to uppermost side of struct so memory accessing may become more yielding so smaller sized elements to lower side can be read in a single read-operation.</p>
<p><strong>6) Size of Workgroup</strong> trying different local workgroup size can give 2-3x performance. Starting from 16 until 512 gives different results. For example, AMD GPUs like integer multiple of 64 while NVIDIA GPUs like integer multiple of 32. INTEL does fine at 8 to anything since it can meld multiple compute units together to work on same workgroup.</p>
<p><strong>7) Separation of Variables</strong>(only if you cant get rid of if-statements) Separation of comparison elements from struct. This way you dont need to load a whole struct from main memory just to compare an int or a boolean. When comparison needs, then loads the struct from main memory(if you have local mem optimization already, then you should put this operation before it so loading into local mem is only done for selected neighbours)</p>
<p>This optimisation makes best case(no neighbour or only one eighbour) considerably faster. Does not affect worst case(maximum neighbours case).</p>
<p><strong>8a) Magic</strong> Using shifting instead of dividing by power of 2. Doing similar for modulo. Putting "f" at the end of floating literals(1.0f instead of 1.0) to avoid automatic conversion from double to float.</p>
<p><strong>8b) Magic-2</strong> -cl-mad-enable Compiler option can increase multiply+add operation speed.</p>
<p><strong>9) Latency Hiding</strong> Execution configuration optimization. You need to hide memory access latency and take care of occupancy.</p>
<pre><code> Get maximum cycles of latency for instructions and global memory access.
Then divide memory latency by instruction latency.
Now you have the ratio of: arithmetic instruction number per memory access to hide latency.
If you have to use N instructions to hide mem latency and you have only M instructions in your code, then you will need N/M warps(wavefronts?) to hide latency because a thread in gpu can do arithmetics while other thread getting things from mem.
</code></pre>
<p><strong>10) Mixed Type Computing</strong> After memory access is optimized, swap or move some instructions where applicable to get better occupancy, use half-type to help floating point operations where precision is not important.</p>
<p><strong>11) Latency Hiding again</strong> Try your kernel code with only arithmetics(comment out all mem accesses and initiate them with 0 or sometihng you like) then try your kernel code with only memory access instructions(comment out calculations/ ifs)</p>
<p>Compare kernel times with original kernel time. Which is affeecting the originatl time more? Concentrate on that..</p>
<p><strong>12) Lane & Bank Conflicts</strong> Correct any LDS-lane conflicts and global memory bank conflicts because same address accessings can be done in a serialed way slowing process(newer cards have broadcast ability to reduce this)</p>
<p><strong>13) Using registers</strong> Try to replace any independent locals with privates since your GPU can give nearly 10TB/s throughput using registers.</p>
<p><strong>14) Not Using Registers</strong> Dont use too many registers or they will spill to global memory and slow the process.</p>
<p><strong>15) Minimalistic Approach for Occupation</strong> Look at local/private usage to get an idea of occupation. If you use much more local and privates then less threads can be utilized in same compute unit and leading lesser occupation. Less resource usage leads higher chance of occupation(if you have enough total threads)</p>
<p><strong>16) Gather Scatter</strong> When neighbours are different particles(like an nbody NNS) from random addresses of memory, its maybe hard to apply but, <strong>gather read</strong> optimization can give 2x-3x speed on top of before optimizations (needs local memory optimization to work) so it reads in an order from memory instead of randomly and reorders as needed in the local memory to share between (scatter) to threads.</p>
<p><strong>17) Divide and Conquer</strong> Just in case when buffer is too big and copied between host and device so makes gpu wait idle, then divide it in two, send them separately, start computing as soon as one arrives, send results back concurrently in the end. Even a process-level parallelism could push a gpu to its limits this way. Also L2 cache of GPU may not be enough for whole of data. Cache-tiled computing but implicitly done instead of direct usage of local memory.</p>
<p><strong>18)</strong> <strong>Bandwidth from memory qualifiers</strong>. When kernel needs some extra 'read' bandwidth, you can use '__constant'(instead of __global) keyword on some parameters which are less in size and only for reading. If those parameters are too large then you can still have good streaming from '__read_only' qualifier(after the '__global' qualifier). Similary '__write_only' increases throughput but these give mostly hardware-specific performance. If it is Amd's HD5000 series, constant is good. Maybe GTX660 is faster with its cache so __read_only may become more usable(or Nvidia using cache for __constant?).</p>
<p>Have three parts of same buffer with one as __global __read_only, one as __constant and one as just __global (if building them doesn't penalty more than reads' benefits).</p>
<p>Just tested my card using AMD APP SDK examples, LDS bandwidth shows 2TB/s while constant is 5TB/s(same indexing instead of linear/random) and main memory is 120 GB/s.</p>
<p>Also don't forget to add <strong>restrict</strong> to kernel parameters where possible. This lets compiler do more optimizations on them(if you are not aliasing them).</p>
<p><strong>19)</strong> <strong>Modern hardware transcendental functions are faster than old bit hack (like Quake-3 fast inverse square root) versions</strong></p>
<p><strong>20)</strong> <strong>Now there is Opencl 2.0 which enables spawning kernels inside kernels so you can further increase resolution in a 2d grid point and offload it to workgroup when needed (something like increasing vorticity detail on edges of a fluid dynamically)</strong></p>
<p>A profiler can help for all those, but any FPS indicator can do if only single optimization is done per step. </p>
<p>Even if benchmarking is not for architecture-dependent code paths, you could try having a multiple of 192 number of dots per row in your compute space since your gpu has multiple of that number of cores and benchmark that if it makes gpu more occupied and have more gigafloatingpoint operations per second.</p>
<p>There must be still some room for optimization after all these options, but idk if it damages your card or feasible for production time of your projects. For example:</p>
<p><strong>21)</strong> <strong>Lookup tables</strong> When there is 10% more memory bandwidth headroom but no compute power headroom, offload 10% of those workitems to a LUT version such that it gets precomputed values from a table. I didn't try but something like this should work:</p>
<ul>
<li>8 compute groups</li>
<li>2 LUT groups</li>
<li>8 compute groups</li>
<li>2 LUT groups</li>
</ul>
<p>so they are evenly distributed into "threads in-flight" and get advantage of latency hiding stuff. I'm not sure if this is a preferable way of doing science.</p>
<p><strong>21)</strong> <strong>Z-order pattern</strong> For traveling neighbors increases cache hit rate. Cache hit rate saves some global memory bandwidth for other jobs so that overall performance increases. But this depends on size of cache, data layout and some other things I don't remember. </p>
<p><strong>22)</strong> <strong>Asynchronous Neighbor Traversal</strong> </p>
<ul>
<li>iteration-1: Load neighbor 2 + compute neighbor 1 + store neighbor 0</li>
<li>iteration-2: Load neighbor 3 + compute neighbor 2 + store neighbor 1</li>
<li>iteration-3: Load neighbor 4 + compute neighbor 3 + store neighbor 2</li>
</ul>
<p>so each body of loop doesn't have any chain of dependency and fully pipelined on GPU processing elements and OpenCL has special instructions for asynchronously loading/storing global variables using all cores of a workgroup. Check this: </p>
<p><a href="https://www.khronos.org/registry/OpenCL/sdk/1.0/docs/man/xhtml/async_work_group_copy.html" rel="noreferrer">https://www.khronos.org/registry/OpenCL/sdk/1.0/docs/man/xhtml/async_work_group_copy.html</a></p>
<p>Maybe you can even divide computing part into two and have one part use transcandental functions and other part use add/multiply so that add/multiply operations don't wait for a slow sqrt. If there are at least several neighbors to traveerse, this should hide some latency behind other iterations.</p> |
27,256,062 | When to use functors over lambdas | <p>Is there ever a situation where it makes more sense to create a functor than to use a lambda?</p>
<p>I know my question is effectively the reverse of <a href="https://stackoverflow.com/questions/4686507/lambda-expression-vs-functor-in-c">when to use a lambda over a functor</a>, but I can't think of a situation in practice where a functor would be <em>preferred</em> over a lambda. Any thoughts on this?</p> | 27,256,160 | 4 | 5 | null | 2014-12-02 18:05:35.94 UTC | 6 | 2014-12-05 00:16:18.693 UTC | 2017-05-23 12:17:41.613 UTC | null | -1 | null | 2,043,536 | null | 1 | 28 | c++|c++11|lambda|functor | 10,036 | <p>A lambda is a functor - just defined with a shorter syntax.</p>
<p>The problem is that this syntax is limited. It doesn't always allow you to solve a problem in the most efficient and flexible way - or at all. Until C++14, the <code>operator()</code> couldn't even be a template.</p>
<p>Furthermore, a lambda has exactly one <code>operator()</code>. You can't provide several overloads to distinguish between, say, the types of the arguments:</p>
<pre><code>struct MyComparator
{
bool operator()( int a, int b ) const {return a < b;}
bool operator()( float a, float b ) const {return /*Some maths here*/;}
};
</code></pre>
<p>.. or value category of the object argument (that is, the closure object that is called). You can also not define special member functions, including constructors and destructors - what if a functor shall be responsible for resources?</p>
<p>Another problem with lambdas is that they cannot be recursive. Of course, normal functions (including operator functions) can be.</p>
<p>Also consider that lambdas are unhandy to use as comparators for associative containers or deleters for smart pointers: You can't directly pass the closure type as a template argument and need to construct the containers member from another closure object. (Closure types don't have a default constructor!). For a block-scope <code>map</code> that isn't too much of a hassle:</p>
<pre><code>auto l = [val] (int a, int b) {return val*a < b;};
std::map<int, int, decltype(l)> map(l);
</code></pre>
<p>Now, what happens if your <code>map</code> is a <em>data member</em>? What template argument, what initializer in the constructors initialization list? You'd have to use another static data member - but since you have to define it outside the classes definition that is arguably ugly.</p>
<p><strong>To sum up</strong>: Lambdas aren't useful for more complex scenarios because they weren't made for them. They provide a short and concise way of creating <em>simple</em> function objects for correspondingly simple situations.</p> |
21,612,058 | Letter-spacing wrong text center alignment | <p>I have noticed a odd behavior in using <code>letter-spacing</code> and <code>text-align: center</code> together. Increasing the space, bring the text to be closer to the left margin of the element.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
width: 400px;
height: 200px;
background-color: #3b0d3b;
text-align: center;
margin: auto;
}
p {
color: #fff;
margin-top: 40px;
text-align: center;
padding-top: 10px;
font-size: 1.2em;
}
.spacing {
letter-spacing:.4em; /* This property is the problem */
}
.spacing-large {
letter-spacing:.9em; /* This property is the problem */
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<p>- Foo Bar Zan -</p>
<p class="spacing">- Foo Bar Zan -</p>
<p class="spacing-large">- Foo Bar Zan -</p>
</div></code></pre>
</div>
</div>
</p>
<p>I spot the same behavior on last Firefox and Chrome. Is there a way to fix this issue?</p> | 21,612,203 | 7 | 4 | null | 2014-02-06 19:22:27.183 UTC | 14 | 2021-10-10 21:33:00.53 UTC | 2021-10-10 21:33:00.53 UTC | null | 171,168 | null | 171,168 | null | 1 | 40 | html|css|letter-spacing | 28,340 | <p>It seems you need to indent the text by the same amount as the letter-spacing. The first letter does not have the spacing applied to the left side</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
width: 400px;
height: 400px;
background-color: #3b0d3b;
text-align: center;
margin: auto;
}
p {
color: #fff;
background: black;
text-align: center;
font-size: 1.2em;
padding: 0;
margin: 0;
}
.spacing {
letter-spacing: .4em;
}
.spacing-large {
letter-spacing: 0.9em;
text-align: center;
text-indent: 0.9em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<p>- Foo Bar Zan -</p>
<p class="spacing">- Foo Bar Zan -</p>
<p class="spacing-large">- Foo Bar Zan -</p>
</div></code></pre>
</div>
</div>
</p>
<p>The logical explanation I came up with is - since it is the first letter, spacing on the left side will not apply.</p> |
21,786,548 | Java 8 Collections concurrent processing | <p>I am planning to do an internal presentation in my company on new features and concepts in Java 8. </p>
<p>What I would like to focus is on the parallel processing capabilities of new collection libraries.</p>
<p>Wherever I read about <strong><em>Java 8</em></strong> and the need for more functional style iterators of the collection library, it is mentioned that this will help to leverage the multi-core servers that are normal nowadays. But very rarely it is mentioned how this is made possible and <em>whether this is a universal truth</em>, let alone any benchmarks on performance.</p>
<p>As even experienced developers in my company who claims to know about threads have no clue how actual threading works at the lower level, I am trying to collect some knowledge in this area. I have made a set of following assertions based on reading several blogs etc. </p>
<p>I would be thankful for some feedback for the following points <strong>(true/false)</strong>..</p>
<ol>
<li><p>A thread is the lowest unit of scheduling in an OS (yeah basic stuff, but not all application programmers know this ;-))</p></li>
<li><p>A single threaded program can run only on one core at a time. So in a quad core CPU, 75% of the CPU is not utilized for example.</p></li>
<li><p>The problem with present Java collection iterator is that it is an external iterator and it is not possible (atleast out of the box) to distribute a bulky collection iteration to multiple threads. The new collection library operations makes it possible to have concurrency without having the need to deal with low level concurrency issues</p></li>
<li><p>Java 8 makes it possible using an enhanced collection library to parallellize iteration using an internal iterator</p>
<p>Instead of Java 7 </p>
<p><code>for (Shape s : shapes) {if (s.getColor() == RED)s.setColor(BLUE); }</code></p>
<p>we have in Java 8</p>
<p><code>shapes.forEach(s -> {
if (s.getColor() == RED)
s.setColor(BLUE); })</code></p></li>
<li><p>But inorder to parallellize the above iteration, one must explicitly use <code>parallel()</code> method of <code>Stream API</code> </p>
<p><code>private static void printUsingCoolLambda (final List<String> names) {
names.parallelStream().forEach(s -> System.out.println(s));
System.out.println("Printed using printUsingCoolLambda");
}</code></p>
<p>But even then there is no guarantee that the operation will be done in parallel as the Javadoc of <code>parallelStream()</code> says the following <a href="http://download.java.net/jdk8/docs/api/java/util/Collection.html#parallelStream--" rel="noreferrer">"Returns a possibly parallel {@code Stream} with this collection as its source. It is allowable for this method to return a sequential stream"</a></p></li>
<li><p>Ultimately, there is no guarantee that all the cores will be utilized as thread scheduling is NOT a JVM responsibility, rather dictated by OS.</p></li>
</ol>
<p><strong>edit</strong></p>
<p>I have most difficulty in getting points 5 and 6 right. As various Java 8 blogs says just that <em>"use this new parallelStream() and you will get parallel processing out of the box(for free and you as an application programmer are freed from having to worry about that)"</em>, my question in one sentence would have been <strong><em>is that really correct all the time</em></strong>?</p> | 21,794,279 | 3 | 8 | null | 2014-02-14 18:11:08.183 UTC | 8 | 2014-02-15 16:56:50.073 UTC | 2014-02-14 18:47:31.607 UTC | null | 2,702,730 | null | 2,702,730 | null | 1 | 20 | java|multithreading|concurrency|parallel-processing|java-8 | 7,088 | <blockquote>
<p>I would be thankful for some feedback for the following points
(true/false)..</p>
</blockquote>
<p>Unfortunately none of the answers are either true or false. They are all "it depends" or "it's complicated". :-)</p>
<blockquote>
<p>1: A thread is the lowest unit of scheduling in an OS.</p>
</blockquote>
<p>This is basically true. OSes schedule threads, and for the most part a Java thread corresponds to an OS thread.</p>
<p>However, there's more to the story. I'd encourage you not to think too much about threads. They are a very low-level construct to use to structure a parallel application.</p>
<p>Of course it's possible to write applications using threads, but it's often preferable to use a higher level construct. One such construct is a <strong>task</strong>, which is an application-specific chunk of work. If you can divide your workload into separate tasks, you can submit these tasks to an <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html">Executor</a>, which will manage the scheduling of tasks onto threads and the creation and destruction of threads. This is the <code>java.util.concurrent</code> stuff that went into Java SE 5.</p>
<p>Another way to structure a parallel applications is using <strong>data parallelism</strong>. Java SE 7 introduced the Fork-Join framework. This refers to forking and joining not of <em>threads</em> but of <em>tasks</em>, specifically, tasks representing recursively-splittable portions of data. The FJ framework is quite effective for some workloads, but the splitting and joining of tasks is the responsibility of the programmer, and this can be burdensome.</p>
<p>New in Java SE 8 is the streams API, which supports data parallelism in a much more convenient fashion.</p>
<p>I've extrapolated quite a bit from your question about threads, but your questions seemed focused on threads, and there is much more to parallelism than threads. (One of my colleagues recently said, "Threads are a false God.")</p>
<blockquote>
<p>2: A single threaded program can run only on one core at a time. So in a quad core CPU, 75% of the CPU is not utilized for example.</p>
</blockquote>
<p>Mostly true. If you consider just the application thread, a single thread can never use more than 25% of a quad core CPU. However, if you consider a Java thread running in a JVM, even a single-threaded Java application will likely run faster on a multi-core system than on a single-core system. The reason is that JVM service threads like the garbage collector can run in parallel with the application thread on a multi-core system, whereas they have to pre-empt the application thread on a single-core system.</p>
<blockquote>
<p>3: The problem with present Java collection iterator is that it is an external iterator and it is not possible (at least out of the box) to distribute a bulky collection iteration to multiple threads. The new collection library operations makes it possible to have concurrency without having the need to deal with low level concurrency issues.</p>
</blockquote>
<p>Mostly yes. <em>External iteration</em> and <em>internal iteration</em> are concepts. External iteration is embodied by the actual <code>Iterator</code> interface. Internal iteration might use an <code>Iterator</code>, a simple for-loop, a set of fork-join tasks, or something else.</p>
<p>It's not so much the new collection library, but the new Streams API in Java 8 will provide a much more convenient way to distribute work across threads.</p>
<blockquote>
<p>4: Java 8 makes it possible using an enhanced collection library to parallellize iteration using an internal iterator (... <code>shapes.forEach</code> example ...)</p>
</blockquote>
<p>Close. Again, it's the new Streams library, not collections, that provides convenient parallelism. There's nothing like <code>Collection.parallelForEach</code>. To process elements of a collection in parallel, you have to pull a parallel stream from it. There are also a variety of parallel operations for arrays in the <code>java.util.Arrays</code> class.</p>
<blockquote>
<p>5: But in order to parallelize the above iteration, one must explicitly use the <code>parallel</code> method of the Stream API .... But even then there is no guarantee that the operation will be done in parallel.</p>
</blockquote>
<p>Right, you need to request parallelism with the <code>parallel</code> or <code>parallelStream</code> method, depending on whether you're starting with a stream or a collection.</p>
<p>Regarding no guarantees, sure, there are never any guarantees in life. :-) After all, if you're running on a single-core system, nothing can run in parallel. Another scenario is, in an applet, the security manager might prohibit the application from using more than a single thread. In practice, in most environments, requesting a parallel stream will indeed split up the workload and run the tasks in parallel. By default, these tasks run in the <a href="http://download.java.net/jdk8/docs/api/java/util/concurrent/ForkJoinPool.html">common fork-join pool</a>, which by default has as many threads as there are cores in the system. But somebody might have set the number of threads to a different number, or even to 1, which is one reason the API itself cannot provide any guarantees.</p>
<blockquote>
<p>6: Ultimately, there is no guarantee that all the cores will be utilized as thread scheduling is NOT a JVM responsibility, rather dictated by OS. ... As various Java 8 blogs says just that <em>"use this new parallelStream() and you will get parallel processing out of the box (for free and you as an application programmer are freed from having to worry about that)",</em> my question in one sentence would have been <strong>is that really correct all the time?</strong></p>
</blockquote>
<p>As above, no guarantees. There are many layers in the system where things can take a left turn. Even if your common FJ pool has as many threads as there are cores, there are no guarantees that each Java thread has its own OS thread. (In the Hotspot JVM I think this is always true though. It depends on the JVM.) There could be other processes -- even other JVMs -- on the same system competing for cores, so your application might not get as many cores as you'd like. In that sense the JVM is at the mercy of the OS to schedule threads for it.</p>
<p>I'm not sure where that blog entry came from, but the bit about parallel processing "for free" and the "you don't have to worry" sentiment is overblown. In fact, it's basically wrong.</p>
<p>It's true that it's possible to write a parallel stream much more conveniently than using earlier APIs. But it's also possible to get it very, very wrong. If you put side effects into your stream pipeline, you'll have race conditions, and you might get a different wrong answer every time. Or, even if you take care to synchronize around side effects, you might create enough contention so that a parallel stream might run even slower than a sequential one.</p>
<p>Even if you've managed to avoid these pitfalls, it's not the case that running a parallel stream on an N-core system will give you an N times speedup. It just doesn't work that way. For small workloads the overhead of splitting and joining parallel tasks dominates, which can cause the computation to be slower than a sequential one. For larger workloads, the overhead is offset by the parallel speedup, but the overhead is still there. The amount of speedup also depends on the nature of the workload, the splitting characteristics, lumpiness of the data, etc. Tuning a parallel application is something of a black art.</p>
<p>For easily-parallelizable workloads, in my experience, it's pretty easy to max out a two-core system. A four-core system usually can get at least 3x speedup. With more cores, it's not too difficult to get a 5x-6x speedup, but getting speedup beyond that requires actual work.</p>
<p>For not-so-easily parallelizable workloads, you might have to do a lot of thinking and restructuring of the application before you can even try running it in parallel.</p>
<p>I would not say that Java 8 gives you parallelism "for free" or "without worry" or anything like that. I <em>would</em> say that Java 8 gives you the opportunity to write parallel programs much more conveniently than before. But you still have to work to get it correct, and you will probably still have to work to achieve the speedup that you want.</p> |
19,767,894 | Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP | <p>I've got this message warning on Netbeans 7.4 for PHP while I'm using <strong>$_POST</strong>, <strong>$_GET</strong>, <strong>$_SERVER</strong>, ....</p>
<blockquote>
<p>Do not Access Superglobal $_POST Array Directly</p>
</blockquote>
<p>What does it mean? What can I do to correct this warning?</p>
<p><strong>Edit:</strong> The Event sample code still shows this warning.</p> | 19,874,791 | 5 | 5 | null | 2013-11-04 12:39:20.34 UTC | 34 | 2020-12-09 12:25:37.1 UTC | 2016-08-31 10:05:45.957 UTC | null | 1,391,249 | null | 899,824 | null | 1 | 119 | php|netbeans|superglobals|netbeans-7.4 | 113,791 | <p><code>filter_input(INPUT_POST, 'var_name')</code> instead of <code>$_POST['var_name']</code><br/>
<code>filter_input_array(INPUT_POST)</code> instead of <code>$_POST</code></p> |
17,547,360 | Create an ArrayList of unique values | <p>I have an <code>ArrayList</code> with values taken from a file (many lines, this is just an extract):</p>
<pre class="lang-none prettyprint-override"><code>20/03/2013 23:31:46 6870 6810 6800 6720 6860 6670 6700 6650 6750 6830 34864 34272
20/03/2013 23:31:46 6910 6780 6800 6720 6860 6680 6620 6690 6760 6790 35072 34496
</code></pre>
<p>Where the first two values per line are strings that contain data and are stored in a single element.</p>
<p>What I want to do is compare the string data elements and delete, for example, the second one and all the elements referred to in that line.</p>
<p>For now, I've used a <code>for</code> loop that compares the string every 13 elements (in order to compare only data strings).</p>
<p>My question: can I implement other better solutions?</p>
<p>This is my code:</p>
<pre><code>import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception{
//The input file
Scanner s = new Scanner(new File("prova.txt"));
//Saving each element of the input file in an arraylist
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
//Arraylist to save modified values
ArrayList<String> ds = new ArrayList<String>();
//
int i;
for(i=0; i<=list.size()-13; i=i+14){
//combining the first to values to obtain data
String str = list.get(i)+" "+list.get(i+1);
ds.add(str);
//add all the other values to arraylist ds
int j;
for(j=2; j<14; j++){
ds.add(list.get(i+j));
}
//comparing data values
int k;
for(k=0; k<=ds.size()-12; k=k+13){
ds.get(k); //first data string element
//Comparing with other strings and delete
//TODO
}
}
}
}
</code></pre> | 17,547,411 | 14 | 3 | null | 2013-07-09 11:41:57.527 UTC | 7 | 2022-07-07 12:16:33.19 UTC | 2019-09-22 22:19:02.08 UTC | null | 6,243,352 | null | 1,690,843 | null | 1 | 43 | java|arraylist | 222,998 | <blockquote>
<p>Create an Arraylist of unique values</p>
</blockquote>
<p>You could use <code>Set.toArray()</code> method.</p>
<blockquote>
<p>A collection that contains no duplicate elements. More formally, sets
contain no pair of elements e1 and e2 such that e1.equals(e2), and at
most one null element. As implied by its name, this interface models
the mathematical set abstraction.</p>
</blockquote>
<p><a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html">http://docs.oracle.com/javase/6/docs/api/java/util/Set.html</a></p> |
17,591,490 | How to make a query with group_concat in sql server | <p>I know that in sql server we cannot use <code>Group_concat</code> function but here is one issue i have in which i need to <code>Group_Concat</code> my query.I google it found some logic but not able to correct it.My sql query is</p>
<pre><code>select m.maskid,m.maskname,m.schoolid,s.schoolname,
md.maskdetail
from tblmask m join school s on s.id = m.schoolid
join maskdetails md on m.maskid = md.maskid
order by m.maskname ;
</code></pre>
<p>It gives me result like</p>
<p><img src="https://i.stack.imgur.com/kr74Z.png" alt="enter image description here"></p>
<p>Just look first 3 rows In that maskid,maskname,schoolid,schoolname is same but maskdetail is different so want to one row for that in which last column can contain all maskdetails as per maskid and so on.</p>
<p>I want my output like</p>
<p><img src="https://i.stack.imgur.com/47Idf.png" alt="enter image description here"></p>
<p>And so on.So please help me while making a query for that.</p>
<p>Thanks in advance.</p> | 17,591,536 | 4 | 1 | null | 2013-07-11 10:54:00.877 UTC | 49 | 2019-02-13 12:52:26.157 UTC | 2019-02-13 12:52:26.157 UTC | null | 330,315 | null | 928,876 | null | 1 | 129 | sql-server|string-aggregation|sql-server-group-concat | 262,324 | <p><strong>Query:</strong></p>
<pre><code>SELECT
m.maskid
, m.maskname
, m.schoolid
, s.schoolname
, maskdetail = STUFF((
SELECT ',' + md.maskdetail
FROM dbo.maskdetails md
WHERE m.maskid = md.maskid
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM dbo.tblmask m
JOIN dbo.school s ON s.ID = m.schoolid
ORDER BY m.maskname
</code></pre>
<p><strong>Additional information:</strong></p>
<p><a href="http://www.codeproject.com/Articles/691102/String-Aggregation-in-the-World-of-SQL-Server" rel="noreferrer">String Aggregation in the World of SQL Server</a></p> |
30,680,824 | How to use a TabLayout with Toolbar inside CollapsingToolbarLayout? | <p>I am looking at the <a href="https://github.com/chrisbanes/cheesesquare">chrisbanes/cheesesquare</a> and I am trying to put TabLayout with a Toolbar inside a CollapsingToolbarLayout, and here is my code</p>
<pre><code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="@dimen/detail_backdrop_height"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/primary_dark"
android:minHeight="150dip"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginBottom="60dp"
app:expandedTitleMarginEnd="64dp">
<ImageView
android:id="@+id/backdrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="110dip"
android:layout_gravity="top"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin" />
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p>This puts on something like this when the CollapsingToolbar is opened which is exactly what I am looking for:</p>
<p><img src="https://i.stack.imgur.com/8d56f.png" alt="enter image description here"></p>
<p>But when I collapse it (by pulling the image up) I get something like this </p>
<p><img src="https://i.stack.imgur.com/LAVwg.png" alt="enter image description here"></p>
<p>And this is due to the reason I've set the Toolbar to have a height of 110dip if I leave the default settings the Tabs and the toolbar title overlap. So I am looking for the right way to do that so that the title of the Toolbar gets it's right place on the appbar and the tablayout is under it. Is there a way this can be achieved ?</p> | 30,724,033 | 18 | 3 | null | 2015-06-06 08:49:03.533 UTC | 30 | 2018-03-28 08:30:38.61 UTC | 2015-06-07 10:08:13.62 UTC | null | 173,677 | null | 677,024 | null | 1 | 42 | android|material-design|android-toolbar|android-design-library | 55,737 | <p>Here's the way I managed to do this, I don't think that's the best solution though if anyone finds a better way please feel free to post the answer.</p>
<pre><code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="@dimen/detail_backdrop_height"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="206dip"
android:background="@color/primary_dark"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginBottom="20dp"
app:expandedTitleMarginEnd="64dp">
<ImageView
android:id="@+id/backdrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="50dip"
app:tabGravity="center"
app:tabMode="scrollable"
android:gravity="bottom"/>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
</code></pre> |
5,068,304 | In Ruby, when should you use self. in your classes? | <p>When do you use <code>self.property_name</code> in Ruby?</p> | 5,068,596 | 3 | 0 | null | 2011-02-21 16:13:24.177 UTC | 13 | 2011-02-22 15:10:01.597 UTC | 2011-02-21 21:45:54.923 UTC | null | 38,765 | null | 39,677 | null | 1 | 15 | ruby|self | 9,983 | <p>Use self when calling a class's mutator. For example, this won't work:</p>
<pre><code>class Foo
attr_writer :bar
def do_something
bar = 2
end
end
</code></pre>
<p>The problem is that 'bar = 2' creates a local variable named 'bar', rather than calling the method 'bar=' which was created by attr_writer. However, a little <code>self</code> will fix it:</p>
<pre><code>class Foo
attr_writer :bar
def do_something
self.bar = 2
end
end
</code></pre>
<p><code>self.bar = 2</code> calls the method <code>bar=</code>, as desired.</p>
<p>You may also use self to call a reader with the same name as a local variable:</p>
<pre><code>class Foo
attr_reader :bar
def do_something
bar = 123
puts self.bar
end
end
</code></pre>
<p>But it's usually better to avoid giving a local variable the same name as an accessor.</p> |
5,495,952 | Draw SVG on HTML5 Canvas with support for font element | <p>Is there a good library for converting SVG to HTML canvas that supports the font element? I have already tried <a href="http://code.google.com/p/canvg/" rel="noreferrer">canvg</a>, but it does not support Font.</p> | 5,505,861 | 3 | 1 | null | 2011-03-31 06:18:06.823 UTC | 15 | 2014-05-21 15:17:49.75 UTC | 2011-03-31 20:05:05.36 UTC | null | 405,017 | null | 468,202 | null | 1 | 23 | html|canvas|svg | 21,288 | <p>Browsers that support HTML5 Canvas also support SVG pretty well themselves. As such, you could do this:</p>
<pre class="lang-js prettyprint-override"><code>var img = new Image;
img.onload = function(){ myCanvasContext.drawImage(img,0,0); };
img.src = "foo.svg";
</code></pre>
<p>The only downside to this technique is that if the SVG is outside of your domain the canvas will become tainted; you will not be able to use <code>getImageData()</code> to read the resulting SVG, if that is your goal.</p>
<p>I've put an example of this technique on my server: <a href="http://phrogz.net/tmp/canvas_from_svg.html" rel="noreferrer">http://phrogz.net/tmp/canvas_from_svg.html</a><br>
I've tested this and verified that it works (and looks the same) on IE9, Chrome v11b, Safari v5, and Firefox v4.</p>
<p><strong>[Edit]</strong> Note that:</p>
<ol>
<li><p><strike>Chrome and Firefox currently 'punt' on security and disallow you from reading the canvas (e.g. <code>getImageData()</code> or <code>toDataURL()</code>) after you draw <em>any</em> SVG to the canvas (regardless of the domain)</strike> <strong><a href="http://phrogz.net/SVG/svg_to_png.xhtml" rel="noreferrer">these have been fixed</a></strong></p></li>
<li><p>Firefox currently has a bug where it refuses to draw SVG to the canvas unless the SVG has <code>height</code> and <code>width</code> attributes specified.</p></li>
</ol> |
5,245,600 | What does the keyword "transient" mean in Java? | <p>I saw somewhere</p>
<pre>
<code>
transient private TrackDAO trackDAO;
</code>
</pre> | 5,245,617 | 3 | 0 | null | 2011-03-09 12:13:35.727 UTC | 23 | 2018-09-17 13:39:30.6 UTC | 2014-07-31 12:26:34.22 UTC | null | 1,288,306 | user562350 | null | null | 1 | 189 | java|transient | 189,619 | <p>Google is your friend - <a href="http://en.wikibooks.org/wiki/Java_Programming/Keywords/transient">first hit</a> - also you might first have a look at what <a href="http://en.wikipedia.org/wiki/Serialization">serialization</a> is.</p>
<blockquote>
<p>It marks a member variable not to be
serialized when it is persisted to
streams of bytes. When an object is
transferred through the network, the
object needs to be 'serialized'.
Serialization converts the object
state to serial bytes. Those bytes are
sent over the network and the object
is recreated from those bytes. Member
variables marked by the java transient
keyword are not transferred, they are
lost intentionally.</p>
</blockquote>
<p>Example from there, slightly modified (thanks @pgras):</p>
<pre><code>public class Foo implements Serializable
{
private String saveMe;
private transient String dontSaveMe;
private transient String password;
//...
}
</code></pre> |
5,230,319 | How to edit the element.style css? | <p>Hi I am using a jquery modal pop up. See picture below.</p>
<p><img src="https://i.stack.imgur.com/FQSfi.jpg" alt="enter image description here"></p>
<p>However, the problem is, I need to edit the width.
So I typed in the css file, after checking and verifying with firebug,</p>
<pre><code>element.style
{
width: 700px !important;
}
</code></pre>
<p>But it does not work. ANy ideas as how to override the jquery css. </p>
<p>Some say the need to edit the css using javascript, making objects and stuff. But I'm not so sure about that.</p>
<p>Any help is appreciated.</p> | 5,230,341 | 4 | 1 | null | 2011-03-08 09:00:47.15 UTC | 0 | 2021-12-21 09:13:32.497 UTC | null | null | null | null | 350,648 | null | 1 | 1 | jquery|html|css|dom|popup | 40,782 | <p><code>element.style</code> in Firebug is the style applied to the element, for exemple</p>
<pre><code><span style="padding: 10px;">My text</span>
</code></pre>
<p><code>element.style</code> will have</p>
<pre><code>element.style
{
padding: 10px;
}
</code></pre>
<p>to override, the best way is to cleat the <code>style</code> attribute, append a <code>class</code> name and write the CSS you need.</p>
<hr>
<p>Regarding your modal problem, if you are using <a href="http://docs.jquery.com/UI/Dialog">jQuery UI Dialog</a> component, why don't you set the width programmatically, like:</p>
<pre><code>$( ".selector" ).dialog({ width: 460, maxWidth: 460, minWidth: 460 });
</code></pre> |
9,235,296 | How to detect empty lines while reading from istream object in C++? | <p>How can I detect if a line is empty?</p>
<p>I have:</p>
<pre><code>1
2
3
4
5
</code></pre>
<p>I'm reading this with istream r
so:</p>
<pre><code>int n;
r >> n
</code></pre>
<p>I want to know when I reach the space between 4 and 5.
I tried reading as char and using .peek() to detect \n but this detects the \n that goes after number 1 . The translation of the above input is: 1\n2\n3\n4\n\n5\n if I'm correct...</p>
<p>Since I'm going to manipulate the ints I rather read them as ints than using getline and then converting to int...</p> | 9,235,441 | 2 | 3 | null | 2012-02-10 21:48:40.823 UTC | 8 | 2021-09-15 23:20:36.327 UTC | 2013-10-12 14:27:40.837 UTC | null | 1,168,156 | null | 721,145 | null | 1 | 14 | c++|string|input|stream|istream | 77,292 | <p>It could look like this:</p>
<pre><code>#include <iostream>
#include <sstream>
using namespace std;
int main()
{
istringstream is("1\n2\n3\n4\n\n5\n");
string s;
while (getline(is, s))
{
if (s.empty())
{
cout << "Empty line." << endl;
}
else
{
istringstream tmp(s);
int n;
tmp >> n;
cout << n << ' ';
}
}
cout << "Done." << endl;
return 0;
}
</code></pre>
<p>output:</p>
<pre><code>1 2 3 4 Empty line.
5 Done.
</code></pre>
<p>Hope this helps.</p> |
9,139,897 | How to set default value to all keys of a dict object in python? | <p>I know you can use setdefault(key, value) to set default value for a given key, but is there a way to set default values of all keys to some value after creating a dict ?</p>
<p>Put it another way, I want the dict to return the specified default value for every key I didn't yet set.</p> | 9,139,961 | 7 | 5 | null | 2012-02-04 09:41:36.093 UTC | 18 | 2016-10-05 09:37:45.813 UTC | 2012-02-04 12:23:43.83 UTC | null | 639,165 | null | 639,165 | null | 1 | 72 | python|dictionary | 131,120 | <p>You can replace your old dictionary with a <a href="http://docs.python.org/py3k/library/collections.html#collections.defaultdict"><code>defaultdict</code></a>:</p>
<pre><code>>>> from collections import defaultdict
>>> d = {'foo': 123, 'bar': 456}
>>> d['baz']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'baz'
>>> d = defaultdict(lambda: -1, d)
>>> d['baz']
-1
</code></pre>
<p>The "trick" here is that a <code>defaultdict</code> can be initialized with another <code>dict</code>. This means
that you preserve the existing values in your normal <code>dict</code>:</p>
<pre><code>>>> d['foo']
123
</code></pre> |
60,087,159 | native.createnavigator factory is not a function | <p>I am going to design a Drawer navigation in my project.</p>
<blockquote>
<p>I installed that by this command:</p>
</blockquote>
<pre><code>npm install @react-navigation/drawer
</code></pre>
<p>Then imported that into <code>App.js</code></p>
<pre><code>import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
</code></pre>
<p>This is my <code>package.json</code> content:</p>
<pre><code>"@react-native-community/masked-view": "^0.1.6",
"@react-navigation/drawer": "^5.0.0",
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.5.6",
"react-native-reanimated": "^1.7.0",
"react-native-screens": "^2.0.0-beta.1",
"react-native-view-shot": "^3.0.2",
"react-navigation": "^4.1.1",
"react-navigation-stack": "^2.1.0",
</code></pre>
<p>This is my <code>App.js</code> content:</p>
<pre class="lang-js prettyprint-override"><code>const App = () => {
const Drawer = createDrawerNavigator();
return (
<View style={styles.container}>
<NavigationContainer>
<Drawer.Navigator initialRouteName="login">
<Drawer.Screen name="login" component={Login} />
<Drawer.Screen name="second" component={SecondPage} />
</Drawer.Navigator>
</NavigationContainer>
</View>
)
};
</code></pre>
<p>I should say that I've already created <code>Login</code> and <code>SecondPage</code> components and declared them in a file named <code>root.js</code></p>
<pre class="lang-js prettyprint-override"><code>import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { Login, Header, SecondPage, Footer, ThirdPage } from './components/index';
const AppNavigator = createStackNavigator({
login: { screen: Login },
header: { screen: Header },
second: { screen: SecondPage },
footer: { screen: Footer },
third: { screen: ThirdPage }
}, {
initialRouteName: 'login',
headerMode: 'none',
mode: 'modal',
}, {});
export default createAppContainer(AppNavigator);
</code></pre>
<p>But i'm getting an error (following screen).</p>
<p>How can i fix this?</p>
<p><a href="https://i.stack.imgur.com/ni1Iw.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ni1Iw.jpg" alt="enter image description here"></a></p>
<p><strong>index.js</strong></p>
<pre class="lang-js prettyprint-override"><code>export * from './login';
export * from './header';
export * from './secondpage';
export * from './footer';
export * from './thirdpage';
</code></pre> | 60,088,101 | 6 | 3 | null | 2020-02-06 03:09:32.63 UTC | 3 | 2020-11-08 00:12:26.343 UTC | 2020-02-06 06:00:34.803 UTC | null | 11,212,074 | null | 12,345,723 | null | 1 | 30 | reactjs|react-native|navigation-drawer|react-navigation | 30,068 | <p>I don't understand what you're trying to do now. I think you want to add a drawer Navigator.</p>
<p>Your problem is you have to use one container, but you have two, and createStackNavigator has two parameters, but you have three.</p>
<blockquote>
<p>createStackNavigator(RouteConfigs, StackNavigatorConfig);</p>
</blockquote>
<p>I think your navigator structure should be as follows.</p>
<p><strong>Drawers.js</strong></p>
<pre class="lang-js prettyprint-override"><code>export default const Drawers = () => {
const Drawer = createDrawerNavigator();
return (
<Drawer.Navigator initialRouteName="login">
<Drawer.Screen name="login" component={Login} />
<Drawer.Screen name="second" component={SecondPage} />
</Drawer.Navigator>
)
};
</code></pre>
<p><strong>App.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import Drawers from "./Drawers"
...
const AppNavigator = createStackNavigator({
login: { screen: Drawers },
header: { screen: Header },
second: { screen: SecondPage },
footer: { screen: Footer },
third: { screen: ThirdPage }
}, {
initialRouteName: 'login',
headerMode: 'none',
mode: 'modal',
});
export default createAppContainer(AppNavigator)
</code></pre>
<p><strong>index.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import Login from './login';
import Header from './header';
import SecondPage from './secondpage';
import Footer from './footer';
import ThirdPage from './thirdpage';
export { Login, Header, SecondPage, Footer, ThirdPage}
</code></pre>
<p>OR </p>
<blockquote>
<p>This issue can be a compatibility issue with the version.
<code>React-Navigation</code> and <code>StackNavigator</code> versions must be up to date.</p>
</blockquote> |
18,392,418 | HTML & CSS - put <link> tag outside of the <head> | <p>Is it ok to put the <code><link></code> to a css file out of the <code><head/></code> tag, for example in the footer side?</p>
<p>Which are bad and good results of this?</p>
<p>I ask this, cause actually i have a css file which doesn't styles anything but brings just some css3 animations to my website, so i would like to put it to the end of the html just for performance reason...</p>
<p>thanks</p> | 18,392,465 | 7 | 0 | null | 2013-08-22 23:35:18.383 UTC | 5 | 2019-03-21 15:51:49.43 UTC | 2017-10-11 14:21:34.16 UTC | null | 1,150,683 | null | 895,174 | null | 1 | 33 | html|css|performance|hyperlink|head | 33,838 | <p>Style sheets are linked in the <code><head></code> so that the browser can style the HTML and render it as it goes. If you put the style information at the bottom of the document the browser will have to restyle and render the whole document from the top again.</p>
<p>This firstly, takes longer, and secondly, looks really ugly.</p>
<p>This differs from included scripts as scripts will block loading until they are done, so you load them as late as possible in the process.</p> |
18,370,219 | How to use ADB in Android Studio to view an SQLite DB | <p>I need to view my SQLite db but I don't know how to do it. I've gone to <a href="http://www.sqlite.org/download.html" rel="noreferrer">http://www.sqlite.org/download.html</a> and downloaded the command line shell for my OS, but when I run the program and type <code>adb ...</code> I get errors.</p>
<p>Note: I'm using Android Studio so I'm assuming I don't need to install anything extra because I recall Android Studio said it had all the SDK tools needed.</p> | 29,206,366 | 7 | 0 | null | 2013-08-22 01:24:44.743 UTC | 51 | 2020-02-26 09:50:15.303 UTC | 2017-01-08 19:53:07.063 UTC | null | 1,788,806 | null | 1,455,043 | null | 1 | 88 | android|adb | 180,097 | <h1>Easiest Way: Connect to Sqlite3 via ADB Shell</h1>
<p>I haven't found any way to do that in Android Studio, but I access the db with a remote shell instead of pulling the file each time.</p>
<p>Find all info here:
<a href="http://developer.android.com/tools/help/sqlite3.html" rel="noreferrer">http://developer.android.com/tools/help/sqlite3.html</a></p>
<p>1- Go to your platform-tools folder in a command prompt</p>
<p>2- Enter the command <code>adb devices</code> to get the list of your devices</p>
<pre><code>C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb devices
List of devices attached
emulator-xxxx device
</code></pre>
<p>3- Connect a shell to your device:</p>
<pre><code>C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb -s emulator-xxxx shell
</code></pre>
<p>4a- You can bypass this step on rooted device </p>
<pre><code>run-as <your-package-name>
</code></pre>
<p>4b- Navigate to the folder containing your db file: </p>
<pre><code>cd data/data/<your-package-name>/databases/
</code></pre>
<p>5- run sqlite3 to connect to your db:</p>
<pre><code>sqlite3 <your-db-name>.db
</code></pre>
<p>6- run sqlite3 commands that you like eg:</p>
<pre><code>Select * from table1 where ...;
</code></pre>
<blockquote>
<p><strong>Note:</strong> Find more commands to run below.</p>
</blockquote>
<h1>SQLite cheatsheet</h1>
<p>There are a few steps to see the tables in an SQLite database:</p>
<ol>
<li><p>List the tables in your database:</p>
<pre><code>.tables
</code></pre></li>
<li><p>List how the table looks:</p>
<pre><code>.schema tablename
</code></pre></li>
<li><p>Print the entire table:</p>
<pre><code>SELECT * FROM tablename;
</code></pre></li>
<li><p>List all of the available SQLite prompt commands:</p>
<pre><code>.help
</code></pre></li>
</ol> |
19,842,746 | Adding a build configuration in Xcode | <p>I'd like to add a new build configuration in Xcode 5, "QA", to the other three we currently have (Debug, Distribution, Release). However, when I click "Editor > Add Configuration", everything is grayed out. I'm not very familiar with Xcode in the first place, so I'm not sure how to go about doing this.</p>
<p>Is there a reason it's grayed out? Is this this process to add a build configuration? Thanks.</p> | 59,134,606 | 3 | 2 | null | 2013-11-07 17:34:03.977 UTC | 21 | 2021-06-28 17:44:39.923 UTC | null | null | null | null | 1,549,201 | null | 1 | 167 | configuration|build|xcode5 | 62,786 | <p>For Xcode 11 + , you can add your custom configuration here:</p>
<p><a href="https://i.stack.imgur.com/YRE1D.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YRE1D.png" alt="enter image description here"></a></p> |
27,760,450 | First random number after setSeed in Java always similar | <p>To give some context, I have been writing a basic Perlin noise implementation in Java, and when it came to implementing seeding, I had encountered a bug that I couldn't explain.</p>
<p>In order to generate the same random weight vectors each time for the same seed no matter which set of coordinates' noise level is queried and in what order, I generated a new seed (<code>newSeed</code>), based on a combination of the original seed and the coordinates of the weight vector, and used this as the seed for the randomization of the weight vector by running:</p>
<pre><code>rnd.setSeed(newSeed);
weight = new NVector(2);
weight.setElement(0, rnd.nextDouble() * 2 - 1);
weight.setElement(1, rnd.nextDouble() * 2 - 1);
weight.normalize()
</code></pre>
<p>Where <code>NVector</code> is a self-made class for vector mathematics.</p>
<p>However, when run, the program generated very bad noise:
<img src="https://i.stack.imgur.com/kPCqA.png" alt="Very bad noise, with vertical streaks"></p>
<p>After some digging, I found that the first element of each vector was very similar (and so the first <code>nextDouble()</code> call after each <code>setSeed()</code> call) resulting in the first element of every vector in the vector grid being similar.</p>
<p>This can be proved by running:</p>
<pre><code>long seed = Long.valueOf(args[0]);
int loops = Integer.valueOf(args[1]);
double avgFirst = 0.0, avgSecond = 0.0, avgThird = 0.0;
double lastfirst = 0.0, lastSecond = 0.0, lastThird = 0.0;
for(int i = 0; i<loops; i++)
{
ran.setSeed(seed + i);
double first = ran.nextDouble();
double second = ran.nextDouble();
double third = ran.nextDouble();
avgFirst += Math.abs(first - lastfirst);
avgSecond += Math.abs(second - lastSecond);
avgThird += Math.abs(third - lastThird);
lastfirst = first;
lastSecond = second;
lastThird = third;
}
System.out.println("Average first difference.: " + avgFirst/loops);
System.out.println("Average second Difference: " + avgSecond/loops);
System.out.println("Average third Difference.: " + avgSecond/loops);
</code></pre>
<p>Which finds the average difference between the first, second and third random numbers generated after a <code>setSeed()</code> method has been called over a range of seeds as specified by the program's arguments; which for me returned these results:</p>
<pre><code>C:\java Test 462454356345 10000
Average first difference.: 7.44638117976783E-4
Average second Difference: 0.34131692827329957
Average third Difference.: 0.34131692827329957
C:\java Test 46245445 10000
Average first difference.: 0.0017196011123287126
Average second Difference: 0.3416750057190849
Average third Difference.: 0.3416750057190849
C:\java Test 1 10000
Average first difference.: 0.0021601598225344998
Average second Difference: 0.3409914232342002
Average third Difference.: 0.3409914232342002
</code></pre>
<p>Here you can see that the first average difference is significantly smaller than the rest, and seemingly decreasing with higher seeds.</p>
<p>As such, by adding a simple dummy call to <code>nextDouble()</code> before setting the weight vector, I was able to fix my perlin noise implementation:</p>
<pre><code>rnd.setSeed(newSeed);
rnd.nextDouble();
weight.setElement(0, rnd.nextDouble() * 2 - 1);
weight.setElement(1, rnd.nextDouble() * 2 - 1);
</code></pre>
<p>Resulting in:</p>
<p><img src="https://i.stack.imgur.com/tfEvQ.png" alt="enter image description here"></p>
<p>I would like to know why this bad variation in the first call to <code>nextDouble()</code> (I have not checked other types of randomness) occurs and/or to alert people to this issue.</p>
<p>Of course, it could just be an implementation error on my behalf, which I would be greatful if it were pointed out to me.</p> | 27,761,175 | 3 | 6 | null | 2015-01-03 22:58:17.243 UTC | 5 | 2015-01-22 18:26:42.683 UTC | null | null | null | null | 4,329,241 | null | 1 | 37 | java|random|noise | 2,134 | <p>The <strong><code>Random</code></strong> class is designed to be a low overhead source of pseudo-random numbers. But the consequence of the "low overhead" implementation is that the number stream has properties that are a long way off perfect ... from a statistical perspective. You have encountered one of the imperfections. <code>Random</code> is documented as being a Linear Congruential generator, and the properties of such generators are well known.</p>
<p>There are a variety of ways of dealing with this. For example, if you are careful you can hide some of the most obvious "poor" characteristics. (But you would be advised to run some statistical tests. You can't see non-randomness in the noise added to your second image, but it could still be there.)</p>
<p>Alternatively, if you want pseudo-random numbers that have guaranteed good statistical properties, then you should be using <strong><code>SecureRandom</code></strong> instead of <strong><code>Random</code></strong>. It has significantly higher overheads, but you can be assured that many "smart people" will have spent a lot of time on the design, testing and analysis of the algorithms.</p>
<p>Finally, it is relatively simple to create a subclass of <code>Random</code> that uses an alternative algorithm for generating the numbers; see <a href="http://demesos.blogspot.com.au/2011/09/replacing-java-random-generator.html" rel="nofollow noreferrer">link</a>. The problem is that you have to select (or design) and implement an appropriate algorithm.</p>
<hr>
<p>Calling this an "<strong>issue</strong>" is debatable. It is a well known and understood property of LCGs, and use of LCGs was a concious engineering choice. People want low overhead PRNGs, but low overhead PRNGs have poor properties. TANSTAAFL.</p>
<p>Certainly, this is not something that Oracle would contemplate changing in <code>Random</code>. Indeed, the reasons for not changing are stated clearly in the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Random.html" rel="nofollow noreferrer">javadoc</a> for the <code>Random</code> class.</p>
<blockquote>
<p>"In order to guarantee this property, particular algorithms are specified for the class <code>Random</code>. Java implementations must use all the algorithms shown here for the class <code>Random</code>, for the sake of absolute portability of Java code."</p>
</blockquote> |
14,939,078 | Scaling with regard to Nested vs Parent/Child Documents | <p>I'm running a proof of concept for us to run nested queries on more "normalised" data in ES. </p>
<p>e.g. with nested </p>
<p>Customer ->
- name<br>
- email
- events ->
- created
- type </p>
<p>Now I have a situation where a list of events for a given customer can be moved to another customer. e.g. Customer A has 50 events
Customer B has 5000 events </p>
<p>I now want to move all events from customer A into Customer B </p>
<p>At scale with millions of customers and queries are run on this for graphs in a UI is Parent/Child more suitable or should nested be able to handle it? </p>
<p>What are the pros and cons in my situation? </p> | 14,941,912 | 1 | 0 | null | 2013-02-18 14:53:29.313 UTC | 8 | 2013-02-18 17:25:09.477 UTC | null | null | null | null | 111,052 | null | 1 | 14 | elasticsearch | 8,116 | <p>It's hard to give you even rough performance metrics like "Nested is good enough", but I can give you some details about Nested vs Parent/Child that can help. I'd still recommend working up a few benchmark tests to verify performance is acceptable.</p>
<p><strong>Nested</strong></p>
<ul>
<li>Nested docs are stored in the same Lucene block as each other, which helps read/query performance. Reading a nested doc is faster than the equivalent parent/child.</li>
<li>Updating a single field in a nested document (parent or nested children) forces ES to reindex the <em>entire</em> nested document. This can be very expensive for large nested docs</li>
<li>Changing the "parent" means ES will: delete old doc, reindex old doc with less nested data, delete new doc, reindex new doc with new nested data.</li>
</ul>
<p><strong>Parent/Child</strong></p>
<ul>
<li>Children are stored separately from the parent, but are routed to the same shard. So parent/children are slightly less performance on read/query than nested</li>
<li>Parent/child mappings have a bit extra memory overhead, since ES maintains a "join" list in memory</li>
<li>Updating a child doc does not affect the parent or any other children, which can potentially save a lot of indexing on large docs</li>
<li>Changing the parent means you will delete the old child document and then index an identical doc under the new parent.</li>
</ul>
<p>It is possible Nested will work fine, but if you think there is the possibility for a lot of "data shuffling", then Parent/Child may be more suitable. Nested is best suited for instances where the nested data is not updated frequently but read often. Parent/Child is better for arrangements where the data moves around more frequently.</p> |
15,462,753 | MySQL Join Multiple Rows as Columns | <p>Say I have two tables in a MySQL Database.</p>
<p>Table 1:</p>
<pre><code>ID Name
1 Jim
2 Bob
</code></pre>
<p>Table 2:</p>
<pre><code>ID Place Race_Number
1 2nd 1
1 3rd 2
1 4th 3
2 1st 1
2 2nd 2
2 2nd 3
</code></pre>
<p>When selecting rows from the database, is there any way to join rows from the second table as columns to the first table? Currently I am using <code>SELECT * FROM Table1 NATURAL JOIN Table2</code>.</p>
<p>This outputs:</p>
<pre><code>ID Name Place Race_Number
1 Jim 2nd 1
1 Jim 3rd 2
1 Jim 4th 3
2 Bob 1st 1
2 Bob 2nd 2
2 Bob 2nd 3
</code></pre>
<p>Currently I am sorting through this in my PHP script to sort it into an array. This is a pain, as I have to look at the IDs and see if they're the same and then sort accordingly. I feel like there is a way to do this right in MySQL, without having to sort it into an array in the PHP. There can be an unlimited number of entries in the second table for each ID.</p>
<p>The desired result right from the MySQL query is:</p>
<pre><code>ID Name Race1 Race2 Race3
1 Jim 2nd 3rd 4th
2 Bob 1st 2nd 2nd
</code></pre>
<p>I can't make columns for Race1, Race2 etc in the table themselves because there can be an unlimited number of races for each ID.</p>
<p>Thanks for any help!</p> | 15,462,774 | 1 | 0 | null | 2013-03-17 15:49:17.59 UTC | 9 | 2013-05-03 11:17:24.87 UTC | 2013-05-03 11:17:24.87 UTC | null | 573,261 | null | 1,609,524 | null | 1 | 27 | php|mysql|sql|join | 22,851 | <p>An <code>INNER JOIN</code> will suffice your needs. MySQL has no <code>PIVOT</code> function by you can still simulate it using <code>CASE</code> and <code>MAX()</code> function.</p>
<pre><code>SELECT a.ID, a.NAME,
MAX(CASE WHEN b.Race_Number = 1 THEN b.Place ELSE NULL END) Race1,
MAX(CASE WHEN b.Race_Number = 2 THEN b.Place ELSE NULL END) Race2,
MAX(CASE WHEN b.Race_Number = 3 THEN b.Place ELSE NULL END) Race3
FROM Table1 a
INNER JOIN Table2 b
ON a.ID = b.ID
GROUP BY a.ID, a.Name
</code></pre>
<p>But if you have unknown number of <code>RACE</code>, then a <code>DYNAMIC SQL</code> is much more preferred.</p>
<pre><code>SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN b.Race_Number = ', Race_Number,
' THEN b.Place END) AS ', CONCAT('`Race', Race_Number, '`'))
) INTO @sql
FROM Table2;
SET @sql = CONCAT('SELECT s.Student_name, ', @sql, '
FROM Table1 a
LEFT JOIN Table2 b
ON ON a.ID = b.ID
GROUP BY a.ID, a.Name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code></pre> |
15,220,921 | How to store double[] array to database with Entity Framework Code-First approach | <p>How can I store an array of doubles to database using Entity Framework Code-First with no impact on the existing code and architecture design?</p>
<p>I've looked at Data Annotation and Fluent API, I've also considered converting the double array to a string of bytes and store that byte to the database in it own column.</p>
<p>I cannot access the <code>public double[] Data { get; set; }</code> property with Fluent API, the error message I then get is:</p>
<blockquote>
<p>The type <code>double[]</code> must be a non-nullable value type in order to use
it as parameter 'T'.</p>
</blockquote>
<p>The class where <code>Data</code> is stored is successfully stored in the database, and the relationships to this class. I'm only missing the <code>Data</code> column. </p> | 15,223,375 | 9 | 6 | null | 2013-03-05 10:03:21.13 UTC | 9 | 2022-01-26 23:12:14.997 UTC | null | null | null | null | 291,356 | null | 1 | 30 | c#|.net|entity-framework|ef-code-first|fluent-interface | 41,480 | <p>Thank you all for your inputs, due to your help I was able to track down the best way to solve this. Which is:</p>
<pre><code> public string InternalData { get; set; }
public double[] Data
{
get
{
return Array.ConvertAll(InternalData.Split(';'), Double.Parse);
}
set
{
_data = value;
InternalData = String.Join(";", _data.Select(p => p.ToString()).ToArray());
}
}
</code></pre>
<p>Thanks to these stackoverflow posts:
<a href="https://stackoverflow.com/a/9524705/291356">String to Doubles array</a> and
<a href="https://stackoverflow.com/a/380712/291356">Array of Doubles to a String</a></p> |
15,205,609 | Call a function when window is resized | <p>How can I call for this(or any) JS function to be run again whenever the Browser window is resized?</p>
<pre><code><script type="text/javascript">
function setEqualHeight(e) {
var t = 0;
e.each(function () {
currentHeight = $(this).height();
if (currentHeight > t) {
t = currentHeight
}
});
e.height(t)
}
$(document).ready(function () {
setEqualHeight($(".border"))
})
</script>
</code></pre> | 15,205,647 | 4 | 0 | null | 2013-03-04 15:57:14.64 UTC | 9 | 2016-09-16 19:44:19.403 UTC | 2013-03-04 16:24:55.03 UTC | null | 128,165 | null | 875,438 | null | 1 | 34 | javascript|jquery|window-resize | 57,544 | <p>You can use the window <code>onresize</code> event:</p>
<pre><code>window.onresize = setEqualHeight;
</code></pre> |
15,192,847 | Saving arrays as columns with np.savetxt | <p>I am trying to do something that is probable very simple. I would like to save three arrays to a file as columns using 'np.savetxt' When I try this</p>
<pre><code>x = [1,2,3,4]
y = [5,6,7,8]
z = [9,10,11,12]
np.savetxt('myfile.txt', (x,y,z), fmt='%.18g', delimiter=' ', newline=os.linesep)
</code></pre>
<p>The arrays are saved like this</p>
<pre><code>1 2 3 4
5 6 7 8
9 10 11 12
</code></pre>
<p>But what I wold like is this </p>
<pre><code>1 5 9
2 6 10
3 7 11
4 8 12
</code></pre> | 15,193,026 | 4 | 0 | null | 2013-03-04 00:48:26.243 UTC | 32 | 2017-07-05 19:12:19.047 UTC | 2017-06-06 20:57:48.113 UTC | null | 3,924,118 | null | 908,924 | null | 1 | 54 | python|numpy | 87,716 | <p>Use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.c_.html"><code>numpy.c_[]</code></a>:</p>
<pre><code>np.savetxt('myfile.txt', np.c_[x,y,z])
</code></pre> |
23,686,118 | AngularJS null value for select | <p>I couldn't find an elegant way for setting <code>null</code> values with a <code><select></code> using AngularJS. </p>
<p>HTML : </p>
<pre><code><select ng-model="obj.selected">
<option value=null>Unknown</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
{{obj}}
</code></pre>
<p>JS : </p>
<pre><code>$scope.obj ={"selected":null};
</code></pre>
<p>When the page is loaded, the first option is selected, which is good, and the output is <code>{"selected":null}</code>. When that first option is reselected after having switch to another one, the output becomes <code>{"selected":"null"}</code> (with the quotes), which is not what I would expect. </p>
<p>Running example :
<a href="http://plnkr.co/edit/WuJrBBGuHGqbKq6yL4La" rel="noreferrer">http://plnkr.co/edit/WuJrBBGuHGqbKq6yL4La</a></p>
<p>I know that the markup <code><option value=null></code> is not correct. I also tried with <code><option value=""></code> but it corresponds to an empty String and not to null : the first option is therefore not selected and another option which disappears after the first selection is selected by default.</p>
<p>Any idea ?</p> | 23,686,375 | 9 | 4 | null | 2014-05-15 18:34:27.94 UTC | 8 | 2020-09-03 19:39:46.127 UTC | null | null | null | null | 766,848 | null | 1 | 38 | javascript|html|angularjs | 62,383 | <p>This should work for you:</p>
<p>Controller:</p>
<pre><code> function MyCntrl($scope) {
$scope.obj ={"selected":null};
$scope.objects = [{id: 1, value: "Yes"}, {id: 0, value: "No"}]
}
</code></pre>
<p>Template:</p>
<pre><code> <div ng-controller="MyCntrl">
<select ng-model="obj.selected"
ng-options="value.id as value.value for value in objects">
<option value="">Unknown</option>
</select>
<br/>
{{obj}}
</div>
</code></pre>
<p><a href="http://plnkr.co/edit/FrBhVlLyHQejFTumrPXT?p=preview">Working plnkr</a></p>
<p>You should use ng-options with select.</p> |
8,567,420 | Redrawing a UIView with a fade animation? | <p>In <code>TwUI</code>, there is a method called <code>redraw</code> on <code>TUIView</code>. It forces the view to redraw, but it also comes with a free fading animation between the old and new state of the view.</p>
<p>I'm wondering if something like that is possible in a normal <code>UIView</code>. Basically, how can I redraw the view (<code>setNeedsDisplay</code>) with a fading animation between the old and the new states?</p> | 8,569,034 | 2 | 3 | null | 2011-12-19 20:53:55.547 UTC | 14 | 2012-10-02 04:25:46.81 UTC | null | null | null | null | 456,851 | null | 1 | 19 | iphone|objective-c|ios|cocoa-touch|uiview | 8,733 | <p>Use <code>+[UIView transitionWithView:duration:options:animations:completion:]</code> with the <code>UIViewAnimationOptionTransitionCrossDissolve</code> option, and inside the animation block, force the view's layer to redraw its contents immediately.</p>
<pre><code>[myView setNeedsDisplay];
[UIView transitionWithView:myView duration:1
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[myView.layer displayIfNeeded];
} completion:nil];
</code></pre> |
4,857,792 | Powershell: Reference a property that contains a space | <p>I am importing a CSV file using powershell.</p>
<p>The problem is, the title of one of the columns is "Remaining Time - Hours".
So I'm getting a sequence of objects, and it's actually assigned the property "Remaining Time - Hours".</p>
<p>What is the syntax to refer to this property?</p>
<p>eg</p>
<pre><code>Import-Csv AllOpenCases.csv | % {$case = $_ }
$case | get-member
</code></pre>
<p>returns</p>
<pre><code>Category : Inquiry
Starred : No
Remaining Time - Hours : 22.5
</code></pre>
<p>but if I type</p>
<pre><code>$case.Remaining Time - Hours
</code></pre>
<p>I get "Unexpected token 'Time' in expression or statement"</p> | 4,858,058 | 4 | 0 | null | 2011-02-01 00:47:15.033 UTC | 12 | 2011-02-01 12:44:45.72 UTC | null | null | null | null | 25,216 | null | 1 | 71 | powershell|csv | 70,189 | <p>Properties with embedded spaces have to be quoted when they're referenced:</p>
<pre><code> $case."Remaining Time - Hours"
</code></pre> |
5,442,661 | Efficiently gathering information about the inner workings of a new PHP project. Tools? Techniques? Scripts? | <p>I am soon to join a PHP project that has been developed over the course of several years. It's going to be huge, sparsely documented, many files, piles of code, no consitent quality level is to be expected.</p>
<p>How would you go about gathering as much information as possible about what is going on?</p>
<ul>
<li><p>Autoloading is not be expected, at
least not extensively, so
<a href="http://www.php.net/manual/en/intro.inclued.php" rel="nofollow noreferrer">inclued</a> might do a good job
revealing the interdependencies.</p></li>
<li><p>Having <a href="http://www.phpdoc.org/" rel="nofollow noreferrer">phpDocumentor</a> digest the
project files might give an idea
about which classes/methods/functions
are present.</p></li>
<li><p>Maybe <a href="http://phpcallgraph.sourceforge.net/" rel="nofollow noreferrer">phpCallGraph</a> for
method/function relations.</p></li>
<li><p>Profiling some generic use cases with
<a href="http://xdebug.org/docs/profiler" rel="nofollow noreferrer">XDebug</a> to gain an idea about the
hierarchies and concepts.</p></li>
<li><p>Inspecting important log-files ...
checking out warnings, deprecated
usages, errors.</p></li>
<li><p><a href="http://de.php.net/manual/en/function.phpinfo.php" rel="nofollow noreferrer">phpinfo()</a>.</p></li>
<li><p>Maybe extracting all comments and
process them into a html-file.</p></li>
</ul>
<p>Didn't cover Unit-Tests, Databases, ....</p>
<p>What would you do? What are your experiences with mentioned tools to get the most out of them?</p>
<p>You can assume any condition necessary.</p>
<p>What statistical information could be useful to extract?</p>
<p>Has somebody experience with those tools?</p>
<p><strong>EDIT</strong> from <a href="https://stackoverflow.com/questions/4202311/php-tools-for-quality-check">"PHP Tools for quality check"</a>:</p>
<ul>
<li><a href="http://phpmd.org/about.html" rel="nofollow noreferrer">PHP Mess Detector</a></li>
<li><a href="https://github.com/sebastianbergmann/phpcpd/#readme" rel="nofollow noreferrer">Copy/Paste Detector (CPD) for PHP code by Seb. Bermann</a></li>
</ul>
<p><strong>EDIT 2</strong> from Bryan Waters' answer:</p>
<ul>
<li><p><a href="https://github.com/sebastianbergmann/phploc" rel="nofollow noreferrer">phploc - phploc is a tool for quickly measuring the size of a PHP project.</a></p></li>
<li><p>Inspecting Apache logs and Google Analytics data to find out about the top requested URLs and then analyze what happens using XDebug profiling and a tool like <a href="http://kcachegrind.sourceforge.net/html/Home.html" rel="nofollow noreferrer">KCachegrind</a>.</p></li>
<li><p>See his answer for concrete techniques.</p></li>
</ul>
<p><a href="https://stackoverflow.com/q/2180460/562440">Setting up a deployment / build / CI cycle for PHP projects - suggested by Pekka</a></p>
<p><strong>EDIT 3</strong></p>
<p>Just found this <a href="http://www.afup.org/templates/forumphp2010/resumes/443-Listen%20AFUP%202010.pdf" rel="nofollow noreferrer">PDF</a> of a talk by Gabriele Santini - "Statistical analysis of the code - Listen to your PHP code". This is like a gold mine.</p> | 5,517,831 | 5 | 9 | null | 2011-03-26 13:39:09.953 UTC | 11 | 2011-04-25 17:56:51.717 UTC | 2017-05-23 11:45:49.397 UTC | null | -1 | null | 562,440 | null | 1 | 17 | php|profiling|xdebug|inclued | 594 | <p>I agreee that your question does have most of the answers. </p>
<p>This is what I would probably do.
I would probably start with Sebastian Bergman's tools, especially phploc so you can get an idea of the scope of the mess (codebase) you are looking at. It gives you class, function counts, etc not just lines of code.</p>
<p>Next I would look in the apache logs or google analytics and get the top 10 most requested php url's. I'd setup XDebug with profiling and run through those top 10 requests and get the files, call tree. (You can view these with a cachegrinder tool)</p>
<p>Finally, I'd read through the entire execution path of 1 or two of those traces, that is most representative of the whole. I'd use my Eclipse IDE but print them out and go to town with a highlighter is valid as well.</p>
<p>The top 10 method might fail you if there are multiple systems cobbled together. You should see quickly with Xdebug whether the top 10 are coded similarliy are if each is a unique island. </p>
<p>I would look at the mysql databases and try to understand what they are all for, espacially looking at table prefixes, you may have a couple of different apps stacked on top of each other. If there are large parts of the db not touched by the top 10 you need to go hunting for the subapps. If you find other sub apps run them through the xdebug profiler and then read through one of the paths that is representative of that sub app.</p>
<p>Now go back and look at your scope numbers from phploc and see what percentage of the codebase (probably count classes, or functions) was untouched during your review. </p>
<p>You should have a basic understanding of the most often run code and and idea of how many nooks and crannies and closets for skeleton storage there are.</p> |
5,146,732 | ViewModel validation for a List | <p>I have the following viewmodel definition</p>
<pre><code>public class AccessRequestViewModel
{
public Request Request { get; private set; }
public SelectList Buildings { get; private set; }
public List<Person> Persons { get; private set; }
}
</code></pre>
<p>So in my application there must be at least 1 person for an access request. What approach might you use to validate? I don't want this validation to happen in my controller which would be simple to do. Is the only choice a custom validation attribute?</p>
<p><strong>Edit:</strong> Currently performing this validation with FluentValidation (nice library!)</p>
<pre><code>RuleFor(vm => vm.Persons)
.Must((vm, person) => person.Count > 0)
.WithMessage("At least one person is required");
</code></pre> | 5,146,766 | 7 | 0 | null | 2011-02-28 19:40:31.663 UTC | 32 | 2018-10-14 18:11:00.713 UTC | 2014-06-25 20:27:42.917 UTC | null | 998,328 | null | 390,407 | null | 1 | 86 | c#|asp.net|asp.net-mvc-3|fluentvalidation|model-validation | 61,687 | <p>If you are using Data Annotations to perform validation you might need a custom attribute:</p>
<pre><code>public class EnsureOneElementAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var list = value as IList;
if (list != null)
{
return list.Count > 0;
}
return false;
}
}
</code></pre>
<p>and then:</p>
<pre><code>[EnsureOneElement(ErrorMessage = "At least a person is required")]
public List<Person> Persons { get; private set; }
</code></pre>
<p>or to make it more generic:</p>
<pre><code>public class EnsureMinimumElementsAttribute : ValidationAttribute
{
private readonly int _minElements;
public EnsureMinimumElementsAttribute(int minElements)
{
_minElements = minElements;
}
public override bool IsValid(object value)
{
var list = value as IList;
if (list != null)
{
return list.Count >= _minElements;
}
return false;
}
}
</code></pre>
<p>and then:</p>
<pre><code>[EnsureMinimumElements(1, ErrorMessage = "At least a person is required")]
public List<Person> Persons { get; private set; }
</code></pre>
<p>Personally I use <a href="http://fluentvalidation.codeplex.com/" rel="noreferrer">FluentValidation.NET</a> instead of Data Annotations to perform validation because I prefer the imperative validation logic instead of the declarative. I think it is more powerful. So my validation rule would simply look like this:</p>
<pre><code>RuleFor(x => x.Persons)
.Must(x => x.Count > 0)
.WithMessage("At least a person is required");
</code></pre> |
5,225,197 | Search NSArray for value matching value | <p>I have an NSArray of <code>objects</code>, which has a particular property called <code>name</code> (type NSString).<br>
I have a second NSArray of NSStrings which are <code>names</code>.</p>
<p>I'd like to get an NSArray of all the <code>objects</code> whose <code>.name</code> property matches one of the <code>names</code> in the second NSArray.</p>
<p>How do I go about this, fast and efficiently as this will be required quite often.</p> | 5,225,240 | 8 | 0 | null | 2011-03-07 21:01:17.633 UTC | 6 | 2015-02-18 08:52:41.633 UTC | null | null | null | null | 191,463 | null | 1 | 24 | iphone|objective-c|ipad|nsarray | 60,641 | <p>With your current data structures, you can only do it in O(n^2) time by looping over the first array once for each member of the second array:</p>
<pre><code>NSMutableArray * array = [NSMutableArray array];
for (NSString * name in names) {
for (MyObject * object in objects) {
if ([[myObject name] isEqualToString:name]) {
[array addObject:object];
}
}
}
</code></pre>
<p>(Alternate as suggested by Stefan: loop over the objects array and ask the names array if it <code>containsObject:</code> for the name of each object.)</p>
<p>But if this really needs to be faster (really depends on the size of the arrays as much as how often you do it), you can improve this by introducing an NSDictionary that maps the <code>names</code> in the first array to their objects. Then each of those lookups is O(1) and the overall time is O(n). (You'd have to keep this dictionary always in sync with the array of objects, which isn't hard with reasonable accessors. This technique also has the constraint that the same <code>name</code> can't appear on more than one object.)</p>
<p>An alternate way of getting this result (and which doesn't have that last constraint) is to use an NSSet for your second collection, then walk through the objects array calling <code>containsObject:</code> with each one on the set of names. Whether this technique is better depends on whether your two collections are roughly the same size, or if one is much larger than the other.</p> |
5,161,284 | Reordering Chart Data Series | <p>How does one reorder series used to create a chart in Excel?</p>
<p>For example, I go to the chart, right click > Select Data. In the left column I see series 1, series 2, to series n. </p>
<p>Say, I want to move series 3 after series 4, can it be done from chart view? I don't want to move the data cells in the worksheet.</p>
<p>I'm using Excel 2011 (mac OS X).</p> | 5,241,453 | 9 | 2 | null | 2011-03-01 22:40:07.223 UTC | 2 | 2019-12-31 04:59:16.227 UTC | 2019-12-31 04:59:16.227 UTC | null | 6,461,462 | null | 297,629 | null | 1 | 43 | excel|charts|excel-2011 | 405,712 | <p>Select a series and look in the formula bar. The last argument is the plot order of the series. You can edit this formula just like any other, right in the formula bar.</p>
<p>For example, select series 4, then change the 4 to a 3.</p> |
5,562,938 | Looking to understand the iOS UIViewController lifecycle | <p>Could you explain me the correct manner to manage the <code>UIViewController</code> lifecycle?</p>
<p>In particular, I would like to know how to use <code>Initialize</code>, <code>ViewDidLoad</code>, <code>ViewWillAppear</code>, <code>ViewDidAppear</code>, <code>ViewWillDisappear</code>, <code>ViewDidDisappear</code>, <code>ViewDidUnload</code> and <code>Dispose</code> methods in Mono Touch for a <code>UIViewController</code> class.</p> | 5,570,363 | 11 | 1 | null | 2011-04-06 07:39:14.37 UTC | 283 | 2020-01-12 07:42:01.8 UTC | 2017-02-21 16:29:02.31 UTC | null | 4,915,882 | null | 231,684 | null | 1 | 321 | ios|uiviewcontroller|xamarin.ios|lifecycle | 261,641 | <p>All these commands are called automatically at the appropriate times by iOS when you load/present/hide the view controller. It's important to note that these methods are attached to <code>UIViewController</code> and not to <code>UIView</code>s themselves. You won't get any of these features just using a <code>UIView</code>.</p>
<p>There's great documentation on Apple's site <a href="https://developer.apple.com/documentation/uikit/uiviewcontroller" rel="noreferrer">here</a>. Putting in simply though:</p>
<ul>
<li><p><code>ViewDidLoad</code> - Called when you create the class and load from xib. Great for initial setup and one-time-only work.</p></li>
<li><p><code>ViewWillAppear</code> - Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen.</p></li>
<li><p><code>ViewDidAppear</code> - Called after the view appears - great place to start an animations or the loading of external data from an API.</p></li>
<li><p><code>ViewWillDisappear</code>/<code>DidDisappear</code> - Same idea as <code>ViewWillAppear</code>/<code>ViewDidAppear</code>.</p></li>
<li><p><code>ViewDidUnload</code>/<code>ViewDidDispose</code> - In Objective-C, this is where you do your clean-up and release of stuff, but this is handled automatically so not much you really need to do here.</p></li>
</ul> |
16,650,787 | iOS 6 - UIActivityViewController items | <p>Hope everyone is aware of iOS 6 contains new style of <code>ActionSheet (UIActivityViewController).</code> The <code>UIActivityViewController</code> can be initiated with the paramentes like string, url, image etc. Below is the code snippet for that (where items is an array with string and url params).</p>
<pre><code>UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
</code></pre>
<p>But, is there any way that we can assign different parameters when we select different share options like Mail, Facebook or Twitter? </p>
<p>One method is we can implement UIActivityItemSource, where we need to implement the source methods</p>
<pre><code>- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType
</code></pre>
<p>which always returns a string value. But I need to pass an Array, so that I can assign various parameters like URL, image and a title. </p>
<p>Any idea how we can achieve this?</p> | 16,654,458 | 1 | 0 | null | 2013-05-20 13:37:54.44 UTC | 14 | 2013-05-20 16:57:08.543 UTC | 2013-05-20 16:32:32.427 UTC | null | 1,565,632 | null | 376,230 | null | 1 | 6 | ios|objective-c|ios6|uiactivityviewcontroller | 20,499 | <p>You can not change anything for the built in iOS UIActivityViewController items like Mail, Facebook and Twitter. In order to implement custom actions for items in your UIActivityViewController you must create a custom subclass of UIActivity for each custom activity you want. Here is an example:</p>
<pre><code>- (UIActivityViewController *)getActivityViewController {
MyFeedbackActivity *feedbackActivity = [[MyFeedbackActivity alloc] init];
MyFacebookActivity *facebookActivity = [[MyFacebookActivity alloc] init];
MyMailActivity *mailActivity = [[MyMailActivity alloc] init];
NSArray *applicationActivities = @[feedbackActivity, facebookActivity, mailActivity];
NSArray *activitiesItems = @[@"A string to be used for MyFeedbackActivity", @"A string to be used for MyFacebookActivity", @"A string to be used for MyMailActivity"];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activitiesItems applicationActivities:applicationActivities];
// Removed un-needed activities
activityVC.excludedActivityTypes = [[NSArray alloc] initWithObjects:
UIActivityTypeCopyToPasteboard,
UIActivityTypePostToWeibo,
UIActivityTypePostToFacebook,
UIActivityTypeSaveToCameraRoll,
UIActivityTypeCopyToPasteboard,
UIActivityTypeMail,
UIActivityTypeMessage,
UIActivityTypeAssignToContact,
nil];
return activityVC;
}
</code></pre>
<p>A very limited example of a subclassed UIActivity with documentation on the methods that you will be interested in overriding to handle your custom data/actions.</p>
<pre><code>#import "MyFeedbackActivity.h"
@implementation MyFeedbackActivity
- (NSString *)activityType {
return @"MyFeedbackActivity";
}
- (NSString *)activityTitle {
return @"Feedback";
}
- (UIImage *)activityImage {
return [UIImage imageNamed:@"feedback"];
}
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems {
return YES;
}
- (UIViewController *)activityViewController {
/**
* DESCRIPTION:
* Returns the view controller to present to the user.
* Subclasses that provide additional UI using a view controller can override this method to return that view controller. If this method returns a valid object, the system presents the returned view controller modally instead of calling the performActivity method.
* Your custom view controller should provide a view with your custom UI and should handle any user interactions inside those views. Upon completing the activity, do not dismiss the view controller yourself. Instead, call the activityDidFinish: method and let the system dismiss it for you.
*/
}
- (void)prepareWithActivityItems:(NSArray *)activityItems {
/**
* DESCRIPTION:
* Prepares your service to act on the specified data.
* The default implementation of this method does nothing. This method is called after the user has selected your service but before your service is asked to perform its action. Subclasses should override this method and use it to store a reference to the data items in the activityItems parameter. In addition, if the implementation of your service requires displaying additional UI to the user, you can use this method to prepare your view controller object and make it available from the activityViewController method.
*/
}
-(void)performActivity {
/**
* DESCRIPTION:
* Performs the service when no custom view controller is provided.
* The default implementation of this method does nothing. If your service does not provide any custom UI using the activityViewController method, override this method and use it to perform the activity. Your activity must operate on the data items received in the prepareWithActivityItems: method.
* This method is called on your app’s main thread. If your app can complete the activity quickly on the main thread, do so and call the activityDidFinish: method when it is done. If performing the activity might take some time, use this method to start the work in the background and then exit without calling activityDidFinish: from this method. Instead, call activityDidFinish: from your background thread after the actual work has been completed.
*/
}
@end
</code></pre> |
12,202,751 | How can I make a DataGridView cell's font a particular color? | <p>This code works fine for making the cell's background Blue:</p>
<pre><code>DataGridViewRow dgvr = dataGridViewLifeSchedule.Rows[rowToPopulate];
dgvr.Cells[colName].Style.BackColor = Color.Blue;
dgvr.Cells[colName].Style.ForeColor = Color.Yellow;
</code></pre>
<p>...but the ForeColor's effects are not what I expected/hoped: the font color is still black, not yellow. </p>
<p>How can I make the font color yellow?</p> | 12,203,065 | 2 | 4 | null | 2012-08-30 17:56:15.837 UTC | 3 | 2012-08-30 18:53:30.39 UTC | 2012-08-30 18:11:41.763 UTC | null | 875,317 | null | 875,317 | null | 1 | 16 | c#|winforms|datagridview|fonts|datagridviewtextboxcell | 74,438 | <p>You can do this:</p>
<pre><code>dataGridView1.SelectedCells[0].Style
= new DataGridViewCellStyle { ForeColor = Color.Yellow};
</code></pre>
<p>You can also set whatever style settings (font, for example) in that cell style constructor.</p>
<p>And if you want to set a particular column text color you could do:</p>
<pre><code>dataGridView1.Columns[colName].DefaultCellStyle.ForeColor = Color.Yellow;
dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Blue;
</code></pre>
<p><strong>updated</strong></p>
<p>So if you want to color based on having a value in the cell, something like this will do the trick:</p>
<pre><code>private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null && !string.IsNullOrWhiteSpace(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = new DataGridViewCellStyle { ForeColor = Color.Orange, BackColor = Color.Blue };
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = dataGridView1.DefaultCellStyle;
}
}
</code></pre> |
12,325,132 | MySQL get missing IDs from table | <p>I have this table in MySQL, for example:</p>
<pre><code>ID | Name
1 | Bob
4 | Adam
6 | Someguy
</code></pre>
<p>If you notice, there is no ID number (2, 3 and 5).</p>
<p>How can I write a query so that MySQL would answer the missing IDs only, in this case: "2,3,5" ?</p> | 12,325,194 | 8 | 0 | null | 2012-09-07 20:44:27.457 UTC | 24 | 2021-06-03 08:30:10.82 UTC | null | null | null | null | 870,292 | null | 1 | 46 | mysql | 23,033 | <pre><code>SELECT a.id+1 AS start, MIN(b.id) - 1 AS end
FROM testtable AS a, testtable AS b
WHERE a.id < b.id
GROUP BY a.id
HAVING start < MIN(b.id)
</code></pre>
<p>Hope this link also helps
<a href="http://www.codediesel.com/mysql/sequence-gaps-in-mysql/">http://www.codediesel.com/mysql/sequence-gaps-in-mysql/</a></p> |
12,229,064 | Mapping over values in a python dictionary | <p>Given a dictionary <code>{ k1: v1, k2: v2 ... }</code> I want to get <code>{ k1: f(v1), k2: f(v2) ... }</code> provided I pass a function <code>f</code>.</p>
<p>Is there any such built in function? Or do I have to do</p>
<pre><code>dict([(k, f(v)) for (k, v) in my_dictionary.iteritems()])
</code></pre>
<p>Ideally I would just write</p>
<pre><code>my_dictionary.map_values(f)
</code></pre>
<p>or</p>
<pre><code>my_dictionary.mutate_values_with(f)
</code></pre>
<p>That is, it doesn't matter to me if the original dictionary is mutated or a copy is created.</p> | 12,229,070 | 8 | 1 | null | 2012-09-01 15:31:37.497 UTC | 54 | 2022-07-13 20:41:27.557 UTC | 2016-09-01 14:22:33.37 UTC | null | 100,297 | null | 621,449 | null | 1 | 323 | python|dictionary|map-function | 415,764 | <p>There is no such function; the easiest way to do this is to use a dict comprehension:</p>
<pre><code>my_dictionary = {k: f(v) for k, v in my_dictionary.items()}
</code></pre>
<p>In python 2.7, use the <code>.iteritems()</code> method instead of <code>.items()</code> to save memory. The dict comprehension syntax wasn't introduced until python 2.7.</p>
<p>Note that there is no such method on lists either; you'd have to use a list comprehension or the <code>map()</code> function.</p>
<p>As such, you could use the <code>map()</code> function for processing your dict as well:</p>
<pre><code>my_dictionary = dict(map(lambda kv: (kv[0], f(kv[1])), my_dictionary.iteritems()))
</code></pre>
<p>but that's not that readable, really.</p> |
12,459,811 | How to embed matplotlib in pyqt - for Dummies | <p>I am currently trying to embed a graph I want to plot in a pyqt4 user interface I designed. As I am almost completely new to programming - I do not get how people did the embedding in the examples I found - <a href="http://www.python-forum.de/viewtopic.php?f=24&t=22673">this one (at the bottom)</a> and <a href="http://eli.thegreenplace.net/files/prog_code/qt_mpl_bars.py.txt">that one</a>.</p>
<p>It would be awesome if anybody could post a step-by-step explanation or at least a very small, very simple code only creating e.g. a graph and a button in one pyqt4 GUI. </p> | 12,465,861 | 3 | 0 | null | 2012-09-17 13:04:39.18 UTC | 63 | 2020-10-02 01:23:02.503 UTC | 2017-09-03 16:40:36.797 UTC | null | 1,033,581 | null | 1,677,646 | null | 1 | 82 | python|matplotlib|pyqt4 | 124,989 | <p>It is not that complicated actually. Relevant Qt widgets are in <a href="http://matplotlib.org/api/backend_qt4agg_api.html" rel="noreferrer"><code>matplotlib.backends.backend_qt4agg</code></a>. <code>FigureCanvasQTAgg</code> and <code>NavigationToolbar2QT</code> are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a <code>Figure</code>, <code>Navigation</code> and a single button that draws some random data. I've added comments to explain things.</p>
<pre><code>import sys
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import random
class Window(QtGui.QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = Figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QtGui.QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
ax.clear()
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
</code></pre>
<p><strong>Edit</strong>:</p>
<p>Updated to reflect comments and API changes.</p>
<ul>
<li><code>NavigationToolbar2QTAgg</code> changed with <code>NavigationToolbar2QT</code> </li>
<li>Directly import <code>Figure</code> instead of <code>pyplot</code> </li>
<li>Replace deprecated <code>ax.hold(False)</code> with <code>ax.clear()</code></li>
</ul> |
18,840,018 | How to show inferred TypeScript type in WebStorm? | <p>In VS2012, you can hover over a typescript variable and it will show you the inferred type. Is there a similar feature in webstorm?</p> | 18,846,155 | 5 | 3 | null | 2013-09-17 01:44:30.68 UTC | 8 | 2022-07-01 07:09:33.16 UTC | 2017-06-14 17:30:32.043 UTC | null | 1,571,491 | null | 256,272 | null | 1 | 59 | typescript|phpstorm|webstorm|type-inference | 14,036 | <p>Although not perfect. Press the <kbd>Ctrl</kbd> key (or <kbd>⌘ Cmd</kbd> on macOS) and hover over a variable with the mouse to kick in the inference logic in webstorm : </p>
<p><img src="https://i.stack.imgur.com/XXX1Y.png" alt="enter image description here"></p> |
8,583,964 | Why does compiler inlining produce slower code than manual inlining? | <h2>Background</h2>
<p>The following critical loop of a piece of numerical software, written in C++, basically compares two objects by one of their members:</p>
<pre><code>for(int j=n;--j>0;)
asd[j%16]=a.e<b.e;
</code></pre>
<p><code>a</code> and <code>b</code> are of class <code>ASD</code>:</p>
<pre><code>struct ASD {
float e;
...
};
</code></pre>
<p>I was investigating the effect of putting this comparison in a lightweight member function:</p>
<pre><code>bool test(const ASD& y)const {
return e<y.e;
}
</code></pre>
<p>and using it like this:</p>
<pre><code>for(int j=n;--j>0;)
asd[j%16]=a.test(b);
</code></pre>
<p>The compiler is inlining this function, but the problem is, that the assembly code will be different and cause >10% of runtime overhead. I have to question:</p>
<h2>Questions</h2>
<ol>
<li><p>Why is the compiler prodrucing different assembly code?</p>
</li>
<li><p>Why is the produced assembly slower?</p>
</li>
</ol>
<p><strong>EDIT:</strong> The second question has been answered by implementing @KamyarSouri's suggestion (j%16). The assembly code now looks almost identical (see <a href="http://pastebin.com/diff.php?i=yqXedtPm" rel="noreferrer">http://pastebin.com/diff.php?i=yqXedtPm</a>). The only differences are the lines 18, 33, 48:</p>
<pre><code>000646F9 movzx edx,dl
</code></pre>
<h2>Material</h2>
<ul>
<li>The test code: <a href="http://pastebin.com/03s3Kvry" rel="noreferrer">http://pastebin.com/03s3Kvry</a></li>
<li>The assembly output on MSVC10 with /Ox /Ob2 /Ot /arch:SSE2:
<ul>
<li>Compiler inlined version: <a href="http://pastebin.com/yqXedtPm" rel="noreferrer">http://pastebin.com/yqXedtPm</a></li>
<li>Manually inlined version: <a href="http://pastebin.com/pYSXL77f" rel="noreferrer">http://pastebin.com/pYSXL77f</a></li>
<li>Difference <a href="http://pastebin.com/diff.php?i=yqXedtPm" rel="noreferrer">http://pastebin.com/diff.php?i=yqXedtPm</a></li>
</ul>
</li>
</ul>
<p>This chart shows the FLOP/s (up to a scaling factor) for 50 testruns of my code.</p>
<p><img src="https://i.stack.imgur.com/BlGeJ.png" alt="enter image description here" /></p>
<p>The gnuplot script to generate the plot: <a href="http://pastebin.com/8amNqya7" rel="noreferrer">http://pastebin.com/8amNqya7</a></p>
<p>Compiler Options:</p>
<p>/Zi /W3 /WX- /MP /Ox /Ob2 /Oi /Ot /Oy /GL /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Gm- /EHsc /MT /GS- /Gy /arch:SSE2 /fp:precise /Zc:wchar_t /Zc:forScope /Gd /analyze-</p>
<p>Linker Options:
/INCREMENTAL:NO "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib" "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib" "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib" /ALLOWISOLATION /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /SUBSYSTEM:CONSOLE /OPT:REF /OPT:ICF /LTCG /TLBID:1 /DYNAMICBASE /NXCOMPAT /MACHINE:X86 /ERRORREPORT:QUEUE</p> | 8,584,227 | 2 | 19 | null | 2011-12-21 01:04:52.5 UTC | 7 | 2012-01-08 23:07:21.093 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 578,832 | null | 1 | 31 | c++|performance|assembly|compiler-optimization|inlining | 1,175 | <h1>Short Answer:</h1>
<p>Your <code>asd</code> array is declared as this:</p>
<pre><code>int *asd=new int[16];
</code></pre>
<p>Therefore, use <code>int</code> as the return type rather than <code>bool.</code><br>
Alternatively, change the array type to <code>bool</code>.</p>
<p><strong>In any case, make the return type of the <code>test</code> function match the type of the array.</strong></p>
<p>Skip to bottom for more details.</p>
<h1>Long Answer:</h1>
<p>In the manually inlined version, the "core" of one iteration looks like this:</p>
<pre><code>xor eax,eax
mov edx,ecx
and edx,0Fh
mov dword ptr [ebp+edx*4],eax
mov eax,dword ptr [esp+1Ch]
movss xmm0,dword ptr [eax]
movss xmm1,dword ptr [edi]
cvtps2pd xmm0,xmm0
cvtps2pd xmm1,xmm1
comisd xmm1,xmm0
</code></pre>
<p>The compiler inlined version is completely identical except for the first instruction.</p>
<p>Where instead of:</p>
<pre><code>xor eax,eax
</code></pre>
<p>it has:</p>
<pre><code>xor eax,eax
movzx edx,al
</code></pre>
<p>Okay, so it's <em>one</em> extra instruction. They both do the same - zeroing a register. This is the only difference that I see...</p>
<p>The <code>movzx</code> instruction has a single-cycle latency and <code>0.33</code> cycle reciprocal throughput on all the newer architectures. So I can't imagine how this could make a 10% difference.</p>
<p>In both cases, the result of the zeroing is used only 3 instructions later. So it's very possible that this could be on the critical path of execution.</p>
<hr />
<p><strong>While I'm not an Intel engineer, here's my guess:</strong></p>
<p>Most modern processors deal with zeroing operations (such as <code>xor eax,eax</code>) via <a href="http://en.wikipedia.org/wiki/Register_renaming" rel="noreferrer">register renaming</a> to a bank of zero registers. It completely bypasses the execution units. However, it's possible that this special handling could cause a pipeline bubble when the (partial) register is accessed via <code>movzx edi,al</code>.</p>
<p>Furthermore, there's also a <em>false</em> dependency on <code>eax</code> in the compiler inlined version:</p>
<pre><code>movzx edx,al
mov eax,ecx // False dependency on "eax".
</code></pre>
<p>Whether or not the <a href="http://en.wikipedia.org/wiki/Out-of-order_execution" rel="noreferrer">out-of-order execution</a> is able to resolve this is beyond me.</p>
<hr />
<h1>Okay, this is basically turning into a question of reverse-engineering the MSVC compiler...</h1>
<p>Here I'll to explain <em><strong>why</strong></em> that extra <code>movzx</code> is generated as well as why it stays.</p>
<p>The key here is the <code>bool</code> return value. Apparently, <code>bool</code> datatypes are probably as stored 8-bit values inside the MSVC internal-representation.
Therefore when you implicitly convert from <code>bool</code> to <code>int</code> here:</p>
<pre><code>asd[j%16] = a.test(b);
^^^^^^^^^ ^^^^^^^^^
type int type bool
</code></pre>
<p>there is an 8-bit -> 32-bit integer promotion. This is the reason why MSVC generates the <code>movzx</code> instruction.</p>
<p>When the inlining is done manually, the compiler has enough information to optimize out this conversion and keeps everything as a 32-bit datatype IR.</p>
<p>However, when the code is put into it's own function with a <code>bool</code> return value, the compiler is not able to optimize out the 8-bit intermediate datatype. Therefore, the <code>movzx</code> stays.</p>
<p>When you make both datatypes the same (either <code>int</code> or <code>bool</code>), no conversion is needed. Hence the problem is avoided altogether.</p> |
10,960,753 | How to make toggle hidden by default | <p>Hello I would like to know how to make toggle hidden when the page loads, I have made a simple code, but when the page loads it will be shown by default. I want it the way around.</p>
<p>I have to tried to use CSS something like</p>
<pre><code>.hidden {
display:none;
}
</code></pre>
<p>when I use this code, the element doesn't show at all.</p>
<p>this is my code</p>
<p><em>EDITED</em></p>
<pre><code><script type="text/javascript">
function toggleDiv(divId) {
$("#"+divId).toggle();
}
</script>
</code></pre>
<p></p>
<pre><code><a href="javascript:toggleDiv('myContent');">this is a test</a>
<div id="myContent">
<a href="javascript:toggleDiv('myContentt');"><span>this is a text</span></a>
<div>this is a test #2 </div>
</div>
<div id="myContentt">
test
</div>
</code></pre>
<p>please help.</p> | 10,960,868 | 4 | 0 | null | 2012-06-09 11:50:27.313 UTC | 4 | 2019-02-07 16:44:12.76 UTC | 2012-06-09 11:58:08.48 UTC | null | 804,253 | null | 804,253 | null | 1 | 8 | jquery | 51,821 | <p>I guess, you want something like this,</p>
<p><a href="http://jsfiddle.net/krY56/1/" rel="noreferrer">Demo</a> ( I used <code>onclick</code> in demo because jsfiddle doesnt like javascript on <code>href</code>)</p>
<p><strong>CSS:</strong> </p>
<pre><code>.hidden{
display:none;
}
</code></pre>
<p><strong>Markup:</strong></p>
<pre><code><a href="javascript:toggleDiv('myContent');">this is a test</a>
<div id="myContent" class='hidden'>
<div>this is a test #1 </div>
</div>
<br />
<a href="javascript:toggleDiv('myContentt');"><span>this is a text</span></a>
<div id="myContentt" class='hidden'>
this is a test #2
</div>
</code></pre>
<p><strong>Javascript:</strong></p>
<pre><code>function toggleDiv(divId) {
$("#"+divId).toggle();
}
</code></pre> |
11,320,692 | javascript enable input on double click | <p>I have a form with some inputs disabled. I want these inputs to be enabled when double clicked. Unfortunately, JS events seem not to fire on disabled inputs.</p>
<pre><code><input type="text" value="asdf" disabled="disabled" ondblclick="this.disabled=false;">
</code></pre>
<p>Is there a way around this limitation?</p>
<p>Or am I just going to have to wrap any affected input in a span to house the event?</p>
<p><a href="http://jsfiddle.net/vhktx/">http://jsfiddle.net/vhktx/</a></p> | 11,320,747 | 4 | 2 | null | 2012-07-03 23:47:14.803 UTC | 2 | 2021-08-21 13:53:45.627 UTC | null | null | null | null | 1,125,513 | null | 1 | 10 | javascript|html|forms | 38,574 | <p><code>ondblclick</code> does not get fired on a <code>disabled</code> element, you should mark it as <code>readonly</code>:</p>
<pre><code><input type="text" value="asdf" readonly="true" ondblclick="this.readOnly='';">
</code></pre>
<p><a href="http://jsfiddle.net/vhktx/4/">http://jsfiddle.net/vhktx/4/</a></p> |
11,223,011 | AttributeError: 'list' object has no attribute 'click' - Selenium Webdriver | <p>I am trying to use click command in Selenium webdriver using python. But I am getting the below error. Can some one help me?</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\vikram\workspace\LDC\test.py", line 13, in <module>
driver.find_elements_by_link_text("MISCQA Misc Tests").click()
AttributeError: 'list' object has no attribute 'click'
</code></pre>
<p>Here is my program</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
import config
url = config.config.get('url')
driver = webdriver.Ie()
driver.get(url)
driver.find_elements_by_link_text("MISCQA Misc Tests").click()
driver.close()
</code></pre>
<p>I think I am missing some thing. Please suggest me</p> | 11,223,369 | 8 | 1 | null | 2012-06-27 09:19:16.657 UTC | 6 | 2020-08-13 00:13:56.717 UTC | null | null | null | null | 727,495 | null | 1 | 27 | python|selenium|webdriver | 108,948 | <p>Thanks for helping out. I found the answer for myself. Idea given by "Dan Niero"</p>
<p>The problem is, I am using <code>driver.find_element[s]</code> instead of <code>driver.find_element</code>. So one s makes difference and calling a wrong method. In fact I am following the eclipse autocomplete :(. Obviously <code>driver.find_elements_by_link_text</code> returns list so If I send click event it wont understand.</p>
<p>Thanks for helping and sorry for my bad question</p>
<p>-Vikram</p> |
11,108,632 | Run Rails commands outside of console | <p>With my large application, the Rails console takes a while to load up. Is there a way to single commands more easily?</p>
<p>I'd also like to be able to automate stuff, and <code>echo "query" | rails console</code> isn't a great way to do things.</p>
<p>Thoughts?</p>
<p>EDIT: What about a long-running process that I can ping queries to whenever I have need?</p> | 11,111,175 | 3 | 7 | null | 2012-06-19 20:11:42.313 UTC | 4 | 2022-06-28 19:35:42.85 UTC | 2012-06-19 20:18:19.703 UTC | null | 569,183 | null | 569,183 | null | 1 | 52 | ruby-on-rails|ruby|ruby-on-rails-3|console | 21,887 | <p>There are two main ways to run commands outside console:</p>
<ol>
<li><p>Rake task which depends on :environment</p>
</li>
<li><p>rails runner (previously script/runner), eg:</p>
<pre><code>$ rails runner "query"
</code></pre>
</li>
</ol>
<p>Both are pretty well documented on the rails guide: <a href="https://guides.rubyonrails.org/command_line.html#bin-rails-runner" rel="noreferrer">https://guides.rubyonrails.org/command_line.html#bin-rails-runner</a></p>
<p>btw: both of these methods will still take the same time as a console to fire up, but they are useful for non-interative tasks.</p> |
11,124,777 | twitter bootstrap navbar fixed top overlapping site | <p>I am using bootstrap on my site and am having issues with the navbar fixed top. When I am just using the regular navbar, everything is fine. However, when i try to switch it to navbar fixed top, all the other content on the site shifts up like the navbar isn't there and the navbar overlaps it. here's basically how i laid it out:</p>
<pre><code>.navbar.navbar-fixed-top
.navbar-inner
.container
.container
.row
//yield content
</code></pre>
<p>i tried to copy bootstraps examples exactly but still having this issue only when using navbar fixed top. what am I doing wrong?</p> | 11,124,805 | 19 | 0 | null | 2012-06-20 17:17:19.563 UTC | 101 | 2021-11-27 14:05:35.447 UTC | 2019-11-26 04:25:14.323 UTC | null | 5,228,830 | null | 673,859 | null | 1 | 373 | html|twitter-bootstrap | 336,689 | <p>Your answer is right in the <a href="http://getbootstrap.com/components/#navbar-fixed-top" rel="noreferrer">docs</a>:</p>
<blockquote>
<h3>Body padding required</h3>
<p>The fixed navbar will overlay your other content, unless you add <code>padding</code> to the top of the <code><body></code>. Try out your own values or use our snippet below. Tip: By default, the navbar is 50px high.</p>
<pre><code>body { padding-top: 70px; }
</code></pre>
<p>Make sure to include this <strong>after</strong> the core Bootstrap CSS.</p>
</blockquote>
<p>and in the <strong>Bootstrap 4 docs...</strong></p>
<blockquote>
<p>Fixed navbars use position: fixed, meaning they’re pulled from the
normal flow of the DOM and may require custom CSS (e.g., padding-top
on the ) to prevent overlap with other elements.</p>
</blockquote> |
11,122,233 | Get current stack trace in Ruby without raising an exception | <p>I want to log the current backtrace (stacktrace) in a Rails 3 app <em>without</em> an exception occurring. Any idea how?</p>
<p>Why do I want this? I'm trying to trace the calls that are made when Rails looks for a template so that I can choose a part of the process to override (because I want to change the view path for a particular subclassed controller of mine).</p>
<p>I'd like to call it from the file: <code>gems\actionpack-3.2.3\lib\action_dispatch\middleware\templates\rescues\missing_template.erb</code>. I know that's not best practice, but I know it's downstream of the stack from where the search for templates occurs.</p> | 11,291,919 | 3 | 1 | null | 2012-06-20 14:51:59.623 UTC | 23 | 2019-08-01 19:10:32 UTC | 2012-07-02 16:28:54.863 UTC | null | 357,743 | null | 507,721 | null | 1 | 160 | ruby|stack-trace | 66,528 | <p>You can use <a href="https://ruby-doc.org/core/Kernel.html#method-i-caller" rel="noreferrer"><code>Kernel#caller</code></a>:</p>
<pre><code># /tmp/caller.rb
def foo
puts caller # Kernel#caller returns an array of strings
end
def bar
foo
end
def baz
bar
end
baz
</code></pre>
<p>Output:</p>
<pre><code>caller.rb:8:in `bar'
caller.rb:12:in `baz'
caller.rb:15:in `<main>'
</code></pre> |
47,992,371 | Where to get msbuild for Linux | <p>I want to build a .net core project on Windows and Linux.</p>
<p>For Windows I use MSBuild, simply downloaded the <code>Build Tools für Visual Studio 2017</code> from <a href="https://www.visualstudio.com/en/downloads/" rel="noreferrer">visualstudio.com</a>.</p>
<p>But where do I get MSBuild for Linux from? Based on the GitHub Project site, it should be available on some Linux distributions (<a href="https://github.com/Microsoft/msbuild/blob/master/README.md" rel="noreferrer">README.md</a>). I do not want to compile it myself (for some reasons).</p>
<p>I <strong>do not</strong> want to use xbuild, but pure MSBuild.</p> | 47,994,512 | 1 | 7 | null | 2017-12-27 12:40:09.403 UTC | 3 | 2019-05-28 06:44:22.147 UTC | null | null | null | null | 4,408,275 | null | 1 | 21 | linux|msbuild|.net-core | 63,781 | <p>You can obtain .NET Core SDK as described in these URLs.<br>
It is divided for each linux distribution.<br></p>
<p><a href="https://www.microsoft.com/net/learn/get-started/linuxredhat" rel="noreferrer">RHEL</a><br>
<a href="https://www.microsoft.com/net/learn/get-started/linuxubuntu" rel="noreferrer">Ubuntu</a><br>
<a href="https://www.microsoft.com/net/learn/get-started/linuxdebian" rel="noreferrer">Debian</a><br>
<a href="https://www.microsoft.com/net/learn/get-started/linuxcentos" rel="noreferrer">CentOS/Oracle</a><br>
<a href="https://www.microsoft.com/net/learn/get-started/linuxopensuse" rel="noreferrer">SLES/OpenSUSE</a><br></p>
<hr>
<p><strong>Updated:2019-03-19</strong> </p>
<p><a href="https://dotnet.microsoft.com/download" rel="noreferrer">.NET Downloads for Linux, macOS, and Windows</a><br>
Select the tab for the desired OS and then download.</p>
<p>related.<br>
<a href="https://github.com/Microsoft/msbuild" rel="noreferrer">Microsoft/msbuild</a><br>
<a href="https://github.com/Microsoft/msbuild/blob/master/documentation/wiki/Building-Testing-and-Debugging-on-.Net-Core-MSBuild.md" rel="noreferrer">msbuild/documentation/wiki/Building-Testing-and-Debugging-on-.Net-Core-MSBuild.md</a> </p>
<blockquote>
<p><strong>Getting .Net Core MSBuild binaries without building the code</strong><br>
The best way to get .NET Core MSBuild is by installing the <a href="https://github.com/dotnet/core-sdk" rel="noreferrer">.NET Core SDK</a>, which redistributes us. This will get you the latest released version of MSBuild for .NET Core. After installing it, you can use MSBuild through <code>dotnet build</code> or by manual invocation of the <code>MSBuild.dll</code> in the dotnet distribution.</p>
</blockquote> |
13,047,526 | Difference between Singleton implemention using pointer and using static object | <p>EDIT: Sorry my question was not clear, why do books/articles prefer implementation#1 over implementation#2?</p>
<p>What is the actual advantage of using pointer in implementation of Singleton class vs using a static object? Why do most books prefer this</p>
<pre><code>class Singleton
{
private:
static Singleton *p_inst;
Singleton();
public:
static Singleton * instance()
{
if (!p_inst)
{
p_inst = new Singleton();
}
return p_inst;
}
};
</code></pre>
<p>over this</p>
<pre><code>class Singleton
{
public:
static Singleton& Instance()
{
static Singleton inst;
return inst;
}
protected:
Singleton(); // Prevent construction
Singleton(const Singleton&); // Prevent construction by copying
Singleton& operator=(const Singleton&); // Prevent assignment
~Singleton(); // Prevent unwanted destruction
};
</code></pre> | 13,047,943 | 7 | 14 | null | 2012-10-24 10:38:43.03 UTC | 18 | 2014-12-13 17:09:17.403 UTC | 2012-10-24 10:46:52.577 UTC | null | 734,154 | null | 734,154 | null | 1 | 27 | c++|design-patterns|singleton | 22,477 | <blockquote>
<p>why do books/articles prefer implementation#1 over implementation#2?</p>
</blockquote>
<p>Because most articles describing the Singleton anti-pattern don't fully understand all the hidden dangers when trying to implement it safely in C++. It's surprisingly difficult to get it right.</p>
<blockquote>
<p>What is the actual advantage of using pointer in implementation of Singleton class vs using a static object?</p>
</blockquote>
<p>Using a pointer, with <code>new</code> but no <code>delete</code>, ensures that the object will never be destroyed, so there is no danger of accessing it after its lifetime has ended. Combined with the "lazy" creation, the first time that it's accessed, this guarantees that all accesses are to a valid object. The disadvantages are that creation is not thread-safe, and that the object and any resources it acquires are not released at the end of the program.</p>
<p>Using a local static object, creation is thread-safe on any compiler that supports the C++11 threading model; also, the object will be destroyed at the end of the program. However, it is possible to access the object after its destruction (e.g. from the destructor of another static object), which could lead to nasty bugs.</p>
<p>The best option is to avoid static data, and globally-accessible data, as much as possible. In particular, never use the Singleton anti-pattern; it combines global, static data with weird instantiation restrictions that make testing unnecessarily difficult.</p> |
13,119,582 | Immutable bitmap crash error | <pre><code>java.lang.IllegalStateException: Immutable bitmap passed to Canvas constructor
at android.graphics.Canvas.<init>(Canvas.java:127)
at app.test.canvas.StartActivity.applyFrame(StartActivity.java:214)
at app.test.canvas.StartActivity$1.onClick(StartActivity.java:163)
at android.view.View.performClick(View.java:4223)
at android.view.View$PerformClick.run(View.java:17275)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>I get this crash error from the developer console .. I don't understand what is the problem ..</p>
<pre><code> BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inScaled = true;
opt.inPurgeable = true;
opt.inInputShareable = true;
Bitmap brightBitmap = BitmapFactory.decodeResource(getResources(), position, opt);
brightBitmap = Bitmap.createScaledBitmap(brightBitmap, 550, 550, false);
chosenFrame = brightBitmap;
Bitmap workingBitmap = Bitmap.createBitmap(chosenFrame);
workingBitmap = Bitmap.createBitmap(workingBitmap);
Canvas c = new Canvas(workingBitmap);
</code></pre>
<p>I think it's related to this ?</p> | 13,119,762 | 5 | 0 | null | 2012-10-29 10:15:03.73 UTC | 18 | 2019-11-22 16:01:08.27 UTC | 2016-03-10 01:04:09.85 UTC | null | 2,642,204 | null | 1,780,939 | null | 1 | 84 | android|bitmap | 61,475 | <p>You have to convert your <code>workingBitmap</code> to <code>Mutable Bitmap</code> for drawing on <code>Canvas</code>. (Note: this method does not help save memory, it will use extra memory)</p>
<pre><code>Bitmap workingBitmap = Bitmap.createBitmap(chosenFrame);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
</code></pre>
<p>This answer helps don't waste memory
<a href="https://stackoverflow.com/a/9194259/925070">Convert immutable bitmap to a mutable bitmap</a></p> |
16,780,908 | Understanding the need for fflush() and problems associated with it | <p>Below is sample code for using fflush():</p>
<pre><code>#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
void flush(FILE *stream);
int main(void)
{
FILE *stream;
char msg[] = "This is a test";
/* create a file */
stream = fopen("DUMMY.FIL", "w");
/* write some data to the file */
fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
/* flush the data to DUMMY.FIL without closing it */
flush(stream);
printf("\nFile was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream)
{
int duphandle;
/* flush the stream's internal buffer */
fflush(stream);
/* make a duplicate file handle */
duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer */
close(duphandle);
}
</code></pre>
<p>All I know about fflush() is that it is a library function used to flush an output buffer. I want to know what is the basic purpose of using fflush(), and where can I use it. And mainly I am interested in knowing <strong>what problems can there be with using fflush().</strong></p> | 16,781,818 | 3 | 3 | null | 2013-05-27 21:45:29.297 UTC | 15 | 2017-03-01 00:09:52.923 UTC | 2017-03-01 00:09:52.923 UTC | null | 1,538,270 | null | 1,616,317 | null | 1 | 17 | c|fflush | 50,487 | <p>It's a little hard to say what "can be problems with" (excessive?) use of <code>fflush</code>. All kinds of things <em>can</em> be, or become, problems, depending on your goals and approaches. Probably a better way to look at this is what the intent of <code>fflush</code> is.</p>
<p>The first thing to consider is that <code>fflush</code> is defined only on output streams. An output stream collects "things to write to a file" into a large(ish) buffer, and then writes that buffer to the file. The point of this collecting-up-and-writing-later is to improve speed/efficiency, in two ways:</p>
<ul>
<li>On modern OSes, there's some penalty for crossing the user/kernel protection boundary (the system has to change some protection information in the CPU, etc). If you make a large number of OS-level write calls, you pay that penalty for each one. If you collect up, say, 8192 or so individual writes into one large buffer and then make one call, you remove most of that overhead.</li>
<li>On many modern OSes, each OS write call will try to optimize file performance in some way, e.g., by discovering that you've extended a short file to a longer one, and it would be good to move the disk block from point A on the disk to point B on the disk, so that the longer data can fit contiguously. (On older OSes, this is a separate "defragmentation" step you might run manually. You can think of this as the modern OS doing dynamic, instantaneous defragmentation.) If you were to write, say, 500 bytes, and then another 200, and then 700, and so on, it will do a lot of this work; but if you make one big call with, say, 8192 bytes, the OS can allocate a large block once, and put everything there and not have to re-defragment later.</li>
</ul>
<p>So, the folks who provide your C library and its stdio stream implementation do whatever is appropriate on your OS to find a "reasonably optimal" block size, and to collect up all output into chunk of that size. (The numbers 4096, 8192, 16384, and 65536 often, today, tend to be good ones, but it really depends on the OS, and sometimes the underlying file system as well. Note that "bigger" is not always "better": streaming data in chunks of four gigabytes at a time will probably perform worse than doing it in chunks of 64 Kbytes, for instance.)</p>
<p>But this creates a problem. Suppose you're writing to a file, such as a log file with date-and-time stamps and messages, and your code is going to keep writing to that file later, but right now, it wants to suspend for a while and let a log-analyzer read the current contents of the log file. One option is to use <code>fclose</code> to close the log file, then <code>fopen</code> to open it again in order to append more data later. It's more efficient, though, to push any pending log messages to the underlying OS file, but keep the file open. That's what <code>fflush</code> does.</p>
<p>Buffering also creates another problem. Suppose your code has some bug, and it sometimes crashes but you're not sure if it's about to crash. And suppose you've written something and it's very important that <em>this</em> data get out to the underlying file system. You can call <code>fflush</code> to push the data through to the OS, before calling your potentially-bad code that might crash. (Sometimes this is good for debugging.)</p>
<p>Or, suppose you're on a Unix-like system, and have a <code>fork</code> system call. This call duplicates the entire user-space (makes a clone of the original process). The stdio buffers are in user space, so the clone has the same buffered-up-but-not-yet-written data that the original process had, at the time of the <code>fork</code> call. Here again, one way to solve the problem is to use <code>fflush</code> to push buffered data out just before doing the <code>fork</code>. If everything is out before the <code>fork</code>, there's nothing to duplicate; the fresh clone won't ever attempt to write the buffered-up data, as it no longer exists.</p>
<p>The more <code>fflush</code>-es you add, the more you're defeating the original idea of collecting up large chunks of data. That is, you are making a tradeoff: large chunks are more efficient, but are causing some other problem, so you make the decision: "be less efficient here, to solve a problem more important than mere efficiency". You call <code>fflush</code>.</p>
<p>Sometimes the problem is simply "debug the software". In that case, instead of repeatedly calling <code>fflush</code>, you can use functions like <code>setbuf</code> and <code>setvbuf</code> to alter the buffering behavior of a stdio stream. This is more convenient (fewer, or even no, code changes required—you can control the set-buffering call with a flag) than adding a lot of <code>fflush</code> calls, so that could be considered a "problem with use (or excessive-use) of <code>fflush</code>".</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.