问:
AmCharts Value axis not starting at Zero
I have a AmCharts serial chart with some columns representing numeric values. Depending on those values, sometimes one of the axes "unsticks" from the ground,  making a weird effect. I have unsuccessfully tried to set the property valueAxis.minimum to zero.

Is there a way to force a valueAxis to start from zero?

```<code>    AmCharts.makeChart("chartdiv", {
        "type": "serial",
        "synchronizeGrid": true,
        "valueAxes":
            [{
                "minimum": 0,
                // ...
            }]
        // ...
    });
</code>```

答:
Sometimes AmCharts doesn't respect the minimum you set, depending on your data and other factors. You can try to force it by setting strictMinMax to true for each valueAxis where you want your minimum enforced (of course, you have to make sure you're setting minimum in each value axis).

```<code>AmCharts.makeChart("chartdiv", {
    "type": "serial",
    //"synchronizeGrid": true,
    "valueAxes":
        [{
            "minimum": 0,
            "strictMinMax": true,
            // ...
        },
         //repeat if you have multiple value axes that need to start from 0
        ]
    // ...
});
</code>```

Note that if you're using the synchronizeGrid feature mentioned at the bottom of this example, then you have to disable it or else it won't respect your min/max values at all.

Body:
I have a AmCharts serial chart with some columns representing numeric values. Depending on those values, sometimes one of the axes "unsticks" from the ground,  making a weird effect. I have unsuccessfully tried to set the property valueAxis.minimum to zero.

Is there a way to force a valueAxis to start from zero?

    AmCharts.makeChart("chartdiv", {
        "type": "serial",
        "synchronizeGrid": true,
        "valueAxes":
            [{
                "minimum": 0,
                // ...
            }]
        // ...
    });

Body:
Sometimes AmCharts doesn't respect the minimum you set, depending on your data and other factors. You can try to force it by setting strictMinMax to true for each valueAxis where you want your minimum enforced (of course, you have to make sure you're setting minimum in each value axis).

AmCharts.makeChart("chartdiv", {
    "type": "serial",
    //"synchronizeGrid": true,
    "valueAxes":
        [{
            "minimum": 0,
            "strictMinMax": true,
            // ...
        },
         //repeat if you have multiple value axes that need to start from 0
        ]
    // ...
});

Note that if you're using the synchronizeGrid feature mentioned at the bottom of this example, then you have to disable it or else it won't respect your min/max values at all.


来源: stackexchange

问:
Angular4 Web Worker application not displaying
I have a website that is heavy on CPU usage that I decide to port to web workers.

I have followed this step by step tutorial: https://medium.com/@enriqueoriol/angular-with-web-workers-step-by-step-dc11d5872135

I have cloned this rep and made it seem identical: https://github.com/kaikcreator/angular-cli-web-worker

I encountered a few issues where the document was not defined or the window. In these cases I tested on the github rep if its a problem with or with the module and it was the module so I removed them.

Basically I have no error right now and the page simply doesn't display:

I assume it is because Angular has no way to access the window object so it can't inject the code.

My app.module complained about lacking platform location providers so I added:

```<code>import { WORKER_APP_LOCATION_PROVIDERS } from '@angular/platform-webworker';
</code>```

while replacing the BrowserModule with the WorkerAppModule

Here is my main.ts

```<code>import { enableProdMode } from '@angular/core';
import { bootstrapWorkerUi } from '@angular/platform-webworker';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

bootstrapWorkerUi('webworker.bundle.js');
</code>```

My workerLoader.ts

```<code>import 'polyfills.ts';
import '@angular/core';
import '@angular/common';

import { platformWorkerAppDynamic } from '@angular/platform-webworker-dynamic';
import { AppModule } from './app/app.module';

platformWorkerAppDynamic().bootstrapModule(AppModule);
</code>```

My webpack config is: https://gist.github.com/misha130/9a21e1c08ca9e0bf79635dedc3279b2d

What could be the problem that stops it from rendering the page?

EDIT: After investigation this caused the problem and the usage of the router module causes the problem for me. How do I use PlatformLocations and RouterModule and Web Workers?

答:
I was also referencing the Angular with Web Workers: Step by Step post on Medium (as did the OP). One of the comments on that post mentioned including WORKER_UI_LOCATION_PROVIDERS and WORKER_APP_LOCATION_PROVIDERS into your application.

In your main.ts, add WORKER_UI_LOCATION_PROVIDERS as the second argument of bootstrapWorkerUi()

```<code>...
import {
  bootstrapWorkerUi,
  WORKER_UI_LOCATION_PROVIDERS
} from '@angular/platform-webworker'
...

bootstrapWorkerUi('webworker.bundle.js', WORKER_UI_LOCATION_PROVIDERS);
</code>```

In your AppModule, add WORKER_APP_LOCATION_PROVIDERS. I also needed to provide a value for base href (which I've included below)

```<code>...
import {
  WorkerAppModule,
  WORKER_APP_LOCATION_PROVIDERS
} from '@angular/platform-webworker';
import { APP_BASE_HREF } from '@angular/common'
...

@NgModule({
  ...
  imports: [
    ...
    WorkerAppModule,
    ...
  ],
  ...
  providers: [
    ...
    {
      provide: APP_BASE_HREF,
      useValue: '/'
    },
    WORKER_APP_LOCATION_PROVIDERS
    ...
  ],
  ...
})
</code>```

That should get you past your PlatformLocation provider problem, and maybe even your future base href problem.

Good luck!

ContentLicense: CC BY-SA 3.0

Body:
I have a website that is heavy on CPU usage that I decide to port to web workers.

I have followed this step by step tutorial: https://medium.com/@enriqueoriol/angular-with-web-workers-step-by-step-dc11d5872135

I have cloned this rep and made it seem identical: https://github.com/kaikcreator/angular-cli-web-worker

I encountered a few issues where the document was not defined or the window. In these cases I tested on the github rep if its a problem with or with the module and it was the module so I removed them.

Basically I have no error right now and the page simply doesn't display:

I assume it is because Angular has no way to access the window object so it can't inject the code.

My app.module complained about lacking platform location providers so I added:

import { WORKER_APP_LOCATION_PROVIDERS } from '@angular/platform-webworker';

while replacing the BrowserModule with the WorkerAppModule

Here is my main.ts

import { enableProdMode } from '@angular/core';
import { bootstrapWorkerUi } from '@angular/platform-webworker';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

bootstrapWorkerUi('webworker.bundle.js');

My workerLoader.ts

import 'polyfills.ts';
import '@angular/core';
import '@angular/common';

import { platformWorkerAppDynamic } from '@angular/platform-webworker-dynamic';
import { AppModule } from './app/app.module';

platformWorkerAppDynamic().bootstrapModule(AppModule);

My webpack config is: https://gist.github.com/misha130/9a21e1c08ca9e0bf79635dedc3279b2d

What could be the problem that stops it from rendering the page?

EDIT: After investigation this caused the problem and the usage of the router module causes the problem for me. How do I use PlatformLocations and RouterModule and Web Workers?

Body:
I was also referencing the Angular with Web Workers: Step by Step post on Medium (as did the OP). One of the comments on that post mentioned including WORKER_UI_LOCATION_PROVIDERS and WORKER_APP_LOCATION_PROVIDERS into your application.

In your main.ts, add WORKER_UI_LOCATION_PROVIDERS as the second argument of bootstrapWorkerUi()

...
import {
  bootstrapWorkerUi,
  WORKER_UI_LOCATION_PROVIDERS
} from '@angular/platform-webworker'
...

bootstrapWorkerUi('webworker.bundle.js', WORKER_UI_LOCATION_PROVIDERS);

In your AppModule, add WORKER_APP_LOCATION_PROVIDERS. I also needed to provide a value for base href (which I've included below)

...
import {
  WorkerAppModule,
  WORKER_APP_LOCATION_PROVIDERS
} from '@angular/platform-webworker';
import { APP_BASE_HREF } from '@angular/common'
...

@NgModule({
  ...
  imports: [
    ...
    WorkerAppModule,
    ...
  ],
  ...
  providers: [
    ...
    {
      provide: APP_BASE_HREF,
      useValue: '/'
    },
    WORKER_APP_LOCATION_PROVIDERS
    ...
  ],
  ...
})

That should get you past your PlatformLocation provider problem, and maybe even your future base href problem.

Good luck!


问:
Get index of character in UILabel from tap
I'd like to get the index for the tapped character on a UILabel.  I've subclassed a UILabel.  In my awakeFromNib() I have this:

```<code>    layoutManager = NSLayoutManager()
    textStorage = NSTextStorage(attributedString: self.attributedText)
    textStorage.addLayoutManager(layoutManager)

    textContainer = NSTextContainer(size: CGSizeMake(self.frame.size.width, self.frame.size.height))
    textContainer.lineFragmentPadding = 0
    textContainer.maximumNumberOfLines = self.numberOfLines
    textContainer.lineBreakMode = self.lineBreakMode
    textContainer.size = self.frame.size

    layoutManager.addTextContainer(textContainer)
</code>```

It is working how I want it to for the first 5 characters of the label, as in I tap the first character and in my touchesEnded I get an index of 0:

var touchedCharacterIndex = layoutManager.characterIndexForPoint(touch.locationInView(self), inTextContainer: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

But when I tap anywhere past the first four characters of the UILabel, I get either 4 or 0, which is incorrect.

Thanks,

Update

From a suggestion in the comments, I've added this:

```<code> func updateTextStorage() {
    if let attributedText = self.attributedText {
        textStorage = NSTextStorage(attributedString: attributedText)
    }
    textStorage?.addLayoutManager(layoutManager)

    textContainer = NSTextContainer(size: CGSizeMake(self.frame.size.width, self.frame.size.height))
    textContainer?.lineFragmentPadding = 7
    textContainer?.maximumNumberOfLines = self.numberOfLines
    textContainer?.lineBreakMode = self.lineBreakMode
    textContainer?.size = self.bounds.size

    layoutManager.addTextContainer(textContainer!)
    layoutManager.textStorage = textStorage
}
</code>```

I call this in layoutSubviews(), awakFromNib and the setters of bounds, frame, attributedText and text.

And it is now giving me some weird indexes, like if text length is 21, tapping the first letter gives me 6.

答:
I've been trying to find something that works for this. Here is what I was able to get to work. It pulls from a few other examples but I had to include the Paragraph style to make it line up exactly. Hope this can help someone else.</p>

```<code>NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeZero];
NSTextStorage *textStorage;

NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
paragraphStyle.alignment = self.label.textAlignment;
// Configure textContainer
textContainer.lineFragmentPadding = 0.0;
textContainer.lineBreakMode = self.label.lineBreakMode;
textContainer.maximumNumberOfLines = self.label.numberOfLines;

CGPoint locationOfTouchInLabel = [tapGesture locationInView:tapGesture.view];
CGSize labelSize = tapGesture.view.bounds.size;
textContainer.size = self.label.bounds.size;

NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.noPoliciesDescriptionLabel.attributedText];
[attributedText addAttributes:@{NSFontAttributeName: self.label.font, NSParagraphStyleAttributeName: paragraphStyle} range:NSMakeRange(0,self.label.attributedText.string.length)];
textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedText];

// Configure layoutManager and textStorage
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];

CGRect textBoundingBox = [layoutManager usedRectForTextContainer:textContainer];
CGPoint textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                          (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);

CGPoint locationOfTouchInTextContainer = CGPointMake(locationOfTouchInLabel.x - textContainerOffset.x,
                                                     locationOfTouchInLabel.y - textContainerOffset.y);

NSInteger indexOfCharacter = [layoutManager characterIndexForPoint:locationOfTouchInTextContainer
                                                        inTextContainer:textContainer
                               fractionOfDistanceBetweenInsertionPoints:nil];

NSRange range = NSMakeRange(indexOfCharacter, 1);
NSString *value = [self.label.text substringWithRange:range];
NSLog(@"%@, %zd, %zd" , value, range.location, range.length);
</code>```

Body:
I'd like to get the index for the tapped character on a UILabel.  I've subclassed a UILabel.  In my awakeFromNib() I have this:

    layoutManager = NSLayoutManager()
    textStorage = NSTextStorage(attributedString: self.attributedText)
    textStorage.addLayoutManager(layoutManager)

    textContainer = NSTextContainer(size: CGSizeMake(self.frame.size.width, self.frame.size.height))
    textContainer.lineFragmentPadding = 0
    textContainer.maximumNumberOfLines = self.numberOfLines
    textContainer.lineBreakMode = self.lineBreakMode
    textContainer.size = self.frame.size

    layoutManager.addTextContainer(textContainer)

It is working how I want it to for the first 5 characters of the label, as in I tap the first character and in my touchesEnded I get an index of 0:

var touchedCharacterIndex = layoutManager.characterIndexForPoint(touch.locationInView(self), inTextContainer: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

But when I tap anywhere past the first four characters of the UILabel, I get either 4 or 0, which is incorrect.

Thanks,

Update

From a suggestion in the comments, I've added this:

 func updateTextStorage() {
    if let attributedText = self.attributedText {
        textStorage = NSTextStorage(attributedString: attributedText)
    }
    textStorage?.addLayoutManager(layoutManager)

    textContainer = NSTextContainer(size: CGSizeMake(self.frame.size.width, self.frame.size.height))
    textContainer?.lineFragmentPadding = 7
    textContainer?.maximumNumberOfLines = self.numberOfLines
    textContainer?.lineBreakMode = self.lineBreakMode
    textContainer?.size = self.bounds.size

    layoutManager.addTextContainer(textContainer!)
    layoutManager.textStorage = textStorage
}

I call this in layoutSubviews(), awakFromNib and the setters of bounds, frame, attributedText and text.

And it is now giving me some weird indexes, like if text length is 21, tapping the first letter gives me 6.

Body:
I've been trying to find something that works for this. Here is what I was able to get to work. It pulls from a few other examples but I had to include the Paragraph style to make it line up exactly. Hope this can help someone else.

NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeZero];
NSTextStorage *textStorage;

NSMutableParagraphStyle *paragraphStyle = NSMutableParagraphStyle.new;
paragraphStyle.alignment = self.label.textAlignment;
// Configure textContainer
textContainer.lineFragmentPadding = 0.0;
textContainer.lineBreakMode = self.label.lineBreakMode;
textContainer.maximumNumberOfLines = self.label.numberOfLines;

CGPoint locationOfTouchInLabel = [tapGesture locationInView:tapGesture.view];
CGSize labelSize = tapGesture.view.bounds.size;
textContainer.size = self.label.bounds.size;

NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.noPoliciesDescriptionLabel.attributedText];
[attributedText addAttributes:@{NSFontAttributeName: self.label.font, NSParagraphStyleAttributeName: paragraphStyle} range:NSMakeRange(0,self.label.attributedText.string.length)];
textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedText];

// Configure layoutManager and textStorage
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];

