问:
Fill in gaps between two dates in a dataframe in r
I want to fill in the 'NAs' between two values in a group with the status of the first value. The group is the "label" field, and I want to fill in the 'NA's' in the "status" field.

Here is what I have:

```<code>     datetime                                      title    label   status           option_title
1  2016-08-06                            Pursuit status:      AIG   Active1                   <NA>
2  2016-08-06 What is the current stage of this Pursuit?      AIG     <NA> 1 - Opportunity Review
3  2016-08-31 What is the current stage of this Pursuit?      AIG     <NA>    2 - Solution Review
4  2016-12-13 What is the current stage of this Pursuit?      AIG     <NA>    4 - Submit Proposal
5  2016-11-14                            Pursuit status:  Allianz   Active1                   <NA>
6  2016-10-27 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
7  2017-05-18 What is the current stage of this Pursuit?  Allianz     <NA> 1 - Opportunity Review
8  2017-05-18 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
9  2017-08-24                            Pursuit status:  Allianz Inactive1                   <NA>
10 2016-10-27 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
11 2016-11-14                            Pursuit status:  Allianz   Active2                   <NA>
12 2016-12-19 What is the current stage of this Pursuit?  Allianz     <NA> 1 - Opportunity Review
13 2017-04-14 What is the current stage of this Pursuit?  Allianz     <NA>    2 - Solution Review
</code>```

Here is what I want:

```<code>         datetime                                      title    label   status           option_title
1  2016-08-06                            Pursuit status:      AIG   Active1                   <NA>
2  2016-08-06 What is the current stage of this Pursuit?      AIG   Active1 1 - Opportunity Review
3  2016-08-31 What is the current stage of this Pursuit?      AIG   Active1    2 - Solution Review
4  2016-12-13 What is the current stage of this Pursuit?      AIG   Active1    4 - Submit Proposal
5  2016-11-14                            Pursuit status:  Allianz   Active1                   <NA>
5  2016-10-27 What is the current stage of this Pursuit?  Allianz   Active1      Pre-Qualification
7  2017-05-18 What is the current stage of this Pursuit?  Allianz   Active1 1 - Opportunity Review
8  2017-05-18 What is the current stage of this Pursuit?  Allianz   Active1      Pre-Qualification
9  2017-08-24                            Pursuit status:  Allianz Inactive1                   <NA>
10 2016-10-27 What is the current stage of this Pursuit?  Allianz Inactive1      Pre-Qualification
11 2016-11-14                            Pursuit status:  Allianz   Active2                   <NA>
12 2016-12-19 What is the current stage of this Pursuit?  Allianz   Active2 1 - Opportunity Review
13 2017-04-14 What is the current stage of this Pursuit?  Allianz   Active2    2 - Solution Review
</code>```

Is there a way to do this? I'm thinking the best way would be to get the date of the first status and the date of the second status, and fill in all of the values in-between with the first status.

答:
A tidyr approach:

It appears you have already solved the ordering issue, so here is code to replicate a minimal example of your dataset.

```<code>df_orig <-
    read.table(text = "
             label   status
               AIG   Active1
               AIG     <NA>
               AIG     <NA>
               AIG     <NA>
           Allianz   Active1
           Allianz     <NA>
           Allianz     <NA>
           Allianz     <NA>
           Allianz Inactive1
           Allianz     <NA>
           Allianz   Active2
           Allianz     <NA>
           Allianz     <NA>
                  ", header = TRUE, stringsAsFactors = FALSE) %>%
    mutate(status = sub("<NA>", NA, status)) # to turn the "<NA>" to active NA's
</code>```

```<code>> str(df_orig)
'data.frame': 13 obs. of  2 variables:
 $ label : chr  "AIG" "AIG" "AIG" "AIG" ...
 $ status: chr  "Active1" NA NA NA ...
</code>```

Filling into the 'empties'

```<code>df_filled <-
    df_orig %>%
    fill(status)
</code>```

The result:

```<code>> df_filled
     label    status
1      AIG   Active1
2      AIG   Active1
3      AIG   Active1
4      AIG   Active1
5  Allianz   Active1
6  Allianz   Active1
7  Allianz   Active1
8  Allianz   Active1
9  Allianz Inactive1
10 Allianz Inactive1
11 Allianz   Active2
12 Allianz   Active2
13 Allianz   Active2
</code>```

Body:
I want to fill in the 'NAs' between two values in a group with the status of the first value. The group is the "label" field, and I want to fill in the 'NA's' in the "status" field.

Here is what I have:

     datetime                                      title    label   status           option_title
1  2016-08-06                            Pursuit status:      AIG   Active1                   <NA>
2  2016-08-06 What is the current stage of this Pursuit?      AIG     <NA> 1 - Opportunity Review
3  2016-08-31 What is the current stage of this Pursuit?      AIG     <NA>    2 - Solution Review
4  2016-12-13 What is the current stage of this Pursuit?      AIG     <NA>    4 - Submit Proposal
5  2016-11-14                            Pursuit status:  Allianz   Active1                   <NA>
6  2016-10-27 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
7  2017-05-18 What is the current stage of this Pursuit?  Allianz     <NA> 1 - Opportunity Review
8  2017-05-18 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
9  2017-08-24                            Pursuit status:  Allianz Inactive1                   <NA>
10 2016-10-27 What is the current stage of this Pursuit?  Allianz     <NA>      Pre-Qualification
11 2016-11-14                            Pursuit status:  Allianz   Active2                   <NA>
12 2016-12-19 What is the current stage of this Pursuit?  Allianz     <NA> 1 - Opportunity Review
13 2017-04-14 What is the current stage of this Pursuit?  Allianz     <NA>    2 - Solution Review

Here is what I want:

         datetime                                      title    label   status           option_title
1  2016-08-06                            Pursuit status:      AIG   Active1                   <NA>
2  2016-08-06 What is the current stage of this Pursuit?      AIG   Active1 1 - Opportunity Review
3  2016-08-31 What is the current stage of this Pursuit?      AIG   Active1    2 - Solution Review
4  2016-12-13 What is the current stage of this Pursuit?      AIG   Active1    4 - Submit Proposal
5  2016-11-14                            Pursuit status:  Allianz   Active1                   <NA>
5  2016-10-27 What is the current stage of this Pursuit?  Allianz   Active1      Pre-Qualification
7  2017-05-18 What is the current stage of this Pursuit?  Allianz   Active1 1 - Opportunity Review
8  2017-05-18 What is the current stage of this Pursuit?  Allianz   Active1      Pre-Qualification
9  2017-08-24                            Pursuit status:  Allianz Inactive1                   <NA>
10 2016-10-27 What is the current stage of this Pursuit?  Allianz Inactive1      Pre-Qualification
11 2016-11-14                            Pursuit status:  Allianz   Active2                   <NA>
12 2016-12-19 What is the current stage of this Pursuit?  Allianz   Active2 1 - Opportunity Review
13 2017-04-14 What is the current stage of this Pursuit?  Allianz   Active2    2 - Solution Review

Is there a way to do this? I'm thinking the best way would be to get the date of the first status and the date of the second status, and fill in all of the values in-between with the first status.

Body:
A tidyr approach:

It appears you have already solved the ordering issue, so here is code to replicate a minimal example of your dataset.

df_orig <-
    read.table(text = "
             label   status
               AIG   Active1
               AIG     <NA>
               AIG     <NA>
               AIG     <NA>
           Allianz   Active1
           Allianz     <NA>
           Allianz     <NA>
           Allianz     <NA>
           Allianz Inactive1
           Allianz     <NA>
           Allianz   Active2
           Allianz     <NA>
           Allianz     <NA>
                  ", header = TRUE, stringsAsFactors = FALSE) %>%
    mutate(status = sub("<NA>", NA, status)) # to turn the "<NA>" to active NA's

> str(df_orig)
'data.frame': 13 obs. of  2 variables:
 $ label : chr  "AIG" "AIG" "AIG" "AIG" ...
 $ status: chr  "Active1" NA NA NA ...

Filling into the 'empties'

df_filled <-
    df_orig %>%
    fill(status)

The result:

> df_filled
     label    status
1      AIG   Active1
2      AIG   Active1
3      AIG   Active1
4      AIG   Active1
5  Allianz   Active1
6  Allianz   Active1
7  Allianz   Active1
8  Allianz   Active1
9  Allianz Inactive1
10 Allianz Inactive1
11 Allianz   Active2
12 Allianz   Active2
13 Allianz   Active2


来源: stackexchange

问:
WebRequest not returning HTML
I want to load this http://www.yellowpages.ae/categories-by-alphabet/h.html url, but it returns null

In some question I have heard about adding Cookie container but it is already there in my code.

```<code>var MainUrl = "http://www.yellowpages.ae/categories-by-alphabet/h.html";
HtmlWeb web = new HtmlWeb();
web.PreRequest += request =>
{
    request.CookieContainer = new System.Net.CookieContainer();
    return true;
};
web.CacheOnly = false;
var doc = web.Load(MainUrl);
</code>```

the website opens perfectly fine in browser.

答:
I doubt it is a cookie issue. Looks like a gzip encryption since I got nothing but gibberish when I tried to fetch the page. If it was a cookie issue the response should return an error saying so. Anyhow. Here is my solution to your problem.

```<code>public static void Main(string[] args)
{
    HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.yellowpages.ae/categories-by-alphabet/h.html");
        request.Method = "GET";
        request.ContentType = "text/html;charset=utf-8";
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

        using (var response = (HttpWebResponse)request.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                doc.Load(stream, Encoding.GetEncoding("utf-8"));
            }
        }
    }
    catch (WebException ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.WriteLine(doc.DocumentNode.InnerHtml);
    Console.ReadKey();
}
</code>```

All it does is that it decrypts/extracts the gzip message that we receive.
How did I know it was GZIP you ask? The response stream from the debugger said that the ContentEncoding was gzip.

Basically just add:

```<code>request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
</code>```

To your code and you're good.

ContentLicense: CC BY-SA 4.0

Title: WebRequest not returning HTML

Body:
I want to load this http://www.yellowpages.ae/categories-by-alphabet/h.html url, but it returns null

In some question I have heard about adding Cookie container but it is already there in my code.

var MainUrl = "http://www.yellowpages.ae/categories-by-alphabet/h.html";
HtmlWeb web = new HtmlWeb();
web.PreRequest += request =>
{
    request.CookieContainer = new System.Net.CookieContainer();
    return true;
};
web.CacheOnly = false;
var doc = web.Load(MainUrl);

the website opens perfectly fine in browser.

Body:
I doubt it is a cookie issue. Looks like a gzip encryption since I got nothing but gibberish when I tried to fetch the page. If it was a cookie issue the response should return an error saying so. Anyhow. Here is my solution to your problem.

public static void Main(string[] args)
{
    HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.yellowpages.ae/categories-by-alphabet/h.html");
        request.Method = "GET";
        request.ContentType = "text/html;charset=utf-8";
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

        using (var response = (HttpWebResponse)request.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                doc.Load(stream, Encoding.GetEncoding("utf-8"));
            }
        }
    }
    catch (WebException ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.WriteLine(doc.DocumentNode.InnerHtml);
    Console.ReadKey();
}

