iOS - change gradient background of UIButton or custom UIButton

Question: I created my own class derived from UIButton with .h file:
@interface MenuButton : UIButton

- (void)changeBackground;

@end

In implementation I tried to add some methods for changing background but without success so far:
#import "MenuButton.h"
#import "GradientLayers.h"

@implementation MenuButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder;
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit;
{

    // Gradient background
    CAGradientLayer *gradient = [GradientLayers darkBlueBackground];
    gradient.frame = [self layer].bounds;

    // Insert background
    [[self layer] insertSublayer:gradient atIndex:0];

    [[self layer] setCornerRadius:10.0f];
    [[self layer] setMasksToBounds:YES];
    [[self layer] setBorderWidth:2];
    [[self layer] setBorderColor:[[UIColor blackColor] CGColor]];

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // handle touch
    [super touchesEnded:touches withEvent:event];

    if ([self state] != UIControlStateSelected)
    {
        CAGradientLayer *gradient = [GradientLayers blackBackground];
        gradient.frame = [self layer].bounds;
        [[self layer] insertSublayer:gradient atIndex:0];
    }
    else
    {
        CAGradientLayer *gradient = [GradientLayers darkBlueBackground];
        gradient.frame = [self layer].bounds;
        [[self layer] insertSublayer:gradient atIndex:0];
    }
}

- (void)changeBackground
{
    CAGradientLayer *gradient = [[[self layer] sublayers] firstObject];
    gradient = [GradientLayers blackBackground];
    [[self layer] insertSublayer:gradient atIndex:0];
    [self setNeedsDisplay];
}

@end

Part of GradientLayer.m file:
#import "GradientLayers.h"

@implementation GradientLayers

+ (CAGradientLayer*) blackBackground {
    // similar to darkBlueBackground
}

+ (CAGradientLayer*) darkBlueBackground {
    // Create colors
    UIColor *darkOp = [UIColor colorWithRed:0.039f green:0.106f blue:0.278f alpha:1.0];
    UIColor *lightOp = [UIColor colorWithRed:0.133f green:0.267f blue:0.65f alpha:1.0];

    // Create gradient
    CAGradientLayer *gradient = [CAGradientLayer layer];

    // Set colors
    gradient.colors = [NSArray arrayWithObjects:
                       (id)lightOp.CGColor,
                       (id)darkOp.CGColor,
                       nil];

    // Shadow
    gradient.shadowOffset = CGSizeMake(3.0f, 3.0f);
    gradient.shadowColor = [UIColor blackColor].CGColor;
    gradient.shadowOpacity = 0.6;
    gradient.shadowRadius = 10;

    // Other options
    gradient.borderWidth = 0.5f;
    gradient.borderColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0].CGColor;
    gradient.cornerRadius = 10;

    return gradient;
}

@end

I have my buttons with darkBlueBackground as set in commonInit. It's not a problem. But I want to change it after user taps on button and so far without luck. If I set breakpoint I am in touchesEnded or changeBackground but after execution the button has same background as before. So how can I change background to another gradient background? Thanks
Answer: Because the [self layer].sublayers array is listed in back to front order (https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/CALayer_class/Introduction/Introduction.html#//apple_ref/occ/instp/CALayer/sublayers), by inserting your replacement layer at index 0, you're always putting it behind the old gradient.
You should remove the old gradient layer and then add the new one.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // handle touch
    [super touchesEnded:touches withEvent:event];

    // Remove old gradient here
    [[[[self layer] sublayers] objectAtIndex:0] removeFromSuperlayer];

    if ([self state] != UIControlStateSelected)
    {
        CAGradientLayer *gradient = [GradientLayers blackBackground];
        gradient.frame = [self layer].bounds;
        [[self layer] insertSublayer:gradient atIndex:0];
    }
    else
    {
        CAGradientLayer *gradient = [GradientLayers darkBlueBackground];
        gradient.frame = [self layer].bounds;
        [[self layer] insertSublayer:gradient atIndex:0];
    }
}

- (void)changeBackground
{
    // Remove old gradient here
    [[[[self layer] sublayers] objectAtIndex:0] removeFromSuperlayer];

    CAGradientLayer *gradient = [[[self layer] sublayers] firstObject];
    gradient = [GradientLayers blackBackground];
    [[self layer] insertSublayer:gradient atIndex:0];
    [self setNeedsDisplay];
}

You really should keep track of the gradient better, so you're not constantly removing and replacing it with the same gradient. Perhaps maybe just showing and hiding the selected state, which would always just sit above the unhighlighted version.
Comment: Thanks for help. Second answer was good too but the user deleted it. It could be helpful for other users because second answer shown that there is `replaceSublayer` method and I could use in my method this call `[[self layer] replaceSublayer:prevGradient with:newGradient];`


Browserify bundle.js Error: exec is not a function

Question: I recently installed Node.js, npm, samba-client and browserify. The Problem is, that i get an Uncaught TypeError in my bundle.js File and i'm not able to resolve this.
bundle.js:107
    Uncaught TypeError: exec is not a function
    at SambaClient.execute (bundle.js:107)
    at SambaClient.mkdir (bundle.js:58)
    at Object.8.samba-client (bundle.js:1319)
    at s (bundle.js:1)
    at e (bundle.js:1)
    at bundle.js:1

I did some research and found out, that it could be the package.json File that is somewhat wrong.
{
  "name": "package.json",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "lib": "lib"
  },
  "dependencies": {
    "child_process": "^1.0.2",
    "debug": "^3.1.0",
    "open": "0.0.5",
    "path": "^0.12.7",
    "samba-client": "^2.0.0",
    "util": "^0.10.3"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

But if i'm honest, i have no clue what to do.
This is the part, where it fails first in bundle.js:
SambaClient.prototype.execute = function(cmd, cmdArgs, workingDir, cb) {
  var fullCmd = wrap(util.format('%s %s', cmd, cmdArgs));

  var command = ['smbclient', this.getSmbClientArgs(fullCmd).join(' ')].join(' ');

  var options = {
    cwd : workingDir
  };

  **exec(command, options, function(err, stdout, stderr) {**
    var allOutput = (stdout + stderr);
    if(err !== null) {
      err.message += allOutput;
    }
    cb(err, allOutput);
  });
};

Hopefully someone can help me. :)
Comment: Why are you using Browserify on NodeJS code? Or are you trying to use a Samba client from a web browser?
Comment: Exact. I'm trying to use samba-client from a web browser. Is that possible?
Comment: No, it is not and probably never will be. The browser's security model won't allow it. Imagine that a random website could access Samba shares visible to your machine... brrr. What you can do is run a local NodeJS server that does the Samba communication, and have a browser based frontend for that.
Comment: Somehow logical - damn. That was eye-opening. Thank you. :)
Answer: Have you import correctly the exec function ?
const exec  = require('child_process').exec;


Snakemake and bash script pipefails

Question: I am attempting to create a snakemake pipeline that is robust to multiple error sources. I would like to call a bash script within my pipeline. One standard procedure for alerting a user of a problem is to use the following at the beginning of a bash script:
#!/bin/bash

set -e
set -u
set -o pipefail

The pipefail checks for errors when redirecting std out using pipes. My script has the following simple lines of code within it
# Read the first argument
input=$1

less $input | head -10

When I run my script using directly in the terminal using
bash script.sh input

it runs completely fine and no errors are detected.
I then wish to run this script within a snakemake pipeline in a rule as follows:
    shell:
        """
        bash script.sh {input}
        """

snakemake throws an error:
        (one of the commands exited with non-zero exit code; note that snakemake uses bash strict mode!)

If I then remove the pipefail condition
# set -o pipefail

and then re-run snakemake I have no problems whatsoever and the script executes beautifully.
Can anyone explain this interaction between a seemingly successful pipe and how snakemake treats it? (or at least give pointers to diagnose it).
Comment: Does this snakemake thing have a proper documentation?
Answer: Your script:
#!/bin/bash

set -e
set -u
set -o pipefail

input=$1

less $input | head -10

Doesn't really exit clean if the input has more then 10 lines. You can check it with:
bash script.sh longfile.txt
echo $? # -> Prints 141

