问:
JSON Get List of attributes values
I have the following JSON, and I want to take a list of IDs with its values

For example in LINQ something like this: result.Select(x=>x.id)

I tried this:

```<code> var inner = outer["pictures"].Value<JArray>().ToList();
</code>```

I have a list there but with all attributes but I am not able to select just IDs since it is an anonymous list.

```<code>    outer
{{
  "id": "669654603",
  "pictures": [
    {
      "id": "659745-MLA25600661898_052017",
      "url": "http://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "size": "500x365",
      "max_size": "625x457",
      "quality": ""
    },
    {
      "id": "908422-MLA25658267858_062017",
      "url": "http://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "size": "47x47",
      "max_size": "47x47",
      "quality": ""
    },
    {
      "id": "794138-MLA25658267889_062017",
      "url": "http://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "size": "40x40",
      "max_size": "40x40",
      "quality": ""
    }
  ]

}}
</code>```

答:
In order to be valid your json should not contain double curly brackets:

```<code>{
  "id": "669654603",
  "pictures": [ ... ]
}
</code>```

You can parse it without additional classes:

```<code>var ids = JObject.Parse(json)["pictures"].Select(p => (string)p["id"]);
</code>```

Output:

```<code>[
  "659745-MLA25600661898_052017",
  "908422-MLA25658267858_062017",
  "794138-MLA25658267889_062017"
]
</code>```

Or you can create several classes to hold your json data:

```<code>public class Container
{
    public List<Picture> Pictures { get; set; }
}

public class Picture
{
    public string Id { get; set; }
    // you can add other properties here
}
</code>```

And use strongly-typed parsing:

```<code>var ids = JsonConvert.DeserializeObject<Container>(json).Pictures.Select(p => p.Id);
</code>```

Title: JSON Get List of attributes values

Body:
I have the following JSON, and I want to take a list of IDs with its values

For example in LINQ something like this: result.Select(x=>x.id)

I tried this:

 var inner = outer["pictures"].Value<JArray>().ToList();

I have a list there but with all attributes but I am not able to select just IDs since it is an anonymous list.

    outer
{{
  "id": "669654603",
  "pictures": [
    {
      "id": "659745-MLA25600661898_052017",
      "url": "http://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
      "size": "500x365",
      "max_size": "625x457",
      "quality": ""
    },
    {
      "id": "908422-MLA25658267858_062017",
      "url": "http://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
      "size": "47x47",
      "max_size": "47x47",
      "quality": ""
    },
    {
      "id": "794138-MLA25658267889_062017",
      "url": "http://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "secure_url": "https://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
      "size": "40x40",
      "max_size": "40x40",
      "quality": ""
    }
  ]

}}

Body:
In order to be valid your json should not contain double curly brackets:

{
  "id": "669654603",
  "pictures": [ ... ]
}

You can parse it without additional classes:

var ids = JObject.Parse(json)["pictures"].Select(p => (string)p["id"]);

Output:

[
  "659745-MLA25600661898_052017",
  "908422-MLA25658267858_062017",
  "794138-MLA25658267889_062017"
]

Or you can create several classes to hold your json data:

public class Container
{
    public List<Picture> Pictures { get; set; }
}

public class Picture
{
    public string Id { get; set; }
    // you can add other properties here
}

And use strongly-typed parsing:

var ids = JsonConvert.DeserializeObject<Container>(json).Pictures.Select(p => p.Id);


来源: stackexchange

问:
How to make requestbody controller works?
So actually everything is working well, except the fact that i can't get access to "inscrit" which is supposed to be the one which is sent to have the information user

This is my function in javascript and it does go into success for ajax.

```<code>function fbLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    var inscrit = {
                        "prenom": response.first_name,
                        "nom": response.last_name,
                        "email": response.email
                    }
                    $.ajax({
                        method: 'post',
                        url: '/hello/facebookconnection',
                        contentType : 'application/json; charset=utf-8',
                        data: JSON.stringify(inscrit),
                        datatype: "json",
                        success: function() {
                        window.alert('User data sent');}
                        ,
                        error: function(){
                            window.alert('Error in sending ajax data');}
                    });
                } else {
                    document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
                }
            }, {scope: 'email'});
        }
</code>```

And this is my java controller (whatever i do, the "inscrit.getEmail()" is always null)

```<code>@RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
@ResponseBody public void createUser(@RequestBody inscrit inscrit, ModelMap model) throws Exception {
    //System.out.println(inscrit.getNom());
    //System.out.println(inscrit.getPrenom());
    System.out.println(inscrit.getEmail());
    try {
        user.adduser(inscrit);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

This is my inscrit class with all the getter and setter correctly set (i know that there's no problem with it)

```<code>@Entity
@Table(name="inscrit")
public class inscrit implements Serializable {
  @Id
  @Column(name="email")
  private String email;

  @Column(name="nom")
  private String nom;

  @Column(name="prenom")
  private String prenom;
}
</code>```

So i would like to know if someone could help me understand why it's not working in my controller (how to do so the data is sent properly from the ajax to the controller) :(
Thx !

EDIT : i did write the answer of that question below. The problem was the fact that response.first_name was really blank... and had to pass through the function userdata() which had the real informations. So that means i don't have any real error in my code, all the informations between the controller and my jsp page works correctly. Be free to use it as an example of how this works

答:
I'll answer to my own question since i found the answer, So this is for people who tries to have a facebook api and want to get informations of the profil to put into database.
My error was the fact that i thought response in login was the same asthe UserData(), which is not the case... So that's how i was supposed to do it. </p>

```<code>        function fbLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    // Get and display the user profile data
                    getFbUserData();
                } else {
                    document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
                }
            }, {scope: 'email'});
        }

        // Fetch the user profile data from facebook
        function getFbUserData(){
            FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
                function (response) {
                    /*document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
                    document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
                    document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
                    document.getElementById('userData').innerHTML = '<div class="fbprofile"><p><b>FB ID:</b> '+response.id+'</p><p><b>Name:</b> '+response.first_name+' '+response.last_name+'</p><p><b>Email:</b> '+response.email+'</p><p><b>Gender:</b> '+response.gender+'</p><p><b>Locale:</b> '+response.locale+'</p></div><p><b>Picture:</b> <img src="'+response.picture.data.url+'"/></p>';*/
                    var inscrit = {
                        "prenom": response.first_name,
                        "nom": response.last_name,
                        "password": "1234",
                        "status": 0,
                        "email": response.email
                    }
                    $.ajax({
                        method: 'post',
                        url: '/hello/facebookconnection',
                        contentType : 'application/json; charset=utf-8',
                        data: JSON.stringify(inscrit),
                        datatype: "json",
                        success: function() {
                            document.location.href = "accueilmember";
                        },
                        error: function(){
                            window.alert('Error in sending ajax data');}
                    });
                });
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So actually everything is working well, except the fact that i can't get access to "inscrit" which is supposed to be the one which is sent to have the information user

This is my function in javascript and it does go into success for ajax.

function fbLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    var inscrit = {
                        "prenom": response.first_name,
                        "nom": response.last_name,
                        "email": response.email
                    }
                    $.ajax({
                        method: 'post',
                        url: '/hello/facebookconnection',
                        contentType : 'application/json; charset=utf-8',
                        data: JSON.stringify(inscrit),
                        datatype: "json",
                        success: function() {
                        window.alert('User data sent');}
                        ,
                        error: function(){
                            window.alert('Error in sending ajax data');}
                    });
                } else {
                    document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
                }
            }, {scope: 'email'});
        }

And this is my java controller (whatever i do, the "inscrit.getEmail()" is always null)

@RequestMapping(value = "/facebookconnection", method = RequestMethod.POST)
@ResponseBody public void createUser(@RequestBody inscrit inscrit, ModelMap model) throws Exception {
    //System.out.println(inscrit.getNom());
    //System.out.println(inscrit.getPrenom());
    System.out.println(inscrit.getEmail());
    try {
        user.adduser(inscrit);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This is my inscrit class with all the getter and setter correctly set (i know that there's no problem with it)

@Entity
@Table(name="inscrit")
public class inscrit implements Serializable {
  @Id
  @Column(name="email")
  private String email;

  @Column(name="nom")
  private String nom;

  @Column(name="prenom")
  private String prenom;
}

So i would like to know if someone could help me understand why it's not working in my controller (how to do so the data is sent properly from the ajax to the controller) :(
Thx !

EDIT : i did write the answer of that question below. The problem was the fact that response.first_name was really blank... and had to pass through the function userdata() which had the real informations. So that means i don't have any real error in my code, all the informations between the controller and my jsp page works correctly. Be free to use it as an example of how this works

Body:
I'll answer to my own question since i found the answer, So this is for people who tries to have a facebook api and want to get informations of the profil to put into database.
My error was the fact that i thought response in login was the same asthe UserData(), which is not the case... So that's how i was supposed to do it.

        function fbLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    // Get and display the user profile data
                    getFbUserData();
                } else {
                    document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
                }
            }, {scope: 'email'});
        }

        // Fetch the user profile data from facebook
        function getFbUserData(){
            FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
                function (response) {
                    /*document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
                    document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
                    document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
                    document.getElementById('userData').innerHTML = '<div class="fbprofile"><p><b>FB ID:</b> '+response.id+'</p><p><b>Name:</b> '+response.first_name+' '+response.last_name+'</p><p><b>Email:</b> '+response.email+'</p><p><b>Gender:</b> '+response.gender+'</p><p><b>Locale:</b> '+response.locale+'</p></div><p><b>Picture:</b> <img src="'+response.picture.data.url+'"/></p>';*/
                    var inscrit = {
                        "prenom": response.first_name,
                        "nom": response.last_name,
                        "password": "1234",
                        "status": 0,
                        "email": response.email
                    }
                    $.ajax({
                        method: 'post',
                        url: '/hello/facebookconnection',
                        contentType : 'application/json; charset=utf-8',
                        data: JSON.stringify(inscrit),
                        datatype: "json",
                        success: function() {
                            document.location.href = "accueilmember";
                        },
                        error: function(){
                            window.alert('Error in sending ajax data');}
                    });
                });
        }