All it does is that it decrypts/extracts the gzip message that we receive.
How did I know it was GZIP you ask? The response stream from the debugger said that the ContentEncoding was gzip.

Basically just add:

request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

To your code and you're good.

ContentLicense: CC BY-SA 3.0


问:
JPA, Hibernate validators - email validator not applying on String
I'm trying to figure out how to validate DTO in my controller

Stack:
Spring boot 1.5.4, Spring Data JPA, Hibernate Validation 5, PostgreSQL

The problem is that I'm still getting exception about missing validators.

Any clues?

```<code>javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Email' validating type 'java.lang.String'. Check configuration for 'email'
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.throwExceptionForNullValidator(ConstraintTree.java:227) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping(ConstraintTree.java:308) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping(ConstraintTree.java:242) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator(ConstraintTree.java:163) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:116) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:616) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
</code>```

DTO

```<code>public class CreateUserDto {

    @NotEmpty
    private String name;

    @Email
    @NotEmpty
    private String email;

    private String password;

    private String address;

    private String phone;

    @NotNull
    private Role role;
}
</code>```

Controller

```<code>@PostMapping(value = "/users", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public UserDto register(@Valid @RequestBody CreateUserDto user) {
    return userService.register(user);
}
</code>```

答:
I suspect you are using Bean Validation 2.0 with Hibernate Validator 5.4 which only supports BV 1.1. The @Email constraint was added to the spec in 2.0 - prior to that, it was only an HV specific constraint.

You probably added a dependency to validation-api 2.0.

So:

either you go back to BV 1.1 and you will need to use the Hibernate Validator specific @Email constraint (from the package org.hibernate.validator.constraints);

or you upgrade HV to 6.0 (which is recommended) and you keep BV 2.0 and the javax.validation @Email constraint.

Body:
I'm trying to figure out how to validate DTO in my controller

Stack:
Spring boot 1.5.4, Spring Data JPA, Hibernate Validation 5, PostgreSQL

The problem is that I'm still getting exception about missing validators.

Any clues?

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Email' validating type 'java.lang.String'. Check configuration for 'email'
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.throwExceptionForNullValidator(ConstraintTree.java:227) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping(ConstraintTree.java:308) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping(ConstraintTree.java:242) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator(ConstraintTree.java:163) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:116) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]
    at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:616) ~[hibernate-validator-5.4.1.Final.jar:5.4.1.Final]

DTO

public class CreateUserDto {

    @NotEmpty
    private String name;

    @Email
    @NotEmpty
    private String email;

    private String password;

    private String address;

    private String phone;

    @NotNull
    private Role role;
}

Controller