echo $? returns the exit exit code of the previous process which is 141 here because head broke the pipe (google exit code 141 to know more about it).
Snakemake detects the non-zero exit code and, accordingly, fails because snakemake executes shell scripts in strict mode (google snakemake strict shell mode). How you want to handle the case is up to you but this should be the explanation for the seemingly inconsistent behaviour you see.
Comment: I just ran this directly in the command line and got a 0 exit code by giving the script a text file with 121 lines. This doesn't throw a non-zero exit code when I run it directly. Only when I run it within snakemake.
Comment: It would be nice if @Aidan's observation was explained in the answer. I'm facing a somewhat similar issue where snakemake run locally succeeds, but when run via a github action, results in the same error with no useful or informative error output, even with the `--verbose` flag. What explains the discrepancy?
Comment: @hepcat72 Aidain doesn't give enough information for a conclusive answer. It would be useful to have the file s/he is using, the bash script, and the snakefile, ideally stripped down to the minimum for us to try it. Regarding your comment, I would post it as a separate answer with more details.
Comment: Regarding my issue, I don't feel like I have enough knowledge of what's going on yet to formulate a well defined question (let alone answer Aidan's question), TBH. I'm just grasping at straws. Since I cannot reproduce the github action failure locally and there is no error message other than "a command failed" in the github action log, I don't know what is causing the gh error. If I find out more, I may post a question of my own.

Snakemake and bash script pipefails


How do I patch NWN2?

Question: I recently bought a legit copy of Neverwinter Nights 2 on sale at a bookstore.  Yes I know it's 11 years old now. I'd still like to be able to patch the game, but alas the site nwn2.com seems long gone. I checked archive.org and a few other places and even links on game cheats are gone.
How can I patch the game now that most of the resources and support for it seem to be missing?
Comment: Have you tried installing on Steam? They might have the latest version.
Comment: Are there legitimate no-CD patches?  It seems like a way to bypass the DRM.
Comment: +JMac I've removed that part of my question.
Comment: +Viper_Sb It's not on Steam.
Comment: Just curious, was it really cheap?   Cheaper than GOG.com @ 75% discount?
Comment: I paid $1 for it in the bargin bin at a used bookstore.  It is the gold edition and also came with the mask of the betrayer expansion and I think someone mistakenly put Company of Heroes in the box too. Can't get much cheaper than that. :-)
Answer: To the Vault!
The Neverwinter Vault may be useful to you; specifically their patches section.
Change the game drop-down to 'NwN2' and patch drop-down to 'Obsidian' (or 'All') and it should bring up all the files you require to update the game from vanilla to a version that satisfies. I believe you need to run each file (i.e from 1.00788 to 1.02809, etc.) individually as you require to update the game.
Alternatively, there is also an additional, optional NwN2 Patcher by tnt220 which would let you update the game offline, but requires the patch files (linked above) to be obtained prior to using the tool. This appears to be an automated process which could reduce some of the monotony of running each patch individually.

How do I patch NWN2?


Node.js BinaryServer: Send a message to the client on stream end?

Question: I'm using a node.js BinaryServer for streaming binary data and I want a callback event from the server, after the client calls for the .Stream.end() function.
I can't seem to understand - How can I send a message or some kind of notification when the node.js server actually closes the stream connection ?
Node JS:
server.on('connection', function(client) {

    client.on('stream', function (stream, meta) {

        stream.on('end', function () {
            fileWriter.end();
            // <--- I want to send an event to the client here
        });
    });

});

client JS:
client = new BinaryClient(nodeURL);
window.Stream = client.createStream({ metaData });
....
window.Stream.end();
//  <--- I want to recieve the callback message

Comment: According to [documentation](https://github.com/binaryjs/binaryjs/blob/master/doc/api.md#event-end) `.end()` appears to expect a function as parameter _"Is emitted when `stream.end` has been called. `stream.readable` is set to false."_ `window.Stream.end(function() {// stream ended});`
Comment: On the Node JS side, you can try `client.send("finished")`
Comment: @ExplosionPills And what should I do on the client side ?
Comment: Listen to the `stream` event, `client.on("stream", data => /* do something with data */)`
Comment: @ExplosionPills Sorry, didn't get it, can you explain the code precicely on the client and on the server side ?
Answer: On the server side, you can send streams to the client with .send. You can send a variety of data types, but a simple string will probably suffice in this case.
On the client side you can also listen to the 'stream' event to receive data back from the server.
Node JS:
server.on('connection', function(client) {
    client.on('stream', function (stream, meta) {
        stream.on('end', function () {
            fileWriter.end();
            client.send('finished');
        });
    });
});

client JS:
client = new BinaryClient(nodeURL);
client.on('stream', data => {
    console.log(data); // do something with data
});
window.Stream = client.createStream({ metaData });
....
window.Stream.end();

Comment: I added the code you suggested, but `client.on('stream', data =>` is never triggered.


MySQL escaped_strings VS. Parameterised Queries

Question: Just reading up on Parameterised queries, which seem to be the last word in database defence, and was wondering the following:
I have an existing PHP/MySQL self-built CMS where ALL inputs (bar checkboxes and radio buttons) are subject to real_escape_string. There is an admin section accessible via a sha1 encrypted password and a matching username where a small (3) group of trusted people can update content (tinyMCE), upload photos, etc. Strictly smalltime. None of my queries are parameterised, but are only executed after escaping.
There are no inputs taken from the general public, but I do want to open it up to user-submitted forms later.
My host is a private one, with a very good record.
All else being equal, how secure am I?
Answer: mysql_real_escape_string does not immediately protect you from SQL injection attacks. I recently helped the developer of a small site who thought he was safe my calling mysql_real_escape_string on all of the inputs, but still got pwn'd. In his case, he was expecting a variable (via GET string) to be an integer, but was not verifying it as such. The attackers then utilized that ID field to craft custom queries and gain access to his entire database.
The moral of the story? Validate, validate, validate. You need to assume every possible piece of data coming from the outside (even if it's an <input type="hidden"> that you populate) is an attempt to bypass security measures.  This is where using frameworks like Codeigniter, etc. are helpful, because they have validation components built right in.  If you want to do everything yourself, just be careful, and check all input variables.
Comment: By validation, do you mean casting, then escaping? Or is there more that can be done?
Comment: In the case I mentioned, a simple `is_numeric` would have prevented the issue.
Answer: I'd rather use parametrized / prepared statements. Compared to just escaping input, they let you specify type which is handy (you don't have, for instance, to convert datetime values to server-specific format), and it also resolves ambiguity in handling conversion errors by different RDMS. For example, query SELECT * FROM table1 WHERE int_field='aaa' (int_field is integer) returns records with int_field equals 0 in Mysql, raises error in Oracle and SQLServer, and returns empty set in SQlite
Comment: Yes, parameterisation seems to be the way to go. I was wondering, however, how necessary it would be for someone to rewrite so many queries for that purpose when those queries had already been escaped...
Comment: @Eamonn: In my opinion, that all depends on the project. Sometimes it's not possible to implement all the best practices because of limited time/human resources... Also, the cost of such refactoring is tied with overall application design. Keeping all sql queries in separate module, and accessing db only through dedicated data access layer significantly reduces amount of work.
Comment: It certainly seems very efficient for larger applications - as a futher query, do you know of a good resource to guide me in building such a framework, or is it very much a case of whatever suits the moment?
Comment: I can recommend some books that might be useful (in my subjective opinion). They cover different aspects of software engineering and help building robust systems. Domain Driven Design by Eric Evans, Working Effectively with Legacy Code by Michael Feather, Refactoring to Patterns by Joshua Kerievsky, Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin.
Comment: Thats great, thanks for that - very helpful! I will certainly look all of those up. I'm going to hold off on selecting the answer for a bit longer, as I'm curious to see what flaws people will point out on a purely real_escaped system. But thanks again!


jQuery detach content with events?

Question: My question is, why isn't the click event on the third div triggered anymore, after i've detached the elements and appended them back? The events aren't preserved.
var test = (function($, undef) {
    var t = {};
    t.test = function(){
        var container = $('
').appendTo('body');
        $('
', {
            'class' :   'some',
            'text'  :   'text'
        }).appendTo(container);
        $('
', {
            'class' :   'some',
            'text'  :   'text'
        }).appendTo(container);
        $('
', {
            'class' :   'some',
            'text'  :   'text',
            'click' :   function(){
                console.log("ahoy");
            }
        }).appendTo(container);
        $('
', {
            'class' :   'some',
            'text'  :   'text'
        }).appendTo(container);
        var content = container.html();
        var detachedContent = $(content).detach();
        container.empty();
        //setTimeout(function(){
            container.append(detachedContent);
        //}, 2000);
    };
    return t;
})(jQuery);
test.test();

example: http://jsfiddle.net/sCJfc/
Answer: detach() is not to blame here.
You're performing a copy of the container element's inner markup, and you're detaching the elements created from that copy. These elements are not part of the DOM to begin with, and will indeed not have any handler registered on them.
Try writing:
var detachedContent = container.children().detach();

Instead of:
var content = container.html();
var detachedContent = $(content).detach();

Comment: Yep, it's said in the .html() API. Thanks :)
Answer: Try cloning the child elements, removing them and then adding them back using the clone.
var detachedContent = $(container).children().clone(true);
console.log(detachedContent);
container.empty();

container.append(detachedContent);

Working Example: http://jsfiddle.net/sCJfc/2/

jQuery detach content with events?


How to restore power after tripping a surge protection device?

Question: What happened
A new electric kettle apparently caused a loss of power in a circuit.  The circuit is one of two 120V/20A lines protected by an Intermatic PanelGuard model IG1240R surge protection device (SPD) at the panel. (This appears to be an older model.  A similar device is described at http://www.intermatic.com/Products/SurgeProtectiveDevices/IG_Series/IG1240RC3.aspx.)  The circuit breaker was not tripped, nor did either of the line monitor lights on the SPD go out (indicating it thinks it is working properly).
The problem
I have been unable to restore power to this circuit.  Of course the kettle was immediately unplugged (and seems to be working properly on a different circuit).  All I can see to do is make sure all connections at the panel are secure and to flip the circuit breaker switches off and back on. I cannot open up the SPD itself and it has no external controls--only its two monitoring lights.  Testing with an ohmmeter at the receptacle shows continuity.  The voltmeter verifies no current at the receptacle, but there is current between the circuit breaker and the SPD.  There is current throughout the other line protected by the SPD.
Additional information
This is the first such loss of power we have experienced in this circuit in the 10 years we have lived here, so presumably it is correctly wired.
There are no receptacle-GFCIs installed on this circuit: just plain 3-prong 2-outlet receptacles.  Each has a little label stating it is GFCI protected and refers to "instructions" at the panel--of which there are none.
The question
This all points to a defective SPD, but am I perhaps missing something?  What does it take to reset one of these things?
Comment: The GFCI for the circuit might be in a bathroom.  Check the GFCI's in the house as one might be feeding the kitchen (which should be on GFCI)
Comment: @diceless Thank you for the suggestion.  This is a dedicated kitchen circuit--no connections to a bathroom.  There are four outlets, all ordinary (non-GFCI) 3-prong receptacles.  However, your suggestion inspired me to hunt around and I found an isolated GFCI (with no outlets) in the basement beneath the kitchen: sure enough, it's on the circuit and was tripped.  If you would be so kind as to paste your comment into an answer I would be glad to accept it.
Answer: The GFCI for the circuit might be in a bathroom. Check the GFCI's in the house as one might be feeding the kitchen (which should be on GFCI)
Comment: +1 The suggestion to look harder for a (hidden, unexpected) GFCI solved the problem: many thanks.


What does GPU serialized mean?

Question: With GPU isolation : multiple processes use the single GPU will be serialized, cause OOM easily
link
https://www.slideshare.net/mobile/Hadoop_Summit/deep-learning-on-yarn-running-distributed-tensorflow-etc-on-hadoop-cluster-v3
slide number 17
Comment: Can you give more context to your question? Is this a quote from some documentation? Can you link where you read it?
Answer: It's saying that if you're using a single GPU, the multiple processes attempting to use the GPU will be queued up and run one at a time rather than some or all being run in parallel. If you have multiple GPUs some of the processes can be run at the same time.

What does GPU serialized mean?


SearchDisplayControler, UILabel stacking after selection

Question: I'm trying to implement a searchDisplayController but I've a problem. Once I filtered the cell and when I selected the cell remaining I get a strange stack of text :
http://postimage.org/image/4fswe8t8n/
It's like having all my cell in one.
So there's my cellForRowAtIndexPath method :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"MFriendCell";

UITableViewCell *cell = [tableView
                         dequeueReusableCellWithIdentifier:CellIdentifier];

if(cell == nil)  {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

if(tableView == self.tableView) {
    UILabel *nameLabel = (UILabel *)[cell viewWithTag:201];
    nameLabel.text = [self.allItems objectAtIndex:indexPath.row];
}
else if(tableView == self.searchDisplayController.searchResultsTableView) {
    UILabel *labelName = [ [UILabel alloc ] initWithFrame:CGRectMake(50, 0.0, 150.0, 43.0) ];
    labelName.text = [self.searchResults objectAtIndex:indexPath.row];

    [cell addSubview:labelName];
}
return cell;
}

And my filter :
- (void)filterContentForSearchText:(NSString*)searchText
                         scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
                                predicateWithFormat:@"SELF contains[cd] %@",
                                searchText];