问:
What is the difference between shallow copy, deepcopy and normal assignment operation?
```<code>import copy

a = "deepak"
b = 1, 2, 3, 4
c = [1, 2, 3, 4]
d = {1: 10, 2: 20, 3: 30}

a1 = copy.copy(a)
b1 = copy.copy(b)
c1 = copy.copy(c)
d1 = copy.copy(d)

print("immutable - id(a)==id(a1)", id(a) == id(a1))
print("immutable - id(b)==id(b1)", id(b) == id(b1))
print("mutable - id(c)==id(c1)", id(c) == id(c1))
print("mutable - id(d)==id(d1)", id(d) == id(d1))
</code>```

I get the following results:

```<code>immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False
</code>```

If I perform deepcopy:

```<code>a1 = copy.deepcopy(a)
b1 = copy.deepcopy(b)
c1 = copy.deepcopy(c)
d1 = copy.deepcopy(d)
</code>```

results are the same:

```<code>immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False
</code>```

If I work on assignment operations:

```<code>a1 = a
b1 = b
c1 = c
d1 = d
</code>```

then results are:

```<code>immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) True
mutable - id(d)==id(d1) True
</code>```

Can somebody explain what exactly makes a difference between the copies? Is it something related to mutable & immutable objects? If so, can you please explain it to me?

答:
Let's see in a graphical example how the following code is executed:

```<code>import copy

class Foo(object):
    def __init__(self):
        pass

a = [Foo(), Foo()]
shallow = copy.copy(a)
deep = copy.deepcopy(a)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
import copy

a = "deepak"
b = 1, 2, 3, 4
c = [1, 2, 3, 4]
d = {1: 10, 2: 20, 3: 30}

a1 = copy.copy(a)
b1 = copy.copy(b)
c1 = copy.copy(c)
d1 = copy.copy(d)

print("immutable - id(a)==id(a1)", id(a) == id(a1))
print("immutable - id(b)==id(b1)", id(b) == id(b1))
print("mutable - id(c)==id(c1)", id(c) == id(c1))
print("mutable - id(d)==id(d1)", id(d) == id(d1))

I get the following results:

immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False

If I perform deepcopy:

a1 = copy.deepcopy(a)
b1 = copy.deepcopy(b)
c1 = copy.deepcopy(c)
d1 = copy.deepcopy(d)

results are the same:

immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False

If I work on assignment operations:

a1 = a
b1 = b
c1 = c
d1 = d

then results are:

immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) True
mutable - id(d)==id(d1) True

Can somebody explain what exactly makes a difference between the copies? Is it something related to mutable & immutable objects? If so, can you please explain it to me?

Body:
Let's see in a graphical example how the following code is executed:

import copy

class Foo(object):
    def __init__(self):
        pass

a = [Foo(), Foo()]
shallow = copy.copy(a)
deep = copy.deepcopy(a)


问:
Restrict variadic function template to only accept variations of one variadic class template's nested variadic class template?
I have a variadic class template that has a nested variadic class template.  The outer class template has a function template that accepts any number of arguments and will return an object of type inner.  My problem is creating a completely separate function that will accept any number of any variation of those inner types (and only the inner types), regardless of the variant of the outer type, while still ensuring that accepted types to the function are nested members of only that outer class template.  Not sure if I explained that adequately...  Here's essentially what I'm working with:

```<code>template<typename... ArgsOuter> class Outer {
    typedef Outer<ArgsOuter...> outer_t;

    template<typename... ArgsInner> class Inner {
        //static const outer_t* outer;
        typedef outer_t outer;

        Inner(const ArgsInner&... args_inner) {
            //do stuff
        }
    };

    /*
      What's passed in here will be related to and will be a subset of
      the types used to define the Outer class, but I'm not really
      concerned about checking what's being passed in right now.
    */
    template<typename... ArgsFunc>
    make_inner(ArgsFunc... args_func) {
        return Inner<ArgsFunc...> (args_func...);
    }
};

struct ThingA : Outer<int, int, float> {
};

struct ThingB : Outer<int, string, int> {
};

struct ThingC : Outer<string, string, int, int> {
};

//struct ThingN : Outer<random types...> {}

//...meanwhile, over at main...

ThingA tA;
ThingB tB;
ThingC tC;

auto tA_inner = tA.make_inner(1, 1.1);
auto tB_inner = tB.make_inner(2, "foo");
auto tC_inner = tC.make_inner("bar", 2, "foobar");

//mystery_func() is the function I'm not sure how to define.
auto meatloaf = mystery_func(tA_inner, tB_inner, tC_inner);
</code>```

Anyone have an SFINAE or variadic function template (or other) solution for this?

答:
Well, I didn't set out to answer my own question, but I think I've beat my head against the wall just enough the past few days to figure this one out... and certainly learned some new stuff along the way (no complaints there).  It's a bit of an ugly duckling (SFINAE + type traits metafunctions + variadic function templates), but I've run a few simple test and it seems to work as expected.

```<code>//Use SFINAE to limit the types accepted
template<typename A, typename Result>
struct require_1_type { };

//Limit to Outer class
template<typename... ArgsA, typename Result>
struct require_1_type<Outer<ArgsA...>, Result> {
    typedef Result type;
};

//Zero argument, base case for variadic function template.
void mystery_func() {}

//Recursive portion of variadic function template.
template<template<typename...> class First, typename... ArgsA, typename... Others>
typename std::enable_if<
    std::is_same<
        First<ArgsA...>
        , typename require_1_type<
            typename First<ArgsA...>::outer_t
            , typename First<ArgsA...>::outer_t::template Inner<ArgsA...>
        >::type
    >::value
    , some_lib::list<First<ArgsA...>, Others...>
>::type
mystery_func (First<ArgsA...> first, Others... others) {
    mystery_func(others...);
    return some_lib::make_list(first, others...);
}
</code>```

My goal was to limit the types being passed in, to any variations of Inner for any variations of Outer.  I think this does what I was looking for, at least it seems that way.

My understanding of how this all works is as follows, please correct as appropriate:

A series of Inner objects gets passed in.  Each Inner object has a typedef referring to its' Outer type.  We strip off one Inner object from the parameter pack, and check the typedef referring to its' Outer type to make sure it matches the expected Outer type.  If it matches, then we take the parameter pack used on the first Inner object that was passed in, and pass the pack along to an Inner template that we reference through the Outer typedef referred to by the first Inner.  Then we check those two Inner's against each other to make sure they're the same.  If they are, then that particular function template instantiation is enabled.

The variadic function template itself simply calls itself recursively so that all objects in the parameter pack have those same checks run on them, until we run out of arguments, which calls the blank version of the function.  Finally, each recursion makes a call to (in this case) a function that puts the objects together in a list.

One thing I'm not sure of is if the compiler is optimizing out all those calls to make_list that are returning into nothingness, except the last one, which is done by the first invocation of mystery_func(), and the only one that has a purposeful return value.

Anyway, improvements, comments, and simplifications are most welcome.

ContentLicense: CC BY-SA 2.5

Body:
I have a variadic class template that has a nested variadic class template.  The outer class template has a function template that accepts any number of arguments and will return an object of type inner.  My problem is creating a completely separate function that will accept any number of any variation of those inner types (and only the inner types), regardless of the variant of the outer type, while still ensuring that accepted types to the function are nested members of only that outer class template.  Not sure if I explained that adequately...  Here's essentially what I'm working with:

template<typename... ArgsOuter> class Outer {
    typedef Outer<ArgsOuter...> outer_t;

    template<typename... ArgsInner> class Inner {
        //static const outer_t* outer;
        typedef outer_t outer;

        Inner(const ArgsInner&... args_inner) {
            //do stuff
        }
    };

    /*
      What's passed in here will be related to and will be a subset of
      the types used to define the Outer class, but I'm not really
      concerned about checking what's being passed in right now.
    */
    template<typename... ArgsFunc>
    make_inner(ArgsFunc... args_func) {
        return Inner<ArgsFunc...> (args_func...);
    }
};

struct ThingA : Outer<int, int, float> {
};

struct ThingB : Outer<int, string, int> {
};

struct ThingC : Outer<string, string, int, int> {
};

//struct ThingN : Outer<random types...> {}

//...meanwhile, over at main...

ThingA tA;
ThingB tB;
ThingC tC;

auto tA_inner = tA.make_inner(1, 1.1);
auto tB_inner = tB.make_inner(2, "foo");
auto tC_inner = tC.make_inner("bar", 2, "foobar");

//mystery_func() is the function I'm not sure how to define.
auto meatloaf = mystery_func(tA_inner, tB_inner, tC_inner);

Anyone have an SFINAE or variadic function template (or other) solution for this?

Body:
Well, I didn't set out to answer my own question, but I think I've beat my head against the wall just enough the past few days to figure this one out... and certainly learned some new stuff along the way (no complaints there).  It's a bit of an ugly duckling (SFINAE + type traits metafunctions + variadic function templates), but I've run a few simple test and it seems to work as expected.

//Use SFINAE to limit the types accepted
template<typename A, typename Result>
struct require_1_type { };

//Limit to Outer class
template<typename... ArgsA, typename Result>
struct require_1_type<Outer<ArgsA...>, Result> {
    typedef Result type;
};

//Zero argument, base case for variadic function template.
void mystery_func() {}

//Recursive portion of variadic function template.
template<template<typename...> class First, typename... ArgsA, typename... Others>
typename std::enable_if<
    std::is_same<
        First<ArgsA...>
        , typename require_1_type<
            typename First<ArgsA...>::outer_t
            , typename First<ArgsA...>::outer_t::template Inner<ArgsA...>
        >::type
    >::value
    , some_lib::list<First<ArgsA...>, Others...>
>::type
mystery_func (First<ArgsA...> first, Others... others) {
    mystery_func(others...);
    return some_lib::make_list(first, others...);
}

My goal was to limit the types being passed in, to any variations of Inner for any variations of Outer.  I think this does what I was looking for, at least it seems that way.

My understanding of how this all works is as follows, please correct as appropriate:

A series of Inner objects gets passed in.  Each Inner object has a typedef referring to its' Outer type.  We strip off one Inner object from the parameter pack, and check the typedef referring to its' Outer type to make sure it matches the expected Outer type.  If it matches, then we take the parameter pack used on the first Inner object that was passed in, and pass the pack along to an Inner template that we reference through the Outer typedef referred to by the first Inner.  Then we check those two Inner's against each other to make sure they're the same.  If they are, then that particular function template instantiation is enabled.

The variadic function template itself simply calls itself recursively so that all objects in the parameter pack have those same checks run on them, until we run out of arguments, which calls the blank version of the function.  Finally, each recursion makes a call to (in this case) a function that puts the objects together in a list.

One thing I'm not sure of is if the compiler is optimizing out all those calls to make_list that are returning into nothingness, except the last one, which is done by the first invocation of mystery_func(), and the only one that has a purposeful return value.

Anyway, improvements, comments, and simplifications are most welcome.


问:
I don't know why my vba code is throwing a compile error
I get a dub or funtion not defined error. I created a command button on the sheet and wrote the code in the button sub i did not rename the button

```<code>Private Sub CommandButton1_Click()
 'fln = family last name
 'fn = first name
 'cn2 = child's name
 Dim fln As String, fn As String, i As Long
 Dim fln2 As String, fn2 As String, cn2 As String, j As Integer

 i = 2 'i is set to 2 to take into account column headers
 j = 1
 fln = Cell(i, 1).Value2
 fn = Cell(i, 2).Value2
 fln2 = Cell(i + 1, 1).Value2
 fn2 = Cell(i + 1, 2).Value2
 cn2 = Cell(i + 1, 7).Value2

 Do While i < Rows.Count
  'if the famlies last name and first name are the same as the ones in the
   row below and the row below is not blank
   If fln = fln2 And fn = fn2 And fln2 <> "" Then
   ' move the childs name to the next free column on the original row
      Cell(i, 7 + j).Value2 = cn2
      'increment the column
      j = j + 1
      'delete the row with the duplicate
      Rows(i + 1).Delete
    'else move the dup checker down a row as the current row now has a
     complete family listing
    Else
     i = i + 1
     'reset j
     j = 1
     Loop
