问:
Should you always unpersist earlier cached rdds after you cache an rdd that appears later in the same lineage graph?
I have an rdd that I cache after loading data from s3, since I don't want to have to re-pull from s3 if I lose an executor. I then make a bunch of transformations on that rdd, and then cache again.

At this point, is there any reason to leave the first cached rdd in the cache? Will all later stages just pull from the more recently cached transformation if I don't use the earlier rdd again?

答:
I don't want to have to re-pull from s3 if I lose an executor.

Default caching variants don't protect you from executor loss. Spark provides replicated cache options (MEMORY_ONLY_SER_2, MEMORY_AND_DISK_SER_2, DISK_ONLY_2) which add some protection in case of node failure, but there more expensive than non-replicated variants.

is there any reason to leave the first cached rdd in the cache?

If the second one has been materialized then there is no reason to keep the first one, but LRU cleaner should be able to do handle this case without your help, if it is necessary.


来源: stackexchange

问:
Single SWF file for Flex 4 created apps?
I made an application in Flex 4. When I export a release build, it generates a whole bunch of files. (including the skins used, etc, etc.)

How do I make those plentiful files except the container HTML file, get compiled into a single SWF file?

E.g.,
My folder should only contain:

my_app.swf

my_app.html

But my_app.swf should still run like a normal Flex 4 app, only this time, all the files, images, skins, etc are inside that one SWF file.

Thanks to those who'd help!

答:
You will need to embed images in flex.For that refer http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf60546-7ff2.html.

That done, you will not need assets like images and sound files in the folder.They will already be embedded in your swf.
NOTE:This will increase the size of you swf drastically.

ContentLicense: CC BY-SA 2.5


问:
Unable to iterate result of splitting string in JavaScript
I have the following JavaScript code:

```<code>System.log( "inputExecArgs = " + inputExecArgs );
System.log( "Object.prototype.toString.call( inputExecArgs ) = " + Object.prototype.toString.call( inputExecArgs ) );

var inputTokens = inputExecArgs.split( "{" );
System.log( "inputTokens = " + inputTokens );

if ( inputTokens = null ){
    System.log( "inputTokens is null" );
}else{
    System.log( "inputTokens not null" );

    System.log( "Object.prototype.toString.call( inputTokens ) = " +     Object.prototype.toString.call( inputTokens ) );
Object.prototype.toString.call( inputTokens ) );

    System.log( "----- begin iterating through inputTokens -----" );
    for (var key in inputTokens) {
        //if (tokens.hasOwnProperty(key)) {
            System.log( key + " -> " + inputTokens[key] );
        //}
    }
    System.log( "----- end iterating through inputTokens -----" );

    var tokensLength = tokens.length
    System.log( "tokensLength = " + tokensLength );

}
</code>```

The iteration seems to not work and "inputTokens.length" results in an error:

```<code>inputExecArgs =  } {token1} {token2} {
Object.prototype.toString.call( inputExecArgs ) = [object String]
inputTokens =  } ,token1} ,token2} ,
inputTokens not null
Object.prototype.toString.call( inputTokens ) = [object Main]
----- begin iterating through inputTokens -----
----- end iterating through inputTokens -----
Error in (Workflow:Andrew.Parse_input_properties / parse string for curly bracket properties (item1)#37) ReferenceError: "tokens" is not defined.
Workflow execution stack:
***
item: 'Andrew.Parse_input_properties/item1', state: 'failed', business state: 'null', exception: 'ReferenceError: "tokens" is not defined. (Workflow:Andrew.Parse_input_properties / parse string for curly bracket properties (item1)#37)'
workflow: 'Andrew.Parse_input_properties' (d5f4738e-e947-45d2-a123-cc62696c1a31)
|  'input': name=inputExecArgs type=string value= } {token1} {token2} {
|  'output': name=outputExecArgs type=string value=null
|  'no attributes'
*** End of execution stack.
</code>```

I don't know if this matters but this is VMware vRO 7 which uses Rhino 1.7R4.

答:
You probably want to change this line:

```<code>if (inputTokens = null) {
</code>```

to, for example:

```<code>if (inputTokens.length > 0) {
</code>```

What you have right now literally assigns the value null to inputTokens, THEN results in a falsey value, so the else branch is taken.

As an aside, to compare with null, you could use the === operator. .split on a String will never result in null. If there are no tokens to split on (e.g. when the string is empty ""), the result is simply an empty array [].

ContentLicense: CC BY-SA 3.0

Body:
I have the following JavaScript code:

System.log( "inputExecArgs = " + inputExecArgs );
System.log( "Object.prototype.toString.call( inputExecArgs ) = " + Object.prototype.toString.call( inputExecArgs ) );

var inputTokens = inputExecArgs.split( "{" );
System.log( "inputTokens = " + inputTokens );

if ( inputTokens = null ){
    System.log( "inputTokens is null" );
}else{
    System.log( "inputTokens not null" );

    System.log( "Object.prototype.toString.call( inputTokens ) = " +     Object.prototype.toString.call( inputTokens ) );
Object.prototype.toString.call( inputTokens ) );

    System.log( "----- begin iterating through inputTokens -----" );
    for (var key in inputTokens) {
        //if (tokens.hasOwnProperty(key)) {
            System.log( key + " -> " + inputTokens[key] );
        //}
    }
    System.log( "----- end iterating through inputTokens -----" );

    var tokensLength = tokens.length
    System.log( "tokensLength = " + tokensLength );

}

The iteration seems to not work and "inputTokens.length" results in an error:

inputExecArgs =  } {token1} {token2} {
Object.prototype.toString.call( inputExecArgs ) = [object String]
inputTokens =  } ,token1} ,token2} ,
inputTokens not null
Object.prototype.toString.call( inputTokens ) = [object Main]
----- begin iterating through inputTokens -----
----- end iterating through inputTokens -----
Error in (Workflow:Andrew.Parse_input_properties / parse string for curly bracket properties (item1)#37) ReferenceError: "tokens" is not defined.
Workflow execution stack:
***
item: 'Andrew.Parse_input_properties/item1', state: 'failed', business state: 'null', exception: 'ReferenceError: "tokens" is not defined. (Workflow:Andrew.Parse_input_properties / parse string for curly bracket properties (item1)#37)'
workflow: 'Andrew.Parse_input_properties' (d5f4738e-e947-45d2-a123-cc62696c1a31)
|  'input': name=inputExecArgs type=string value= } {token1} {token2} {
|  'output': name=outputExecArgs type=string value=null
|  'no attributes'
*** End of execution stack.

I don't know if this matters but this is VMware vRO 7 which uses Rhino 1.7R4.

Body:
You probably want to change this line:

if (inputTokens = null) {

to, for example:

if (inputTokens.length > 0) {

What you have right now literally assigns the value null to inputTokens, THEN results in a falsey value, so the else branch is taken.

As an aside, to compare with null, you could use the === operator. .split on a String will never result in null. If there are no tokens to split on (e.g. when the string is empty ""), the result is simply an empty array [].


问:
Using Grep and Regex to generate a text file which lists all files that have specific strings in them
I am having trouble figuring out a very specific use case for Grep and Regex.  I have searched a lot and can't seem to find the answer.

I want to run Grep recursively from within a root directory which contains directories for hundreds of different programs.  I want the output to print to a text file and list the file names of all the files which match some regex.  Specifically, here's what I need to do in english:

find all files that contain the text [stringA] AND ["stringB"] OR ['stringB'] and print the file paths for each of these files to an output text file with some context added.  For the two stringB pieces, the quotes are important and I only want to find files that have stringB with single or double quotes around it.  In other words,

all files that contain stringA with no quotes and stringB with either single or double quotes.

Any help is appreciated, thanks!

Edit: Sorry for asking a terrible question :)

I have done some research and have figured out part of it.  I have figured out the regex for finding the string I am looking for.  The actual string is "ATA".  To find this globally, case-insensitive, and with either type of quotes around it with some or no whitespace on either side of the string, we can use:

```<code>/['"]\s*ATA\s*['"]/gi
</code>```

The first string I need to also find is a function call: call wflnkmod( and the regex for that is:

```<code>/call\swflnkmod\(/gi
</code>```

Now I just need to figure out how to search a file and ensure that it has an instance of each of these in it, then figure out the grep command to use to search all files recursively and print them to an output file!

答:
Solution

Should do the trick (<dir> needs to be replaced with the directory to search in):

```<code>grep -r -i -l "stringA" <dir> | xargs grep -i -l -E "'stringB'|\"stringB\""
</code>```

Explanation

The above line searches for stringA first. The resulting list of files is piped into xargs and the specified command (grep -i -l -E "'stringB'|\"stringB\"") is invoked with the additional parameters provided through stdin (the list of files, that contain stringA).

grep options:

-r, --recursive (self explanatory)

-i, --ignore-case search case insensitive

-l, --files-with-matches only print filename of files that match the
given pattern

-E interpret pattern as extended regular expression

The two main issues with the expressions you've tried are:

Inappropriate use of []. [] lets you define a character set, e.g. [abcd] matches one of specified characters.

Incorrect quoting  or escaping of quotes in your expressions. If you quote something in double quotes ("), double quotes inside the quoted string need to be escaped: \" yields a " in a quoted string. If you're not quoting your expression at all, ( needs to be escaped as well.

Body:
I am having trouble figuring out a very specific use case for Grep and Regex.  I have searched a lot and can't seem to find the answer.

I want to run Grep recursively from within a root directory which contains directories for hundreds of different programs.  I want the output to print to a text file and list the file names of all the files which match some regex.  Specifically, here's what I need to do in english:

find all files that contain the text [stringA] AND ["stringB"] OR ['stringB'] and print the file paths for each of these files to an output text file with some context added.  For the two stringB pieces, the quotes are important and I only want to find files that have stringB with single or double quotes around it.  In other words,

all files that contain stringA with no quotes and stringB with either single or double quotes.

Any help is appreciated, thanks!

Edit: Sorry for asking a terrible question :)

I have done some research and have figured out part of it.  I have figured out the regex for finding the string I am looking for.  The actual string is "ATA".  To find this globally, case-insensitive, and with either type of quotes around it with some or no whitespace on either side of the string, we can use:

/['"]\s*ATA\s*['"]/gi

The first string I need to also find is a function call: call wflnkmod( and the regex for that is:

/call\swflnkmod\(/gi

Now I just need to figure out how to search a file and ensure that it has an instance of each of these in it, then figure out the grep command to use to search all files recursively and print them to an output file!

Body:
Solution

Should do the trick (<dir> needs to be replaced with the directory to search in):

grep -r -i -l "stringA" <dir> | xargs grep -i -l -E "'stringB'|\"stringB\""

Explanation

The above line searches for stringA first. The resulting list of files is piped into xargs and the specified command (grep -i -l -E "'stringB'|\"stringB\"") is invoked with the additional parameters provided through stdin (the list of files, that contain stringA).

grep options:

-r, --recursive (self explanatory)

-i, --ignore-case search case insensitive

-l, --files-with-matches only print filename of files that match the
given pattern

-E interpret pattern as extended regular expression

The two main issues with the expressions you've tried are:

Inappropriate use of []. [] lets you define a character set, e.g. [abcd] matches one of specified characters.

Incorrect quoting  or escaping of quotes in your expressions. If you quote something in double quotes ("), double quotes inside the quoted string need to be escaped: \" yields a " in a quoted string. If you're not quoting your expression at all, ( needs to be escaped as well.


问:
Getting R printed texts to have color esp. in R markdown knits?
Very simple question: I love writing R notebooks/markdowns, and with something like highlight: tango I can give background color to codes when I knit my notebook to pdfs.

However, I don't know how to give colored backgrounds or colored fonts to printed outputs in R. For example, suppose I have the following chunk.

```<code>```{r, echo = FALSE}
writeLines("Help")
```
</code>```

I'd like to see the word Help to be highlighted, say in red font with gray background. How can I achieve this?

Many thanks in advance.

答:
with kableExtra, you can format your texts in R using text_spec

```<code>---
output: pdf_document
---

```{r}
library(kableExtra)
options(knitr.table.format = "latex")
```

`r text_spec("Help", color = "red")`

`r text_spec("Help Help", background = "#D05A6E", color = "white", bold = T)`

`r text_spec("Hello", font_size = 20)`

`r text_spec("World", angle = 180)`
</code>```

You get

Same goes for HTML

See more in the Cell/Text Specification of the package vignette.

Body:
Very simple question: I love writing R notebooks/markdowns, and with something like highlight: tango I can give background color to codes when I knit my notebook to pdfs.

However, I don't know how to give colored backgrounds or colored fonts to printed outputs in R. For example, suppose I have the following chunk.

```{r, echo = FALSE}
writeLines("Help")
```

I'd like to see the word Help to be highlighted, say in red font with gray background. How can I achieve this?

Many thanks in advance.

Body:
with kableExtra, you can format your texts in R using text_spec

---
output: pdf_document
---

```{r}
library(kableExtra)
options(knitr.table.format = "latex")
```

`r text_spec("Help", color = "red")`

`r text_spec("Help Help", background = "#D05A6E", color = "white", bold = T)`

`r text_spec("Hello", font_size = 20)`

`r text_spec("World", angle = 180)`

You get

Same goes for HTML

See more in the Cell/Text Specification of the package vignette.


问:
Angular, content type is not being sent with $http
Angular is not adding the correct content type option, I tried the following command:

$http({
    url: "http://localhost:8080/example/teste",
    dataType: "json",
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    }
}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});
```

<p>The code above generates the following http request:</p>

```POST http://localhost:8080/example/teste HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 0
Cache-Control: no-cache
Pragma: no-cache
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Content-Type: application/xml
Accept: application/json, text/plain, */*
X-Requested-With: XMLHttpRequest
Referer: http://localhost:8080/example/index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: JSESSIONID=C404CE2DA653136971DD1A3C3EB3725B
```

As you can see, instead of "application/json", the content type is "application/xml". Am I missing something here ?

答:
Just to show an example of how to dynamically add the "Content-type" header to every POST request. In may case I'm passing POST params as query string, that is done using the transformRequest. In this case its value is application/x-www-form-urlencoded.

```<code>// set Content-Type for POST requests
angular.module('myApp').run(basicAuth);
function basicAuth($http) {
    $http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
}
</code>```

Then from the interceptor in the request method before return the config object

```<code>// if header['Content-type'] is a POST then add data
'request': function (config) {
  if (
    angular.isDefined(config.headers['Content-Type'])
    && !angular.isDefined(config.data)
  ) {
    config.data = '';
  }
  return config;
}
</code>```

Body:
Angular is not adding the correct content type option, I tried the following command:

$http({
    url: "http://localhost:8080/example/teste",
    dataType: "json",
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    }
}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

The code above generates the following http request:

POST http://localhost:8080/example/teste HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 0
Cache-Control: no-cache
Pragma: no-cache
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Content-Type: application/xml
Accept: application/json, text/plain, */*
X-Requested-With: XMLHttpRequest
Referer: http://localhost:8080/example/index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: JSESSIONID=C404CE2DA653136971DD1A3C3EB3725B

As you can see, instead of "application/json", the content type is "application/xml". Am I missing something here ?

Body:
Just to show an example of how to dynamically add the "Content-type" header to every POST request. In may case I'm passing POST params as query string, that is done using the transformRequest. In this case its value is application/x-www-form-urlencoded.

// set Content-Type for POST requests
angular.module('myApp').run(basicAuth);
function basicAuth($http) {
    $http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
}

Then from the interceptor in the request method before return the config object

// if header['Content-type'] is a POST then add data
'request': function (config) {
  if (
    angular.isDefined(config.headers['Content-Type'])
    && !angular.isDefined(config.data)
  ) {
    config.data = '';
  }
  return config;
}


问:
Porting C++ to C# - templates
I'm porting a C++ application to C#, and have run across templates.  I've read up a little on these, and I understand that some templates are akin to .Net generics.  I read the SO answer to this case which nicely summed it up.

However, some uses of c++ templating don't seem to be directly related to generics.  In the below example from Wikipedia's Template metaprogramming article the template seems to accept a value, rather than a type.  I'm not quite sure how this would be ported to C#?

```<code>template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}
</code>```

Clearly for this example I could do:

```<code>public int Factorial(int N){
    if(N == 0) return 1;
    return Factorial(N - 1);
}
</code>```

but this seems to me to be a refactoring to a function, rather than a port to semantically similar code.

答:
In the below example … the template seems to accept a value, rather than a type.

This isn’t your biggest problem. In fact, this could theoretically be solved in C# by using a Church numeral or Peano representation relying on nested generic types.1

However, your problem is that C# doesn’t allow template specialization. Template specialization is responsible in your example for defining that the factorial of 0 is 1, rather than the same as for all other numbers. C# doesn’t allow doing that.

So there is no way to specify a base case in a recursive template (generic) definition and hence no recursion. C# generics aren’t Turing complete, whereas C++ templates are.

1 Something like this:

```<code>class Zero { }

class Successor<T> : Zero where T : Zero { }

// one:
Successor<Zero>
// two:
Successor<Successor<Zero>>
// etc.
</code>```

Implementing operations on these numbers is left as an exercise to the reader.

Title: Porting C++ to C# - templates

Body:
I'm porting a C++ application to C#, and have run across templates.  I've read up a little on these, and I understand that some templates are akin to .Net generics.  I read the SO answer to this case which nicely summed it up.

However, some uses of c++ templating don't seem to be directly related to generics.  In the below example from Wikipedia's Template metaprogramming article the template seems to accept a value, rather than a type.  I'm not quite sure how this would be ported to C#?

template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

Clearly for this example I could do:

public int Factorial(int N){
    if(N == 0) return 1;
    return Factorial(N - 1);
}

but this seems to me to be a refactoring to a function, rather than a port to semantically similar code.

Body:
In the below example … the template seems to accept a value, rather than a type.

This isn’t your biggest problem. In fact, this could theoretically be solved in C# by using a Church numeral or Peano representation relying on nested generic types.1

However, your problem is that C# doesn’t allow template specialization. Template specialization is responsible in your example for defining that the factorial of 0 is 1, rather than the same as for all other numbers. C# doesn’t allow doing that.

So there is no way to specify a base case in a recursive template (generic) definition and hence no recursion. C# generics aren’t Turing complete, whereas C++ templates are.

1 Something like this:

class Zero { }

class Successor<T> : Zero where T : Zero { }

// one:
Successor<Zero>
// two:
Successor<Successor<Zero>>
// etc.

Implementing operations on these numbers is left as an exercise to the reader.


问:
Vertically align select and number input in firefox
What can I do to have these inputs vertically aligned in Firefox?

It works in Chrome, Safari and Opera but not in Firefox (Version 57 tested in macOS, Windows and Linux Mint). Removing type="number" from the input solves it in Firefox but isn't something I want to remove.

label {
  display: inline-block;
}

.form-control {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <label>First number <input class="form-control" type="number"></label>
  <label>
    Dropdown
    <select class="form-control">
      <option label="First option" selected="selected">
        First option
      </option>
    </select>
  </label>
</body></code>```

答:
you need to reset the vertical-align property on your inline-block displayed elements.

label {
  display: inline-block;
  vertical-align: top;
}

.form-control {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <label>
     First number
     <input class="form-control" type="number">
  </label>
  <label>
    Dropdown
    <select class="form-control">
      <option label="First option" selected="selected">
        First option
      </option>
    </select>
  </label>
</body></code>```

Body:
What can I do to have these inputs vertically aligned in Firefox?

It works in Chrome, Safari and Opera but not in Firefox (Version 57 tested in macOS, Windows and Linux Mint). Removing type="number" from the input solves it in Firefox but isn't something I want to remove.

label {
  display: inline-block;
}

.form-control {
  display: block;
}

  First number <input class="form-control" type="number">

    Dropdown
    <select class="form-control">
      <option label="First option" selected="selected">
        First option
      </option>
    </select>

Body:
you need to reset the vertical-align property on your inline-block displayed elements.

label {
  display: inline-block;
  vertical-align: top;
}

.form-control {
  display: block;
}

<body>
  <label>
     First number
     <input class="form-control" type="number">
  </label>
  <label>
    Dropdown
    <select class="form-control">
      <option label="First option" selected="selected">
        First option
      </option>
    </select>
  </label>
</body>


问:
SQL query to include time segments with no counts
I am working in SQL Server 2014. I have table that records 'counts' and a timestamp of the count. The counting period is a two hour block that can start at any quarter hour. In the example data below, the count starts at 16:00 and goes through 18:00. The counting block could have started at 01:30 and stopped at 03:30.

```<code>Timestamp   Count
16:00:31    1
16:00:42    1
16:16:04    1
16:16:06    1
16:45:10    1
16:45:31    1
16:45:32    1
17:16:45    1
17:16:52    1
17:16:53    1
17:33:19    1
17:34:01    1
17:45:03    1
17:46:08    1
</code>```

I have a query which sums the counts over 15 minute intervals within the two hour block:

```<code>SELECT
    FORMAT(DATEPART(HOUR, [Timestamp]), '0#') + ':' + FORMAT(DATEPART(MINUTE, [TimeStamp]) / 15 * 15, '0#') AS QtrHrBeg
    , COUNT(*) AS CountTotal
FROM
    [Sandbox].[trippetoe].[SURVEYCOUNTS]
GROUP BY
    DATEPART(HOUR, [TIMESTAMP])
    , (DATEPART(MINUTE, [TIMESTAMP]) / 15 * 15)
</code>```

which results in this:

```<code>QtrHrBeg    Count
16:00   2
16:15   2
16:45   3
17:15   3
17:30   2
17:45   2
</code>```

I'd like to include 15 minute intervals where there are no counts - in this example the quarter hours beginning at 16:30 and 17:00, like below:

```<code>QtrHrBeg    Count
16:00   2
16:15   2
16:30   0
16:45   3
17:00   0
17:15   3
17:30   2
17:45   2
</code>```

How can i do that?

答:
See below.

Begin by creating a time table of all intervals for the day, then restricting that to the intervals for the 2 hour window you want.

Then left join that to the sum of your data table, pushing 0 where the join returns null.

```<code>DECLARE @Data TABLE ([TimeStamp] TIME, [Count] INT)
INSERT INTO @Data ([TimeStamp],[Count])
VALUES ('16:00:31',1),
       ('16:00:42',1),
       ('16:16:04',1),
       ('16:16:06',1),
       ('16:45:10',1),
       ('16:45:31',1),
       ('16:45:32',1),
       ('17:16:45',1),
       ('17:16:52',1),
       ('17:16:53',1),
       ('17:33:19',1),
       ('17:34:01',1),
       ('17:45:03',1),
       ('17:46:08',1)

;with AllIntervals AS
(
    SELECT CONVERT(TIME,'00:00:00') AS Interval
    UNION ALL
    SELECT DATEADD(MINUTE,15,Interval)
    FROM AllIntervals
    WHERE Interval<'23:45:00'
), MyIntervals AS
    (
        SELECT CONVERT(VARCHAR(5),Interval,108) AS Interval
        FROM AllIntervals
        WHERE Interval >= (SELECT MIN(CONVERT(TIME,DATEADD(minute,(DATEDIFF(minute,0,[TimeStamp])/15)*15,0))) FROM @Data)
          AND Interval < DATEADD(HOUR,2,(SELECT MIN(CONVERT(TIME,DATEADD(minute,(DATEDIFF(minute,0,[TimeStamp])/15)*15,0))) FROM @Data))
    )

SELECT M.Interval, ISNULL(I.[Count],0)
FROM MyIntervals M
LEFT JOIN (SELECT CONVERT(TIME,DATEADD(minute,(DATEDIFF(minute,0,[TimeStamp])/15)*15,0)) AS Interval, SUM([Count]) AS Count
           FROM @Data
           GROUP BY CONVERT(TIME,DATEADD(minute,(DATEDIFF(minute,0,[TimeStamp])/15)*15,0))) I
   ON M.Interval=I.Interval
</code>```

Body:
I am working in SQL Server 2014. I have table that records 'counts' and a timestamp of the count. The counting period is a two hour block that can start at any quarter hour. In the example data below, the count starts at 16:00 and goes through 18:00. The counting block could have started at 01:30 and stopped at 03:30.

Timestamp   Count
16:00:31    1
16:00:42    1
16:16:04    1
16:16:06    1
16:45:10    1
16:45:31    1
16:45:32    1
17:16:45    1
17:16:52    1
17:16:53    1
17:33:19    1
17:34:01    1
17:45:03    1
17:46:08    1

I have a query which sums the counts over 15 minute intervals within the two hour block:

SELECT
    FORMAT(DATEPART(HOUR, [Timestamp]), '0#') + ':' + FORMAT(DATEPART(MINUTE, [TimeStamp]) / 15 * 15, '0#') AS QtrHrBeg
    , COUNT(*) AS CountTotal
FROM
    [Sandbox].[trippetoe].[SURVEYCOUNTS]
GROUP BY
    DATEPART(HOUR, [TIMESTAMP])
    , (DATEPART(MINUTE, [TIMESTAMP]) / 15 * 15)

which results in this:

QtrHrBeg    Count
16:00   2
16:15   2
16:45   3
17:15   3
17:30   2
17:45   2

I'd like to include 15 minute intervals where there are no counts - in this example the quarter hours beginning at 16:30 and 17:00, like below:

QtrHrBeg    Count
16:00   2
16:15   2
16:30   0
16:45   3
17:00   0
17:15   3
17:30   2
17:45   2

How can i do that?

Body:
See below.

Begin by creating a time table of all intervals for the day, then restricting that to the intervals for the 2 hour window you want.

Then left join that to the sum of your data table, pushing 0 where the join returns null.

DECLARE @Data TABLE ([TimeStamp] TIME, [Count] INT)
INSERT INTO @Data ([TimeStamp],[Count])
VALUES ('16:00:31',1),
       ('16:00:42',1),
       ('16:16:04',1),
       ('16:16:06',1),
       ('16:45:10',1),
       ('16:45:31',1),
       ('16:45:32',1),
       ('17:16:45',1),
       ('17:16:52',1),
       ('17:16:53',1),
       ('17:33:19',1),
       ('17:34:01',1),
       ('17:45:03',1),
       ('17:46:08',1)

;with AllIntervals AS
(
    SELECT CONVERT(TIME,'00:00:00') AS Interval
    UNION ALL
    SELECT DATEADD(MINUTE,15,Interval)
    FROM AllIntervals
    WHERE Interval<'23:45:00'
), MyIntervals AS
    (
        SELECT CONVERT(VARCHAR(5),Interval,108) AS Interval
        FROM AllIntervals
        WHERE Interval >= (SELECT MIN(CONVERT(TIME,DATEADD(minute,(DATEDIFF(minute,0,[TimeStamp])/15)*15,0))) FROM @Data)
          AND Interval < DATEADD(HOUR,2,(SELECT MIN(CONVERT(TIME,DATEADD(minute,(DATEDIFF(minute,0,[TimeStamp])/15)*15,0))) FROM @Data))
    )

SELECT M.Interval, ISNULL(I.[Count],0)
FROM MyIntervals M
LEFT JOIN (SELECT CONVERT(TIME,DATEADD(minute,(DATEDIFF(minute,0,[TimeStamp])/15)*15,0)) AS Interval, SUM([Count]) AS Count
           FROM @Data
           GROUP BY CONVERT(TIME,DATEADD(minute,(DATEDIFF(minute,0,[TimeStamp])/15)*15,0))) I
   ON M.Interval=I.Interval


问:
SQL Server Data Tools (VS2017) Error with Data Flow Tasks
When adding any kind of data flow task or attempting to edit one on the design surface, I get the error

"The task with the name ... and the creation name "SSIS.Pipeline.6" is not registered for use on this computer. Contact Information: Data Flow Task"

Additionally, an error similar to the following is displayed for all properties of the data flow task:

"Could not get value for property '{1A11EC69-3AC7-475A-9E7A-B452B6BA6301}'. Specified cast is not valid."

I have looked in the GAC and there is no component with this CLSID, nor do I see it in the .dtproj file

Oddly enough, the package will run from the designer, but pops up an error message on every data flow task that says:

"This task does not have a custom editor. Use the Poperties window to edit properties of this task".

As long as I keep clicking it, it will continue through. Makes me think the issue is with SSDT or Integration Services, but I have uninstalled and reinstalled both. The issue with editing or viewing properties for a data flow task, however, persists :(

I have VS2015 on the same system, and it appears unaffected. Any idea how to correct this without a full wipe of VS2017?

答:
According to this Link, do the following steps to solve this:

open sql server configuration manager

choose sql server services

right click sql server integration services, choose properties

choose log on tab, select this account, enter your username and password which is used to log on your computer.

reopen the visual studio. There you are, the task component can work properly again.

If you are using a custom SSIS component then follow this Link


问:
Multiple where clauses and elimination
I'm trying to generate the count of unique drivers who have completed their trip and never cancel on the client. If a driver has ever canceled on any client they should be removed from the results.

I'm wondering if a subquery is needed here or not.
The data that I am working with is shown here and while rudimentary, it's simply to test my query.

```<code>id  driver_id   client_id   city_id status
1   1011        9004        546     completed
1   1011        9008        323     completed
2   1011        9001        546     completed
3   1011        9006        323     completed
3   1011        9007        154     cancelled_by_client
1   1012        9001        546     cancelled_by_client
2   1012        9003        123     cancelled_by_driver
2   1012        9002        789     completed
2   1013        9007        546     cancelled_by_driver
4   1013        9006        546     cancelled_by_driver
2   1015        9001        546     completed
3   1015        9006        323     completed
3   1015        9007        154     cancelled_by_client
</code>```

What I am after as my expected result is a count of the unique driver IDs that have both completed their trips and never canceled on the client (canceled_by_driver).

```<code>driver_id    non_driver_cancels
1011         1
1015         1
</code>```

I have a GROUP BY in here to show the data with more detail and I am seeing that driver 1012 has a canceled_by_driver but they are still in my results. From there I believe I can simply count the driver_id's and finish this task.

Any help is greatly appreciated.

http://sqlfiddle.com/#!9/ad7cca/7

答:
Try with this:</p>

```<code>SELECT driver_id, COUNT( DISTINCT driver_id) as Non_Driver_Cancel
FROM Trip
WHERE status NOT IN (SELECT DISTINCT status FROM Trip WHERE status <> 'cancelled_by_driver')
GROUP BY driver_id;
</code>```

Title: Multiple where clauses and elimination

Body:
I'm trying to generate the count of unique drivers who have completed their trip and never cancel on the client. If a driver has ever canceled on any client they should be removed from the results.

I'm wondering if a subquery is needed here or not.
The data that I am working with is shown here and while rudimentary, it's simply to test my query.

id  driver_id   client_id   city_id status
1   1011        9004        546     completed
1   1011        9008        323     completed
2   1011        9001        546     completed
3   1011        9006        323     completed
3   1011        9007        154     cancelled_by_client
1   1012        9001        546     cancelled_by_client
2   1012        9003        123     cancelled_by_driver
2   1012        9002        789     completed
2   1013        9007        546     cancelled_by_driver
4   1013        9006        546     cancelled_by_driver
2   1015        9001        546     completed
3   1015        9006        323     completed
3   1015        9007        154     cancelled_by_client

What I am after as my expected result is a count of the unique driver IDs that have both completed their trips and never canceled on the client (canceled_by_driver).

driver_id    non_driver_cancels
1011         1
1015         1

I have a GROUP BY in here to show the data with more detail and I am seeing that driver 1012 has a canceled_by_driver but they are still in my results. From there I believe I can simply count the driver_id's and finish this task.

Any help is greatly appreciated.

http://sqlfiddle.com/#!9/ad7cca/7

Body:
Try with this:

SELECT driver_id, COUNT( DISTINCT driver_id) as Non_Driver_Cancel
FROM Trip
WHERE status NOT IN (SELECT DISTINCT status FROM Trip WHERE status <> 'cancelled_by_driver')
GROUP BY driver_id;


问:
Access VBA round by the quarter of the hour
I want to be able to round time by the quarter of the hour, so when it is 3 minutes past the quarter of the hour it rounds up and when it's within the 3 minutes it rounds down.  Like below:

```<code>08:01 (will be 08:00)
08:03 (will be 08:00)
08:04 (will be 08:15)
</code>```

Managed to get it working in excel but cannot get it working in Access.

Here is the excel formula:

```<code>=(TRUNC((VALUE("08:03")+VALUE("00:11"))*96)*VALUE("00:15"))
</code>```

答:
Here's my attempt. The function takes two arguments. The date to round, and the optional roundingThreshold which is a byte. You can set a new rounding point by changing this roundingThreshold value. Currently it is set as 3, which means, values larger than 3 will round to next closest 15 minute interval.

It should be pretty quick to run, I ran a test for like 6000 dates and it took less than a second.

```<code>Option Explicit

Public Function roundDate(dateIn As Date, _
                          Optional roundThreshold As Byte = 3) As Date

    'get the minutes from the date
    Dim minutes    As Byte: minutes = Format(dateIn, "nn")
    Dim revisedMin As Byte

    'Determine if the item should be rounded up/down
    If minutes Mod 15 > roundThreshold Then
        'Round up to closest 15 minutes
        'Use integer to round the number down, add 1, then multiply by 15
        revisedMin = minutes + ((((minutes \ 15) + 1) * 15) - minutes)
    Else
        'Round down to the closest 15 min interval
        revisedMin = minutes - minutes Mod 15
    End If

    'Rebuild the date with the rounded date
    If Not revisedMin = 60 Then
        roundDate = CDate(Format(dateIn, "hh") & ":" & revisedMin)
    Else
        roundDate = CDate(DateAdd("h", 1, Format(dateIn, "hh") & ":00"))
    End If

End Function
</code>```

Testing Results:

```<code>Test Date     Rounded Result
9:00:00 AM    9:00:00 AM
9:01:00 AM    9:00:00 AM
9:02:00 AM    9:00:00 AM
9:03:00 AM    9:00:00 AM
9:04:00 AM    9:15:00 AM
9:05:00 AM    9:15:00 AM
9:06:00 AM    9:15:00 AM
9:07:00 AM    9:15:00 AM
9:08:00 AM    9:15:00 AM
9:09:00 AM    9:15:00 AM
9:10:00 AM    9:15:00 AM
9:11:00 AM    9:15:00 AM
9:12:00 AM    9:15:00 AM
9:13:00 AM    9:15:00 AM
9:14:00 AM    9:15:00 AM
9:15:00 AM    9:15:00 AM
9:16:00 AM    9:15:00 AM
9:17:00 AM    9:15:00 AM
9:18:00 AM    9:15:00 AM
9:19:00 AM    9:30:00 AM
9:20:00 AM    9:30:00 AM
9:21:00 AM    9:30:00 AM
9:22:00 AM    9:30:00 AM
9:23:00 AM    9:30:00 AM
9:24:00 AM    9:30:00 AM
9:25:00 AM    9:30:00 AM
9:26:00 AM    9:30:00 AM
9:27:00 AM    9:30:00 AM
9:28:00 AM    9:30:00 AM
9:29:00 AM    9:30:00 AM
9:30:00 AM    9:30:00 AM
9:31:00 AM    9:30:00 AM
9:32:00 AM    9:30:00 AM
9:33:00 AM    9:30:00 AM
9:34:00 AM    9:45:00 AM
9:35:00 AM    9:45:00 AM
9:36:00 AM    9:45:00 AM
9:37:00 AM    9:45:00 AM
9:38:00 AM    9:45:00 AM
9:39:00 AM    9:45:00 AM
9:40:00 AM    9:45:00 AM
9:41:00 AM    9:45:00 AM
9:42:00 AM    9:45:00 AM
9:43:00 AM    9:45:00 AM
9:44:00 AM    9:45:00 AM
9:45:00 AM    9:45:00 AM
9:46:00 AM    9:45:00 AM
9:47:00 AM    9:45:00 AM
9:48:00 AM    9:45:00 AM
9:49:00 AM    10:00:00 AM
9:50:00 AM    10:00:00 AM
9:51:00 AM    10:00:00 AM
9:52:00 AM    10:00:00 AM
9:53:00 AM    10:00:00 AM
9:54:00 AM    10:00:00 AM
9:55:00 AM    10:00:00 AM
9:56:00 AM    10:00:00 AM
9:57:00 AM    10:00:00 AM
9:58:00 AM    10:00:00 AM
9:59:00 AM    10:00:00 AM
10:00:00 AM   10:00:00 AM
</code>```

Body:
I want to be able to round time by the quarter of the hour, so when it is 3 minutes past the quarter of the hour it rounds up and when it's within the 3 minutes it rounds down.  Like below:

08:01 (will be 08:00)
08:03 (will be 08:00)
08:04 (will be 08:15)

Managed to get it working in excel but cannot get it working in Access.

Here is the excel formula:

=(TRUNC((VALUE("08:03")+VALUE("00:11"))*96)*VALUE("00:15"))

Body:
Here's my attempt. The function takes two arguments. The date to round, and the optional roundingThreshold which is a byte. You can set a new rounding point by changing this roundingThreshold value. Currently it is set as 3, which means, values larger than 3 will round to next closest 15 minute interval.

It should be pretty quick to run, I ran a test for like 6000 dates and it took less than a second.

Option Explicit

Public Function roundDate(dateIn As Date, _
                          Optional roundThreshold As Byte = 3) As Date

    'get the minutes from the date
    Dim minutes    As Byte: minutes = Format(dateIn, "nn")
    Dim revisedMin As Byte

    'Determine if the item should be rounded up/down
    If minutes Mod 15 > roundThreshold Then
        'Round up to closest 15 minutes
        'Use integer to round the number down, add 1, then multiply by 15
        revisedMin = minutes + ((((minutes \ 15) + 1) * 15) - minutes)
    Else
        'Round down to the closest 15 min interval
        revisedMin = minutes - minutes Mod 15
    End If

    'Rebuild the date with the rounded date
    If Not revisedMin = 60 Then
        roundDate = CDate(Format(dateIn, "hh") & ":" & revisedMin)
    Else
        roundDate = CDate(DateAdd("h", 1, Format(dateIn, "hh") & ":00"))
    End If

End Function

Testing Results:

Test Date     Rounded Result
9:00:00 AM    9:00:00 AM
9:01:00 AM    9:00:00 AM
9:02:00 AM    9:00:00 AM
9:03:00 AM    9:00:00 AM
9:04:00 AM    9:15:00 AM
9:05:00 AM    9:15:00 AM
9:06:00 AM    9:15:00 AM
9:07:00 AM    9:15:00 AM
9:08:00 AM    9:15:00 AM
9:09:00 AM    9:15:00 AM
9:10:00 AM    9:15:00 AM
9:11:00 AM    9:15:00 AM
9:12:00 AM    9:15:00 AM
9:13:00 AM    9:15:00 AM
9:14:00 AM    9:15:00 AM
9:15:00 AM    9:15:00 AM
9:16:00 AM    9:15:00 AM
9:17:00 AM    9:15:00 AM
9:18:00 AM    9:15:00 AM
9:19:00 AM    9:30:00 AM
9:20:00 AM    9:30:00 AM
9:21:00 AM    9:30:00 AM
9:22:00 AM    9:30:00 AM
9:23:00 AM    9:30:00 AM
9:24:00 AM    9:30:00 AM
9:25:00 AM    9:30:00 AM
9:26:00 AM    9:30:00 AM
9:27:00 AM    9:30:00 AM
9:28:00 AM    9:30:00 AM
9:29:00 AM    9:30:00 AM
9:30:00 AM    9:30:00 AM
9:31:00 AM    9:30:00 AM
9:32:00 AM    9:30:00 AM
9:33:00 AM    9:30:00 AM
9:34:00 AM    9:45:00 AM
9:35:00 AM    9:45:00 AM
9:36:00 AM    9:45:00 AM
9:37:00 AM    9:45:00 AM
9:38:00 AM    9:45:00 AM
9:39:00 AM    9:45:00 AM
9:40:00 AM    9:45:00 AM
9:41:00 AM    9:45:00 AM
9:42:00 AM    9:45:00 AM
9:43:00 AM    9:45:00 AM
9:44:00 AM    9:45:00 AM
9:45:00 AM    9:45:00 AM
9:46:00 AM    9:45:00 AM
9:47:00 AM    9:45:00 AM
9:48:00 AM    9:45:00 AM
9:49:00 AM    10:00:00 AM
9:50:00 AM    10:00:00 AM
9:51:00 AM    10:00:00 AM
9:52:00 AM    10:00:00 AM
9:53:00 AM    10:00:00 AM
9:54:00 AM    10:00:00 AM
9:55:00 AM    10:00:00 AM
9:56:00 AM    10:00:00 AM
9:57:00 AM    10:00:00 AM
9:58:00 AM    10:00:00 AM
9:59:00 AM    10:00:00 AM
10:00:00 AM   10:00:00 AM


问:
Disable input method of EditText but keep cursor blinking
In my Android application, I want an EditText with android:editable="false" but the cursor blinking. The cursor blinking seems doesn't work after "editable" is set to false.

I just want to use my own Keyboard widget(not the system's soft keyboard), and keep the cursor blinking.

Is there any idea to make that possible?

答:
I called the following from onCreate(), but this affects all EditTexts.</p>

```<code>private void hideKeyboard ()
{
    getWindow ().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    getWindow ().setFlags (WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                           WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}
</code>```

Body:
I called the following from onCreate(), but this affects all EditTexts.

private void hideKeyboard ()
{
    getWindow ().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    getWindow ().setFlags (WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                           WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}


问:
how can I add rows to DB on android only when DB is created? (using room)
I have category class:

```<code>@Entity(tableName = "Categories",indices = {@Index(value = {"id"},
        unique = true)})
public class Category  implements Serializable {

    public  Category(String name,int icon,int color)
    {
        _name= name;
        _icon = icon;
        _color = color;
    }
    @PrimaryKey(autoGenerate = true)
    public int id;

    @ColumnInfo(name = "name")
    public String _name;

    @ColumnInfo(name = "icon")
    public int _icon;

    @ColumnInfo(name = "color")
    public int _color;

    public String get_name() {return _name;}

    public int getColor() {
        return _color;
    }

    public int getIcon() {
        return _icon;
    }
}
</code>```

and I would like to create constant rows only when DB is newly created and not each time the application is loading.
what I did till now is:

```<code>protected CategorySingletone() {
        // Exists only to defeat instantiation.

        AppDatabase db = AppDatabase.getAppDatabase(MainActivity.get().getApplicationContext());
        if (db.categoryDao().countCategories()==0) {
            _categoryList = new ArrayList<>();
            _categoryList.add(new Category("Cars", R.drawable.couch, 3));
            _categoryList.add(new Category("Tech", R.drawable.phone, 3));
            _categoryList.add(new Category("Home", R.drawable.book_1, 3));
            _categoryList.add(new Category("Leisure", R.drawable.book_1, 3));
            _categoryList.add(new Category("Motors", R.drawable.book_4, 3));
            _categoryList.add(new Category("Fashion", R.drawable.book_5, 3));
            for (Iterator<Category> i = _categoryList.iterator(); i.hasNext();) {
                Category item = i.next();
                db.categoryDao().insertAll(item);
            }
        }
</code>```

while I am checking if rows exists.
is there a better way?

答:
A more efficient way would be to use the DatabaseUtils queryNumEntries method.

e.g.

```<code>    if (DatabaseUtils.queryNumEntries(db,"Categories") == 0) {
        .......
    }
</code>```

Body:
I have category class:

@Entity(tableName = "Categories",indices = {@Index(value = {"id"},
        unique = true)})
public class Category  implements Serializable {

    public  Category(String name,int icon,int color)
    {
        _name= name;
        _icon = icon;
        _color = color;
    }
    @PrimaryKey(autoGenerate = true)
    public int id;

    @ColumnInfo(name = "name")
    public String _name;

    @ColumnInfo(name = "icon")
    public int _icon;

    @ColumnInfo(name = "color")
    public int _color;

    public String get_name() {return _name;}

    public int getColor() {
        return _color;
    }

    public int getIcon() {
        return _icon;
    }
}

and I would like to create constant rows only when DB is newly created and not each time the application is loading.
what I did till now is:

protected CategorySingletone() {
        // Exists only to defeat instantiation.

        AppDatabase db = AppDatabase.getAppDatabase(MainActivity.get().getApplicationContext());
        if (db.categoryDao().countCategories()==0) {
            _categoryList = new ArrayList<>();
            _categoryList.add(new Category("Cars", R.drawable.couch, 3));
            _categoryList.add(new Category("Tech", R.drawable.phone, 3));
            _categoryList.add(new Category("Home", R.drawable.book_1, 3));
            _categoryList.add(new Category("Leisure", R.drawable.book_1, 3));
            _categoryList.add(new Category("Motors", R.drawable.book_4, 3));
            _categoryList.add(new Category("Fashion", R.drawable.book_5, 3));
            for (Iterator<Category> i = _categoryList.iterator(); i.hasNext();) {
                Category item = i.next();
                db.categoryDao().insertAll(item);
            }
        }

while I am checking if rows exists.
is there a better way?

Body:
A more efficient way would be to use the DatabaseUtils queryNumEntries method.

e.g.

    if (DatabaseUtils.queryNumEntries(db,"Categories") == 0) {
        .......
    }


问:
react-native-fbsdk get user_birthday and user_location permission doesn't work
Everyone
I am going to get birthday and location from Facebook using react-native-fbsdk.

Here's part of my code:

```<code>LoginManager.logInWithReadPermissions(['public_profile', 'user_birthday', 'user_location'])
        .then((result) => {
          if (result.isCancelled) {
            return;
          }
          AccessToken.getCurrentAccessToken().then((data) => {
              console.log(data); // output 1:
              const responseInfoCallback = (error, profile) => {
                if (error) {
                  console.log(error);
                } else {
                  console.log(profile); // output 2:
                }
              };
              const accessToken = data.accessToken;
              const infoRequest = new GraphRequest(
                '/me',
                {
                  accessToken,
                  parameters: {
                    fields: {
                      string: 'name,gender,birthday,location{location}',
                    },
                  },
                },
                responseInfoCallback,
              );
              new GraphRequestManager().addRequest(infoRequest).start();
            });
          });
        })
        .catch(error => console.log(error));
</code>```

```<code>Here's result of output 1 and 2
--------- output 1 -------
{ accessToken: .......,
          permissions: [ 'email', 'public_profile' ],
          declinedPermissions: [],
          applicationID: '968214779983507',
          accessTokenSource: undefined,
          userID: '161823674419561',
          expirationTime: 1515417067593.333,
          lastRefreshTime: 1510242607593.949 }
-------output 2--------
{ id: '161823674419561', gender: 'male', name: '....' }
</code>```

Please help me.
Thanks.

答: Those permissions only work for users with a role in the App. If you want to make them work for everyone else, you need to go through a review process: https://developers.facebook.com/docs/facebook-login/review</p>

Body:
Everyone
I am going to get birthday and location from Facebook using react-native-fbsdk.

Here's part of my code:

LoginManager.logInWithReadPermissions(['public_profile', 'user_birthday', 'user_location'])
        .then((result) => {
          if (result.isCancelled) {
            return;
          }
          AccessToken.getCurrentAccessToken().then((data) => {
              console.log(data); // output 1:
              const responseInfoCallback = (error, profile) => {
                if (error) {
                  console.log(error);
                } else {
                  console.log(profile); // output 2:
                }
              };
              const accessToken = data.accessToken;
              const infoRequest = new GraphRequest(
                '/me',
                {
                  accessToken,
                  parameters: {
                    fields: {
                      string: 'name,gender,birthday,location{location}',
                    },
                  },
                },
                responseInfoCallback,
              );
              new GraphRequestManager().addRequest(infoRequest).start();
            });
          });
        })
        .catch(error => console.log(error));

Here's result of output 1 and 2
--------- output 1 -------
{ accessToken: .......,
          permissions: [ 'email', 'public_profile' ],
          declinedPermissions: [],
          applicationID: '968214779983507',
          accessTokenSource: undefined,
          userID: '161823674419561',
          expirationTime: 1515417067593.333,
          lastRefreshTime: 1510242607593.949 }
-------output 2--------
{ id: '161823674419561', gender: 'male', name: '....' }

Please help me.
Thanks.


问:
Javascript to check whether a checkbox is being checked or unchecked
I have a javascript routine that is performing actions on a group of checkboxes, but the final action I want to set the clicked checkbox to checked or unchecked based on if the user was checking the box or unchecking.

Unfortunately, every time I check for whether it is being checked or unchecked, it returns "on" indicating the user is always checking the box!  Any help would be appreciated, I've also included the javascript.

```<code>// Uncheck all the checkboxs with the same Tax Credit
for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].value == "on")   // <-- This is always returning true, even if the box is being unchecked
        {
            arrChecks[i].checked = 1;
        } else {
            arrChecks[i].checked = 0;
        }

    } else {
        arrChecks[i].checked = 0;
    }
}
</code>```

答: Also make sure you test it both in firefox and IE. There are some nasty bugs with JS manipulated checkboxes.</p>

OwnerDisplayName: Mark K.

Body:
I have a javascript routine that is performing actions on a group of checkboxes, but the final action I want to set the clicked checkbox to checked or unchecked based on if the user was checking the box or unchecking.

Unfortunately, every time I check for whether it is being checked or unchecked, it returns "on" indicating the user is always checking the box!  Any help would be appreciated, I've also included the javascript.

// Uncheck all the checkboxs with the same Tax Credit
for (i=0; i<arrChecks.length; i++)
{
    var attribute = arrChecks[i].getAttribute("xid")
    if (attribute == elementName)
    {
        // if the current state is checked, unchecked and vice-versa
        if (arrChecks[i].value == "on")   // <-- This is always returning true, even if the box is being unchecked
        {
            arrChecks[i].checked = 1;
        } else {
            arrChecks[i].checked = 0;
        }

    } else {
        arrChecks[i].checked = 0;
    }
}

OwnerDisplayName: Spikolynn


问:
Get value of placeholder in empty input field with jquery?
Something is weird and I'm stumped.

When I have an input field with placeholder, eg:

```<code><input id="box1" placeholder="not applicable">
</code>```

I've always been able to grab the user input, or if input is left empty, the placeholder value with jquery as such:

```<code>var text = $('#box1').val();
</code>```

No big deal. using jquery .val() always did the trick. Then I started seeing some code output errors in previously working apps wherein empty inputs were not capturing the placeholder value.

Did something change with the javascript engine that would account for this? Or is there a new way to get the placeholder value if the input field is empty?

See this example:

$('#done').on('click', function(){
   if($('#box3').val() == ''){
            var box3 = $(this).data('placeholder');
        } else {
        var box3 = $('#box3').val();
        }
  $('#output').val(box3);
});

// Clicking the button doesn't capture the placeholder value if empty?```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<input id="box3" placeholder="not applicable">
<br><br>
<button id="done">
Done
</button>
<br><br>
<textarea id="output"></textarea>
<br><br>
<p>
Why doesn't the button click capture the value of the placeholder in this instance, using jquery 3.1.1?
</p></code>```

答:
Use attr('placeholder'). Also, your use of this inside the if statement was faulty. It referred to the subject of the click function.

$('#done').on('click', function(){
   if($('#box3').val() == ''){
            var box3 = $('#box3').attr('placeholder');
        } else {
           var box3 = $('#box3').val();
        }
  $('#output').val(box3);
});

// Clicking the button doesn't capture the placeholder value if empty?```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<input id="box3" placeholder="not applicable">
<br><br>
<button id="done">
Done
</button>
<br><br>
<textarea id="output"></textarea>
<br><br>
<p>
Why doesn't the button click capture the value of the placeholder in this instance, using jquery 3.1.1?
</p></code>```

Body:
Something is weird and I'm stumped.

When I have an input field with placeholder, eg:

<input id="box1" placeholder="not applicable">

I've always been able to grab the user input, or if input is left empty, the placeholder value with jquery as such:

var text = $('#box1').val();

No big deal. using jquery .val() always did the trick. Then I started seeing some code output errors in previously working apps wherein empty inputs were not capturing the placeholder value.

Did something change with the javascript engine that would account for this? Or is there a new way to get the placeholder value if the input field is empty?

See this example:

$('#done').on('click', function(){
   if($('#box3').val() == ''){
            var box3 = $(this).data('placeholder');
        } else {
        var box3 = $('#box3').val();
        }
  $('#output').val(box3);
});

// Clicking the button doesn't capture the placeholder value if empty?

<input id="box3" placeholder="not applicable">

<button id="done">
Done
</button>

<textarea id="output"></textarea>

Why doesn't the button click capture the value of the placeholder in this instance, using jquery 3.1.1?

Body:
Use attr('placeholder'). Also, your use of this inside the if statement was faulty. It referred to the subject of the click function.

$('#done').on('click', function(){
   if($('#box3').val() == ''){
            var box3 = $('#box3').attr('placeholder');
        } else {
           var box3 = $('#box3').val();
        }
  $('#output').val(box3);
});

// Clicking the button doesn't capture the placeholder value if empty?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<input id="box3" placeholder="not applicable">
<br><br>
<button id="done">
Done
</button>
<br><br>
<textarea id="output"></textarea>
<br><br>
<p>
Why doesn't the button click capture the value of the placeholder in this instance, using jquery 3.1.1?
</p>


问:
In go Is there a way to expose the data used for location zone and zoneTrans?
I would like to know when a Location's offset from UTC is going to change. I see that this information is known by the time package, obviously or it wouldn't be able to account for daylight savings. That way I could find out that for the location "America/New_York" daylight savings begins on Sunday, March 11 2018 at 07:00 UTC.

Is there a way to do this short of making my own copy of the time package that exports the Location properties or writing my own parser for the time zone files?

答:
As you've seen in the source, no, that information is not exposed. But, as you can also see from the source, the raw TZDB used to generate the timezones is included in the Go distribution:

```<code>//go:generate env ZONEINFO=$GOROOT/lib/time/zoneinfo.zip go run genzabbrs.go -output zoneinfo_abbrs_windows.go
</code>```

If you take a look at your $GOROOT/lib/time you'll find that file, which contains all the data used to generate the time zone list, and you can look at $GOROOT/src/time/genzabbrs.go to see how it's used.

Body:
As you've seen in the source, no, that information is not exposed. But, as you can also see from the source, the raw TZDB used to generate the timezones is included in the Go distribution:

//go:generate env ZONEINFO=$GOROOT/lib/time/zoneinfo.zip go run genzabbrs.go -output zoneinfo_abbrs_windows.go

If you take a look at your $GOROOT/lib/time you'll find that file, which contains all the data used to generate the time zone list, and you can look at $GOROOT/src/time/genzabbrs.go to see how it's used.


问:
Generate opaque pointer in C using rusty-cheddar
I'm trying to generate C header file for a library written in Rust using the rusty-cheddar crate.

Here is the definition and implementation of the struct in Rust:

```<code>pub struct AccountDatabase {
    money: HashMap<String, u32>,
}

impl AccountDatabase {
    fn new() -> AccountDatabase {
        AccountDatabase {
            money: HashMap::new(),
        }
    }
}
</code>```

If I place #[repr(C)] before the struct, rusty-cheddar generates the following declaration of the struct in C

typedef struct AccountDatabase {
    HashMap money;
} AccountDatabase;
```

The HashMap is not known to C, therefore I'd like for the struct to be declared as an opaque pointer.

答:
The solution is specified right on the readme file:

To define an opaque struct you must define a public newtype which is marked as #[repr(C)].

Thus:

```<code>struct AccountDatabase {
    money: HashMap<String, u32>,
}

impl AccountDatabase {
    fn new() -> AccountDatabase {
        AccountDatabase {
            money: HashMap::new()
        }
    }
}

#[repr(C)]
pub struct Crate_AccountDatabase(AccountDatabase);
</code>```

(or with some other struct naming of your choice)

Body:
I'm trying to generate C header file for a library written in Rust using the rusty-cheddar crate.

Here is the definition and implementation of the struct in Rust:

pub struct AccountDatabase {
    money: HashMap<String, u32>,
}

impl AccountDatabase {
    fn new() -> AccountDatabase {
        AccountDatabase {
            money: HashMap::new(),
        }
    }
}

If I place #[repr(C)] before the struct, rusty-cheddar generates the following declaration of the struct in C

typedef struct AccountDatabase {
    HashMap money;
} AccountDatabase;

The HashMap is not known to C, therefore I'd like for the struct to be declared as an opaque pointer.

Body:
The solution is specified right on the readme file:

To define an opaque struct you must define a public newtype which is marked as #[repr(C)].

Thus:

struct AccountDatabase {
    money: HashMap<String, u32>,
}

impl AccountDatabase {
    fn new() -> AccountDatabase {
        AccountDatabase {
            money: HashMap::new()
        }
    }
}

#[repr(C)]
pub struct Crate_AccountDatabase(AccountDatabase);

(or with some other struct naming of your choice)


问:
SQL Query progress using PostgreSQL or My SQL
Introduction

Hello everyone.
Working on web application management I often find myself having a problem that I have never solved with my current knowledge.
In my applications, most data extraction processes are long-lasting due to complex queries and large amounts of data.
In fact, the waiting time of a data extraction through PHP is largely spent by the QUERY EXECUTION (in most cases).
Suppose we have this common situation

Question

At this point my question is: Is there a solution for know at what point of query execution process has arrived and then do a query trace for have my [PROGRESS QUERY %]?

My solution

So far the solution I have used are this: "Query time history"

When I run a data extraction query with specific parameters i save in the table the duration of the query and every time that query is executed with those parameters i overwrite the rescheduled duration with the average of all durations.
So I can have an estimate based on an average, obviously ignoring other parameters that can affect the duration of a query and i can call a client side function based on seconds estimated and populate the [PROGRESS QUERY %].

Example: (i use boostrap progress bar for view)

HTML

```<code><!-- where "data-seconds" are the average seconds of the execution saved in my query time history table -->
<button type="button" id="runQuery" data-seconds="500">Get Data</button>
<div class="progress">
  <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
  </div>
</div>
</code>```

JAVASCRIPT

```<code>$("#runQuery").on("click", function() {
    var currentSeconds = 0;
    var totalSeconds = parseFloat($(this).data("seconds"));
    var $progressBar = $(".progress-bar");
    var progressPercentage = 0;
    var execution;

    $.ajax({
        url: "scriptForQueryExecution.php", type: "POST", beforeSend: function() {
            execution = setInterval(function() {
                progressPercentage = currentSeconds / totalSeconds * 100;
                $progressBar.css("width", progressPercentage + '%').attr("aria-valuenow", progressPercentage);

                currentSeconds++;
            }, 1000);
        }, success: function() {
            $progressBar.css("width", '100%').attr("aria-valuenow", 100);
            clearInterval(execution);
        }
    });
});
</code>```

答: Sure you've probably thought of this, but you could write a query that determines the number of rows in the table using select count([ID]) from dbo.MyTable which should take less that 1 second and then build in some calculation on the client side that calculates the current number of rows divided by the total number of rows in the table...

Body:
Introduction

Hello everyone.
Working on web application management I often find myself having a problem that I have never solved with my current knowledge.
In my applications, most data extraction processes are long-lasting due to complex queries and large amounts of data.
In fact, the waiting time of a data extraction through PHP is largely spent by the QUERY EXECUTION (in most cases).
Suppose we have this common situation

Question

At this point my question is: Is there a solution for know at what point of query execution process has arrived and then do a query trace for have my [PROGRESS QUERY %]?

My solution

So far the solution I have used are this: "Query time history"

When I run a data extraction query with specific parameters i save in the table the duration of the query and every time that query is executed with those parameters i overwrite the rescheduled duration with the average of all durations.
So I can have an estimate based on an average, obviously ignoring other parameters that can affect the duration of a query and i can call a client side function based on seconds estimated and populate the [PROGRESS QUERY %].

Example: (i use boostrap progress bar for view)

HTML

<button type="button" id="runQuery" data-seconds="500">Get Data</button>

JAVASCRIPT

$("#runQuery").on("click", function() {
    var currentSeconds = 0;
    var totalSeconds = parseFloat($(this).data("seconds"));
    var $progressBar = $(".progress-bar");
    var progressPercentage = 0;
    var execution;

    $.ajax({
        url: "scriptForQueryExecution.php", type: "POST", beforeSend: function() {
            execution = setInterval(function() {
                progressPercentage = currentSeconds / totalSeconds * 100;
                $progressBar.css("width", progressPercentage + '%').attr("aria-valuenow", progressPercentage);

                currentSeconds++;
            }, 1000);
        }, success: function() {
            $progressBar.css("width", '100%').attr("aria-valuenow", 100);
            clearInterval(execution);
        }
    });
});


问:
What components and code are recommended for "real-time" viewing of histogram data sets through a web server?
We have an app that produces large data sets in the form of histograms. (A "bin" with a value associated with it) and we would like to provide that data to a web server of some kind so that users can see the data.

We also would like users to be able to zoom and expand or contract the bin size - so that the VIEWABLE histogram bins are combined or separated depending on the view/zoom level.

We're (low-level) C++ developers and are unfamiliar with that territory.

So essentially we have three questions regarding this:

Is there a recommended web server to use as the publishing engine for this specific use-case or will any old web server do?

What component/plugin/software will to do the rendering and user functionality for zooming in/out

What communication to get the data set to the rendering engine (say, once per minute or 10 minutes, etc)

The goal is to use an off-the-shelf tool/library/software for this - also would be nice if it was "free".

The current platform for the data collection software is Win32.  It will be ported to Linux as well.

Any links to known projects or services that do similar things are appreciated.

答:
If you want to show graphs on demand - any webserver will do. IIS on Windows, Apache/Lighthttpd/nginx on linux. If you want realtime streaming - you should use Comet server - hookbox, ape, node.js.

Not sure I am aware of. I would draw myself or use variety of charts libs via JS.

JSON encoded array of values. For realtime transfers you just push your values in the channel as soon as you get them also in JSON format. Clients subscribe to these channels and get data in realtime.


问:
Sharing a connection and a transaction in EF across multiple contexts (UnintentionalCodeFirstException)
The previous version and question are provided as an added context below. The improved problem formulation and question could be as follows:

How does one share a transaction between multiple contexts in EF 6.1.0 database first and .NET 4.5.2 without doing a distributed transaction?

For that it looks like I need to share a connection between the multiple contexts, but the code examples and tutorials I've been looking at thus far haven't been that fruitful. The problem looks like is hovering around on how to define a functioning combination of a connection object and transaction object types so that EF database first object metadata is also built and found when constructing the object contexts.

That is, I would like to do akin to what has been described in the EF 6.n tutorials here. Some example code could be

```<code>int count1;
int count2;
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
    //How to define this connection so as not to run into UnintentionalCodeFirstException?
    //Creating a dummy context to obtain the connectiong string like so
    //dummyContext.Database.Connection.ConnectionString  and then using the connection will be greeted with the aforementioned exception.
    using(var conn = new SqlConnection("..."))
    {
        using(var c1 = new SomeEntities(conn, contextOwnsConnection: false))
        {
            //Use some stored procedures etc.
            count1 = await c1.SomeEntity1.CountAsync();
        }

        using(var c2 = new SomeEntities(conn, contextOwnsConnection: false))
        {
            //Use some stored procedures etc.
            count2 = await c2.SomeEntity21.CountAsync();
        }
    }
}

int count = count1 + count2;
</code>```

In the examples there are also other methods as to how to create a shared connection and a transaction, but as written, the culprit seem to be that if, say, I provide the connectiong string in (the "..." part) the previous snippet as dummyContext.Database.Connection.ConnectionString I'll get just an exception.

I'm not sure if I'm just reading the wrong sources or if there's something else that's wrong in my code when I try to share a transaction across multiple EF contexts. How could it be done?

I've read quite a few other SO posts regarding this (e.g. this) and some tutorials. They did not help.

I have a strange problem in that it looks I don't have the constructor overloads defined as in other tutorials and posts. That is, taking the linked tutorial link, I can't write new BloggingContext(conn, contextOwnsConnection: false)) and use a shared connection and an external transaction.

Then if I write

```<code>public partial class SomeEntities: DbContext
{
    public SomeEntities(DbConnection existingConnection, bool contextOwnsConnection): base(existingConnection, contextOwnsConnection) { }
}
</code>```

and use it like in the tutorials, I get an exception from the following line from the following T4 template generated code

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    throw new UnintentionalCodeFirstException();
}
</code>```

I'm using .NET 4.5.2 and EF 6.1.0. I'ved constructed the edmx from an existing database and generated the code from there. In this particular situation I'm using Task Parallel threads to load dozens of SQL Server Master Data Services staging tables (yes, a big model) and to call the associated procedures (provided by the MDS one per table). MDS has its own compensation logic in case staging to some of the tables fails, but rolling back a transaction should be doable too. It just looks like I have a (strange) problem with my EF.

<Addendum: Steve suggested using straight TransactionScope. Without a shared connection that would require a distributed transaction, which isn't an option I can choose. Then if I try to provide a shared connection for the contexts (some options shown in the tutorials, one here I have the problem of "missing constructors". When I define one, I get the exception I refer in the code. All in all, this feels quite strange. Maybe there's something wrong in how I go about generating the DbContext and related classes.

<Note 1: It looks like the root cause is as in this blog post by Arthur (of EF developer team) Don't use Code First by mistake. That is, in database first development the framework seeks for the class-relational mappings as defined in the connection string. Something fishy in my connection string that is..?

答:
Because of connection pool, using multiple EF DbContext which are using exactly the same connection string, under same transaction scope will usually not result in DTC escalation (unless you disabled pooling in connection string), because the same connection will be reused for them both (from the pool). Anyway, you can reuse the same connection in your case like this (I assume you already added constructor which accepts DbConnection and flag indicating if context owns connection):

```<code>using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
    // important - use EF connection string here,
    // one that starts with "metadata=res://*/..."
    var efConnectionString = ConfigurationManager.ConnectionStrings["SomeEntities"].ConnectionString;
    // note EntityConnection, not SqlConnection
    using (var conn = new EntityConnection(efConnectionString)) {
        // important to prevent escalation
        await conn.OpenAsync();
        using (var c1 = new SomeEntities(conn, contextOwnsConnection: false)) {
            //Use some stored procedures etc.
            count1 = await c1.SomeEntity1.CountAsync();
        }

        using (var c2 = new SomeEntities(conn, contextOwnsConnection: false)) {
            //Use some stored procedures etc.
            count2 = await c2.SomeEntity21.CountAsync();
        }
    }
    scope.Complete();
}
</code>```

This works and does not throw UnintentionalCodeFirstException because you pass EntityConnection. This connection has information about EDMX metadata and that is what database first needs. When you pass plain SqlConnection - EF has no idea where to look for metadata and actually doesn't even know it should look for it - so it immediately assumes you are doing code-first.

Note that I pass EF connection string in code above. If you have some plain SqlConnection which you obtained by some other means, outside EF, this will not work, because connection string is needed. But, it's still possible because EntityConnection has constructor which accepts plain DbConnection. However, then you should pass reference to metadata yourself. If you are interested in this - I can provide code example of how to do that.

To check that you indeed prevent escalation in all cases - disable pooling (Pooling=false in connection string) and stop DTC service, then run this code - it should run fine. Then run another code which does not share the same connection and you should observe error indicating escalation was about to happen but service is not available.

Body:
The previous version and question are provided as an added context below. The improved problem formulation and question could be as follows:

How does one share a transaction between multiple contexts in EF 6.1.0 database first and .NET 4.5.2 without doing a distributed transaction?

For that it looks like I need to share a connection between the multiple contexts, but the code examples and tutorials I've been looking at thus far haven't been that fruitful. The problem looks like is hovering around on how to define a functioning combination of a connection object and transaction object types so that EF database first object metadata is also built and found when constructing the object contexts.

That is, I would like to do akin to what has been described in the EF 6.n tutorials here. Some example code could be

int count1;
int count2;
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
    //How to define this connection so as not to run into UnintentionalCodeFirstException?
    //Creating a dummy context to obtain the connectiong string like so
    //dummyContext.Database.Connection.ConnectionString  and then using the connection will be greeted with the aforementioned exception.
    using(var conn = new SqlConnection("..."))
    {
        using(var c1 = new SomeEntities(conn, contextOwnsConnection: false))
        {
            //Use some stored procedures etc.
            count1 = await c1.SomeEntity1.CountAsync();
        }

        using(var c2 = new SomeEntities(conn, contextOwnsConnection: false))
        {
            //Use some stored procedures etc.
            count2 = await c2.SomeEntity21.CountAsync();
        }
    }
}

int count = count1 + count2;

In the examples there are also other methods as to how to create a shared connection and a transaction, but as written, the culprit seem to be that if, say, I provide the connectiong string in (the "..." part) the previous snippet as dummyContext.Database.Connection.ConnectionString I'll get just an exception.

I'm not sure if I'm just reading the wrong sources or if there's something else that's wrong in my code when I try to share a transaction across multiple EF contexts. How could it be done?

I've read quite a few other SO posts regarding this (e.g. this) and some tutorials. They did not help.

I have a strange problem in that it looks I don't have the constructor overloads defined as in other tutorials and posts. That is, taking the linked tutorial link, I can't write new BloggingContext(conn, contextOwnsConnection: false)) and use a shared connection and an external transaction.

Then if I write

public partial class SomeEntities: DbContext
{
    public SomeEntities(DbConnection existingConnection, bool contextOwnsConnection): base(existingConnection, contextOwnsConnection) { }
}

and use it like in the tutorials, I get an exception from the following line from the following T4 template generated code

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    throw new UnintentionalCodeFirstException();
}

I'm using .NET 4.5.2 and EF 6.1.0. I'ved constructed the edmx from an existing database and generated the code from there. In this particular situation I'm using Task Parallel threads to load dozens of SQL Server Master Data Services staging tables (yes, a big model) and to call the associated procedures (provided by the MDS one per table). MDS has its own compensation logic in case staging to some of the tables fails, but rolling back a transaction should be doable too. It just looks like I have a (strange) problem with my EF.

<Addendum: Steve suggested using straight TransactionScope. Without a shared connection that would require a distributed transaction, which isn't an option I can choose. Then if I try to provide a shared connection for the contexts (some options shown in the tutorials, one here I have the problem of "missing constructors". When I define one, I get the exception I refer in the code. All in all, this feels quite strange. Maybe there's something wrong in how I go about generating the DbContext and related classes.

<Note 1: It looks like the root cause is as in this blog post by Arthur (of EF developer team) Don't use Code First by mistake. That is, in database first development the framework seeks for the class-relational mappings as defined in the connection string. Something fishy in my connection string that is..?

Body:
Because of connection pool, using multiple EF DbContext which are using exactly the same connection string, under same transaction scope will usually not result in DTC escalation (unless you disabled pooling in connection string), because the same connection will be reused for them both (from the pool). Anyway, you can reuse the same connection in your case like this (I assume you already added constructor which accepts DbConnection and flag indicating if context owns connection):

using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
    // important - use EF connection string here,
    // one that starts with "metadata=res://*/..."
    var efConnectionString = ConfigurationManager.ConnectionStrings["SomeEntities"].ConnectionString;
    // note EntityConnection, not SqlConnection
    using (var conn = new EntityConnection(efConnectionString)) {
        // important to prevent escalation
        await conn.OpenAsync();
        using (var c1 = new SomeEntities(conn, contextOwnsConnection: false)) {
            //Use some stored procedures etc.
            count1 = await c1.SomeEntity1.CountAsync();
        }

        using (var c2 = new SomeEntities(conn, contextOwnsConnection: false)) {
            //Use some stored procedures etc.
            count2 = await c2.SomeEntity21.CountAsync();
        }
    }
    scope.Complete();
}

This works and does not throw UnintentionalCodeFirstException because you pass EntityConnection. This connection has information about EDMX metadata and that is what database first needs. When you pass plain SqlConnection - EF has no idea where to look for metadata and actually doesn't even know it should look for it - so it immediately assumes you are doing code-first.

Note that I pass EF connection string in code above. If you have some plain SqlConnection which you obtained by some other means, outside EF, this will not work, because connection string is needed. But, it's still possible because EntityConnection has constructor which accepts plain DbConnection. However, then you should pass reference to metadata yourself. If you are interested in this - I can provide code example of how to do that.

To check that you indeed prevent escalation in all cases - disable pooling (Pooling=false in connection string) and stop DTC service, then run this code - it should run fine. Then run another code which does not share the same connection and you should observe error indicating escalation was about to happen but service is not available.


问:
Haxe - How to initialize all members of an array to the same value?
I need to initialize an array with given size and same value.

For example, create an array of int that has size 10 and set all values to 0.

```<code>Int[] array = new Int[10]{0}
</code>```

In other languages it's very easy, but I'm not sure how to solve this problem on Haxe.

Please help me.

答:
You could use Array Comprehension</p>

```<code>var array:Array<Int> = [for (i in 0...10) 0];
</code>```

Body:
I need to initialize an array with given size and same value.

For example, create an array of int that has size 10 and set all values to 0.

Int[] array = new Int[10]{0}

In other languages it's very easy, but I'm not sure how to solve this problem on Haxe.

Please help me.

Body:
You could use Array Comprehension

var array:Array<Int> = [for (i in 0...10) 0];


问:
What type signature to use for an iterator generated from a slice?
I have this toy example, but it's what I'm trying to accomplish:

```<code>fn lazy_vec() {
    let vec: Vec<i64> = vec![1, 2, 3, 4, 5];
    let mut iter: Box<Iterator<Item = i64>> = Box::new(vec.into_iter());
    iter = Box::new(iter.map(|x| x + 1));
    // potentially do additional similar transformations to iter
    println!("{:?}", iter.collect::<Vec<_>>());
}
</code>```

This (if I'm not mistaken) is a lazy iterator pattern, and the actual map operation doesn't occur until .collect() is called. I want to do the same thing with slices:

```<code>fn lazy_slice() {
    let vec: Vec<i64> = vec![1, 2, 3, 4, 5];
    let slice: &[i64] = &vec[..3];
    let mut iter: Box<Iterator<Item = i64>> = Box::new(slice.into_iter());
    iter = Box::new(iter.map(|x| x + 1));
    // potentially do additional similar transformations to iter
    println!("{:?}", iter.collect::<Vec<_>>());
}
</code>```

This results in a type mismatch:

error[E0271]: type mismatch resolving `<std::slice::Iter<'_, i64> as std::iter::Iterator>::Item == i64`
 --> src/main.rs:4:47
  |
4 |     let mut iter: Box<Iterator<Item = i64>> = Box::new(slice.into_iter());
  |                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected reference, found i64
  |
  = note: expected type `&i64`
             found type `i64`
  = note: required for the cast to the object type `std::iter::Iterator<Item=i64>`
```

<p>I can't figure out what I need to do to resolve this error. The second <code>note</code> made me think I needed:</p>

```iter = Box::new(iter.map(|x| x + 1) as Iterator<Item = i64>);
```

<p>or</p>

```iter = Box::new(iter.map(|x| x + 1)) as Box<Iterator<Item = i64>>;
```

<p>These fail with other errors depending on the exact syntax (e.g. <code>expected reference, found i64</code>, or <code>expected i64, found &i64</code>). I've tried other ways to declare the types involved, but I'm basically just blindly adding <code>&</code> and <code>*</code> in places and not making any progress.</p>

<p>What am I missing here? What do I need to change in order to make this compile?</p>

<hr>

<p><strong>Edit</strong></p>

<p>Here's a slightly more concrete example - I need <code>iter</code> to be <code>mut</code> so that I can compose an unknown number of such transformations before actually invoking <code>.collect()</code>. My impression was this was a somewhat common pattern, apologies if that wasn't correct.</p>

```fn lazy_vec(n: i64) {
    let vec: Vec<i64> = vec![1, 2, 3, 4, 5];
    let mut iter: Box<Iterator<Item = i64>> = Box::new(vec.into_iter());
    for _ in 0..n {
        iter = Box::new(iter.map(|x| x + 1));
    }
    println!("{:?}", iter.collect::<Vec<_>>());
}
```

<p>I'm aware I could rewrite this specific task in a simpler way (e.g. a single <code>map</code> that adds <code>n</code> to each element) - it's an oversimplified MCVE of the problem I'm running into. My issue is this works for <code>lazy_vec</code>, but I'm not sure how to do the same with slices.</p>

<hr>

<p><strong>Edit 2</strong></p>

<p>I'm just learning Rust and some of the nomenclature and concepts are new to me. Here's what I'm envisioning doing in Python, for comparison. My intent is to do the same thing with slices that I can currently do with vectors.</p>

```#!/usr/bin/env python3

import itertools

ls = [i for i in range(10)]

def lazy_work(input):
  for i in range(10):
    input = (i + 1 for i in input)
  # at this point no actual work has been done
  return input

print("From list: %s" % list(lazy_work(ls)))
print("From slice: %s" % list(lazy_work(itertools.islice(ls, 5))))
```

Obviously in Python there's no issues with typing, but hopefully that more clearly demonstrates my intent?

答:
As discussed in What is the difference between iter and into_iter?, these methods create iterators which yield different types when called on a Vec compared to a slice.

[T]::iter and [T]::into_iter both return an iterator which yields values of type &T. That means that the returned value doesn't implement Iterator<Item = i64> but instead  Iterator<Item = &i64>, as the error message states.

However, your subsequent map statements change the type of the iterator's item to an i64, which means the type of the iterator would also need to change. As an analogy, you've essentially attempted this:

```<code>let mut a: &i64 = &42;
a = 99;
</code>```

Iterator::cloned exists to make clones of the iterated value. In this case, it converts a &i64 to an i64 essentially dereferencing the value:

```<code>fn lazy_slice(n: i64) {
    let array = [1i64, 2, 3, 4, 5];
    let mut iter: Box<Iterator<Item = i64>> = Box::new(array.iter().cloned());
    for _ in 0..n {
        iter = Box::new(iter.map(|x| x + 1));
    }
    println!("{:?}", iter.collect::<Vec<_>>());
}
</code>```

Body:
I have this toy example, but it's what I'm trying to accomplish:

fn lazy_vec() {
    let vec: Vec<i64> = vec![1, 2, 3, 4, 5];
    let mut iter: Box<Iterator<Item = i64>> = Box::new(vec.into_iter());
    iter = Box::new(iter.map(|x| x + 1));
    // potentially do additional similar transformations to iter
    println!("{:?}", iter.collect::<Vec<_>>());
}

This (if I'm not mistaken) is a lazy iterator pattern, and the actual map operation doesn't occur until .collect() is called. I want to do the same thing with slices:

fn lazy_slice() {
    let vec: Vec<i64> = vec![1, 2, 3, 4, 5];
    let slice: &[i64] = &vec[..3];
    let mut iter: Box<Iterator<Item = i64>> = Box::new(slice.into_iter());
    iter = Box::new(iter.map(|x| x + 1));
    // potentially do additional similar transformations to iter
    println!("{:?}", iter.collect::<Vec<_>>());
}

This results in a type mismatch:

error[E0271]: type mismatch resolving `<std::slice::Iter<'_, i64> as std::iter::Iterator>::Item == i64`
 --> src/main.rs:4:47
  |
4 |     let mut iter: Box<Iterator<Item = i64>> = Box::new(slice.into_iter());
  |                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected reference, found i64
  |
  = note: expected type `&i64`
             found type `i64`
  = note: required for the cast to the object type `std::iter::Iterator<Item=i64>`

I can't figure out what I need to do to resolve this error. The second note made me think I needed:

iter = Box::new(iter.map(|x| x + 1) as Iterator<Item = i64>);

or

iter = Box::new(iter.map(|x| x + 1)) as Box<Iterator<Item = i64>>;

These fail with other errors depending on the exact syntax (e.g. expected reference, found i64, or expected i64, found &i64). I've tried other ways to declare the types involved, but I'm basically just blindly adding & and * in places and not making any progress.

What am I missing here? What do I need to change in order to make this compile?

Edit

Here's a slightly more concrete example - I need iter to be mut so that I can compose an unknown number of such transformations before actually invoking .collect(). My impression was this was a somewhat common pattern, apologies if that wasn't correct.

fn lazy_vec(n: i64) {
    let vec: Vec<i64> = vec![1, 2, 3, 4, 5];
    let mut iter: Box<Iterator<Item = i64>> = Box::new(vec.into_iter());
    for _ in 0..n {
        iter = Box::new(iter.map(|x| x + 1));
    }
    println!("{:?}", iter.collect::<Vec<_>>());
}

I'm aware I could rewrite this specific task in a simpler way (e.g. a single map that adds n to each element) - it's an oversimplified MCVE of the problem I'm running into. My issue is this works for lazy_vec, but I'm not sure how to do the same with slices.

Edit 2

I'm just learning Rust and some of the nomenclature and concepts are new to me. Here's what I'm envisioning doing in Python, for comparison. My intent is to do the same thing with slices that I can currently do with vectors.

#!/usr/bin/env python3

import itertools

ls = [i for i in range(10)]

def lazy_work(input):
  for i in range(10):
    input = (i + 1 for i in input)
  # at this point no actual work has been done
  return input

print("From list: %s" % list(lazy_work(ls)))
print("From slice: %s" % list(lazy_work(itertools.islice(ls, 5))))

Obviously in Python there's no issues with typing, but hopefully that more clearly demonstrates my intent?

Body:
As discussed in What is the difference between iter and into_iter?, these methods create iterators which yield different types when called on a Vec compared to a slice.

[T]::iter and [T]::into_iter both return an iterator which yields values of type &T. That means that the returned value doesn't implement Iterator<Item = i64> but instead  Iterator<Item = &i64>, as the error message states.

However, your subsequent map statements change the type of the iterator's item to an i64, which means the type of the iterator would also need to change. As an analogy, you've essentially attempted this:

let mut a: &i64 = &42;
a = 99;

Iterator::cloned exists to make clones of the iterated value. In this case, it converts a &i64 to an i64 essentially dereferencing the value:

fn lazy_slice(n: i64) {
    let array = [1i64, 2, 3, 4, 5];
    let mut iter: Box<Iterator<Item = i64>> = Box::new(array.iter().cloned());
    for _ in 0..n {
        iter = Box::new(iter.map(|x| x + 1));
    }
    println!("{:?}", iter.collect::<Vec<_>>());
}


问:
power distribution on a 6 wheel drive train
I'm on a FIRST Robotics Competition team and we're looking into a 6 wheel drive train  for the upcoming season. We're going to use arcade drive with a basic wheel type, like kit of parts. I'm just wondering what other FRC teams have done in the past and what the power distribution looked like. </p>

答:
Team 10874 here.

So my team uses a 2 wheel drive but it basically goes like this : Our right motor's power is negated if it comes from the stick because using the gamepad sends negative values, while our left motor's power is kept positive. For distribution of power, we ask ourselves a question; What direction should the robot drive? If straight, then the integer literal in each power function should be set to 1. If reverse, the opposite (-1). Now my team had a specific question when we switched from Blockly to Java. How does a DC Motor rotate..? It usually only goes straight and backwards. The way you do it is this : If you have two wheel drive (like my team did for the majority of our time), one motor's power should be set to 1 while the other motor's power is set to negative one. Assuming the first motor is the left motor, and the second is the right try to visualize this, the left motor is going straight and the right motor is going in reverse. This will cause the robot to turn to the left! Here is some code

```<code>private void turn()
    leftFrontMotor.setPower(1);
    leftBackMotor.setPower(1);
    rightFrontMotor.setPower(-1);
    rightBackMotor.setPower(-1);
</code>```

Body:
Team 10874 here.

So my team uses a 2 wheel drive but it basically goes like this : Our right motor's power is negated if it comes from the stick because using the gamepad sends negative values, while our left motor's power is kept positive. For distribution of power, we ask ourselves a question; What direction should the robot drive? If straight, then the integer literal in each power function should be set to 1. If reverse, the opposite (-1). Now my team had a specific question when we switched from Blockly to Java. How does a DC Motor rotate..? It usually only goes straight and backwards. The way you do it is this : If you have two wheel drive (like my team did for the majority of our time), one motor's power should be set to 1 while the other motor's power is set to negative one. Assuming the first motor is the left motor, and the second is the right try to visualize this, the left motor is going straight and the right motor is going in reverse. This will cause the robot to turn to the left! Here is some code

private void turn()
    leftFrontMotor.setPower(1);
    leftBackMotor.setPower(1);
    rightFrontMotor.setPower(-1);
    rightBackMotor.setPower(-1);