text:
Q: Regex to separate list of parameters at commas, but ignore commas enclosed in quotation marks I need to parse a string that's a comma-separated lists of parameters of the form
key1=value1,key2=value2,key3=value3...

The complication is that the values can be enclosed in quotation marks to allow them to contain spaces and commas and such. Of course the quotation-mark enclosed commas should not count as separating parameters. (There can also be spaces in various places outside the quotation marks that maybe should be ignored.)
My thought is to split the list at the commas, and then inside each parameter definition, to separate the key from the value at the equal sign. So to split the parameters, I need to find the valid ones (not in quotation marks); I'm thinking a regular expression is the way to go for brevity and directness.
Here are some example strings:

*

*Include="All Violations", CheckType=MaxTrans

*MetricName = PlacedInstances, PlacedOnly = 1

*CheckType=Hold, Include="reg2reg,in2reg,in2out,reg2out"

*CheckType=Setup, Include="reg2reg,in2reg,in2out,reg2out (sic)

Yes, the last one is poorly formed: missing a terminating quotation mark in the value.
I found this answer helpful (regex: /,(?=(?:(?:[^"]*"){2})*[^"]*$)/), except for parsing the poorly formed one. In my case I've got additional information in the equal sign, which would allow parsing that one.
I tried this: (/(?<==[^"]+),/, which works for the poorly formed one, but fails my first example. I think what I need is a way to find commas preceded by an equal sign but which have either zero or two quotation marks (not just a single quotation mark) between them and the first preceding equal sign. But how do I write that in Javascript Regex?

A: Something like this would work:
/(?:^|, *)(?<key>[a-z]+) *= *(?<value>[^\r\n,"]+|"[^\r\n"]+"?)/gmi

https://regex101.com/r/z05WcM/1

*

*(?:^|, *)(?<key>[a-z]+) name a capture group "key" which is defined as a sequence of alpha chars which are either at the start of the line or after a comma and optional space

* *= * - the assignment operator (equal sign) can have spaces on either side

*(?<value>[^\r\n,"]+|"[^\r\n"]+"?) - name a capture group as "value" which is either a non comma and non quote containing string or if it starts with a quote then it can have commas with an optional closing quote

But if you have data like Include="All Viola\"tions" then it will fail.
Do note that I avoided using lookbehinds because they are not universally supported in all browsers.

A: One could use an approach which is based on e.g. two regular expressions ...

*

*/,\s*(?=[^=,]+=)/

*/^(?<key>[^=\s]+)\s*="*(?<value>[^"]+)/
The first one has to split the provided string according to the OP's requirements; thus it is based on a positive lookahead.
The second one will be used within an operation which does map the resulting array of parameter template items. Each item will be processed by a regex which tries to capture named groups. In addition the string value of a group's value field will be trimmed.

// see ... [https://regex101.com/r/nUc8en/1/]
const regXParameterSplit = (/,\s*(?=[^=,]+=)/);

// see ... [https://regex101.com/r/7xSwyX/1/]
const regXCaptureKeyValue = (/^(?<key>[^=\s]+)\s*="*(?<value>[^"]+)/);

const testSample = 'Include="All Violations", CheckType=MaxTrans, MetricName = PlacedInstances, PlacedOnly = 1, CheckType=Hold, Include="reg2reg,in2reg,in2out,reg2out", CheckType=Setup, Include="reg2reg,in2reg,in2out,reg2out,CheckType=Setup';

function getKeyAndValue(template) {
  const { groups } = (regXCaptureKeyValue.exec(template) || {});
  if (groups) {
    groups.value = groups.value.trim();
  }
  return groups;
}

console.log(
  '... just splitting ...',
  testSample
    .split(regXParameterSplit)
);
console.log(
  '... the full approach ...',
  testSample
    .split(regXParameterSplit)
    .map(getKeyAndValue)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

A: Use
string.match(/\w+\s*=\s*(?:"[^"\n]*(?:"|$)|\S+(?=,|$))/g)

See proof.
Explanation
--------------------------------------------------------------------------------
  \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  =                        '='
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  (?:                      group, but do not capture:
--------------------------------------------------------------------------------
    "                        '"'
--------------------------------------------------------------------------------
    [^"\n]*                  any character except: '"', '\n'
                             (newline) (0 or more times (matching the
                             most amount possible))
--------------------------------------------------------------------------------
    (?:                      group, but do not capture:
--------------------------------------------------------------------------------
      "                        '"'
--------------------------------------------------------------------------------
     |                        OR
--------------------------------------------------------------------------------
      $                        before an optional \n, and the end of
                               the string
--------------------------------------------------------------------------------
    )                        end of grouping
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    \S+                      non-whitespace (all but \n, \r, \t, \f,
                             and " ") (1 or more times (matching the
                             most amount possible))
--------------------------------------------------------------------------------
    (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
      ,                        ','
--------------------------------------------------------------------------------
     |                        OR
--------------------------------------------------------------------------------
      $                        before an optional \n, and the end of
                               the string
--------------------------------------------------------------------------------
    )                        end of look-ahead
--------------------------------------------------------------------------------
  )                        end of grouping


text:
Q: Need help in solving Remote - SSH problem Hello guys I am trying to do Remote SSH for quite some time and unable to make it work .
The problem :
Trying to connect to Aws Codecatalyst Dev environment Linux(remote ssh) to my local windows machine and it is in an endless loop of " Setting up SSH Host aws -exampleID".
I had tried it with my remote ubuntu aws workspace and it works flawlessly (ubuntu remote workspace to Aws codecatalyst Dev Environment) so it seems like some issue with my local machine .
Things I have tried:
When comparing the logs of failed vs successful I have noted that the remote.SSH.useLocalServer was true in my success log. So tried to add this to the settings.json but during run time it automatically changes from true to false .
Also tried clean uninstall and install couple of times (remove appData and ssh config files)
I have added an image of log of the failed Remote SSH .
Would appreciate if Remote SSH users can take a look into the logs and give their insights .
log of Remote SSH

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unknown column XXXX in field_list OK, here's a weird issue :

Error Number: 1054
Unknown column 'alias' in 'field list'
INSERT INTO projects (id, alias, url, domains, progress,
  total, email)
  VALUES
  (80511, 'Some Alias', 'somedomains.com',
  'xxxxxx', 0, 199, 'some@gmail.com')

I've been using a specific database table, which I've been populated through a model script.
After I added another column (let's say alias), the function doesn't work anymore and displays the above error.

And the Database population code :
function createNew($proj)
{
    $data = array(
        'id' => $proj['id'],
        'alias' => $proj['alias'],
        'url' => $proj['url'],
        'domains' => $proj['domains'],
        'progress' => $proj['progress'],
        'total' => $proj['total'],
        'email' => $proj['email']
        );

    $this->db->insert('projects',$data);
}

The weirdest thing of all is that when I manually execute the exact same query (e.g. using the SQL via phpMyAdmin), it works perfectly fine.
Any ideas?

A: Have you tried to use query method?
$sql = 'INSERT INTO projects (id, alias, url, domains, progress, total, email) VALUES (?, ?, ?, ?, ?, ?, ?)';
$this->db->query($sql,$proj);

A: Since alias is a keyword in Sql so just use '`alias`' when you want to insert data to the table.
'`alias`' => $proj['alias']


text:
Q: How to convert ASCII to int? I am getting an ASCII value and I want to convert it into an integer because I know it's an Integer ASCII value.
int a=53;

This is an ASCII value for 5. How would I be able to convert it to an integer?

A: int yourInt = Integer.parseInt(yourString);

http://www.cse.wustl.edu/~kjg/java/api/java/lang/Integer.html#parseInt%28java.lang.String%29

A: int asciiValue = 53;
int numericValue = Character.getNumericValue(asciiValue);

System.out.println(numericValue);

A: Use:
try
{
  int i = Integer.parseInt(StringValue);
}
catch (NumberFormatException nfe)
{
  System.out.println("NumberFormatException: " + nfe.getMessage());
}

A: Use Integer.parseInt(String) or if it is only a single character use: int n = (int) (_char - '0')

A: If you're sure that it is an int, you can just use Integer.parseInt();

A: If you can guarantee the string contains an integer:
 Integer.parseInt(String)

A: Use Integer.parseInt() static method:
Oracle Docs Integer.parseInt()

A: Do you mean a single character or a String?
char ch =
int n = Character.forDigit(ch, 10);

or
int n = ch - '0';


text:
Q: flipping view in swift : issues with whole screen flipping + tap gesture only works twice I would like to create a simple flip effect, but I don't understand the problems I have here :

*

*the whole screen is flipping, not only the view, is there a way to flip the 100,100 square only?

*I can only flip twice, then the tap does not work anymore, would you know why?
import UIKit
class ViewController: UIViewController {

var fromOneToTwo : Bool = true
var view1 : UIImageView!
var view2 : UIImageView!
var tap : UITapGestureRecognizer!

func handleTap(tap: UITapGestureRecognizer){

    println("1/fromOneToTwo \(fromOneToTwo)")
    var v1 = (fromOneToTwo ? self.view1 : self.view2)
    var v2 = (fromOneToTwo ? self.view2 : self.view1)

    UIView.transitionFromView(v1, toView: v2, duration: 0.5, options: (UIViewAnimationOptions.TransitionFlipFromLeft | UIViewAnimationOptions.CurveEaseInOut) ) { finished in

        self.fromOneToTwo = !self.fromOneToTwo
        println("2/fromOneToTwo \(self.fromOneToTwo) ")
    }
}

func createView( str:String)->UIImageView!{
    var img = UIImage(named: str)!
    var imgView = UIImageView(frame: CGRectMake(0,0, 200, 200))
    imgView.image = img
    imgView.sizeToFit()
    imgView.userInteractionEnabled = true
    imgView.addGestureRecognizer(tap)
    return imgView
}

required init(coder aDecoder:NSCoder){
    super.init(coder:aDecoder)

    tap = UITapGestureRecognizer(target: self, action: "handleTap:")
    view1 = createView("imageOnee.png")
    view2 = createView("imageTwo.png")
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(view1)
    view.addSubview(view2)

    view.backgroundColor = UIColor.redColor()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}
Also, when I try to add the whole code in a custom UIView, and add the custom instance myViewto the ViewController, the tap does not work at all.

A: I made this work creating a container view for view1 and view2.  The tap recognizer is then added to this container view.
class ViewController: UIViewController {

    var fromOneToTwo : Bool = true
    var view1 : UIImageView!
    var view2 : UIImageView!
    var container : UIView!
    var tap : UITapGestureRecognizer!

    func handleTap(tap: UITapGestureRecognizer){

        println("1/fromOneToTwo \(fromOneToTwo)")
        var v1 = (fromOneToTwo ? self.view1 : self.view2)
        var v2 = (fromOneToTwo ? self.view2 : self.view1)

        UIView.transitionFromView(v1, toView: v2, duration: 0.5, options: .TransitionFlipFromLeft | .CurveEaseInOut ) { finished in

            self.fromOneToTwo = !self.fromOneToTwo
            println("2/fromOneToTwo \(self.fromOneToTwo) ")
        }
    }

    func createView( str:String)->UIImageView!{
        var img = UIImage(named: str)!
        var imgView = UIImageView(frame: CGRectMake(0, 0, 200, 200))
        imgView.image = img
        imgView.sizeToFit()
        return imgView
    }

    required init(coder aDecoder:NSCoder){
        super.init(coder:aDecoder)

        tap = UITapGestureRecognizer(target: self, action: "handleTap:")
        view1 = createView("imageOnee.png")
        container = UIView(frame: CGRectMake(0, 0, view1.bounds.width, view1.bounds.height))
        container.userInteractionEnabled = true

        container.addGestureRecognizer(tap)
        container.addSubview(view1)
        view2 = createView("imageTwo.png")
        container.addSubview(view2)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(container)

        view.backgroundColor = UIColor.redColor()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}


text:
Q: qgis2threejs generated webpage works fine in Chrome, but not in Safari Exported HTML from qgis2threejs and uploaded it to my website. Everything works fine in Chrome, but not in Safari. I exported the file using the defaults. It opens fine and works completely in Chrome, but with Safari I get an initial message saying "page was reloaded because a problem occurred" then it goes to a message that says "A problem repeatedly occurred with www.rioembudobirds.org/ws3d/" with an active "Reload Webpage" button. Have shutdown and restarted my computer. I generated the html in qgis2threejs again and re-uploaded. Same result. Safari ver: 15.0 MacBookPro MacOS BigSur ver:11.6  Below are screen shots from qgis2threejs while exporting. Here is the link to the page: http://www.rioembudobirds.org/ws3d/
qgis2threejs export dialog
qgis2threejs export log


text:
Q: BibTeX style like [Jones90]? Is there a "standard" BibTeX style which is like 'alpha' in all other respects but uses first author surname, (preferably) 2-digit year keys, so a citation for "Jones, Smith and Other" would show up like [Jones90], perhaps with a disambiguator like [Jones90a]?
Ideally I don't want to manually hack .bst files since learning the language looks like a 2 week project by itself. I tried using http://www.witpress.com/downloads/authors/latex/witpress.dbj which does offer Jones90-like as an option, calling it "alf-f", but it asks dozens of very pernickety questions, meaning I'm very likely to screw something up; I've yet to find a .bst generator that allows you to say "I want a style like [standard] except for [attribute].

A: I don't think there's a "standard" BibTeX bibliography style out there that already accomplishes what you're looking for. However, achieving your objective fortunately doesn't require you to learn BibTeX's programming language. I suggest you take a look at the makebst utility. Type
latex makebst

at a command prompt and follow the detailed prompts to build your very own custom .bst (bibliography style file) file. You'll get lots of questions; when in doubt, just select the default option that's presented (which one "selects" by simply hitting "Return").
One of the first substantive questions and associated options you'll encounter are the following:
STYLE OF CITATIONS:
(*) Numerical as in standard LaTeX
(a) Author-year with some non-standard interface
(b) Alpha style, Jon90 or JWB90 for single or multiple authors
(o) Alpha style, Jon90 even for multiple authors
(f) Alpha style, Jones90 (full name of first author)
(c) Cite key (special for listing contents of bib file)
  Select:

Be sure to type f to choose the option Alpha style, Jones90 (full name of first author). Continue to make informed choices for all further questions, and you'll have a customized .bst file.


text:
Q: Verifying S3 credentials w/o GET or PUT using boto3 Is there a way to verify a given set of S3 credentials has access to a specific bucket without doing an explicit PUT or GET of some sort?
Instantiating an s3.Client, s3.Resource or s3.Bucket object doesn't seem to verify credentials at all, let alone bucket access.
boto3 1.4.7.
python 2.7.13.
We have automation and orchestration that automates bucket creation and I want to include a piece that verifies a user's access key and secret. I know the bucket exists at this point since I created it. The bucket is empty.
I want to verify a user has access w/o doing a PUT operation.
Thanks for any help.
* update *
I ended up doing this with an s3.Client object:
objects = client.list_objects(Bucket=cfg['bucket'])

Since the bucket is empty this is a lightweight operation and a one-liner for the most part. (wrapped in a try block)

A: Use head_bucket.

head_bucket(**kwargs)
This operation is useful to determine if a
bucket exists and you have permission to access it.

If you don't have access, you will get an exception:

botocore.exceptions.ClientError: An error occurred (403) when calling
the HeadBucket operation: Forbidden

Modify this Python 2.7 code to suit to your needs:
import boto3
s3 = boto3.client('s3')
try:
  s3.head_bucket(Bucket='mybucket')
  print 'Can access the bucket'
except:
  print 'Cannot access the bucket'

A: Yes, you can use IAM policy simulation for that. Here's an example:
import boto3

iam = boto3.client('iam')
sts = boto3.client('sts')

# Get the arn represented by the currently configured credentials
arn = sts.get_caller_identity()['Arn']

# Create an arn representing the objects in a bucket
bucket_objects_arn = 'arn:aws:s3:::%s/*' % 'my-test-bucket'

# Run the policy simulation for the basic s3 operations
results = iam.simulate_principal_policy(
    PolicySourceArn=arn,
    ResourceArns=[bucket_objects_arn],
    ActionNames=['s3:PutObject', 's3:GetObject', 's3:DeleteObject']
)
for result in results['EvaluationResults']:
    print("%s - %s" % (result['EvalActionName'], result['EvalDecision']))

You can find all the s3 actions here.
One caveat to this is that IAM is eventually consistent, so if you're creating users on the fly you still might have to wait a bit for the changes to propagate.


text:
Q: Angular typeahead debouncetime request Search functionality debounce issue makes too many requests and debounceTime not working properly.
 <search"></search>

 search(argument: string): void {
    this.argument = argument;
      this.searchService
        .getSuggestions(this.argument )
        .pipe(debounceTime(8000), distinctUntilChanged(), take(1))
        .subscribe(
          (suggestions) => {
            this.suggestions= suggestions;
          }
        );
    }

A: The reason that your current implementation is not working is that you are creating a new subscription every time you enter a character.
 search(argument: string): void {
    // you don't need to do this
    this.argument = argument;
    // or this
    this.live = this.argument.length >= 3;
    if (this.live) {
      this.searchService
        .getSuggestions(this.argument )
        .pipe(debounceTime(8000), distinctUntilChanged(), take(1))
        // This subscription is then called every time you enter a value
        .subscribe(
          (suggestions: Array<string>) => {
            this.suggestions= suggestions;
            this.changeDetection.detectChanges();
          }
        );
    }

I would use a form control for your search input like this:
<input [formControl]='myControl'>`

In your TS, declare this as a class variable:
myControl = new FormControl();

FormControl exposes valueChanges as an observable that you can then subscribe to.
Then you probably want to do something like this:
suggestions$ = this.myControl.valueChanges.pipe(
    // use an RxJS filter here instead of using class variables like you were earlier
    filter(searchTerm => searchTerm?.length >= 3),
    distinctUntilChanged(),
    debounceTime(8000),
    // switchMap will subscribe to the inner observable
    // and cancel any in flight XHR requests if you create a new one
    switchMap(valueChange =>
       this.searchService.getSuggestions(valueChange)
    )
)

I am assuming you will have some sort of *ngFor to iterate through the suggestions that are returned, like so:
<suggestion
    *ngFor="let suggestion of suggestions$ | async"
    [suggestion]="suggestion"
></suggestion>

Using the async pipe ensures that your subscription is tidied up on destroy of the component. You can do this in other ways (you are on the right path with your usage of take(1)), but a suggestion (pun unintended :D) from me would be to use the async pipe where possible.

A: Hi try below code for typeahead functionality
this.searchService
.getSuggestions((this.argument)).pipe(
    debounceTime(8000),
    distinctUntilChanged(),
    switchMap((this.argument) => {

        // Any other operation

    })
)
.subscribe((res) => {
    // Result
});


text:
Q: MTASA GTA SA On Ubuntu Keeps Crashign I installed GTA and it works completly fine. I have samp and it works. I tried installing MTA and it turns on...But then it just closes. Any fixes?

A: Try installing some essential programs if you haven't.. C++ 2005/2008 Redistributable Package and perhaps .NET 2/3/3.5. That could be the problem. If that doesn't work, then I am not sure.. Never used MTA so can't help you there too. SAMP works great though :D


text:
Q: How to add meta tag to wordpress posts filter? For example, I have an url:
mysite.com/author/admin

It's not considered as single post or single page to add meta tag via SEO plugin. And to this page I want to add something like:
<meta name="description" content="All posts by author admin."/>

Is there are any way to do this? Thanks in advance!

A: There is not a standerized way to add HTML meta tags in WordPress but you can use wp_head action as a generic way to add meta tags.
I think description meta tag should not be in the theme, as you suggest in your answer, because description meta tag is a property of the document, nothing to do with the look and feel of the document, that is, the theme.
This is a samlple code to do it:
add_action( 'wp_head', 'cyb_author_archive_meta_desc' );
function cyb_author_archive_meta_desc() {

   // Check is we are in author archive
   // https://developer.wordpress.org/reference/functions/is_author/
   if( is_author() ) {
       // get_queried_object() returns current author in author's arvhives
       // https://developer.wordpress.org/reference/classes/wp_query/get_queried_object/
       $author = get_queried_object();

       // Generate meta description
       $description = sprintf( __( 'All posts by author %s', 'cyb-textdomain' ), $author->display_name );

       // Print description meta tag
       echo '<meta name="description" content="' . esc_attr( $description ) . '">';
   }

}

A: UPDT: Figured it out. Had to just hardcode it in header.php file located in my theme name folder.
<!-- Meta Tags -->

<?php if (is_archive() && !is_category()){
   echo '<meta property="og:description"  content="Your description"/>';
}
?>


text:
Q: Getting the error since Python 3.9.5 was installed on Ubuntu 18.04 scrapy startproject dal

GIVES THIS ERROE SINCE I INSTALLES PYTHON 3.9.5 IN UBANTU 18.04
 from .. import etree
ImportError: cannot import name 'etree' from 'lxml' (/usr/lib/python3/dist-packages/lxml/__init__.py)


text:
Q: valgrind does not show line numbers I'm probably missing sth obvious. I find many related questions on StackOverflow, but they just tell me things I already did. I compile my test app like:
g++ -std=c++11 -g -O0 core_cpu.cpp test.cpp -o test.bin

Then, running valgrind ./test.bin:
...
==23638== Invalid write of size 4
==23638==    at 0x401F12: ??? (in /u/zeyer/setups/combined/2021-05-31/tools/returnn/returnn/extern/WarpRna/warp-rna/test.bin)
==23638==    by 0x40223B: ??? (in /u/zeyer/setups/combined/2021-05-31/tools/returnn/returnn/extern/WarpRna/warp-rna/test.bin)
==23638==    by 0x402AAC: ??? (in /u/zeyer/setups/combined/2021-05-31/tools/returnn/returnn/extern/WarpRna/warp-rna/test.bin)
==23638==    by 0x40361C: ??? (in /u/zeyer/setups/combined/2021-05-31/tools/returnn/returnn/extern/WarpRna/warp-rna/test.bin)
==23638==    by 0x4038B4: ??? (in /u/zeyer/setups/combined/2021-05-31/tools/returnn/returnn/extern/WarpRna/warp-rna/test.bin)
==23638==    by 0x56FB83F: (below main) (libc-start.c:291)

So, there are no line numbers. What am I missing?
Edit Ah, I just found the comment here, which says this was a problem with some older valgrind version, and I actually have an old valgrind version (still Ubuntu 16.04), so that might be it. I'm trying to get a newer valgrind version and test that.

A: My valgrind version was too old. After installing 3.19.0 (downloading the source and compiling it), it works.


text:
Q: Is there a way to integrate the contributions/commits from Azure DevOps to GitHub? In the past 6 months I've been working with Azure DevOps. Due to that, my GitHub contributions chart looks a bit empty.
I would like to integrate all of my contributions from Azure DevOps to Github's contributions chart.
I did some research, browsed for different extensions/APis. Though there are plenty out there, it didn't seem like they covered what I wanted to achieve.
Is this possible? Any suggestions?

A: First of all,  you should understand that GitHub and Azure DevOps are independent systems. Azure DevOps has provided some functions e.g REST API, extensions to get repository from GitHub. But It's a one-way data transfer from GitHub to Azure DevOps.
There is no supported REST API or extensions that can sync commits from Azure DevOps to your GitHub according DevOps documents at present.
I'm afraid that you could only sync contributions/commits manually.
If  you want GitHub contributions chart logged your activity, you should make commits in GitHub.


text:
Q: Sinon clock.tick doesn't advance time for setTimeout I am writing a test for an async function which performs a series of tasks and at one point waits for 60 seconds before doing some more tasks. I am trying to use sinon.useFakeTimers() to skip those 60 seconds so that I can test the logic after the delay.
foo.js
module.exports.foo = async f => {
  // ... more code ...
  await new Promise((resolve, reject) => {
    setTimeout(resolve, 60000);
  });
  // ... more code ...
  f();
  // ... more code ...
};

test-foo.js
const sinon = require('sinon');
const expect = require('chai').expect;

const { foo } = require('./foo');

describe('Module Foo ', function() {
  it('call function after 1 minute', function() {
    var clock = sinon.useFakeTimers();
    const bar = sinon.stub();

    foo(bar);
    expect(bar.called).to.be.false;
    clock.tick(100000);
    expect(bar.called).to.be.true; // this one fails
  });
});

I tried putting sinon.useFakeTimers(); in various other places, but the Promise doesn't resolve and the stub I pass into foo doesn't get called.

A: Make your test function async and await a resolved Promise after advancing your clock to give the Promise callback queued by the await in foo a chance to run before doing your assertion:
const sinon = require('sinon');
const expect = require('chai').expect;

const { foo } = require('./foo');

describe('Module Foo ', function() {
  it('call function after 1 minute', async function() {  // <= async test function
    var clock = sinon.useFakeTimers();
    const bar = sinon.stub();

    foo(bar);
    expect(bar.called).to.be.false;  // Success!
    clock.tick(100000);
    await Promise.resolve();  // <= give queued Promise callbacks a chance to run
    expect(bar.called).to.be.true;  // Success!
  });
});

For complete details see my answer here which uses Jest and Jest timer mocks but the concepts are the same and also apply to Mocha and Sinon fake timers.


text:
Q: Why does \dimexpr swallow \relax? Following the comments at Doing maths with distance values in LaTeX source code:

+1 for teaching me that \dimexpr can optionally swallow a \relax. Yesterday I tried to use \relax as a delimiter for \numexpr, and I just couldn't understand why the \relax is gone although it's not expandable. – Hendrik Vogt Feb 18 at 9:32
@Hendrik: Yeah, I think you need two \relax then. I find the \relax swallowing extremely useful. Its friends like \numexpr do the same. – Martin Scharrer♦ Feb 18 at 9:36

and with this issue being touched on again by the answers of Joseph and Martin at Which is better: a dimension or a macro?, I ask myself why does Etex do things this way?  I find it unintuitive and I don't see how it can be useful to avoid carrying out a no-operation command.

A: For the same reason as TeX gobbles a trailing spaces from numbers. In the case of TeX, this is needed to stop a number cleanly and make sure that in all cases it will be terminated without expanding anything further nor inserting a blank space. In fact, TeX probably skips spaces after control words (multiletter control sequences) for the same reason (although that happens at a different stage of processing). The idea is that it should always be possible to "stop without inserting anything".
Example: \ifdigit below tests whether the argument is a digit. The space after #1 is required to stop TeX from expanding the first \expandafter prematurely. On the other hand, we don't want the space to end up in the output. So in that case at least, TeX's space gobbling is a feature.
\long\def\ifdigit#1{%
    \ifnum 9<1\string #1 %
        \expandafter\@firstoftwo
    \else
        \expandafter\@secondoftwo
    \fi}

eTeX's designers could decide that a space stops the \numexpr or \dimexpr, because they simply use TeX's procedures to read operands. And these procedures already remove a trailing space. eTeX does not see the space before + in \numexpr 1 + 2. It would have been technically possible to let \numexpr be stopped by two space tokens in a row, and gobble them, but that would be very difficult to input, since two space characters in a row are equivalent to one. Some other delimiter had to be chosen. It had to be non-expandable, preferably already there in the language, and it had better do nothing when used outside a \...expr situation... No need to add a new primitive: \relax was a natural choice.
Now consider a \compareint function defined as follows
\long\def\compareint#1#2#3{%
    \ifnum\numexpr#1\relax#2\numexpr#3\relax
        \expandafter\@firstoftwo
    \else
        \expandafter\@secondoftwo
    \fi}
\compareint{1+2}<{3-1}{Yes}{No}

In this particular case, leaving \relax behind would not be a problem. However, think of nesting this:
\def\X{345}\def\Y{534}
\compareint {132} < {\compareint{12}>{9}{\X}{\Y}+1} {Yes} {No}

If the \relax was not removed from the internal \compareint, it would stop expansion of the outside \compareint too early (actually, before expanding to \X or \Y, so that would be a problem).

A: Actually, the single paragraph of documentation in the e-TeX manual already answers this question with an illustrative example, which surprisingly has not been mentioned in the answers here. The example given there is:
\ifdim\dimexpr (2pt-5pt)*\numexpr 3-3*13/5\relax + 34pt/2<\wd20

as equivalent to \ifdim 32pt < \wd20. In this case, the inner \numexpr 3-3*13/5\relax expands to -5 (note rounding), so that the outer \dimexpr becomes equivalent to (-3pt) * (-5) + 17pt. If the \relax were not swallowed, and were instead left on the input stream, then the outer \dimexpr would also get terminated at the \relax, resulting in errors.

For completeness, reproducing the documentation of the grammar here, lightly reformatted:

e-TeX introduces the notion of expressions of type number, dimen, glue, or muglue, that can be used whenever a quantity of that type is needed. Such expressions are evaluated by e-TeX's scanning mechanism;

*

*they are initiated by one of the commands \numexpr, \dimexpr, \glueexpr, or \muexpr (determining the type t) and optionally terminated by one \relax (that will be absorbed by the scanning mechanism).

*An expression: consists of one or more terms of the same type to be added or subtracted;

*a term of type t: consists of a factor of that type, optionally multiplied and/or divided by numeric factors; finally

*a factor of type t: is either a parenthesized subexpression or a quantity (number, etc.) of that type.
Thus, the conditional
\ifdim\dimexpr (2pt-5pt)*\numexpr 3-3*13/5\relax + 34pt/2<\wd20

is true if and only if the width of box 20 exceeds 32 pt .
Note the use of \relax to terminate the inner (numeric) expression, the outer (dimen) expression is terminated automatically by the token <₁₂ that does not fit into the expression syntax.

And then there are a couple more paragraphs about arithmetic (e.g. rounding), and how this is expandable.

A: To add to what Hendrik says, I think the overall point was that \numexpr, \dimexpr, etc. can be used in a full expansion context without leaving a stray \relax or space:
\edef\example{\the\dimexpr 10 pt + 20 pt \relax}

gives \example defined as 30pt with no unexpected tokens. That is in many ways much 'neater' than the alternative of leaving the \relax in place. The same argument does not apply to TeX's setting of registers as that is never expandable, so the issue does not arise.
(Of course, for a definitive answer you would need to ask the members of the NTS team who actually wrote this code.)

A: I would say this makes it easy to delimit a \dimexpr in a fully expandable way. Putting a \relax is a usual way to delimit TeX dimensions, which I learned the hard way: It's always a good idea to put a \relax after something like \hskip1pt. Now it seems that eTeX just made a principle out of this.
(An alternative is to put a space to delimit a TeX dimension, but firstly a \relax is a lot more visible, and secondly it's sometimes not so easy to put a space, namely after a control sequence. As Bruno points out in his comment, spaces cannot be used to delimit \dimexpr and friends.)


text:
Q: any easy way AOSP app development workflow? i am trying development an app put in aosp source tree.it use aosp built system,and with some native code .it also is an system app.but development workflow is a bit annoying:  i am modify my app code first.then go aosp dir,run mmm command,then use make command build system images and flash it to my android development board.then run app for test and check logcat,then back to modify code ....
is there any other workflow for development system app ?
i have tryed these method:
Android.mk with these line:
LOCAL_CERTIFICATE := platform
LOCAL_PRIVILEGED_MODULE := true

i can not use adb install install app apk file found in build out dir.
if i comment out that two lines,and set LOCAL_MODULE_TAGS := tests,then i can install apk use adb install command. but app is not system app,can not access some native api.
and my app have some native code.(not prebuilt library),aosp build apk but without my library.so my app can not running with error:
java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data

/app/com.mytest.app-IpmPY1ehtNYFMP3BCMb8HA==/base.apk"],nativeLibraryDirectories=[/data/app/com.mytest.app-IpmPY1ehtNYFMP3BCMb8HA==/lib/arm64,
/system/lib64, /vendor/lib64]]] couldn't find "libmytest_jni.so"

then i am check my device filesystem,aosp not pack my library into system.img.
here is Android.mk for app:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_SRC_FILES := \
            $(call all-subdir-java-files)

# LOCAL_MODULE_TAGS := optional
LOCAL_MODULE_TAGS := tests
LOCAL_PACKAGE_NAME := Mytest

LOCAL_SDK_VERSION := current

# with this two lines,i can not use adb install to update my app
# without ,can not access some system api
# LOCAL_CERTIFICATE := platform
# LOCAL_PRIVILEGED_MODULE := true
LOCAL_PROGUARD_ENABLED := disabled
LOCAL_DEX_PREOPT := false

LOCAL_JNI_LIBRARIES := libmytest_jni
LOCAL_REQUIRED_MODULES := libmytest_jni

include $(BUILD_PACKAGE)

#jni
include $(CLEAR_VARS)
include $(call all-makefiles-under,$(LOCAL_PATH))

Android.mk for libmytest_jni library:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

# with this line, library not pack into system.img
# without this line,is pack into system.img,but i must refulsh image file to test
# whatever with or without,library is not pack into apk file.
# LOCAL_MODULE_TAGS := tests

LOCAL_MODULE:= libmytest_jni

LOCAL_SRC_FILES:= \
    main_jni.cpp

LOCAL_SHARED_LIBRARIES := \
    libnativehelper \
    libcutils \
    libutils \
    liblog

LOCAL_C_INCLUDES += \
    $(JNI_H_INCLUDE)

LOCAL_CFLAGS +=

include $(BUILD_SHARED_LIBRARY)

A: *

*For a module to be added as part of system when you run full make, you'll have to add it in your device makefile, or device.mk a line like this:  PRODUCT_PACKAGES += MyTest

*When building a specific module via mmm, you'll have to run make snodto re-generate system.img

*Instead of flashing system.img like in step 2, you can use adb sync. This will push any changed files to device. You might need to run adb reboot, or at least adb shell stop && adb shell start after.


text:
Q: How to pass hidden field value to query string in asp.net view? I am using asp.net mvc with razor view.I have a scenario where I have to pass the hidden field value to query string and access the value. I've declared the hidden field but the problem is that I cannot access the hidden field.
The declaration of hidden field goes here
@model CloudCashWizard.Models.CashSafeLockViewModel
@{
   ViewBag.Title = CloudCashWizard.Resources.Resources.AMSEC;
   <input type="hidden" value="@Model.CashSafeLockView.DoorNumber" id="hFieldDoorNumber"
   name="hFieldDoorNumber" />
}

Want to access the hidden field here at DoorNo
 Print

How can I do that?Any help will be appreciated.

A: M.b that's easier to create form with GET method and it will assemble proper URL by itself, based on fields inside that form.
Example:
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Get))
{
  @Html.Hidden("CashSafeId", Model.CashSafeLockView.CashSafeId);
  @Html.Hidden("DoorNo", Model.CashSafeLockView.DoorNumber);

  <button type="button">Print</button>
}

A: You can use this script:
$(document).ready(function(){
   $('body').on('click', 'a', function (e) {
      $(e).attr("href", $(e).attr("href") + '&ParamName='+$('#hFieldDoorNumber').val();
   });
});


text:
Q: How to loop through elements inside a foreach() I'm basically trying to loop through links that I've already selected using querySelectorAll, which runs in a forEach method that also loops through a list of boxes.
Unfortunately, I'm still unable to solve the second part of the code (looping through the link node list).
A simple summary of the code is something like this:

const link = document.querySelectorAll('.link')
const box = document.querySelectorAll('.box')

box.forEach((singleBox) => {
    singleBox.addEventListener("mouseenter", () => {
        link[].classList.add('top'); // I know I need to use a for loop here to loop between link node list, but i'm still unable to find out the way :(
    });
    singleBox.addEventListener("mouseleave", () => {
        link[].classList.remove("top");
    });
});
.box {
      position: relative;
      width: 30rem;
      height: 25rem;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      transition: all 1s ease-out;
 }

.img-holder {
      background: #fff;
      width: 18rem;
      height: 18.8rem;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: flex;
      justify-content: center;
      align-items: center;
  }

.link {
    position: absolute;
    width: 200px;
    height: 200px;
    background-color: transparent;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -35;
}

.top {
    z-index: 35;
    cursor: pointer;
    transition: all .5s ease-in;
    background-color: red; // Changing he bg-color just for visualizing whats going on //
}
/* first box I'm looping through (using foreach) */

     /* first link */

/* second box I'm looping through (using foreach) */

     /* second link */

A: You could get the .links per box like below:

const box = document.querySelectorAll('.box');

box.forEach((singleBox) => {
  let boxLinks = singleBox.querySelectorAll('.link');
    singleBox.addEventListener("mouseenter", () => {
      boxLinks.forEach(boxLink => {
        boxLink.classList.add('top');
      });

    });
    singleBox.addEventListener("mouseleave", () => {
      boxLinks.forEach(boxLink => {
        boxLink.classList.remove('top');
      });
    });
});
.box {
      position: relative;
      width: 30rem;
      height: 25rem;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      transition: all 1s ease-out;
 }

.img-holder {
      background: #fff;
      width: 18rem;
      height: 18.8rem;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: flex;
      justify-content: center;
      align-items: center;
  }

.link {
    position: absolute;
    width: 200px;
    height: 200px;
    background-color: transparent;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -35;
}

.top {
    z-index: 35;
    cursor: pointer;
    transition: all .5s ease-in;
    background-color: red; // Changing he bg-color just for visualizing whats going on //
}
/* first box I'm looping through (using foreach) */

     /* first link */

/* second box I'm looping through (using foreach) */

     /* second link */


text:
Q: Layout Height for Card View is not working? I was trying to make a cardview of layout_height=="match_parent" but the card's height is never match_parent, it's always wrap_content.
I tried all permutation of converting RelativeLayout to LinearLayout and even FrameLayout for my activity_main but nothing worked. Please tell me how to increase it's size to match_parent
list_item.xml
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="16dp"
card_view:cardCornerRadius="2dp"
card_view:contentPadding="10dp"
android:layout_margin="8dp"
android:background="?android:selectableItemBackground">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dp"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/sportsImage1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"/>

    <TextView
        android:id="@+id/newsTitle1"
        style="@style/TextAppearance.AppCompat.Headline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/subTitle1"
        style="@style/TextAppearance.AppCompat.Subhead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp" />

</LinearLayout>

</android.support.v7.widget.CardView>
</RelativeLayout>

I can't remove Relative Layout containing card_view in my list_item.xml file because if I did so then card_view loses its shadow and looks like a normal view.
activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:divider="@android:color/transparent"
    android:id="@+id/list"
/>
</RelativeLayout>

I tried removing relative layout in activity_main also but that also didn't work.

MainActivity.java

    public class MainActivity extends AppCompatActivity {

String title="Bitfinex Confirms it Will not List the Petro Cryptocurrency";
String cont="It is evident the Venezuelan Petro is a pretty intriguing currency.";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<News_item> arrayList=new ArrayList<News_item>();
    arrayList.add(new News_item(R.drawable.img_badminton,title,cont));
    arrayList.add(new News_item(R.drawable.img_baseball,title,cont));
    arrayList.add(new News_item(R.drawable.img_basketball,title,cont));
    arrayList.add(new News_item(R.drawable.img_bowling,title,cont));
    arrayList.add(new News_item(R.drawable.img_cycling,title,cont));
    arrayList.add(new News_item(R.drawable.img_golf,title,cont));
    arrayList.add(new News_item(R.drawable.img_running,title,cont));
    arrayList.add(new News_item(R.drawable.img_soccer,title,cont));

    News_adapter adapter=new News_adapter(this,arrayList);
    ListView listView=(ListView) findViewById(R.id.list);
    listView.setAdapter(adapter);

}
}

ArrayAdapter
   public class News_adapter extends ArrayAdapter<News_item> {
Context mContext;
public News_adapter(@NonNull Context context, ArrayList<News_item> resource) {
    super(context,0,resource);
    mContext=context;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.layout, parent, false);
    }
    News_item news_item=getItem(position);
    TextView textView=(TextView) listItemView.findViewById(R.id.newsTitle1);
    TextView textView2=(TextView) listItemView.findViewById(R.id.subTitle1);
    ImageView imageView=(ImageView) listItemView.findViewById(R.id.sportsImage1);

    Glide.with(mContext).load(news_item.getImage()).into(imageView);
    textView.setText(news_item.getHeading());
    textView2.setText(news_item.getBody());

    return listItemView;
}

}

A: Use app:cardUseCompatPadding="true" and you don't have to use RelativeLayout as parent. This will add enough space for card to keep shadow showing.


text:
Q: RewriteRule issue - modular php Bad Request What I'm ultimately looking to do is do /about instead of /main.php?p=about. I've seen a few posts (like this!) but none seem to work from me.
Firstly, I was putting the ReWrite rules in httpd.conf..is this correct?
Lots of places mention .htaccess but I didn't have that file in any directory that seems important (the only references are in phpMyAdmin). I copied the file from phpMyAdmin into htdocs and then replaced the text with a simple rule:
RewriteEngine on
RewriteRule home main.php [L]

However localhost/home reported a Bad Request.
So firstly which file should I use & if .htaccess where should I put the file & do I have to reference it in any other files? Secondly, is the following likely to work for my desired approach?
RewriteEngine on
RewriteRule ^([^/]+)/?  main.php?p=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

Thanks for any clarity & help.
Mike

A: You actually have conditions (RewriteCond) after RewriteRule. It should be other way round.
Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /main.php?p=$1 [L,QSA]

RewriteRule ^home/?$ main.php [L,NC]

Suggested Read: Apache mod_rewrite Introduction


text:
Q: SQL Statement : Update issue I have these three tables :
RESEARCHER(Re_Id, Re_Name, Re_Address, Re_Phone, Re_HomePhoneNumber,
Re_OfficeNumber, Re_FirstScore, Re_Second_Score)

PUBLICATION(Pub_ID, Pub_Title, Pub_Type, Pub_Publisher, Pub_Year,Pub_Country, Pub_StartingPage, Pub_Number_of_Page, Score1, Score2)

WRITTEN_BY(Re_Id, Pub_ID)

I want to change the authors of the publication "Introduction to Database System" to "Henry Gordon" and "Sarah Parker".
The problem is in WRITTEN_BY table,I just store the researcher's ID and publication's ID.
My idea is to change the Re_Id in WRITTEN_BY by those names are "Henry Gorgon" , "Sarah Parker" , which are already existed in RESEARCHER table
UPDATE WRITTEN_BY
SET Re_Id = ....( SELECT Re_Id
                  FROM RESEACHER
                  WHERE Re_Name = 'Henry Gordon' OR Re_Name = 'Sarah Paker' )
WHERE Pub_ID IN ( SELECT Pub_ID
                   FROM PUBLICATION
                   WHERE Pub_Name = 'Introduciton to Database system' );

I have problem in the SET part,so how to write the SQL statement for that requirement?
Here is the sqlfiddle link for my schema : http://sqlfiddle.com/#!9/b9118/1

A: I'd use something like below query:
DELETE FROM WRITTEN_BY WHERE Pub_ID IN (
SELECT Pub_ID FROM PUBLICATION
                   WHERE Pub_Title = 'Introduciton to Database system' )

INSERT INTO WRITTEN_BY
SELECT Re_Id,Pub_Id
FROM RESEARCHER CROSS JOIN PUBLICATION
WHERE Re_Name = 'Henry Gordon' OR Re_Name = 'Sarah Paker'
AND Pub_Title like 'Introduciton to Database system'

SELECT * FROM WRITTEN_BY

The idea is to first drop the existing mapping- you should not update it- and the insert a new one.
The reason for delete/insert approach vs update in case of mapping table is justified in favor of delete/insert as most mapping tables contain many-many mapping and usually one-to-many mappings.
Initially we may have a book mapped to say n number of authors where n <>1 then we either add extra rows, or are left with extraneous rows.
See sample fiddle: http://sqlfiddle.com/#!6/a0e72/13
The real deal however is CROSS JOIN. This does not take any ON  like other JOINs and is used to produce cartesian product type map.
We are restricting it to get only limited number of rows as per our need by adding suitable WHERE clauses


text:
Q: Killing thread in python I defined class A which has a method like this.
def func(self):
    while True:
        threading.Timer(0,self.func2, ["0"]).start()
        time.sleep(nseconds)
        threading.Timer(0,self.func2, ["1"]).start()
        time.sleep(nseconds)

If I define an instance of a this class in another script and run func method of this instance, how can I break while loop and stop these threads correctly? Do I need a ctrl-c signal handler in class A, if yes how? Note: I am also calling a system call by os.system function in func2 method of class A.  Problem is when I run main script file and try to stop  running of these threads, they do not stop.

A: There are myriads of ways to achieve what you want, one of the most straightforward ones would be using Events
from threading import Event

class Foo(object):

    def __init__(self):
        # the stop event is initially set to false, use .set() to set it true
        self.stop_event = Event()

    def func(self):
        while not self.stop_event.is_set():
           # your code

Meanwhile in some other thread (assuming the object your're talking about is obj):
obj.stop_event.set()

to finish the loop in the next iteration.


text:
Q: Export lambda function Pattern I am new to javascript and typescript. Export Lambda function below is a export lambda function.
export const paintBoard = ( ) => ((console.log()), (console.log()))

in the function body, it has console.log() separate by comma, i do not understand how this function works. what is function pattern called?
When this lambda paintBoard function is called, this two console.log() is called  simultaneously or in sequence.


text:
Q: Loading links from an XML file onto a UIWebView (SIGABRT error) I have been trying to parse an XML file in order to get articles from a website using background fetch.
Someone gave me an answer to this question here.
However, his answer resulted in an SIGABRT error.
Could someone please look at my code and see what my problem is? Thanks in advance.
My CODE:
NewsViewController.h (This file loads a uitableview that runs the background fetch to get the articles):
 #import <UIKit/UIKit.h>

 @interface NewsViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>

 @property (weak, nonatomic) IBOutlet UITableView *tblNews;

 - (IBAction)removeDataFile:(id)sender;

 -(void)fetchNewDataWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;

 @end

NewsViewController.m:
 #import "NewsViewController.h"
 #define NewsFeed @"http://www.teamfortress.com/rss.xml"
 #import "XMLParser.h"

 @interface NewsViewController ()

 @property (nonatomic, strong) UIRefreshControl *refreshControl;
 @property (nonatomic, strong) NSArray *arrNewsData;
 @property (nonatomic, strong) NSString *dataFilePath;
 -(void)refreshData;
 -(void)performNewFetchedDataActionsWithDataArray:(NSArray *)dataArray;

 @end

 @implementation NewsViewController

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 {
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     if (self) {
         // Custom initialization
     }
     return self;
 }

 - (void)viewDidLoad
 {
     [super viewDidLoad];
     // 1. Make self the delegate and datasource of the table view.
     [self.tblNews setDelegate:self];
     [self.tblNews setDataSource:self];

     // 2. Specify the data storage file path.
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *docDirectory = [paths objectAtIndex:0];
     self.dataFilePath = [docDirectory stringByAppendingPathComponent:@"newsdata"];

     // 3. Initialize the refresh control.
     self.refreshControl = [[UIRefreshControl alloc] init];

     [self.refreshControl addTarget:self
                        action:@selector(refreshData)
              forControlEvents:UIControlEventValueChanged];

     [self.tblNews addSubview:self.refreshControl];

     // 4. Load any saved data.
     if ([[NSFileManager defaultManager] fileExistsAtPath:self.dataFilePath]) {
         self.arrNewsData = [[NSMutableArray alloc] initWithContentsOfFile:self.dataFilePath];

         [self.tblNews reloadData];
     }

 }

 - (IBAction)removeDataFile:(id)sender {
     if ([[NSFileManager defaultManager] fileExistsAtPath:self.dataFilePath]) {
         [[NSFileManager defaultManager] removeItemAtPath:self.dataFilePath error:nil];

         self.arrNewsData = nil;

         [self.tblNews reloadData];
     }
 }

 -(void)refreshData{
     XMLParser *xmlParser = [[XMLParser alloc] initWithXMLURLString:NewsFeed];
     [xmlParser startParsingWithCompletionHandler:^(BOOL success, NSArray *dataArray, NSError *error) {

         if (success) {
             [self performNewFetchedDataActionsWithDataArray:dataArray];

             [self.refreshControl endRefreshing];
         }
         else{
             NSLog(@"%@", [error localizedDescription]);
         }
     }];
 }

 -(void)performNewFetchedDataActionsWithDataArray:(NSArray *)dataArray{
     // 1. Initialize the arrNewsData array with the parsed data array.
     if (self.arrNewsData != nil) {
         self.arrNewsData = nil;
     }
     self.arrNewsData = [[NSArray alloc] initWithArray:dataArray];

     // 2. Reload the table view.
     [self.tblNews reloadData];

     // 3. Save the data permanently to file.
     if (![self.arrNewsData writeToFile:self.dataFilePath atomically:YES]) {
         NSLog(@"Couldn't save data.");
     }
 }

 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
     return 1;
 }

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
     return self.arrNewsData.count;
 }

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
     UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:@"idCellNewsTitle"];

     if (cell == nil) {
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"idCellNewsTitle"];
     }

     NSDictionary *dict = [self.arrNewsData objectAtIndex:indexPath.row];

     cell.textLabel.text = [dict objectForKey:@"title"];
     cell.detailTextLabel.text = [dict objectForKey:@"pubDate"];

     return cell;
 }

 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     return 80.0;
 }

 - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{

 }

 - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

     if([segue.identifier isEqualToString:@"detail"]){

         DetailViewController *detail = segue.destinationViewController;
         NSIndexPath *indexPath = [self.tblNews indexPathForSelectedRow];
         detail.item = [self.arrNewsData objectAtIndex:indexPath.row];

     }
 }

 -(void)fetchNewDataWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
     XMLParser *xmlParser = [[XMLParser alloc] initWithXMLURLString:NewsFeed];
     [xmlParser startParsingWithCompletionHandler:^(BOOL success, NSArray *dataArray, NSError *error) {
         if (success) {
             NSDictionary *latestDataDict = [dataArray objectAtIndex:0];
             NSString *latestTitle = [latestDataDict objectForKey:@"title"];

             NSDictionary *existingDataDict = [self.arrNewsData objectAtIndex:0];
             NSString *existingTitle = [existingDataDict objectForKey:@"title"];

             if ([latestTitle isEqualToString:existingTitle]) {
                 completionHandler(UIBackgroundFetchResultNoData);

                 NSLog(@"No new data found.");
             }
             else{
                 [self performNewFetchedDataActionsWithDataArray:dataArray];

                 completionHandler(UIBackgroundFetchResultNewData);

                 NSLog(@"New data was fetched.");
             }
         }
         else{
             completionHandler(UIBackgroundFetchResultFailed);

             NSLog(@"Failed to fetch new data.");
         }
     }];
 }

 @end

XMLParser.h (This file parses the XML to get the title, date it was published, link, etc.)
#import <Foundation/Foundation.h>

@interface XMLParser : NSObject <NSXMLParserDelegate> {
NSMutableDictionary *item;
NSMutableString * currentLink;
}

@property (retain, nonatomic) NSMutableString *currentLink;

-(id)initWithXMLURLString:(NSString *)xmlUrlString;
-(void)startParsingWithCompletionHandler:(void(^)(BOOL success, NSArray *dataArray, NSError *error))completionHandler;

@end

XMLParser.m:
 #import "XMLParser.h"

 @interface XMLParser()

 @property (nonatomic, strong) NSXMLParser *xmlParser;

 @property (nonatomic, strong) NSOperationQueue *operationQueue;

 @property (nonatomic, strong) NSMutableArray *arrParsedData;

 @property (nonatomic, strong) NSString *currentElement;

 @property (nonatomic, strong) NSString *newsTitle;

 @property (nonatomic, strong) NSString *newsPubDate;

 @property (nonatomic, strong) NSString *newsLink;

 @property (nonatomic, strong) void (^completionHandler)(BOOL, NSArray *, NSError *);

 @property (nonatomic) BOOL isNewsItem;

 @property (nonatomic) BOOL allowedData;

 -(void)parse;
 -(void)endParsingWithError:(NSError *)error;

 @end

 @implementation XMLParser

 -(id)initWithXMLURLString:(NSString *)xmlUrlString{
     self = [super init];
     if (self) {
         self.xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:xmlUrlString]];

         self.xmlParser.delegate = self;

         self.operationQueue = [NSOperationQueue new];

         self.currentElement = @"";

         self.isNewsItem = NO;

         self.allowedData = NO;
     }

     return self;
 }

 #pragma mark - Public method implementation

 -(void)startParsingWithCompletionHandler:(void (^)(BOOL, NSArray *, NSError *))completionHandler{
     self.completionHandler = completionHandler;

     NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                         selector:@selector(parse)
                                                                          object:nil];
     [self.operationQueue addOperation:operation];
 }

 #pragma mark - Private method implementation

 -(void)parse{
     if (self.xmlParser != nil) {
         [self.xmlParser parse];
     }
 }

 -(void)endParsingWithError:(NSError *)error{
     BOOL success = (error == nil) ? YES : NO;

     self.completionHandler(success, self.arrParsedData, error);
 }

 #pragma mark - NSXMLParserDelegate method implementation

 -(void)parserDidStartDocument:(NSXMLParser *)parser{
     if (self.arrParsedData != nil) {
         [self.arrParsedData removeAllObjects];
         self.arrParsedData = nil;
     }

     self.arrParsedData = [[NSMutableArray alloc] init];
 }

 -(void)parserDidEndDocument:(NSXMLParser *)parser{
     [self performSelectorOnMainThread:@selector(endParsingWithError:) withObject:nil waitUntilDone:NO];
 }

 -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

     if ([elementName isEqualToString:@"item"]) {
     item = [[NSMutableDictionary alloc] init];
     self.currentLink = [[NSMutableString alloc] init];
     self.isNewsItem = YES;
 }

     if (self.isNewsItem) {
         if ([elementName isEqualToString:@"title"] ||
             [elementName isEqualToString:@"pubDate"] ||
             [elementName isEqualToString:@"link"]) {

             self.allowedData = YES;
         }
     }

     self.currentElement = elementName;
 }

 -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

     if ([elementName isEqualToString:@"item"]) {
         self.isNewsItem = NO;

         [item setObject:self.currentLink forKey:@"link"];

         NSDictionary *dict = @{@"title":    self.newsTitle,
                                @"pubDate":  self.newsPubDate,
                                @"link":     self.newsLink
                                };

         [self.arrParsedData addObject:dict];
     }

     if (self.isNewsItem) {
         if ([elementName isEqualToString:@"title"] ||
             [elementName isEqualToString:@"pubDate"] ||
             [elementName isEqualToString:@"link"]) {

             self.allowedData = NO;
         }
     }
 }

 -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
     if (self.allowedData) {
         if ([self.currentElement isEqualToString:@"title"]) {
             self.newsTitle = string;
         }
         else if ([self.currentElement isEqualToString:@"pubDate"]){
             self.newsPubDate = string;
         }
        else if ([self.currentElement isEqualToString:@"link"]){
             self.newsLink = string;
             [self.currentLink appendString:string];
        }
     }
 }

 -(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
     [self performSelectorOnMainThread:@selector(endParsingWithError:) withObject:parseError waitUntilDone:NO];
 }

 -(void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validationError{
     [self performSelectorOnMainThread:@selector(endParsingWithError:) withObject:validationError waitUntilDone:NO];
 }

 @end

DetailViewController.h (This is the file that encompasses a uiviewcontroller containing my UIWebView):
 #import <UIKit/UIKit.h>

 @interface DetailViewController : UIViewController<UIWebViewDelegate> {
     NSDictionary *item;
 }

 @property (retain, nonatomic) NSDictionary *item;
 @property (retain, nonatomic) IBOutlet UIWebView *itemSummary;

 @end

DetailViewController.m:
 #import "DetailViewController.h"

 @interface DetailViewController ()

 @end

 @implementation DetailViewController
 @synthesize item;
 @synthesize itemSummary = _itemSummary;

 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 {
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     if (self) {
         // Custom initialization
     }
     return self;
 }

 - (void)viewDidLoad
 {
     [super viewDidLoad];

     _itemSummary.delegate = self;
     _itemSummary.scalesPageToFit = YES;

     NSURL* url = [NSURL URLWithString:[item objectForKey:@"link"]];
     [_itemSummary loadRequest:[NSURLRequest requestWithURL:url]];
     // Do any additional setup after loading the view.
 }

 - (void)didReceiveMemoryWarning
 {
     [super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
 }

 /*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation  before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
     // Get the new view controller using [segue destinationViewController].
     // Pass the selected object to the new view controller.
 }
 */

 @end

If you would like to run the project yourself, you can find it on Github here
NOTE When using the link, the Xcode project is under "Your Guide to TF2".
Thanks to anyone that helps!
CRASH LOG
2014-04-08 16:33:05.611 Your Guide to TF2[499:70b] -[UINavigationController fetchNewDataWithCompletionHandler:]: unrecognized selector sent to instance 0x1090aa930
2014-04-08 16:33:05.755 Your Guide to TF2[499:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UINavigationController fetchNewDataWithCompletionHandler:]: unrecognized selector sent to instance 0x1090aa930'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010189a795 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x00000001015fd991 objc_exception_throw + 43
    2   CoreFoundation                      0x000000010192bbad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x000000010188c09d ___forwarding___ + 973
    4   CoreFoundation                      0x000000010188bc48 _CF_forwarding_prep_0 + 120
    5   Your Guide to TF2                   0x0000000100004819 -[AppDelegate application:performFetchWithCompletionHandler:] + 345
    6   UIKit                               0x000000010026e0b5 -[UIApplication _handleOpportunisticFetchWithSequenceNumber:] + 170
    7   UIKit                               0x000000010025b200 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1761
    8   UIKit                               0x000000010025ebe8 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 660
    9   UIKit                               0x000000010026faab -[UIApplication handleEvent:withNewEvent:] + 3092
    10  UIKit                               0x000000010026ff1e -[UIApplication sendEvent:] + 79
    11  UIKit                               0x00000001002602be _UIApplicationHandleEvent + 618
    12  GraphicsServices                    0x00000001039a2bb6 _PurpleEventCallback + 762
    13  GraphicsServices                    0x00000001039a267d PurpleEventCallback + 35
    14  CoreFoundation                      0x000000010181c819 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
    15  CoreFoundation                      0x000000010181c5ee __CFRunLoopDoSource1 + 478
    16  CoreFoundation                      0x0000000101845ab3 __CFRunLoopRun + 1939
    17  CoreFoundation                      0x0000000101844f33 CFRunLoopRunSpecific + 467
    18  UIKit                               0x000000010025e4bd -[UIApplication _run] + 609
    19  UIKit                               0x0000000100260043 UIApplicationMain + 1010
    20  Your Guide to TF2                   0x0000000100004ce3 main + 115
    21  libdyld.dylib                       0x0000000101f295fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

AppDelegate.m
 #import "AppDelegate.h"
 #import "NewsViewController.h"
 #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue &  0xFF))/255.0 alpha:1.0]

 @implementation AppDelegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
     [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
     // Override point for customization after application launch.
     // Uncomment to change the background color of navigation bar
     [[UINavigationBar appearance] setBarTintColor:UIColorFromRGB(0xb35326)];

     // Uncomment to change the color of back button
     //[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

     // Uncomment to assign a custom backgroung image
     //[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"tf2_logo.png"] forBarMetrics:UIBarMetricsDefault];

     // Uncomment to change the back indicator image
     /*
      [[UINavigationBar appearance] setBackIndicatorImage:[UIImage imageNamed:@"back_btn.png"]];
      [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"back_btn.png"]];
      */

     // Uncomment to change the font style of the title
     /*
      NSShadow *shadow = [[NSShadow alloc] init];
 shadow.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
      shadow.shadowOffset = CGSizeMake(0, 1);
      [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
      [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], NSForegroundColorAttributeName,
 shadow, NSShadowAttributeName,
      [UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:21.0], NSFontAttributeName, nil]];
      */

     return YES;
 }

 -(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
     NSDate *fetchStart = [NSDate date];

NewsViewController *viewController = (NewsViewController *)self.window.rootViewController;

[viewController fetchNewDataWithCompletionHandler:^(UIBackgroundFetchResult result) {
    completionHandler(result);

    NSDate *fetchEnd = [NSDate date];
    NSTimeInterval timeElapsed = [fetchEnd timeIntervalSinceDate:fetchStart];
    NSLog(@"Background Fetch Duration: %f seconds", timeElapsed);

     }];
 }

A: The problem is in your -[AppDelegate application:performFetchWithCompletionHandler:]
This line is wrong:
NewsViewController *viewController = (NewsViewController *)self.window.rootViewController;

The root view controller is a UINavigationController, but you're assuming it is a NewsViewController.  That should be:
UINavigationController *navController = (UINavigationController *)self.window.rootViewController;
NewsViewController *viewController = (NewsViewController *)[[navController viewControllers] objectAtIndex:0];

A: Ok.. looked at your code again.
A couple of things that are missing.
In your NewsViewController.h
@interface NewsViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>{
    NSArray *items;
    NSMutableArray *itemArray;
}

Need to include the Array and MutableArray
Also add the properties in NewsViewController.h
@property (retain, nonatomic) NSArray *items;
@property (retain, nonatomic) NSMutableArray *itemArray;

In your implementation file.
@synthesize items, itemArray;

In your XMLParser implementation
@synthesize currentLink;

Finally on your storyboard, you have the segue coming from the view controller instead of the cell row.
Delete your current segue and add another one coming from the cell to the DetailViewController view.
I pushed the changes as well.


text:
Q: Form closing when gecko browser shows popup I'm using GeckoFx-Windows-22.0-0.7 and when I click something a popup with yes and no options is shown. My form closes without triggering FormClosing or FormClosed event. How can I solve this ?
It closes always before 3. popup.
I solved, Adding this code GeckoWebBrowser.UseCustomPrompt(); before Gecko.Xpcom.Initialize is solved my problem.
Thanks

A: Adding this code  GeckoWebBrowser.UseCustomPrompt(); before
            Gecko.Xpcom.Initialize is solved my problem.


text:
Q: Why won't my cleaning script delete specified files? I am making a batch script that will automatically delete junk files from windows. With the exception of files that will be in use, the script won't delete files in some locations like %WinDir%\Logs. Here is the script I have so far:
@ECHO OFF
Color 1F
TITLE Windows Cleaner
ECHO.
:choice
set /P c=Do you want to run Windows Cleaner? Enter Y to run or C to cancel.
if /I "%c%" EQU "Y" goto :choice_yes
if /I "%c%" EQU "C" goto :choice_cancel
goto :choice
:choice_yes
for %%a in ("%TEMP%") do rd /s /q "%%~a"
for %%a in ("%AppData%\Microsoft\Windows\Cookies") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\CrashDumps") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\Microsoft\Feeds Cache") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\Microsoft\Internet Explorer\DOMStore") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\Microsoft\Windows\Caches") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\Microsoft\Windows\Explorer") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\Microsoft\Windows\History") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\Microsoft\Windows\INetCache\IE") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\Microsoft\Windows\INetCache\Low\IE") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\Microsoft\Windows\INetCache\Virtualized") do rd /s /q "%%~a"
for %%a in ("%LocalAppData%\Microsoft\Windows\INetCookies") do rd /s /q "%%~a"
takeown /F "%WinDir%\Log"* /R /A
icacls "%WinDir%\Log"*.* /T /grant administrators:Fy
for %%a in (%WinDir%\Log") do rd /s /q "%%~a"
takeown /F "%WinDir%\Logs"* /R /A
icacls "%WinDir%\Logs"*.* /T /grant administrators:Fy
for %%a in (%WinDir%\Logs") do rd /s /q "%%~a"
takeown /F "%WinDir%\Temp"* /R /A
icacls "%WinDir%\Temp"*.* /T /grant administrators:Fy
for %%a in ("%WinDir%\Temp") do rd /s /q "%%~a"
:choice_cancel
echo Cleaning has been cancelled.
pause
exit
@ECHO OFF

If I understand correctly, I need to use takeown on system files and folders before my script can remove their contents. I am also running the script with elevated privileges. What a I missing here?

A: Your batch file's syntax is incorrect.  Consider the following lines:
for %%a in (%WinDir%\Log") do rd /s /q "%%~a"
...
for %%a in (%WinDir%\Logs") do rd /s /q "%%~a"

On both of these lines you're missing the double quote before %WinDir%. The correct syntax is:
for %%a in ("%WinDir%\Log") do rd /s /q "%%~a"
...
for %%a in ("%WinDir%\Logs") do rd /s /q "%%~a"

Because by default the Administrators group has full access to the Logs folder, it's unnecessary to take ownership of it before attempting to delete the files it contains.
As a side note, the directory %WinDir%\Log is a non-standard directory.


text:
Q: Hibernate Batch insert/update constraintviolationexception I'm writing a program to run a batch process over hundreds of thousands of entities of a few related types.  I was originally doing this with a single transaction per persist.  This seemed very slow, so I tried doing somewhat naive batch updates in the way described in http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html, with longer transactions and occasional flush+clears.  I'm running into a ConstraintViolationException for some of my entity types, because I have unique field constraints.  However, I'm unsure of how to check for existing instances; I currently have a criteria to list collisions, but it seems to not return entities that I have saveOrUpdated within the same transaction.
A made-up example may help:
entities Family, Person, Name
Family has many Persons (One to Many)
Persons have many names, different Persons can have the same Name. (Many to Many)
My updates include persisting a Family along with its Persons and Names, but I'm not sure how to dedupe Names (may collide with existing Name in db or another Name in the same update batch).  I could just keep track of new entities' unique constraint fields outside of hibernate, but I thought this is probably not necessary.  Is there any built-in way of checking for duplicates both in the db and uncommitted changes?  I saw Hibernate batch updates with constraintviolationexception, but I do not savor using exceptions in the normal codepath.  Thanks, I appreciate any guidance.

A: Short answer: no. For batch operations, Hibernate doesn't keeps track of the generated ids, so, you'd have to go to the database for each Name, as you'd do a query based on the name, not on the ID, unless you are using some query cache (which would be tricky for your case, I suppose).
What I would suggest is to do this in a two-step (three?) process: first, batch-insert all Name objects. Then, load them all using Hibernate itself, storing them on a Map. Then, just persist the other data, linking the Name to the non-persisted Person. Of course, you'd need as much memory as you have names :-)  But why are you keeping Name as a separate entity, anyway?


text:
Q: Can multiple subnets reach each other connecting to a central IPsec VPN? Say you have three networks, networks A, B, and C.
-A is an ipsec VPN server
-B is connected to A through ipsec
-C is connected to A through ipsec
Can network B access network C?

A: Depends on the traffic selectors negotiated via IKEv2 and the resulting IPsec policies.
For B to access network C it has to propose that subnet (or multiple if necessary) as remote traffic selector, A will negotiate it as its local traffic selector for this connection.  The same goes for C, which needs access to subnet B.
Or they could both propose e.g. 0.0.0.0/0 as remote traffic selector, which A could then narrow to all the necessary subnets behind other clients via its local traffic selector.


text:
Q: @import sass en Gulp.js estoy intentando que compilen los archivos sass en un archivo principal que contiene todos los @import pero no logro hacer que funcione. Mi código es:
gulpfile.js:
//Cargar módulos
var gulp = require('gulp'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    notify = require("gulp-notify"),
    browserSync = require('browser-sync').create(),
    browserSync = require('browser-sync'),
    sass = require('gulp-sass'),
    //sassImport    = require('gulp-sass-import'),
    autoprefixer = require('gulp-autoprefixer'),
    sourcemaps = require('gulp-sourcemaps'),
    imagemin = require('gulp-imagemin'),
    connect = require('gulp-connect-php');

//browsersync sass
gulp.task('serve', ['sass'], function() {
    browserSync.init({
        proxy: "localhost"
    });
});

//browsersync php
gulp.task('connect', function() {
    connect.server({}, function() {
        browserSync({
            proxy: 'localhost'
        });
    });
});

//estilos css
gulp.task('sass', function(done) {
    return gulp.src('./src/scss/*.scss')
        .pipe(sourcemaps.init())
        /*.pipe(sassImport({
            filename : '_file',
            marker : '/*'
        }))*/
        .pipe(sass.sync()).on('error', notify.onError(function(error) {
            return 'Error al compilar sass.\n Detalles en la consola.\n' +
                error;
        }))
        .pipe(sass({
            outputStyle: 'compressed'
        }))
        .pipe(autoprefixer({
            browsers: ['last 3 versions'],
            cascade: false
        }))
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest("./dist/css/"))
        .pipe(notify({
            title: "SASS",
            message: "OK: Archivo compilado"
        }))
        .pipe(browserSync.stream());
});

//Procesar scripts
gulp.task('scripts', function() {
    return gulp.src('./src/js/*.js')
        .pipe(concat('all.js'))
        .pipe(uglify())
        .pipe(gulp.dest('./dist/js/'));
});

//Minificar imágenes
gulp.task('image', function() {
    return gulp.src('./src/images/**/*')
        .pipe(imagemin({
            interlaced: true,
            progressive: true,
            optimizationLevel: 5,
            svgoPlugins: [{
                removeViewBox: true
            }]
        }))
        .pipe(gulp.dest('./dist/images/'));
});

//Tarea por default
gulp.task('watch', function() {
    gulp.watch('./src/scss/*.scss', ['sass']); //Vigila cambios en los
    estilos
    gulp.watch("./*.php").on("change", browserSync.reload);
    gulp.watch('./src/js/*.js', ['scripts']);
    gulp.watch('./src/images/**/*', ['image']);
    //gulp.watch('**/*.php').on('change', function () {
    //   browserSync.reload();
    //});
});

//Default task
gulp.task('default', ['serve', 'sass', 'scripts', 'image', 'connect',
    'watch'
]);

main.scss(el que importa los archivos sass):
    // BASE
    @import 'base/_reset.scss';
@import 'base/_typography.scss';

//VENDORS (librerías externas)
@import 'vendors/_fontawesome.scss';

//UTILIDADES (variables, funciones, mixins,...)
@import 'utils/_variables.scss';
@import 'utils/_functions.scss';
@import 'utils/_mixins.scss';
//@import 'utils/_helpers.scss';

//COMPONENTES (botones, tablas, carrusel,..)
@import 'components/_buttons.scss';
//@import 'components/_dropdown.scss';
//@import 'components/_tables.scss';

//LAYOUT (elementos estructurales)
@import 'layout/_header.scss';
@import 'layout/_footer.scss';
//@import 'layout/_navigation.scss';
//@import 'layout/_sidebar.scss';
@import 'layout/_forms.scss';
@import 'layout/_grid.scss';

//PAGES (estilos específicos para algunas páginas: home, contacto,...)
//@import 'pages/_home.scss';
//@import 'pages/_contact.scss';

//TEMAS (si se utilizan... por defecto, administrador,..)
//@import 'themes/_theme.scss';
//@import 'themes/_admin.scss';

A: Nada, ya está arreglado. Era la ruta de los archivos css en el gulpfile.js que apuntaba al archivo que importa, main.scss, en vez de al resto  de archivos.


text:
Q: Java - remove strings from an ArrayList that contains the specified Sometimes, due to faulty data collected, a line generated by the following method ends up looking like this when saved: ",-1,0" or something similar, with no name, an ID of -1 and a level of 115 or something else. (The lines are formatted like this (excluding quotes): "name,id,level" (e.g: "Honour guard,5514,115")
What i need to do is to remove all strings in monstersToAdd that contains -1.
I've tried this, but with no success:
private void combineInfo() {
    for(int i = 0; i < monsterList.size(); i++){
        monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
    }
    monstersToAdd.remove(monstersToAdd.contains("-1"));
}

with the line monstersToAdd.remove(monstersToAdd.contains("-1")); I was trying to remove all strings in monstersToAdd that contains "-1". This however does not work, probably for good reasons, which I unfortunately don't know of yet.
I would really appreciate any input :).

A: You would be better off not adding the lines you don't want in the first place.
for (....) {
  if (IDs[i] != -1) {
    // add it
  }
  // else it simply doesn't get added
}

More on your original code: You could post a little more detail, such as the type of monsterToAdd. If it is a non-generic list, then the contains method just returns true or false depending if the parameter (here a string of "-1") is present in the list exactly as you pass it, that is it doesn't search for substring matches of the list elements.
remove then tries to remove the element you ask to remove, which may be a Boolean object, automatically boxed from the boolean primitive value returned by contains.
Also, it is suspicious that you have a variable called monsterList which you use for iteration length, but not actually use any elements from that list. Maybe the arrays you use have the same values as the list, and were copied out beforehand? If so, it would be nicer to iterate on the monsterList directly and use its elements.

A: Why don't you do this instead:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
    if(IDs[i] != -1){
        monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
    }
}
monstersToAdd.remove(monstersToAdd.contains("-1"));

}
That way, you never add the monster to the list in the first place, if the ID is -1.

A: Its easier if you dont even add them, than adding and removing them so check the sanity of ID names and levels before adding them
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
    //add only if name is non empty, ID is not negative and level is below 100
    if(!(names[i].isEmpty() || IDs[i]<0 || levels[i]>100))
    monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}

A: You are really close:
private void combineInfo() {
    for(int i = 0; i < monsterList.size(); i++){
        if (IDs[i] == -1) continue; // Skip this iteration
        monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
    }
}

Filter them out as early as possible rather than back-tracking and removing them.

A: contains() returns only a true/false result depending on whether the list contains the given input object (in your case the string "-1"). So in your example, your list wouldn't contain "-1", so your remove statement would be resolved to this:
monstersToAdd.remove(false);

which wouldn't work for obvious reasons.

A: Here is the code:
for(Iterator<String> it = monsterList; it.hasNext();) {
    String elem = it.next();
    if (elem.contains("-1")) {
         it.remove();
    }
}

contains() method of collection returns true if collection contains element equals to one passed as an argument. In you case you want to use String's contains() that returns true if the string contains specified substring. This is the reason that you need loop.
This loop must be implemented with iterator. Using new java 5 syntax for(String elem : list) will not work here because you have to remove element. Using for(int i = 0; i < list.size(); i++) requires implementation of logic that safely moves to the next index after element removal.
And the last point. You have to use iterator.remove() instead of Collection.remove() to avoid ConcurrentModificationException


text:
Q: How do you read a integer and a string seperatly from a single line in file and store them to variables? I have a text file that looks something like this:
1 Song one
2 Song two
3 Song three
...

How do I read a line by line and extract number and String separately from a single line, and let's say print them to the console with:
String title; // extracted from current line
int num; // extracted from current line
System.out.println("Number: " + num + "Title: " + title);

A:
How do I read a line by line

Use a BufferedReader and its readLine() method.

How do I extract number and String separately

Use line.indexOf(' ') then substring(...) to get the 2 parts.
Then use Integer.parseInt(...) on the first part to get number.


text:
Q: Create unformatted partition from unallocated disk space The parted output is as below:
$> parted /dev/sda print free
Model: ATA Hitachi HUA72302 (scsi)
Disk /dev/sda: 2000GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:

Number  Start   End     Size    Type     File system  Flags
        32.3kB  1049kB  1016kB           Free Space
 1      1049kB  33.6GB  33.6GB  primary               raid
 2      33.6GB  67.1GB  33.6GB  primary               raid
 3      67.1GB  67.7GB  524MB   primary  ext4         boot, raid
        67.7GB  2000GB  1933GB           Free Space

What would be the steps on CentOS 7.1 to create an empty, non-formatted partition on those free 1933GB? (using terminal tools only)

A: I'll put an answer here since I've figured it out.
First I query the disk layout using command similar to above but request sectors a units:
> parted /dev/sda unit s print free
Model: ATA Hitachi HUA72302 (scsi)
Disk /dev/sda: 3907029168s
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:

Number  Start       End          Size         Type     File system  Flags
        63s         2047s        1985s                 Free Space
 1      2048s       65570815s    65568768s    primary               raid
 2      65570816s   66594815s    1024000s     primary  ext4         boot, raid
 3      66594816s   132163583s   65568768s    primary               raid
 4      132163584s  3907029167s  3774865584s  primary

note 132163584s, the starting sector of the free space (previous partition end +1, if you don't use free switch). Then the rest is as simple as:
parted /dev/sda mkpart primary ext4 132163584s -- -1s

-1s is the ending sector being the end of disk. -- is to use -1s in batch mode and prevent parted: invalid option -- '1' error (running parted in interactive mode doesn't need this).

A: Just to add another way (using fdisk command) to create a partition out of unallocated space. fdisk is available across several Linux distros, at least Centos, Ubuntu and Debian have this command.
IMPORTANT NOTE: before executing the following commands, make sure you identify the disk you want to work with, in my case it is /dev/sda but yours could be different. Using the wrong disk can break your disk and data.
First, check where there is the unallocated space on your disk.
sudo parted /dev/sda unit s print free

The output is shown in the picture below, where we can see that there is a 2GB (aprox.) unallocated space. The unallocated space corresponds to the line which has "Free Space" under the file system column.

Then, run fdisk in interactive mode.
sudo fdisk /dev/sda

Afterfdisk is running, go through the following steps:

*

*Type n for creating a new partition.

*Type p for a primary partition (this is my case, yours can be a different one).

*Type the value of the first sector of your partition (you can get this value from the "Start" column of the sudo parted /dev/sda unit s print free command, i.e. from the previous picture). In my case this would be the value 308582400 (the trailing s is not needed)

*Type the value of the final sector of your partition (analogous to the previous step, you can get this value from the "End" column of the sudo parted /dev/sda unit s print free command, i.e. from the previous picture). In my case this would be the value 312581807 (again, the trailing s is not needed)

*Type w to write the changes to disk

After this, you will have to reboot your system or run the sudo partprobe command to make the partition changes available for the kernel.
You can end at this point and you will have your partition created. In the case that you want to tag your partition because it will have a specific use, e.g. a swap partition, you can follow the steps below before typing the w letter into fdisk command (i.e. before writing changes to disk, i.e. this means that the steps below substitute to the previous step "Type w to write...").

*

*Type t for tagging the newly created partition

*Type the number of the partition to be tagged, the one that we just created, in my case it would be 3 (fdisk command will inform you the number assigned to the newly created partition)

*Type the partition type (82 in my case for a swap partition, but you can type L to list all the types and select the type that suits you)

*Type w to write the changes to disk

Below is a screenshot that shows all the previous steps executed and the output.

The final result, after creating the new partition is shown below. You can see yours by executing the following command
sudo fdisk -l /dev/sda


text:
Q: cvc-complex-type.2.4.a: Invalid content was found starting with element 'beans:bean'
One of '{"http://www.springframework.org/schema/beans":meta, "h
      ttp://www.springframework.org/schema/beans":constructor-arg, "http://www.springframework.org/schema/beans":property, "http://www.springframework.org/schema/beans":qualifier, "http://www.springframework.or
      g/schema/beans":lookup-method, "http://www.springframework.org/schema/beans":replaced-method, WC[##other:"http://www.springframework.org/schema/beans"]}' is expected.

Tomcat is showing me above error
My spring-servlet.xml is given below. I am using .3.11.RELEASE version of springframework.
<?xml version="1.0" encoding="UTF-8"?>
<beans:bean xmlns="http://www.springframework.org/schema/mvc"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:context="http://www.springframework.org/schema/context"
            xmlns:beans="http://www.springframework.org/schema/beans"
            xsi:schemaLocation="
              http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
              http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-4.3.xsd
              http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

    <context:component-scan base-package="in.project.*" />

    <annotation-driven/>

    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/views/"/>
        <beans:property name="suffix" value=".jsp"/>
    </beans:bean>

</beans:bean>

A: The root entity of the xml application context is <beans>, not <bean>.
So you might end up with
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
...
</beans:beans>

Haven't tested is but should work. Hope that helps.


text:
Q: Aggregate vs non-aggregate structs/classes I am trying to understand what an aggregate class/struct/union is: Here is from the C++ standard:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

So I've written this for testing:
struct NonAggregate{
    virtual void f()const&{} // virtual member function makes the struct non-aggregate
};

struct Bar{}; // aggregate
struct X{}; // aggregate

struct Foo : Bar, X{
   // Foo() = default; // if un-comment out makes Foo non-aggregate
   Foo& operator =(Foo const&){return *this;} // ok
   ~Foo(){} // ok
   int x_ = 0; // has an initializer. ? still aggregate?
   Bar b_{}; // has an initializer. still aggregate?

private:
    static double constexpr pi_ = 3.14;
};

double constexpr Foo::pi_; // definition needed- (although it has an in-class intializer) if Foo::pi_ used outside of the class

int main(){

    std::cout << std::boolalpha << "Foo is an aggregate type: " << std::is_aggregate<Foo>::value << '\n';

}

The output is:
Foo is an aggregate type: true

*

*So why If I default the synthesized default constructor Foo is no more an Aggregate? As long as I've not provided a user-defined one?

*Also the standard says: no base classes (Clause 10) but my struct inherits multiply from two aggregate structs Bar and X but still n Aggregate??!

*The standard says: no brace-or-equal-initializers for non-static data members (9.2) but I have initializers for non-static data members x_ and b_ but the compiler still consider Foo as an aggregate struct?? Thank you!
*P.S: I've used GCC and C++2a standard

A: The rules for what is and what is not an aggregate has changed a lot over various standard versions. This answer briefly highlights the changes related with OP's three questions. For a more thorough passage, see e.g. The fickle aggregate, which walks through these different rules along with the correct standard (version) references.

So why If I default the synthesized default constructor Foo is no more an Aggregate? As long as I've not provided a user-defined one?

In C++11 through C++17, the requirement reads "no user-provided" constructors, which still allows declaring constructors as long as they are defined as explicitly-defaulted or explicitly-deleted on their first declaration.
// Aggregate in C++11 through C++17. Not an aggregate in C++20.
struct A {
    A() = default;  // user-declared, but not user-provided
};

// Aggregate in C++11 through C++17. Not an aggregate in C++20.
struct B {
    B() = delete;  // user-declared, but not user-provided
};

// Never an aggregate.
struct C {
    C();  // user-declared & user-provided
};
C::C() = default;

As of C++20, this requirement was made more strict to "no user-declared constructors".

Also the standard says: no base classes (Clause 10) but my struct inherits multiply from two aggregate structs Bar and X but still n Aggregate??!

This was the rule in C++11 and C++14. As of C++17 an onwards, it's more lenient:

1.4) no virtual, private, or protected base classes ([class.mi]).

The standard says: no brace-or-equal-initializers for non-static data members (9.2) but I have initializers for non-static data members x_ and b_ but the compiler still consider Foo as an aggregate struct?? Thank you!

This rule was removed in C++14.