</code>```

'start checking for dup family rows again

答:
You didnt close your IF statement.

put END IF on the line right before LOOP

Body:
I get a dub or funtion not defined error. I created a command button on the sheet and wrote the code in the button sub i did not rename the button

Private Sub CommandButton1_Click()
 'fln = family last name
 'fn = first name
 'cn2 = child's name
 Dim fln As String, fn As String, i As Long
 Dim fln2 As String, fn2 As String, cn2 As String, j As Integer

 i = 2 'i is set to 2 to take into account column headers
 j = 1
 fln = Cell(i, 1).Value2
 fn = Cell(i, 2).Value2
 fln2 = Cell(i + 1, 1).Value2
 fn2 = Cell(i + 1, 2).Value2
 cn2 = Cell(i + 1, 7).Value2

 Do While i < Rows.Count
  'if the famlies last name and first name are the same as the ones in the
   row below and the row below is not blank
   If fln = fln2 And fn = fn2 And fln2 <> "" Then
   ' move the childs name to the next free column on the original row
      Cell(i, 7 + j).Value2 = cn2
      'increment the column
      j = j + 1
      'delete the row with the duplicate
      Rows(i + 1).Delete
    'else move the dup checker down a row as the current row now has a
     complete family listing
    Else
     i = i + 1
     'reset j
     j = 1
     Loop

'start checking for dup family rows again


问:
Julia: Abstract and Concrete Types Integer versus Int8 versus Int64
Suppose I have an integer n that will only ever take values in [0, 10]. Should I declare it as n::Integer to be general about it, as n::Int8 or n::UInt8 to be parsimonious or n::Int64 for a 64 bit system?

Please clarify the reasons for a newbie, e.g. style, performance.

Reference: https://docs.julialang.org/en/release-0.5/manual/integers-and-floating-point-numbers/

Updated Reference (2021): https://docs.julialang.org/en/v1/manual/types/#man-abstract-types

答:
It's important to distinguish two different cases.

Storage: If you have a type that stores n as one of its fields, or as a value in an array, then you should definitely consider using Int8 or UInt8. Even if the saved space for a single value is negligible, if many instances of your type are created and stored in a collection, then the space savings can rapidly become significant. Let's say you have a Foo type with a field n, then you might do this:

```<code>struct Foo
    n::UInt8
end
</code>```

When a value is assigned to the n field of a Foo object, it will automatically be converted to UInt8 and an error will be raised if the value cannot be converted faithfully:

```<code>julia> Foo(123) # Ints are automatically converted to UInt8
Foo(0x7b)

julia> typeof(ans.n)
UInt8

julia> Foo(500) # if too large, an error is raised
ERROR: InexactError()
Stacktrace:
 [1] Foo(::Int64) at ./REPL[1]:2

julia> Foo(-1) # ditto if too small
ERROR: InexactError()
Stacktrace:
 [1] Foo(::Int64) at ./REPL[1]:2

julia> Foo(2π/π)
Foo(0x02)
</code>```

If the value that's assigned is already of the correct type then no check is required so there's no overhead.

Dispatch: If you are writing a method of a function that takes n as an argument, then there's no harm in having as loose a type annotation on the n argument as makes sense semantically. In the case you've described, it seems that any kind of integer value would be sensible, so using n::Integer would probably be appropriate. For example, if wanted to implement a checked constructor for Foo objects, you could do this:

```<code>struct Foo
    n::UInt8

    function Foo(n::Integer)
        0 <= n <= 10 || throw(ArgumentError("n not in [0, 10]: $n"))
        return new(n)
    end
end
</code>```

Now an error is thrown if a value outside of [0, 10] is given:

```<code>julia> Foo(123)
ERROR: ArgumentError: n not in [0, 10]: 123
Stacktrace:
 [1] Foo(::Int64) at ./REPL[26]:2

julia> Foo(3)
Foo(0x03)
</code>```

This Foo construction works for any kind of integer, checking that it's in the correct range, and then converting to UInt8. This is slightly more restrictive than the built-in constructor for Foo, which will happily take any kind of n argument and try to convert it to UInt8 – even when the argument is not of an integer type. If that kind of behavior is desirable, you could loosen the type signature here further to n::Real, n::Number (or even n::Any, although that seems excessive).

Note that there is no performance advantage to tightly typed method arguments – the specialized code for actual argument types is generated on demand anyway.

Body:
It's important to distinguish two different cases.

Storage: If you have a type that stores n as one of its fields, or as a value in an array, then you should definitely consider using Int8 or UInt8. Even if the saved space for a single value is negligible, if many instances of your type are created and stored in a collection, then the space savings can rapidly become significant. Let's say you have a Foo type with a field n, then you might do this:

struct Foo
    n::UInt8
end

When a value is assigned to the n field of a Foo object, it will automatically be converted to UInt8 and an error will be raised if the value cannot be converted faithfully:

julia> Foo(123) # Ints are automatically converted to UInt8
Foo(0x7b)

julia> typeof(ans.n)
UInt8

julia> Foo(500) # if too large, an error is raised
ERROR: InexactError()
Stacktrace:
 [1] Foo(::Int64) at ./REPL[1]:2

julia> Foo(-1) # ditto if too small
ERROR: InexactError()
Stacktrace:
 [1] Foo(::Int64) at ./REPL[1]:2

julia> Foo(2π/π)
Foo(0x02)

If the value that's assigned is already of the correct type then no check is required so there's no overhead.

Dispatch: If you are writing a method of a function that takes n as an argument, then there's no harm in having as loose a type annotation on the n argument as makes sense semantically. In the case you've described, it seems that any kind of integer value would be sensible, so using n::Integer would probably be appropriate. For example, if wanted to implement a checked constructor for Foo objects, you could do this:

struct Foo
    n::UInt8

    function Foo(n::Integer)
        0 <= n <= 10 || throw(ArgumentError("n not in [0, 10]: $n"))
        return new(n)
    end
end

Now an error is thrown if a value outside of [0, 10] is given:

julia> Foo(123)
ERROR: ArgumentError: n not in [0, 10]: 123
Stacktrace:
 [1] Foo(::Int64) at ./REPL[26]:2

julia> Foo(3)
Foo(0x03)

This Foo construction works for any kind of integer, checking that it's in the correct range, and then converting to UInt8. This is slightly more restrictive than the built-in constructor for Foo, which will happily take any kind of n argument and try to convert it to UInt8 – even when the argument is not of an integer type. If that kind of behavior is desirable, you could loosen the type signature here further to n::Real, n::Number (or even n::Any, although that seems excessive).

Note that there is no performance advantage to tightly typed method arguments – the specialized code for actual argument types is generated on demand anyway.


问:
C# executing code using condition ? method call : method call
I'm trying to add to one list or another based on a condition using ? : syntax, is this possible in c#, the syntax I was using does not compile

```<code>List<int> Negatives = new List<int>();
List<int> Positives = new List<int>();

foreach (int number in numbers)
{
    (number >= 0) ? Negatives.Add(number) : Positives.Add(number);
}
</code>```

答:
The consequence and alternative of a conditional expression must have a value; void-returning methods do not have a value.

Use an if statement.

Body:
I'm trying to add to one list or another based on a condition using ? : syntax, is this possible in c#, the syntax I was using does not compile

List<int> Negatives = new List<int>();
List<int> Positives = new List<int>();

foreach (int number in numbers)
{
    (number >= 0) ? Negatives.Add(number) : Positives.Add(number);
}


问:
How to Import Pymysql?
I am trying to connect to SQL Server through Eclipse using the below code and it is returning 'No module name pymysql.' I have been researching and I believe I need PIP installed. However, I have Python 2.7.10, which I believe comes with PIP. Is there some type of driver that I need, too? I read this module does not need any driver, but not sure how valid that is. </p>

```<code>import pymysql
import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='sqlhost', trusted=True)
</code>```

答:
Yes you are right python 2.7.x comes with pip pre-installed but we need to add the path/to/Python27/Scripts/ directory in the PATH environment variable to use pip from the terminal.
Once pip is present in system PATH you can execute below command to install pymysql.

pip install pymysql

Title: How to Import Pymysql?

Body:
I am trying to connect to SQL Server through Eclipse using the below code and it is returning 'No module name pymysql.' I have been researching and I believe I need PIP installed. However, I have Python 2.7.10, which I believe comes with PIP. Is there some type of driver that I need, too? I read this module does not need any driver, but not sure how valid that is.

import pymysql
import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='sqlhost', trusted=True)


问:
Tree inside a node in c
I need to implement a binary tree that every node of this main tree has a binary tree inside. What i did was create these two structs following

```<code>typedef struct depart{
   int salary, employee;
   struct depart *left, *right;
}depart;