@PostMapping(value = "/users", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public UserDto register(@Valid @RequestBody CreateUserDto user) {
    return userService.register(user);
}


问:
Is storing configurations in vuex store a good practice?
Is storing configurations in vuex store a good practice?</p>

```<code>export default {
  state: {
    app: {
      name: 'A project using vuex'
    }
  }
}
</code>```

答:
As far as I know there is really nothing wrong with storing configuration in Vuex.

Now password and other sensitive information is another thing.

I personally store sensitive info in .env as :

```<code>MONGODB_URI=mongodb://foo:bar@foo.com/foobar
MAILGUN_USER=2342d@34234218b9fd5d4e5dc.mailgun.org
MAILGUN_PASSWORD=4uri62342342
</code>```

You can also store and export other simple configuration in a js file as:

```<code>export default {
  app: [
    name: 'foo',
    path: '../app'
  ]
}
</code>```

Anything outside those that you need to manage the state of (change) or access globally can and should be done in vuex.

Body:
Is storing configurations in vuex store a good practice?

export default {
  state: {
    app: {
      name: 'A project using vuex'
    }
  }
}

Body:
As far as I know there is really nothing wrong with storing configuration in Vuex.

Now password and other sensitive information is another thing.

I personally store sensitive info in .env as :

MONGODB_URI=mongodb://foo:bar@foo.com/foobar
MAILGUN_USER=2342d@34234218b9fd5d4e5dc.mailgun.org
MAILGUN_PASSWORD=4uri62342342

You can also store and export other simple configuration in a js file as:

export default {
  app: [
    name: 'foo',
    path: '../app'
  ]
}

Anything outside those that you need to manage the state of (change) or access globally can and should be done in vuex.


问:
Unicode Replacement with ASCII
I have created a text file on windows system where I think default encoding style is ANSI and contents of the file looks like this :

```<code>This is\u2019 a sample text file \u2014and it can ....
</code>```

I saved this file using the default encoding style of windows though there were encoding styles were also available like UTF-8,UTF-16 etc.

Now I want to write a simple java function where I will pass some input string and replace all of the unicodes with the corresponding ascii value.

e.g :- \u2019 should be replaced with "'"
\u2014 should be replaced with "-" and so on.

Observation :
When i created a string literal like this

```<code>  String s = "This is\u2019 a sample text file \u2014and it can ....";
</code>```

My code is working fine , but when I am reading it from the file it is not working. I am aware that in Java String uses UTF-16 encoding .

Below is the code that I am using to read the input file.

```<code>FileReader fileReader  = new FileReader(new File("C:\\input.txt"));
BufferedReader bufferedReader = new BufferedReader(fileReader)
String record = bufferedReader.readLine();
</code>```

I also tried using the InputStream and setting the Charset to UTF-8 , but still the same result.

Replacement code :

```<code>public static String removeUTFCharacters(String data){
        for(Entry<String,String> entry : utfChars.entrySet()){
            data=data.replaceAll(entry.getKey(), entry.getValue());
        }
        return data;
    }
</code>```

Map :

```<code>    utfChars.put("\u2019","'");
    utfChars.put("\u2018","'");
    utfChars.put("\u201c","\"");
    utfChars.put("\u201d","\"");
    utfChars.put("\u2013","-");
    utfChars.put("\u2014","-");
    utfChars.put("\u2212","-");
    utfChars.put("\u2022","*");
</code>```

Can anybody help me in understanding the concept and solution to this problem.

答:
If you can use another library, you can use apache commons
https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html</p>

```<code>String dirtyString = "Colocaci\u00F3n";
String cleanString = StringEscapeUtils.unescapeJava(dirtyString);
//cleanString = "Colocación"
</code>```

Title: Unicode Replacement with ASCII

Body:
I have created a text file on windows system where I think default encoding style is ANSI and contents of the file looks like this :

This is\u2019 a sample text file \u2014and it can ....

I saved this file using the default encoding style of windows though there were encoding styles were also available like UTF-8,UTF-16 etc.

Now I want to write a simple java function where I will pass some input string and replace all of the unicodes with the corresponding ascii value.

e.g :- \u2019 should be replaced with "'"
\u2014 should be replaced with "-" and so on.

Observation :
When i created a string literal like this

  String s = "This is\u2019 a sample text file \u2014and it can ....";

My code is working fine , but when I am reading it from the file it is not working. I am aware that in Java String uses UTF-16 encoding .

Below is the code that I am using to read the input file.

FileReader fileReader  = new FileReader(new File("C:\\input.txt"));
BufferedReader bufferedReader = new BufferedReader(fileReader)
String record = bufferedReader.readLine();

I also tried using the InputStream and setting the Charset to UTF-8 , but still the same result.

Replacement code :

public static String removeUTFCharacters(String data){
        for(Entry<String,String> entry : utfChars.entrySet()){
            data=data.replaceAll(entry.getKey(), entry.getValue());
        }
        return data;
    }

Map :

    utfChars.put("\u2019","'");
    utfChars.put("\u2018","'");
    utfChars.put("\u201c","\"");
    utfChars.put("\u201d","\"");
    utfChars.put("\u2013","-");
    utfChars.put("\u2014","-");
    utfChars.put("\u2212","-");
    utfChars.put("\u2022","*");

Can anybody help me in understanding the concept and solution to this problem.

Body:
If you can use another library, you can use apache commons
https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html

String dirtyString = "Colocaci\u00F3n";
String cleanString = StringEscapeUtils.unescapeJava(dirtyString);
//cleanString = "Colocación"


问:
Does polymorphism exist in QML?
Does polymorphism and/or object pointers exist in QML? I have a class A that has five members of different classes of which exactly one is visible at any given moment. I also have properties in A that depend on properties in the visible member (which are called the same things in all members).

Currently, I'm calculating every such property in A using the following strategy:

```<code>import QtQuick 2.7

Rectangle {
    property int a: member1.visible ? member1.alpha + member1.beta :
                    member2.visible ? member2.alpha + member2.beta :
                    member3.visible ? member3.alpha + member3.beta :
                    member4.visible ? member4.alpha + member4.beta :
                    member5.visible ? member5.alpha + member5.beta :
                    0

    property int b: member1.visible ? member1.gamma * member1.delta :
                    member2.visible ? member2.gamma * member2.delta :
                    member3.visible ? member3.gamma * member3.delta :
                    member4.visible ? member4.gamma * member4.delta :
                    member5.visible ? member5.gamma * member5.delta :
                    0

    // Exactly one of these members have its visible-property set to true
    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}
</code>```

which feels both like it's using more code than necessary, and like it's not very maintenance friendly both since it's easy to make an error and since I have to update the expressions for all properties in A if I want to add or remove a member.

Ideally (comming from a background of doing a lot of C++ programming), I would like to be able to do something like this:

```<code>import QtQuick 2.7

Rectangle {
    property <property-type> visibleMember:
        member1.visible ? member1 :
        member2.visible ? member2 :
        member3.visible ? member3 :
        member4.visible ? member4 :
        member5.visible ? member5 :
        0  // Shouldn't happen

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}
</code>```

in order to reduce the amount of code needed to be written and increase the maintainability, where visibleMember would then be a pointer or some kind of reference to an object. Or perhaps even:

```<code>import QtQuick 2.7

Rectangle {
    property <property-type> visibleMember: NULL

    property int a: visibleMember !== NULL ? visibleMember.alpha + visibleMember.beta : 0
    property int b: visibleMember !== NULL ? visibleMember.gamma * visibleMember.delta : 0
}
</code>```

and set visibleMember from outside the class (for example by its parent) and in that way be able to create objects dynamically (if that is possible) which are then assigned to visibleMember, instead of having all possible objects that can be assigned to visibleMember existing as latent members in A.

However, I'm not sure what <property-type> would be, or whether you can assign an object pointer to visibleMember like this (i.e. whether object pointers/references exist), which can then be checked to see whether it is a NULL pointer. Is at least somethng of what I'm trying to do possible to achieve in some way?

答:
If all classes inherit the same base class, let's say QtObject you can easily use that as the property type.

You can still access properties that would not be existent in the base class, as the concrete objects keep their original meta information.

This meta information then is used to evaluate the bindings.

If you try to access a property that is not defined in the concrete object where you want to access it, it will evaluate to undefined. If you try to access a subproperty this would throw warning.

If you don't have any common baseclass, because it might also be a string or a int you can use  var as data type for the property.

For performance reasons it is advisable to use the closest fitting/possible data type. If the data type used for the property already features the properties that you want to access in it, the bindings can be optimized.

Lets say our base class is MyBaseClass, then you could write:

```<code>import QtQuick 2.7

Rectangle {
    property MyBaseClass visibleMember:
        member1.visible ? member1 :
        member2.visible ? member2 :
        member3.visible ? member3 :
        member4.visible ? member4 :
        member5.visible ? member5 :
        null  // Shouldn't happen

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}
</code>```

If that base class also has the properties alpha, beta, gamma, delta predefined, the bindings for a and b might be optimized.

Of course you can also just set that property from the outside, as you have exposed it in the root node of the component.

Title: Does polymorphism exist in QML?

Body:
Does polymorphism and/or object pointers exist in QML? I have a class A that has five members of different classes of which exactly one is visible at any given moment. I also have properties in A that depend on properties in the visible member (which are called the same things in all members).

Currently, I'm calculating every such property in A using the following strategy:

import QtQuick 2.7

Rectangle {
    property int a: member1.visible ? member1.alpha + member1.beta :
                    member2.visible ? member2.alpha + member2.beta :
                    member3.visible ? member3.alpha + member3.beta :
                    member4.visible ? member4.alpha + member4.beta :
                    member5.visible ? member5.alpha + member5.beta :
                    0

    property int b: member1.visible ? member1.gamma * member1.delta :
                    member2.visible ? member2.gamma * member2.delta :
                    member3.visible ? member3.gamma * member3.delta :
                    member4.visible ? member4.gamma * member4.delta :
                    member5.visible ? member5.gamma * member5.delta :
                    0

    // Exactly one of these members have its visible-property set to true
    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}

which feels both like it's using more code than necessary, and like it's not very maintenance friendly both since it's easy to make an error and since I have to update the expressions for all properties in A if I want to add or remove a member.

Ideally (comming from a background of doing a lot of C++ programming), I would like to be able to do something like this:

import QtQuick 2.7

Rectangle {
    property <property-type> visibleMember:
        member1.visible ? member1 :
        member2.visible ? member2 :
        member3.visible ? member3 :
        member4.visible ? member4 :
        member5.visible ? member5 :
        0  // Shouldn't happen

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}

in order to reduce the amount of code needed to be written and increase the maintainability, where visibleMember would then be a pointer or some kind of reference to an object. Or perhaps even:

import QtQuick 2.7

Rectangle {
    property <property-type> visibleMember: NULL

    property int a: visibleMember !== NULL ? visibleMember.alpha + visibleMember.beta : 0
    property int b: visibleMember !== NULL ? visibleMember.gamma * visibleMember.delta : 0
}

and set visibleMember from outside the class (for example by its parent) and in that way be able to create objects dynamically (if that is possible) which are then assigned to visibleMember, instead of having all possible objects that can be assigned to visibleMember existing as latent members in A.

However, I'm not sure what <property-type> would be, or whether you can assign an object pointer to visibleMember like this (i.e. whether object pointers/references exist), which can then be checked to see whether it is a NULL pointer. Is at least somethng of what I'm trying to do possible to achieve in some way?

Body:
If all classes inherit the same base class, let's say QtObject you can easily use that as the property type.

You can still access properties that would not be existent in the base class, as the concrete objects keep their original meta information.

This meta information then is used to evaluate the bindings.

If you try to access a property that is not defined in the concrete object where you want to access it, it will evaluate to undefined. If you try to access a subproperty this would throw warning.

If you don't have any common baseclass, because it might also be a string or a int you can use  var as data type for the property.

For performance reasons it is advisable to use the closest fitting/possible data type. If the data type used for the property already features the properties that you want to access in it, the bindings can be optimized.

Lets say our base class is MyBaseClass, then you could write:

import QtQuick 2.7

Rectangle {
    property MyBaseClass visibleMember:
        member1.visible ? member1 :
        member2.visible ? member2 :
        member3.visible ? member3 :
        member4.visible ? member4 :
        member5.visible ? member5 :
        null  // Shouldn't happen

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}

If that base class also has the properties alpha, beta, gamma, delta predefined, the bindings for a and b might be optimized.

Of course you can also just set that property from the outside, as you have exposed it in the root node of the component.


问:
Fixing Subversion Repository
This is a very annoying problem with Subversion.  The problem is talked about in this thread, but I don't see how to apply the solution to my situation.

I am developing using Netbeans 7-beta and sometimes use my Mac, sometimes my Windows system, and I made the mistake of renaming a file (using Netbeans refactoring) where the rename was just changing the case of the letters.   Then there were subsequent checkins from both the Mac and the Windows side -- I don't remember exactly what step did the damage.

The result is that if I try to just go to check out the project on any system, I get the error:

```<code>svn: Can't open file zzzzz/.svn/tmp/text-base/xxxxx.java.svn-base
</code>```

where the tokens zzzzz and xxxxx are specific to my project.   The xxxxx was once named xXxXx or something.

I can check out the plain code (no .svn directories) and create a new repository, but that will lose all my history.  Trying to get Netbeans to check in the file with the original name doesn't seem to work either.   Is there another way to clean this up?

答: As in the accepted answer in the thread you referred to I would suggest inspecting the files in the folder using TortoiseSVN's repo browser - it appears likely that you'll find two files with the same name but different case.  From within repo browser delete one of the files, and try your update again.

ContentLicense: CC BY-SA 2.5

Title: Fixing Subversion Repository

Body:
This is a very annoying problem with Subversion.  The problem is talked about in this thread, but I don't see how to apply the solution to my situation.

I am developing using Netbeans 7-beta and sometimes use my Mac, sometimes my Windows system, and I made the mistake of renaming a file (using Netbeans refactoring) where the rename was just changing the case of the letters.   Then there were subsequent checkins from both the Mac and the Windows side -- I don't remember exactly what step did the damage.

The result is that if I try to just go to check out the project on any system, I get the error:

svn: Can't open file zzzzz/.svn/tmp/text-base/xxxxx.java.svn-base

where the tokens zzzzz and xxxxx are specific to my project.   The xxxxx was once named xXxXx or something.

I can check out the plain code (no .svn directories) and create a new repository, but that will lose all my history.  Trying to get Netbeans to check in the file with the original name doesn't seem to work either.   Is there another way to clean this up?


问:
Objectify - save order of Ref<?>-s
I have a system where I'm trying to minimize the number of Datastore writes (who wouldn't?), all the while using ancestor relations. Consider the following simplified classes:

```<code>public class Ancestor {
    @Id
    private String id;
    private String field;
    private Ref<Descendant> descendantRef;
    public Descendant getDescendant() {
        return this.descendantRef.get();
    }
    public void setDescendant(Descendant des) {
        this.descendantRef = Ref.create(des);
    }
}

public class Descendant {
    @Id
    private String id;
    private String field;
    @Parent
    private Key parent;
}
</code>```