self.searchResults = [self.allItems filteredArrayUsingPredicate:resultPredicate];
}

if you need anything else just ask :)
Comment: this is because you are setting a new label on previous label
Comment: Change the text, but it's ok I changed the way I was manipuling my UILabel and now it's working just fine ;)
Comment: Is it because my logic is bad or I should just add something to check if there are already a label?
Comment: you want to add different label or set your text to previous label
Answer: Just add nameLabel in cell same like labelName see the code bellow..
if(tableView == self.tableView) {
    UILabel *nameLabel = (UILabel *)[cell viewWithTag:201];
    nameLabel.text = [self.allItems objectAtIndex:indexPath.row];
    [cell addSubview:nameLabel]; ///YOU ARE Not add This Lable so Add this lable also
}
else if(tableView == self.searchDisplayController.searchResultsTableView) {
    UILabel *labelName = [ [UILabel alloc ] initWithFrame:CGRectMake(50, 0.0, 150.0, 43.0) ];
    labelName.text = [self.searchResults objectAtIndex:indexPath.row];

    [cell addSubview:labelName];
}

here in your didSelectRowAtIndexPath method u just take value of self.allItems array instead of self.searchResults array WHEN you are in searchResultTableView
try this code
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;{
     if(tableView == self.tableView) {
         NSLog("\n Normal Table View Selected cell ==> %@",[self.allItems objectAtIndex:indexPath.row]);

    }
    else if(tableView == self.searchDisplayController.searchResultsTableView) {
           NSLog("\n Search TableView Selected cell ==> %@",[self.searchResults objectAtIndex:indexPath.row];);

    }
}

and also in numberOfRowsInSection method set row like bellow...
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == self.tableView) {
             return [self.allItems count];

        }
        else{
               return [self.searchResults count];
        }
}

i hope this help you...
Comment: @BaNz you add [cell addSubview:labelName]; but not add same like[cell addSubview:nameLabel]; in if(tableView == self.tableView) { this condition dude.. try it..
Comment: Thanks for trying to help me but I think like Rajneesh071 said, it's because I'm adding multiple time a label to the subview of the cell.
Comment: yes dude but here also possible to problem which i tell and also here you see the latest label with your title so must required to add current label on cell as a subview right dude??
Answer: You can make label in you tableView like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MFriendCell";

    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    UILabel *nameLabel = (UILabel *)[cell viewWithTag:201];

    if(tableView == self.tableView)
    {
       nameLabel.text = [self.allItems objectAtIndex:indexPath.row];
    }

    else if(tableView == self.searchDisplayController.searchResultsTableView)
    {
        labelName.text = [self.searchResults objectAtIndex:indexPath.row];
    }
    return cell;
}


can i load 12.04 into a completely formatted pc via a usb stick?

Question: when my son was given a pc that needed its original windows disc to boot again, i had an ubuntu 9.04 disc so we loaded that in instead, removing windows in the process. however, since this was an older version of ubuntu, there was a lot he couldn't use or do, so i sent off for a 12.04 usb stick. we are trying to load this into his computer but can't get things running as they should - he has to have the old disc in to start the pc in the first place. Is there a way we can remove everything and just turn on the pc with new usb inserted and things will load in fresh from there?
Answer: You have to insert the usb with the computer off. Then turn it on and enter the BIOS as soon as possible at the start up (sometimes pressing the F8 or Esc or F12, depending on your machine, it usually tells you what key to press at the splash screen (when the mainboard/processor manufacturer logo appears). Once inside the BIOS go to the boot device priority and tell it to boot from the USB stick. In some cases the USB stick does not appear as Removable Device but appears as Hard Disk Drive, double check just in case. Save and Exit. Then your machine should boot from the USB. Once in Live Ubuntu, install the OS and choose the option to use the whole HDD (not to upgrade/use along other prior OS).
Comment: thanks for your reply - seems we're unable to format at the moment, and we're busy trying to do that first. otherwise all we get up is the screen  (after selecting language) that asks where we're booting form and won't accept anything other than the disc. busy right now but if i can format it i'll run the process as you've suggested. thanks again for your time.
Comment: What screen are you talking about? BIOS screen? or Ubuntu Start Up screen?


In what instance can a bedroom not have a proper egress window

Question: Wife and I were watching one of the home improvement/ flip  shows.  We noticed that in a bedroom the owner had the big window with the lower sill taken out and only 2 small windows with the sills at about 48" remained in the room.  There was no door to the exterior.
We both commented that they would have to replace the window because of egress code.  In the end the home was done and no new window. Only the 2 small ones in the bedroom.
How is this allowed. Or is it not, as I suspected, and the show was just BS as most of them are?
The home was in Vermont.  Special building codes there?
If this get closed, I'm ok with it, just knew there would be people on here that knew the code for sure.
Comment: Locally over on the west coast, I think that I wouldn't be allowed to call it a "bedroom." It's an "office," "rec room," etc. The code uses the term "sleeping room" in the emergency escape and rescue opening section. There's no definition listed, so it's down to your choice of dictionary. As long as there isn't a sleeping affordance in there, e.g. a bed, I suspect that it's conformant. A fold out sofa would be an interesting edge case.
Comment: Could be weird code.  It was not permitted/inspected.  Windows were bigger than they looked on tv.
Comment: In my locale (SoCal) there is no such requirement that I am aware of except for in special occupancies, such as foster homes and other care home settings, or special conditions, such as basement bedrooms.
Comment: @Jimmy, see [IRC R310.1](https://codes.iccsafe.org/content/IRC2021P2/chapter-3-building-planning#IRC2021P2_Pt03_Ch03_SecR310.1).
Comment: @popham, thanks I see that now So if the room OP is referencing was indeed a sleeping room it would not comply because the bottom of the opening is greater than 44" from the floor (and also perhaps because the opening is too small).
Answer: Depending precisely where in Vermont, there might not be a building code official to actually inspect it, so it might only come to official attention after it kills someone.
The cities (and ski-area-towns) tend to be pretty loaded with the usual bureaucracy, the smaller towns not so much.
One is supposed to follow applicable codes, but if nobody checks, some people won't.
I live in a small town. I had to have the road crew head decide that my driveway did not need a culvert, I had to submit a zoning application, and I had to have the health department guy look at my septic installation. No other official town input on my building. While this might horrify some, I look at it as "here's your personal responsibility - if the building you put up falls down, that's your problem, so you might want to make sure it doesn't."
This only applies to single-family-residential - as far as I recall the State does inspections for commercial work.
Comment: Thank You for the explanation.
Comment: The County I live in allows single family residential construction to declare that you are going to follow code, your title gets flagged, then only septic and electrical inspections are required for a legal build. Even on non-flagged parcels no permit needed for agricultural (barns and sheds).


How do I level up just my attributes in Dragon Age: Origins (PS3)?

Question: Is any one still playing dragon age origins?  I need to know how I got stuck leveling up as far as attributes go?  I cant level up anymore as it seems to keep me from completing the level up after using my points.  Is it because of glicth usage or should i start over and plan the levels?
Comment: @lilserf - you beat me to the edit by 9 seconds, ahaha.
Comment: Heh, that's amusing.
Answer: There are plenty of people that play it still.
To answer your question, there is a level cap on Dragon Age: Origins, sort of.
You cap at 25 and then due to a bug in the game you cannot hit 26, unless you get Awakening.
Comment: I agree - the same has happened to me. Getting awakening should solve your problem


Symfony2 with typeahead.js: How to pass %QUERY to path parameter

Question: I wanna use typeahead.js within my symfony2 project. Therefor i have the following javascript:
    $(document).ready(function(){

        var players = new Bloodhound({
          datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); },
          queryTokenizer: Bloodhound.tokenizers.whitespace,
          remote: "{{ path('_api_player_search', {searchterm: '%QUERY', limit: 5}) }}",
          prefetch: ''
        });

        players.initialize();

        $('#searchfield').typeahead(null, {
          displayKey: 'firstname',
          source: players.ttAdapter(),
          templates: {
            suggestion: Handlebars.compile(
              '{% verbatim %}
{{firstname}} – {{lastname}}
{% endverbatim %}'
            )
          }
        });
    });

As you can see, i want to pass an url created by the twig path helper to the remote: property of the Bloodhound() configuration. (Later i want to use FOSJsRoutingBundle for that purpose).
The thing is now, that Bloodhound() do not replace the %QUERY placeholder in my twig expression. Is there any way to achieve this?
Your help would really be appreciated! :)
Comment: I would consider using `%QUERY` as a GET parameter
Comment: Yeah i have rewriten my method now to get searchterm as a get-parameter, not in url directly.
Now i have to replace the url in remote: with a custom ajax-function like remote:function(){...} ??
Comment: `remote: "{{ path('_api_player_search') }}?limit=5&searchterm=%QUERY"`
Answer: Ok i've found a solution:
According to @Peter Bailey's answer on this question i have created a custom twig extension to be able to add an url_decode filter to my {{ path() }} tag like {{ path() |url_decode }}.
This will prevent %QUERY to be converted to %25QUERY, an then it could be replaced in the rendered url by javascript.
Additionally i also add a |raw filter, to avoid the ampersand beeing encoded. So finally my tag looks something like this: {{ path() |url_decode|raw }}


How to figure out what the address of an invalid is