typedef struct tree{
    int ndepart;
    depart dpt;
    struct tree *left, *right;
}tree;
</code>```

I have no problems with the main tree. But i don't understand how to create a the trees inside each node of the main tree and didn't found anywhere about this type of data structure. Someone can give me hints about it?

答:
This seems (as mentioned by @kaylum in the comments) like a classical recursive definition of a tree where clearly every left and right node is again root of a (possibly empty) binary tree. If that is so then you just have to form a binary tree.

If indeed what you need is an additional tree in every node, and it really sounds strange to me, you just have to define something like a local root node where you attach the local tree at every node. Since your description is a little vague I assume that there will be a main tree where every node has such an additional tree and all the additional trees that do not contain further local trees.

To avoid confusion you should maybe define a struct main_tree_node that contains *left,*right, and *local_tree as well as a second struct local_tree_node that only has a *left and *right reference.

Title: Tree inside a node in c

Body:
I need to implement a binary tree that every node of this main tree has a binary tree inside. What i did was create these two structs following

typedef struct depart{
   int salary, employee;
   struct depart *left, *right;
}depart;

typedef struct tree{
    int ndepart;
    depart dpt;
    struct tree *left, *right;
}tree;

I have no problems with the main tree. But i don't understand how to create a the trees inside each node of the main tree and didn't found anywhere about this type of data structure. Someone can give me hints about it?


问:
ionic build Android | error: No installed build tools found. Please install the Android build tools
When I run ionic build android command in root of ionic project, I am getting this error:

FAILURE: Build failed with an exception.

Where: Script '/home/javad/Desktop/javadApp/platforms/android/CordovaLib/cordova.gradle'
  line: 64

What went wrong: A problem occurred evaluating root project 'android'.

No installed build tools found. Please install the Android build tools version 19.1.0 or higher.

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

```<code>javad@javad:~/Desktop/javadApp$ ionic build android
Running command: /home/javad/Desktop/javadApp/hooks/after_prepare/010_add_platform_class.js /home/javad/Desktop/javadApp
add to body class: platform-android
Running command: /home/javad/Desktop/javadApp/platforms/android/cordova/build
ANDROID_HOME=/opt/android-sdk
JAVA_HOME=/usr/lib/jvm/default-java
Running: /home/javad/Desktop/javadApp/platforms/android/gradlew cdvBuildDebug -b /home/javad/Desktop/javadApp/platforms/android/build.gradle -Dorg.gradle.daemon=true

FAILURE: Build failed with an exception.

* Where:
Script '/home/javad/Desktop/javadApp/platforms/android/CordovaLib/cordova.gradle' line: 64

* What went wrong:
A problem occurred evaluating root project 'android'.
> No installed build tools found. Please install the Android build tools version 19.1.0 or higher.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1.564 secs

/home/javad/Desktop/javadApp/platforms/android/cordova/node_modules/q/q.js:126
                    throw e;
                          ^
Error code 1 for command: /home/javad/Desktop/javadApp/platforms/android/gradlew with args: cdvBuildDebug,-b,/home/javad/Desktop/javadApp/platforms/android/build.gradle,-Dorg.gradle.daemon=true
ERROR building one of the platforms: Error: /home/javad/Desktop/javadApp/platforms/android/cordova/build: Command failed with exit code 8
You may not have the required environment or OS to build this project
Error: /home/javad/Desktop/javadApp/platforms/android/cordova/build: Command failed with exit code 8
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:134:23)
    at ChildProcess.EventEmitter.emit (events.js:98:17)
    at maybeClose (child_process.js:743:16)
    at Process.ChildProcess._handle.onexit (child_process.js:810:5)
</code>```

in ~/.profile i have:

export PATH=$PATH:/opt/android-sdk/tools

export PATH=$PATH:/opt/android-sdk/platform-tools

export PATH=$PATH:/opt/node/bin

export JAVA_HOME=/usr/lib/jvm/default-java

export ANDROID_HOME=/opt/android-sdk

$PATH is:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/android-sdk/tools:/opt/android-sdk/platform-tools:/opt/node/bin

Important issue:

in file:
/home/javad/Desktop/javadApp/platforms/android/CordovaLib/cordova.gradle | line 38:

```<code>String[] getAvailableBuildTools() {
    def buildToolsDir = new File(getAndroidSdkDir(), "build-tools")
    buildToolsDir.list()
        .findAll { it ==~ /[0-9.]+/ }
        .sort { a, b -> compareVersions(b, a) }
}
</code>```

just returned /opt/android-sdk/build-tools  !!!

in /opt/android-sdk/build-tools folder i have:

android-5.1 folder that extract from:
https://dl.google.com/android/repository/build-tools_r22-linux.zip

答:
This problem I solved with the following detail, somehow the android SDK manage installed all the dependencies and necessary files, but forget this `templates` files where is found templates> gradle> wrapper. This set of files is missing.

Path  in mac
/Users/giogio/Library/Android/sdk/tools/templates

Body:
When I run ionic build android command in root of ionic project, I am getting this error:

FAILURE: Build failed with an exception.

Where: Script '/home/javad/Desktop/javadApp/platforms/android/CordovaLib/cordova.gradle'
  line: 64

What went wrong: A problem occurred evaluating root project 'android'.

No installed build tools found. Please install the Android build tools version 19.1.0 or higher.

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

javad@javad:~/Desktop/javadApp$ ionic build android
Running command: /home/javad/Desktop/javadApp/hooks/after_prepare/010_add_platform_class.js /home/javad/Desktop/javadApp
add to body class: platform-android
Running command: /home/javad/Desktop/javadApp/platforms/android/cordova/build
ANDROID_HOME=/opt/android-sdk
JAVA_HOME=/usr/lib/jvm/default-java
Running: /home/javad/Desktop/javadApp/platforms/android/gradlew cdvBuildDebug -b /home/javad/Desktop/javadApp/platforms/android/build.gradle -Dorg.gradle.daemon=true

FAILURE: Build failed with an exception.

* Where:
Script '/home/javad/Desktop/javadApp/platforms/android/CordovaLib/cordova.gradle' line: 64

* What went wrong:
A problem occurred evaluating root project 'android'.
> No installed build tools found. Please install the Android build tools version 19.1.0 or higher.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1.564 secs

/home/javad/Desktop/javadApp/platforms/android/cordova/node_modules/q/q.js:126
                    throw e;
                          ^
Error code 1 for command: /home/javad/Desktop/javadApp/platforms/android/gradlew with args: cdvBuildDebug,-b,/home/javad/Desktop/javadApp/platforms/android/build.gradle,-Dorg.gradle.daemon=true
ERROR building one of the platforms: Error: /home/javad/Desktop/javadApp/platforms/android/cordova/build: Command failed with exit code 8
You may not have the required environment or OS to build this project
Error: /home/javad/Desktop/javadApp/platforms/android/cordova/build: Command failed with exit code 8
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:134:23)
    at ChildProcess.EventEmitter.emit (events.js:98:17)
    at maybeClose (child_process.js:743:16)
    at Process.ChildProcess._handle.onexit (child_process.js:810:5)

in ~/.profile i have:

export PATH=$PATH:/opt/android-sdk/tools

export PATH=$PATH:/opt/android-sdk/platform-tools

export PATH=$PATH:/opt/node/bin

export JAVA_HOME=/usr/lib/jvm/default-java

export ANDROID_HOME=/opt/android-sdk

$PATH is:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/android-sdk/tools:/opt/android-sdk/platform-tools:/opt/node/bin

Important issue:

in file:
/home/javad/Desktop/javadApp/platforms/android/CordovaLib/cordova.gradle | line 38:

String[] getAvailableBuildTools() {
    def buildToolsDir = new File(getAndroidSdkDir(), "build-tools")
    buildToolsDir.list()
        .findAll { it ==~ /[0-9.]+/ }
        .sort { a, b -> compareVersions(b, a) }
}

just returned /opt/android-sdk/build-tools  !!!

in /opt/android-sdk/build-tools folder i have:

android-5.1 folder that extract from:
https://dl.google.com/android/repository/build-tools_r22-linux.zip


问:
Installed Laravel 5 in subfolder with modified .htaccess but assets not showing
I have installed laravel 5.4 in a subfolder, e.x. example.com/laravel.

I followed ka_lin's anwser and it seems like everything works fine except the assets as they are not showing. However, if I add "public" to the url, like example.com/laravel/public/(asset uri...) I can request the asset. I am wondering if there's anyway to work around with this.

.htaccess which resides in the project root folder:

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

   RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
</code>```

答:
I finally figured out why!!

Because I named my folder to "img" instead of "images", so I have to change

```<code>RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
</code>```

to

```<code>RewriteRule ^(css|js|img)/(.*)$ public/$1/$2 [L,NC]
</code>```

And if I have any other assets like fonts, I need to add the folder name to the parentheses and modify

```<code>RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
</code>```

to include the extension.

I don't know much about apache configuration but it works for me. Hope it help other people.

Body:
I have installed laravel 5.4 in a subfolder, e.x. example.com/laravel.

I followed ka_lin's anwser and it seems like everything works fine except the assets as they are not showing. However, if I add "public" to the url, like example.com/laravel/public/(asset uri...) I can request the asset. I am wondering if there's anyway to work around with this.