My problem: even though I set the descendant ref, upon saving the Ancestor entity, a null is saved, but if I save the Descendant as well, Objectify complains Attempted to save a null entity.

My question: I gathered that Objectify optimizes the order of get() operations with the @Load annotation, so is there a way to make it do the same on save() operations as well, so that by the time the Ancestor is being sent to the Datastore, the Descendant ref is populated properly?

Thank you in advance for any advice!

答:
You can hide this implementation like this:

```<code>public Descendant getDescendant() {
    // You probably don't want to break your code on null descendantRef
    if (this.descendantRef != null) {
        return this.descendantRef.get();
    }
    return null;
}

public void setDescendant(Descendant des) {
    // Insert if this des have never been insert
    if (getDescendant() != null) {
        new DescendantEndpoint().insert(des);
    }
    // You probably don't want to break your code on null des
    if (des != null) {
        this.descendantRef = Ref.create(des);
    }
}
</code>```

By this, you don't have to do deal with each insertion of the ref on each endpoint you will make. Still, this method is not optimized for bulk insert as it will insert on each seperate datastore connection.

For this you can do something like this:

```<code>private Object bulkInsertAncestor(ArrayList<Ancestor> list){
        ArrayList<Descendant> descendantArrayList = //get descendant list
        // You should do all this inside a transaction
        new DescendantEndpoint().bulkInsertDescendant(descendantArrayList);
        return ofy().save().entities(list);
    }
</code>```

Title: Objectify - save order of Ref<?>-s

Body:
I have a system where I'm trying to minimize the number of Datastore writes (who wouldn't?), all the while using ancestor relations. Consider the following simplified classes:

public class Ancestor {
    @Id
    private String id;
    private String field;
    private Ref<Descendant> descendantRef;
    public Descendant getDescendant() {
        return this.descendantRef.get();
    }
    public void setDescendant(Descendant des) {
        this.descendantRef = Ref.create(des);
    }
}

public class Descendant {
    @Id
    private String id;
    private String field;
    @Parent
    private Key parent;
}

My problem: even though I set the descendant ref, upon saving the Ancestor entity, a null is saved, but if I save the Descendant as well, Objectify complains Attempted to save a null entity.

My question: I gathered that Objectify optimizes the order of get() operations with the @Load annotation, so is there a way to make it do the same on save() operations as well, so that by the time the Ancestor is being sent to the Datastore, the Descendant ref is populated properly?

Thank you in advance for any advice!

Body:
You can hide this implementation like this:

public Descendant getDescendant() {
    // You probably don't want to break your code on null descendantRef
    if (this.descendantRef != null) {
        return this.descendantRef.get();
    }
    return null;
}

public void setDescendant(Descendant des) {
    // Insert if this des have never been insert
    if (getDescendant() != null) {
        new DescendantEndpoint().insert(des);
    }
    // You probably don't want to break your code on null des
    if (des != null) {
        this.descendantRef = Ref.create(des);
    }
}

By this, you don't have to do deal with each insertion of the ref on each endpoint you will make. Still, this method is not optimized for bulk insert as it will insert on each seperate datastore connection.

For this you can do something like this:

private Object bulkInsertAncestor(ArrayList<Ancestor> list){
        ArrayList<Descendant> descendantArrayList = //get descendant list
        // You should do all this inside a transaction
        new DescendantEndpoint().bulkInsertDescendant(descendantArrayList);
        return ofy().save().entities(list);
    }


问:
Regex for Phone Number in the MIDDLE of a string?
I've seen multiple questions/answers regarding phone number authentication, which is great, but all of them only seen to work IF the string is strictly a phone number. In my case, we might have receive a string like this:

"Okay, I've got your number as 313-123-1234. Now lets..."

The formatting of the phone number can vary as well, so I think it would be better if the regex could handle "any sequence of 10 numbers, ignoring (  )  -  ."

I've tried a few different things, including:

```<code>"^((\\+\\d{1,2}|1)[\\s.-]?)?\\(?[2-9](?!11)\\d{2}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}$"
</code>```

and

```<code>"/[0-9]{10}\\b/"
</code>```

Among others, which, again, seen to work if it's the phone number by itself, but when I call:myStrig.matches(myRegex); on the full string, it always returns false.

With that being said, is there either a native solution, such as PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber) that would work with the example phrase mentioned above, or what is a regex that would actually work in this case?

Thanks!

Body:
I've seen multiple questions/answers regarding phone number authentication, which is great, but all of them only seen to work IF the string is strictly a phone number. In my case, we might have receive a string like this:

"Okay, I've got your number as 313-123-1234. Now lets..."

The formatting of the phone number can vary as well, so I think it would be better if the regex could handle "any sequence of 10 numbers, ignoring (  )  -  ."

I've tried a few different things, including:

"^((\\+\\d{1,2}|1)[\\s.-]?)?\\(?[2-9](?!11)\\d{2}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}$"

and

"/[0-9]{10}\\b/"

Among others, which, again, seen to work if it's the phone number by itself, but when I call:myStrig.matches(myRegex); on the full string, it always returns false.

With that being said, is there either a native solution, such as PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber) that would work with the example phrase mentioned above, or what is a regex that would actually work in this case?

Thanks!

Body:
Try using this pattern :

String REGEX_PHONE_NUMBER_ALL = "(?:\\(\\d{3}\\)|\\d{3}[-]*)\\d{3}[-]*\\d{4}";


问:
constructor Arguments and Spring Data De-Serialization Issue
Using Spring Data with MongoDB.

Problem is in instantiating a bean retrieved from Mongo because the constructor has some argument which actually is inside a nested object. Persistance is not an issue. Retrieval Is.

Class structure is as below where B is nested inside A. A sets B instantiating it using one of its constructor Params.

Class A

```<code>Class A{
 int prop1;
 B b;

 @JsonCreator
 public A(  @JsonProperty int prop1, @JsonProperty  int prop2){
  this.prop1 = prop1;
  this.b = new B(prop2);
 }
}
</code>```

Class B which is nested inside A

```<code>Class B(){
 int prop2;

 @JsonCreator
 public B(@JsonProperty int prop2){
  this.prop2 = prop2;
 }
}
</code>```

When Object is received by REST API in the below Json form:

```<code> {"prop1":"Hello1","prop2":"Hello2"}
</code>```

Spring Controller receives it and maps it correctly to Object A. Since Spring uses no-arg constructor by default, I used jsoncreator annotation on arg-constructor and it is added to MongoDB without any fuss.

The data is stored in below format as per bean structure which is right.

```<code>      {"prop1":"Hello1","b":{"prop2":"Hello2"}}
</code>```

Coming to the problem: Error comes when I try to retrieve from Mongo. It says:

```<code> org.springframework.data.mapping.model.MappingException: No property prop2
 found on entity class A to bind constructor parameter to
</code>```

How Can I tell SpringData to use object B which contains prop2 when getting it from SpringData? (Perhaps thats not possible)

I thought perhaps adding one more constructor will do the trick, where I use object B as one of the constructor arguments like below:

```<code>   public A(int prop1, B b){
       ......
       ......
   }
</code>```

Adding one more constructor works with ObjectMapper but again not with SpringData.

This time a new exception is thrown :

```<code>      org.springframework.data.mapping.model.MappingInstantiationException:
      Failed to instantiate A using constructor NO_CONSTRUCTOR with
      arguments.
</code>```

I checked the above error where List is being used/not used , but I tried both ways and didnt resolve.

Please note: I am using object B as nested since it contains common properties which will be used by lot of other beans ( could be abstract class , but I will need to try that later, but somehow abstract class seems limiting)

How do have SpringData create object A ?

答:
Looks like a faux pas.

Should have used better terms in searching. Would have found the correct answer. Just in case somebody faces this problem ...

Some searching led me to this below question:

How exactly does spring-data-mongodb handle constructors when rehydrating objects?

The above question mentions few things which gave me the solution. The answer lies in using another constructor for deserialization from SpringData to bean. This constructor needs to be annotated with:

```<code>    @PersistenceConstructor
</code>```

In the example in the question, if I use the second constructor with this annotation, retrieval works.

```<code>        @PersistenceConstructor
        public A(int prop1, B b){
         ......
         ......
        }
</code>```

So now , I have 2 constructors , one with @jsoncreator and another with @PersistenceConstructor. But to add , this other constructor can be private also if you have no other use for it other than for retrieval from SpringData and it will not be used in code by anybody thus leaving your Business Logic intact.
Hence the below will also work:

```<code>        @PersistenceConstructor
        private A(int prop1, B b){
         ......
         ......
        }
</code>```

Body:
Using Spring Data with MongoDB.

Problem is in instantiating a bean retrieved from Mongo because the constructor has some argument which actually is inside a nested object. Persistance is not an issue. Retrieval Is.

Class structure is as below where B is nested inside A. A sets B instantiating it using one of its constructor Params.

Class A

Class A{
 int prop1;
 B b;

 @JsonCreator
 public A(  @JsonProperty int prop1, @JsonProperty  int prop2){
  this.prop1 = prop1;
  this.b = new B(prop2);
 }
}

Class B which is nested inside A

Class B(){
 int prop2;

 @JsonCreator
 public B(@JsonProperty int prop2){
  this.prop2 = prop2;
 }
}

When Object is received by REST API in the below Json form:

 {"prop1":"Hello1","prop2":"Hello2"}

Spring Controller receives it and maps it correctly to Object A. Since Spring uses no-arg constructor by default, I used jsoncreator annotation on arg-constructor and it is added to MongoDB without any fuss.

The data is stored in below format as per bean structure which is right.

      {"prop1":"Hello1","b":{"prop2":"Hello2"}}