CGRect textBoundingBox = [layoutManager usedRectForTextContainer:textContainer];
CGPoint textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                          (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);

CGPoint locationOfTouchInTextContainer = CGPointMake(locationOfTouchInLabel.x - textContainerOffset.x,
                                                     locationOfTouchInLabel.y - textContainerOffset.y);

NSInteger indexOfCharacter = [layoutManager characterIndexForPoint:locationOfTouchInTextContainer
                                                        inTextContainer:textContainer
                               fractionOfDistanceBetweenInsertionPoints:nil];

NSRange range = NSMakeRange(indexOfCharacter, 1);
NSString *value = [self.label.text substringWithRange:range];
NSLog(@"%@, %zd, %zd" , value, range.location, range.length);


问:
Representing boolean values in JSON
Say i have a file.json that contains the following:

```<code>[
  {
    "name": "Shirt1",
    "product_id": "001234"
  },
  {
    "name": "Shirt2",
    "product_id": "005678"
  }
]
</code>```

Using Python3, i want to add to both dictionaries the following lines:

```<code>"type": "external"
"reviews_allowed": false
</code>```

This is my code:

```<code>import json
import os

with open("file.json", "r", encoding="utf8") as in_file:
INP = json.load(in_file)
DATA = []
for item in INP:
    item["type"] = "external"
    item["reviews_allowed"] = "false"
    DATA.append(item)
    with open("file2.json", "w", encoding="utf-8") as out_file:
        out_file.write(json.dumps(DATA, indent=2, ensure_ascii=False))
os.rename("file2.json", "file.json")
</code>```

However, I get the following:

```<code>[
  {
    "name": "Shirt1",
    "product_id": "001234",
    "type": "external",
    "reviews_allowed": "false"
  },
  {
    "name": "Shirt2",
    "product_id": "005678",
    "type": "external",
    "reviews_allowed": "false"
  }
]
</code>```

Is there a way to get rid of the double quotes around false?
Thank you very much in advance for your time!

答:
false is recognised as its own type in JSON:

A value can be a string in double quotes, or a number, or true or
  false or null, or an object or an array.

In python, the JSON false maps directly to the False bool value:

```<code>>>> json.dumps({'val' : False})
'{"val": false}'
</code>```

ContentLicense: CC BY-SA 4.0

Title: Representing boolean values in JSON

Body:
Say i have a file.json that contains the following:

[
  {
    "name": "Shirt1",
    "product_id": "001234"
  },
  {
    "name": "Shirt2",
    "product_id": "005678"
  }
]

Using Python3, i want to add to both dictionaries the following lines:

"type": "external"
"reviews_allowed": false

This is my code:

import json
import os

with open("file.json", "r", encoding="utf8") as in_file:
INP = json.load(in_file)
DATA = []
for item in INP:
    item["type"] = "external"
    item["reviews_allowed"] = "false"
    DATA.append(item)
    with open("file2.json", "w", encoding="utf-8") as out_file:
        out_file.write(json.dumps(DATA, indent=2, ensure_ascii=False))
os.rename("file2.json", "file.json")

However, I get the following:

[
  {
    "name": "Shirt1",
    "product_id": "001234",
    "type": "external",
    "reviews_allowed": "false"
  },
  {
    "name": "Shirt2",
    "product_id": "005678",
    "type": "external",
    "reviews_allowed": "false"
  }
]

Is there a way to get rid of the double quotes around false?
Thank you very much in advance for your time!

Body:
false is recognised as its own type in JSON:

A value can be a string in double quotes, or a number, or true or
  false or null, or an object or an array.

In python, the JSON false maps directly to the False bool value:

>>> json.dumps({'val' : False})
'{"val": false}'


答:
The JSON concept false maps directly to the Python concept False. Use this line:

```<code>item["reviews_allowed"] = False
</code>```

Title: Representing boolean values in JSON

Body:
The JSON concept false maps directly to the Python concept False. Use this line:

item["reviews_allowed"] = False


问:
What is the most performant way to rewrite a correlated subquery in the SELECT clause?
I am trying to count whether a user has visited a site in three time ranges:

last 30 days

between 31 and 60 days

between 61 and 90 days

I am using Netezza, which does NOT support correlated subqueries in the SELECT clause. See Rextester for successful query that must be re-written to NOT use a correlated subquery: http://rextester.com/JGR62033

Sample Data:

```<code>| user_id | last_visit | num_days_since_2017117 |
|---------|------------|------------------------|
| 1234    | 2017-11-02 | 15.6                   |
| 1234    | 2017-09-30 | 48.6                   |
| 1234    | 2017-09-03 | 75.0                   |
| 1234    | 2017-08-21 | 88.0                   |
| 9876    | 2017-10-03 | 45.0                   |
| 9876    | 2017-07-20 | 120.0                  |
| 5545    | 2017-09-15 | 63.0                   |
</code>```

Desired Output:

```<code>| user_id | last_30 | btwn_31_60 | btwn_61_90 |
|---------|---------|------------|------------|
| 1234    | 1       | 1          | 1          |
| 5545    | 0       | 0          | 1          |
| 9876    | 0       | 1          | 0          |
</code>```

答:
I don't know the specific DBMS you're using, but if it supports CASE or an equivalent you don't need a correlated sub-query; you can do it with a combination of SUM() and CASE.

Untested in your DBMS, of course, but it should give you a starting point:

```<code>SELECT
  user_id,
  SUM(CASE WHEN num_days <= 30 then 1 else 0 end) as last_30,
  SUM(CASE WHEN num_days > 30 AND numdays < 61 then 1 else 0 end) as btwn_31_60,
  SUM(CASE WHEN num_days >= 61 then 1 else 0 end) as btwn_61_90
FROM
  YourTableName  -- You didn't provide a tablename
GROUP BY
  user_id
</code>```

Since your values are floating point and not integer, you may need to adjust the values used for the day ranges to work with your specific requirements.

Body:
I am trying to count whether a user has visited a site in three time ranges:

last 30 days

between 31 and 60 days

between 61 and 90 days

I am using Netezza, which does NOT support correlated subqueries in the SELECT clause. See Rextester for successful query that must be re-written to NOT use a correlated subquery: http://rextester.com/JGR62033

Sample Data:

| user_id | last_visit | num_days_since_2017117 |
|---------|------------|------------------------|
| 1234    | 2017-11-02 | 15.6                   |
| 1234    | 2017-09-30 | 48.6                   |
| 1234    | 2017-09-03 | 75.0                   |
| 1234    | 2017-08-21 | 88.0                   |
| 9876    | 2017-10-03 | 45.0                   |
| 9876    | 2017-07-20 | 120.0                  |
| 5545    | 2017-09-15 | 63.0                   |

Desired Output:

| user_id | last_30 | btwn_31_60 | btwn_61_90 |
|---------|---------|------------|------------|
| 1234    | 1       | 1          | 1          |
| 5545    | 0       | 0          | 1          |
| 9876    | 0       | 1          | 0          |

Body:
I don't know the specific DBMS you're using, but if it supports CASE or an equivalent you don't need a correlated sub-query; you can do it with a combination of SUM() and CASE.

Untested in your DBMS, of course, but it should give you a starting point:

SELECT
  user_id,
  SUM(CASE WHEN num_days <= 30 then 1 else 0 end) as last_30,
  SUM(CASE WHEN num_days > 30 AND numdays < 61 then 1 else 0 end) as btwn_31_60,
  SUM(CASE WHEN num_days >= 61 then 1 else 0 end) as btwn_61_90
FROM
  YourTableName  -- You didn't provide a tablename
GROUP BY
  user_id