.htaccess which resides in the project root folder:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

   RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

Body:
I finally figured out why!!

Because I named my folder to "img" instead of "images", so I have to change

RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]

to

RewriteRule ^(css|js|img)/(.*)$ public/$1/$2 [L,NC]

And if I have any other assets like fonts, I need to add the folder name to the parentheses and modify

RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]

to include the extension.

I don't know much about apache configuration but it works for me. Hope it help other people.


问:
Is it good idea to write multi level inline functions in C++?
Is something like this code considered a bad practice?
If so, what should I do when func1 duplicates func2's behavior and I need both functions to be present (isn't that considered code redundancy)?!

UPD: Sorry for my bad illustration, I'll try to explain the question more clearly.
What i wanted to ask about is that:
I'm trying to design an optimized class that heavily calls two methods func1 and func2, func1's implementation uses func2 and i want the two methods calls to be inlined as much as possible, So is it better to call func2 from func1 like this code or to implement both independently.

```<code>inline int func2(int x) {
    return x * (x + 2);
}
inline int func1(int x) {
    return x * (x + 1) * func2(x + 2);
}
</code>```

答:
There's no problem in a function calling another function. You'll see real programs go much deeper than 2 calls, if you sample them.

As far as inlining, that's also no problem. An optimizing compiler would typically inline func2 (assuming its definition is visible and optimizations are enabled). Many common compilers and optimizers are smart about inlining. They often know when to inline and when not to inline -- all without your assistance.

Writing small functions is not a bad practice. Clarity and intent are typically of a higher importance than micro-optimizations. Under typical circumstances, there's nothing wrong with your example.

Body:
Is something like this code considered a bad practice?
If so, what should I do when func1 duplicates func2's behavior and I need both functions to be present (isn't that considered code redundancy)?!

UPD: Sorry for my bad illustration, I'll try to explain the question more clearly.
What i wanted to ask about is that:
I'm trying to design an optimized class that heavily calls two methods func1 and func2, func1's implementation uses func2 and i want the two methods calls to be inlined as much as possible, So is it better to call func2 from func1 like this code or to implement both independently.

inline int func2(int x) {
    return x * (x + 2);
}
inline int func1(int x) {
    return x * (x + 1) * func2(x + 2);
}


问:
How to set upstream branch to the same name as the branch
If I create a new branch and try to push it, I am told that I have to explicitly say what the name of the upstream branch needs to be.

```<code>> git checkout -b feature/long-branch-name-I-dont-want-to-have-to-type-out
Switched to a new branch 'feature/long-branch-name-I-dont-want-to-have-to-type-out'
> git push
fatal: The current branch feature/long-branch-name-I-dont-want-to-have-to-type-out has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin feature/long-branch-name-I-dont-want-to-have-to-type-out
</code>```

Is there some way to do that without having to type out the name of the upstream branch?  I virtually always want it to be the same name on the server as it is locally.

Is there any way to do something like  git push --set-upstream <current_branch_name>, independent of what the current branch name happens to be?

答:
Configure git config

```<code>$ git config --global push.default current
</code>```

Now, after checkout to a branch, you should use simply git push

```<code>$ git checkout -b new-branch
$ git push                    # similar to git push -u origin new-branch
</code>```

If you want to set upstream for the future then use --set-upstream (-u) flag:

```<code>$ git push -u origin HEAD
</code>```

N.B. HEAD and local current branch normally stay in the same state.

Body:
If I create a new branch and try to push it, I am told that I have to explicitly say what the name of the upstream branch needs to be.

> git checkout -b feature/long-branch-name-I-dont-want-to-have-to-type-out
Switched to a new branch 'feature/long-branch-name-I-dont-want-to-have-to-type-out'
> git push
fatal: The current branch feature/long-branch-name-I-dont-want-to-have-to-type-out has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin feature/long-branch-name-I-dont-want-to-have-to-type-out

Is there some way to do that without having to type out the name of the upstream branch?  I virtually always want it to be the same name on the server as it is locally.

Is there any way to do something like  git push --set-upstream <current_branch_name>, independent of what the current branch name happens to be?

Body:
Configure git config

$ git config --global push.default current

Now, after checkout to a branch, you should use simply git push

$ git checkout -b new-branch
$ git push                    # similar to git push -u origin new-branch

If you want to set upstream for the future then use --set-upstream (-u) flag:

$ git push -u origin HEAD

N.B. HEAD and local current branch normally stay in the same state.


问:
Play sounds one after another with loop
I have four audios. Let’s say s1, s2, s3, and s4. I also have a variable with random integers between one and four, for example myVar = [2, 1, 3, 4]. It can be longer or shorter than four, but the integers in it will be always between one and four.

I want to make a cycle which will look on myVar and play my sounds in corresponding order (in this case: s2, s1, s3, s4). One sound after another, that is very important. Not all at once.

All my solutions play the sounds at once so far. I know there are several similar questions, but I am so bad at JavaScript that I was not able to use the answers. Anybody knows how to do it?

One of current solutions (does not work):

```<code>function recTime (i) {

  if (i === myVar.length) return;

  if (myVar[i] === 1) {
    setTimeout(function() {
      s1.play();
      return recTime(++i);
    },350);}
  else if (myVar[i] === 2) {
    setTimeout(function() {
      s2.play();
      return recTime(++i);
    },350);
  }
  else if (myVar[i] === 3) {
    setTimeout(function() {
      s3.play();
      return recTime(++i);
    },350);
  }
  else if (myVar[i] === 4) {
    setTimeout(function() {
      s4.play();
      return recTime(i++);
    },350);
  }
  }

I call it in this cycle:

  for (var i = 0; i < stimuli.length+1; ++i){
  recTime(i);
  }
</code>```

答:
There can also be a solution without mutation of 'order' array, for example using Symbol.iterator called for each ended event:

var a1 = new Audio('http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg'); a1.id = "1"; // id helps to see console.log is fine
var a2 = new Audio('http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg'); a2.id = "2";
var a3 = new Audio('http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg'); a3.id = "3";
var a4 = new Audio('http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg'); a4.id = "4";

var order = [2, 1, 4, 3, 2, 1];

rotateAudio(order); // main function; pass order array here

function rotateAudio(order) {
  var orderMap = {1: a1, 2: a2, 3: a3, 4: a4};
  var iterator = order[Symbol.iterator]();
  var value, done;

  function rotate({value, done}) { // get next iteration
    function next(e) {
      e.target.removeEventListener('ended', next); // helps for garbage removal I guess
      rotate(iterator.next())
    };
    if (done) { console.log('done!'); return };
    var current = orderMap[value];
    console.log('current: ', current);
    current.play();
    current.addEventListener('ended', next) // listen to 'ended' on audio, start next one
  }

  rotate(iterator.next()); // first call
}```

Title: Play sounds one after another with loop

Body:
I have four audios. Let’s say s1, s2, s3, and s4. I also have a variable with random integers between one and four, for example myVar = [2, 1, 3, 4]. It can be longer or shorter than four, but the integers in it will be always between one and four.

I want to make a cycle which will look on myVar and play my sounds in corresponding order (in this case: s2, s1, s3, s4). One sound after another, that is very important. Not all at once.

All my solutions play the sounds at once so far. I know there are several similar questions, but I am so bad at JavaScript that I was not able to use the answers. Anybody knows how to do it?

One of current solutions (does not work):

function recTime (i) {

  if (i === myVar.length) return;

  if (myVar[i] === 1) {
    setTimeout(function() {
      s1.play();
      return recTime(++i);
    },350);}
  else if (myVar[i] === 2) {
    setTimeout(function() {
      s2.play();
      return recTime(++i);
    },350);
  }
  else if (myVar[i] === 3) {
    setTimeout(function() {
      s3.play();
      return recTime(++i);
    },350);
  }
  else if (myVar[i] === 4) {
    setTimeout(function() {
      s4.play();
      return recTime(i++);
    },350);
  }
  }

I call it in this cycle:

  for (var i = 0; i < stimuli.length+1; ++i){
  recTime(i);
  }


问:
How do I parse a java simple date format in R?
The extra T and Z are throwing me off:

```<code>strptime("2017-06-08T11:55:53.179000Z", "%Y-%m-%dT%H:%M:%SZ")
</code>```

Returns NA

答:
Just use the anytime() function of the anytime package:

```<code>R> anytime("2017-06-08T11:55:53.179000Z")
[1] "2017-06-08 11:55:53.178 CDT"
R>
</code>```

The whole point of the anytime package is to parse such common formats without requiring a format.  Dealing with the trailing Z comes for free via the Boost parser.

If you want it interpreted as UTC use the corresponding utctime() package:

```<code>R> utctime("2017-06-08T11:55:53.179000Z")
[1] "2017-06-08 06:55:53.178 CDT"
R>
</code>```

If you want it stored as UTC, set the timezone accordingly:

```<code>R> utctime("2017-06-08T11:55:53.179000Z", tz="UTC")
[1] "2017-06-08 11:55:53.178 UTC"
R>
</code>```

Body:
The extra T and Z are throwing me off:

strptime("2017-06-08T11:55:53.179000Z", "%Y-%m-%dT%H:%M:%SZ")

Returns NA

Body:
Just use the anytime() function of the anytime package:

R> anytime("2017-06-08T11:55:53.179000Z")
[1] "2017-06-08 11:55:53.178 CDT"
R>

The whole point of the anytime package is to parse such common formats without requiring a format.  Dealing with the trailing Z comes for free via the Boost parser.

If you want it interpreted as UTC use the corresponding utctime() package:

R> utctime("2017-06-08T11:55:53.179000Z")
[1] "2017-06-08 06:55:53.178 CDT"
R>

If you want it stored as UTC, set the timezone accordingly:

R> utctime("2017-06-08T11:55:53.179000Z", tz="UTC")
[1] "2017-06-08 11:55:53.178 UTC"
R>


问:
How to get Javascript variable value into CSS?
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}
```

<p>CSS:</p>