Coming to the problem: Error comes when I try to retrieve from Mongo. It says:

 org.springframework.data.mapping.model.MappingException: No property prop2
 found on entity class A to bind constructor parameter to

How Can I tell SpringData to use object B which contains prop2 when getting it from SpringData? (Perhaps thats not possible)

I thought perhaps adding one more constructor will do the trick, where I use object B as one of the constructor arguments like below:

   public A(int prop1, B b){
       ......
       ......
   }

Adding one more constructor works with ObjectMapper but again not with SpringData.

This time a new exception is thrown :

      org.springframework.data.mapping.model.MappingInstantiationException:
      Failed to instantiate A using constructor NO_CONSTRUCTOR with
      arguments.

I checked the above error where List is being used/not used , but I tried both ways and didnt resolve.

Please note: I am using object B as nested since it contains common properties which will be used by lot of other beans ( could be abstract class , but I will need to try that later, but somehow abstract class seems limiting)

How do have SpringData create object A ?

Body:
Looks like a faux pas.

Should have used better terms in searching. Would have found the correct answer. Just in case somebody faces this problem ...

Some searching led me to this below question:

How exactly does spring-data-mongodb handle constructors when rehydrating objects?

The above question mentions few things which gave me the solution. The answer lies in using another constructor for deserialization from SpringData to bean. This constructor needs to be annotated with:

    @PersistenceConstructor

In the example in the question, if I use the second constructor with this annotation, retrieval works.

        @PersistenceConstructor
        public A(int prop1, B b){
         ......
         ......
        }

So now , I have 2 constructors , one with @jsoncreator and another with @PersistenceConstructor. But to add , this other constructor can be private also if you have no other use for it other than for retrieval from SpringData and it will not be used in code by anybody thus leaving your Business Logic intact.
Hence the below will also work:

        @PersistenceConstructor
        private A(int prop1, B b){
         ......
         ......
        }


问:
How to convert c++ for loop to Python?
I wrote a code in C++ and would like to convert it to Python3. How to do that?

```<code>int N = 1000
for (p=2; p*p<=N; p++)
    for (w=p*p; w<=N; w=w+p)
</code>```

I tried to change the first for loop to:

```<code>for p in range(2,N**0.5+1):
</code>```

But it doesn't work - TypeError: 'float' object cannot be interpreted as an integer

And what about the second for loop?

答:
Try This ( in python You should do that with while ):

```<code>N = 1000
p = 2

while p*p <= N:

    p = p + 1
    w = p*p
    print(p)

    while w <= N:
        w = w + p
        print(w)
</code>```

UPDATE :

The reason that you get the error "TypeError: 'float' object cannot be interpreted as an integer" is that the "range" function expects "integers" as arguments, whereas "N ** 0.5" is of type float, so is "N ** 0.5+1". To resolve this issue you can simply use "int" function to the conversion from float to integer. The following code is what you are looking for:

```<code>N = 1000
for p in range(2, int(N ** 0.5) + 1, 1):
    for w in range(p * p, N + 1, p):
        print(p, w)
</code>```

Title: How to convert c++ for loop to Python?

Body:
I wrote a code in C++ and would like to convert it to Python3. How to do that?

int N = 1000
for (p=2; p*p<=N; p++)
    for (w=p*p; w<=N; w=w+p)

I tried to change the first for loop to:

for p in range(2,N**0.5+1):

But it doesn't work - TypeError: 'float' object cannot be interpreted as an integer

And what about the second for loop?

Body:
Try This ( in python You should do that with while ):

N = 1000
p = 2

while p*p <= N:

    p = p + 1
    w = p*p
    print(p)

    while w <= N:
        w = w + p
        print(w)

UPDATE :

The reason that you get the error "TypeError: 'float' object cannot be interpreted as an integer" is that the "range" function expects "integers" as arguments, whereas "N ** 0.5" is of type float, so is "N ** 0.5+1". To resolve this issue you can simply use "int" function to the conversion from float to integer. The following code is what you are looking for:

N = 1000
for p in range(2, int(N ** 0.5) + 1, 1):
    for w in range(p * p, N + 1, p):
        print(p, w)


问:
What is time complexity for nested map
For the nested map like :

```<code>Map<String, Map<String, List<String>>> map = new HashMap<String, HashMap<String, ArrayList<String>>>();
</code>```

What would the time complexity be for its normal operation like put, remove, containsKey?

Thanks!

答:
The time complexity would be the same as the time complexity of non-nested HashMaps.

Each lookup still takes average constant time.

To search for an inner value in the nested Map you need to perform two lookups - the first in the outer Map, and if a value was found in the outer Map, a second lookup in the inner Map. Since both lookup will take constant time, the total lookup time remains constant.

The same is true for put, remove, etc...

Title: What is time complexity for nested map

Body:
For the nested map like :

Map<String, Map<String, List<String>>> map = new HashMap<String, HashMap<String, ArrayList<String>>>();

What would the time complexity be for its normal operation like put, remove, containsKey?

Thanks!


问:
Dataflow Workers unable to connect to Dataflow Service
I am using Google Dataprep to start Dataflow jobs and am facing some difficulties.

For background, we used Dataprep for some weeks and it worked without problem before we started to have authorization issues with the service account. When we finally solved this, we restarted the jobs we used to launch but they failed with "The Dataflow appears to be stuck.".

We tried with another very simple job but we met the same error. Here are the full error messages, the job fails after one hour being stuck:

Dataflow -

```<code>(1ff58651b9d6bab2): Workflow failed. Causes: (1ff58651b9d6b915): The Dataflow appears to be stuck.
</code>```

Dataprep -

```<code>The Dataflow job (ID: 2017-11-15_00_23_23-9997011066491247322) failed. Please
contact Support and provide the Dataprep Job ID 20825 and the Dataflow Job ID.
</code>```

It seems this kind of error has various origins and I have no clue about where to start.
Thanks in advance

答:
the best route would be to contact Google Support.
The issue is related to the Dataflow side and would require some more research on the Dataflow backend by Google</p>

Body:
I am using Google Dataprep to start Dataflow jobs and am facing some difficulties.

For background, we used Dataprep for some weeks and it worked without problem before we started to have authorization issues with the service account. When we finally solved this, we restarted the jobs we used to launch but they failed with "The Dataflow appears to be stuck.".

We tried with another very simple job but we met the same error. Here are the full error messages, the job fails after one hour being stuck:

Dataflow -

(1ff58651b9d6bab2): Workflow failed. Causes: (1ff58651b9d6b915): The Dataflow appears to be stuck.

Dataprep -

The Dataflow job (ID: 2017-11-15_00_23_23-9997011066491247322) failed. Please
contact Support and provide the Dataprep Job ID 20825 and the Dataflow Job ID.

It seems this kind of error has various origins and I have no clue about where to start.
Thanks in advance


问:
Achieve (possibly) covariant cast

I have the following classes:

```<code>X : BaseX
</code>```

```<code>XView : BaseView<X>
</code>```

```<code>XDAO : BaseDAO<X>
</code>```

```<code>MainViewModel<TX, TView, TDAO>
where TX : X
where TView : View<X>
where TDAO : DAO<X>
</code>```

```<code>XMainViewModel : MainViewModel<X, XView, XDAO>
</code>```

I have an instance of XMainViewModel<X, XView, XDAO>. I want to cast this to MainViewModel<BaseX, BaseView<X>, BaseDAO<X>>. Is this possible? It might have covariants involved. I'm not familiar with covariants, and only started using generics not long ago so I'm rather confused here (I also hope I did not make any typos in the question). Any help is appreciated.

答:
Is this possible?

No. Generic covariance and contravariance are supported only on interfaces and delegates constructed with reference types.

I'm rather confused here

It's a confusing topic. One way to think about it is to always be asking yourself "suppose this were legal; what could go wrong?" You say

I have XMainViewModel<X, XView, XDAO>. I want to cast this to MainViewModel<BaseX, BaseView<X>, BaseDAO<X>>

Let's look at a simpler example. You have a List<Giraffe> and you wish to cast it to List<Animal>.  What can go wrong?

```<code>List<Giraffe> giraffes = new List<Giraffe>();
giraffes.Add(new Giraffe());
List<Animal> animals = (List<Animal>)giraffes; // This is illegal. What if it were legal?
animals.Add(new Tiger());
Giraffe g = giraffes[1]; // And we just put a Tiger into a variable of type Giraffe.
</code>```

That's why this is illegal, and why your example would also be illegal.  But this is legal:

```<code>IEnumerable<Animal> animals = giraffes;
</code>```

Why is that legal?  Because IEnumerable provides no way at all for a tiger to be inserted. The interface has been marked as safe for covariance, and the C# compiler has verified that it is safe, so this conversion is allowed.

I've written lots of SO answers and blog posts and articles on covariance and contravariance, so do some searches if you want to learn more about this feature and why we designed it as we did.

You could make your example legal by (1) make MainViewModel into an interface and mark it IMainViewModel<out A, out B, out C>, and then (2) ensure that no method of the interface takes an A, B or C as a parameter, no property of type A, B or C has a setter, and so on. That is, every usage of A, B and C is an output position, not an input position. That's how the compiler knows that it is safe for covariance.

I also hope I did not make any typos in the question

It's "covariance", not "covariants". "Covariance" is a noun; "covariant" is an adjective.

Title: Achieve (possibly) covariant cast

Body:
I have the following classes:

X : BaseX

XView : BaseView<X>

XDAO : BaseDAO<X>

MainViewModel<TX, TView, TDAO>
where TX : X
where TView : View<X>
where TDAO : DAO<X>

XMainViewModel : MainViewModel<X, XView, XDAO>