Since your values are floating point and not integer, you may need to adjust the values used for the day ranges to work with your specific requirements.


问:
gem install rb-appscript on macos fails / Alfred todo workflow
I'd like to install rb-appscript on my macbook pro running high sierra but it fails for reasons I can't tell

```<code>sa@mbp: ~ sudo gem install rb-appscript
Password:
Building native extensions.  This could take a while...
ERROR:  Error installing rb-appscript:
    ERROR: Failed to build gem native extension.

    current directory: /usr/local/lib/ruby/gems/2.4.0/gems/rb-appscript-0.6.1
/usr/local/opt/ruby/bin/ruby -r ./siteconf20171117-38586-zi3axn.rb extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/local/Cellar/ruby/2.4.2_1/bin/$(RUBY_BASE_NAME)
extconf.rb:44:in `<main>': uninitialized constant Config (NameError)
Did you mean?  RbConfig
               CONFIG

extconf failed, exit code 1

Gem files will remain installed in /usr/local/lib/ruby/gems/2.4.0/gems/rb-appscript-0.6.1 for inspection.
Results logged to /usr/local/lib/ruby/gems/2.4.0/extensions/x86_64-darwin-17/2.4.0/rb-appscript-0.6.1/gem_make.out
sa@mbp: ~ uname -a
Darwin mbp.home 17.2.0 Darwin Kernel Version 17.2.0: Fri Sep 29 18:27:05 PDT 2017; root:xnu-4570.20.62~3/RELEASE_X86_64 x86_64
sa@mbp: ~ ruby -v
ruby 2.3.3p222 (2016-11-21 revision 56859) [universal.x86_64-darwin17]
sa@mbp: ~ xcode-select -p
/Library/Developer/CommandLineTools
sa@mbp: ~ gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin17.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
sa@mbp: ~ make -v
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i386-apple-darwin11.3.0
sa@mbp: ~
</code>```

Any clues on what the issue is and how to resolve it?

What I actually want to achieve is installing a workflow for alfred that seems to require 'rb-appscript' https://github.com/dv/alfred-omnifocus-workflow

答: I figured, rb-appscript is the root of the problem. Pity, I really loved the alfred workflow for omnifocus because it was fast getting a task into omnifocus and continue with whatever you were workin on.</p>

Body:
I'd like to install rb-appscript on my macbook pro running high sierra but it fails for reasons I can't tell

sa@mbp: ~ sudo gem install rb-appscript
Password:
Building native extensions.  This could take a while...
ERROR:  Error installing rb-appscript:
    ERROR: Failed to build gem native extension.

    current directory: /usr/local/lib/ruby/gems/2.4.0/gems/rb-appscript-0.6.1
/usr/local/opt/ruby/bin/ruby -r ./siteconf20171117-38586-zi3axn.rb extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/local/Cellar/ruby/2.4.2_1/bin/$(RUBY_BASE_NAME)
extconf.rb:44:in `': uninitialized constant Config (NameError)
Did you mean?  RbConfig
               CONFIG

extconf failed, exit code 1

Gem files will remain installed in /usr/local/lib/ruby/gems/2.4.0/gems/rb-appscript-0.6.1 for inspection.
Results logged to /usr/local/lib/ruby/gems/2.4.0/extensions/x86_64-darwin-17/2.4.0/rb-appscript-0.6.1/gem_make.out
sa@mbp: ~ uname -a
Darwin mbp.home 17.2.0 Darwin Kernel Version 17.2.0: Fri Sep 29 18:27:05 PDT 2017; root:xnu-4570.20.62~3/RELEASE_X86_64 x86_64
sa@mbp: ~ ruby -v
ruby 2.3.3p222 (2016-11-21 revision 56859) [universal.x86_64-darwin17]
sa@mbp: ~ xcode-select -p
/Library/Developer/CommandLineTools
sa@mbp: ~ gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.38)
Target: x86_64-apple-darwin17.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
sa@mbp: ~ make -v
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i386-apple-darwin11.3.0
sa@mbp: ~

Any clues on what the issue is and how to resolve it?

What I actually want to achieve is installing a workflow for alfred that seems to require 'rb-appscript' https://github.com/dv/alfred-omnifocus-workflow


问:
Triggering a Msg when page loads (elm 0.18)
If I want to trigger an update SomeAction with a button in elm (0.18), I would do it like this:

```<code>myView : Html Msg
myView =
    div []
        [ button [ onClick SomeAction ] [ text "Some Action" ]
        ]
</code>```

I want SomeAction to fire when myView renders.  How do I do something like this:

```<code>myView : Html Msg
myView =
    div [ onLoad SomeAction ]
        []
</code>```

答:
This is dirty but it works... do an animation that practically does nothing and listen on "animationend" and "webkitanimationend".

```<code>          Html.div
                [ Html.style [ ( "display", "inline-block" ), ( "animation", "pulse 0.1s" ) ]
                , Html.Events.on "webkitAnimationEnd"
                   (Json.Decode.succeed (FancyMessageHere)
                ]
                []
</code>```

Also have a dummy pulse in your CSS:

```<code>@keyframes pulse {
    0%   {background-color: white;}
    100% {background-color: white;}
}
</code>```

Body:
If I want to trigger an update SomeAction with a button in elm (0.18), I would do it like this:

myView : Html Msg
myView =
    div []
        [ button [ onClick SomeAction ] [ text "Some Action" ]
        ]

I want SomeAction to fire when myView renders.  How do I do something like this:

myView : Html Msg
myView =
    div [ onLoad SomeAction ]
        []