<pre class="lang-css prettyprint-override"><code>.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}
</code>```

答:
You can use CSS-Variables.

Can I use: http://caniuse.com/css-variables/embed

Docs: https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables

const updateTime = () => {
  var d = new Date();
  var hour = d.getHours();
  var min = d.getMinutes();
  var second = d.getSeconds();
  var time = `${hour}:${min}:${second}`;

  // set CSS variable
  document.documentElement.style.setProperty(`--text`, `'${time}'`);
}

// initial call
updateTime();

// interval to update time
setInterval(updateTime, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  --text: '----';
}

.container {
  position: absolute;
  height: 75%;
  width: 75%;
  background: #98E8EE;
  top: 11.5%;
  left: 12.5%;
}

.container::after {
  content: var(--text);
  color: #F9F5F4;
  font-size: 40px;
  content: ;
  font-family: Arial;
  margin-left: 36.5px;
  top: 20px;
  position: relative
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">

```

Body:
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}

CSS:

.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}

Body:
You can use CSS-Variables.

Can I use: http://caniuse.com/css-variables/embed

Docs: https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables

const updateTime = () => {
  var d = new Date();
  var hour = d.getHours();
  var min = d.getMinutes();
  var second = d.getSeconds();
  var time = `${hour}:${min}:${second}`;

  // set CSS variable
  document.documentElement.style.setProperty(`--text`, `'${time}'`);
}

// initial call
updateTime();

// interval to update time
setInterval(updateTime, 1000);

:root {
  --text: '----';
}

.container {
  position: absolute;
  height: 75%;
  width: 75%;
  background: #98E8EE;
  top: 11.5%;
  left: 12.5%;
}

.container::after {
  content: var(--text);
  color: #F9F5F4;
  font-size: 40px;
  content: ;
  font-family: Arial;
  margin-left: 36.5px;
  top: 20px;
  position: relative
}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>

  <body>
    <div class="container"></div>
  </body>
</html>


答:
The conditional operator evaluates one expression or other to compute a value. It doesn't execute void-returning methods.

You can use the conditional operator here though, to decide which list to add to:

```<code>(number >= 0 ? positives : negatives).Add(number);
</code>```

Or more clearly:

```<code>var listToAddTo = number >= 0 ? positives : negatives;
listToAddTo.Add(number);
</code>```

Of course, you could use LINQ instead, for fun:

```<code>// This replaces the whole code
var lookup = numbers.ToLookup(x => x >= 0);
var positives = lookup[true].ToList();
var negatives = lookup[false].ToList();
</code>```

Or even, to be more strictly-accurate:

```<code>var lookup = numbers.ToLookup(Math.Sign);
var positives = lookup[1].ToList();
var zeroes = lookup[0].ToList();
var negatives = lookup[-1].ToList();
</code>```

Title: C# executing code using condition ? method call : method call

Body:
The conditional operator evaluates one expression or other to compute a value. It doesn't execute void-returning methods.

You can use the conditional operator here though, to decide which list to add to:

(number >= 0 ? positives : negatives).Add(number);

Or more clearly:

var listToAddTo = number >= 0 ? positives : negatives;
listToAddTo.Add(number);

Of course, you could use LINQ instead, for fun:

// This replaces the whole code
var lookup = numbers.ToLookup(x => x >= 0);
var positives = lookup[true].ToList();
var negatives = lookup[false].ToList();

Or even, to be more strictly-accurate:

var lookup = numbers.ToLookup(Math.Sign);
var positives = lookup[1].ToList();
var zeroes = lookup[0].ToList();
var negatives = lookup[-1].ToList();


问:
concatenate two lists of string in r
Here is my sample:

```<code>a = c("a","b","c")
b = c("1","2","3")
</code>```

I need to concatenate a and b automatically. The result should be "a 1","a 2","a 3","b 1","b 2","b 3","c 1","c 2","c 3".

For now, I am using the paste function:

```<code>paste(a[1],b[1])
</code>```

I need an automatic way to do this. Besides writing a loop, is there any easier way to achieve this?

Title: concatenate two lists of string in r

Body:
Here is my sample:

a = c("a","b","c")
b = c("1","2","3")

I need to concatenate a and b automatically. The result should be "a 1","a 2","a 3","b 1","b 2","b 3","c 1","c 2","c 3".

For now, I am using the paste function:

paste(a[1],b[1])

I need an automatic way to do this. Besides writing a loop, is there any easier way to achieve this?

Body:
c(outer(a, b, paste))

# [1] "a 1" "b 1" "c 1" "a 2" "b 2" "c 2" "a 3" "b 3" "c 3"


问:
how to let the parent view know that the subview has been removed - iphone
My app has a tab view controller as the main access point.
However, when it runs for the first time, I need to check for some basic data, and if that is missing, I need to show a view to capture this information first . The table in the tab view uses this information to display the data.

The way I am doing it is like this:
In my app-delegate, I show the tab view.
Then check for information x. If not present, add subview view2 and show it on top.
In view2, I capture the information, and on click of a button remove it from superview. The required data is stored in global variables in the model.
Now, the control goes back to the tab view which showed it.
The problem is that I need to reload the table data in the tab view so that it reflects the correct information. However, I am not able to capture this in my parent tab view. So, the only way I can do a refresh is by manually clicking a button, which is not ideal. I want it to automatically refresh as soon as the subview is removed from the stack.

答: One way would be to subclass your parent view and override willRemoveSubview:. This is called just before a view is removed from its superview.</p>


问:
How to get current TensorFlow name scope
I create relative name scopes with tf.name_scope.

How can I get the current absolute name scope?

From the code, it looks like tf.get_default_graph()._name_stack would give me that but that looks like a non-official way. Is there any official way? (I think not, thus I made an upstream feature request.)

(I implemented a bunch of functions like get_current_name_scope() or reuse_name_scope() here. Note that you need to be careful when mixing tf.name_scope and tf.variable_scope.)

答: Currently (2017-06-08) in master and in r1.2 is tf.contrib.framework.get_name_scope.


问:
Variadic templates and Alexandrescu tuple implementation
I try to learn a little bit about template metaprogramming and
currently i play around with variadic templates.

In his talk "Variadic Templates are Funadic" Alexandrescu introduces a
small tuple implementation, which i try to build and maybe extend a
little bit. (I know it is a toy example, i just try to learn a little
bit more about c++). However, i have a small problem with his code.

Here it is:

```<code>template <typename... Ts>
class tuple
{};

template<size_t, typename> struct tuple_element;

template<typename T, typename... Ts>
struct tuple_element<0, tuple<T, Ts...>>
{
    typedef T type;
};

template <size_t k, typename T, typename... Ts>
struct tuple_element<k, tuple<T, Ts...>>
{
    typedef
       typename tuple_element<k-1,tuple<Ts...>>::type type;
};

template<size_t k, typename... Ts>
typename std::enable_if<k == 0,
                        typename tuple_element<0,tuple<Ts...>>::type&>::type
   get(tuple<Ts...>& t)
{return t.head_;}

template<size_t k, typename T, typename... Ts>
typename std::enable_if<k != 0,
                        typename tuple_element<k,tuple<T,Ts...>>::type&>::type
   get(tuple<T,Ts...>& t)
{
    tuple<Ts...> & super = t;
    return get<k-1>(super);
}

template <typename T, typename... Ts>
class tuple<T,Ts...> : private tuple<Ts...>
{
private:
   T head_;

};

int main(int argc, char *argv[])
{
     tuple<int,std::string> t;
     get<0>(t) = 10;
     get<1>(t) = std::string("test");
     std::cout<<get<0>(t)<<std::endl;
}
</code>```

In order to work correctly, the get function must be friend of the
tuple class (It is also mentioned on this slides, see 32). But how
does the friend declaration looks like? I tried different approaches
but could not get it to work. When i change the code from private to public inheritance
and change the access rules for head_ to public it works.

Thanks for your help

Kevin

答:
Another implementation from the other point of view:

```<code>#include <iostream>
#include <type_traits>

template <class... Args>
class Tuple;

template <>
class Tuple<> {};

template <class T, class... Args>
class Tuple<T, Args...>: public Tuple<Args...> {
    using Base = Tuple<Args...>;
    T Value_;

public:
    Tuple(T&& value, Args&&... args)
        : Value_(std::forward<T>(value))
        , Base(std::forward<Args>(args)...)
    {
    }
    T& Value() {
        return Value_;
    }
};

template <size_t k, class T, class... Args>
struct Select {
    using Type = typename Select<k - 1, Args...>::Type;
};

template <class T, class... Args>
struct Select<0, T, Args...> {
    using Type = T;
};

template <size_t k, class... Args>
using TSelect = typename Select<k, Args...>::Type;

template <bool P, class T>
using TEnableIf = typename std::enable_if<P, T>::type;

template <size_t k, class T, class... Args>
TEnableIf<(k != 0), TSelect<k, T, Args...>&> get(Tuple<T, Args...>& t) {
    return get<k - 1, Args...>(t);
}

template <size_t k, class T, class... Args>
TEnableIf<(k == 0), TSelect<k, T, Args...>&> get(Tuple<T, Args...>& t) {
    return t.Value();
}

int main() {
    Tuple<int, char> t(1, 'a');
    std::cout << get<0>(t) << std::endl;
    std::cout << get<1>(t) << std::endl;
    get<1>(t) = 'b';
    std::cout << get<1>(t) << std::endl;
}
</code>```

Actually, we don't need a Tuple to get a type.

Body:
I try to learn a little bit about template metaprogramming and
currently i play around with variadic templates.

In his talk "Variadic Templates are Funadic" Alexandrescu introduces a
small tuple implementation, which i try to build and maybe extend a
little bit. (I know it is a toy example, i just try to learn a little
bit more about c++). However, i have a small problem with his code.

Here it is:

template <typename... Ts>
class tuple
{};

template<size_t, typename> struct tuple_element;

template<typename T, typename... Ts>
struct tuple_element<0, tuple<T, Ts...>>
{
    typedef T type;
};

template <size_t k, typename T, typename... Ts>
struct tuple_element<k, tuple<T, Ts...>>
{
    typedef
       typename tuple_element<k-1,tuple<Ts...>>::type type;
};