I have an instance of XMainViewModel<X, XView, XDAO>. I want to cast this to MainViewModel<BaseX, BaseView<X>, BaseDAO<X>>. Is this possible? It might have covariants involved. I'm not familiar with covariants, and only started using generics not long ago so I'm rather confused here (I also hope I did not make any typos in the question). Any help is appreciated.

Body:
Is this possible?

No. Generic covariance and contravariance are supported only on interfaces and delegates constructed with reference types.

I'm rather confused here

It's a confusing topic. One way to think about it is to always be asking yourself "suppose this were legal; what could go wrong?" You say

I have XMainViewModel<X, XView, XDAO>. I want to cast this to MainViewModel<BaseX, BaseView<X>, BaseDAO<X>>

Let's look at a simpler example. You have a List<Giraffe> and you wish to cast it to List<Animal>.  What can go wrong?

List<Giraffe> giraffes = new List<Giraffe>();
giraffes.Add(new Giraffe());
List<Animal> animals = (List<Animal>)giraffes; // This is illegal. What if it were legal?
animals.Add(new Tiger());
Giraffe g = giraffes[1]; // And we just put a Tiger into a variable of type Giraffe.

That's why this is illegal, and why your example would also be illegal.  But this is legal:

IEnumerable<Animal> animals = giraffes;

Why is that legal?  Because IEnumerable provides no way at all for a tiger to be inserted. The interface has been marked as safe for covariance, and the C# compiler has verified that it is safe, so this conversion is allowed.

I've written lots of SO answers and blog posts and articles on covariance and contravariance, so do some searches if you want to learn more about this feature and why we designed it as we did.

You could make your example legal by (1) make MainViewModel<A, B, C> into an interface and mark it IMainViewModel<out A, out B, out C>, and then (2) ensure that no method of the interface takes an A, B or C as a parameter, no property of type A, B or C has a setter, and so on. That is, every usage of A, B and C is an output position, not an input position. That's how the compiler knows that it is safe for covariance.

I also hope I did not make any typos in the question

It's "covariance", not "covariants". "Covariance" is a noun; "covariant" is an adjective.


问:
Directly access methods from another Class
I want to be able to use a method from another class directly.

```<code>import package.dialog;

public class Class1 {
    public static void main(String[] args) {
        dialog.dialog("This is a dialog");
    }
}

import javax.swing.JOptionPane
public class dialog {
    public static void dialog(String message) {
        JOptionPane.showMessageDialog(null, message);
    }

}
</code>```

This code works excactly as it's supposed to, but as you can see I'm using dialog.dialog(). I was wondering wether there is a way to use just use dialog() directly?

答:
No, this isn't possible. Consider the following situation:

```<code>import package.dialog;

public class Class1 {
    public static void main(String[] args) {
        // Omit the class and call the dialog method "directly"
        dialog("This is a dialog");
    }
}

import javax.swing.JOptionPane
public class dialog {
    public static void dialog(String message) {
        JOptionPane.showMessageDialog(null, message);
    }

}

public class SomeOtherClass {
    public static void dialog(String message) {
        // Perform some action
    }
}
</code>```

How would the compiler know which one you intended to call - the dialog method in the dialog class, or the dialog method in SomeOtherClass?

Programming languages are generally very carefully designed to avoid permitting this kind of ambiguity.

One notorious example of poor design (and the potential difficulty with doing what you suggest) is the diamond problem in C++ and other languages with multiple inheritance, which is an ambiguity that results from something very similar to what you're proposing. In fact, that's one of the major reasons that C# and Java banned multiple inheritance. Point being that this is really not something you'd like languages to have.

Ultimately, that would make code more difficult to read and potentially ambiguous just to save a little typing. Remember that, for readability, it's always better to be as explicit as possible about your intent.

Body:
I want to be able to use a method from another class directly.

import package.dialog;

public class Class1 {
    public static void main(String[] args) {
        dialog.dialog("This is a dialog");
    }
}

import javax.swing.JOptionPane
public class dialog {
    public static void dialog(String message) {
        JOptionPane.showMessageDialog(null, message);
    }

}

This code works excactly as it's supposed to, but as you can see I'm using dialog.dialog(). I was wondering wether there is a way to use just use dialog() directly?

Body:
No, this isn't possible. Consider the following situation:

import package.dialog;

public class Class1 {
    public static void main(String[] args) {
        // Omit the class and call the dialog method "directly"
        dialog("This is a dialog");
    }
}

import javax.swing.JOptionPane
public class dialog {
    public static void dialog(String message) {
        JOptionPane.showMessageDialog(null, message);
    }

}

public class SomeOtherClass {
    public static void dialog(String message) {
        // Perform some action
    }
}

How would the compiler know which one you intended to call - the dialog method in the dialog class, or the dialog method in SomeOtherClass?

Programming languages are generally very carefully designed to avoid permitting this kind of ambiguity.

One notorious example of poor design (and the potential difficulty with doing what you suggest) is the diamond problem in C++ and other languages with multiple inheritance, which is an ambiguity that results from something very similar to what you're proposing. In fact, that's one of the major reasons that C# and Java banned multiple inheritance. Point being that this is really not something you'd like languages to have.

Ultimately, that would make code more difficult to read and potentially ambiguous just to save a little typing. Remember that, for readability, it's always better to be as explicit as possible about your intent.


问:
How to drop columns using Rails migration
What's the syntax for dropping a database table column through a Rails migration?</p>

答:
Generate a migration to remove a column such that if it is migrated (rake db:migrate), it should drop the column. And it should add column back if this migration is rollbacked (rake db:rollback).

The syntax:

remove_column :table_name, :column_name, :type

Removes column, also adds column back if migration is rollbacked.

Example:

```<code>remove_column :users, :last_name, :string
</code>```

Note: If you skip the data_type, the migration will remove the column successfully but if you rollback the migration it will throw an error.

Body:
Generate a migration to remove a column such that if it is migrated (rake db:migrate), it should drop the column. And it should add column back if this migration is rollbacked (rake db:rollback).

The syntax:

remove_column :table_name, :column_name, :type

Removes column, also adds column back if migration is rollbacked.

Example:

remove_column :users, :last_name, :string

Note: If you skip the data_type, the migration will remove the column successfully but if you rollback the migration it will throw an error.


问:
Angular: delegation pattern. The way to optimise handlers inside ngFor
For example: I need to output a list. Each item will have a (click) handler with item object like parameter.

```<code><ul>
    <li *ngFor="let item of myList">
          <button (click)="clickHandler(item)"></button>
    </li>
</ul>
</code>```

This list will be updated dynamically quite often: I will load new items onScroll, or filter the list by search.

For each item Angular adds an event listener!

Question:

It can be a lot of items in the list, so a lot of eventListeners will be connected and disconnected all the time.

Is there a way to apply delegation pattern to have only one eventListener live?

答: You have nothing to worry about here. The new Angular change detection will take care of performance for you, and there shouldn't be an active listener on every item. It's a common pattern, and should not affect performance.</p>

Body:
For example: I need to output a list. Each item will have a (click) handler with item object like parameter.

          <button (click)="clickHandler(item)"></button>

This list will be updated dynamically quite often: I will load new items onScroll, or filter the list by search.

For each item Angular adds an event listener!

Question:

It can be a lot of items in the list, so a lot of eventListeners will be connected and disconnected all the time.

Is there a way to apply delegation pattern to have only one eventListener live?


问:
How to Deal with Null (GridView Container.DataItem)
whats wrong here, why is it complaining about closing the ")" ?

```<code><asp:TemplateField HeaderText="Name" SortExpression="Name">
                    <ItemTemplate>
                        <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>
                    </ItemTemplate>
                    <EditItemTemplate>
                       <asp:dropdownlist id="ddlStudent" runat="server" datasourceid="CountyDataSource"
                            datatextfield="Name" datavaluefield="Id" autopostback="false">
                        </asp:dropdownlist>
                    </EditItemTemplate>
                </asp:TemplateField>

 protected string FixNull(object dataItem, string fieldName)
 {
        if (dataItem != null)
        {
            System.Data.DataRowView cls = (System.Data.DataRowView)dataItem;
            if (!cls.Row.IsNull(fieldName))
                return (cls[fieldName]).ToString();
            else
                return " ";
        }
        else
            return " ";
    }

Compiler Error Message: CS1026: ) expected

Source Error: Line: 133

Line 131:                  <asp:TemplateField HeaderText="Name" SortExpression="Name">
Line 132:                    <ItemTemplate>
Line 133:    <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>
Line 134:                    </ItemTemplate>
Line 135:                    <EditItemTemplate>
</code>```

答:
Maybe try something like this:</p>

```<code> <asp:TemplateField HeaderText="Name" SortExpression="Name">
    <ItemTemplate>
        <%# FixNull(DataBinder.Eval(Container.DataItem, "Name"))%>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:dropdownlist id="ddlStudent" runat="server" datasourceid="CountyDataSource"
            datatextfield="Name" datavaluefield="Id" autopostback="false">
        </asp:dropdownlist>
    </EditItemTemplate>
</asp:TemplateField>

protected string FixNull(string dataItem)
{
    if (!string.IsNullOrEmpty(dataItem))
    {
        return dataItem;
    }
    return " ";
}
</code>```

Body:
whats wrong here, why is it complaining about closing the ")" ?

<asp:TemplateField HeaderText="Name" SortExpression="Name">
                    <ItemTemplate>
                        <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>
                    </ItemTemplate>
                    <EditItemTemplate>
                       <asp:dropdownlist id="ddlStudent" runat="server" datasourceid="CountyDataSource"
                            datatextfield="Name" datavaluefield="Id" autopostback="false">
                        </asp:dropdownlist>
                    </EditItemTemplate>
                </asp:TemplateField>

 protected string FixNull(object dataItem, string fieldName)
 {
        if (dataItem != null)
        {
            System.Data.DataRowView cls = (System.Data.DataRowView)dataItem;
            if (!cls.Row.IsNull(fieldName))
                return (cls[fieldName]).ToString();
            else
                return " ";
        }
        else
            return " ";
    }

