问:
XInclude not working with Saxon?
I have this XSLT stylesheet xinclude-test.xsl:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xi="http://www.w3.org/2001/XInclude">
  <xsl:output method="text"/>
  <xi:include href="xinclude-test-included.xml"/>

  <!-- <xsl:param name="test"> -->
  <!--   aaa -->
  <!-- </xsl:param> -->

  <xsl:template name="main">
    <xsl:value-of select="$test"/>
  </xsl:template>
</xsl:stylesheet>
</code>```

The included file xinclude-test-included.xml is

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:param name="test" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
aaa
</xsl:param>
</code>```

When I evaluate the stylesheet with

```<code>saxon -xi -xsl:xinclude-test.xsl -it:main -t
</code>```

It prints

```<code>Saxon-HE 9.8.0.1J from Saxonica
Java version 1.8.0_31
Static error at char 5 in xsl:value-of/@select on line 13 column 35 of xinclude-test.xsl:
  XPST0008: Variable test has not been declared (or its declaration is not in scope)
Errors were reported during stylesheet compilation
</code>```

where I expect it to print "aaa".

However if I use another stylesheet to load the first XSLT:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="2.0">
  <xsl:template name="main">
    <xsl:copy-of select="document('xinclude-test.xsl')"/>
  </xsl:template>
</xsl:stylesheet>
</code>```

it correctly does the XInclude processing.

So what did I do wrong in my first XSLT?

答:
The documentation doesn't match the code, I'm afraid: Saxon makes no attempt to apply the -xi option to the stylesheet document. We will have to make a decision about whether to treat the code or the documentation as correct.

Raised as a bug here: https://saxonica.plan.io/issues/3343

Title: XInclude not working with Saxon?

Body:
I have this XSLT stylesheet xinclude-test.xsl:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xi="http://www.w3.org/2001/XInclude">
  <xsl:output method="text"/>
  <xi:include href="xinclude-test-included.xml"/>

  <xsl:template name="main">
    <xsl:value-of select="$test"/>
  </xsl:template>
</xsl:stylesheet>

The included file xinclude-test-included.xml is

<?xml version="1.0" encoding="utf-8"?>
<xsl:param name="test" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
aaa
</xsl:param>

When I evaluate the stylesheet with

saxon -xi -xsl:xinclude-test.xsl -it:main -t

It prints

Saxon-HE 9.8.0.1J from Saxonica
Java version 1.8.0_31
Static error at char 5 in xsl:value-of/@select on line 13 column 35 of xinclude-test.xsl:
  XPST0008: Variable test has not been declared (or its declaration is not in scope)
Errors were reported during stylesheet compilation

where I expect it to print "aaa".

However if I use another stylesheet to load the first XSLT:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="2.0">
  <xsl:template name="main">
    <xsl:copy-of select="document('xinclude-test.xsl')"/>
  </xsl:template>
</xsl:stylesheet>

it correctly does the XInclude processing.

So what did I do wrong in my first XSLT?


来源: stackexchange

问:
What is the equivalent of Java's Stream#Peek method in Linq C#?
I have been used to using Java's Stream#Peek method so much as it's a useful method to debug intermediate stream operation. For those of you who are not familiar with the Stream#Peek method, below shows the definition of it:

Stream<T> peek(Consumer<? super T> action)

Returns a stream consisting of the elements of this stream,
  additionally performing the provided action on each element as
  elements are consumed from the resulting stream. This is an
  intermediate operation.

Consider this simple example below:

```<code>List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> result = integerList.stream()
                                  .filter(i -> i % 2 == 0)
                                  .peek(System.out::println)
                                  .collect(Collectors.toList());
</code>```

With the Stream#Peek method, this should basically allow me to print all the even numbers to the console so that I can test to see if that's what I would expect.

I have tried to find an answer to the question at hand but can't seem to find a similar method in C#, does anyone know the equivalent of Java's Stream#Peek or some other method with similar behavior?

答:
EDIT: this answer is outdated, after edits to the original question. The initial question was worded with the intention of peek-ing all the filter-ed values, then performing findFirst:

```<code>List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Optional<Integer> result = integerList.stream()
                                      .filter(i -> i % 2 ==0== 0)
                                      .peek(System.out::println)
                                      .findFirst();
</code>```

As far as I know, there's no built-in LINQ solution to do this, so here's an extension method:

```<code>public static IEnumerable<T> Peek<T>(this IEnumerable<T> source, Action<T> action)
{
    using (var iterator = source.GetEnumerator())
    {
        while (iterator.MoveNext())
        {
            action(iterator.Current);
        }
    }

    using (var iterator = source.GetEnumerator())
    {
        while (iterator.MoveNext())
        {
            yield return iterator.Current;
        }
    }
}
</code>```

Usage:

```<code>var integerList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int? result = integerList.Where(i => i % 2 == 0)
                         .Peek(i => Console.WriteLine(i))
                         .FirstOrDefault();

Console.WriteLine(result);
</code>```

Output:

```<code>2
4
6
8
10
2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been used to using Java's Stream#Peek method so much as it's a useful method to debug intermediate stream operation. For those of you who are not familiar with the Stream#Peek method, below shows the definition of it:

Stream<T> peek(Consumer<? super T> action)

Returns a stream consisting of the elements of this stream,
  additionally performing the provided action on each element as
  elements are consumed from the resulting stream. This is an
  intermediate operation.

Consider this simple example below:

List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<Integer> result = integerList.stream()
                                  .filter(i -> i % 2 == 0)
                                  .peek(System.out::println)
                                  .collect(Collectors.toList());

With the Stream#Peek method, this should basically allow me to print all the even numbers to the console so that I can test to see if that's what I would expect.

I have tried to find an answer to the question at hand but can't seem to find a similar method in C#, does anyone know the equivalent of Java's Stream#Peek or some other method with similar behavior?

Body:
EDIT: this answer is outdated, after edits to the original question. The initial question was worded with the intention of peek-ing all the filter-ed values, then performing findFirst:

List<Integer> integerList = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Optional<Integer> result = integerList.stream()
                                      .filter(i -> i % 2 ==0== 0)
                                      .peek(System.out::println)
                                      .findFirst();

As far as I know, there's no built-in LINQ solution to do this, so here's an extension method:

public static IEnumerable<T> Peek<T>(this IEnumerable<T> source, Action<T> action)
{
    using (var iterator = source.GetEnumerator())
    {
        while (iterator.MoveNext())
        {
            action(iterator.Current);
        }
    }

    using (var iterator = source.GetEnumerator())
    {
        while (iterator.MoveNext())
        {
            yield return iterator.Current;
        }
    }
}

Usage:

var integerList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int? result = integerList.Where(i => i % 2 == 0)
                         .Peek(i => Console.WriteLine(i))
                         .FirstOrDefault();

Console.WriteLine(result);

Output:

2
4
6
8
10
2


问:
How to finish all fetch before executing next function in React?
Using ReactJS, I have two different API points that I am trying to get and restructure: students and scores. They are both an array of objects.

My goal is : first, get students and scores, and second, with students and scores saved in state, I will modify them and create a new state based on students and scores state. In short, I have 3 functions: getStudents, getScores, and rearrangeStudentsAndScores. getStudents and getScores need to finish before rearrangeStudentsAndScores can run.

My problem is: sometimes rearrangeStudentsAndScores will run before getScores would complete. That messed rearrangeStudentsAndScores up. But sometimes it would complete. Not sure why it works 50% of the time, but I need to make it work 100% of the time.

This is what I have to fetch students and scores in my Client file:

```<code>function getStudents(cb){
    return fetch(`api/students`, {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then((response) => response.json())
    .then(cb)
};

function getScores(cb){
    return fetch(`api/scores`, {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then((response) => response.json())
    .then(cb)
};
</code>```

I then combined them together:

```<code>function getStudentsAndScores(cbStudent, cbScores, cbStudentsScores){
    getStudents(cbStudent).then(getScores(cbScores)).then(cbStudentsScores);
}
</code>```

In my react app, I have the following:

```<code>getStudentsAndScores(){
    Client.getStudentsAndScores(
        (students) => {this.setState({students})},
        (scores) => {this.setState({scores})},
        this.rearrangeStudentsWithScores
    )
}

rearrangeStudentsWithScores(){
    console.log('hello rearrange!')
    console.log('students:')
    console.log(this.state.students);
    console.log('scores:');
    console.log(this.state.scores);        //this returns [] half of the time
    if (this.state.students.length > 0){
        const studentsScores = {};
        const students = this.state.students;
        const scores = this.state.scores;
        ...
    }
}
</code>```

Somehow, by the time I get to rearrangeStudentsWithScores, this.state.scores will still be [].

How can I ensure that this.state.students and this.state.scores are both loaded before I run rearrangeStudentsWithScores?

答:
Your code mixes continuation callbacks and Promises. You'll find it easier to reason about it you use one approach for async flow control. Let's use Promises, because fetch uses them.

```<code>// Refactor getStudents and getScores to return  Promise for their response bodies
function getStudents(){
  return fetch(`api/students`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then((response) => response.json())
};

function getScores(){
  return fetch(`api/scores`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then((response) => response.json())
};

// Request both students and scores in parallel and return a Promise for both values.
// `Promise.all` returns a new Promise that resolves when all of its arguments resolve.
function getStudentsAndScores(){
  return Promise.all([getStudents(), getScores()])
}

// When this Promise resolves, both values will be available.
getStudentsAndScores()
  .then(([students, scores]) => {
    // both have loaded!
    console.log(students, scores);
  })
</code>```

As well as being simpler, this approach is more efficient because it makes both requests at the same time; your approach waited until the students were fetched before fetching the scores.

See Promise.all on MDN

Body:
Using ReactJS, I have two different API points that I am trying to get and restructure: students and scores. They are both an array of objects.

My goal is : first, get students and scores, and second, with students and scores saved in state, I will modify them and create a new state based on students and scores state. In short, I have 3 functions: getStudents, getScores, and rearrangeStudentsAndScores. getStudents and getScores need to finish before rearrangeStudentsAndScores can run.

My problem is: sometimes rearrangeStudentsAndScores will run before getScores would complete. That messed rearrangeStudentsAndScores up. But sometimes it would complete. Not sure why it works 50% of the time, but I need to make it work 100% of the time.

This is what I have to fetch students and scores in my Client file:

function getStudents(cb){
    return fetch(`api/students`, {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then((response) => response.json())
    .then(cb)
};

function getScores(cb){
    return fetch(`api/scores`, {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then((response) => response.json())
    .then(cb)
};

I then combined them together:

function getStudentsAndScores(cbStudent, cbScores, cbStudentsScores){
    getStudents(cbStudent).then(getScores(cbScores)).then(cbStudentsScores);
}

In my react app, I have the following:

getStudentsAndScores(){
    Client.getStudentsAndScores(
        (students) => {this.setState({students})},
        (scores) => {this.setState({scores})},
        this.rearrangeStudentsWithScores
    )
}

rearrangeStudentsWithScores(){
    console.log('hello rearrange!')
    console.log('students:')
    console.log(this.state.students);
    console.log('scores:');
    console.log(this.state.scores);        //this returns [] half of the time
    if (this.state.students.length > 0){
        const studentsScores = {};
        const students = this.state.students;
        const scores = this.state.scores;
        ...
    }
}

Somehow, by the time I get to rearrangeStudentsWithScores, this.state.scores will still be [].

How can I ensure that this.state.students and this.state.scores are both loaded before I run rearrangeStudentsWithScores?

Body:
Your code mixes continuation callbacks and Promises. You'll find it easier to reason about it you use one approach for async flow control. Let's use Promises, because fetch uses them.

// Refactor getStudents and getScores to return  Promise for their response bodies
function getStudents(){
  return fetch(`api/students`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then((response) => response.json())
};

function getScores(){
  return fetch(`api/scores`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then((response) => response.json())
};

// Request both students and scores in parallel and return a Promise for both values.
// `Promise.all` returns a new Promise that resolves when all of its arguments resolve.
function getStudentsAndScores(){
  return Promise.all([getStudents(), getScores()])
}

// When this Promise resolves, both values will be available.
getStudentsAndScores()
  .then(([students, scores]) => {
    // both have loaded!
    console.log(students, scores);
  })

As well as being simpler, this approach is more efficient because it makes both requests at the same time; your approach waited until the students were fetched before fetching the scores.

See Promise.all on MDN


问:
Get all AD Users and their group memberships (recursively) using Powershell
I have a script from a previously answered question, but don't have enough reputation to comment. I tried to run that script and came across this error message:

Export-CSV : Cannot append CSV content to the following file: C:\users.csv. The appended object does not have a property that corresponds to the following column: User;Group. To continue with mismatched properties, add the -Force parameter, and then retry the command.

How can I debug this script to resolve this issue?

```<code>Function Get-ADGroupsRecursive{
Param([String[]]$Groups)
Begin{
    $Results = @()
}
Process{
    ForEach($Group in $Groups){
        $Results+=$Group
        ForEach($Object in (Get-ADGroupMember $Group|?{$_.objectClass -eq "Group"})){
            $Results += Get-ADGroupsRecursive $Object
        }
    }
}
End{
    $Results | Select -Unique
}}

import-module activedirectory

$users = get-aduser -Filter {Name -Like "*"} -Searchbase "OU=Sample Accounts,DC=domain,DC=com" -Properties MemberOf | Where-Object { $_.Enabled -eq 'True' }

$targetFile = "C:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"

foreach ($user in $users)
{
    $Groups = $User.MemberOf
    $Groups += $Groups | %{Get-ADGroupsRecursive $_}
$Groups | %{New-Object PSObject -Property @{User=$User;Group=$_}}|Export-CSV $targetfile -notype -append
}
</code>```

答:
try this function</p>

```<code>function Get-InChainGroups
{
    param (
        [parameter(mandatory = $true)]
        $user,
        $domain)

    $user1 = (get-aduser -filter { name -eq $user } -server $domain).distinguishedname
    Write-verbose "checking $user"
    $ldap = "(&(objectcategory=group)(groupType:1.2.840.113556.1.4.803:=2147483648)(member:1.2.840.113556.1.4.1941:=$user1))"

    try { Get-ADobject -LDAPFilter $ldap -server $domain | select  @{ n = 'Identity'; e = { $user } }, Name, @{ n = 'DN'; e = { $_.distinguishedname } } | ft -a }
    catch { "Exception occurred" }

}
</code>```

Body:
I have a script from a previously answered question, but don't have enough reputation to comment. I tried to run that script and came across this error message:

Export-CSV : Cannot append CSV content to the following file: C:\users.csv. The appended object does not have a property that corresponds to the following column: User;Group. To continue with mismatched properties, add the -Force parameter, and then retry the command.

How can I debug this script to resolve this issue?

Function Get-ADGroupsRecursive{
Param([String[]]$Groups)
Begin{
    $Results = @()
}
Process{
    ForEach($Group in $Groups){
        $Results+=$Group
        ForEach($Object in (Get-ADGroupMember $Group|?{$_.objectClass -eq "Group"})){
            $Results += Get-ADGroupsRecursive $Object
        }
    }
}
End{
    $Results | Select -Unique
}}

import-module activedirectory

$users = get-aduser -Filter {Name -Like "*"} -Searchbase "OU=Sample Accounts,DC=domain,DC=com" -Properties MemberOf | Where-Object { $_.Enabled -eq 'True' }

$targetFile = "C:\users.csv"
rm $targetFile
Add-Content $targetFile "User;Group"

foreach ($user in $users)
{
    $Groups = $User.MemberOf
    $Groups += $Groups | %{Get-ADGroupsRecursive $_}
$Groups | %{New-Object PSObject -Property @{User=$User;Group=$_}}|Export-CSV $targetfile -notype -append
}

Body:
try this function

function Get-InChainGroups
{
    param (
        [parameter(mandatory = $true)]
        $user,
        $domain)

    $user1 = (get-aduser -filter { name -eq $user } -server $domain).distinguishedname
    Write-verbose "checking $user"
    $ldap = "(&(objectcategory=group)(groupType:1.2.840.113556.1.4.803:=2147483648)(member:1.2.840.113556.1.4.1941:=$user1))"

    try { Get-ADobject -LDAPFilter $ldap -server $domain | select  @{ n = 'Identity'; e = { $user } }, Name, @{ n = 'DN'; e = { $_.distinguishedname } } | ft -a }
    catch { "Exception occurred" }

}


问:
Querying multiple tables in Big Query
As it is not possible to update data within a table in BigQuery, and supports only append mechanism, I have decided to create new tables on monthly basis. So suppose for year 2012 the tables would be (tbl_012012, tbl_022012, tbl_032012,...tbl_122012). Each record will be stored along with date timestamp as string.

Now, if my application wants to fetch records ranging from Jan 2012(tbl_012012) to March 2012(tbl_032012), will BigQuery API automatically traverse through the desired tables via single SQL range query or will I have to write multiple SQL queries with extra application code to retrieve each query result and then aggregate them altogether?

答:
2017 update:

With BigQuery #standardSQL - you can either use standard UNION ALL to go through multiple tables, or you can use a * to match all tables that share the same prefix. When using the * matcher, you will also have access to the meta-column _TABLE_SUFFIX - to know which table the rows came from.

```<code>SELECT * FROM Roster
UNION ALL
SELECT * FROM TeamMascot
</code>```

Title: Querying multiple tables in Big Query

Body:
2017 update:

With BigQuery #standardSQL - you can either use standard UNION ALL to go through multiple tables, or you can use a * to match all tables that share the same prefix. When using the * matcher, you will also have access to the meta-column _TABLE_SUFFIX - to know which table the rows came from.

SELECT * FROM Roster
UNION ALL
SELECT * FROM TeamMascot


问:
Kafka and apache Spark streaming cluster configuration
I need to run some Spark scala scripts on a cluster of machines. Data are generated by an Apache Kafka producer running on 1 of these machines.

I have already configured the slaves.template file in the conf directory in Apache Spark with the URL of every node of the cluster.

I run the scripts with this instruction:
./bin/spark-submit --class com.unimi.lucaf.App /Users/lucaferrari/scala-spark-script2/target/scala-spark-script-1.0.jar but it seemes that it is only running on the master node.

How can i fix it?

Thanks

SOLVED

In folder conf renamed the slaves.template file to slaves and added the URL of every worker

In folder conf renamed the spark-env.sh.templatefile to spark-env.sh and added these lines:

SPARK_MASTER_HOST=1.2.3.4

SPARK_MASTER_PORT=7077

SPARK_MASTER_WEBUI_PORT=4444

SPARK_WORKER_WEBUI_PORT=8081

In folder sbin on the master machine I run the start-master.sh script.

On every worker, in folder sbin I run start-slave.sh spark://master-url:master-port. master-url and master-port must be the same configured in the spark-env.sh file.

On the spark configuration of the script I've added also the master-url (val sparkConf = new SparkConf().setAppName("SparkScript").setMaster("spark://master-url:master-port")

Run the script with ./bin/spark-submit --class com.unimi.lucaf.App /home/spark1/scala-spark-script2/target/scala-spark-script-1.0.jar --master spark://master-url:master-port --deploy-mode cluster

答:
Have you tried to add the

```<code>--master <master_url>
</code>```

option? If you omit this option to spark-submit, it will run locally.

You may also check Spark's documentation on spark-submit options: https://spark.apache.org/docs/latest/submitting-applications.html#launching-applications-with-spark-submit

Body:
Have you tried to add the

--master <master_url>

option? If you omit this option to spark-submit, it will run locally.

You may also check Spark's documentation on spark-submit options: https://spark.apache.org/docs/latest/submitting-applications.html#launching-applications-with-spark-submit


问:
Understanding the limitations of the bignumber.js library
I have recently found the bignumber.js library:

source: https://github.com/MikeMcl/bignumber.js

What I'm not sure of is if there is a limit to how big the number operations can be? I have been looking into the documentation, trying to find sources online. But nothing as of yet.

答:
If you run this:

```<code>console.log(new BigNumber('123456789012345678901234567890').c);
</code>```

You can see that numbers are stored as arrays, of maximum 14 digits

So the actual limitation would be the maximum length you can have for an array, multiplied by 14. This depends a lot on your machine, but assuming you have the best machine ever, ECMA-262 v6.0 says the limit is for the length of an array is 2^32-1, which is the size of ToUint32, so, theoretically, you could store a number with 14 * (2^32-1) digits using that library, that's something like:

```<code>console.log(new BigNumber(2).pow(32).sub(1).mul(14).toString());
</code>```

Which is something around 60129542130 digits

Body:
If you run this:

console.log(new BigNumber('123456789012345678901234567890').c);

You can see that numbers are stored as arrays, of maximum 14 digits

So the actual limitation would be the maximum length you can have for an array, multiplied by 14. This depends a lot on your machine, but assuming you have the best machine ever, ECMA-262 v6.0 says the limit is for the length of an array is 2^32-1, which is the size of ToUint32, so, theoretically, you could store a number with 14 * (2^32-1) digits using that library, that's something like:

console.log(new BigNumber(2).pow(32).sub(1).mul(14).toString());

Which is something around 60129542130 digits


问:
Visual Studio setup doesn't start
I have just downloaded the Visual Studio Community setup, run it and it doesn't go further than administrator confirmation, then it just shuts down. It worked for me before on Windows 8.1 (now I am on Windows 10 x64).</p>

答: This guide solved my problem, Visual Studio installed without any problems.</p>

Title: Visual Studio setup doesn't start


问:
Removing the second "|" on the last position
Here are some examples from my data:

```<code>a <-c("sp|Q9Y6W5|","sp|Q9HB90|,sp|Q9NQL2|","orf|NCBIAAYI_c_1_1023|",
     "orf|NCBIACEN_c_10_906|,orf|NCBIACEO_c_5_1142|",
      "orf|NCBIAAYI_c_258|,orf|aot172_c_6_302|,orf|aot180_c_2_405|")
</code>```

For a: The individual strings can contain even more entries of "sp|" and "orf"

The results have to be like this:

```<code>[1] "sp|Q9Y6W5" "sp|Q9HB90,sp|Q9NQL2" "orf|NCBIAAYI_c_1_1023"
   "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142"
   "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405"
</code>```

So the aim is to remove the last "|" for each "sp|" and "orf|" entry. It seems that "|" is a special challenge because it is a metacharacter in regular expressions. Furthermore, the length and composition of the "orf|" entries varying a lot. The only things they have in common is "orf|" or "sp|" at the beginning and that "|" is on the last position. I tried different things with gsub() but also with the stringr package or regexpr() or [:punct:], but nothing really worked. Maybe it was just the wrong combination.

答:
You do not have to use a PCRE regex here as all you need can be done with the default TRE regex (if you specify perl=TRUE, the pattern is compiled with a PCRE regex engine and is sometimes slower than TRE default regex engine).

Here is the single simple gsub call:

```<code>gsub("\\|(,|$)", "\\1", a)
</code>```

See the online R demo. No lookarounds are really necessary, as you see.

Pattern details

\\| - a literal | symbol (because if you do not escape it or put into a bracket expression it will denote an alternation operator, see the line below)

(,|$)  - a capturing group (referenced to with \1 from the replacement pattern) matching either of the two alternatives:

, - a comma

| - or (the alternation operator)

$ - end of string anchor.

The \1 in the replacement string tells the regex engine to insert the contents stored in the capturing group #1 back into the resulting string (so, the commas are restored that way where necessary).

Body:
Here are some examples from my data:

a <-c("sp|Q9Y6W5|","sp|Q9HB90|,sp|Q9NQL2|","orf|NCBIAAYI_c_1_1023|",
     "orf|NCBIACEN_c_10_906|,orf|NCBIACEO_c_5_1142|",
      "orf|NCBIAAYI_c_258|,orf|aot172_c_6_302|,orf|aot180_c_2_405|")

For a: The individual strings can contain even more entries of "sp|" and "orf"

The results have to be like this:

[1] "sp|Q9Y6W5" "sp|Q9HB90,sp|Q9NQL2" "orf|NCBIAAYI_c_1_1023"
   "orf|NCBIACEN_c_10_906,orf|NCBIACEO_c_5_1142"
   "orf|NCBIAAYI_c_258,orf|aot172_c_6_302,orf|aot180_c_2_405"

So the aim is to remove the last "|" for each "sp|" and "orf|" entry. It seems that "|" is a special challenge because it is a metacharacter in regular expressions. Furthermore, the length and composition of the "orf|" entries varying a lot. The only things they have in common is "orf|" or "sp|" at the beginning and that "|" is on the last position. I tried different things with gsub() but also with the stringr package or regexpr() or [:punct:], but nothing really worked. Maybe it was just the wrong combination.

Body:
You do not have to use a PCRE regex here as all you need can be done with the default TRE regex (if you specify perl=TRUE, the pattern is compiled with a PCRE regex engine and is sometimes slower than TRE default regex engine).

Here is the single simple gsub call:

gsub("\\|(,|$)", "\\1", a)

See the online R demo. No lookarounds are really necessary, as you see.

Pattern details

\\| - a literal | symbol (because if you do not escape it or put into a bracket expression it will denote an alternation operator, see the line below)

(,|$)  - a capturing group (referenced to with \1 from the replacement pattern) matching either of the two alternatives:

, - a comma

| - or (the alternation operator)

$ - end of string anchor.

The \1 in the replacement string tells the regex engine to insert the contents stored in the capturing group #1 back into the resulting string (so, the commas are restored that way where necessary).


问:
Destroying app from Marathon puts it into the Deployments. How to destroy app in marathon?
I am trying to destroy my sample apps that I deployed using marathon framework. Now I am trying to destroy that app but unfortunately, I can not destroy them for some reason.

I have already tried:

restarting marathon service on my slave.

restarting mesos-manager.

restarting mesos-master.

checked if they are all connected to the each other properly.

Why would an app go in the deployment mode when I destroy it?
Is there any way to destroy this app now?
Errors I am getting are as follows,

While destroying app
Error Destroying Application
Error destroying null: App '/null' does not exist

Spawning a new app
App is locked by one or more deployments. Override with the option '?force=true'. View details at '/v2/deployments/

答:
Just tried

Restarting mesos-master

Restarting mesos-slave

Cleared cache for the mesos-zookeeper

Went inside mesos-manager docker image and restarted all services.

One of these is bound to work


问:
Wow64DisableWow64FsRedirection() function not working when compiled for 64-bit in Visual Studio in Window 10
I am facing an issue with Wow64DisableWow64FsRedirection().

When I compile for a 64-bit platform in Visual Studio 2010, it is not working in Window 10, it returns with error 1.

But, when I compile for a 32-bit platform instead, the function works in Window 10.

```<code>typedef BOOL(__stdcall *tFSRED)(HMODULE );

HMODULE hKernel = LoadLibrary(_T("Kernel32.dll")); // Get Kernel module handle
if (hKernel == NULL)
{
    return 2;
}

tFSRED pFunc;
pFunc = (tFSRED) GetProcAddress(hKernel, "Wow64DisableWow64FsRedirection");
ret = pFunc(&oldValue);  // Turn the file the file system redirector off
if (ret == FALSE)
{
    _tprintf(_T("\nFile System Redirection could not be turned off. Reason: %d"), GetLastError());
    return 4;
}
// ret is always TRUE when compile through 32-bit platform
// but ret return FALSE when compile through 64-bit platform
</code>```

In Visual Studio, if I compile for 64-bit platform, then after compile if I open the generated EXE in depends.exe, it shows 64 in front of the EXE.

After selecting a 32-bit platform, the generated EXE is 32-bit. That EXE works in my case, but I want my EXE to be 64-bit, so I am selecting 64-bit platform and I get a 64-bit EXE, but it is not working as I explained above.

答:
WOW64 emulation only applies to 32-bit executables running on a 64-bit system.  A 64-bit EXE should not try to use WOW64 functions (other than maybe IsWow64Process()) because the EXE will not be running inside of WOW64 to begin with.  That is why you are getting error code 1 (ERROR_INVALID_FUNCTION) in your 64-bit EXE.

So, either:

ifdef the code to skip WOW64 functions in a 64-bit compilation:

```<code>#ifndef _WIN64
typedef BOOL (WINAPI *tFSDisable)(PVOID*);
typedef BOOL (WINAPI *tFSRevert(PVOID);

HMODULE hKernel = GetModuleHandle(_T("Kernel32"));
tFSDisable pDisableFunc = (tFSDisable) GetProcAddress(hKernel, "Wow64DisableWow64FsRedirection");
tFSRevert pRevertFunc = (tFSRevert) GetProcAddress(hKernel, "Wow64RevertWow64FsRedirection");

PVOID oldValue;

if ((pDisableFunc) && (pRevertFunc))
{
    if (!pDisableFunc(&oldValue))  // Turn off the file system redirector
    {
        _tprintf(_T("\nFile System Redirection could not be turned off. Reason: %d"), GetLastError());
        return 4;
    }
}
#endif

// do file system operations as needed...

#ifndef _WIN64
if ((pDisableFunc) && (pRevertFunc))
{
    if (!pRevertFunc(oldValue))  // Restore the file system redirector
    {
        _tprintf(_T("\nFile System Redirection could not be restored. Reason: %d"), GetLastError());
        return 5;
    }
}
#endif
</code>```

omit the ifdef and just call the WOW64 functions only if IsWow64Process() reports the current process is actually running inside of WOW64:

```<code>typedef BOOL (WINAPI tW64P)(HANDLE, PBOOL);
typedef BOOL (WINAPI *tFSDisable)(PVOID*);
typedef BOOL (WINAPI *tFSRevert(PVOID);

HMODULE hKernel = GetModuleHandle(_T("Kernel32"));

tW64P pIsWow64Func = (tW64P) GetProcAddress(hKernel, "IsWow64Process");
tFSDisable pDisableFunc = NULL;
tFSRevert pRevertFunc = NULL;

BOOL bIsWow64 = FALSE;
if (pIsWow64Func)
{
    pIsWow64Func(GetCurrentProcess(), &bIsWow64);
    if (bIsWow64)
    {
        pDisableFunc = (tFSDisable) GetProcAddress(hKernel, "Wow64DisableWow64FsRedirection");
        pRevertFunc = (tFSRevert) GetProcAddress(hKernel, "Wow64RevertWow64FsRedirection");
    }
}

PVOID oldValue;

if ((pDisableFunc) && (pRevertFunc))
{
    if (!pDisableFunc(&oldValue))  // Turn off the file system redirector
    {
        _tprintf(_T("\nFile System Redirection could not be turned off. Reason: %d"), GetLastError());
        return 4;
    }
}

// do file system operations as needed...

if ((pDisableFunc) && (pRevertFunc))
{
    if (!pRevertFunc(oldValue))  // Restore the file system redirector
    {
        _tprintf(_T("\nFile System Redirection could not be restored. Reason: %d"), GetLastError());
        return 5;
    }
}
</code>```

Body:
I am facing an issue with Wow64DisableWow64FsRedirection().

When I compile for a 64-bit platform in Visual Studio 2010, it is not working in Window 10, it returns with error 1.

But, when I compile for a 32-bit platform instead, the function works in Window 10.

typedef BOOL(__stdcall *tFSRED)(HMODULE );

HMODULE hKernel = LoadLibrary(_T("Kernel32.dll")); // Get Kernel module handle
if (hKernel == NULL)
{
    return 2;
}

tFSRED pFunc;
pFunc = (tFSRED) GetProcAddress(hKernel, "Wow64DisableWow64FsRedirection");
ret = pFunc(&oldValue);  // Turn the file the file system redirector off
if (ret == FALSE)
{
    _tprintf(_T("\nFile System Redirection could not be turned off. Reason: %d"), GetLastError());
    return 4;
}
// ret is always TRUE when compile through 32-bit platform
// but ret return FALSE when compile through 64-bit platform

In Visual Studio, if I compile for 64-bit platform, then after compile if I open the generated EXE in depends.exe, it shows 64 in front of the EXE.

After selecting a 32-bit platform, the generated EXE is 32-bit. That EXE works in my case, but I want my EXE to be 64-bit, so I am selecting 64-bit platform and I get a 64-bit EXE, but it is not working as I explained above.

Body:
WOW64 emulation only applies to 32-bit executables running on a 64-bit system.  A 64-bit EXE should not try to use WOW64 functions (other than maybe IsWow64Process()) because the EXE will not be running inside of WOW64 to begin with.  That is why you are getting error code 1 (ERROR_INVALID_FUNCTION) in your 64-bit EXE.

So, either:

ifdef the code to skip WOW64 functions in a 64-bit compilation:

#ifndef _WIN64
typedef BOOL (WINAPI *tFSDisable)(PVOID*);
typedef BOOL (WINAPI *tFSRevert(PVOID);

HMODULE hKernel = GetModuleHandle(_T("Kernel32"));
tFSDisable pDisableFunc = (tFSDisable) GetProcAddress(hKernel, "Wow64DisableWow64FsRedirection");
tFSRevert pRevertFunc = (tFSRevert) GetProcAddress(hKernel, "Wow64RevertWow64FsRedirection");

PVOID oldValue;

if ((pDisableFunc) && (pRevertFunc))
{
    if (!pDisableFunc(&oldValue))  // Turn off the file system redirector
    {
        _tprintf(_T("\nFile System Redirection could not be turned off. Reason: %d"), GetLastError());
        return 4;
    }
}
#endif

// do file system operations as needed...

#ifndef _WIN64
if ((pDisableFunc) && (pRevertFunc))
{
    if (!pRevertFunc(oldValue))  // Restore the file system redirector
    {
        _tprintf(_T("\nFile System Redirection could not be restored. Reason: %d"), GetLastError());
        return 5;
    }
}
#endif

omit the ifdef and just call the WOW64 functions only if IsWow64Process() reports the current process is actually running inside of WOW64:

typedef BOOL (WINAPI tW64P)(HANDLE, PBOOL);
typedef BOOL (WINAPI *tFSDisable)(PVOID*);
typedef BOOL (WINAPI *tFSRevert(PVOID);

HMODULE hKernel = GetModuleHandle(_T("Kernel32"));

tW64P pIsWow64Func = (tW64P) GetProcAddress(hKernel, "IsWow64Process");
tFSDisable pDisableFunc = NULL;
tFSRevert pRevertFunc = NULL;

BOOL bIsWow64 = FALSE;
if (pIsWow64Func)
{
    pIsWow64Func(GetCurrentProcess(), &bIsWow64);
    if (bIsWow64)
    {
        pDisableFunc = (tFSDisable) GetProcAddress(hKernel, "Wow64DisableWow64FsRedirection");
        pRevertFunc = (tFSRevert) GetProcAddress(hKernel, "Wow64RevertWow64FsRedirection");
    }
}

PVOID oldValue;

if ((pDisableFunc) && (pRevertFunc))
{
    if (!pDisableFunc(&oldValue))  // Turn off the file system redirector
    {
        _tprintf(_T("\nFile System Redirection could not be turned off. Reason: %d"), GetLastError());
        return 4;
    }
}

// do file system operations as needed...

if ((pDisableFunc) && (pRevertFunc))
{
    if (!pRevertFunc(oldValue))  // Restore the file system redirector
    {
        _tprintf(_T("\nFile System Redirection could not be restored. Reason: %d"), GetLastError());
        return 5;
    }
}


答:
I would recommend restructuring slightly - instead of updating your state after each fetch call completes, wait for both to complete and then update the state all at once. you can then use the setState callback method to run the next method you would like to.

You can use a Promise library such as Bluebird to wait for multiple fetch requests to finish before doing something else

```<code>import Promise from 'bluebird'

getStudents = () => {
  return fetch(`api/students`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(response => response.json());
};

getScores = () => {
  return fetch(`api/scores`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(response => response.json());
};

Promise.join(getStudents(), getScores(), (students, scores) => {
    this.setState({
        students,
        scores
    }, this.rearrangeStudentsWithScores);
});
</code>```

Title: How to finish all fetch before executing next function in React?

Body:
I would recommend restructuring slightly - instead of updating your state after each fetch call completes, wait for both to complete and then update the state all at once. you can then use the setState callback method to run the next method you would like to.

You can use a Promise library such as Bluebird to wait for multiple fetch requests to finish before doing something else

import Promise from 'bluebird'

getStudents = () => {
  return fetch(`api/students`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(response => response.json());
};

getScores = () => {
  return fetch(`api/scores`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(response => response.json());
};

Promise.join(getStudents(), getScores(), (students, scores) => {
    this.setState({
        students,
        scores
    }, this.rearrangeStudentsWithScores);
});


问:
Realm migration inadequately documented. Can anyone clarify?
Performing migrations on a Realm database is poorly documented and the documentation seems to be out-of-date. There are two areas explaining how to migrate data:

-- The simple example on the Realm website:  https://realm.io/docs/swift/latest/

-- A more detailed example in the Github examples section:  https://github.com/realm/realm-cocoa/blob/master/examples/ios/swift-3.0/Migration/AppDelegate.swift

Neither of these examples adequately explain how to migrate data between schema versions. I've tried playing around with the examples and have yet to get any migrations working. As well, I've had problems with app crashes when upgrading to newer Realm versions without schema changes and data changes, which don't occur in the Simulator but occur when installing the app from TestFlight or the App Store.

Seems like the Realm documentation and examples detailing migrations are due for a refresh. My areas of interest are:

Upgrading to a newer Realm version without a schema change in the database. Unclear whether I should continue using the default.realm file generated with a previous version, or whether I need to re-generate the default.realm file using the newer Realm framework version.

Adding a new attribute to a Realm object.

New objects ("rows") added to an existing class without any schema change.

No schema changes to existing classes in the database, but addition of an entirely new class or classes.

Any combination of the above.

Thanks!

答:
Sorry the docs are not sufficient. We appreciate the feedback and will use it to improve them. In the mean time, let me answer your questions:

You do not need to do anything when you upgrade the SDK. Sometimes, we upgrade the core database file format, but this migration happens automatically when you open the Realm (Realm()) so you don't have to worry about it.

When you add a new property to an object you can just follow this code snippet.

Nothing is needed in the migration block since this block is simply to apply data transformations between versions. All you need to do is increment the schemaVersion

```<code>// Inside your application(application:didFinishLaunchingWithOptions:)

let config = Realm.Configuration(
  // Set the new schema version. This must be greater than the previously used
  // version (if you've never set a schema version before, the version is 0).
  schemaVersion: 1,

  // Set the block which will be called automatically when opening a Realm with
  // a schema version lower than the one set above
  migrationBlock: { migration, oldSchemaVersion in
    // We haven’t migrated anything yet, so oldSchemaVersion == 0
    if (oldSchemaVersion < 1) {
      // Nothing to do!
      // Realm will automatically detect new properties and removed properties
      // And will update the schema on disk automatically
    }
  })

// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config

// Now that we've told Realm how to handle the schema change, opening the file
// will automatically perform the migration
let realm = try! Realm()
</code>```

Adding objects to a Realm does not affect the schema so a migration is not relevant.

This is the same as 2, you simply need to increment the schemaVersion but you don't have to do anything in the migration block since Realm handles everything. The migration block is for custom migration logic where, for example, you want to transform firstName and lastName from schemaVersion=0 to fullName when updating to schemaVersion=1. In this case, you could get the data from the old version and concatenate the strings into the new fullName property within the migration block.

Hope this helps!

Body:
Sorry the docs are not sufficient. We appreciate the feedback and will use it to improve them. In the mean time, let me answer your questions:

You do not need to do anything when you upgrade the SDK. Sometimes, we upgrade the core database file format, but this migration happens automatically when you open the Realm (Realm()) so you don't have to worry about it.

When you add a new property to an object you can just follow this code snippet.

Nothing is needed in the migration block since this block is simply to apply data transformations between versions. All you need to do is increment the schemaVersion

// Inside your application(application:didFinishLaunchingWithOptions:)

let config = Realm.Configuration(
  // Set the new schema version. This must be greater than the previously used
  // version (if you've never set a schema version before, the version is 0).
  schemaVersion: 1,

  // Set the block which will be called automatically when opening a Realm with
  // a schema version lower than the one set above
  migrationBlock: { migration, oldSchemaVersion in
    // We haven’t migrated anything yet, so oldSchemaVersion == 0
    if (oldSchemaVersion < 1) {
      // Nothing to do!
      // Realm will automatically detect new properties and removed properties
      // And will update the schema on disk automatically
    }
  })

// Tell Realm to use this new configuration object for the default Realm
Realm.Configuration.defaultConfiguration = config

// Now that we've told Realm how to handle the schema change, opening the file
// will automatically perform the migration
let realm = try! Realm()

Adding objects to a Realm does not affect the schema so a migration is not relevant.

This is the same as 2, you simply need to increment the schemaVersion but you don't have to do anything in the migration block since Realm handles everything. The migration block is for custom migration logic where, for example, you want to transform firstName and lastName from schemaVersion=0 to fullName when updating to schemaVersion=1. In this case, you could get the data from the old version and concatenate the strings into the new fullName property within the migration block.

Hope this helps!


答:
I believe you need to wrap your functions in arrow functions. The functions are being invoked as the promise chain is being compiled and sent to the event loop. This is creating a race condition.

```<code>    function getStudentsAndScores(cbStudent, cbScores, cbStudentsScores){
  getStudents(cbStudent).then(() => getScores(cbScores)).then(cbStudentsScores);
}
</code>```

I recommend this article for additional reading:
We Have a Problem with Promises by Nolan Lawson

And here's a repo I made that has an example for each of the concepts talked about in the article.
Pinky Swear

Body:
I believe you need to wrap your functions in arrow functions. The functions are being invoked as the promise chain is being compiled and sent to the event loop. This is creating a race condition.

    function getStudentsAndScores(cbStudent, cbScores, cbStudentsScores){
  getStudents(cbStudent).then(() => getScores(cbScores)).then(cbStudentsScores);
}

I recommend this article for additional reading:
We Have a Problem with Promises by Nolan Lawson

And here's a repo I made that has an example for each of the concepts talked about in the article.
Pinky Swear


问:
In C++, is there a defined order of operations when assigning an expression into an object when the expression involves that object?
Consider the following C++ code that uses Qt's container class QMap:

```<code>#include <QMap>
#include <iostream>

QMap<int, int> myMap;

int count() {
    return myMap.size();
}

int main() {
    myMap[0] = count();
    std::cout << myMap[0] << std::endl;
    return 0;
}
</code>```

Depending on whether myMap has a new entry created in it before or after count() is executed, this code's output will be either 1 or 0 respectively.

Does the output of this code depend on the implementation of QMap? Or does the C++ specification make any guarantees about when count() will be executed in relation to QMap::operator[]? Or could the result be undefined and this is a situation that's best avoided?

I ask because I had an essentially identical situation in a program I was working on. When I compiled the program in Windows and ran it using the stock Qt 5.5.1 DLLs, the result was 0. However, when I ran it using a different set of Qt 5.5.1 DLLs that had been compiled from source, the result was 1. It was an awfully confusing bug that took me a little while to track down, particularly since I got different results depending on where I ran the executable!

I'm hoping that I can understand how there was two different behaviors for the same program so that I might be able to avoid bugs like this in the future.

答:
Either side of the assignment can be evaluated first. It's analogous to a function call (and actually may well be a function call, if you have overloaded the assignment operator) such as:

```<code>  void f( X a, X b );
</code>```

where either a or b may be evaluated first.

This is not necessarily specific to a particular compiler - the same compiler might choose a different order of evaluation in different circumstances.

Body:
Consider the following C++ code that uses Qt's container class QMap:

#include <QMap>
#include <iostream>

QMap<int, int> myMap;

int count() {
    return myMap.size();
}

int main() {
    myMap[0] = count();
    std::cout << myMap[0] << std::endl;
    return 0;
}

Depending on whether myMap has a new entry created in it before or after count() is executed, this code's output will be either 1 or 0 respectively.

Does the output of this code depend on the implementation of QMap? Or does the C++ specification make any guarantees about when count() will be executed in relation to QMap::operator[]? Or could the result be undefined and this is a situation that's best avoided?

I ask because I had an essentially identical situation in a program I was working on. When I compiled the program in Windows and ran it using the stock Qt 5.5.1 DLLs, the result was 0. However, when I ran it using a different set of Qt 5.5.1 DLLs that had been compiled from source, the result was 1. It was an awfully confusing bug that took me a little while to track down, particularly since I got different results depending on where I ran the executable!

I'm hoping that I can understand how there was two different behaviors for the same program so that I might be able to avoid bugs like this in the future.

Body:
Either side of the assignment can be evaluated first. It's analogous to a function call (and actually may well be a function call, if you have overloaded the assignment operator) such as:

  void f( X a, X b );

where either a or b may be evaluated first.

This is not necessarily specific to a particular compiler - the same compiler might choose a different order of evaluation in different circumstances.


问:
Showing element activates animation in css
When an elements display goes from none to some other value its animation(if it has any) activates.
Does anyone know how to prevent this?

Also it would be nice to understand why this happens. Is because the DOM is being reflown?

Here is an example of what I mean for reference:

https://jsfiddle.net/darlyp/2p2q767r/

HTML

```<code><div class="red-square"></div>
<br/>
<button id="btn">
  Hide and Show square
</button>
</code>```

CSS

```<code>.red-square{
  width: 100px;
  height: 100px;
  background-color: red;
  display: inline-block;
  animation: 1s both moveSquare 1;
}
@keyframes moveSquare{
  0%{
    margin-left: 0px;
  }
  50%{
    margin-left: 400px;
  }
  100%{
    margin-left: 0px;
  }
}
</code>```

JS

```<code>document.getElementById('btn').addEventListener("click", function() {
  var currentDisplay = document.querySelector('.red-square').style.display;
  if (currentDisplay === 'none') {
    document.querySelector('.red-square').style.display = 'inline-block';
  } else {
    document.querySelector('.red-square').style.display = 'none';
  }
})
</code>```

https://jsfiddle.net/darlyp/2p2q767r/

答:
When you display it, you could set the animation-play-state to paused.

JSfiddle

document.getElementById('btn').addEventListener("click", function() {
  var currentDisplay = document.querySelector('.red-square').style.display;
  if (currentDisplay === 'none') {
    document.querySelector('.red-square').style.display = 'inline-block';
    document.querySelector('.red-square').style.animationPlayState = 'paused';
  } else {
    document.querySelector('.red-square').style.display = 'none';
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red-square{
  width: 100px;
  height: 100px;
  background-color: red;
  display: inline-block;
  animation: 1s both moveSquare 1;
}
@keyframes moveSquare{
  0%{
    margin-left: 0px;
  }
  50%{
    margin-left: 400px;
  }
  100%{
    margin-left: 0px;
  }
}</code>```

<button id="btn">
  Hide and Show square
</button>```

Body:
When an elements display goes from none to some other value its animation(if it has any) activates.
Does anyone know how to prevent this?

Also it would be nice to understand why this happens. Is because the DOM is being reflown?

Here is an example of what I mean for reference:

https://jsfiddle.net/darlyp/2p2q767r/

HTML

<button id="btn">
  Hide and Show square
</button>

CSS

.red-square{
  width: 100px;
  height: 100px;
  background-color: red;
  display: inline-block;
  animation: 1s both moveSquare 1;
}
@keyframes moveSquare{
  0%{
    margin-left: 0px;
  }
  50%{
    margin-left: 400px;
  }
  100%{
    margin-left: 0px;
  }
}

JS

document.getElementById('btn').addEventListener("click", function() {
  var currentDisplay = document.querySelector('.red-square').style.display;
  if (currentDisplay === 'none') {
    document.querySelector('.red-square').style.display = 'inline-block';
  } else {
    document.querySelector('.red-square').style.display = 'none';
  }
})

https://jsfiddle.net/darlyp/2p2q767r/

Body:
When you display it, you could set the animation-play-state to paused.

JSfiddle

document.getElementById('btn').addEventListener("click", function() {
  var currentDisplay = document.querySelector('.red-square').style.display;
  if (currentDisplay === 'none') {
    document.querySelector('.red-square').style.display = 'inline-block';
    document.querySelector('.red-square').style.animationPlayState = 'paused';
  } else {
    document.querySelector('.red-square').style.display = 'none';
  }
})

.red-square{
  width: 100px;
  height: 100px;
  background-color: red;
  display: inline-block;
  animation: 1s both moveSquare 1;
}
@keyframes moveSquare{
  0%{
    margin-left: 0px;
  }
  50%{
    margin-left: 400px;
  }
  100%{
    margin-left: 0px;
  }
}

<div class="red-square"></div>
<br/>
<button id="btn">
  Hide and Show square
</button>


问:
Excel: INDEX MATCH with partial number
I have a large table of 12 digit numbers and associated info

I have a small list of 10 and 11 digit numbers (the first and/or last digits were cut off) - I'm attempting to cross these two lists to identify the items on the small list

normally, I'd use an index match to bring the associated info out of the table into the list, but because today I have only partial numbers in my list, I can't get the formula to work

I've seen other examples here that search for partial text strings contained within a range, but I haven't been able to adapt those formulas to my data. wildcards don't seem to work with numbers.

Many thanks for your input, and apologies in advance if I failed to find an existing solution on the site.

答:
To match partial numbers inside a number range, like you do with strings, you can use an array formula with INDEX/MATCH, by composing a temporary array that converts the numbers into strings.

Say column A is your 12 digit numbers column, and you want to match the sequence 1234567890 and retrieve the value from column B, This CSE formula works:

```<code>=INDEX($B$2:$B$9999, MATCH("*1234567890*",""&$A$2:$A$9999,0))
</code>```

CtrlShiftEnter

Although you can use full columns A:A and B:B, this should be avoided as much as possible with array formulas, because they're slow. Full columns mean computing and operating arrays of more than a million entries, so avoid it. Also note the "expensive" conversion from numbers to strings (all numbers in the $A$2:$A$9999 are converted to strings here).

To use a cell reference, say D2, instead of the harcoded 1234567890, the formula should be used like this:

```<code>=INDEX($B$2:$B$9999,MATCH("*"&D2&"*",""&$A$2:$A$9999,0))
</code>```

Title: Excel: INDEX MATCH with partial number

Body:
To match partial numbers inside a number range, like you do with strings, you can use an array formula with INDEX/MATCH, by composing a temporary array that converts the numbers into strings.

Say column A is your 12 digit numbers column, and you want to match the sequence 1234567890 and retrieve the value from column B, This CSE formula works:

=INDEX($B$2:$B$9999, MATCH("*1234567890*",""&$A$2:$A$9999,0))

CtrlShiftEnter

Although you can use full columns A:A and B:B, this should be avoided as much as possible with array formulas, because they're slow. Full columns mean computing and operating arrays of more than a million entries, so avoid it. Also note the "expensive" conversion from numbers to strings (all numbers in the $A$2:$A$9999 are converted to strings here).

To use a cell reference, say D2, instead of the harcoded 1234567890, the formula should be used like this:

=INDEX($B$2:$B$9999,MATCH("*"&D2&"*",""&$A$2:$A$9999,0))


问:
Gitlab Style Network Graphs on Github
One of the things i really liked on Gitlab was their network graphs

Is there a way to get a similar look/feel in Github?

I find the gitlab version much easier to work with

答:
We've just moved our client work from a self-hosted GitLab instance to private GitHub repositories and I feel the same pain - I live on the GitLab network graph page!

So I've gone ahead and got it working for any local repository. That's not quite GitHub of course, but you can locally clone any GitHub project to use it.

The code and instructions are at https://github.com/chromatixau/gitlab-network-graph. It's not perfect yet - there are issues with getting the right 'space' allocation on the graph for some merge strategies, but it works for most simpler situations. I'm continuing to work on it.

The steps were basically to copy the network related frontend JS files from the MIT-licensed GitLab CE repository, build a small webpack config based on GitLab's, and then put together some scripts to create the JSON that GitLab builds the graph from (I've used a shell script to basically run git log and format it as JSON, and then a Node.js script to further massage that JSON).

Title: Gitlab Style Network Graphs on Github


问:
How to get total in recursive function
How do I get the total interest paid on all months in the below recursive function?  This should simulate a credit card payment.</p>

```<code>def creditcard_interest(balance,months,monthly_interest_rate=2.95/100):
    if months==1:
        return print("The new balance= ",balance)
    else:
        min_monthly_payment=balance*0.05
        balance=balance-min_monthly_payment
        interest=balance*monthly_interest_rate
        print("Min_monthly_payment for month "+str(months)+'= ', min_monthly_payment)
        print("Unpaid balance  for month "+str(months)+'= ',balance)
        print("Calculated interest for month "+str(months)+'= ',interest)

        return  creditcard_interest((balance+interest),months-1,)
</code>```

答:
Accumulate the interest as you return from each call:

```<code>return interest + creditcard_interest((balance+interest), months-1, )
</code>```

BTW, your first statement is illegal: you can't return a print statement.  What are you trying to do with that?  Look at the semantics of your two branches: the first returns something relating to the balance, while the other apparently returns an interest amount.

I suspect that what you need to do is to print the balance, then return the interest.  Something like ...

```<code>interest=balance*monthly_interest_rate
if months==1:
    print("The new balance= ", balance)
    return interest
</code>```

After changes,

```<code>print ("Total interest paid", creditcard_interest(1000, 12))
</code>```

yields

```<code>Min_monthly_payment for month 12=  50.0
Unpaid balance  for month 12=  950.0
Calculated interest for month 12=  29.500000000000004
Min_monthly_payment for month 11=  48.975
Unpaid balance  for month 11=  930.525
Calculated interest for month 11=  28.89525
Min_monthly_payment for month 10=  47.9710125
Unpaid balance  for month 10=  911.4492375
Calculated interest for month 10=  28.302897375
Min_monthly_payment for month 9=  46.98760674375001
Unpaid balance  for month 9=  892.76452813125
Calculated interest for month 9=  27.722687978812502
Min_monthly_payment for month 8=  46.02436080550313
Unpaid balance  for month 8=  874.4628553045594
Calculated interest for month 8=  27.154372875246846
Min_monthly_payment for month 7=  45.080861408990316
Unpaid balance  for month 7=  856.5363667708159
Calculated interest for month 7=  26.597708231304285
Min_monthly_payment for month 6=  44.15670375010601
Unpaid balance  for month 6=  838.9773712520142
Calculated interest for month 6=  26.05245521256255
Min_monthly_payment for month 5=  43.25149132322884
Unpaid balance  for month 5=  821.778335141348
Calculated interest for month 5=  25.518379880705016
Min_monthly_payment for month 4=  42.364835751102646
Unpaid balance  for month 4=  804.9318792709503
Calculated interest for month 4=  24.995253093150563
Min_monthly_payment for month 3=  41.49635661820505
Unpaid balance  for month 3=  788.4307757458959
Calculated interest for month 3=  24.48285040474098
Min_monthly_payment for month 2=  40.645681307531845
Unpaid balance  for month 2=  772.2679448431049
Calculated interest for month 2=  23.980951971443787
The new balance=  796.2488968145487
Total interest paid 23.48934245602919
</code>```

You still have a base case (end condition) to handle, and perhaps some formatting issues, but this fixed the main problems.

Title: How to get total in recursive function

Body:
How do I get the total interest paid on all months in the below recursive function?  This should simulate a credit card payment.

def creditcard_interest(balance,months,monthly_interest_rate=2.95/100):
    if months==1:
        return print("The new balance= ",balance)
    else:
        min_monthly_payment=balance*0.05
        balance=balance-min_monthly_payment
        interest=balance*monthly_interest_rate
        print("Min_monthly_payment for month "+str(months)+'= ', min_monthly_payment)
        print("Unpaid balance  for month "+str(months)+'= ',balance)
        print("Calculated interest for month "+str(months)+'= ',interest)

        return  creditcard_interest((balance+interest),months-1,)

Body:
Accumulate the interest as you return from each call:

return interest + creditcard_interest((balance+interest), months-1, )

BTW, your first statement is illegal: you can't return a print statement.  What are you trying to do with that?  Look at the semantics of your two branches: the first returns something relating to the balance, while the other apparently returns an interest amount.

I suspect that what you need to do is to print the balance, then return the interest.  Something like ...

interest=balance*monthly_interest_rate
if months==1:
    print("The new balance= ", balance)
    return interest

After changes,

print ("Total interest paid", creditcard_interest(1000, 12))

yields

Min_monthly_payment for month 12=  50.0
Unpaid balance  for month 12=  950.0
Calculated interest for month 12=  29.500000000000004
Min_monthly_payment for month 11=  48.975
Unpaid balance  for month 11=  930.525
Calculated interest for month 11=  28.89525
Min_monthly_payment for month 10=  47.9710125
Unpaid balance  for month 10=  911.4492375
Calculated interest for month 10=  28.302897375
Min_monthly_payment for month 9=  46.98760674375001
Unpaid balance  for month 9=  892.76452813125
Calculated interest for month 9=  27.722687978812502
Min_monthly_payment for month 8=  46.02436080550313
Unpaid balance  for month 8=  874.4628553045594
Calculated interest for month 8=  27.154372875246846
Min_monthly_payment for month 7=  45.080861408990316
Unpaid balance  for month 7=  856.5363667708159
Calculated interest for month 7=  26.597708231304285
Min_monthly_payment for month 6=  44.15670375010601
Unpaid balance  for month 6=  838.9773712520142
Calculated interest for month 6=  26.05245521256255
Min_monthly_payment for month 5=  43.25149132322884
Unpaid balance  for month 5=  821.778335141348
Calculated interest for month 5=  25.518379880705016
Min_monthly_payment for month 4=  42.364835751102646
Unpaid balance  for month 4=  804.9318792709503
Calculated interest for month 4=  24.995253093150563
Min_monthly_payment for month 3=  41.49635661820505
Unpaid balance  for month 3=  788.4307757458959
Calculated interest for month 3=  24.48285040474098
Min_monthly_payment for month 2=  40.645681307531845
Unpaid balance  for month 2=  772.2679448431049
Calculated interest for month 2=  23.980951971443787
The new balance=  796.2488968145487
Total interest paid 23.48934245602919

You still have a base case (end condition) to handle, and perhaps some formatting issues, but this fixed the main problems.


答:
Unfortunately, to my knowledge, there is no defined order, either by a given compiler, compiler version, or library for the order of evaluation, unlike a language like Python. Your code depends on undefined behavior.

There are some rules, however, that a compiler must conform to: this is not one of them. An example they give on undefined behavior is analogous to your example:

```<code>a[i] = i++;
</code>```

Title: In C++, is there a defined order of operations when assigning an expression into an object when the expression involves that object?

Body:
Unfortunately, to my knowledge, there is no defined order, either by a given compiler, compiler version, or library for the order of evaluation, unlike a language like Python. Your code depends on undefined behavior.

There are some rules, however, that a compiler must conform to: this is not one of them. An example they give on undefined behavior is analogous to your example:

a[i] = i++;


问:
Conditional Rolling Sum (rolling average) in R
```<code>ID  Year  Firm Score

1   2005    A   2
1   2006    A   5
1   2006    B   1
1   2007    A   36
1   2007    E   69
1   2008    E   8
1   2008    B   54
1   2009    A   25
1   2009    C   2
1   2010    E   2
1   2010    B   2
1   2011    A   5
1   2011    B   5
1   2012    A   4
1   2012    B   1
</code>```

Data

In above data, I want to perform group by 5 year rolling sum of 'Score' for each individual (ID) conditional on the current year Firm the person is working in.
Let me explain this by example. Suppose I want rolling sum of 'Score' variable for year 2009, it should first check the firms in which the person (ID) is working. In 2009, person is working in A and C. It should then calculate 5 year rolling sum of 'Score' only for Firms A or C. Output of 5 year rolling sum for year 2009 will be (2 (for year 2005 firm A) + 5 ((for year 2006 firm A)) + 36 (for year 2007 firm A) + 27 (for year 2009 firm A and C) ) = 70. [Note: Year 2008 is ignored because person is neither registered in firm A nor firm C]

I also want to perform Rolling Average on similar lines.
[Note: Original data has around 30 million observations]

Body:
ID  Year  Firm Score

1   2005    A   2
1   2006    A   5
1   2006    B   1
1   2007    A   36
1   2007    E   69
1   2008    E   8
1   2008    B   54
1   2009    A   25
1   2009    C   2
1   2010    E   2
1   2010    B   2
1   2011    A   5
1   2011    B   5
1   2012    A   4
1   2012    B   1

Data

In above data, I want to perform group by 5 year rolling sum of 'Score' for each individual (ID) conditional on the current year Firm the person is working in.
Let me explain this by example. Suppose I want rolling sum of 'Score' variable for year 2009, it should first check the firms in which the person (ID) is working. In 2009, person is working in A and C. It should then calculate 5 year rolling sum of 'Score' only for Firms A or C. Output of 5 year rolling sum for year 2009 will be (2 (for year 2005 firm A) + 5 ((for year 2006 firm A)) + 36 (for year 2007 firm A) + 27 (for year 2009 firm A and C) ) = 70. [Note: Year 2008 is ignored because person is neither registered in firm A nor firm C]

I also want to perform Rolling Average on similar lines.
[Note: Original data has around 30 million observations]

Body:
set up dataframe

rs <- as.data.frame(matrix(nrow =15, ncol = 4))

colnames(rs) <- c("ID", "Year", "Firm", "Score")

rs$ID <- 1
rs$Year <- c(2005,
             2006,
             2006,
             2007,
             2007,
             2008,
             2008,
             2009,
             2009,
             2010,
             2010,
             2011,
             2011,
             2012,
             2012)

rs$Firm <- c("A", "A", "B", "A", "E",
             "E", "B", "A", "C", "E",
             "B", "A", "B", "A", "B")

rs$Score <- c(2, 5, 1, 36, 69, 8,
              54, 25, 2, 2, 2, 5, 5, 4,
              1)

loop over unique years

a <- rs$Year

for(i in unique(a)){

  b <- rs[rs$Year == i,]
  c <- (b$Firm)
  d <-  rs[rs$Year <=  i & rs$Firm %in% c,]
  print(paste(i, sum(d$Score)))

}

Output:

[1] "2005 2"
[1] "2006 8"
[1] "2007 112"
[1] "2008 132"
[1] "2009 70"
[1] "2010 136"
[1] "2011 135"
[1] "2012 140"


问:
How to Autowire property in spring
I am trying to Autowire the field variables into the class by adding a property in my the bean configuration. so that when the spring gets instantiate the strings with value in properties.

my spring configuration file is as

```<code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="authentication" class="com.quicut.model.authenticationModel">
    <property name="dbURL" value="jdbc:mysql://127.0.0.1:3306/quicut" />
    <property name="userN" value="user1" />
    <property name="userP" value="password" />
    <property name="JDBC_DRIVER" value="com.mysql.jdbc.Driver" />
</bean>
</code>```

the class that i created a bean for has the following fields which i want their values to be assigned by spring when instantiated.

```<code>public class authenticationModel {

    private String dbURL;
    private  String userN;
    private  String userP;
    private String JDBC_DRIVER;
</code>```

the class which requires the dependency is as follows;

```<code>public class login extends HttpServlet {
@Autowired
@Qualifier(value="authentication")
authenticationModel aModel;
</code>```

i'm quite new to spring so i don't know what i am doing wrong or missing.

答:
As a suggestion, you can name your classes with an initial capital letter, for example, instead of authenticationModel name it as AuthenticationModel.

Now, if you want to autowire spring beans in a particular Java class, you need to mark that class as a @Controller or @Service bean type. Only spring beans can autowire other beans.

In your case, your Login class is not marked as a particular spring bean, so you probably need to use one of the previous annotations.

For example:

```<code>@Service
public class LoginService {
    @Autowired
    @Qualifier(value="authentication")
    AuthenticationModel aModel;
}
</code>```

Title: How to Autowire property in spring

Body:
I am trying to Autowire the field variables into the class by adding a property in my the bean configuration. so that when the spring gets instantiate the strings with value in properties.

my spring configuration file is as

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="authentication" class="com.quicut.model.authenticationModel">
    <property name="dbURL" value="jdbc:mysql://127.0.0.1:3306/quicut" />
    <property name="userN" value="user1" />
    <property name="userP" value="password" />
    <property name="JDBC_DRIVER" value="com.mysql.jdbc.Driver" />
</bean>

the class that i created a bean for has the following fields which i want their values to be assigned by spring when instantiated.

public class authenticationModel {

    private String dbURL;
    private  String userN;
    private  String userP;
    private String JDBC_DRIVER;

the class which requires the dependency is as follows;

public class login extends HttpServlet {
@Autowired
@Qualifier(value="authentication")
authenticationModel aModel;

i'm quite new to spring so i don't know what i am doing wrong or missing.

Body:
As a suggestion, you can name your classes with an initial capital letter, for example, instead of authenticationModel name it as AuthenticationModel.

Now, if you want to autowire spring beans in a particular Java class, you need to mark that class as a @Controller or @Service bean type. Only spring beans can autowire other beans.

In your case, your Login class is not marked as a particular spring bean, so you probably need to use one of the previous annotations.

For example:

@Service
public class LoginService {
    @Autowired
    @Qualifier(value="authentication")
    AuthenticationModel aModel;
}


问:
VLOOKUP for different sheets
I have value in Sheet1 "B" column which is to be vlookup in Sheet2 from Column "A to K" and copy the corresponding C column value of Sheet2 and paste it in Sheet1's E column.

I have tried with below code but it shows error as

Run-time error '1004':
Unable to get the Vlookup Property of the worksheetfunction class.

```<code>Sub vlook_up()
  For i = 2 To 11
       Cells("D" & i).Value = WorksheetFunction.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, 0)
  Next i
End Sub
</code>```

答:
This works for me, however I feel you are passing the function an inappropriate var type. </p>

```<code>Sub vlook_up()
  For i = 2 To 11
       Range("D" & i).Value = WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, False), "error")
  Next i
End Sub
</code>```

Title: VLOOKUP for different sheets

Body:
I have value in Sheet1 "B" column which is to be vlookup in Sheet2 from Column "A to K" and copy the corresponding C column value of Sheet2 and paste it in Sheet1's E column.

I have tried with below code but it shows error as

Run-time error '1004':
Unable to get the Vlookup Property of the worksheetfunction class.

Sub vlook_up()
  For i = 2 To 11
       Cells("D" & i).Value = WorksheetFunction.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, 0)
  Next i
End Sub

Body:
This works for me, however I feel you are passing the function an inappropriate var type.

Sub vlook_up()
  For i = 2 To 11
       Range("D" & i).Value = WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, False), "error")
  Next i
End Sub


答:
Another way would be to toggle opacity instead, and change the height to 0 when it's hidden so it doesn't occupy any space on the page.

document.getElementById('btn').addEventListener("click", function() {
  document.querySelector('.red-square').classList.toggle('hide');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red-square {
  width: 100px;
  height: 100px;
  background-color: red;
  display: inline-block;
  animation: 1s both moveSquare 1;
}

@keyframes moveSquare {
  0% {
    margin-left: 0px;
  }
  50% {
    margin-left: 400px;
  }
  100% {
    margin-left: 0px;
  }
}

.hide {
  opacity: 0;
  height: 0;
}</code>```

<button id="btn">
  Hide and Show square
</button>```

Title: Showing element activates animation in css

Body:
Another way would be to toggle opacity instead, and change the height to 0 when it's hidden so it doesn't occupy any space on the page.

document.getElementById('btn').addEventListener("click", function() {
  document.querySelector('.red-square').classList.toggle('hide');
})

.red-square {
  width: 100px;
  height: 100px;
  background-color: red;
  display: inline-block;
  animation: 1s both moveSquare 1;
}

@keyframes moveSquare {
  0% {
    margin-left: 0px;
  }
  50% {
    margin-left: 400px;
  }
  100% {
    margin-left: 0px;
  }
}

.hide {
  opacity: 0;
  height: 0;
}

<div class="red-square"></div>
<br/>
<button id="btn">
  Hide and Show square
</button>


问:
Apache beam word count example with spark runner fails with " Unknown 'runner' specified 'SparkRunner'"
I am trying to do spark-submit of the Apache beam word-count example by giving the below command

```<code>spark-submit --class org.apache.beam.examples.WordCount word-count-beam-0.1.jar --inputFile=pom.xml --output=counts --runner=SparkRunner
</code>```

I get the below Exception:

Exception in thread "main" java.lang.IllegalArgumentException: Unknown
  'runner' specified 'SparkRunner', supported pipeline runners
  [DirectRunner]

答: Your pom.xml needs to include a dependency on the Spark runner. The documentation on using the Spark runner includes more details about what is necessary. </p>

Body:
I am trying to do spark-submit of the Apache beam word-count example by giving the below command

spark-submit --class org.apache.beam.examples.WordCount word-count-beam-0.1.jar --inputFile=pom.xml --output=counts --runner=SparkRunner

I get the below Exception:

Exception in thread "main" java.lang.IllegalArgumentException: Unknown
  'runner' specified 'SparkRunner', supported pipeline runners
  [DirectRunner]


问:
Set HttpContext.Current.User from Thread.CurrentPrincipal
I have a security manager in my application that works for both windows and web, the process is simple, just takes the user and pwd and authenticates them against a database then sets the  Thread.CurrentPrincipal with a custom principal. For windows applications this works fine, but I have problems with web applications.

After the process of authentication, when I'm trying to set the Current.User to the custom principal from Thread.CurrentPrincipal this last one contains a GenericPrincipal. Am I doing something wrong? This is my code:

Login.aspx

```<code>protected void btnAuthenticate_Click(object sender, EventArgs e)
{
    SecurityManager.Authenticate("user","pwd"); // This is where I set the custom principal in Thread.CurrentPrincipal
    FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(1,
                        "user",
                        DateTime.Now,
                        DateTime.Now.AddMinutes(30),
                        false,
                        "");

    string ticket = FormsAuthentication.Encrypt(authenticationTicket);
    HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket);
    Response.Cookies.Add(authenticationCookie);
    Response.Redirect(FormsAuthentication.GetRedirectUrl("user", false));
}
</code>```

Global.asax (This is where the problem appears)

```<code>protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie == null)
        return;

    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity)
    {
        HttpContext.Current.User = System.Threading.Thread.CurrentPrincipal; //Here the value is GenericPrincipal
    }
</code>```

Thanks in advance for any help.

答:
First of all: You need to set the principal on every request.

Forms authentication uses it's own assignment of the principal on each request. That's why you are seeing the GenericPrincipal

I usually reassign my custom prinicpal in OnPostAuthenticate when the standard authentication mechanism is done.

ContentLicense: CC BY-SA 2.5

Body:
I have a security manager in my application that works for both windows and web, the process is simple, just takes the user and pwd and authenticates them against a database then sets the  Thread.CurrentPrincipal with a custom principal. For windows applications this works fine, but I have problems with web applications.

After the process of authentication, when I'm trying to set the Current.User to the custom principal from Thread.CurrentPrincipal this last one contains a GenericPrincipal. Am I doing something wrong? This is my code:

Login.aspx

protected void btnAuthenticate_Click(object sender, EventArgs e)
{
    SecurityManager.Authenticate("user","pwd"); // This is where I set the custom principal in Thread.CurrentPrincipal
    FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(1,
                        "user",
                        DateTime.Now,
                        DateTime.Now.AddMinutes(30),
                        false,
                        "");

    string ticket = FormsAuthentication.Encrypt(authenticationTicket);
    HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket);
    Response.Cookies.Add(authenticationCookie);
    Response.Redirect(FormsAuthentication.GetRedirectUrl("user", false));
}

Global.asax (This is where the problem appears)

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie == null)
        return;

    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity)
    {
        HttpContext.Current.User = System.Threading.Thread.CurrentPrincipal; //Here the value is GenericPrincipal
    }

Thanks in advance for any help.


问:
table-striped not working when used with angular js
I am using table-striped style provided by Bootstrap in a table. And I am using angular js to populate the data. It is not showing the table in stripe format. Can someone help me in recognizing the error that I am making?</p>

```<code><table class="table table-striped">
  <thead>
    <tr>
      <th>H1</th>
      <th>H2</th>
      <th>H3</th>
      <th>H4</th>
      <th>H5</th>
      <th>H6</th>
    </tr>
  </thead>
  <tbody ng-repeat="e in data.events">
    <tr>
        <td>{{e.e1}}</td>
        <td>{{e.e2}}</td>
        <td>{{e.e3}}</td>
        <td>{{e.e4}}</td>
        <td>{{e.e5}}</td>
        <td>{{e.e6}}</td>
    </tr>
  </tbody>
</table>
</code>```

答:
I think you meant to put the ng-repeat on the tr element instead of the body. You're repeating the body instead of rows.

Bootstrap alternates the colours on the rows, and since you are creating a new table body with 1 row each, it's only going to show one color.

Body:
I am using table-striped style provided by Bootstrap in a table. And I am using angular js to populate the data. It is not showing the table in stripe format. Can someone help me in recognizing the error that I am making?

      H1
      H2
      H3
      H4
      H5
      H6

        {{e.e1}}
        {{e.e2}}
        {{e.e3}}
        {{e.e4}}
        {{e.e5}}
        {{e.e6}}


问:
Pass parameters with EventEmitter
I have a directive to initializes a jQueryUI sortable on a DOM element. The jQueryUI sortable also has a set of callback events that trigger on certain actions. For example, when you start or stop sorting elements.

I'd like to pass the return parameters from such an event through the emit() function, so I can actually see what happend in my callback function. I just haven't found a way to pass parameters through an EventEmiiter.

I currently have the following.

My directive:

@Directive({
    selector: '[sortable]'
})
export class Sortable {
    @Output() stopSort = new EventEmitter();

    constructor(el: ElementRef) {
      console.log('directive');
        var options = {
          stop: (event, ui) => {
            this.stopSort.emit(); // How to pass the params event and ui...?
          }
        };

        $(el.nativeElement).sortable(options).disableSelection();
    }
}
```

<p>And this is my <code>Component</code> that uses the event emiited by the directive:</p>

<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'my-app',
  directives: [Sortable],
  providers: [],
  template: `
    <div>
      <h2>Event from jQueryUI to Component demo</h2>

      <ul id="sortable" sortable (stopSort)="stopSort(event, ui)">
        <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
        <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
        <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>
      </ul>
    </div>
  `
})
export class App {
  constructor() {

  }

  stopSort(event, ui) { // How do I get the 'event' and 'ui' params here?
    console.log('STOP SORT!', event);
  }
}
</code>```

How can I get the event and ui params in my stopSort() function?

Here is a demo of what I have so far: http://plnkr.co/edit/5ACcetgwWWgTsKs1kWrA?p=info

答:
I can't add a comment, but just wanted to point out from Alpha Bravo's answer that you can pass this.event, you just can't use property value shorthand:

```<code>this.stopSort.emit({ event : this.event, ui : this.ui });
</code>```

Also note, if they are passed through the EventEmmiter as this.stopSort.emit({ val1, val2 }); then they would be accessed in the parent as:

```<code>hereIsHeight(value) {
    console.log(`event = ${ value.val1 }`);
    console.log(`ui = ${ value.val2 }`);
}
</code>```

So avoiding the shorthand might be preferable in this type of situation to keep naming consistent.

Title: Pass parameters with EventEmitter

Body:
I have a directive to initializes a jQueryUI sortable on a DOM element. The jQueryUI sortable also has a set of callback events that trigger on certain actions. For example, when you start or stop sorting elements.

I'd like to pass the return parameters from such an event through the emit() function, so I can actually see what happend in my callback function. I just haven't found a way to pass parameters through an EventEmiiter.

I currently have the following.

My directive:

@Directive({
    selector: '[sortable]'
})
export class Sortable {
    @Output() stopSort = new EventEmitter();

    constructor(el: ElementRef) {
      console.log('directive');
        var options = {
          stop: (event, ui) => {
            this.stopSort.emit(); // How to pass the params event and ui...?
          }
        };

        $(el.nativeElement).sortable(options).disableSelection();
    }
}

And this is my Component that uses the event emiited by the directive:

@Component({
  selector: 'my-app',
  directives: [Sortable],
  providers: [],
  template: `

Event from jQueryUI to Component demo

Item 1

Item 2

Item 3

  `
})
export class App {
  constructor() {

  }

  stopSort(event, ui) { // How do I get the 'event' and 'ui' params here?
    console.log('STOP SORT!', event);
  }
}

How can I get the event and ui params in my stopSort() function?

Here is a demo of what I have so far: http://plnkr.co/edit/5ACcetgwWWgTsKs1kWrA?p=info

Body:
I can't add a comment, but just wanted to point out from Alpha Bravo's answer that you can pass this.event, you just can't use property value shorthand:

this.stopSort.emit({ event : this.event, ui : this.ui });

Also note, if they are passed through the EventEmmiter as this.stopSort.emit({ val1, val2 }); then they would be accessed in the parent as:

hereIsHeight(value) {
    console.log(`event = ${ value.val1 }`);
    console.log(`ui = ${ value.val2 }`);
}

So avoiding the shorthand might be preferable in this type of situation to keep naming consistent.

ContentLicense: CC BY-SA 4.0


答:
I believe your issue is the placement of the repeat directive. If you move it to your tr element, it should be fine. As is, it is creating a new tbody element for each item in your events array. Since table-striped alternates the background color of even rows, and each tbody contains only 1 row, you aren't seeing that style applied.</p>

```<code><table class="table table-striped">
  <thead>
    <tr>
      <th>H1</th>
      <th>H2</th>
      <th>H3</th>
      <th>H4</th>
      <th>H5</th>
      <th>H6</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in data.events">
        <td>{{e.e1}}</td>
        <td>{{e.e2}}</td>
        <td>{{e.e3}}</td>
        <td>{{e.e4}}</td>
        <td>{{e.e5}}</td>
        <td>{{e.e6}}</td>
    </tr>
  </tbody>
</table>
</code>```

Title: table-striped not working when used with angular js

Body:
I believe your issue is the placement of the repeat directive. If you move it to your tr element, it should be fine. As is, it is creating a new tbody element for each item in your events array. Since table-striped alternates the background color of even rows, and each tbody contains only 1 row, you aren't seeing that style applied.

<table class="table table-striped">
  <thead>
    <tr>
      <th>H1</th>
      <th>H2</th>
      <th>H3</th>
      <th>H4</th>
      <th>H5</th>
      <th>H6</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in data.events">
        <td>{{e.e1}}</td>
        <td>{{e.e2}}</td>
        <td>{{e.e3}}</td>
        <td>{{e.e4}}</td>
        <td>{{e.e5}}</td>
        <td>{{e.e6}}</td>
    </tr>
  </tbody>
</table>


答:
```<code><table class="table table-striped">
  <thead>
    <tr>
      <th>H1</th>
      <th>H2</th>
      <th>H3</th>
      <th>H4</th>
      <th>H5</th>
      <th>H6</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in data.events">
        <td>{{e.e1}}</td>
        <td>{{e.e2}}</td>
        <td>{{e.e3}}</td>
        <td>{{e.e4}}</td>
        <td>{{e.e5}}</td>
        <td>{{e.e6}}</td>
    </tr>
  </tbody>
</table>
</code>```

This should work fine, but you need to repeat the table rows <tr>, not the table body
.

Body:
<table class="table table-striped">
  <thead>
    <tr>
      <th>H1</th>
      <th>H2</th>
      <th>H3</th>
      <th>H4</th>
      <th>H5</th>
      <th>H6</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in data.events">
        <td>{{e.e1}}</td>
        <td>{{e.e2}}</td>
        <td>{{e.e3}}</td>
        <td>{{e.e4}}</td>
        <td>{{e.e5}}</td>
        <td>{{e.e6}}</td>
    </tr>
  </tbody>
</table>

This should work fine, but you need to repeat the table rows <tr>, not the table body <tbody>.


问:
Create a View From Max1 of One Column and the Max2 of Another if there are multiple Max1 for group
From my table, I want to select for each project ID the ID with the latest deploymentDate and if there are two identical latest deployment dates for the same project ID, select the ID with the latest submittedOn datetime. So if my table looks like this:

```<code>    id  | projectId  |  deploymentDate  | submittedOn         |
    1   | 1          |  2017-01-02      | 2017-01-02 13:00:00 |
    2   | 1          |  2017-01-04      | 2017-01-04 11:00:00 |
    3   | 2          |  2017-01-06      | 2017-01-06 17:00:00 |
    4   | 2          |  2017-01-06      | 2017-01-01 12:00:00 |
    5   | 3          |  2017-01-02      | 2017-01-02 13:30:00 |
    6   | 3          |  2017-01-02      | 2017-01-05 15:00:00 |
    7   | 3          |  2017-01-02      | 2017-01-04 10:00:00 |
</code>```

The desired rows are:

```<code>    id  | projectId  |  deploymentDate  | submittedOn         |
    2   | 1          |  2017-01-04      | 2017-01-04 11:00:00 |
    3   | 2          |  2017-01-06      | 2017-01-06 17:00:00 |
    6   | 3          |  2017-01-02      | 2017-01-05 15:00:00 |
</code>```

答:
This would work:

```<code>select t.id, latest.*
from tab t join (
                    select projectid, max(deploymentdate) deploymentdate, max(submittedon) submittedon
                    from tab
                    group by projectid
                ) latest on t.projectid = latest.projectid and t.deploymentdate = latest.deploymentdate and t.submittedon = latest.submittedon
</code>```

I found the latest based on the project id and then, joined with the source table to find the corresponding id.

Body:
From my table, I want to select for each project ID the ID with the latest deploymentDate and if there are two identical latest deployment dates for the same project ID, select the ID with the latest submittedOn datetime. So if my table looks like this:

    id  | projectId  |  deploymentDate  | submittedOn         |
    1   | 1          |  2017-01-02      | 2017-01-02 13:00:00 |
    2   | 1          |  2017-01-04      | 2017-01-04 11:00:00 |
    3   | 2          |  2017-01-06      | 2017-01-06 17:00:00 |
    4   | 2          |  2017-01-06      | 2017-01-01 12:00:00 |
    5   | 3          |  2017-01-02      | 2017-01-02 13:30:00 |
    6   | 3          |  2017-01-02      | 2017-01-05 15:00:00 |
    7   | 3          |  2017-01-02      | 2017-01-04 10:00:00 |

The desired rows are:

    id  | projectId  |  deploymentDate  | submittedOn         |
    2   | 1          |  2017-01-04      | 2017-01-04 11:00:00 |
    3   | 2          |  2017-01-06      | 2017-01-06 17:00:00 |
    6   | 3          |  2017-01-02      | 2017-01-05 15:00:00 |

Body:
This would work:

select t.id, latest.*
from tab t join (
                    select projectid, max(deploymentdate) deploymentdate, max(submittedon) submittedon
                    from tab
                    group by projectid
                ) latest on t.projectid = latest.projectid and t.deploymentdate = latest.deploymentdate and t.submittedon = latest.submittedon

I found the latest based on the project id and then, joined with the source table to find the corresponding id.


问:
ARKit Session Paused and Not Resuming
In my ARKit app I am presenting a modal window. When I close the modal and go back to the ARSCNView then I find out that the session is paused due to this code:

```<code> override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // Pause the view's session
        sceneView.session.pause()
    }
</code>```

When I close the modal and go back to the ARKit camera view screen this code gets fired:

```<code>override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Create a session configuration
        let configuration = ARWorldTrackingSessionConfiguration()

        // Run the view's session
        sceneView.session.run(configuration)
    }
</code>```

But this code never resumes the session. The screen is completely frozen on the last image it read. Any ideas?

I update the viewDidAppear code to be the following. It is still stuck on the camera screen with image frozen.

```<code>  override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Create a session configuration
        let configuration = ARWorldTrackingSessionConfiguration()

        sceneView.session.delegate = self

        if self.isPaused {
            sceneView.session.run(sceneView.session.configuration!)
        } else {
            // Run the view's session
            sceneView.session.run(configuration)
        }

    }
</code>```

答:
Not sure why your session isn't resuming, but... this generally isn't a situation you want to be in anyway.

Notice in the readme that ships with Apple's ARKit sample code (attached to the WWDC17 session on ARKit):

Avoid interrupting the AR experience. If the user transitions to another fullscreen UI in your app, the AR view might not be an expected state when coming back.

Use the popover presentation (even on iPhone) for auxiliary view controllers to keep the user in the AR experience while adjusting settings or making a modal selection. In this example, the SettingsViewController and VirtualObjectSelectionViewController classes use popover presentation.

To go into a bit more detail: if you pause the session, it won't be tracking the world while your user is away in a different fullscreen view controller. That means that when you resume, any virtual content placed in the scene won't be in the positions (relative to the camera) where you left it.

Title: ARKit Session Paused and Not Resuming

Body:
In my ARKit app I am presenting a modal window. When I close the modal and go back to the ARSCNView then I find out that the session is paused due to this code:

 override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // Pause the view's session
        sceneView.session.pause()
    }

When I close the modal and go back to the ARKit camera view screen this code gets fired:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Create a session configuration
        let configuration = ARWorldTrackingSessionConfiguration()

        // Run the view's session
        sceneView.session.run(configuration)
    }

But this code never resumes the session. The screen is completely frozen on the last image it read. Any ideas?

I update the viewDidAppear code to be the following. It is still stuck on the camera screen with image frozen.

  override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Create a session configuration
        let configuration = ARWorldTrackingSessionConfiguration()

        sceneView.session.delegate = self

        if self.isPaused {
            sceneView.session.run(sceneView.session.configuration!)
        } else {
            // Run the view's session
            sceneView.session.run(configuration)
        }

    }