Question: Valgrind reports:
<code>==4538== Invalid read of size 4
==4538==    at 0x822D3C6: _zval_ptr_dtor (zend.h:385)
==4538==    by 0x823C1FF: _zval_ptr_dtor_wrapper (zend_variables.c:189)
==4538==    by 0x824E1A1: zend_hash_destroy (zend_hash.c:529)
==4538==    by 0x826655A: zend_object_std_dtor (zend_objects.c:45)
==4538==    by 0x8266A28: zend_objects_free_object_storage (zend_objects.c:126)
==4538==    by 0x826C43D: zend_objects_store_del_ref_by_handle_ex (zend_objects_API.c:220)
==4538==    by 0x826C0AC: zend_objects_store_del_ref (zend_objects_API.c:172)
==4538==    by 0x823BD77: _zval_dtor_func (zend_variables.c:52)
==4538==    by 0x822B99B: _zval_dtor (zend_variables.h:35)
==4538==    by 0x822D463: _zval_ptr_dtor (zend_execute_API.c:443)
==4538==    by 0x823C1FF: _zval_ptr_dtor_wrapper (zend_variables.c:189)
==4538==    by 0x824E518: zend_hash_apply_deleter (zend_hash.c:614)
==4538==  Address 0x44c1718 is 8 bytes inside a block of size 20 free'd
==4538==    at 0x4026E9C: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4538==    by 0x8216374: _efree (zend_alloc.c:2358)
==4538==    by 0x822D48E: _zval_ptr_dtor (zend_execute_API.c:444)
==4538==    by 0x469B2C5: zim_ASTTree___destruct (parser.c:336)
==4538==    by 0x822F8CE: zend_call_function (zend_execute_API.c:986)
==4538==    by 0x825A8E2: zend_call_method (zend_interfaces.c:97)
==4538==    by 0x8266978: zend_objects_destroy_object (zend_objects.c:112)
==4538==    by 0x826C2AD: zend_objects_store_del_ref_by_handle_ex (zend_objects_API.c:206)
==4538==    by 0x826C0AC: zend_objects_store_del_ref (zend_objects_API.c:172)
==4538==    by 0x823BD77: _zval_dtor_func (zend_variables.c:52)
==4538==    by 0x822B99B: _zval_dtor (zend_variables.h:35)
==4538==    by 0x822D463: _zval_ptr_dtor (zend_execute_API.c:443)
</code>
How can I find the address of the invalid read?
Answer: The invalid read is taking place inside a function called zend_hash_destroy().
But the memory was already deallocated by the zend_objects_destroy_object() function earlier.
The fact that this is all happening inside "zend" appears to point to a problem with "zend". If you're trying to debug PHP I'm not sure you're going to get very far using valgrind here (as much as I love this tool)...
Comment: The clue is this message "Address 0x44c1718 is 8 bytes inside a block of size 20 free'd" - you're trying to read at 0x44c1718 which is 8 bytes inside the 20 byte block malloc'd much earlier. If you want to know who malloc'd the block you can run valgrind with the --track-origins=yes flag as well as --leak-check=yes.
Comment: I'm 100% confident it's my code that is buggy, I've messed with refcounting (the garbage collector counter) and the ZE expects some other value there, that's why it's happening. So I really need the number. The pointer, concretely.
Comment: Ok so if I understand it correctly, the beginning of the block is at `0x44c1710`?
Comment: Yes, or better said: that is where it was.


property value cannot be undefined in javascript

Question: I am reading a book JavaScript: The Good Parts for increasing my JavaScript knowledge. In Chapter 3 Objects the Author says:

An object is a container of properties, where a property has a name and a value. A property name can be any string, including the empty string. A property value can be any JavaScript value except for undefined.