template<size_t k, typename... Ts>
typename std::enable_if<k == 0,
                        typename tuple_element<0,tuple<Ts...>>::type&>::type
   get(tuple<Ts...>& t)
{return t.head_;}

template<size_t k, typename T, typename... Ts>
typename std::enable_if<k != 0,
                        typename tuple_element<k,tuple<T,Ts...>>::type&>::type
   get(tuple<T,Ts...>& t)
{
    tuple<Ts...> & super = t;
    return get<k-1>(super);
}

template <typename T, typename... Ts>
class tuple<T,Ts...> : private tuple<Ts...>
{
private:
   T head_;

};

int main(int argc, char *argv[])
{
     tuple<int,std::string> t;
     get<0>(t) = 10;
     get<1>(t) = std::string("test");
     std::cout<<get<0>(t)<<std::endl;
}

In order to work correctly, the get function must be friend of the
tuple class (It is also mentioned on this slides, see 32). But how
does the friend declaration looks like? I tried different approaches
but could not get it to work. When i change the code from private to public inheritance
and change the access rules for head_ to public it works.

Thanks for your help

Kevin

Body:
Another implementation from the other point of view:

#include <iostream>
#include <type_traits>

template <class... Args>
class Tuple;

template <>
class Tuple<> {};

template <class T, class... Args>
class Tuple<T, Args...>: public Tuple<Args...> {
    using Base = Tuple<Args...>;
    T Value_;

public:
    Tuple(T&& value, Args&&... args)
        : Value_(std::forward<T>(value))
        , Base(std::forward<Args>(args)...)
    {
    }
    T& Value() {
        return Value_;
    }
};

template <size_t k, class T, class... Args>
struct Select {
    using Type = typename Select<k - 1, Args...>::Type;
};

template <class T, class... Args>
struct Select<0, T, Args...> {
    using Type = T;
};

template <size_t k, class... Args>
using TSelect = typename Select<k, Args...>::Type;

template <bool P, class T>
using TEnableIf = typename std::enable_if<P, T>::type;

template <size_t k, class T, class... Args>
TEnableIf<(k != 0), TSelect<k, T, Args...>&> get(Tuple<T, Args...>& t) {
    return get<k - 1, Args...>(t);
}

template <size_t k, class T, class... Args>
TEnableIf<(k == 0), TSelect<k, T, Args...>&> get(Tuple<T, Args...>& t) {
    return t.Value();
}

int main() {
    Tuple<int, char> t(1, 'a');
    std::cout << get<0>(t) << std::endl;
    std::cout << get<1>(t) << std::endl;
    get<1>(t) = 'b';
    std::cout << get<1>(t) << std::endl;
}

Actually, we don't need a Tuple to get a type.


问:
Getting -nil- values for ActiveRecord attributes in Rails database when parsing spreadsheet using roo-gem
So I am trying to build a feature within my application that will allow a User to upload a spreadsheet file filled with new products. I installed the Roo gem. I created a link for the User to download a templated Google Spreadsheet to use to upload Products to my app. For the purposes of testing this feature I am using this templated sheet to upload to my application.

The first row headers have the names of the attributes necessary to create a product in the database.

I am able to upload the file, however, no matter how many products are listed in the file it will only upload one product. Also, the product that is imported has -nil- values associated with the attributes from the file. I can verify this through the Rails Console.

For instance:
  name: nil, description: nil, etc.

This is the corresponding code in my Product.rb file:

```<code>def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      product = find_by_id(row["id"]) || new
      product.attributes = row.to_hash.slice(*accessible_attributes)
      product.save!
    end
end

def self.accessible_attributes
   ['name', 'description', 'category', 'barcode', 'quantity',
   'capacity', 'threshold']
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::Csv.new(file.path, file_warning: :ignore)
  when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end
</code>```

This is how I have my route setup:

```<code>resources :products do
   collection { post :import }
end
</code>```

答:
Ok so the issue I had was that on the spreadsheet I was imported I had the header rows capitalized and not lowercase. Also had issues with the Capacity, Threshold and Quantity attributes because they were not apart of the Product model. </p>

<p>Once I edited the spreadsheet and removed those three attributes it imported correctly with no errors. </p>

Body:
So I am trying to build a feature within my application that will allow a User to upload a spreadsheet file filled with new products. I installed the Roo gem. I created a link for the User to download a templated Google Spreadsheet to use to upload Products to my app. For the purposes of testing this feature I am using this templated sheet to upload to my application.

The first row headers have the names of the attributes necessary to create a product in the database.

I am able to upload the file, however, no matter how many products are listed in the file it will only upload one product. Also, the product that is imported has -nil- values associated with the attributes from the file. I can verify this through the Rails Console.

For instance:
  name: nil, description: nil, etc.

This is the corresponding code in my Product.rb file:

def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      product = find_by_id(row["id"]) || new
      product.attributes = row.to_hash.slice(*accessible_attributes)
      product.save!
    end
end

def self.accessible_attributes
   ['name', 'description', 'category', 'barcode', 'quantity',
   'capacity', 'threshold']
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::Csv.new(file.path, file_warning: :ignore)
  when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end

This is how I have my route setup:

resources :products do
   collection { post :import }
end

Body:
Ok so the issue I had was that on the spreadsheet I was imported I had the header rows capitalized and not lowercase. Also had issues with the Capacity, Threshold and Quantity attributes because they were not apart of the Product model.

Once I edited the spreadsheet and removed those three attributes it imported correctly with no errors.


问:
What would be the Go structs for this terse JSON document?
The document has minimal key/value pair metadata on purpose.  In a list of people, we could have something like "name":"joe" or we could have a key of joe.  It errs on having fewer keys.

Perhaps this document is just too dynamic for Go structs?  I've tried YAML as well, it's the structs that's the problem.  The structs remain empty because it's not mapping correctly.

Playground link: https://play.golang.org/p/PGSjoKvNja

Or do I need to roll my own UnmarshalJSON and have conditionals (or switch) for "actions"?  That's fine if so.  I could do coercion and validation in there, loop through the doc and detect what the problematic generic action bit is and then create a struct of the right type.

答:
If the data is NOT consistent, as @Adrian stated, you should not go for what I'm showing.

Otherwise, you should be able to unmarshal your string with the following struct generated with json-to-go, a very useful tool to get a struct out of a json

```<code>type Custom struct {
    Ball []struct {
        Throw struct {
            Strength string `json:"strength"`
        } `json:"throw"`
    } `json:"ball"`
    Frisbee []struct {
        Fling struct {
            Curve string `json:"curve"`
        } `json:"fling"`
        Catch struct {
            Trick string `json:"trick"`
            Jump string `json:"jump"`
        } `json:"catch"`
    } `json:"frisbee"`
}
</code>```

And then

```<code>func main() {

    var c Custom
    err := json.Unmarshal([]byte(input), &c )
    if err != nil {
        panic(err)
    }

     fmt.Println(input)

}
</code>```

Which prints out

```<code>{
    "ball": [{
        "throw": {
            "strength": "60%"
        }
    }, {
        "throw": {
            "strength": "20%"
        }
    }],
    "frisbee": [{
        "fling": {
            "curve": "left"
        }
    }, {
        "catch": {
            "trick": "behind back",
            "jump": "sure"
        }
    }]
}
</code>```

Have a look at this Playground I set up.

Body:
If the data is NOT consistent, as @Adrian stated, you should not go for what I'm showing.

Otherwise, you should be able to unmarshal your string with the following struct generated with json-to-go, a very useful tool to get a struct out of a json

type Custom struct {
    Ball []struct {
        Throw struct {
            Strength string `json:"strength"`
        } `json:"throw"`
    } `json:"ball"`
    Frisbee []struct {
        Fling struct {
            Curve string `json:"curve"`
        } `json:"fling"`
        Catch struct {
            Trick string `json:"trick"`
            Jump string `json:"jump"`
        } `json:"catch"`
    } `json:"frisbee"`
}

And then

func main() {

    var c Custom
    err := json.Unmarshal([]byte(input), &c )
    if err != nil {
        panic(err)
    }

     fmt.Println(input)

}

Which prints out

{
    "ball": [{
        "throw": {
            "strength": "60%"
        }
    }, {
        "throw": {
            "strength": "20%"
        }
    }],
    "frisbee": [{
        "fling": {
            "curve": "left"
        }
    }, {
        "catch": {
            "trick": "behind back",
            "jump": "sure"
        }
    }]
}

Have a look at this Playground I set up.


问:
How can I hide a table until filtered/input entered in search
I'm new to web developing but catching on fairly quickly. I'm developing a wiki page for my company and I have a filter table built but I want to hide the table until the filter function is applied when a user enters their search text. So this way it only shows the text input box and then when they type in their search the table results will THEN show.

I'm using this Javascript for the filtering:

```<code>  function ContactsearchFX() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
     td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";

      }
    }
  }
}
</code>```

on a basic search table with this html code:

```<code><input type="text" id="myInput"            onkeyup="ContactsearchFX()" placeholder="Search for           names..">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Number</th>
  </tr>
   <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
     <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
  <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
</code>```

....and so on.

答:
window.onload = function() {
  var rows = document.querySelectorAll('tr:not(.header)');

  for (var i = 0; i < rows.length; i++) {
    rows[i].style.display = 'none';
  }
}