Body:
This is dirty but it works... do an animation that practically does nothing and listen on "animationend" and "webkitanimationend".

          Html.div
                [ Html.style [ ( "display", "inline-block" ), ( "animation", "pulse 0.1s" ) ]
                , Html.Events.on "webkitAnimationEnd"
                   (Json.Decode.succeed (FancyMessageHere)
                ]
                []

Also have a dummy pulse in your CSS:

@keyframes pulse {
    0%   {background-color: white;}
    100% {background-color: white;}
}


问:
Reasons for upgrading from Team Foundation Server 2008 to Team Foundation Server 2010
Currently our team is using TFS 2008 and I need to substantiate my opinion to push my whole team forward.

What are the must-have features of TFS 2010?

Or: What are your main reasons to upgrade from TFS 2008 to TFS 2010?

Thanks in advance

答:
Off the top of my head, these are what are important to me from a 2010 standpoint:

Hierarchical work items (parent/child)

Performance and Stability improvements

The concept of project collections to allow for logically separate instances of TFS to be hosted on a single data tier.

Ease of installation.

Better rollback support.

Better branching and merging visualization.

Improved process templates and reports.

ContentLicense: CC BY-SA 2.5


问:
Auto add history table into view in SQL Server
We have a history view which has tables for 2011, 2012, ...., 2017.

When the time passes to 2018, we need to add the 2018 table into the view.

The definition for the table is like:

```<code>create view v_a
as
   select id, name, 1 from 2011
   union all
   select id, name, 1 from 2012
   ....
   union all
   select id, name, 1 from 2017
</code>```

I want the view changing to

```<code>create view v_a
as
    select id, name, 1 from 2011
    union all
    select id, name, 1 from 2012
    ....
    union all
    select id, name, 1 from 2017
    union all
    select id, name, 1 from 2018
</code>```

How can I implement it by using an automatic script?

答: You could set up a SQL Agent Job with a "run once" schedule? Or create a windows task scheduler task that kicks off a batch script that calls a PowerShell script that updates the database. </p>

Body:
We have a history view which has tables for 2011, 2012, ...., 2017.

When the time passes to 2018, we need to add the 2018 table into the view.

The definition for the table is like:

create view v_a
as
   select id, name, 1 from 2011
   union all
   select id, name, 1 from 2012
   ....
   union all
   select id, name, 1 from 2017

I want the view changing to

create view v_a
as
    select id, name, 1 from 2011
    union all
    select id, name, 1 from 2012
    ....
    union all
    select id, name, 1 from 2017
    union all
    select id, name, 1 from 2018

How can I implement it by using an automatic script?


问:
Fixing invalid JSON octal escape
KISSmetrics generates invalid JSON strings I need to parse. I'm getting tons of errors like

```<code>ERROR 2013-03-04 04:31:12,253 Invalid \escape: line 1 column 132 (char 132): {"search engine":"Google","_n":"search engine hit","_p":"z392cpdpnm6silblq5mac8kiugq=","search terms":"happy new year animation 1920\303\2271080 hd","_t":1356390128}

ERROR 2013-03-04 04:34:19,153 Invalid \escape: line 1 column 101 (char 101): {"search engine":"Google","_n":"ad campaign hit","_p":"byskpczsw6sorbmzqi0tk1uimgw=","search terms":"\331\203\330\261\330\252\331\207 \331\201\331\212\330\257\331\212\330\244\331\211 \330\256\331\212\331\204\330\247\330\255\331\211 \331\203\331\210\330\261\330\257\331\211","_t":1356483052}
</code>```

My code is:

```<code>for line in lines:
    try:
        data = self.clean_data(json.loads(line))
        except ValueError, e:
            logger.error('%s: %s' % (e.message, line))
</code>```

Example raw data:

```<code>{"search engine":"Google","_n":"search engine hit","_p":"kvceh84hzbhywcnlivv+hdztizw=","search terms":"military sound effects programs","_t":1356034177}
</code>```

Is there any chance to cleanup this messy JSON and parse it? Thanks for your help.

答:
I had similar problem and just replacing json library with yaml solved the issue. (YAML is compatible with JSON.)

Example:

```<code>import yaml

obj = yaml.load(json_string) # instead of json.loads(json_string)
</code>```

Title: Fixing invalid JSON octal escape

Body:
KISSmetrics generates invalid JSON strings I need to parse. I'm getting tons of errors like

ERROR 2013-03-04 04:31:12,253 Invalid \escape: line 1 column 132 (char 132): {"search engine":"Google","_n":"search engine hit","_p":"z392cpdpnm6silblq5mac8kiugq=","search terms":"happy new year animation 1920\303\2271080 hd","_t":1356390128}

ERROR 2013-03-04 04:34:19,153 Invalid \escape: line 1 column 101 (char 101): {"search engine":"Google","_n":"ad campaign hit","_p":"byskpczsw6sorbmzqi0tk1uimgw=","search terms":"\331\203\330\261\330\252\331\207 \331\201\331\212\330\257\331\212\330\244\331\211 \330\256\331\212\331\204\330\247\330\255\331\211 \331\203\331\210\330\261\330\257\331\211","_t":1356483052}

My code is:

for line in lines:
    try:
        data = self.clean_data(json.loads(line))
        except ValueError, e:
            logger.error('%s: %s' % (e.message, line))

Example raw data:

{"search engine":"Google","_n":"search engine hit","_p":"kvceh84hzbhywcnlivv+hdztizw=","search terms":"military sound effects programs","_t":1356034177}

Is there any chance to cleanup this messy JSON and parse it? Thanks for your help.

Body:
I had similar problem and just replacing json library with yaml solved the issue. (YAML is compatible with JSON.)

Example:

import yaml

obj = yaml.load(json_string) # instead of json.loads(json_string)


问:
Lambda expression question
```<code>string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/
</code>```

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

答:
The lambda expression populates the first variable name as the item itself, and the second as the index.

So if you have (fruit,index) then:

fruit = The data object.

index = The index in the array.

Title: Lambda expression question

Body:
string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.


问:
Configuration file for training jobs
The command ml-engine jobs submit training accepts a --config flag that identifies a configuration file for the job. According to the documentation, many fields of this file are "Output only". I assume this means that the fields are set by the ML Engine.

How do you write the configuration file so that the ML Engine will set these "Output only" fields? I've rewritten my file a few times, but I get an error when I run my application.

If anyone has any example configuration files, that would be great.

答:
Here's one example of how to modify the worker types and counts, taken from the criteo_tft sample:

```<code>trainingInput:
  scaleTier: CUSTOM
  masterType: large_model
  workerType: complex_model_m
  parameterServerType: large_model
  workerCount: 60
  parameterServerCount: 29
</code>```

You'll find another example for Hyperparameter tuning, taken from the Census sample.

Title: Configuration file for training jobs

Body:
Here's one example of how to modify the worker types and counts, taken from the criteo_tft sample:

trainingInput:
  scaleTier: CUSTOM
  masterType: large_model
  workerType: complex_model_m
  parameterServerType: large_model
  workerCount: 60
  parameterServerCount: 29

You'll find another example for Hyperparameter tuning, taken from the Census sample.


问:
Fill every word in a qword using corresponding high bit of each word
I have a qword. It consists of 4 parts -- 16 bits each.

Each part has a structure: the first bit of every part is either 1 or 0, others are zeros.

I want to broadcast that first bit to all the other positions with that 16-bit element.

答:
In x64 assembly you can apply arithmetic right shift on a per-word basis:

```<code>psraw xmm0, 15
</code>```

This actually processes two of such qwords side by side, but you can use it for only one. For example, maybe that qword is in memory somewhere, then you can do:

```<code>movq xmm0, [somewhere]
psraw xmm0, 15
movq [somewhere], xmm0
</code>```

This can be used to and from a general purpose register as well.

Without SSE, even generically (eg using operations that exist in typical higher level languages as well), there are other options. These all assume that the input x has the specified form, with no stray 1's, only the top bit of every word is allowed to ever be 1. The code above can have arbitrary junk in the other bits.

When implemented literally (with a real multiplication), this still only uses one register. The shift is a logical shift. In a higher level language, the multiplication may be compiled to something else:

```<code>(x >> 15) * 0xFFFF
</code>```

Maybe faster, depending on the cost of multiplication, but needs a temporary register:

```<code>(x << 1) - (x >> 15)
</code>```

A more brute force way, with no practical use as far as I know, but may be interesting:

```<code>x |= x >> 8
x |= x >> 4
x |= x >> 2
x |= x >> 1
</code>```

Body:
In x64 assembly you can apply arithmetic right shift on a per-word basis:

psraw xmm0, 15

This actually processes two of such qwords side by side, but you can use it for only one. For example, maybe that qword is in memory somewhere, then you can do:

movq xmm0, [somewhere]
psraw xmm0, 15
movq [somewhere], xmm0

This can be used to and from a general purpose register as well.

Without SSE, even generically (eg using operations that exist in typical higher level languages as well), there are other options. These all assume that the input x has the specified form, with no stray 1's, only the top bit of every word is allowed to ever be 1. The code above can have arbitrary junk in the other bits.

When implemented literally (with a real multiplication), this still only uses one register. The shift is a logical shift. In a higher level language, the multiplication may be compiled to something else:

(x >> 15) * 0xFFFF

Maybe faster, depending on the cost of multiplication, but needs a temporary register:

(x << 1) - (x >> 15)

A more brute force way, with no practical use as far as I know, but may be interesting:

x |= x >> 8
x |= x >> 4
x |= x >> 2
x |= x >> 1


问:
C# Copy one row from datagrid
I have problem with copying one row from my datagrid and then copy it.
For multiple selected rows it works fine as i want. But for one row not.

This is code for copy row

```<code>/// <summary>
    /// Method which will copy entire row.
    /// </summary>
    private void CopyRow(object obj)
    {
        var datagrid = obj as System.Windows.Controls.DataGrid;

        List<string> valsCollection = new List<string>();

        foreach (ENotifiedTruck item in datagrid.SelectedItems)
        {
            valsCollection.Add(item.ToStringLP());
        }

        var rows = GetDataGridRows(datagrid);
        int i1 = 0;
        foreach (DataGridRow r in rows)
        {
            DataGridColumn column = datagrid.Columns[0];

            TextBlock cellcontent = column.GetCellContent(r) as TextBlock;

            valsCollection[i1] = string.Format("{0}\t{1}", cellcontent.Text, valsCollection[i1]);
            i1++;

        }

        datagrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
        valsCollection.Insert(0, string.Empty);
        ApplicationCommands.Copy.Execute(null, datagrid);
        string oldresult = (string)Clipboard.GetData(DataFormats.Text);

        List<string> rowCollection = new List<string>();
        rowCollection = oldresult.Split(new char[] { '\n' }).ToList<string>();

        if (rowCollection.Count == 0)
            return;

        string last = rowCollection[0];
        rowCollection = new List<string>();
        rowCollection.Add(last);
        rowCollection.AddRange(valsCollection);

        oldresult = string.Join("\n", rowCollection);
        Clipboard.SetText($"{oldresult}");
    }

    public IEnumerable<DataGridRow> GetDataGridRows(System.Windows.Controls.DataGrid grid)
    {
        var itemsSource = grid.ItemsSource as IEnumerable;
        if (null == itemsSource) yield return null;
        foreach (var item in itemsSource)
        {
            var row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(item);
            if (null != row) yield return row;
        }
    }
</code>```

Now in this particular line :

```<code>valsCollection[i1] = string.Format("{0}\t{1}", cellcontent.Text, valsCollection[i1]);
</code>```

I got error when i select only one row.
This is the message i get from error: "An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll"

Any ideas? Thanks :]

答:
DataGridRow has an Item property that should be the ENotifiedTruck you are trying to use.

You can use that instead of creating a separate collection beforehand.

Also, from what it looks like, you are getting all DataGridRow objects from GetDataGridRows based on the ItemsSource collection, while you are only creating entries in the valsCollection for selected rows.

If you have 1 selected row and 2 or more rows, then I think this should fail with an out of range exception when you get to [1] and valsCollection has no [1].

```<code>if(!datagrid.SelectedItems.Contains(r.Item))
    continue;
</code>```

will skip any rows that aren't selected.

Title: C# Copy one row from datagrid

Body:
I have problem with copying one row from my datagrid and then copy it.
For multiple selected rows it works fine as i want. But for one row not.

This is code for copy row

///
    /// Method which will copy entire row.
    ///
    private void CopyRow(object obj)
    {
        var datagrid = obj as System.Windows.Controls.DataGrid;

        List<string> valsCollection = new List<string>();

        foreach (ENotifiedTruck item in datagrid.SelectedItems)
        {
            valsCollection.Add(item.ToStringLP());
        }

        var rows = GetDataGridRows(datagrid);
        int i1 = 0;
        foreach (DataGridRow r in rows)
        {
            DataGridColumn column = datagrid.Columns[0];

            TextBlock cellcontent = column.GetCellContent(r) as TextBlock;

            valsCollection[i1] = string.Format("{0}\t{1}", cellcontent.Text, valsCollection[i1]);
            i1++;

        }

        datagrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
        valsCollection.Insert(0, string.Empty);
        ApplicationCommands.Copy.Execute(null, datagrid);
        string oldresult = (string)Clipboard.GetData(DataFormats.Text);

        List<string> rowCollection = new List<string>();
        rowCollection = oldresult.Split(new char[] { '\n' }).ToList<string>();

        if (rowCollection.Count == 0)
            return;

        string last = rowCollection[0];
        rowCollection = new List<string>();
        rowCollection.Add(last);
        rowCollection.AddRange(valsCollection);

        oldresult = string.Join("\n", rowCollection);
        Clipboard.SetText($"{oldresult}");
    }

    public IEnumerable<DataGridRow> GetDataGridRows(System.Windows.Controls.DataGrid grid)
    {
        var itemsSource = grid.ItemsSource as IEnumerable;
        if (null == itemsSource) yield return null;
        foreach (var item in itemsSource)
        {
            var row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(item);
            if (null != row) yield return row;
        }
    }

Now in this particular line :

valsCollection[i1] = string.Format("{0}\t{1}", cellcontent.Text, valsCollection[i1]);

I got error when i select only one row.
This is the message i get from error: "An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll"

Any ideas? Thanks :]

Body:
DataGridRow has an Item property that should be the ENotifiedTruck you are trying to use.

You can use that instead of creating a separate collection beforehand.

Also, from what it looks like, you are getting all DataGridRow objects from GetDataGridRows based on the ItemsSource collection, while you are only creating entries in the valsCollection for selected rows.

If you have 1 selected row and 2 or more rows, then I think this should fail with an out of range exception when you get to [1] and valsCollection has no [1].

if(!datagrid.SelectedItems.Contains(r.Item))
    continue;

will skip any rows that aren't selected.


问:
Why does VSCode external links don't open and make firefox crashing
OS version: Ubuntu 17.10 x64
VSCode version:1.17.2 x64

When I click on a link in VSCode which refer to an internet URL (ex:on welcome page at startup>Help>Introductory videos) it opens 2 "Mozilla Crash Reporter" windows with "Firefox had a problem and crash"

I tried to disable all Add-ons in Firefox and VSCode, but the issue is still there.
I tried to re-install VSCode
I didn't find a way to ask VSCode to use Chrome instead of Firefox...

here is the Modzilla firefox report content:

```<code>Add-ons: sbv4-gradual-rollout%40mozilla.com:1.0.0,firefox%40getpocket.com:1.0.5,activity-stream%40mozilla.org:0.0.0,clicktoplay-rollout%40mozilla.org:1.4,followonsearch%40mozilla.com:0.9.3,aushelper%40mozilla.org:2.0,onboarding%40mozilla.org:0.1,shield-recipe-client%40mozilla.org:65,e10srollout%40mozilla.org:3.00,formautofill%40mozilla.org:1.0,webcompat%40mozilla.org:1.1,screenshots%40mozilla.org:10.12.0,langpack-en-ZA%40firefox.mozilla.org:56.0,%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D:56.0,langpack-en-GB%40firefox.mozilla.org:56.0,ubufox%40ubuntu.com:3.3
AddonsShouldHaveBlockedE10s: 0
BuildID: 20171003222101
CTPCohort: user-changed-from-test
ContentSandboxCapabilities: 119
ContentSandboxCapable: 1
ContentSandboxLevel: 2
CrashTime: 1510735922
DOMIPCEnabled: 1
E10SCohort: addons-set50allmpc-test
EMCheckCompatibility: true
Email: -----@gmail.com
FramePoisonBase: 9223372036600930304
FramePoisonSize: 4096
InstallTime: 1509968396
Notes: Ubuntu 17.10FP(D00-L1000-W00000000-T000) OpenGL: X.Org -- Gallium 0.4 on AMD RS880 (DRM 2.50.0 / 4.13.0-16-generic, LLVM 4.0.0) -- 3.0 Mesa 17.0.7 -- texture_from_pixmap
WR? WR-
ProductID: {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
ProductName: Firefox
ReleaseChannel: release
SafeMode: 0
SecondsSinceLastCrash: 302
StackTraces:
StartupCrash: 0
StartupTime: 1510735920
TelemetryEnvironment: {"build":{"applicationId":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","applicationName":"Firefox","architecture":"x86-64","buildId":"20171003222101","version":"56.0","vendor":"Mozilla","platformVersion":"56.0","xpcomAbi":"x86_64-gcc3","hotfixVersion":null},"partner":{"distributionId":null,"distributionVersion":null,"partnerId":null,"distributor":null,"distributorChannel":null,"partnerNames":[]},"system":{"memoryMB":7727,"virtualMaxMB":null,"cpu":{"count":4,"cores":4,"vendor":"AuthenticAMD","family":16,"model":5,"stepping":3,"l2cacheKB":512,"l3cacheKB":512,"speedMHz":3100,"extensions":["hasMMX","hasSSE","hasSSE2","hasSSE3"]},"os":{"name":"Linux","version":"4.13.0-16-generic","locale":"en-US"},"hdd":{"profile":{"model":null,"revision":null},"binary":{"model":null,"revision":null},"system":{"model":null,"revision":null}},"gfx":{"D2DEnabled":null,"DWriteEnabled":null,"ContentBackend":"Skia","adapters":[{"description":"X.Org -- Gallium 0.4 on AMD RS880 (DRM 2.50.0 / 4.13.0-16-generic, LLVM 4.0.0)","vendorID":"X.Org","deviceID":"Gallium 0.4 on AMD RS880 (DRM 2.50.0 / 4.13.0-16-generic, LLVM 4.0.0)","subsysID":null,"RAM":null,"driver":null,"driverVersion":"3.0 Mesa 17.0.7","driverDate":null,"GPUActive":true}],"monitors":[],"features":{"compositor":"none","gpuProcess":{"status":"unused"}}}},"settings":{"blocklistEnabled":true,"e10sEnabled":true,"e10sMultiProcesses":1,"e10sCohort":"addons-set50allmpc-test","telemetryEnabled":false,"locale":"en-US","update":{"channel":"release","enabled":true,"autoDownload":true},"userPrefs":{"browser.cache.disk.capacity":358400,"browser.newtabpage.enhanced":true},"sandbox":{"effectiveContentProcessLevel":2},"addonCompatibilityCheckEnabled":true,"isDefaultBrowser":null},"profile":{},"experiments":{"clicktoplay-rollout":{"branch":"user-changed-from-test"},"e10sCohort":{"branch":"addons-set50allmpc-test"}}}
Theme: classic/1.0
ThreadIdNameMapping: 13144:"Gecko_IOThread",13145:"Timer",13146:"Link Monitor",13147:"Socket Thread",13148:"JS Watchdog",13158:"Hang Monitor",13161:"Cache2 I/O",13162:"GMPThread",13164:"SoftwareVsyncThread",13165:"Compositor",13166:"ImgDecoder #1",13167:"ImgDecoder #2",13168:"ImgDecoder #3",13169:"ImageIO",13170:"SysProxySetting",13171:"ProxyResolution",13172:"DataStorage",13173:"URL Classifier",13174:"DNS Resolver #1",13175:"DataStorage",13176:"DataStorage",13177:"HTML5 Parser",13178:"IPDL Background",13179:"Classifier Update",13182:"DOM Worker",13184:"DOM Worker",13186:"StreamTrans #5",13187:"StreamTrans #6",13188:"StreamTrans #7",13192:"ImageBridgeChild",13194:"ProcessHangMon",
Throttleable: 1
UptimeTS: 1.6526776
Vendor: Mozilla
Version: 56.0
useragent_locale: en-US

This report also contains technical information about the state of the application when it crashed.
</code>```

答: I resolved this issue by setting Chrome as "default browser" on my Ubuntu and then re-install VSCode</p>

Body:
OS version: Ubuntu 17.10 x64
VSCode version:1.17.2 x64

When I click on a link in VSCode which refer to an internet URL (ex:on welcome page at startup>Help>Introductory videos) it opens 2 "Mozilla Crash Reporter" windows with "Firefox had a problem and crash"

I tried to disable all Add-ons in Firefox and VSCode, but the issue is still there.
I tried to re-install VSCode
I didn't find a way to ask VSCode to use Chrome instead of Firefox...

here is the Modzilla firefox report content:

Add-ons: sbv4-gradual-rollout%40mozilla.com:1.0.0,firefox%40getpocket.com:1.0.5,activity-stream%40mozilla.org:0.0.0,clicktoplay-rollout%40mozilla.org:1.4,followonsearch%40mozilla.com:0.9.3,aushelper%40mozilla.org:2.0,onboarding%40mozilla.org:0.1,shield-recipe-client%40mozilla.org:65,e10srollout%40mozilla.org:3.00,formautofill%40mozilla.org:1.0,webcompat%40mozilla.org:1.1,screenshots%40mozilla.org:10.12.0,langpack-en-ZA%40firefox.mozilla.org:56.0,%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D:56.0,langpack-en-GB%40firefox.mozilla.org:56.0,ubufox%40ubuntu.com:3.3
AddonsShouldHaveBlockedE10s: 0
BuildID: 20171003222101
CTPCohort: user-changed-from-test
ContentSandboxCapabilities: 119
ContentSandboxCapable: 1
ContentSandboxLevel: 2
CrashTime: 1510735922
DOMIPCEnabled: 1
E10SCohort: addons-set50allmpc-test
EMCheckCompatibility: true
Email: -----@gmail.com
FramePoisonBase: 9223372036600930304
FramePoisonSize: 4096
InstallTime: 1509968396
Notes: Ubuntu 17.10FP(D00-L1000-W00000000-T000) OpenGL: X.Org -- Gallium 0.4 on AMD RS880 (DRM 2.50.0 / 4.13.0-16-generic, LLVM 4.0.0) -- 3.0 Mesa 17.0.7 -- texture_from_pixmap
WR? WR-
ProductID: {ec8030f7-c20a-464f-9b0e-13a3a9e97384}
ProductName: Firefox
ReleaseChannel: release
SafeMode: 0
SecondsSinceLastCrash: 302
StackTraces:
StartupCrash: 0
StartupTime: 1510735920
TelemetryEnvironment: {"build":{"applicationId":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","applicationName":"Firefox","architecture":"x86-64","buildId":"20171003222101","version":"56.0","vendor":"Mozilla","platformVersion":"56.0","xpcomAbi":"x86_64-gcc3","hotfixVersion":null},"partner":{"distributionId":null,"distributionVersion":null,"partnerId":null,"distributor":null,"distributorChannel":null,"partnerNames":[]},"system":{"memoryMB":7727,"virtualMaxMB":null,"cpu":{"count":4,"cores":4,"vendor":"AuthenticAMD","family":16,"model":5,"stepping":3,"l2cacheKB":512,"l3cacheKB":512,"speedMHz":3100,"extensions":["hasMMX","hasSSE","hasSSE2","hasSSE3"]},"os":{"name":"Linux","version":"4.13.0-16-generic","locale":"en-US"},"hdd":{"profile":{"model":null,"revision":null},"binary":{"model":null,"revision":null},"system":{"model":null,"revision":null}},"gfx":{"D2DEnabled":null,"DWriteEnabled":null,"ContentBackend":"Skia","adapters":[{"description":"X.Org -- Gallium 0.4 on AMD RS880 (DRM 2.50.0 / 4.13.0-16-generic, LLVM 4.0.0)","vendorID":"X.Org","deviceID":"Gallium 0.4 on AMD RS880 (DRM 2.50.0 / 4.13.0-16-generic, LLVM 4.0.0)","subsysID":null,"RAM":null,"driver":null,"driverVersion":"3.0 Mesa 17.0.7","driverDate":null,"GPUActive":true}],"monitors":[],"features":{"compositor":"none","gpuProcess":{"status":"unused"}}}},"settings":{"blocklistEnabled":true,"e10sEnabled":true,"e10sMultiProcesses":1,"e10sCohort":"addons-set50allmpc-test","telemetryEnabled":false,"locale":"en-US","update":{"channel":"release","enabled":true,"autoDownload":true},"userPrefs":{"browser.cache.disk.capacity":358400,"browser.newtabpage.enhanced":true},"sandbox":{"effectiveContentProcessLevel":2},"addonCompatibilityCheckEnabled":true,"isDefaultBrowser":null},"profile":{},"experiments":{"clicktoplay-rollout":{"branch":"user-changed-from-test"},"e10sCohort":{"branch":"addons-set50allmpc-test"}}}
Theme: classic/1.0
ThreadIdNameMapping: 13144:"Gecko_IOThread",13145:"Timer",13146:"Link Monitor",13147:"Socket Thread",13148:"JS Watchdog",13158:"Hang Monitor",13161:"Cache2 I/O",13162:"GMPThread",13164:"SoftwareVsyncThread",13165:"Compositor",13166:"ImgDecoder #1",13167:"ImgDecoder #2",13168:"ImgDecoder #3",13169:"ImageIO",13170:"SysProxySetting",13171:"ProxyResolution",13172:"DataStorage",13173:"URL Classifier",13174:"DNS Resolver #1",13175:"DataStorage",13176:"DataStorage",13177:"HTML5 Parser",13178:"IPDL Background",13179:"Classifier Update",13182:"DOM Worker",13184:"DOM Worker",13186:"StreamTrans #5",13187:"StreamTrans #6",13188:"StreamTrans #7",13192:"ImageBridgeChild",13194:"ProcessHangMon",
Throttleable: 1
UptimeTS: 1.6526776
Vendor: Mozilla
Version: 56.0
useragent_locale: en-US

This report also contains technical information about the state of the application when it crashed.


问:
I can't deploy to the device in Xcode
Xcode doesn't let me choose "Device". I only deploy to simulator, to iPad 3.2. Organizer tells me: "XCode cannot find the software image to install this version" when I connect an iPhone 3.1.3 firmware.

I have Xcode 3.2.5 with iOS 4.2. What can I do to solve this?

答: You need to upgrade your phone to 4.2, because you can only deploy to iphone versions where you have the sdk from.</p>

Title: I can't deploy to the device in Xcode


问:
Puppeteer: How to handle multiple tabs?
Scenario: Web form for developer app registration with two part workflow.

Page 1: Fill out developer app details and click on button to create Application ID, which opens, in a new tab...

Page 2: The App ID page. I need to copy the App ID from this page, then close the tab and go back to Page 1 and fill in the App ID (saved from Page 2), then submit the form.

I understand basic usage - how to open Page 1 and click the button which opens Page 2 - but how do I get a handle on Page 2 when it opens in a new tab?

Example:

```<code>const puppeteer = require('puppeteer');

(async() => {
    const browser = await puppeteer.launch({headless: false, executablePath: '/Applications/Google Chrome.app'});
    const page = await browser.newPage();

    // go to the new bot registration page
    await page.goto('https://register.example.com/new', {waitUntil: 'networkidle'});

    // fill in the form info
    const form = await page.$('new-app-form');

    await page.focus('#input-appName');
    await page.type('App name here');

    await page.focus('#input-appDescription');
    await page.type('short description of app here');

    await page.click('.get-appId'); //opens new tab with Page 2

    // handle Page 2
    // get appID from Page 2
    // close Page 2

    // go back to Page 1
    await page.focus('#input-appId');
    await page.type(appIdSavedFromPage2);

    // submit the form
    await form.evaluate(form => form.submit());

    browser.close();
})();
</code>```

Update 2017-10-25

The work for Browser.pages has been completed and merged

Fixes Emit new Page objects when new tabs created #386 and Request: browser.currentPage() or similar way to access Pages #443.

Still looking for a good usage example.

答:
In theory, you could override the window.open function to always open "new tabs" on your current page and navigate via history.

Your workflow would then be:

Override the window.open function:

```<code>await page.evaluateOnNewDocument(() => {
  window.open = (url) => {
    top.location = url
  }
})
</code>```

Go to your first page and perform some actions:

```<code>await page.goto(PAGE1_URL)
// ... do stuff on page 1
</code>```

Navigate to your second page by clicking the button and perform some actions there:

```<code>await page.click('#button_that_opens_page_2')
await page.waitForNavigation()
// ... do stuff on page 2, extract any info required on page 1
// e.g. const handle = await page.evaluate(() => { ... })
</code>```

Return to your first page:

```<code>await page.goBack()
// or: await page.goto(PAGE1_URL)
// ... do stuff on page 1, injecting info saved from page 2
</code>```

This approach, obviously, has its drawbacks, but I find it simplifies multi-tab navigation drastically, which is especially useful if you're running parallel jobs on multiple tabs already. Unfortunately, current API doesn't make it an easy task.

Title: Puppeteer: How to handle multiple tabs?

Body:
Scenario: Web form for developer app registration with two part workflow.

Page 1: Fill out developer app details and click on button to create Application ID, which opens, in a new tab...

Page 2: The App ID page. I need to copy the App ID from this page, then close the tab and go back to Page 1 and fill in the App ID (saved from Page 2), then submit the form.

I understand basic usage - how to open Page 1 and click the button which opens Page 2 - but how do I get a handle on Page 2 when it opens in a new tab?

Example:

const puppeteer = require('puppeteer');

(async() => {
    const browser = await puppeteer.launch({headless: false, executablePath: '/Applications/Google Chrome.app'});
    const page = await browser.newPage();

    // go to the new bot registration page
    await page.goto('https://register.example.com/new', {waitUntil: 'networkidle'});

    // fill in the form info
    const form = await page.$('new-app-form');

    await page.focus('#input-appName');
    await page.type('App name here');

    await page.focus('#input-appDescription');
    await page.type('short description of app here');

    await page.click('.get-appId'); //opens new tab with Page 2

    // handle Page 2
    // get appID from Page 2
    // close Page 2

    // go back to Page 1
    await page.focus('#input-appId');
    await page.type(appIdSavedFromPage2);

    // submit the form
    await form.evaluate(form => form.submit());

    browser.close();
})();

Update 2017-10-25

The work for Browser.pages has been completed and merged

Fixes Emit new Page objects when new tabs created #386 and Request: browser.currentPage() or similar way to access Pages #443.

Still looking for a good usage example.

Body:
In theory, you could override the window.open function to always open "new tabs" on your current page and navigate via history.

Your workflow would then be:

Override the window.open function:

await page.evaluateOnNewDocument(() => {
  window.open = (url) => {
    top.location = url
  }
})

Go to your first page and perform some actions:

await page.goto(PAGE1_URL)
// ... do stuff on page 1

Navigate to your second page by clicking the button and perform some actions there:

await page.click('#button_that_opens_page_2')
await page.waitForNavigation()
// ... do stuff on page 2, extract any info required on page 1
// e.g. const handle = await page.evaluate(() => { ... })

Return to your first page:

await page.goBack()
// or: await page.goto(PAGE1_URL)
// ... do stuff on page 1, injecting info saved from page 2

This approach, obviously, has its drawbacks, but I find it simplifies multi-tab navigation drastically, which is especially useful if you're running parallel jobs on multiple tabs already. Unfortunately, current API doesn't make it an easy task.


问:
HttpContext in .net standard library
I am working on couple of projects one of which is an ASP.NET 4.5 application and other one is .Net Core API 1.1 project. The asp.net application is using HttpContext classes to read cookies and page headers. Now, I need to move this to a .net standard library which can be used by both the project. I don't find HttpContext in .net standard SDK. Any suggestions?

答:
I need to move this [read cookies and page headers] to a .NET standard library which can be used by both the project...

Do NOT do this.

Let's assume you're performing an operation X on the data you read from the cookies. You may move this operation X to the library instead. The job of the ASP.NET projects is to handle the request pipeline. Reading the cookies belongs there.

Title: HttpContext in .net standard library


问:
unix mv --backup=numbered
I'm trying in php to move a folder but keep both files in the dest folder if exist duplicate.
i tried todo that in recursion but its too complicated so many things can go wrong for example file premissions and duplicate files\folders.

im trying to work with system() command and i cant figure out how to move files but keep backup if duplicate without destroying the extension

```<code>$last_line = system('mv --backup=t websites/test/ websites/test2/', $retval);
</code>```

gives the following if file exist in both dirs:

```<code>ajax.html~
ajax.html~1
ajax.html~2
</code>```

what im looking for is:

```<code>ajax~.html
ajax~1.html
ajax~2.html
</code>```

or any other like (1), (2) ... but without ruining the extension of the file.
any ideas? please.

p.s must use the system() command.

答:
I am not responding strictly to your question, but the case I am presenting here is very common and therefore valid!

Here's my hack!

TO USE WITH FILES:

```<code>#!/bin/bash

# It will find all the files according to the arguments in
# "<YOUR_ARGUMENT_TO_FIND_FILES>" ("find" command) and move them to the
# "<DEST_FOLDER>" folder. Files with the same name will follow the pattern:
# "same_name.ext", "same_name (1).ext", "same_name (2).ext",
# "same_name (3).ext"...

cd <YOUR_TARGET_FOLDER>
mkdir ./<DEST_FOLDER>
find ./ -iname "<YOUR_ARGUMENT_TO_FIND_FILES>" -type f -print0 | xargs -0 -I "{}" sh -c 'cp --backup=numbered "{}" "./<DEST_FOLDER>/" && rm -f "{}"'
cd ./<DEST_FOLDER>
for f_name in *.~*~; do
    f_bak_ext="${f_name##*.}"
    f_bak_num="${f_bak_ext//[^0-9]/}"
    f_orig_name="${f_name%.*}"
    f_only_name="${f_orig_name%.*}"
    f_only_ext="${f_orig_name##*.}"
    mv "$f_name" "$f_only_name ($f_bak_num).$f_only_ext"
done
cd ..
</code>```

TO USE WITH FOLDERS:

```<code>#!/bin/bash

# It will find all the folders according to the arguments in
# "<YOUR_ARGUMENT_TO_FIND_FOLDERS>" ("find" command) and move them to the
# "<DEST_FOLDER>" folder. Folders with the same name will have their contents
# merged, however files with the same name WILL NOT HAVE DUPLICATES (example:
# "same_name.ext", "same_name (1).ext", "same_name (2).ext",
# "same_name (3).ext"...).

cd <YOUR_TARGET_FOLDER>
find ./ -path "./<DEST_FOLDER>" -prune -o -iname "<YOUR_ARGUMENT_TO_FIND_FOLDERS>" -type d -print0 | xargs -0 -I "{}" sh -c 'rsync -a "{}" "./<DEST_FOLDER>/" && rm -rf "{}"'
</code>```

Title: unix mv --backup=numbered

Body:
I'm trying in php to move a folder but keep both files in the dest folder if exist duplicate.
i tried todo that in recursion but its too complicated so many things can go wrong for example file premissions and duplicate files\folders.

im trying to work with system() command and i cant figure out how to move files but keep backup if duplicate without destroying the extension

$last_line = system('mv --backup=t websites/test/ websites/test2/', $retval);

gives the following if file exist in both dirs:

ajax.html~
ajax.html~1
ajax.html~2

what im looking for is:

ajax~.html
ajax~1.html
ajax~2.html

or any other like (1), (2) ... but without ruining the extension of the file.
any ideas? please.

p.s must use the system() command.

Body:
I am not responding strictly to your question, but the case I am presenting here is very common and therefore valid!

Here's my hack!

TO USE WITH FILES:

#!/bin/bash

# It will find all the files according to the arguments in
# "<YOUR_ARGUMENT_TO_FIND_FILES>" ("find" command) and move them to the
# "<DEST_FOLDER>" folder. Files with the same name will follow the pattern:
# "same_name.ext", "same_name (1).ext", "same_name (2).ext",
# "same_name (3).ext"...

cd <YOUR_TARGET_FOLDER>
mkdir ./<DEST_FOLDER>
find ./ -iname "<YOUR_ARGUMENT_TO_FIND_FILES>" -type f -print0 | xargs -0 -I "{}" sh -c 'cp --backup=numbered "{}" "./<DEST_FOLDER>/" && rm -f "{}"'
cd ./<DEST_FOLDER>
for f_name in *.~*~; do
    f_bak_ext="${f_name##*.}"
    f_bak_num="${f_bak_ext//[^0-9]/}"
    f_orig_name="${f_name%.*}"
    f_only_name="${f_orig_name%.*}"
    f_only_ext="${f_orig_name##*.}"
    mv "$f_name" "$f_only_name ($f_bak_num).$f_only_ext"
done
cd ..

TO USE WITH FOLDERS:

#!/bin/bash

# It will find all the folders according to the arguments in
# "<YOUR_ARGUMENT_TO_FIND_FOLDERS>" ("find" command) and move them to the
# "<DEST_FOLDER>" folder. Folders with the same name will have their contents
# merged, however files with the same name WILL NOT HAVE DUPLICATES (example:
# "same_name.ext", "same_name (1).ext", "same_name (2).ext",
# "same_name (3).ext"...).

cd <YOUR_TARGET_FOLDER>
find ./ -path "./<DEST_FOLDER>" -prune -o -iname "<YOUR_ARGUMENT_TO_FIND_FOLDERS>" -type d -print0 | xargs -0 -I "{}" sh -c 'rsync -a "{}" "./<DEST_FOLDER>/" && rm -rf "{}"'


问:
Linux rename files before directories
I have the following command that I run to lowercase files/directories, replace . with _ and various other manipulations.  The problem with it is that it seems to try to rename the directories first and then it cannot find the files below it. Is there a way to rename all files in a directory first then the directory itself recursively?  e.g.

directory1

file1

file2

directory1

file1

file2

directory2

file1

directory2

file1

file2

My code is

```<code>while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done < <(find . -iname '*' -print0)
</code>```

答:
Here is sample UNTESTED code using recursion :</p>

```<code>recurse()
{
for entry in "$1"/*; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      recurse $entry
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done
}

recurse "/home"
</code>```

Title: Linux rename files before directories

Body:
I have the following command that I run to lowercase files/directories, replace . with _ and various other manipulations.  The problem with it is that it seems to try to rename the directories first and then it cannot find the files below it. Is there a way to rename all files in a directory first then the directory itself recursively?  e.g.

directory1

file1

file2

directory1

file1

file2

directory2

file1

directory2

file1

file2

My code is

while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done < <(find . -iname '*' -print0)

Body:
Here is sample UNTESTED code using recursion :

recurse()
{
for entry in "$1"/*; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      recurse $entry
      rename  'y/A-Z/a-z/; s/ /_/g; s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   else
      rename  'y/A-Z/a-z/; s/\.(?=.*\.)/_/g; s/ /_/g;  s/_-_/-/g; s/sometext//g; s/_extras/-extras/g' "$entry"
   fi
done
}

recurse "/home"


答:
Here is one way with conditional aggregation, Rextester:</p>

```<code>select
    user_id
    ,MAX(case when '2017-11-17'-visit_date <=30
          then 1
          else 0
     end) as last_30
    ,MAX(case when '2017-11-17'-visit_date >=31
               and '2017-11-17'-visit_date <=60
          then 1
          else 0
     end) as between_31_60
    ,MAX(case when '2017-11-17'-visit_date >=61
              and '2017-11-17'-visit_date <=90
          then 1
          else 0
     end) as between_61_90
from
    visits
group by user_id
order by user_id
</code>```

Title: What is the most performant way to rewrite a correlated subquery in the SELECT clause?

Body:
I am trying to count whether a user has visited a site in three time ranges:

last 30 days

between 31 and 60 days

between 61 and 90 days

I am using Netezza, which does NOT support correlated subqueries in the SELECT clause. See Rextester for successful query that must be re-written to NOT use a correlated subquery: http://rextester.com/JGR62033

Sample Data:

| user_id | last_visit | num_days_since_2017117 |
|---------|------------|------------------------|
| 1234    | 2017-11-02 | 15.6                   |
| 1234    | 2017-09-30 | 48.6                   |
| 1234    | 2017-09-03 | 75.0                   |
| 1234    | 2017-08-21 | 88.0                   |
| 9876    | 2017-10-03 | 45.0                   |
| 9876    | 2017-07-20 | 120.0                  |
| 5545    | 2017-09-15 | 63.0                   |

Desired Output:

| user_id | last_30 | btwn_31_60 | btwn_61_90 |
|---------|---------|------------|------------|
| 1234    | 1       | 1          | 1          |
| 5545    | 0       | 0          | 1          |
| 9876    | 0       | 1          | 0          |

Body:
Here is one way with conditional aggregation, Rextester:

select
    user_id
    ,MAX(case when '2017-11-17'-visit_date <=30
          then 1
          else 0
     end) as last_30
    ,MAX(case when '2017-11-17'-visit_date >=31
               and '2017-11-17'-visit_date <=60
          then 1
          else 0
     end) as between_31_60
    ,MAX(case when '2017-11-17'-visit_date >=61
              and '2017-11-17'-visit_date <=90
          then 1
          else 0
     end) as between_61_90
from
    visits
group by user_id
order by user_id


问:
Run Meteor as a Daemon process
I've just setup a Linux CentOS server to run a Meteor application.

The first problem I come across now is starting the meteor process as a Daemon, so it's running in background and I can exit my SSH session.. When starting with meteor --production I can't.

When using Ruby on Rails I could just start with rails s -d -p 80 and exit.

I found out that an app called screen and echo "meteor --production" | at are options, but I do not have the at command installed, and installing an app just for running it in background seems like a weird choice.

Do I really need to install screen or at? Are there any other options?

答:
You can use the following shell command

```<code>$ ROOT_URL="http://yourserver.com" nohup meteor --production -p 8085 >meteor.log 2>meteor.error.log &
</code>```

Replace 8085 with the port that you want to run it on.
If you are running your own mongo instance and do not want to use meteor's bundled mongo, you can also add the MONGO_URL="mongodb://yourserver:port/"

Title: Run Meteor as a Daemon process

Body:
You can use the following shell command

$ ROOT_URL="http://yourserver.com" nohup meteor --production -p 8085 >meteor.log 2>meteor.error.log &

Replace 8085 with the port that you want to run it on.
If you are running your own mongo instance and do not want to use meteor's bundled mongo, you can also add the MONGO_URL="mongodb://yourserver:port/"


问:
sql delete cascade not working
I have a Microsoft SQL Database with 2 tables: dog and cat.

"dog" table has a primary key column called "food", which is related to a column called "food" as well in the "cat" table, which acts as the foreign key.

The relationship between the tables has an "on delete cascade" rule set, so when I delete a row from "dog" table, the relveant rows from "cat" table should be deleted as well.

But the rows in "cat" table do net get deleted, they stay. I use the Microsoft SQL Database manager to delete the row in "dog" table.

Any idea why this happens? do I need to use a special delete sql command to delete a row in this manner?

//edit

the script for the tables is:

```<code>USE [VELES]
GO
/****** Object:  Table [dbo].[Periods]    Script Date: 01/18/2011 14:52:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Periods](
    [PeriodID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [PeriodName] [nvarchar](50) COLLATE Hebrew_CS_AS NULL,
    [PeriodStartDate] [smalldatetime] NOT NULL,
    [PeriodEndDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_Periods] PRIMARY KEY CLUSTERED
(
    [PeriodID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

USE [VELES]
GO
/****** Object:  Table [dbo].[Exams]    Script Date: 01/18/2011 14:55:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Exams](
    [ExamID] [int] IDENTITY(1,1) NOT NULL,
    [ExamUserID] [char](7) COLLATE Hebrew_CS_AS NOT NULL,
    [ExamBase] [tinyint] NOT NULL,
    [ExamUserTimesAccessed] [tinyint] NULL,
    [ExamMaxTimesToOpen] [tinyint] NOT NULL,
    [ExamUserLastTimeOpened] [datetime] NULL,
    [ExamUserLastTimeFinished] [datetime] NULL,
    [ExamTimeToFinish] [int] NOT NULL,
    [ExamPassGrade] [int] NOT NULL,
    [ExamPeriod] [int] NOT NULL,
    [ExamUserRank] [tinyint] NULL,
 CONSTRAINT [PK_Exams] PRIMARY KEY CLUSTERED
(
    [ExamID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
USE [VELES]
GO
ALTER TABLE [dbo].[Exams]  WITH CHECK ADD  CONSTRAINT [FK_Exams_Bases] FOREIGN KEY([ExamBase])
REFERENCES [dbo].[Bases] ([BaseID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Exams]  WITH NOCHECK ADD  CONSTRAINT [FK_Exams_Periods] FOREIGN KEY([ExamPeriod])
REFERENCES [dbo].[Periods] ([PeriodID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Exams]  WITH NOCHECK ADD  CONSTRAINT [FK_Exams_Users] FOREIGN KEY([ExamUserID])
REFERENCES [dbo].[Users] ([UserID])
ON UPDATE CASCADE
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[Exams] CHECK CONSTRAINT [FK_Exams_Users]
GO
ALTER TABLE [dbo].[Exams]  WITH CHECK ADD  CONSTRAINT [UserRanks_Exams_FK1] FOREIGN KEY([ExamUserRank])
REFERENCES [dbo].[UserRanks] ([RankID])
ON UPDATE CASCADE
ON DELETE CASCADE
</code>```

答:
I've solved the problem.

In the relationship window, there was an option called Enforce Foreign Key Constraint, which was set to "No".
I set it to "Yes" and now row deletion works well.

Title: sql delete cascade not working

Body:
I have a Microsoft SQL Database with 2 tables: dog and cat.

"dog" table has a primary key column called "food", which is related to a column called "food" as well in the "cat" table, which acts as the foreign key.

The relationship between the tables has an "on delete cascade" rule set, so when I delete a row from "dog" table, the relveant rows from "cat" table should be deleted as well.

But the rows in "cat" table do net get deleted, they stay. I use the Microsoft SQL Database manager to delete the row in "dog" table.

Any idea why this happens? do I need to use a special delete sql command to delete a row in this manner?

//edit

the script for the tables is:

USE [VELES]
GO
/****** Object:  Table [dbo].[Periods]    Script Date: 01/18/2011 14:52:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Periods](
    [PeriodID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    [PeriodName] [nvarchar](50) COLLATE Hebrew_CS_AS NULL,
    [PeriodStartDate] [smalldatetime] NOT NULL,
    [PeriodEndDate] [smalldatetime] NOT NULL,
 CONSTRAINT [PK_Periods] PRIMARY KEY CLUSTERED
(
    [PeriodID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

USE [VELES]
GO
/****** Object:  Table [dbo].[Exams]    Script Date: 01/18/2011 14:55:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Exams](
    [ExamID] [int] IDENTITY(1,1) NOT NULL,
    [ExamUserID] [char](7) COLLATE Hebrew_CS_AS NOT NULL,
    [ExamBase] [tinyint] NOT NULL,
    [ExamUserTimesAccessed] [tinyint] NULL,
    [ExamMaxTimesToOpen] [tinyint] NOT NULL,
    [ExamUserLastTimeOpened] [datetime] NULL,
    [ExamUserLastTimeFinished] [datetime] NULL,
    [ExamTimeToFinish] [int] NOT NULL,
    [ExamPassGrade] [int] NOT NULL,
    [ExamPeriod] [int] NOT NULL,
    [ExamUserRank] [tinyint] NULL,
 CONSTRAINT [PK_Exams] PRIMARY KEY CLUSTERED
(
    [ExamID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
USE [VELES]
GO
ALTER TABLE [dbo].[Exams]  WITH CHECK ADD  CONSTRAINT [FK_Exams_Bases] FOREIGN KEY([ExamBase])
REFERENCES [dbo].[Bases] ([BaseID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Exams]  WITH NOCHECK ADD  CONSTRAINT [FK_Exams_Periods] FOREIGN KEY([ExamPeriod])
REFERENCES [dbo].[Periods] ([PeriodID])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Exams]  WITH NOCHECK ADD  CONSTRAINT [FK_Exams_Users] FOREIGN KEY([ExamUserID])
REFERENCES [dbo].[Users] ([UserID])
ON UPDATE CASCADE
ON DELETE CASCADE
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[Exams] CHECK CONSTRAINT [FK_Exams_Users]
GO
ALTER TABLE [dbo].[Exams]  WITH CHECK ADD  CONSTRAINT [UserRanks_Exams_FK1] FOREIGN KEY([ExamUserRank])
REFERENCES [dbo].[UserRanks] ([RankID])
ON UPDATE CASCADE
ON DELETE CASCADE


问:
assembly bootloader won't jump to kernel
I have made a basic bootloader in assembly, but it doesn't actually jump to the kernel. It just says "Booting...". I'm sure it's just some silly mistake I made, like jumping to the wrong place. It should show an output like "Booting... Loaded!". I've also tried setting es to 0 before loading it, but even that doesn't work. Here's my code:

```<code>mov ax, 9ch
mov ss, ax
mov sp, 4096d
mov ax, 7c0h
mov ds, ax
mov es, ax

xor ah, ah
int 13h

clc

mov si, msg2
call print

mov ah, 02h
xor ax, ax
mov es, ax
mov bx, 0x7E00
mov al, 1h
mov ch, 0
mov cl, 2h
mov dh, 0
int 13h

jc error

jmp 0x7E00

mov si, msg3
call print

error:
mov si, msg
call print
hlt

print:
lodsb
cmp al, 0
jz done
mov ah, 0eh
int 10h
jmp print
done:
ret

msg db "An error occured!!", 0
msg2 db "Booting...", 0
msg3 db "Did not jump to kernel correctly!"

times 510-($-$$) db 0
dw 0xAA55

mov si, msgloaded
call printl
jmp $

printl:
lodsb
cmp al, 0
jz donel
mov ah, 0eh
int 10h
jmp print
donel:
ret

msgloaded db "Loaded!", 0

times 0x400-($-$$) db 0
</code>```

All help is appreciated. I will credit anyone who can help me. Thanks!

答:
For high level languages there's lots of clues about what the programmer intended contained in the structure loops, how variable names were chosen, defines/enums, etc; and it's easy to write maintainable code without comments.

For assembly language there's no well chosen variable names and no variable types (e.g. ax doesn't tell the reader if it's a pointer to a string or a giraffe's height or ...), instructions often don't show the intent (e.g. lea might be used to multiply by a constant and might not be used to load an effective address), control flow is far more flexible (e.g. something like a do(condition1) { } while(condition2) is perfectly fine) and goto (both jmp and conditional branches like jc) are used a lot.

For this reason, well written/maintainable assembly language uses lots of comments. More specifically, you'd use comments on the right hand side to describe your intentions. This allows you to check if the intentions are correct by reading comments, and then check if the intention is implemented correctly by comparing the instruction on each line with it's comment. It makes it much easier to avoid bugs, and much easier to find bugs.

Here's the first half of your code with comments:

```<code>;Memory Layout
;
; 0x009C:0x1000 = 0x000019C0 = stack top
; 0x07C0:0x0000 = 0x00007C00 = load address
; 0x0000:0x7E00 = 0x00007E00 = kernel address

%define STACK_SEGMENT      0x009C
%define STACK_TOP_OFFSET   0x1000
%define LOAD_SEGMENT       0x07C0
%define KERNEL_SEGMENT     0x0000
%define KERNEL_OFFSET      0x7E00

;_______________________________________________

;Entry point
;
;Input
; dl = BIOS boot device number

    mov ax, STACK_SEGMENT
    mov ss, ax
    mov sp, STACK_TOP_OFFSET
    mov ax, LOAD_SEGMENT
    mov ds, ax
    mov es, ax

;Reset disk system
;
;Note: This should be completely unnecessary. We know the BIOS
;      disk services are working correctly and don't need
;      to be reset because the BIOS just used it successfully
;      to load this code into memory.

    xor ah, ah            ;ah = BIOS "reset disk system" function number
    int 13h               ;Call BIOS disk services
    clc                   ;Unnecessary

;Display welcome message

    mov si, msg2
    call print

;Load kernel from disk
; dl = BIOS boot device number

    mov ah, 02h           ;ah = BIOS "read sectors" function number
    xor ax, ax            ;ax = KERNEL_SEGMENT
    mov es, ax
    mov bx, KERNEL_OFFSET ;es:bx = address to load kernel
    mov al, 1h            ;al = number of sectors to read
    mov ch, 0             ;ch = cylinder number for first sector
    mov cl, 2h            ;cl = sector number for first sector
    mov dh, 0             ;dh = head number for first sector
    int 13h               ;Call BIOS disk services

    jc error              ;Handle error if there was one

;Pass control to "kernel"

    jmp KERNEL_SEGMENT:KERNEL_OFFSET
</code>```

Here's the part that makes your bug obvious:

```<code>                          ;ah = BIOS "read sectors" function number
                          ;ax = KERNEL_SEGMENT
</code>```

Essentially, if you commented your code properly, you would've noticed that loading KERNEL_SEGMENT into ax overwrites the BIOS function number (which was in the highest 8 bits of ax). This causes this piece of code to call the BIOS "reset disk system" function and not load anything from disk at all. When it jumps to where the kernel should've been loaded (but wasn't) later, that memory is probably still full of zeros because it hasn't been used, but memory full of zeros are decoded as add instructions by the CPU, so the CPU happily executes the add instructions for ages.

Note: There is another (unrelated) bug - your code to print strings uses lodsb which depends on the direction flag; but you don't do a cld instruction to set the direction flag, so depending on the (undefined) state the BIOS left this flag in, it could print garbage instead.

Body:
I have made a basic bootloader in assembly, but it doesn't actually jump to the kernel. It just says "Booting...". I'm sure it's just some silly mistake I made, like jumping to the wrong place. It should show an output like "Booting... Loaded!". I've also tried setting es to 0 before loading it, but even that doesn't work. Here's my code:

mov ax, 9ch
mov ss, ax
mov sp, 4096d
mov ax, 7c0h
mov ds, ax
mov es, ax

xor ah, ah
int 13h

clc

mov si, msg2
call print

mov ah, 02h
xor ax, ax
mov es, ax
mov bx, 0x7E00
mov al, 1h
mov ch, 0
mov cl, 2h
mov dh, 0
int 13h

jc error

jmp 0x7E00

mov si, msg3
call print

error:
mov si, msg
call print
hlt

print:
lodsb
cmp al, 0
jz done
mov ah, 0eh
int 10h
jmp print
done:
ret

msg db "An error occured!!", 0
msg2 db "Booting...", 0
msg3 db "Did not jump to kernel correctly!"

times 510-($-$$) db 0
dw 0xAA55

mov si, msgloaded
call printl
jmp $

printl:
lodsb
cmp al, 0
jz donel
mov ah, 0eh
int 10h
jmp print
donel:
ret

msgloaded db "Loaded!", 0

times 0x400-($-$$) db 0

All help is appreciated. I will credit anyone who can help me. Thanks!

Body:
For high level languages there's lots of clues about what the programmer intended contained in the structure loops, how variable names were chosen, defines/enums, etc; and it's easy to write maintainable code without comments.

For assembly language there's no well chosen variable names and no variable types (e.g. ax doesn't tell the reader if it's a pointer to a string or a giraffe's height or ...), instructions often don't show the intent (e.g. lea might be used to multiply by a constant and might not be used to load an effective address), control flow is far more flexible (e.g. something like a do(condition1) { } while(condition2) is perfectly fine) and goto (both jmp and conditional branches like jc) are used a lot.

For this reason, well written/maintainable assembly language uses lots of comments. More specifically, you'd use comments on the right hand side to describe your intentions. This allows you to check if the intentions are correct by reading comments, and then check if the intention is implemented correctly by comparing the instruction on each line with it's comment. It makes it much easier to avoid bugs, and much easier to find bugs.

Here's the first half of your code with comments:

;Memory Layout
;
; 0x009C:0x1000 = 0x000019C0 = stack top
; 0x07C0:0x0000 = 0x00007C00 = load address
; 0x0000:0x7E00 = 0x00007E00 = kernel address

%define STACK_SEGMENT      0x009C
%define STACK_TOP_OFFSET   0x1000
%define LOAD_SEGMENT       0x07C0
%define KERNEL_SEGMENT     0x0000
%define KERNEL_OFFSET      0x7E00

;_______________________________________________

;Entry point
;
;Input
; dl = BIOS boot device number

    mov ax, STACK_SEGMENT
    mov ss, ax
    mov sp, STACK_TOP_OFFSET
    mov ax, LOAD_SEGMENT
    mov ds, ax
    mov es, ax

;Reset disk system
;
;Note: This should be completely unnecessary. We know the BIOS
;      disk services are working correctly and don't need
;      to be reset because the BIOS just used it successfully
;      to load this code into memory.

    xor ah, ah            ;ah = BIOS "reset disk system" function number
    int 13h               ;Call BIOS disk services
    clc                   ;Unnecessary

;Display welcome message

    mov si, msg2
    call print

;Load kernel from disk
; dl = BIOS boot device number

    mov ah, 02h           ;ah = BIOS "read sectors" function number
    xor ax, ax            ;ax = KERNEL_SEGMENT
    mov es, ax
    mov bx, KERNEL_OFFSET ;es:bx = address to load kernel
    mov al, 1h            ;al = number of sectors to read
    mov ch, 0             ;ch = cylinder number for first sector
    mov cl, 2h            ;cl = sector number for first sector
    mov dh, 0             ;dh = head number for first sector
    int 13h               ;Call BIOS disk services

    jc error              ;Handle error if there was one

;Pass control to "kernel"

    jmp KERNEL_SEGMENT:KERNEL_OFFSET

Here's the part that makes your bug obvious:

                          ;ah = BIOS "read sectors" function number
                          ;ax = KERNEL_SEGMENT

Essentially, if you commented your code properly, you would've noticed that loading KERNEL_SEGMENT into ax overwrites the BIOS function number (which was in the highest 8 bits of ax). This causes this piece of code to call the BIOS "reset disk system" function and not load anything from disk at all. When it jumps to where the kernel should've been loaded (but wasn't) later, that memory is probably still full of zeros because it hasn't been used, but memory full of zeros are decoded as add instructions by the CPU, so the CPU happily executes the add instructions for ages.

Note: There is another (unrelated) bug - your code to print strings uses lodsb which depends on the direction flag; but you don't do a cld instruction to set the direction flag, so depending on the (undefined) state the BIOS left this flag in, it could print garbage instead.


问:
How to test my blocking queue actually blocks
I have a blocking queue (it would be really hard for me to change its implementation), and I want to test that it actually blocks. In particular, the pop methods must block if the queue is empty and unblock as soon as a push is performed. See the following pseudo C++11 code for the test:

```<code>BlockingQueue queue; // empty queue

thread pushThread([]
{
    sleep(large_delay);
    queue.push();
});

queue.pop();
</code>```

Obviously it is not perfect, because it may happen that the whole thread pushThread is executed and terminates before pop is called, even if the delay is large, and the larger the delay the more I have to wait for the test being over.

How can I properly ensure that pop is executed before push is called and that is blocks until push returns?

答:
I do not believe this is possible without adding some extra state and interfaces to your BlockingQueue.

Proof goes something like this. You want to wait until the reading thread is blocked on pop. But there is no way to distinguish between that and the thread being about to execute the pop. This remains true no matter what you put just before or after the call to pop itself.

If you really want to fix this with 100% reliability, you need to add some state inside the queue, guarded by the queue's mutex, that means "someone is waiting". The pop call then has to update that state just before it atomically releases the mutex and goes to sleep on the internal condition variable. The push thread can obtain the mutex and wait until "someone is waiting". To avoid a busy loop here, you will want to use the condition variable again.

All of this machinery is nearly as complicated as the queue itself, so maybe you will want to test it, too... This sort of multi-threaded code is where concepts like "code coverage" -- and arguably even unit testing itself -- break down a bit. There are just too many possible interleavings of operations.

In practice, I would probably go with your original approach of sleeping.

Body:
I have a blocking queue (it would be really hard for me to change its implementation), and I want to test that it actually blocks. In particular, the pop methods must block if the queue is empty and unblock as soon as a push is performed. See the following pseudo C++11 code for the test:

BlockingQueue queue; // empty queue

thread pushThread([]
{
    sleep(large_delay);
    queue.push();
});

queue.pop();

Obviously it is not perfect, because it may happen that the whole thread pushThread is executed and terminates before pop is called, even if the delay is large, and the larger the delay the more I have to wait for the test being over.

How can I properly ensure that pop is executed before push is called and that is blocks until push returns?