What does the Author mean by that? As far as I know, we can set values to undefined in an object literal or outside of an object literal using with prototype word.  For example Object.prototype.customName = undefined; works well. What am I missing here?
Comment: You're missing nothing. Unless there's some context there you're not including (I haven't read it myself), that particular point on its own is incorrect.
Comment: I just downloaded the book and read the part you mentioned, considering the book was released in 2008 it could very well be that at that time (ECMAScript 3) you couldn't set `undefined` for an Object key's value.
Comment: @prsvr Not sure if you saw [this](https://stackoverflow.com/questions/49105908/property-value-cannot-be-undefined-in-javascript#comment85217812_49106055), but I don't believe the semantics of setting a property to `undefined` have changed since ECMAScript 3, so I'm pretty sure we can't dismiss the author's claim as "outdated"; it's just incorrect.
Comment: @PatrickRoberts Maybe he fixes it in 2nd version if it ever comes to life, which it should considering it's been 10 years and 2 new releases of ES.
Answer: You're right that you can assign the value undefined to a property, and even define a literal with the undefined property; however, the resulting object is very easily confused with the similar object written without that property.
For example, in Node:
> x = {a: 1, b: undefined}
{ a: 1, b: undefined }
> y = {a: 1}
{ a: 1 }
> x.a
1
> y.a
1
> x.b
undefined
> y.b
undefined
> Object.keys(x)
[ 'a', 'b' ]
> Object.keys(y)
[ 'a' ]
> JSON.stringify(x)
'{"a":1}'
> JSON.stringify(y)
'{"a":1}'

It appears the author is saying that if you want to write good, responsible code, you should not use undefined as a property value, because you could asking for confusion.
But semantically, that undefined is really there, so if you interpret what the author is saying literally, it's technically incorrect. But if you follow best practices, I can see what he's trying to get across. It's very Crockford-esque.
By the way, the right way to remove properties is with delete but that's perhaps for a different question.
ADDENDUM
In response to a question in the comments from @prsvr, I looked up the old ECMAScript 3 Specification and found the following:

ECMAScript is object-based: basic language and host facilities are provided by objects, and an ECMAScript program is a cluster of communicating objects. An ECMAScript object is an unordered collection of properties each with zero or more attributes that determine how each property can be used—for example, when the ReadOnly attribute for a property is set to true, any attempt by executed ECMAScript code to change the value of the property has no effect. Properties are containers that hold other objects, primitive values, or methods. A  ECMAScript Language primitive value is a member of one of the following built-in types: Undefined, Null, Boolean, Number, and String; an object is a member of one of the following built-in types: Undefined, Null, Boolean, Number, and String; an object is a member of the remaining built-in type Object; and a method is a function associated with an object via a property.

There is no mention of undefined being disallowed as property values in the spec. (https://www-archive.mozilla.org/js/language/E262-3.pdf).
There were changes to undefined during the evolution of JavaScript; for example you used to be able to reassign the value of the identifier undefined to some value other than undefined, hence the idiom typeof(x) === "undefined" (among others).
Comment: To expand on your point about "very easily confused", a common case is the erroneous check for a property's existence by doing `x.b === undefined` or `typeof x.b === 'undefined'` or similar. The correct way for checking a property _if it is enumerable_ is `'b' in x`, or if it is an own, non-enumerable property, `x.hasOwnProperty('b')`. If is not an own, or enumerable property, checking for its existence when it is `undefined` is a bit more involved, and perhaps out of scope for this question.
Comment: Looking at the [ECMAScript 3 specification](https://www-archive.mozilla.org/js/language/E262-3.pdf) and comparing it to the [ECMAScript 5.1 specification](https://www.ecma-international.org/ecma-262/5.1/), 3 didn't have definitions for §4.3.24-31 which included "property", "own property" and "inherited property". However, they did both contain the `in` operator in §11.8.7, and both specifications reference the internal [[HasProperty]] method and define `in` semantically the same, which leads me to believe that the author's claim in the book is simply erroneous and not due to being outdated.
Comment: I think you're right. I suppose, too, we could always ask him what he meant by that statement. :)
Comment: @oyilmaztekin I'm not implying anything about what a developer should do, other than follow up their reading with critical research to confirm that everything they learned is indeed correct. So kudos to you for listening to your gut instead of taking the author's word without question.
Comment: Could it be that `undefined` was allowed as a value in later releases of JS ?
Comment: Hmm, good point @prsvr, that may have been true in ES3 (pre-2009) and ES5 (2009-2015) days.
Comment: @RayToal It was still at version 3 at the time that book was released.
Comment: Quite right, December 2008 is the publication date on that.
Comment: @PatrickRoberts So you imply a developer should read the newer books include modern ES6 or ES.Next explanations. There might be so popular or accepted in their era but now they are outdated. Is that true?
Comment: Thanks for your help and valuable information you gave. @PatrickRoberts.
Answer: I think the author is trying to say that a key of an object cannot be defined without defining its value. That is, a key should always have a value.
For example if the key test is defined without defining its value, it will throw an error.

var abc = {
  test:
}
Comment: If that was what the author meant then why would they explicitly say "except for undefined"? Why does "can be any JavaScript value" not suffice for this case?
Answer: i think because js object consider undefined is default value for both inactive key and unknown key
var person = {
   name: 'name',
   '': 'this is empty key',
   null: 'this is null key',
   another_null: null,
   undefined: 'this is undefined key',
   inactive_key: undefined
}
console.log(person['key_from_nowhere']) // unknown key => undefined
console.log(person.hasOwnProperty('key_from_nowhere')) // false
console.log(person['inactive_key']) // undefined
console.log(person.hasOwnProperty('inactive_key')) // true

so that if you assign value of a object's key to undefined then this key fall into the inactive key case (JSON.stringify will ignore)
person.name = undefined;
console.log(JSON.stringify(person)); // name will disappear

BTW, i see that assign undefined maybe cause confuse and error prone since logic code must use hasOwnProperty to check the key exist or not, so do you think that the best practice here is do not assign undefined ?


Getting all ancestors/ Super types of a descendent/ Sub type from table in MySQL

Question: I have a table with hierarchical data that looks like this:

ObjectType
ObjectSubType

Everything
Solid

Solid
Solid

Solid
Metal

Metal
Metal

Metal
Iron

Iron
Iron

I'm trying to get all the ancestors/supertypes of any given objectSubType.
so if I want all the parents of Iron, it would look something like this:
Iron, Metal, Solid, Everything
I've tried using recursion by referring this
recursion code:
WITH RECURSIVE
  ancestorCategories  AS
  (
    SELECT ObjectType, ObjectSubType, 0 AS depth
      FROM ObjectTypeHierarchyTable
      WHERE ObjectType = "Iron"
    UNION ALL
    SELECT c.ObjectType, c.ObjectSubType, ac.depth - 2
      FROM ancestorCategories AS ac
        JOIN ObjectTypeHierarchyTable AS c ON ac.ObjectSubType = c.ObjectType
  )
SELECT * FROM ancestorCategories;

This does not seem to work though (possibly missing a termination condition?) - I get this error message when trying it out on db-fiddle:

Recursive query aborted after 1001 iterations. Try increasing @@cte_max_recursion_depth to a larger value.

Any help is appreciated!
Comment: `This does not seem to work` - what does this mean? Please share the exact error message or describe the unexpected behaviour!
Answer: Didn't solve it using recursion but managed to use a WHILE loop and a temporary table to get all the ancestors:
DELIMITER $$
CREATE PROCEDURE get_ancestors(IN value VARCHAR(50))
BEGIN
  -- create a temporary table to hold the ancestors, once and truncate it
  CREATE TABLE IF NOT EXISTS ancestors (
    ObjectType VARCHAR(50) NOT NULL
  );
  TRUNCATE TABLE ancestors;
  -- insert the initial value into the ancestors table
  INSERT INTO ancestors (ObjectType) VALUES (value);

  -- Loop until no more ancestors are found
  SET @new_rows = 1;
  SET @iterations = 0;
  SET @max_iterations = 100;
  WHILE (@new_rows > 0) AND (@iterations < @max_iterations) DO
      INSERT INTO ancestors (ObjectType)
      SELECT DISTINCT ObjectType
      FROM ObjectTypeHierarchyTable
      WHERE ObjectSubType IN (SELECT ObjectType FROM ancestors)
      AND ObjectType NOT IN (SELECT ObjectType FROM ancestors);

      SET @new_rows = ROW_COUNT();
      SET @iterations = @iterations + 1;
  END WHILE;

  -- select the ancestors from the temporary table
  SELECT * FROM ancestors;
END$$
DELIMITER ;

CALL get_ancestors('Metal');

A procedure is also being used to wrap the WHILE statement because WHILE statements can't be used directly.
Optionally TEMPORARY keyword can be used while creating the ancestors table depending on the type and version of MySQL(it works in PyMySQL which is my use-case).


Can I use .show() or .hide() with a switch 1/0 instead of an If statement

Question: I was just wondering if it was possible to do something like this in jQuery:
$('#MyDiv').show((MyVar==2?1:0)); // 1=show, 0=hide.

otherwise I'd have to write it like this everywhere.
if(MyVar==2?1:0){$('#MyVar').show();}else{$('#MyVar').hide();}

Comment: No you don't have to, you can do `$('#MyDiv')[MyVar==2?'show':'hide']()`.
Answer: There's a built-in function .toggle(boolean value) since jQuery 1.3:
$('#MyDiv').toggle(MyVar === 2);

Answer: Considering that the manual for .show() says it takes no arguments, I believe that you must do it the 2nd way.
I would recommend instead something like if (MyVal==2) { $('#MyVar').show(); } else { $('#MyVar').hide(); }. The ? operator is unnecessary in an if since MyVal==2 already evaluates to a true (1) or false (0). Also, putting spaces in your code will drastically improve your readability and you will thank yourself later when trying to debug things.
Edit: lol forgot about the toggle method...that works too.


How do I continuously build and debug a PhoneGap/Cordova app?

Question: What is the most efficient way to develop and continuously deploy to the simulator while receiving debug info from console.log etc? For example, is there a way to see the console.log output without manually deploying the build using xCode? Is there any way to see the log output outside of xCode?
Also what is the best way to continuously deploy the app to the simulator? Is there a way to make Cordova rebuild every time I save a file? Would that be a bad idea to try and do? This may just be me having a hard time making the transition from web development to (pseudo) app development.
Answer: Have you read this page? https://github.com/phonegap/phonegap/wiki/Debugging-in-PhoneGap
Your best bet is to develop the app using a browser on your computer. Periodically deploy the app to the simulator to make sure that things are still working as intended. Continuously deploying the app to the simulator is pretty slow, so yes I would think that it's a bad idea. Refreshing the browser is lightning fast, so you want to be doing that as much as possible.
I've found that whenever I develop a new bit of code that does something different that I haven't tested before on the simulator (maybe a fancy CSS transition), I'll write a test page and test it on the simulator, and then probably test it on the phone as well. If it works ok I'll continue development on my machine.


Wiring 2 pull chain operated lights in series

Question: How do I wire 2 pull chain operated lights in series from the same single power source so that both lights are powered and will work independently. There will be no other switch on the line and power source is coming from a nearby power outlet.
Comment: Hello, and welcome to Home Improvement. What do you mean by "in series"? (A diagram would help.) And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know you'll know the details of contributing here.
Answer: You will not be wiring the two light fixtures in series. In fact you will be wiring them up in parallel from a single power feed. Since the power feed is always on make sure to have the breaker off before attempting to do any connections.
The pull chains on each light assembly will allow independent control of each light.


macro expansion ignores token `for` and any following

Question: Similarly to this question, I was stumped by a compiler macro expansion error.
The offending code was:
/// send a command and wait for the response
///
/// 'dirty' macro that relies on outside context
macro_rules! send_and_receive {
    ($cmd: expr, $response_pat:pat => $r_block:block) => {
        send_command(&mut port, $cmd);

        for i in 0..3 {
            match receive_response(&mut port) {
                $response_pat => $r_block,
                r => {
                    eprintln!("got response: {r:?}");
                    continue;
                }
            };
        }
        panic!("missing response");
    }
}

Where the expected arguments are an enum instance, and a 'match like' expression, like so:
send_and_receive!(
    Command::Thing { field: value /* etc */ },
    Response::ThingResponse { response_field1,  /* ... */ } => {
        do_stuff_here();
    }
);

Comment: I see that you have already found the issue, but in the future you can use tools like [cargo-expand](https://crates.io/crates/cargo-expand), which will expand all macros in your source code. This is really helpful for debugging macros.
Answer: The issue was that the macro expands to 'loose expressions', without an enclosing block.
Adding it fixed the issue (because it creates a scope to be able to return from), like so:
macro_rules! send_and_receive {
    ($cmd: expr, $response_pat:pat => $r_block:block) => {
        {
            send_command(&mut port, $cmd);

            for i in 0..3 {
                match receive_response(&mut port) {
                    $response_pat => $r_block,
                    r => {
                        eprintln!("got response: {r:?}");
                        continue;
                    }
                };
            }
            panic!("missing response");
        }
    }
}


JavaScript V8 security

Question: I was reading about V8 JavaScript engine and was shocked that Node JS and Browser JS use the same V8 engine and that's way produce the same Machine Code.
Question:
Is it browser responsibility to protect from accessing Network/OS/etc? It seems like huge field for different kind of injections and lot of security risks...
Comment: Browser security only involves browser-supplied APIs. V8 doesn't know anything about `document`, `window`, `localStorage`, etc etc.
Comment: Occam's razor: *if* V8 was so insecure/sharing so problematic, because it is so widely used, in a field so incredibly popular and constantly attacked by so many attackers, shouldn't it already be a known security nightmare?
Answer: Security is obviously a big concern on the web platform, so there are several layers of protection built in:

V8 itself doesn't even provide access to OS or network. It's a virtual machine, and one of the consequences of running stuff (like JavaScript code) in a virtual machine is that it provides insulation from the host system. (The OS/network functionality you see in node.js is provided by node.js and doesn't exist in Chrome.)
Chrome additionally sandboxes the renderer processes that V8 runs in. So even if someone found a way to exploit V8 to generate and run arbitrary machine code (which V8 tries very hard to make impossible), they'd still have to find a way to break out of the sandbox (which prevents wild access to the system; for example renderer processes can't even read files from disk or write files to disk).

The fact that "the same V8 engine" runs on the server and in the browser does not constitute a risk. All HTTP based interaction between server and client is the same regardless of what software runs on both (whether it's, e.g., Apache/Firefox or node.js/Chrome or any other combination).
Injecting things into V8 should be really really hard (it's a bug when it's possible!), so if you have specific ideas how to do that, we'd like to work with you to fix it ;-)
It all boils down to: there's a clearly defined set of things that JavaScript programs can do in the browser (which should all be safe), and the platform makes it impossible to do anything else. If it is possible to do something else, it's a security bug, and you'll (probably) earn a bug bounty when you report it.

JavaScript V8 security


How to open the new link (generated after clicking an element in a web page) in a new tab using Selenium and Python?

Question: I have to try to click an element on a web page, and I want the link after the click should open in a new tab, here is the code snippet:
browser.find_element_by_xpath('//*[@id="container"]/main/div/sec[1]').click()

# Above code open the link but in the same tab.

I have tried the following code to open it in a new tab:
browser.find_element_by_xpath('//*[@id="container"]/main/div/sec[1]').send_keys(Keys.CONTROL + 't').click()

# But it's not working.

How to open this in a new tab?
P.S.: This is not the link to open in a new tab, its the element to be opened on a new tab, so don't mark it as duplicate.
Comment: Possible duplicate of [Opening link in the new tab and switching between tabs (Selenium WebDriver + Python)](https://stackoverflow.com/questions/46425797/opening-link-in-the-new-tab-and-switching-between-tabs-selenium-webdriver-pyt)
Comment: @hashcode55 please read the both questions before marking it as duplicate
Comment: @KallolSamanta Can you update the question with the relevant HTML?
Comment: @KallolSamanta What do you mean by "opening an element in a new tab"? The only difference I see between the your question and duplicate question is you are trying to find the element by xpath.
Comment: @KallolSamanta, check out my answer (second not accepted one): https://stackoverflow.com/questions/46425797/opening-link-in-the-new-tab-and-switching-between-tabs-selenium-webdriver-pyt
Answer: This should work in Java (Hope you can write this logic in Python),
To open a link in new tab
WebElement ele = wd.findElement(By.xpath(xpath));
Actions link = new Actions(wd);
link.keyDown(Keys.COMMAND).click(ele).keyUp(Keys.COMMAND).build().perform();
Thread.sleep(5000);

Switch to new tab,
Set<String> windows = wd.getWindowHandles();
wd.switchTo().window((String) windows.toArray()[1]);


Re-do paint over plaster in bathroom: How to feather/match?

Question: I want to understand what went wrong, and how to repair it:

This bathroom in a loft was done in 2012. The plasterwork is really good --- smooth and shiny; but the last year or so the paint (Dulux Trade, 2-3coats) has been peeling off. It has all been done by builders that have wrecked a series of things, so it hardly surprises me [their plastering subcontractor was great].
This is how much I can easily remove with a flat 4inch scraping blade, it peeled in large smooth flaps getting smaller and more brittle towards the edge.
I guess it should have been Bathroom paint, but I know they first did a 'mist coat'. So how do I match the white & chocolate areas? Should I scrape a straight edge with a knife or so all around the peeling area and then scrape all paint off up to that line (so the patch is a rectangle or near enough)? Or just remove the 'island' (caused by a repair, as they put the ventilator there originally).
Should I sand down the sharp edges now, then re-paint 2-3layers, then sand down the transition again, and then give the whole room a layer?
I suspect the paint higher up where the ceiling flattens off is also loose (because the same surfaces and products, and the hot moist air pools up there around ineffective ventilator).
Looking at the other 'peeling paint' questions, this is a much higher-moisture situation. And I'm guessing PVA-sealing doesn't do anything, because of the high PVA content of the plaster (UK standard practice) or does it still?
Answer: Here's how you get paint to stick to things.
Scuff-sand.
Paint cannot bond to a shiny surface; don't take my word on it, try to paint a mirror and see what happens.
Paint wants to see a surface that looks like Swiss Alps on a microscopic level - lots of jaggies and crevasses for paint to flow into and bond in shear.  To human eyes, that doesn't look like anything more than a loss of gloss.
But this requires a "scuff-sand"; my favorite tool for that is a green Scotch-Brite pad.  If you've ever gone to town with that on pots and pans, you know you can easily lift the shine off the pot.
So we're not trying to sand to level a surface; just to give it a microscopic roughness. Try around edges not to "blow through" an existing coating layer; that's not the goal.
Without the scuff-sand, you are painting a mirror, and the new coat will bond poorly. *This is particularly a problem where gloss paint is used, e.g. bathrooms.  Satin/flat paint typically forms a roughened surface (to achieve the satin look) and that it easier to bond to (but I'd still scuff-sand it).
Everyone is looking for "scuff sand in a can".  I am aware of many products which make that claim, but none I believe.  We certainly don't want any residue that could become the second threat:
Remove contaminants.
That requires a washdown; typically with whatever removes contaminants, e.g. soap and water.  I also like to do one last 2-cloth wipedown with the actual solvent of the paint (e.g. water for latex), the 2-cloth makes sure you are lifting the contaminants away, not just smearing it around.
Contaminants prevent the paint from bonding by sitting as a film between old and new paint.  Adding a layer that has no bonding strength to either the old substrate or the new paint.  So it's gotta be gone.
Sometimes the substrate is a contaminant, like trying to paint a 2-part LPU over, well, almost anything :)  In that case you need to use an appropriate primer as a barrier coat; the primer has different chemistry and is able to bond to both the substrate and the topcoat.  There are many other reasons to use primer, but that is one of them.
Anyway, your predecessor did none of the above.  Typical.
Any 2 layers that aren't bonding well will fail your entire paint job.
I have a machine where the original primer is separating from the substrate (because it was primed over mill scale).  Separately, the original topcoat is separating from the second painting's primer (poor prep in an oily shop).  Of course, it's not failing all at the same time, but in blotches.  There is simply no saving this.  No paint job can expect to perform well on top of a substrate that is failing.
Again, everyone is looking for a product in a can that will magically fix this, and they're not looking for paint stripper :)  Unfortunately that's the only one.
The answer for good long-term performance is "it's all gotta go".  This is the problem with letting monkeys paint your house, or applying products of poor provenance. You pay dearly for the mistake.
Fortunately, latex paints are easily removed with comparatively mild paint strippers, so you're not having to go crazy with Aircraft Remover as you must with alkyds or LPUs.
Comment: This will 100% happen. The painters didn't screw up only the middle of the ceiling. The screwed everything up. The middle just happens to be failing faster, but you already know the rest of it will fail. If you repair just the middle, then you will do it again when the other parts fail.

An unprimed surface will last a couple years. A properly primed surface with the correct topcoat can last more than a decade.
Comment: While I agree, it's worth noting that you probably want a high-number (200+) grit. Sanding with an 80 grit will leave noticeable marks after painting.
Comment: I think an AIM-120 AMRAAM is a bit much for a bathroom, plus I'm not sure it can properly acquire a surface target... wait... You meant something else by "Aircraft Remover", didn't you? ;)
Comment: @harper Thanks for this detailed answer! It does raise the question to me, Why do British plasterers work towards a super-shiny finish --- if it then has to anyway be immediately overpainted? [This happened in a loft-conversion, so plaster not dry probably; and probably no mist coat as the bathroom was behind schedule]. Any continental visitor is always astonished here with the plaster finish.
Comment: @Nelson Arhg you are right of course --- the paint fails above the shower due to repeated hot moist air/ cooling down cycles being most intense there I suppose.
Comment: @user3445853 because if the contractor is even lazier, they wouldn't even paint over the plaster... >.>
Answer: I have fixed paint similar to this in my current house. There were large areas where I could peel it off back to the plaster by hand or with a scraper.
Your builder's first coat has failed to adhere to the plaster and now it's peeling off. This could have been caused by:

Painting with full strength paint rather than a mist coat
Painting before the plaster was fully dry
Plaster surface is too shiny and polished
Plaster surface is contaminated, perhaps with fine dust

You need to get as much of that paint off as possible, otherwise you will be putting new paint onto a surface that is likely to peel in the future.
I would use a filling knife or a Stanley scraper with fresh blades used at a shallow angle to get as much loose paint off as possible. If you get all the paint off up to the walls then great. Areas that are firmly stuck down you can leave or maybe sand or strip small islands. Remaining paint doesn't have to be straight lines, just as long as it's firmly bonded on.
Try not to gouge grooves into the plaster otherwise you're making more work for yourself by having to fill them back in.
I would then lightly sand the plaster and remaining paint all over with P120 sandpaper or sanding mesh. Be very light on the plaster because it will be much softer than the paint. This is why I would avoid sanding the transition lines at this point.
Then, as Harper suggests, thoroughly clean off the surface and remove any dust. Paint on a mist coat, over the entire ceiling. Use diluted Dulux supermatt or something similar.
Any remaining gouges or paint/plaster transition ridges can now be filled and smoothed. Use fine surface filler and a wide knife for anything shallower than 2 mm. Smooth it in firmly along the length of the defect, but don't overwork it. Wipe off with a damp sponge and try again if you need to. Use all purpose powder filler for deeper holes. When dry lightly sand any uneven filler and remove the dust. Remember it doesn't have to be perfect, just good enough to paint.
Paint on a couple of topcoats. Use a good quality paint suitable for bathrooms, such as Johnstone's acrylic durable matt. Follow the instructions and paint the entire ceiling.
Don't be tempted to use PVA as a sealer underneath paint. If you have problem surfaces then use a problem solving primer such a Zinsser product.
Comment: My mom bought a house from a guy that had never built a house before and had no idea what he was doing. He didn't use primer, he didn't wait long enough to ensure plaster was dry, AND, he did all the work in the winter (<40*F). ALL of the paint in her (900sqft) house peeled off. Huge sheets at first. She patiently waited for it all to loosen (2 yrs) then scraped off the rest, and hired a painter (a real one) to prime w/a product meant for plaster, and repaint. You HAVE to get the old paint off. I upvoted bc you stated this fact even tho it's tough to hear. Correct products are key too.
Comment: @James thanks for these additional insights! PVA priming was suggested to me, but your combined answers firmly put that aside. Gouging into the plaster indeed worried me for additional work.  All in all the plaster seems perfectly fine, so it's a good basis.


JAVA program run problem

Question: I have install java in my computer. when i doing compile java program it is successfully done but when i try to run program it show error like
<code>Exception in thread "main" java.lang.UnsupportedClassVersionError: Example2 : Unsupported major.minor version 51.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: Example2. Program will exit.
</code>
what should i do??
Comment: we need information like what is your program and how are you trying to run it.
Comment: With only that information is hard to point out the exact problem. How have you installed Java (`apt-get`/Software Center/Oracle installer)? Which Java version you have (`java -version`)? Ubuntu version and arch? Check you are not compiling your app with a newer version of the JRE you are using to run the program (ex: compiling with OpenJDK7 and running with Oracle JDK6).
Comment: java version "1.6.0_27"
OpenJDK Runtime Environment (IcedTea6 1.12.5) (6b27-1.12.5-0ubuntu0.11.10.1)
OpenJDK Client VM (build 20.0-b12, mixed mode, sharing)
Answer: if i'm not mistaking this error is thrown if your virtual machine tries to run a program with different minor and major versions. Your number is 51.0 which means that your program is supported by J2SE and you try to run it with a newer version.
To fix your problem you should make sure that you got the newest version of the Java JRE
Comment: i have install both JDK&JRE 6 and 7 version.      class Example2
{
  public static void main(String args[])
  {
  int num;
  num = 100;
  System.out.println("This is num: " + num);
  num = num * 2;
  System.out.print("The value of num * 2 is ");
  System.out.println(num);
 }
}  this is my simple program
Comment: so your problem is that you compiled your program with v6 and try to run it with v7. But I'm not quite sure how to change the wrong path on ubuntu... :(   edit: your program is fine there is no mistake with it.
Comment: than what should i do??

JAVA program run problem


Using Case-When in Teradata

Question: Simple problem but driving me crazy for a while. Have following table in Teradata:
A       B
112211
113311  56
226144  61
996688  66
005400
771277

For the blank fields in col-B need to pull the numbers from col-A like:
SELECT A
CASE 'B'
WHEN 'B' IS NULL THEN SUBSTR('A',3,4)
END AS 'B'
FROM TABLE_T1;

Referred some documentation but not getting what's going wrong in the above query. This query will work on MySQL but why not in Teradata.
Expected O/P:
A       B
112211  22
113311  56
226144  61
996688  66
005400  54
771277  12

Comment: *why not in Teradata*: This will fail in most other DBMSes, too, because it's a mixture between *searched* `CASE WHEN condition THEN...`and *valued* `CASE column WHEN x THEN`
Answer: You can use this form of case expression note the difference is  case when ... not case b when .... Also use single quotes for literals only, use double quotes for identities. (Note sure why you used single quotes.)
SELECT
      A
    , CASE WHEN B IS NULL THEN SUBSTR(A,3,4)
           ELSE B
      END AS "B"
FROM TABLE_T1;

But you can also use coalesce() for this I believe:
SELECT
      A
    , coalesce(B ,SUBSTR(A,3,4) AS "B"
FROM TABLE_T1;

Using Case-When in Teradata


Unable to connect using PuTTY ssh

Question: I'm on a Windows 7 machine and have installed PuTTY.  I'm trying to connect, but the authentication fails because of an incorrect password.  But, the VM I'm connecting to doesn't have a password?
Here are the creds I'm trying to use:
<code>Host: 127.0.0.1
Port: 2222
Username: vagrant
Private key: c:/users/<username>/.vagrant.d/insecure_private_key
</code>
When I open PuTTY, I put in the above credentials and click open, at which  point it ask for the username and I enter 'vagrant', then it asks for the password, but there isn't a password, so I get access denied?
Not sure how to get around this?
Thanks.
Comment: Probably better asked at http://superuser.com
Comment: Normally this is a symptom of the key authentication failing and it falling back on password authentication.  Putty has its own key format, is your key file in that format?  Puttygen is used to convert a key from the openssh format to Putty.
Comment: I've never used PuTTY before, so I'm not sure what format it expects.  I checked the private key file and it is a long encrypted string `----Begin RSA PRIVATE KEY----MIIEogIBAAKCAQEA6NF8iallvQVp22W...etc....----END RSA PRIVATE KEY----`
Answer: The "---Begin RSA PRIVATE KEY ...." key is not of a format that PuTTY uses.

Use the program puttygen.exe (same place where the putty.exe program
is) to "Load" the private key.
Select "All Files (.)" from the filter to see the file c:/users/.../.vagrant.d/insecure_private_key
and open it.  It will say that it has successfully imported foreign
key....
Then use "Save private key" option to save the loaded key
into a *.ppk file.
Then use that ppk file as the key file for "SSH |
Auth" in PuTTY

That should work.
Answer: I had experienced the opposite: using the putty proprietary .ppk format to configure the "config.ssh.private_key_path" which expects the SSH format.
You can also you the puttygen to convert from .ppk format to SSH format.

Unable to connect using PuTTY ssh


Toilet flange no longer over pipe

Question: My toilet was leaking a bit from the base so I figured maybe the wax ring needed replacing. I took the toilet off the flange and saw something that doesn't look quite right. The flange is case iron and one side is torn and coming up. But even worse the flange is not directly over the pipe. It looks like it was pushed a few inches toward the wall. Have a look at the pics:
Here is the front of the flange, clearly not flush against the floor:

Here is a top view. You can see the flange is not directly over the outflow pipe anymore:

Here it is from the back. You can see the tear in the flange:

I'm not sure how this happened. It looks like the flange was pushed toward the wall at some point. Or the pipe was moved out from under the flange. A few years ago we had our foundation leveled, which tends to move things around in your house. That's the only thing I can think of that might produce and affect like this.
How do you fix this? Do we have to replace the tile and move the flange back over the pipe?
Answer: There are a wide variety of repair options that might work without damaging/removing tile, including repair flanges that use a compressible rubber sleeve that slides down over the existing pipe.
Unfortunately, it is difficult to see exactly what's what from the pictures. Repair options vary much depending on what you find after removal of the existing flange, so I recommend that you work on that first (hopefully you have a spare toilet...) I assume the foundation is raised (since you spoke of having it leveled) and suggest you get under there to ensure you have not had a sewage leak under the house. Carefully inspect the underside of the subfloor while you are there, because you will need to secure your new flange to it somehow and if it is damaged then you need to plan for that repair as well.
This type of repair may seem simple, and really they are, but the details and tricks gained from experience are often invaluable. If you can't figure a clear path forward after inspection and a visit to a plumbing shop to look at and discuss options... you may want to hire it done.
Answer: Well, I feel silly. The flange isn't bent. It's just an angled closet flange (aka offset flange) like this:

I didn't know that such a thing existed until a did I little more googling. It is broken and will have to be replaced but there's not some weird foundation issue like I thought. Sorry for the false alarm.

Toilet flange no longer over pipe


Apache Camel : Context level intercept/filter layers

Question: In our web application, we are using camel as the central piece to orchestrate/route the webservices, which will be connecting to several other local resources.
Can someone suggest, what is the best way to write context level (global / one-time) layers.
For example, we want to write a global security layer, which does a basic signature based auth check, which is going to be the first step for any route in the application.
We want this logic to be configured at global level(CamelContext ?), so that we don't need to write/add this process in every route we build.
Also, in case of multiple such layers ( say security, validation, etc.. ), is it possible to set the order in which they need to be executed ?.
Any sort of examples or reading pointers are very appreciated.
Answer: You should have a look at Route Policies that can hook into route execution and do such things as you describe. You can of course have your policy delegate to various layers of authorizations/validation/logging in any order you want.
To add the policy to every route, create a factory and assign to the context.
<code>context.addRoutePolicyFactory(new TheSpecialSecurityAndValidationPolicyFactory());
</code>
For security, however, different protocol tend to implement security using different methods. In SOAP you may check transport level security (Basic Auth, SSL,..) but also message level security (WS-Security). In other protocols, you may only be able to check transport and/or message level security tokens.
If you want some common security stack to deal with security on a higher level, I suggest you check out Apache Shiro. It is well integrated with Apache Camel.
Comment: I did look in to this earlier, but is there a way to tap the calls in camel context even before the route is started/prepared.. say even before the Exchange object is created ?


Using a DirectX c++ DLL in a C# WPF or Windows Forms Application

Question: I have written a DX11 renderer using c++. I am now looking for a way to implement an Editor/GUI for it.
Since im pretty used to Windows Forms and WPF C# Applications im thinking about putting my renderer inside a dll, load the dll from a c# application and use it to draw into a defined section of the form. Does this even work with a window handle passed by a managed c# appication and how is the performance if it does?
From my understanding, since the actual communication with the DX11 API would still be directly in c++ and the c# part would only tell the dll what to do the performance loss should be almost nothing. Or is this generally a bad idea and implementing the GUI directly in c++ using a library or D2D is the better approach.
Comment: You might want to look into the code of SharpDX to get some inspiration. Or just simply use SharpDX, if suitable for your needs... ;-)
Comment: This is exactly what i not want to do, SharpDX is a wrapper for the whole API which means every single call to the API has an extra overhead. There is a reason why no one uses c# to write games. Im just looking for a GUI without abandoning the benefits of using c++ directly. Here is a pretty interesting benchmark comparison for that: http://code4k.blogspot.com/2011/03/benchmarking-cnet-direct3d-11-apis-vs.html
Comment: Ah, okay, i misunderstood you. If your question is merely about whether you should render the UI as part of the DX surface through your renderer, or whether the UI should be built in .NET with the renderer just rendering the scene/model in a panel/surface within that UI, then this is purely a design and implementation choice depending on what functionality and what interactions between UI elements and rendered scene/model you want/need. There is no simple, general answer that one is good and the other is bad. It is a decision you have to make based on desired features and involved devl. costs.
Answer: In WPF you can use D3DImage which is just like a simple Image in your xaml. The general principle is as follows:

Allocate a Direct3D 9 texture, this will be your rendering target.
Hand it over to the D3DImage.SetBackBuffer.
Put your rendering code inside CompositionTarget.Rendering event handler.
<code>    RenderStuffToTexture();
    d3dImage.Lock();
    d3dImage.AddDirtyRect(new Int32Rect()
    {
        X = 0,
        Y = 0,
        Height = d3dImage.PixelHeight,
        Width = d3dImage.PixelWidth
    });
    d3dImage.Unlock();
</code>

Since you are using Direct3D 11, you have to use DXGI surface sharing to share the D3D9 textute with D3D11. There are 2 examples I know of that illustrate how to do just that. Microsoft D3D11Image and D3DImageEx (my personal preference, can be found in multiple places online).
Regarding performance, once you use WPF you no longer doing the presentation yourself. You literally write a small render-to-texture logic inside a WPF D3D9-based renderer. So not everything can be controlled including presentation time. From my personal experience, you can definitly render simple scenes at a nice framerate. For a really graphics intensive app and strict FPS requirements I would use a more lightweight (and less intrusive) UI solution.
Note that you can also use WinformHost control to get a HWND and render to it. This has a serious disadvantage if you want to overlay UI controls over the rendered frame - AFAIK you simply can't.


execute of dynamic sql does not set found in psql

Question: I execute an sql using dynamic sql in a trigger as the trigger will run across multiple tables. The sql will select from a table and check if there are results do nothing if no results insert into a table. it works  wit the first psql select but the found variable is true even though it is empty
 create function test() returns trigger $Body$
 execute 'select * from ' || quote_ident(TG_TABLE_NAME) || '_table1 where condition';

 if not found then
 insert into x values(anything);
 end if;

execute 'select * from ' || quote_indent(TG_TABLE_NAME) || '_table2 where condition';

if not found then
insert into y values (values);
end if;
......

the second condition i am sure it produces no result but found is still true any solution to have this working?
Answer: You can use get diagnostics instead:
...
declare
    rcount int;
begin
    execute 'select * from some_table';
    get diagnostics rcount = row_count;
    if rcount = 0 then
        ...

Per the documentation:

Note in particular that EXECUTE changes the output of GET DIAGNOSTICS, but does not change FOUND.


remove null atributes from json with gson

Question: I want to remove attributes that have empty collections or null values using gson.
Aiperiodo periodo = periodoService();
//periodo comes from a service method with a lot of values
Gson gson = new Gson();
String json = gson.toJson(periodo);

I print json and I have this:
{"idPeriodo":121,"codigo":"2014II",
"activo":false,"tipoPeriodo":1,
"fechaInicioPreMatricula":"may 1, 2014",
"fechaFinPreMatricula":"jul 1, 2014",
"fechaInicioMatricula":"jul 15, 2014",
"fechaFinMatricula":"ago 3, 2014",
"fechaInicioClase":"ago 9, 2014",
"fechaFinClase":"dic 14, 2014",
"fechaActa":"ene 15, 2015",
"fechaUltModificacion":"May 28, 2014 12:28:26 PM",
"usuarioModificacion":1,"aiAvisos":[],
"aiAlumnoCarreraConvalidacionCursos":[],
"aiAlumnoMatriculas":[],"aiMallaCurriculars":[],
"aiAlumnoCarreraEstados":[],"aiAdmisionGrupos":[],
"aiMatriculaCronogramaCabeceras":[],
"aiAlumnoCarreraConvalidacions":[],
"aiHorarioHorases":[],"aiAsistencias":[],
"aiAlumnoPreMatriculas":[],
"aiAlumnoMatriculaCursoNotaDetalles":[],
"aiOfertaAcademicas":[],"aiTarifarios":[]}

For example for that json I don't want to have the collection aiAvisos, there is a way to delete this from the json.
I'm working with a lot of collections actually here I show one, I really need remove these from the json.
I need something like this:
{"idPeriodo":121,"codigo":"2014II",
"activo":false,"tipoPeriodo":1,
"fechaInicioPreMatricula":"may 1, 2014",
"fechaFinPreMatricula":"jul 1, 2014",
"fechaInicioMatricula":"jul 15, 2014",
"fechaFinMatricula":"ago 3, 2014",
"fechaInicioClase":"ago 9, 2014",
"fechaFinClase":"dic 14, 2014",
"fechaActa":"ene 15, 2015",
"fechaUltModificacion":"May 28, 2014 12:28:26 PM",
"usuarioModificacion":1}

I tried setting the collections to null, I check the documentation and there's no method there neither...
Please any suggestions.
Yeah I update the json I had posted some minutes ago.
Thanks a lot who read this!
Comment: Hi oshingc, what have you tried so far & what hasn't worked as you expected? Please elaborate with some example code & a specific problem.
Comment: It's not a valid JSON. Check it here [The JSON Validator](http://jsonlint.com/)
Comment: @Braj I update the json I was showing at the post, I'm working with a valid JSON actually. Thanks for your attention.
Answer: Steps to follow:

Convert the JSON String into Map<String,Object> using Gson#fromJson()
Iterate the map and remove the entry from the map which are null or empty ArrayList.
Form the JSON String back from the final map using Gson#toJson().

Note : Use GsonBuilder#setPrettyPrinting() that configures Gson to output Json that fits in a page for pretty printing.
Find the sample code here Remove empty collections from a JSON with Gson


Should search result urls be accessible and intuitive?

Question: We usually aim for friendly (vanity) urls to help visitors identify where they are in the website, e.g. www.website.com/products/acme-product. But, are there standards here for search results?
At the moment our search results are something like this:
http://www.website.com/search?by=<category>=<selected_category>&<price_range>=<selected_price_range>

The search query string seems intuitive to me, but I am looking for some standards here - or, if it's been identified that we don't need to worry about intuitive URLs for search results.
Comment: The `by==` is non standard. A standard form would be `category=`. Or in general `base-url?param1=value1&param2=value2&param3=value3`.
Comment: Making them pretty *enough* is nice, but I wouldn't risk making the back end (significantly) code more complicated to try and make search urls more readable; unlike static pages it's unlikely they'll ever be typed in or bookmarked (and if they are bookmarked, they still work, so what?)
Answer: I recently did some research on that, and I came to the conclusion that the search urls needn't be accessible. It is surely nice to have them accessible like http://yourdomain.com/search?q=hello, but if you cannot manage that, it's no big issue.
How I came to these results:

All major search sites have huge search URLS showing for a simple search: Just try a search for hello on Google and you will land on an url like this:
https://www.google.ch/#hl=de&safe=off&output=search&sclient=psy-ab&q=hello&oq=hello&gs_l=hp.3..0l4.203.750.0.1012.5.5.0.0.0.0.594.2081.4-2j2.4.0...0.0...1c.wpHgEXrgAJU&pbx=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=474cec96d8423c1f&biw=1440&bih=758.
Not really understandable to a normal user, right? There are other sites with search urls a little bit more accessible (like Youtube), but even then, it's never a memorable url the user would go and enter in the search bar. I think you can rely on these sites to do user testing quite thoroughly, so if it's not important for them, it may not be important for you.
You can have a look at this research Nielsen did regarding users typing urls. From that you can deduce that for the normal user, it may be possible to remember an easy url. To remember how to search via the adress bar is asking too much.
All the major browsers implement some sort of searching mechanism to the adress bar. This results in many users not even entering full URLs anymore, instead they just search for what they want (Awesome bar in Firefox, address bar in Google Chrome, usw)

There may be, however, other things which speak for considering an easy search url

If you want to make your search url an access point of your API, for example, developers are surely happy to have easy accessible urls
If you want to implement Open Search on your site so the user can use your site as a search engine in his/her browser, easily accessible urls reduce implementation time.
Answer: It is important to stick to the search standards so that:

Other utilities can search your sites. E.g. so that users can define (or add existing) search engine definitions to their browsers. (This is more of a SW API issue than a UX issue.)
Advanced users can quickly edit the query.
Comment: That's a good point. I use the Chrome address bar to search directly in many sites. When I have to [add a new search engine](http://support.google.com/chrome/bin/answer.py?hl=en&answer=95653&topic=14676&ctx=topic), I appreciate the fact that the search URL is easy to read and edit.
Answer: Why not continue the 'vanity' standard you established with your users else-ware in the site?
http://www.website.com/search/<selected_category>/<selected_price_range>
Use a url mapper to set the /<param>/ to be executed by convention. This should not a big technical challenge and services both the points brought up by: Danny Varod


Do structures count as terrain?

Question: Vayne's Condemn says:

If they collide with terrain after being knocked back, they are dealt the same amount of physical damage again and are stunned for 1.5 seconds.

Similarly, Poppy's Heroic Charge says:

... if they collide with terrain, her target will take a high amount of magic damage and be stunned for 1.5 seconds.

So if the enemy hits a turret, inhibitor, or nexus, does it count as terrain and cause these abilities to stun the target?
Answer: Yes. Turrets count as terrain for the purpose of champion abilities.
The wikia confirms this:

Towers count as terrain. Any abilities that interacts with terrain
  will trigger the effect, namely  Poppy's  Heroic Charge's and  Vayne's
  Condemn's stuns.
Comment: For the record, this also includes destroyed buildings. The base is still there and counts as impassable terrain.
Comment: I was looking under the skills themselves... :/
Comment: What about inhibitors and nexuses?...nexi?...nexussssssss...now they all sound weird...
Comment: @OrigamiRobot same deal.
Answer: Yes, they count as terrain. They even count when destroyed. So do things like trundle's pillar. It can be very powerful for trundle to cause a pillar to appear behind the target, then for vayne to shoot him.
Comment: Do you have a source for that? I haven't ever seen that particular interaction.
Comment: other then from my personnal experience no
Comment: It was my understanding the terrain from trundle, annivia, and jarvan IV were all fake "minions" which is why a lot of skills go through them. It would surprise me if you can stun into them.

Do structures count as terrain?


linux batch jobs in parallel

Question: I have seven licenses of a particular software. Therefore, I want to start 7 jobs simultaneously. I can do that using '&'. Now, 'wait' command waits till the end of all of those 7 processes to be finished to spawn the next 7. Now, I would like to write the shell script where after I start the first seven, as and when a job gets completed I would like to start another. This is because some of those 7 jobs might take very long while some others get over really quickly. I don't want to waste time waiting for all of them to finish. Is there a way to do this in linux? Could you please help me?
Thanks.
Answer: GNU parallel is the way to go. It is designed for launching multiples instances of a same command, each with a different argument retrieved either from stdin or an external file.
Let's say your licensed script is called myScript, each instance having the same options --arg1 --arg2 and taking a variable parameter --argVariable for each instance spawned, those parameters being stored in file myParameters :
cat myParameters | parallel -halt 1 --jobs 7 ./myScript --arg1 --argVariable {} --arg2

Explanations :

-halt 1 tells parallel to halt all jobs if one fails
--jobs 7 will launch 7 instances of myScript

On a debian-based linux system, you can install parallel using :
sudo apt-get install parallel

As a bonus, if your licenses allow it, you can even tell parallel to launch these 7 instances amongst multiple computers.
Answer: You could check how many are currently running and start more if you have less than 7:
while true; do
    if [ "`ps ax -o comm | grep process-name | wc -l`" -lt 7 ]; then
        process-name &
    fi
    sleep 1
done

Comment: `ps auxw | grep process-name | wc -l` will show 8 when here is 7 processes started
Comment: Thanks. I didn't use ps auxw but a command that monitors how many licenses are currently in use (irrespective of user id because they are shared network licenses). I liked the idea of using 'if' to check it and sleep for a few seconds. That helped. Thanks a lot.
Answer: Write two scripts. One which restarts a job everytime it is finished and one that starts 7 times the first script.
Like:
script1:

./script2 job1
...
./script2 job7

and
script2:

while(...)
  ./jobX

Answer: I found a fairly good solution using make, which is a part of the standard distributions. See here

linux batch jobs in parallel


which rails4/ruby2 web/app server on unix for production ussage?

Question: If you were deploying a production rails 4/ruby 2 app on unix, what app/web server would you use and why?
I have been using apache/passenger for my rails 2 & 3 apps for years, no big problems, it generally works pretty well. We have had one app that kept restarting and leaked memory, but most have been fine.
This app may have a bit more bursty traffic and require a bit more concurrent usage.
Other options I have read about :
Thin,
Unicorn,
Puma
I do need to support HTTPS, but don't need to run any other apps on this server, so I don't need all the features of Apache.
So I would like to hear from folks that run production apps in think, unicorn, puma or others, or even the latest passenger (with apache or nginx) and see if they have opinion on reliability, security & performance of these servers.
Comment: Phusion Passenger is not a static thing. It's been constantly developed over the past few years. The Passenger you see today is a very different (and better) beast than the one from a few years ago. Take a look at [the Technology Preview blog posts at blog.phusion.nl](http://blog.phusion.nl/category/passenger/phusion-passenger-technology-previews/). Version 4, released just a little over half a year ago, was a major improvement over not just Passenger 3 but also over Unicorn. As for Puma, try reading [this comparison](https://github.com/phusion/passenger/wiki/Puma-vs-Phusion-Passenger).
Answer: I found this today, I think it does a pretty good job at articulating the pros/cons of the options I described above - https://www.engineyard.com/articles/rails-server


What exactly does "/scoreboard @a  = @a " do?

Question: I'm developing a multiplayer minigame, but haven't been able to get any of my friends to help me on testing yet. I need to set EVERY players internalCash score to their cash score, but cannot use /execute, since it needs to run for non-op players.
It would be INCREDIBLY elegant if I could simply use
/scoreboard players operation @a internalCash = @a cash

but it doesn't seem to work properly with @e, which scares me. Could someone please tell me if I need to develop a clever workaround for this, or if this will do.
edit Oops! Kinda need the "players operation " part. :P
Comment: Hmmmmm... I seem to recall there being a way to do this, but `/scoreboard @a objective = @a objective2` isn't it. I'll look into this.
Comment: @Unionhawk its the players operation under scoreboard
Comment: @ModDL Yeah, `/scoreboard players operation @a targetObjective = @a sourceObjective`, I *think*, but I'm not confident enough/haven't tested the operation of this enough to post such things as an answer right now. If you want to. go for it
Comment: Same here, haven't tested this out. Never had to use operation before.
Answer: /execute does not require the targets to be OP'd and is very necessary to use in order to do what you're trying to do. /scoreboard operations requires one of the two selectors to resolve to a single target, so you cannot use @a with @a.
Using /execute:
/execute @a ~ ~ ~ scoreboard players operation @a[c=1] internalCash = @a[c=1] cash

Comment: You might be confusing execute with JSON-based commands in books, signs and tellraw, which do run with the user's permission level (hence `/trigger` exists).
Comment: @MrLemon Just a tiny correction: signs, unlike /tellraw or books, actually behave like /execute in that the clicker is given elevated permission to run the command. Oddly though, the coordinate origin of execution is the sign's coordinates, but the player is still the designated executor as sender bias applies to them.
Comment: It doesn't? Hmm. I thought I had trouble with that before. What you suggest is what i originally had (except the @a[c=1] were @p selectors instead). So I DON'T have to go through and redo EVERYTHING. Thank goodness. Also, thanks for the help! :) New here, so my upvote doesn't count for your answer score :(
Comment: @sharpturn From the [wiki](http://minecraft.gamepedia.com/Commands#execute): "executes the specified command as if executed by the specified target(s) with operator-level permission". Using `@a[c=1]` is preferred if /execute's target is also `@a`, because it is the only selector capable of targeting dead players. If you used `@p` instead of `@a[c=1]`, dead players will still run the /scoreboard command but will instead target the next-nearest living player, which changes the wrong target's scores. You could also use `@e[type=Player]` instead of `@a` for /execute and use `@p` for /scoreboard.
Comment: Thanks for all the help! I was probably just confusing /tellraw clickEvents with /execute commands. I only recently got back into commands in minecraft, so still very slightly rusty. Still capable of making shelves in one command block, though! Proud of that one.