Compiler Error Message: CS1026: ) expected

Source Error: Line: 133

Line 131:                  <asp:TemplateField HeaderText="Name" SortExpression="Name">
Line 132:                    <ItemTemplate>
Line 133:    <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>
Line 134:                    </ItemTemplate>
Line 135:                    <EditItemTemplate>

Body:
Maybe try something like this:

 <asp:TemplateField HeaderText="Name" SortExpression="Name">
    <ItemTemplate>
        <%# FixNull(DataBinder.Eval(Container.DataItem, "Name"))%>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:dropdownlist id="ddlStudent" runat="server" datasourceid="CountyDataSource"
            datatextfield="Name" datavaluefield="Id" autopostback="false">
        </asp:dropdownlist>
    </EditItemTemplate>
</asp:TemplateField>

protected string FixNull(string dataItem)
{
    if (!string.IsNullOrEmpty(dataItem))
    {
        return dataItem;
    }
    return "&nbsp;";
}


问:
Check if a value from a list of values in a python dictionary exists in another dictionary
I writing a python script to verify report templates. There is a master template, which contains all possible reports with all their possible fields. Then there is a template csv which contains some of those reports. For simplicity lets say then look like this;

Template csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, age, dob, id
 AccountReport, f1, f2, f3, f4, f5
 TransactionReport, f1, f2, f3, f4, f5

Master csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, street, age, id
 TransactionReport, f1, f2, f3, f4, f5

So in this example the AccountReport doesn't even exist in the Master, the PersonReport contains a field dob which isn't valid because it isn't in the Master. The only valid report is TransactionReport.

So I idea is to read these csvs in as dictionaries, with the OutputName as the key and the field names as the values.

```<code> import pandas as pd
 masterDf = pd.read_csv('master.csv')
 master = masterDf.set_index('OutputName').T.to_dict('list')

 templateDf = pd.read_csv('template.csv')
 template = templateDf.set_index('OutputName').T.to_dict('list')
</code>```

The dictionaries looks like;

template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

Now the I want to first match on the keys, to find out which keys don't exist in the master dict. After that when finding keys that do match, I wish to check if the values in the dictionary are valid, by checking that they exist in the master dict's values.

So I try :

```<code>errorCount = 0

for key, value in template.items():
    if key  not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
    if key in master:
        for fields in template.values():
            for field in fields:
                for cols in master.values():
                    if field not in cols:
                        print("{} is an invalid field in {} report".format(field, key))
                        errorCount += 1
</code>```

However the output I get is wrong. I get :

```<code>name is an invalid field in  PersonReport report
 surname is an invalid field in  PersonReport report
 age is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 id is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5 is an invalid field in  PersonReport report
 AccountReport is an invalid report
 name is an invalid field in  TransactionReport report
 surname is an invalid field in  TransactionReport report
 age is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 id is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5 is an invalid field in  TransactionReport report
</code>```

My expected output would :

```<code>AccountReport is an invalid report
dob is an invalid field in PersonReport report
</code>```

Any help is appreciated
Thanks
p.s I'm using python 3.6

答:
You can try this:

```<code>template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}
master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}
invalid_names = ["{} in dict".format(i) if i in master else "{} not in dict".format(i) for i in template]
invalid_values = filter(lambda x:x, [["{} is an invalid value".format(c) for c in b if c not in master[a]] for a, b in template.items() if a in master])
print(invalid_names)
print(invalid_values)
</code>```

Output:

```<code>[' TransactionReport in dict', ' PersonReport in dict', ' AccountReport not in dict']
[[' dob is an invalid value']]
</code>```

Body:
I writing a python script to verify report templates. There is a master template, which contains all possible reports with all their possible fields. Then there is a template csv which contains some of those reports. For simplicity lets say then look like this;

Template csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, age, dob, id
 AccountReport, f1, f2, f3, f4, f5
 TransactionReport, f1, f2, f3, f4, f5

Master csv:

OutputName, col1, col2, col3, col4, col5
 PersonReport, name, surname, street, age, id
 TransactionReport, f1, f2, f3, f4, f5

So in this example the AccountReport doesn't even exist in the Master, the PersonReport contains a field dob which isn't valid because it isn't in the Master. The only valid report is TransactionReport.

So I idea is to read these csvs in as dictionaries, with the OutputName as the key and the field names as the values.

 import pandas as pd
 masterDf = pd.read_csv('master.csv')
 master = masterDf.set_index('OutputName').T.to_dict('list')

 templateDf = pd.read_csv('template.csv')
 template = templateDf.set_index('OutputName').T.to_dict('list')

The dictionaries looks like;

template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

Now the I want to first match on the keys, to find out which keys don't exist in the master dict. After that when finding keys that do match, I wish to check if the values in the dictionary are valid, by checking that they exist in the master dict's values.

So I try :

errorCount = 0

for key, value in template.items():
    if key  not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
    if key in master:
        for fields in template.values():
            for field in fields:
                for cols in master.values():
                    if field not in cols:
                        print("{} is an invalid field in {} report".format(field, key))
                        errorCount += 1

However the output I get is wrong. I get :

name is an invalid field in  PersonReport report
 surname is an invalid field in  PersonReport report
 age is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 id is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5 is an invalid field in  PersonReport report
 AccountReport is an invalid report
 name is an invalid field in  TransactionReport report
 surname is an invalid field in  TransactionReport report
 age is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 id is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5 is an invalid field in  TransactionReport report

My expected output would :

AccountReport is an invalid report
dob is an invalid field in PersonReport report

Any help is appreciated
Thanks
p.s I'm using python 3.6

Body:
You can try this:

template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}
master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}
invalid_names = ["{} in dict".format(i) if i in master else "{} not in dict".format(i) for i in template]
invalid_values = filter(lambda x:x, [["{} is an invalid value".format(c) for c in b if c not in master[a]] for a, b in template.items() if a in master])
print(invalid_names)
print(invalid_values)

Output:

[' TransactionReport in dict', ' PersonReport in dict', ' AccountReport not in dict']
[[' dob is an invalid value']]


问:
CSS hover transition not chaning color of an icon on unhover on Firefox
I'm chaning background color and text color on hover in menu - simply case. In all browsers everything works well, but in Firefox (normal and developer edition (version 58.0b1)) when I'm hovering the navbar element few times the icon after unhover does not change the color back and it looks like this:

and it should look like this:

.

HTML element:

```<code><a href="#">
  <i class="fa fa-calendar-check-o" aria-hidden="true"></i>  Plan dnia
</a>
</code>```

CSS before:

```<code>.navbar-default .navbar-nav>li>a {
  color: #314461;
  border-radius: 15px;
}
</code>```

CSS after:

```<code>.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
    background-color: #4D87EA;
    color: white;
    transition: 0.3s;
}
</code>```

I would like to emphasise that when I remove the transition from the above css, everything works well.

答:
Try to add your apply also in i element like so:</p>

```<code>.navbar-default .navbar-nav > li > a:hover > i,
.navbar-default .navbar-nav > li > a:focus > i {
    background-color: #4D87EA;
    color: white;
    transition: 0.3s;
}
</code>```

Body:
I'm chaning background color and text color on hover in menu - simply case. In all browsers everything works well, but in Firefox (normal and developer edition (version 58.0b1)) when I'm hovering the navbar element few times the icon after unhover does not change the color back and it looks like this:

and it should look like this:

.

HTML element:

    Plan dnia

CSS before:

.navbar-default .navbar-nav>li>a {
  color: #314461;
  border-radius: 15px;
}

CSS after:

.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
    background-color: #4D87EA;
    color: white;
    transition: 0.3s;
}

I would like to emphasise that when I remove the transition from the above css, everything works well.

Body:
Try to add your apply also in i element like so:

.navbar-default .navbar-nav > li > a:hover > i,
.navbar-default .navbar-nav > li > a:focus > i {
    background-color: #4D87EA;
    color: white;
    transition: 0.3s;
}


问:
How to go back to app from play store
I'm testing an interaction when in app, user can swipe up to go to Google Play Store. But when that happens, Espresso can not execute rest of the test flow due to RuntimeException: Could not find RESUMED activity on main thread.

On the UI there's left arrow (<--) so user can tap on it to go back to previous app. How do I tell Espresso to do similar thing? Or force the app being tested to come to the foreground again?

Below is the RuntimeException for reference:

```<code>java.lang.RuntimeException: Could not find RESUMED activity on main thread
at com.snapchat.android.crema.Screenshotter.screenshotCurrentActivity(Screenshotter.java:49)
at com.snapchat.android.crema.Screenshotter$1.run(Screenshotter.java:33)
at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:2092)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

INSTRUMENTATION_RESULT: shortMsg=Process crashed.
INSTRUMENTATION_CODE: 0
</code>```

答:
Espresso cannot be used for a cross-app testing. Espresso is bound to your application process.

But there are ways of testing this interaction:

Catch the intent to go the play store with Espresso-Intents and return a stub response. This way, your test will be canned and will never leave your application. This is a recommended way of doing it as it tests this scenario in isolation without interacting with the external dependency that is out of your control.

Use UiAutomator that can act outside of the context of your application and click things there. Might be useful if you are interested in end-end testing, but with the tradeoff of being more fragile. You can find sample usage in this question: How to regain Access on a Activity after sending it to background

Title: How to go back to app from play store