function ContactsearchFX() {
  var input, filter, table, tr, td, i;

  input = document.getElementById("myInput");

  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";

      }
    }
  }

   var rows = document.querySelectorAll('tr:not(.header)');

   if (input.value.length == 0) {
    for (var i = 0; i < rows.length; i++) {
      rows[i].style.display = 'none';
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="myInput" onkeyup="ContactsearchFX()" placeholder="Search for           names..">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Number</th>
  </tr>
  <tr>
    <td>test 1</td>
    <td>number</td>
  </tr>
  <tr>
    <td>test 2</td>
    <td>number</td>
  </tr>
  <tr>
    <td>test 3</td>
    <td>number</td>
  </tr></code>```

This seems to do the trick! On the load of the window, it loops through all the table rows which do now have the class of header. So your header, is always visible.

Then as your code originally did, it goes through the table and filters out the ones that are matching.

After this, I just added in another loop which then sets the rows back to display: none if there is nothing that is in the input box.

Hope this is what you were looking for.

Body:
I'm new to web developing but catching on fairly quickly. I'm developing a wiki page for my company and I have a filter table built but I want to hide the table until the filter function is applied when a user enters their search text. So this way it only shows the text input box and then when they type in their search the table results will THEN show.

I'm using this Javascript for the filtering:

  function ContactsearchFX() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";

      }
    }
  }
}

on a basic search table with this html code:

<input type="text" id="myInput"            onkeyup="ContactsearchFX()" placeholder="Search for           names..">

    Name
    Number

    contact
    number

    contact
    number

    contact
    number

....and so on.

Body:
window.onload = function() {
  var rows = document.querySelectorAll('tr:not(.header)');

  for (var i = 0; i < rows.length; i++) {
    rows[i].style.display = 'none';
  }
}

function ContactsearchFX() {
  var input, filter, table, tr, td, i;

  input = document.getElementById("myInput");

  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";

      }
    }
  }

   var rows = document.querySelectorAll('tr:not(.header)');

   if (input.value.length == 0) {
    for (var i = 0; i < rows.length; i++) {
      rows[i].style.display = 'none';
    }
  }
}

<input type="text" id="myInput" onkeyup="ContactsearchFX()" placeholder="Search for           names..">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Number</th>
  </tr>
  <tr>
    <td>test 1</td>
    <td>number</td>
  </tr>
  <tr>
    <td>test 2</td>
    <td>number</td>
  </tr>
  <tr>
    <td>test 3</td>
    <td>number</td>
  </tr>

This seems to do the trick! On the load of the window, it loops through all the table rows which do now have the class of header. So your header, is always visible.

Then as your code originally did, it goes through the table and filters out the ones that are matching.

After this, I just added in another loop which then sets the rows back to display: none if there is nothing that is in the input box.

Hope this is what you were looking for.


问:
Finding a dynamically added control on an aspx page
I have an asp page "A" and I've created a user control "B"

When I do A.Controls.Add(B), I would like to make an element, say a TableRow which is defined inside control "B", invisible via code behind.

When looking through Controls of "A", I cannot seem to find that table row.

Any hints?

I'm sure it is something really simple I'm missing.

Thank you.

答:
You should expose the controls that are modifiable and accessible from outside as properties.
 MSDN

But consider not to expose the whole control itself but only f.e. a Text-Property of a Textbox, because that prevents from unintentional and unpredictable behaviour.
A usercontrol should encapsulate complexity and should be (mostly) reusable. The more control you offer to the controls(f.e. the page) that use the usercontrol, the less reusable and the more error-phrone they are.

If you for example have built a Login-Control with a Textbox for the Username and a Textbox for the Password, it makes sense to offer properties named Username and Password instead of returning the Textboxes itself. The properties each return the respective  Textbox-Text value.

In your example with the TableRow, what is its purpose? You should expose a property with a meaningful name to control its visibility(f.e. ShowTitle if the row contains a title, the getter/setter would return/set the actual tablerow's visible state).

Of course you need a reference to your UserControl if you want to access its properties. You should provide sourcecode if you have problems on finding it on the page. It depends on where you have created and added it. Normally you will find controls with FindControl on the NamingContainer (f.e. the NamingContainer of a control defined in a GridView's TemplateColumn is the GridViewRow itself).


问:
Is it a good practice to cast from an interface to some concrete class when needed?
I'am developing a small system and i developed the classic generic repository. For now, i have the following architecture for my DAL.

```<code>public interface IRepositorio<T> where T : class
{
    T Get(long id);
    long Insert(T obj);
    bool Update(T obj);
    bool Delete(T obj);
}

public abstract class Repositorio<T> : IRepositorio<T> where T : class
{
    public IDbConnection Connection
    {
        get
        {
            return new SqlConnection(ConfigurationManager.ConnectionStrings["DBFila"].ConnectionString);
        }
    }

    public T Get(long id)
    {
        //...
    }

    public long Insert(T obj)
    {
        //...
    }

    public bool Update(T obj)
    {
        //...
    }

    public bool Delete(T obj)
    {
        //...
    }
}
</code>```

My concrete repository looks like this:

```<code>public class FilaRepositorio : Repositorio<FilaRepositorio>
{
    public FilaRepositorio()
    {
    }

    public void SomeCustomMethod()
    {
        // Some custom method
    }
}
</code>```

I am also using Simple Injector to follow the IoC and DI patterns, for this reason, when i try to call "SomeCustomMethod()" i dont have access to it (obviously). Look:

```<code>public class Processador
{
    private IRepositorio<FilaModel> _repoFila;
    public Processador(IRepositorio<FilaModel> repoFila)
    {
        _repoFila = repoFila;
    }

    public void Processar()
    {
        _repoFila.SomeCustomMethod(); // <-- wrong

        ((FilaRepositorio)_repoFila).SomeCustomMethod();// <-- works
    }
}
</code>```

Given this i have some questions:

Is a good or acceptable practice to make that cast (FilaRepositorio)?

If its not a good practice, how to write good code for this case?

答:
There are a few options available. The main problem with making the cast is that it is an implementation concern.

What would happen if the injected object was not a FilaRepositorio?

By making the cast you are tightly coupling the class to an implementation concern that is not guaranteed to be the inject dependency. Thus the constructor is not being entirely truthful about what it needs to perform its function.

This demonstrates the need to practice Explicit Dependencies Principle

The Explicit Dependencies Principle states:

Methods and classes should explicitly require (typically through
  method parameters or constructor parameters) any collaborating objects
  they need in order to function correctly.

One way to avoid it would be to make a derived interface that explicitly exposes the desired functionality of its dependents.

```<code>public interface IFilaRepositorio : IRepositorio<FilaModel> {
    void SomeCustomMethod();
}

public class FilaRepositorio : Repositorio<FilaModel>, IFilaRepositorio {
    public void SomeCustomMethod() {
        //...other code removed for brevity.
    }
}
</code>```

and have the Processador depend on that more targeted abstraction.

Now there is no need for the cast at all and the class explicitly expresses what it needs.

```<code>public class Processador {
    private readonly IFilaRepositorio _repoFila;

    public Processador(IFilaRepositorio  repoFila) {
        _repoFila = repoFila;
    }

    public void Processar() {
        _repoFila.SomeCustomMethod(); // <-- works
    }
}
</code>```

Body:
I'am developing a small system and i developed the classic generic repository. For now, i have the following architecture for my DAL.

public interface IRepositorio<T> where T : class
{
    T Get(long id);
    long Insert(T obj);
    bool Update(T obj);
    bool Delete(T obj);
}

public abstract class Repositorio<T> : IRepositorio<T> where T : class
{
    public IDbConnection Connection
    {
        get
        {
            return new SqlConnection(ConfigurationManager.ConnectionStrings["DBFila"].ConnectionString);
        }
    }

    public T Get(long id)
    {
        //...
    }

    public long Insert(T obj)
    {
        //...
    }

    public bool Update(T obj)
    {
        //...
    }

    public bool Delete(T obj)
    {
        //...
    }
}

My concrete repository looks like this:

public class FilaRepositorio : Repositorio<FilaRepositorio>
{
    public FilaRepositorio()
    {
    }

    public void SomeCustomMethod()
    {
        // Some custom method
    }
}

I am also using Simple Injector to follow the IoC and DI patterns, for this reason, when i try to call "SomeCustomMethod()" i dont have access to it (obviously). Look:

public class Processador
{
    private IRepositorio<FilaModel> _repoFila;
    public Processador(IRepositorio<FilaModel> repoFila)
    {
        _repoFila = repoFila;
    }

    public void Processar()
    {
        _repoFila.SomeCustomMethod(); // <-- wrong

        ((FilaRepositorio)_repoFila).SomeCustomMethod();// <-- works
    }
}

Given this i have some questions:

Is a good or acceptable practice to make that cast (FilaRepositorio)?

If its not a good practice, how to write good code for this case?

Body:
There are a few options available. The main problem with making the cast is that it is an implementation concern.

What would happen if the injected object was not a FilaRepositorio?

By making the cast you are tightly coupling the class to an implementation concern that is not guaranteed to be the inject dependency. Thus the constructor is not being entirely truthful about what it needs to perform its function.

This demonstrates the need to practice Explicit Dependencies Principle

The Explicit Dependencies Principle states:

Methods and classes should explicitly require (typically through
  method parameters or constructor parameters) any collaborating objects
  they need in order to function correctly.

One way to avoid it would be to make a derived interface that explicitly exposes the desired functionality of its dependents.

public interface IFilaRepositorio : IRepositorio<FilaModel> {
    void SomeCustomMethod();
}

public class FilaRepositorio : Repositorio<FilaModel>, IFilaRepositorio {
    public void SomeCustomMethod() {
        //...other code removed for brevity.
    }
}

and have the Processador depend on that more targeted abstraction.

Now there is no need for the cast at all and the class explicitly expresses what it needs.

public class Processador {
    private readonly IFilaRepositorio _repoFila;

    public Processador(IFilaRepositorio  repoFila) {
        _repoFila = repoFila;
    }

    public void Processar() {
        _repoFila.SomeCustomMethod(); // <-- works
    }
}


问:
URLEncoder not able to translate space character
I am expecting

```<code>System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8"));
</code>```

to output:

Hello%20World

(20 is ASCII Hex code for space)

However, what I get is:

Hello+World

Am I using the wrong method? What is the correct method I should be using?

答:
Am I using the wrong method? What is the correct method I should be using?

Yes, this method java.net.URLEncoder.encode wasn't made for converting " " to "20%" according to spec (source).

The space character " " is converted into a plus sign "+".

Even this is not the correct method, you can modify this to: System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replaceAll("\\+", "%20"));have a nice day =).

Body:
I am expecting

System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8"));

to output:

Hello%20World

(20 is ASCII Hex code for space)

However, what I get is:

Hello+World

Am I using the wrong method? What is the correct method I should be using?