Body:
I'm testing an interaction when in app, user can swipe up to go to Google Play Store. But when that happens, Espresso can not execute rest of the test flow due to RuntimeException: Could not find RESUMED activity on main thread.

On the UI there's left arrow (<--) so user can tap on it to go back to previous app. How do I tell Espresso to do similar thing? Or force the app being tested to come to the foreground again?

Below is the RuntimeException for reference:

java.lang.RuntimeException: Could not find RESUMED activity on main thread
at com.snapchat.android.crema.Screenshotter.screenshotCurrentActivity(Screenshotter.java:49)
at com.snapchat.android.crema.Screenshotter$1.run(Screenshotter.java:33)
at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:2092)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

INSTRUMENTATION_RESULT: shortMsg=Process crashed.
INSTRUMENTATION_CODE: 0


问:
jquery hyperlink in firefox
I have the code below which checks if a user is logged in, if they are it echo's out a javascript function hideLogin() otherwise it will echo the function showLogin() . This works fine on every browser I have tested in, but firefox. The link is not clickable, where as it is in every other browser I tested in.

```<code><div id="account">
<script type="text/javascript">
<?php
if(loggedIn())
{
    echo "hideLogin();";
}
else
{
    echo "showLogin();";
}
?>
</script>

</div>
function hideLogin()
{
        $('#accountAccess').html('Welcome <?php echo $_SESSION["firstName"]; ?> |  <a href="logout.php">Logout</a>');
}

function showLogin()
{
    $('#accountAccess').html('Welcome Guest | <a href="javascript:void(0);" id="login_link">Login</a>');
}
</code>```

Any ideas? Thanks.

答: When links are not clickable, most probably something is obstructing it. To verify, right click and choose "inspect element" from the context menu. If it does not show you the link tag, it will show the obstructing "div" or "ul" or whatever.</p>

Title: jquery hyperlink in firefox

Body:
I have the code below which checks if a user is logged in, if they are it echo's out a javascript function hideLogin() otherwise it will echo the function showLogin() . This works fine on every browser I have tested in, but firefox. The link is not clickable, where as it is in every other browser I tested in.

function hideLogin()
{
        $('#accountAccess').html('Welcome <?php echo $_SESSION["firstName"]; ?> |  Logout');
}

function showLogin()
{
    $('#accountAccess').html('Welcome Guest | Login');
}

Any ideas? Thanks.


问:
Android Leanback PageRow Animation
I am building a Android TV application using the Leanback Support library using PageRows.

I am following pretty much what the leanback-showcase same app is doing here, but I am wondering if it is possible to animate the fragments exiting and entering when the row changes?

It is pretty jolting when the fragments are changed for each row.

答: As stated in the official documentation, android.support.v17.leanback has R.animator class. Then you may use the lb_playback_rows_fade_in and lb_playback_rows_fade_out methods.

Title: Android Leanback PageRow Animation


问:
How to split app and vendor code with Webpack
I'm starting a new project with react
So I have this webpack.config.js file that's supposed to hundle 2 chunks , one for the app code and one for vendor based on this exemple from webpack documentation

webpack.config.js

```<code>const webpack = require('webpack');
module.exports = {
    entry: {
        app: './src/App.jsx',
        vendor: ['react', 'react-dom', 'whatwg-fetch']
    },
    output: {
        path: __dirname + './static/',
        filename: 'app.bundle.js'
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            filename: 'vendor.bundle.js'
        })
    ],
    module: {
        loaders: [{
            test: /.jsx$/,
            loader: 'babel-loader',
            query: {
                presets: ['react', 'es2015']
            }
        }, ]
    }
};
</code>```

When I run webpack -p I can see that my two assets are supposed to be generated but there is nothing in the output directory.

Webpack output

```<code>           Asset    Size  Chunks             Chunk Names
   app.bundle.js    6 kB       0  [emitted]  app
vendor.bundle.js  108 kB       1  [emitted]  vendor
   [6] ./src/App.jsx 3.37 kB {0} [built]
   [7] ./src/IssueAdd.jsx 3.57 kB {0} [built]
   [9] ./src/IssueList.jsx 5.46 kB {0} [built]
  [10] ./src/IssueFilter.jsx 2.52 kB {0} [built]
  [20] multi react react-dom whatwg-fetch 52 bytes {1} [built]
    + 16 hidden modules
</code>```

Webpack version is 3.8.1 with windows 7 dev environment.
Am I missing something here?

答:
If you want two separate files to be emitted in output folder Firstly you have to make sure those files have new name every-time files are updated and one of the ways is to make use of caching [chunkhash] as suggested in webpack 3.8.1 Documentation

Include path on top of the file , so your output should be something like (You can change it accordingly):

```<code> var path = require('path');

 output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].[chunkhash].js'
  },
</code>```

And inside your plugin you can just give name

```<code>plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor'
    })
]
</code>```

You can read more about Webpack 3.8.1 output-filename

Body:
I'm starting a new project with react
So I have this webpack.config.js file that's supposed to hundle 2 chunks , one for the app code and one for vendor based on this exemple from webpack documentation

webpack.config.js

const webpack = require('webpack');
module.exports = {
    entry: {
        app: './src/App.jsx',
        vendor: ['react', 'react-dom', 'whatwg-fetch']
    },
    output: {
        path: __dirname + './static/',
        filename: 'app.bundle.js'
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            filename: 'vendor.bundle.js'
        })
    ],
    module: {
        loaders: [{
            test: /.jsx$/,
            loader: 'babel-loader',
            query: {
                presets: ['react', 'es2015']
            }
        }, ]
    }
};

When I run webpack -p I can see that my two assets are supposed to be generated but there is nothing in the output directory.

Webpack output

           Asset    Size  Chunks             Chunk Names
   app.bundle.js    6 kB       0  [emitted]  app
vendor.bundle.js  108 kB       1  [emitted]  vendor
   [6] ./src/App.jsx 3.37 kB {0} [built]
   [7] ./src/IssueAdd.jsx 3.57 kB {0} [built]
   [9] ./src/IssueList.jsx 5.46 kB {0} [built]
  [10] ./src/IssueFilter.jsx 2.52 kB {0} [built]
  [20] multi react react-dom whatwg-fetch 52 bytes {1} [built]
    + 16 hidden modules

Webpack version is 3.8.1 with windows 7 dev environment.
Am I missing something here?

Body:
If you want two separate files to be emitted in output folder Firstly you have to make sure those files have new name every-time files are updated and one of the ways is to make use of caching [chunkhash] as suggested in webpack 3.8.1 Documentation

Include path on top of the file , so your output should be something like (You can change it accordingly):

 var path = require('path');

 output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].[chunkhash].js'
  },

And inside your plugin you can just give name

plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor'
    })
]

You can read more about Webpack 3.8.1 output-filename


问:
"initializer list "vs. "default argument value" difference when setting a member value
I've been experiencing a linking issue on a project, and I've found a workaround I can't really explain.

I had this kind of class and I was getting an unresolved external symbol on getType<>(), which was correctly imported from another lib.

```<code>MyClass( CustomType& iType = getType<OtherClass>() )
{...}
</code>```

The workaround found is a little less reusable, but still satisfies conviniently my use case for now. Same linker properties, etc.

```<code>MyClass( )
: mType( getType<OtherClass>() )
{...}
</code>```

What difference does it make to set a member variable with a default argument value or through the initializer list?

Is there a difference of scope? e.g. could it be because otherClass and getType<>() exist in different namespaces?

EDIT:
Declaration of getType:

```<code>template<typename type>
CustomType* getType() {
  static CustomType* oType = getType(typeid(type));
  return oType;
}
</code>```

Linker error:

```<code>MyClass.obj : error LNK2019: unresolved external symbol "public: class CustomType * __thiscall Metadata::getType<class OtherClass>(void)" ...
</code>```

答:
Default arguments are only "exectuted" at call site: so for

```<code>MyClass(CustomType& iType = getType<OtherClass>())
</code>```

You only need declaration of getType<OtherClass>().

Instantiation would be done only when you use something like:

```<code>MyClass myClass{}; // MyClass myClass{getType<OtherClass>()}
</code>```

I assume that definition of getType<OtherClass> is inaccessible.
(you might have implementation of template inside cpp file)

For

```<code>MyClass() : mType(getType<OtherClass>()) {}
</code>```

getType<OtherClass> is instantiated.

Body:
I've been experiencing a linking issue on a project, and I've found a workaround I can't really explain.

I had this kind of class and I was getting an unresolved external symbol on getType<>(), which was correctly imported from another lib.

MyClass( CustomType& iType = getType<OtherClass>() )
{...}

The workaround found is a little less reusable, but still satisfies conviniently my use case for now. Same linker properties, etc.

MyClass( )
: mType( getType<OtherClass>() )
{...}

What difference does it make to set a member variable with a default argument value or through the initializer list?

Is there a difference of scope? e.g. could it be because otherClass and getType<>() exist in different namespaces?

EDIT:
Declaration of getType:

template<typename type>
CustomType* getType() {
  static CustomType* oType = getType(typeid(type));
  return oType;
}

Linker error:

MyClass.obj : error LNK2019: unresolved external symbol "public: class CustomType * __thiscall Metadata::getType<class OtherClass>(void)" ...

Body:
Default arguments are only "exectuted" at call site: so for

MyClass(CustomType& iType = getType<OtherClass>())

You only need declaration of getType<OtherClass>().

Instantiation would be done only when you use something like:

MyClass myClass{}; // MyClass myClass{getType<OtherClass>()}

I assume that definition of getType<OtherClass> is inaccessible.
(you might have implementation of template inside cpp file)

For

MyClass() : mType(getType<OtherClass>()) {}

getType<OtherClass> is instantiated.