问:
nth-child formula for hover state - all elements except the first one
I want to select all elements except the first one for a hover state. I'm doing this using nth-child() selector.

I'm following this guide: https://css-tricks.com/useful-nth-child-recipies/

It gives a formula for selecting all but the first 5 - the example they give is below:

```<code>li:nth-child(n+6) {
    color: green;
}
</code>```

I want to take this and apply it so that it selects all but the first element. My approach to do that is so:

```<code>li:nth-child(n+1) {
    color: green;
}
</code>```

Is this not correct?

I need to try to apply this to a hover state situation, where it only performs the :hover action all all but the first li. See the embed below:

  li {
    display: inline-block;
  }

  a {
    margin-right: 1.8rem;
      padding-bottom: 23px;
  }

  #login-signup li:nth-child(n+1):hover {
    text-decoration: none;
    border-bottom: 3px solid #292c2e;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="login-signup">
      <li> No Underline</li>
      <li>Log In</li>
      <li>Sign Up</li>
    </ul></code>```

How do you apply the formula for selecting anything but the first element with nth-child? Does :hover not work with nth-child? I can't find any sources that say otherwise.

答:
li {
  display: inline-block;
}
a {
  margin-right: 1.8rem;
  padding-bottom: 23px;
}
#login-signup li:not(:eq(0)):hover {
  text-decoration: none;
  border-bottom: 3px solid #292c2e;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="login-signup">
  <li> No Underline</li>
  <li>Log In</li>
  <li>Sign Up</li>
</ul></code>```

Body:
I want to select all elements except the first one for a hover state. I'm doing this using nth-child() selector.

I'm following this guide: https://css-tricks.com/useful-nth-child-recipies/

It gives a formula for selecting all but the first 5 - the example they give is below:

li:nth-child(n+6) {
    color: green;
}

I want to take this and apply it so that it selects all but the first element. My approach to do that is so:

li:nth-child(n+1) {
    color: green;
}

Is this not correct?

I need to try to apply this to a hover state situation, where it only performs the :hover action all all but the first li. See the embed below:

  li {
    display: inline-block;
  }

  a {
    margin-right: 1.8rem;
      padding-bottom: 23px;
  }

  #login-signup li:nth-child(n+1):hover {
    text-decoration: none;
    border-bottom: 3px solid #292c2e;
  }

 No Underline

Log In

Sign Up

How do you apply the formula for selecting anything but the first element with nth-child? Does :hover not work with nth-child? I can't find any sources that say otherwise.

Body:
li {
  display: inline-block;
}
a {
  margin-right: 1.8rem;
  padding-bottom: 23px;
}
#login-signup li:not(:eq(0)):hover {
  text-decoration: none;
  border-bottom: 3px solid #292c2e;
}

<ul id="login-signup">
  <li> <a href="#">No Underline</a></li>
  <li><a href="#">Log In</a></li>
  <li><a href="#">Sign Up</a></li>
</ul>


来源: stackexchange

问:
How can I override the Angular Material Purple?
I want to use the deeppurple-amber.css for Angular 2 Material, but instead of the deeppurple I want to overide that color with a different color, everything else should be exactly the same though. How best to achieve this?</p>

答:
Angular provides these pre-built themes

deeppurple-amber.css

indigo-pink.css

pink-bluegrey.css

purple-green.css

so if you are looking for any color which is listed in this then u may put it straight away by referencing the file directly.

but if not then u may have to build a custom theme this way link

[I tried changing colors in pre-built themes directly in the file , doesnt work . so create a theme file referencing the deeppurple file then add a new entry to your styles]

ContentLicense: CC BY-SA 3.0


问:
Amazon S3 Can't Delete Object via API
I'm setting up a new policy so my website can store images on S3, and I'm trying to keep it as secure as possible.

I can put an object and read it, but can not delete it, even though it appears I've followed the recommendations from Amazon. I am not using versioning.

What am I doing wrong?

Here's my policy

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObjectAcl",
                "s3:GetObject",
                "s3:DeleteObjectVersion",
                "s3:PutLifecycleConfiguration",
                "s3:DeleteObject",
                "s3:ListObjects"
            ],
            "Resource": "*"
        }
    ]
}
</code>```

答: After screwing around with multiple permission actions it turns out I needed to add s3:ListBucket and s3:ListObjects. Once added I can now delete objects.

Title: Amazon S3 Can't Delete Object via API

Body:
I'm setting up a new policy so my website can store images on S3, and I'm trying to keep it as secure as possible.

I can put an object and read it, but can not delete it, even though it appears I've followed the recommendations from Amazon. I am not using versioning.

What am I doing wrong?

Here's my policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObjectAcl",
                "s3:GetObject",
                "s3:DeleteObjectVersion",
                "s3:PutLifecycleConfiguration",
                "s3:DeleteObject",
                "s3:ListObjects"
            ],
            "Resource": "*"
        }
    ]
}


问:
Why am I unable to enter the php page via the AJAX call?
My HTML and PHP code is given below, I'm able to receive the mail.value in txt but faltering during the AJAX call, it doesn't even enter error.

Can someone help me rectify the error so I'm able to pass the AJAX call and get the value sent to the php page.

There is the same piece of code which works for me on the login page, but it it isn't working for the newaccount page.

HTML code:

```<code><script src="jquery-3.2.1.js"></script>
<script>

function check()
    {
       var mail=document.getElementById("mail");
       var password=document.getElementById("password");
       var First_name=document.getElementById("First_name");
       var Last_name=document.getElementById("Last_name");
       var st_number=document.getElementById("st_number");
       var st_name=document.getElementById("st_name");
       var zip=document.getElementById("zip");
       var Phone=document.getElementById("phone");
       var Gender=document.getElementsByClassName("gender");
       var age=document.getElementById("age");
       var account=document.getElementById("account");
       document.getElementById("txt").innerHTML=mail.value;

        $.ajax({
url: "newacc.php?",
data: {
    "account": account.value,
    "Email": mail.value,
    "Pass": password.value,
    "FirstName": First_name.value,
    "LastName": Last_name.value,
    "Phone":Phone.value,
    "age": age.value,
    "Gender": Gender.value,
    "st_number": st_number.value,
    "st_name": st_name.value,
    "zip": zip.value
},
    cache: false,
    type: "POST",
    success: function(response) {
     document.getElementById("txt").innerHTML= "this is it";

    },
    error: function(xhr) {
      document.getElementById("txt").innerHTML= "No";
    }
});

  }

</script>
</code>```

PHP code:

```<code><?php
echo "Check";
$servername ="localhost";
$username = "root";
$password ="root";
$dbname ="pitt_store";
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected so successfully";
$account = $_POST["account"];
echo "The address is $account";
$email = $_POST["Email"];
echo "The email is $email";
$password = $_POST["Pass"];
echo "The Password is $password";
$first_name = $_POST["FirstName"];
echo "The FNAME is $first_name";
$last_name = $_POST["LastName"];
echo "The LNAME is $last_name";
$phone = $_POST["Phone"];
echo "The phone number is $phone";
$age = $_POST["age"];
echo "The age is $age";
$gender = $_POST["Gender"];
echo "The gender is $gender";
$st_number = $_POST["st_number"];
echo "The street number is $st_number";
$st_name = $_POST["st_name"];
echo "The street name is $st_name";
$zip = $_POST["zip"];
echo "The zip is $zip";

/*$sql= "INSERT INTO Customer(first_name,last_name,email,password) VALUES('$first_name'
,'$last_name','$email','$password')";
if ($conn->query($sql) == TRUE)
{
  echo "Record added successfully";
}
else
{
  echo "Error adding record: " . $conn->error;
}*/
$conn->close();
?>
</code>```

答: The reason this was happening was because one of my parameters was giving an undefined value. </p>

Body:
My HTML and PHP code is given below, I'm able to receive the mail.value in txt but faltering during the AJAX call, it doesn't even enter error.

Can someone help me rectify the error so I'm able to pass the AJAX call and get the value sent to the php page.

There is the same piece of code which works for me on the login page, but it it isn't working for the newaccount page.

HTML code:

PHP code:

<?php
echo "Check";
$servername ="localhost";
$username = "root";
$password ="root";
$dbname ="pitt_store";
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected so successfully";
$account = $_POST["account"];
echo "The address is $account";
$email = $_POST["Email"];
echo "The email is $email";
$password = $_POST["Pass"];
echo "The Password is $password";
$first_name = $_POST["FirstName"];
echo "The FNAME is $first_name";
$last_name = $_POST["LastName"];
echo "The LNAME is $last_name";
$phone = $_POST["Phone"];
echo "The phone number is $phone";
$age = $_POST["age"];
echo "The age is $age";
$gender = $_POST["Gender"];
echo "The gender is $gender";
$st_number = $_POST["st_number"];
echo "The street number is $st_number";
$st_name = $_POST["st_name"];
echo "The street name is $st_name";
$zip = $_POST["zip"];
echo "The zip is $zip";

/*$sql= "INSERT INTO Customer(first_name,last_name,email,password) VALUES('$first_name'
,'$last_name','$email','$password')";
if ($conn->query($sql) == TRUE)
{
  echo "Record added successfully";
}
else
{
  echo "Error adding record: " . $conn->error;
}*/
$conn->close();
?>


问:
difficulty to define the monad on all values
I trying to write monad that multiply all data nodes by given number.
I don't know how to define the Monad correctly.

```<code>module Main where
data LinkedList a = NodeWithoutNext a | Node a (LinkedList a) deriving (Show)

instance Functor LinkedList where
  fmap f (NodeWithoutNext x) = NodeWithoutNext (f x)
  fmap f (Node a next) = Node (f a) (fmap f next)

instance Applicative LinkedList where
   pure = NodeWithoutNext
   (NodeWithoutNext f) <*> (NodeWithoutNext x) = NodeWithoutNext (f x)
   (NodeWithoutNext f) <*> (Node a next) = Node (f a) (fmap f next)

instance Monad LinkedList where
   return = NodeWithoutNext
   (NodeWithoutNext a) >>= f = f a
   **(Node a next) >>= f =  Node (f a) (next >>= f)**

main :: IO ()
main  =  do
    let list = Node 3 (Node 2 (NodeWithoutNext 7))
    print (list)
    print (list >>= (\x -> NodeWithoutNext (x+200)))
</code>```

I get error-

```<code>Bla.hs:16:39: error:
    * Couldn't match type `b' with `LinkedList b'
      `b' is a rigid type variable bound by
        the type signature for:
          (>>=) :: forall a b.
                   LinkedList a -> (a -> LinkedList b) -> Linked
        at Bla.hs:15:24-26
      Expected type: LinkedList (LinkedList b)
        Actual type: LinkedList b
    * In the second argument of `Node', namely `(next >>= f)'
      In the expression: Node (f a) (next >>= f)
      In an equation for `>>=':
          (Node a next) >>= f = Node (f a) (next >>= f)
    * Relevant bindings include
        f :: a -> LinkedList b (bound at Bla.hs:16:22)
        (>>=) :: LinkedList a -> (a -> LinkedList b) -> LinkedLi
          (bound at Bla.hs:15:24)
   |
16 |    (Node a next) >>= f =  Node (f a) (next >>= f)
   |                                       ^^^^^^^^^^
</code>```

What do I need to fix here?
The problem is on the line that is with **.

答:
The type system will complain, since the "bind" operator >>= has signature:

```<code><b>(>>=) :: Monad m => m a -> (a -> m b) -> m b</b></code>```

So let us specialize the signature for the LinkedList:

```<code>(>>=) :: <b>LinkedList a</b> -> (a -> <b>LinkedList b</b>) -> <b>LinkedList b</b></code>```

So the function takes at the left side a LinkedList a, and at the right side a function that maps an a (!) to a LinkedList b, and we expect the outcome to be a LinkedList b. The function you have defined can not do that: since if you construct a Node (f a) (next >>= f), the result will be a LinkedList (LinkedList b). Indeed, you apply f to a (the head of the list), which yields a LinkedList b (as head of the Node).

If we look at the signature above, there are perhaps some ideas that might come up, but the most straightforward idea, is probably to implement some sort of concatMap :: [a] -> (a -> [b]) -> [b]. The "bind" has to satisfy the following rules:

return a >>= k  =  k a;

m >>= return  =  m; and

m >>= (\x -> k x >>= h)  =  (m >>= k) >>= h.

the concatMap function satisfies the three constraints. (1) If we wrap a value x into a LinkedList, and apply f on every element (of the singleton list), we will obtain a list that contains one list, that of the result of k a, but by using the concat of concatMap, we flatten this again. (2) If we would use m >>= return with concat, we will wrap every element in a new singleton list, but the concatenation, will unwrap it again.

So we can implement it as:

```<code>instance Monad LinkedList where
   return = NodeWithoutNext
   (NodeWithoutNext a) >>= f = f a
   (Node a next) >>= f =  build (f a)
       where build (NodeWithoutNext x) = (Node x (next >>= f))
             build (Node x xs) = Node x (build xs)
</code>```

So here build will iterate through the LinkedList produced by f a, and basically construct an almost duplicate, except that when we reach the end, we will continue with the concatenation of the outcome of the bind of the remaining elements.

Body:
I trying to write monad that multiply all data nodes by given number.
I don't know how to define the Monad correctly.

module Main where
data LinkedList a = NodeWithoutNext a | Node a (LinkedList a) deriving (Show)

instance Functor LinkedList where
  fmap f (NodeWithoutNext x) = NodeWithoutNext (f x)
  fmap f (Node a next) = Node (f a) (fmap f next)

instance Applicative LinkedList where
   pure = NodeWithoutNext
   (NodeWithoutNext f) <*> (NodeWithoutNext x) = NodeWithoutNext (f x)
   (NodeWithoutNext f) <*> (Node a next) = Node (f a) (fmap f next)

instance Monad LinkedList where
   return = NodeWithoutNext
   (NodeWithoutNext a) >>= f = f a
   **(Node a next) >>= f =  Node (f a) (next >>= f)**

main :: IO ()
main  =  do
    let list = Node 3 (Node 2 (NodeWithoutNext 7))
    print (list)
    print (list >>= (\x -> NodeWithoutNext (x+200)))

I get error-

Bla.hs:16:39: error:
    * Couldn't match type `b' with `LinkedList b'
      `b' is a rigid type variable bound by
        the type signature for:
          (>>=) :: forall a b.
                   LinkedList a -> (a -> LinkedList b) -> Linked
        at Bla.hs:15:24-26
      Expected type: LinkedList (LinkedList b)
        Actual type: LinkedList b
    * In the second argument of `Node', namely `(next >>= f)'
      In the expression: Node (f a) (next >>= f)
      In an equation for `>>=':
          (Node a next) >>= f = Node (f a) (next >>= f)
    * Relevant bindings include
        f :: a -> LinkedList b (bound at Bla.hs:16:22)
        (>>=) :: LinkedList a -> (a -> LinkedList b) -> LinkedLi
          (bound at Bla.hs:15:24)
   |
16 |    (Node a next) >>= f =  Node (f a) (next >>= f)
   |                                       ^^^^^^^^^^

What do I need to fix here?
The problem is on the line that is with **.

Body:
The type system will complain, since the "bind" operator >>= has signature:

(>>=) :: Monad m => m a -> (a -> m b) -> m b

So let us specialize the signature for the LinkedList:

(>>=) :: LinkedList a -> (a -> LinkedList b) -> LinkedList b

So the function takes at the left side a LinkedList a, and at the right side a function that maps an a (!) to a LinkedList b, and we expect the outcome to be a LinkedList b. The function you have defined can not do that: since if you construct a Node (f a) (next >>= f), the result will be a LinkedList (LinkedList b). Indeed, you apply f to a (the head of the list), which yields a LinkedList b (as head of the Node).

If we look at the signature above, there are perhaps some ideas that might come up, but the most straightforward idea, is probably to implement some sort of concatMap :: [a] -> (a -> [b]) -> [b]. The "bind" has to satisfy the following rules:

return a >>= k  =  k a;

m >>= return  =  m; and

m >>= (\x -> k x >>= h)  =  (m >>= k) >>= h.

the concatMap function satisfies the three constraints. (1) If we wrap a value x into a LinkedList, and apply f on every element (of the singleton list), we will obtain a list that contains one list, that of the result of k a, but by using the concat of concatMap, we flatten this again. (2) If we would use m >>= return with concat, we will wrap every element in a new singleton list, but the concatenation, will unwrap it again.

So we can implement it as:

instance Monad LinkedList where
   return = NodeWithoutNext
   (NodeWithoutNext a) >>= f = f a
   (Node a next) >>= f =  build (f a)
       where build (NodeWithoutNext x) = (Node x (next >>= f))
             build (Node x xs) = Node x (build xs)

So here build will iterate through the LinkedList produced by f a, and basically construct an almost duplicate, except that when we reach the end, we will continue with the concatenation of the outcome of the bind of the remaining elements.


问:
path to adjacency matrix in networkx
I'm trying to convert paths in graphs in into adjacency matrix using the networkx library.
I can convert a whole graph into an adjacency matrix:

```<code>>>>import networkx as nx
>>>DG=nx.DiGraph()
>>>DG.add_edges_from([(1,2), (2,3),(1,3)])
>>>nx.to_numpy_matrix(DG)
....matrix([[ 0.,  1.,  1.],
    [ 0.,  0.,  1.],
    [ 0.,  0.,  0.]])
</code>```

However, after I find all simple paths from node 1 to node 3:

```<code>>>>list(nx.all_simple_paths(DG,1,3))
....[[1, 2, 3], [1, 3]]
</code>```

I'm unable to turn them into an adjacency matrix.
I want to be able to choose a path and turn it into an adjacency matrix,
for example, the second path should return:

```<code>....matrix([[ 0.,  0.,  1.],
    [ 0.,  0.,  0.],
    [ 0.,  0.,  0.]])
</code>```

答:
That is not an adjacency matrix. But you can easily build it yourself as follows:

```<code>import networkx as nx
import numpy as np

DG=nx.DiGraph()
DG.add_edges_from([(1,2), (2,3),(1,3)])
paths = list(nx.all_simple_paths(DG,1,3))

for path in paths:
    matrix = np.matrix(np.zeros((len(DG), len(DG))))
    for i in range(len(path)-1):
        matrix[path[i]-1], path[i+1]-1] = 1  # edit: credits to @Joel
    print(matrix)
</code>```

output:

```<code>[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 0.  0.  0.]]
[[ 0.  0.  1.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]
</code>```

Title: path to adjacency matrix in networkx

Body:
I'm trying to convert paths in graphs in into adjacency matrix using the networkx library.
I can convert a whole graph into an adjacency matrix:

>>>import networkx as nx
>>>DG=nx.DiGraph()
>>>DG.add_edges_from([(1,2), (2,3),(1,3)])
>>>nx.to_numpy_matrix(DG)
....matrix([[ 0.,  1.,  1.],
    [ 0.,  0.,  1.],
    [ 0.,  0.,  0.]])

However, after I find all simple paths from node 1 to node 3:

>>>list(nx.all_simple_paths(DG,1,3))
....[[1, 2, 3], [1, 3]]

I'm unable to turn them into an adjacency matrix.
I want to be able to choose a path and turn it into an adjacency matrix,
for example, the second path should return:

....matrix([[ 0.,  0.,  1.],
    [ 0.,  0.,  0.],
    [ 0.,  0.,  0.]])

Body:
That is not an adjacency matrix. But you can easily build it yourself as follows:

import networkx as nx
import numpy as np

DG=nx.DiGraph()
DG.add_edges_from([(1,2), (2,3),(1,3)])
paths = list(nx.all_simple_paths(DG,1,3))

for path in paths:
    matrix = np.matrix(np.zeros((len(DG), len(DG))))
    for i in range(len(path)-1):
        matrix[path[i]-1], path[i+1]-1] = 1  # edit: credits to @Joel
    print(matrix)

output:

[[ 0.  1.  0.]
 [ 0.  0.  1.]
 [ 0.  0.  0.]]
[[ 0.  0.  1.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]


问:
Where can I download a windows binary of Windres (part of Binutils)?
Can't find any prebuilt binaries for Windows. Does anybody know a place where I can get them?</p>

答: It comes with MinGW. You can download the installer here.</p>

ContentLicense: CC BY-SA 2.5


问:
How to group a list of dicts?
I have a list of dicts

```<code>[
  {"day":"10", "car":"bmw", "count":"3"},
  {"day":"10", "car":"audi", "count":"2"},
  {"day":"10", "car":"jeep", "count":"4"},
  {"day":"11", "car":"bmw", "count":"6"},
  {"day":"11", "car":"audi", "count":"7"},
  {"day":"11", "car":"jeep", "count":"8"},
]
</code>```

I want to convert it to like this (desired output)

```<code>[
      {"day":"10", "bmw":"3","audi":"2","jeep":"4"},
      {"day":"11","bmw":"6","audi":"7","jeep":"8"},
]
</code>```

this is what i did. is there any better and optimal way to achieve this.

```<code>def dl():
    list_of_dicts = [
            {"day":"10", "car":"bmw", "count":"3"},
            {"day":"10", "car":"audi", "count":"2"},
            {"day":"10", "car":"jeep", "count":"4"},
            {"day":"11", "car":"bmw", "count":"6"},
            {"day":"11", "car":"audi", "count":"7"},
            {"day":"11", "car":"jeep", "count":"8"},
            ]

    result = []
    data = {}

    for item in list_of_dicts:

        if not data.get(item["day"], False):
            data[item["day"]] = []
            data[item["day"]].append({item["car"]:item["count"]})

        else:
            data[item["day"]].append({item["car"]:item["count"]})

    for key in data:
        new_dict = {}
        new_dict["day"] = key
        for item in data[key]:
            new_dict.update(item)
        result.append(new_dict)

    print result
    return result

dl()
</code>```

If the question is not correct somebody please help me to

correct this question . i am a beginner

答:
Use itertools.groupby to group based on the day, then create a new dict for each day:

```<code>list_of_dicts = [
  {"day":"10", "car":"bmw", "count":"3"},
  {"day":"10", "car":"audi", "count":"2"},
  {"day":"10", "car":"jeep", "count":"4"},
  {"day":"11", "car":"bmw", "count":"6"},
  {"day":"11", "car":"audi", "count":"7"},
  {"day":"11", "car":"jeep", "count":"8"},
]

# to use groupby the list must be sorted
list_of_dicts.sort(key=operator.itemgetter("day"))

result_list = []
for day, dicts_for_that_day in itertools.groupby(list_of_dicts, key=operator.itemgetter("day")):
    day_dict = {'day': day}
    day_dict.update({d['car']: d['count'] for d in dicts_for_that_day})
    result_list.append(day_dict)

print(result_list)
</code>```

Title: How to group a list of dicts?

Body:
I have a list of dicts

[
  {"day":"10", "car":"bmw", "count":"3"},
  {"day":"10", "car":"audi", "count":"2"},
  {"day":"10", "car":"jeep", "count":"4"},
  {"day":"11", "car":"bmw", "count":"6"},
  {"day":"11", "car":"audi", "count":"7"},
  {"day":"11", "car":"jeep", "count":"8"},
]

I want to convert it to like this (desired output)

[
      {"day":"10", "bmw":"3","audi":"2","jeep":"4"},
      {"day":"11","bmw":"6","audi":"7","jeep":"8"},
]

this is what i did. is there any better and optimal way to achieve this.

def dl():
    list_of_dicts = [
            {"day":"10", "car":"bmw", "count":"3"},
            {"day":"10", "car":"audi", "count":"2"},
            {"day":"10", "car":"jeep", "count":"4"},
            {"day":"11", "car":"bmw", "count":"6"},
            {"day":"11", "car":"audi", "count":"7"},
            {"day":"11", "car":"jeep", "count":"8"},
            ]

    result = []
    data = {}

    for item in list_of_dicts:

        if not data.get(item["day"], False):
            data[item["day"]] = []
            data[item["day"]].append({item["car"]:item["count"]})

        else:
            data[item["day"]].append({item["car"]:item["count"]})

    for key in data:
        new_dict = {}
        new_dict["day"] = key
        for item in data[key]:
            new_dict.update(item)
        result.append(new_dict)

    print result
    return result

dl()

If the question is not correct somebody please help me to

correct this question . i am a beginner

Body:
Use itertools.groupby to group based on the day, then create a new dict for each day:

list_of_dicts = [
  {"day":"10", "car":"bmw", "count":"3"},
  {"day":"10", "car":"audi", "count":"2"},
  {"day":"10", "car":"jeep", "count":"4"},
  {"day":"11", "car":"bmw", "count":"6"},
  {"day":"11", "car":"audi", "count":"7"},
  {"day":"11", "car":"jeep", "count":"8"},
]

# to use groupby the list must be sorted
list_of_dicts.sort(key=operator.itemgetter("day"))

result_list = []
for day, dicts_for_that_day in itertools.groupby(list_of_dicts, key=operator.itemgetter("day")):
    day_dict = {'day': day}
    day_dict.update({d['car']: d['count'] for d in dicts_for_that_day})
    result_list.append(day_dict)

print(result_list)


问:
Snap to center of a cell when scrolling UICollectionView horizontally
I know some people have asked this question before but they were all about UITableViews or UIScrollViews and I couldn't get the accepted solution to work for me. What I would like is the snapping effect when scrolling through my UICollectionView horizontally - much like what happens in the iOS AppStore. iOS 9+ is my target build so please look at the UIKit changes before answering this.

Thanks.

答:
If you want simple native behavior, without customization:

```<code>collectionView.pagingEnabled = YES;
</code>```

This only works properly when the size of the collection view layout items are all one size only and the UICollectionViewCell's clipToBounds property is set to YES.

ContentLicense: CC BY-SA 4.0

Body:
If you want simple native behavior, without customization:

collectionView.pagingEnabled = YES;

This only works properly when the size of the collection view layout items are all one size only and the UICollectionViewCell's clipToBounds property is set to YES.


问:
Values not being submitted from PHP HTML form
I am trying to take the input from drop down menus that users enter and submit them to a table in my database. I am trying to submit the values into this table:
I use the POST to check that the values are being pulled from the HTML form and they are, but they won't submit into my table. I've made sure that all of the names with the columns and HTML forms are correct, why won't the values post to the table?

```<code><?php

$databaseName = 'pizza_db';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected sucessfully\n";

if(isset($_POST['submit'])){
$value = mysqli_real_escape_string($conn,$_POST['drink']);
$value2 = mysqli_real_escape_string($conn,$_POST['cheese']);
$value3 = mysqli_real_escape_string($conn,$_POST['veggies']);
$value4 = mysqli_real_escape_string($conn,$_POST['meat']);
$value5 = mysqli_real_escape_string($conn,$_POST['sauce']);
$value6 = mysqli_real_escape_string($conn,$_POST['crust']);
$value7 = mysqli_real_escape_string($conn,$_POST['size']);

$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
    VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";

//Here I am posting the values to check that they are being submitted
echo $_POST["size"];
echo "\n";
echo $_POST["sauce"];
echo "\n";
echo $_POST["crust"];
echo "\n";
echo $_POST["cheese"];
echo "\n";
echo $_POST["meat"];
echo "\n";
echo $_POST["veggies"];
echo "\n";
echo $_POST["drink"];
$conn->close();
}
?>

<!DOCTYPE html>
<html>
<body>
<form action='' method='post'>

<p>Choose a size<p>
<select id="size" name="size">
  <option value="small">Small</option>
  <option value="medium">Medium</option>
  <option value="large">Large</option>
  <option value="x-large">X-large</option>
</select>

<p> Choose a sauce <p>
<select id="sauce" name="sauce">
  <option value="none">None</option>
  <option value="marinara">Marinara</option>
  <option value="alfredo">Alfredo</option>
  <option value="ranch">Ranch</option>
  <option value="bbq">BBQ</option>
</select>

<p> Choose a cheese<p>
<select id="cheese" name="cheese">
  <option value="none">None</option>
  <option value="mozzarelaa">Mozarella</option>
  <option value="cheddar">Cheddar</option>
  <option value="parmesan">Parmesan</option>
  <option value="three cheese">Three-Cheese</option>
</select>

<p> Choose a meat <p>
<select id="meat" name="meat">
  <option value="none">None</option>
  <option value="Pepperroni">Pepperroni</option>
  <option value="sausage">Sausage</option>
  <option value="bacon">Bacon</option>
  <option value="canadian bacon">Canadian Bacon</option>
  <option value="chicken">Chicken</option>
  <option value="salami">Beef</option>
  <option value="anchovies">Anchovies</option>
</select>

<p> Choose a veggies <p>
<select id="veggies" name="veggies">
  <option value="none">None</option>
  <option value="onions">Onions</option>
  <option value="green peppers">Green Peppers</option>
  <option value="Red peppers">Red peppers</option>
  <option value="Black olives">Mushrooms</option>
   <option value="jalapenos">Jalapenos</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="pineapple">Pineapple</option>
</select>

<p> Choose a crust <p>
<select id="crust" name="crust">
  <option value="regular">Regular</option>
  <option value="deep-dish">Deep-dish</option>
  <option value="thin-crust">Thin Crust</option>
  <option value="stuffed crust">Stuffed Crust</option>
  <option value="gluten free">Gluten Free</option>
</select>

<p> Choose a drink <p>
<select id="drink" name="drink">
  <option value="none">None</option>
  <option value="rootbeer">Root Beer</option>
  <option value="coke">Coke</option>
  <option value="diet coke">Diet Coke</option>
  <option value="dr pepper">Dr Pepper</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
</code>```

答:
You prepared string query but you are not executing it.

```<code>$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";

// run query with below mentioned function
mysqli_query($conn, $sql);
</code>```

Then check your table. You will see the data saved.

Body:
I am trying to take the input from drop down menus that users enter and submit them to a table in my database. I am trying to submit the values into this table:
I use the POST to check that the values are being pulled from the HTML form and they are, but they won't submit into my table. I've made sure that all of the names with the columns and HTML forms are correct, why won't the values post to the table?

<?php

$databaseName = 'pizza_db';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected sucessfully\n";

if(isset($_POST['submit'])){
$value = mysqli_real_escape_string($conn,$_POST['drink']);
$value2 = mysqli_real_escape_string($conn,$_POST['cheese']);
$value3 = mysqli_real_escape_string($conn,$_POST['veggies']);
$value4 = mysqli_real_escape_string($conn,$_POST['meat']);
$value5 = mysqli_real_escape_string($conn,$_POST['sauce']);
$value6 = mysqli_real_escape_string($conn,$_POST['crust']);
$value7 = mysqli_real_escape_string($conn,$_POST['size']);

$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
    VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";

//Here I am posting the values to check that they are being submitted
echo $_POST["size"];
echo "\n";
echo $_POST["sauce"];
echo "\n";
echo $_POST["crust"];
echo "\n";
echo $_POST["cheese"];
echo "\n";
echo $_POST["meat"];
echo "\n";
echo $_POST["veggies"];
echo "\n";
echo $_POST["drink"];
$conn->close();
}
?>

<!DOCTYPE html>

<form action='' method='post'>

Choose a size

<select id="size" name="size">
  <option value="small">Small</option>
  <option value="medium">Medium</option>
  <option value="large">Large</option>
  <option value="x-large">X-large</option>
</select>

 Choose a sauce

<select id="sauce" name="sauce">
  <option value="none">None</option>
  <option value="marinara">Marinara</option>
  <option value="alfredo">Alfredo</option>
  <option value="ranch">Ranch</option>
  <option value="bbq">BBQ</option>
</select>

 Choose a cheese

<select id="cheese" name="cheese">
  <option value="none">None</option>
  <option value="mozzarelaa">Mozarella</option>
  <option value="cheddar">Cheddar</option>
  <option value="parmesan">Parmesan</option>
  <option value="three cheese">Three-Cheese</option>
</select>

 Choose a meat

<select id="meat" name="meat">
  <option value="none">None</option>
  <option value="Pepperroni">Pepperroni</option>
  <option value="sausage">Sausage</option>
  <option value="bacon">Bacon</option>
  <option value="canadian bacon">Canadian Bacon</option>
  <option value="chicken">Chicken</option>
  <option value="salami">Beef</option>
  <option value="anchovies">Anchovies</option>
</select>

 Choose a veggies

<select id="veggies" name="veggies">
  <option value="none">None</option>
  <option value="onions">Onions</option>
  <option value="green peppers">Green Peppers</option>
  <option value="Red peppers">Red peppers</option>
  <option value="Black olives">Mushrooms</option>
   <option value="jalapenos">Jalapenos</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="pineapple">Pineapple</option>
</select>

 Choose a crust

<select id="crust" name="crust">
  <option value="regular">Regular</option>
  <option value="deep-dish">Deep-dish</option>
  <option value="thin-crust">Thin Crust</option>
  <option value="stuffed crust">Stuffed Crust</option>
  <option value="gluten free">Gluten Free</option>
</select>

 Choose a drink

<select id="drink" name="drink">
  <option value="none">None</option>
  <option value="rootbeer">Root Beer</option>
  <option value="coke">Coke</option>
  <option value="diet coke">Diet Coke</option>
  <option value="dr pepper">Dr Pepper</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>

Body:
You prepared string query but you are not executing it.

$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";

// run query with below mentioned function
mysqli_query($conn, $sql);

Then check your table. You will see the data saved.


问:
Debug ionic3 app for building it with --prod flag
For a while, I didn't build my ionic3 app with --prod flag, it used to work fine, but I've made quite a few changes since that. Now when I run ionic cordova build android --prod I get this error message:

```<code>TypeError: Cannot read property 'length' of undefined
    at Object.unescapeIdentifier (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:10550:26)
    at getTextOfNode (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:68575:27)
    at emitIdentifier (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66931:19)
    at pipelineEmitUnspecified (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66594:28)
    at pipelineEmitWithHint (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66566:50)
    at pipelineEmitWithSourceMap (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66558:17)
    at emitNodeWithComments (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:64200:17)
    at pipelineEmitWithComments (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66547:17)
    at pipelineEmitWithNotification (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66541:17)
    at emit (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66528:13)
</code>```

The app builds and run fine without --prod flag.

I understand the problem comes from an undefined property that could not be read and therefore typescript refuse to compile the code.

My problem is that I've no idea where that length property is in my app, since there are plenty of them.
Is there a way to get more info about where that property is situated in my code, from typescript or ionic, so that I can correct this error and be able to build the app with --prod flag?

答: It seems a problem with one of your node_modules item or items. So delete node_modules folder and then run npm i

Body:
For a while, I didn't build my ionic3 app with --prod flag, it used to work fine, but I've made quite a few changes since that. Now when I run ionic cordova build android --prod I get this error message:

TypeError: Cannot read property 'length' of undefined
    at Object.unescapeIdentifier (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:10550:26)
    at getTextOfNode (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:68575:27)
    at emitIdentifier (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66931:19)
    at pipelineEmitUnspecified (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66594:28)
    at pipelineEmitWithHint (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66566:50)
    at pipelineEmitWithSourceMap (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66558:17)
    at emitNodeWithComments (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:64200:17)
    at pipelineEmitWithComments (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66547:17)
    at pipelineEmitWithNotification (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66541:17)
    at emit (/path/to/my/app/node_modules/@angular/compiler-cli/node_modules/typescript/lib/typescript.js:66528:13)

The app builds and run fine without --prod flag.

I understand the problem comes from an undefined property that could not be read and therefore typescript refuse to compile the code.

My problem is that I've no idea where that length property is in my app, since there are plenty of them.
Is there a way to get more info about where that property is situated in my code, from typescript or ionic, so that I can correct this error and be able to build the app with --prod flag?


问:
Cannot query or scan DynamoDB in Unity

TLDR: Can't create an AsyncSearch object from QueryAsync or ScanAsync without running into a weird ArgumentNullException deep inside the AWS library.

I'm developing an online game in Unity and want to synchronize data with DynamoDB. When I only had a table with player data this worked very well. I would just use "DBContext.LoadAsync(id, callback);" and it works flawlessly. Saving with "SaveAsync" works just as well.

Now I introduced some more tables and I need to perform scans and queries. For testing purposes, I gave my Unity app all the rights it can possibly have (I used "dynamodb:*" and "Resource": ["*"] in IAM).

I tried basically all the possible versions of ScanAsync, QueryAsync and FromQueryAsync with different parameters but I just always get an error.

Simple example: I want to download all departments (of my university):

```<code>AsyncSearch<DepartmentData> search = AWSManager.Instance.DBContext.ScanAsync<DepartmentData>();
</code>```

This call already fails, before I can do anything like "search.GetRemainingAsync(callback)". The same goes for for simple queries like:

```<code>AsyncSearch<POIVisit> query = AWSManager.Instance.DBContext.QueryAsync<POIVisit>(poiType);
</code>```

The error is the following and is somewhere deep in the AWS library, so I can't really go in there, set some breakpoints and see what exactly is failing:

```<code>ArgumentNullException: Argument cannot be null.
Parameter name: key
System.Collections.Generic.Dictionary`2[System.Type,Amazon.Runtime.IExceptionHandler].TryGetValue (System.Type key, IExceptionHandler& value) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:588)
Amazon.Runtime.Internal.ErrorHandler.ProcessException (IExecutionContext executionContext, System.Exception exception) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/ErrorHandler/ErrorHandler.cs:202)
Amazon.Runtime.Internal.ErrorHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/ErrorHandler/ErrorHandler.cs:78)
Amazon.Runtime.Internal.PipelineHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/PipelineHandler.cs:57)
Amazon.Runtime.Internal.CallbackHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/CallbackHandler.cs:45)
Amazon.Runtime.Internal.PipelineHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/PipelineHandler.cs:57)
Amazon.Runtime.Internal.Signer.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/Signer.cs:38)
Amazon.Runtime.Internal.PipelineHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/PipelineHandler.cs:57)
Amazon.Runtime.Internal.CredentialsRetriever.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/CredentialsRetriever.cs:72)
Amazon.Runtime.Internal.PipelineHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/PipelineHandler.cs:57)
Amazon.Runtime.Internal.RetryHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/RetryHandler.cs:74)
</code>```

It gets even worse, if I want to query based on a secondary index. For that, I need to attach a DynamoDBOperationConfig after the conditions for hash and range key like so:

```<code>var queryConfig = new DynamoDBOperationConfig() { IndexName = "PlayerIndex" };
AsyncSearch<POIVisit> query = AWSManager.Instance.DBContext.QueryAsync<POIVisit>(poiType, QueryOperator.Equal, PlayerID, queryConfig);
</code>```

Now, it somehow seems to think, the queryConfig is just another value for the range key (so it basically chooses the wrong overloaded  version of  QueryAsync). Or at least I think that's what happens, because I get a weird conversion error now:

```<code>InvalidCastException: Cannot cast from source type to destination type.
Amazon.DynamoDBv2.Converter`1[T].TryTo (System.Object value, Amazon.DynamoDBv2.DocumentModel.Primitive& p) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Services/DynamoDBv2/Custom/Conversion/DynamoDBEntryConversion.cs:630)
…
Amazon.DynamoDBv2.DataModel.DynamoDBContext.QueryAsync[POIVisit] (System.Object hashKeyValue, QueryOperator op, System.Object[] values) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Services/DynamoDBv2/Custom/DataModel/_unity/Context.Async.cs:550)
DBManager.RetrievePlayerVisits (System.String poiType, UnityEngine.Events.UnityAction`1 callback) (at Assets/Scripts/Managers/DBManager.cs:359)
</code>```

My Unity version is 5.6.3f1. I tried AWSSDK.DynamoDBv2.3.3.4.18 and the older AWSSDK.DynamoDBv2.3.3.4.14 Unity packages containing the AWS SDK downloaded directly from Amazon.

If someone has a hint what I could be doing wrong, I'd be really grateful, thanks!

答:
You need to build a request object before you create a query. I've never used Unity but it should be something like

```<code>var request = new QueryRequest();
request.TableName = "YourTable";
request.KeyConditions = new Dictionary<string, Condition>()
{
    {
        "YourId",  new Condition()
        {
            ComparisonOperator = "EQ",
            AttributeValueList = new List<AttributeValue>()
            {
                new AttributeValue { S = YourId }
            }
        }
    }
};

client.QueryAsync(request,(result));
</code>```

Specifically, it looks like you are not including your keycondition as part of the request, which is required.

Title: Cannot query or scan DynamoDB in Unity

Body:
TLDR: Can't create an AsyncSearch object from QueryAsync or ScanAsync without running into a weird ArgumentNullException deep inside the AWS library.

I'm developing an online game in Unity and want to synchronize data with DynamoDB. When I only had a table with player data this worked very well. I would just use "DBContext.LoadAsync(id, callback);" and it works flawlessly. Saving with "SaveAsync" works just as well.

Now I introduced some more tables and I need to perform scans and queries. For testing purposes, I gave my Unity app all the rights it can possibly have (I used "dynamodb:*" and "Resource": ["*"] in IAM).

I tried basically all the possible versions of ScanAsync, QueryAsync and FromQueryAsync with different parameters but I just always get an error.

Simple example: I want to download all departments (of my university):

AsyncSearch<DepartmentData> search = AWSManager.Instance.DBContext.ScanAsync<DepartmentData>();

This call already fails, before I can do anything like "search.GetRemainingAsync(callback)". The same goes for for simple queries like:

AsyncSearch<POIVisit> query = AWSManager.Instance.DBContext.QueryAsync<POIVisit>(poiType);

The error is the following and is somewhere deep in the AWS library, so I can't really go in there, set some breakpoints and see what exactly is failing:

ArgumentNullException: Argument cannot be null.
Parameter name: key
System.Collections.Generic.Dictionary`2[System.Type,Amazon.Runtime.IExceptionHandler].TryGetValue (System.Type key, IExceptionHandler& value) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:588)
Amazon.Runtime.Internal.ErrorHandler.ProcessException (IExecutionContext executionContext, System.Exception exception) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/ErrorHandler/ErrorHandler.cs:202)
Amazon.Runtime.Internal.ErrorHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/ErrorHandler/ErrorHandler.cs:78)
Amazon.Runtime.Internal.PipelineHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/PipelineHandler.cs:57)
Amazon.Runtime.Internal.CallbackHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/CallbackHandler.cs:45)
Amazon.Runtime.Internal.PipelineHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/PipelineHandler.cs:57)
Amazon.Runtime.Internal.Signer.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/Signer.cs:38)
Amazon.Runtime.Internal.PipelineHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/PipelineHandler.cs:57)
Amazon.Runtime.Internal.CredentialsRetriever.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/Handlers/CredentialsRetriever.cs:72)
Amazon.Runtime.Internal.PipelineHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/PipelineHandler.cs:57)
Amazon.Runtime.Internal.RetryHandler.InvokeSync (IExecutionContext executionContext) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Core/Amazon.Runtime/Pipeline/RetryHandler/RetryHandler.cs:74)

It gets even worse, if I want to query based on a secondary index. For that, I need to attach a DynamoDBOperationConfig after the conditions for hash and range key like so:

var queryConfig = new DynamoDBOperationConfig() { IndexName = "PlayerIndex" };
AsyncSearch<POIVisit> query = AWSManager.Instance.DBContext.QueryAsync<POIVisit>(poiType, QueryOperator.Equal, PlayerID, queryConfig);

Now, it somehow seems to think, the queryConfig is just another value for the range key (so it basically chooses the wrong overloaded  version of  QueryAsync). Or at least I think that's what happens, because I get a weird conversion error now:

InvalidCastException: Cannot cast from source type to destination type.
Amazon.DynamoDBv2.Converter`1[T].TryTo (System.Object value, Amazon.DynamoDBv2.DocumentModel.Primitive& p) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Services/DynamoDBv2/Custom/Conversion/DynamoDBEntryConversion.cs:630)
…
Amazon.DynamoDBv2.DataModel.DynamoDBContext.QueryAsync[POIVisit] (System.Object hashKeyValue, QueryOperator op, System.Object[] values) (at E:/JenkinsWorkspaces/v3-trebuchet-release/AWSDotNetPublic/sdk/src/Services/DynamoDBv2/Custom/DataModel/_unity/Context.Async.cs:550)
DBManager.RetrievePlayerVisits (System.String poiType, UnityEngine.Events.UnityAction`1 callback) (at Assets/Scripts/Managers/DBManager.cs:359)

My Unity version is 5.6.3f1. I tried AWSSDK.DynamoDBv2.3.3.4.18 and the older AWSSDK.DynamoDBv2.3.3.4.14 Unity packages containing the AWS SDK downloaded directly from Amazon.

If someone has a hint what I could be doing wrong, I'd be really grateful, thanks!

Body:
You need to build a request object before you create a query. I've never used Unity but it should be something like

var request = new QueryRequest();
request.TableName = "YourTable";
request.KeyConditions = new Dictionary<string, Condition>()
{
    {
        "YourId",  new Condition()
        {
            ComparisonOperator = "EQ",
            AttributeValueList = new List<AttributeValue>()
            {
                new AttributeValue { S = YourId }
            }
        }
    }
};

client.QueryAsync(request,(result));

Specifically, it looks like you are not including your keycondition as part of the request, which is required.


问:
best way to concatenate scope results
I have two scopes. One that checks if db column is null or empty string and another that checks for the opposite (not null, and not empty string)

```<code>scope :has_something, where('something IS NOT NULL AND something != ""')
scope :has_no_something, where('something IS NULL OR something = ""')
</code>```

I would like to end up with the two results concatenated. ie results that have something followed by results that do not have something

My first attempt was something like this:

```<code>def self.with_something_data_first
  has_something + has_no_something
end
</code>```

This results in:

NoMethodError: undefined method `order' for #

because this method is combined with an order

```<code>Model.with_something_data_first.order(:created_at).reverse_order.limit(20)
</code>```

It would be great if I could could do this in one scope where it returned all records with data then all records with null or empty string. Obviously you can't order by nil but maybe you know of a tricky way to get around this?

答:
It's very simple and straight forward. Ideally you should be able to get the result applying both conditions right?

If so, do the following,

```<code>def self.with_something_data_first
  has_something.has_no_something
end
</code>```

Title: best way to concatenate scope results

Body:
I have two scopes. One that checks if db column is null or empty string and another that checks for the opposite (not null, and not empty string)

scope :has_something, where('something IS NOT NULL AND something != ""')
scope :has_no_something, where('something IS NULL OR something = ""')

I would like to end up with the two results concatenated. ie results that have something followed by results that do not have something

My first attempt was something like this:

def self.with_something_data_first
  has_something + has_no_something
end

This results in:

NoMethodError: undefined method `order' for #

because this method is combined with an order

Model.with_something_data_first.order(:created_at).reverse_order.limit(20)

It would be great if I could could do this in one scope where it returned all records with data then all records with null or empty string. Obviously you can't order by nil but maybe you know of a tricky way to get around this?

Body:
It's very simple and straight forward. Ideally you should be able to get the result applying both conditions right?

If so, do the following,

def self.with_something_data_first
  has_something.has_no_something
end


问:
Extended Attribute Unresolvable, Powershell
I am trying to set up a method in which a user can tell me there username, I plug it in and it will return me their computerName.

//Get the Username

```<code>$username = Read-Host -prompt 'Username'
</code>```

//Get the DistinguishedName and store it

```<code>$usernameDN = Get-ADUser $username -properties * | SELECT DistinguishedName
</code>```

//Get the ComputerName

//This one fails everytime

```<code>Get-ADComputer -Filter {ManagedBy -eq $usernameDN} -properties * | SELECT CN,ManagedBy
</code>```

//Error I receive...almost as if it has to be a string

Get-ADComputer : Invalid value: '' specified for extended attribute:
  'ManagedBy'. At line:1 char:1
  + Get-ADComputer -Filter {ManagedBy -eq $usernamedn} -properties * | SE ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidArgument: (:) [Get-ADComputer], ArgumentException
      + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Comm
  ands.GetADComputer

//So you put it as a string

```<code>PS C:\WINDOWS\system32> Get-ADComputer -Filter {ManagedBy -eq '$usernamedn'} -properties * | SELECT CN,ManagedBy
</code>```

//Error

Get-ADComputer : Identity info provided in the extended attribute:
  'ManagedBy' could not be resolved. Reason: 'Cannot find an object with
  identity: '$usernamedn' under: 'DC=****,DC=*****'.'. At line:1 char:1
  + Get-ADComputer -Filter {ManagedBy -eq '$usernamedn'} -properties * |  ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidData: (:) [Get-ADComputer], ADIdentityResolutionException
      + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityResolutionException
  ,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

//However if you replace the variable with the literal DistinguishedName...it will work

```<code>PS C:\WINDOWS\system32> Get-ADComputer -Filter {ManagedBy -eq 'CN=*******\, ***** *.,OU=********,OU=*****,OU=******,DC=*****,DC=******'} -properties * | SELECT CN,ManagedBy
</code>```

//Result

```<code>CN        ManagedBy
--        ---------
********* CN=**\, ** *.,OU=***,OU=***,OU=***,DC=***,DC=**
********* CN=**\, ** *.,OU=***,OU=***,OU=***,DC=***,DC=**
</code>```

So I'm thinking my issue is that the Filter requires it to be string, but I can't figure out the right escape to make the variable read that way.

I tried to do the string formatting as well, but I don't completely understand that yet

Thanks,

答:
I recommend using -LDAPFilter instead of -Filter and using an LDAP filter string:

```<code>Get-ADUser -LDAPFilter "(managedBy=$usernameDN)"
</code>```

It is worth your while to learn the LDAP search filter syntax, since that's what PowerShell has to "translate" the -Filter into anyway.

Body:
I am trying to set up a method in which a user can tell me there username, I plug it in and it will return me their computerName.

//Get the Username

$username = Read-Host -prompt 'Username'

//Get the DistinguishedName and store it

$usernameDN = Get-ADUser $username -properties * | SELECT DistinguishedName

//Get the ComputerName

//This one fails everytime

Get-ADComputer -Filter {ManagedBy -eq $usernameDN} -properties * | SELECT CN,ManagedBy

//Error I receive...almost as if it has to be a string

Get-ADComputer : Invalid value: '' specified for extended attribute:
  'ManagedBy'. At line:1 char:1
  + Get-ADComputer -Filter {ManagedBy -eq $usernamedn} -properties * | SE ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidArgument: (:) [Get-ADComputer], ArgumentException
      + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Comm
  ands.GetADComputer

//So you put it as a string

PS C:\WINDOWS\system32> Get-ADComputer -Filter {ManagedBy -eq '$usernamedn'} -properties * | SELECT CN,ManagedBy

//Error

Get-ADComputer : Identity info provided in the extended attribute:
  'ManagedBy' could not be resolved. Reason: 'Cannot find an object with
  identity: '$usernamedn' under: 'DC=****,DC=*****'.'. At line:1 char:1
  + Get-ADComputer -Filter {ManagedBy -eq '$usernamedn'} -properties * |  ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidData: (:) [Get-ADComputer], ADIdentityResolutionException
      + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityResolutionException
  ,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

//However if you replace the variable with the literal DistinguishedName...it will work

PS C:\WINDOWS\system32> Get-ADComputer -Filter {ManagedBy -eq 'CN=*******\, ***** *.,OU=********,OU=*****,OU=******,DC=*****,DC=******'} -properties * | SELECT CN,ManagedBy

//Result

CN        ManagedBy
--        ---------
********* CN=**\, ** *.,OU=***,OU=***,OU=***,DC=***,DC=**
********* CN=**\, ** *.,OU=***,OU=***,OU=***,DC=***,DC=**

So I'm thinking my issue is that the Filter requires it to be string, but I can't figure out the right escape to make the variable read that way.

I tried to do the string formatting as well, but I don't completely understand that yet

Thanks,

Body:
I recommend using -LDAPFilter instead of -Filter and using an LDAP filter string:

Get-ADUser -LDAPFilter "(managedBy=$usernameDN)"

It is worth your while to learn the LDAP search filter syntax, since that's what PowerShell has to "translate" the -Filter into anyway.


问:
Project-Swift.h file not found
I have a new Swift project with a few files, I've needed to add some Objc code.

In Build Settings, my Objective-C Generated Interface Header Name is MyProject-Swift.h

Product Module Name and Product Name are both MyProject.

My Objective-C Bridging Header is MyProject/MyProject-Bridging-Header.h

The contents of my Bridging Header are:

```<code>#ifndef MyProject_Bridging_Header_h
#define MyProject_Bridging_Header_h

#import "Blakey.h"

#endif
</code>```

Blakey.h is pretty simple:

```<code>@import Foundation;

#import "MyProject-Swift.h"
@class KeyPair;

@interface Blakey: NSObject

- (void)createKeyPairForSeed:(NSString *)seed;

@end
</code>```

And Blakey.m

```<code>#import <Foundation/Foundation.h>
#import "Blakey.h"

@implementation Blakey

- (void)createKeyPairForSeed:(NSString *)seed;
{

}

@end
</code>```

(side note: I'm aware my function returns a void, that will be changed later once this issue is fixed so it returns an actual value)

Why is Xcode throwing an error at the #import "MyProject-Swift.h" in Blakey.h?

答:
I had similar issue and almost ended up spending a whole day trying to figure out what wrong with my app.
So following the solution that's helped me :

Clear derived data

Create a class in swift with prefix of @objc for example @objc class mySwiftClass{...}

Build the project again

Et voila.. Should work now.

Why to add @objc?
  this @objc prefix, tells the compiler to generate to your swift class a header file. it will add it to the "MyModule-Swift.h" file

Title: Project-Swift.h file not found

Body:
I have a new Swift project with a few files, I've needed to add some Objc code.

In Build Settings, my Objective-C Generated Interface Header Name is MyProject-Swift.h

Product Module Name and Product Name are both MyProject.

My Objective-C Bridging Header is MyProject/MyProject-Bridging-Header.h

The contents of my Bridging Header are:

#ifndef MyProject_Bridging_Header_h
#define MyProject_Bridging_Header_h

#import "Blakey.h"

#endif

Blakey.h is pretty simple:

@import Foundation;

#import "MyProject-Swift.h"
@class KeyPair;

@interface Blakey: NSObject

- (void)createKeyPairForSeed:(NSString *)seed;

@end

And Blakey.m

#import <Foundation/Foundation.h>
#import "Blakey.h"

@implementation Blakey

- (void)createKeyPairForSeed:(NSString *)seed;
{

}

@end

(side note: I'm aware my function returns a void, that will be changed later once this issue is fixed so it returns an actual value)

Why is Xcode throwing an error at the #import "MyProject-Swift.h" in Blakey.h?


问:
Keep Secret Keys Out
One of the causes of the local_settings.py anti-pattern is that putting SECRET_KEY, AWS
keys, etc.. values into settings files has problem:

Secrets often should be just that: secret! Keeping them in version control means
that everyone with repository access has access to them.

My question is how to keep all keys as secret?

答:
The original question was about how to keep secrets in environment variables. This is discussed extensively in the book Two Scoops of Django. Below is a summary of what they said, followed by a caveat about using this technique.

Starting on page 48 (Section 5.3) of the edition for 1.11:

Every operating system supported by Django (and Python) provides the
  easy capability to create environment variables.

Here are the benefits of using environment variables for secret keys:

Keeping secrets out of settings allows you to store every settings file in version control without hesitation. All of your Python code
  really should be stored in version control, including your settings.

Instead of each developer maintaining their own copy-and-pasted version of local_settings.py.example for development, everyone shares
  the same version-controlled settings/local.py .

System administrators can rapidly deploy the project without having to modify files containing Python code.

Most platforms-as-a-service recommend the use of environment variables for configuration and have built-in features for setting and
  managing them.

On the following page, the book continues:

Before you begin setting environment variables, you should have the
  following:

A way to manage the secret information you are going to store.

A good understanding of how bash settings work on servers, or a willingness to have your project hosted by a platform-as-a-service.

They describe how to set the environment variables locally and in production (with Heroku as an example--you will need to check if you are using a different host this is just one possibility):

How To Set Environment Variables Locally

      export SOME_SECRET_KEY=1c3-cr3am-15-yummy

How To Set Environment Variables in Production

     heroku config:set SOME_SECRET_KEY=1c3-cr3am-15-yummy

Finally, on page 52 they give instructions for how to access the key. For instance you could put the first two lines below in your settings file to replace the raw key string that is put there by default:

```<code>>>> import os
>>> os.environ['SOME_SECRET_KEY']
'1c3-cr3am-15-yummy'
</code>```

This snippet simply gets the value of the SOME_SECRET_KEY environment
  variable from the operating system and saves it to a Python variable
  called SOME_SECRET_KEY.

Following this pattern means all code can remain in version control,
  and all secrets remain safe.

Note this will not work in some cases, for instance if you are using an Apache server. To deal with situations where this pattern will not work, you should see Section 5.4 of their book ('When You Can't Use Environment Variables'). In that case, they recommend use a secret file.

As of late 2017, this technique of storing secrets in your environment variables is the recommended best practice in Two Scoops and in the Twelve Factor App design pattern. It is also recommended at the Django docs. However, there are some security risks: if some developer, or some code, has access to your system, they will have access to your environment variables and may inadvertently (or advertently) make them public. This point was made by Michael Reinsch here:

http://movingfast.io/articles/environment-variables-considered-harmful/

Title: Keep Secret Keys Out

Body:
The original question was about how to keep secrets in environment variables. This is discussed extensively in the book Two Scoops of Django. Below is a summary of what they said, followed by a caveat about using this technique.

Starting on page 48 (Section 5.3) of the edition for 1.11:

Every operating system supported by Django (and Python) provides the
  easy capability to create environment variables.

Here are the benefits of using environment variables for secret keys:

Keeping secrets out of settings allows you to store every settings file in version control without hesitation. All of your Python code
  really should be stored in version control, including your settings.

Instead of each developer maintaining their own copy-and-pasted version of local_settings.py.example for development, everyone shares
  the same version-controlled settings/local.py .

System administrators can rapidly deploy the project without having to modify files containing Python code.

Most platforms-as-a-service recommend the use of environment variables for configuration and have built-in features for setting and
  managing them.

On the following page, the book continues:

Before you begin setting environment variables, you should have the
  following:

A way to manage the secret information you are going to store.

A good understanding of how bash settings work on servers, or a willingness to have your project hosted by a platform-as-a-service.

They describe how to set the environment variables locally and in production (with Heroku as an example--you will need to check if you are using a different host this is just one possibility):

How To Set Environment Variables Locally

      export SOME_SECRET_KEY=1c3-cr3am-15-yummy

How To Set Environment Variables in Production

     heroku config:set SOME_SECRET_KEY=1c3-cr3am-15-yummy

Finally, on page 52 they give instructions for how to access the key. For instance you could put the first two lines below in your settings file to replace the raw key string that is put there by default:

>>> import os
>>> os.environ['SOME_SECRET_KEY']
'1c3-cr3am-15-yummy'

This snippet simply gets the value of the SOME_SECRET_KEY environment
  variable from the operating system and saves it to a Python variable
  called SOME_SECRET_KEY.

Following this pattern means all code can remain in version control,
  and all secrets remain safe.

Note this will not work in some cases, for instance if you are using an Apache server. To deal with situations where this pattern will not work, you should see Section 5.4 of their book ('When You Can't Use Environment Variables'). In that case, they recommend use a secret file.

As of late 2017, this technique of storing secrets in your environment variables is the recommended best practice in Two Scoops and in the Twelve Factor App design pattern. It is also recommended at the Django docs. However, there are some security risks: if some developer, or some code, has access to your system, they will have access to your environment variables and may inadvertently (or advertently) make them public. This point was made by Michael Reinsch here:

http://movingfast.io/articles/environment-variables-considered-harmful/


问:
How to make a scroll news like Top Tweets in twitter homepage? (php)
I want to make a site use wp, and I want add a scroll news like Top Tweets in twitter homepage. when the custom post a new replys in every part of my page, the new topics will disply in this scroll news part. they all come from latest 10 items of database. How to do that? Thanks</p>

答:
Using Jquery you can make a div slide in and slide out of view.
http://docs.jquery.com/UI/Effects/Slide#overview.

Then you give each div a unique id each containing a comment from your database. Initialize div 0,1,2 as visible and 3-9 as hidden.  Here the javascript structure:

```<code>echo <<<CONTENT
<html>
<head>
       <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
       </script>
       <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
       <script type="text/javascript">
        k=1;
        setInterval("livefeed(k++)",1000);
        function livefeed(i){
        slide(i);
        }

        function slide(i){
                 addTop((i+3)%10);
                removeBottom(i%10);
                 var j=((i-1)%10);
                 $('.livefeed').prepend($("#"+j));

        }

        function addTop(i){
                  var e=document.getElementById(i);
                  $("#"+i).fadeIn(1000);
        }
        function removeBottom(i){
                  $("#"+i).fadeOut(1000);
         }
</script>

</head>
<body>
CONTENT;

     echo "<div class='livefeed'>";
     for($i=9;$i>=0;$i--){
         if($i<4&&$i>0){
        echo "<div id='".$i."' >This is comment $i from the database</div>";
         }else{
        echo "<div style='display:none' id='".$i."'  >This is comment ".$i." from the database</div>";
          }
     }
     echo "</div>";
</code>```

THis updates every second.. which is a bit fast ... so you should set it to something like 7000 milliseconds.
demo

Body:
Using Jquery you can make a div slide in and slide out of view.
http://docs.jquery.com/UI/Effects/Slide#overview.

Then you give each div a unique id each containing a comment from your database. Initialize div 0,1,2 as visible and 3-9 as hidden.  Here the javascript structure:

echo <<<CONTENT
<html>
<head>
       <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
       </script>
       <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
       <script type="text/javascript">
        k=1;
        setInterval("livefeed(k++)",1000);
        function livefeed(i){
        slide(i);
        }

        function slide(i){
                 addTop((i+3)%10);
                removeBottom(i%10);
                 var j=((i-1)%10);
                 $('.livefeed').prepend($("#"+j));

        }

        function addTop(i){
                  var e=document.getElementById(i);
                  $("#"+i).fadeIn(1000);
        }
        function removeBottom(i){
                  $("#"+i).fadeOut(1000);
         }
</script>

</head>
<body>
CONTENT;

     echo "<div class='livefeed'>";
     for($i=9;$i>=0;$i--){
         if($i<4&&$i>0){
        echo "<div id='".$i."' >This is comment $i from the database</div>";
         }else{
        echo "<div style='display:none' id='".$i."'  >This is comment ".$i." from the database</div>";
          }
     }
     echo "</div>";

THis updates every second.. which is a bit fast ... so you should set it to something like 7000 milliseconds.
demo


问:
RecyclerView onItemClick Interface: get values in the Adapter or in the Activity?
I have a ViewHolder with an OnClickListener, which sends the click over an Interface to the underlying Activity. The only information i send is the AdapterPosition. In the Activity i then get the information out of the Activitie's reference to the ArrayList (which also fills the Adapter), using the position i get passed from the Adapter. I then use this to open a new Activity where i show this data.
Now, this works, but i just came to mind that this could cause problems, if i don't properly call notifyDataSetChanged/ItemInserted/Removed etc. and the Adapter shows a different List than the actualy up-to-date List in the Activity. I am right about this? Should i get the values out of the Objects IN the Adapter and pass them to the Activity or is my approach correct?

ViewHolder:

```<code>public class ExampleViewHolder extends RecyclerView.ViewHolder {
    public ImageView mImageView;
    public TextView mTextViewCreator;
    public TextView mTextViewLikes;

    public ExampleViewHolder(View itemView) {
        super(itemView);
        mImageView = itemView.findViewById(R.id.image_view);
        mTextViewCreator = itemView.findViewById(R.id.text_view_creator);
        mTextViewLikes = itemView.findViewById(R.id.text_view_likes);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        mListener.onItemClick(position);
                    }
                }
            }
        });
    }
}
</code>```

MainActivity OnItemClick implementation:

```<code>@Override
public void onItemClick(int position) {
    Intent detailIntent = new Intent(this, DetailActivity.class);
    ExampleItem clickedItem = mExampleList.get(position);

    detailIntent.putExtra("imageUrl", clickedItem.getImageUrl());
    detailIntent.putExtra("creatorName", clickedItem.getCreator());
    detailIntent.putExtra("likeCount", clickedItem.getLikeCount());

    startActivity(detailIntent);
}
</code>```

答:
My personal preference is that you send the model to the activity, that's what it's interested in, it doesn't care about your adapter position, and even if in the future your list became an expandable list or even a ViewPager, all the Callback (Activity) wants is the model to start the new screen.

You can change your listener method to

```<code>onItemClick(ExampleItem item)
</code>```

and then you can set your listener when onBindViewHolder is called.

Body:
I have a ViewHolder with an OnClickListener, which sends the click over an Interface to the underlying Activity. The only information i send is the AdapterPosition. In the Activity i then get the information out of the Activitie's reference to the ArrayList (which also fills the Adapter), using the position i get passed from the Adapter. I then use this to open a new Activity where i show this data.
Now, this works, but i just came to mind that this could cause problems, if i don't properly call notifyDataSetChanged/ItemInserted/Removed etc. and the Adapter shows a different List than the actualy up-to-date List in the Activity. I am right about this? Should i get the values out of the Objects IN the Adapter and pass them to the Activity or is my approach correct?

ViewHolder:

public class ExampleViewHolder extends RecyclerView.ViewHolder {
    public ImageView mImageView;
    public TextView mTextViewCreator;
    public TextView mTextViewLikes;

    public ExampleViewHolder(View itemView) {
        super(itemView);
        mImageView = itemView.findViewById(R.id.image_view);
        mTextViewCreator = itemView.findViewById(R.id.text_view_creator);
        mTextViewLikes = itemView.findViewById(R.id.text_view_likes);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION) {
                        mListener.onItemClick(position);
                    }
                }
            }
        });
    }
}

MainActivity OnItemClick implementation:

@Override
public void onItemClick(int position) {
    Intent detailIntent = new Intent(this, DetailActivity.class);
    ExampleItem clickedItem = mExampleList.get(position);

    detailIntent.putExtra("imageUrl", clickedItem.getImageUrl());
    detailIntent.putExtra("creatorName", clickedItem.getCreator());
    detailIntent.putExtra("likeCount", clickedItem.getLikeCount());

    startActivity(detailIntent);
}

Body:
My personal preference is that you send the model to the activity, that's what it's interested in, it doesn't care about your adapter position, and even if in the future your list became an expandable list or even a ViewPager, all the Callback (Activity) wants is the model to start the new screen.

You can change your listener method to

onItemClick(ExampleItem item)

and then you can set your listener when onBindViewHolder is called.


问:
Require explicit FTP over TLS with PHP
I'm trying to upload file to ftp with php. Only requirement from server's admin were Encryption should be Require explicit FTP over TLS. And that's it but I'm getting error Warning: ftp_fput() [function.ftp-fput]: Can't open data connection.. I manage to connect(in passive mode), but it fails to upload with any function(ftp_put, ftp_nb_put, ftp_fput). Error is the same all the times. I'm trying following code:

```<code>$host = 'ftps.someserver.net';
$user = '****';
$pass = '****';
$filename = "somefile.txt"

$dest_file = $filename;
$source_file = dirname(__FILE__) . '/' . $filename;

$fp = fopen($source_file, 'r');

$ftp = ftp_ssl_connect($host, 21, 180);

if (ftp_login($ftp,$user,$pass)) {

    var_dump(ftp_pasv($ftp, true)); // gives me true
    // # first way
    // ftp_put($ftp, $dest_file, $source_file, FTP_BINARY);

    // # second
    // $ret = ftp_nb_put($ftp, $dest_file, $source_file, FTP_BINARY, FTP_AUTORESUME);

    // while (FTP_MOREDATA == $ret)
    // {
    //   $ret = ftp_nb_continue($ftp);
    // }

    // # third
    if (ftp_fput($ftp, $dest_file, $fp, FTP_ASCII)) { // I was trying FTP_BINARY and FTP_ASCII.
        echo "Successfully uploaded\n";
    } else {
        echo "There was a problem while uploading\n";
    }
}
ftp_close($ftp);
fclose($fp);
</code>```

It works fine with my own ftp, that does not asks for explicit TLS. Any ideas would be appreciated.

答: This one got me too. I discovered it was a bug with the version of PHP I was using (5.4.28). I tried the same script with PHP version 5.6.31 and everything worked.</p>

Title: Require explicit FTP over TLS with PHP

Body:
I'm trying to upload file to ftp with php. Only requirement from server's admin were Encryption should be Require explicit FTP over TLS. And that's it but I'm getting error Warning: ftp_fput() [function.ftp-fput]: Can't open data connection.. I manage to connect(in passive mode), but it fails to upload with any function(ftp_put, ftp_nb_put, ftp_fput). Error is the same all the times. I'm trying following code:

$host = 'ftps.someserver.net';
$user = '****';
$pass = '****';
$filename = "somefile.txt"

$dest_file = $filename;
$source_file = dirname(__FILE__) . '/' . $filename;

$fp = fopen($source_file, 'r');

$ftp = ftp_ssl_connect($host, 21, 180);

if (ftp_login($ftp,$user,$pass)) {

    var_dump(ftp_pasv($ftp, true)); // gives me true
    // # first way
    // ftp_put($ftp, $dest_file, $source_file, FTP_BINARY);

    // # second
    // $ret = ftp_nb_put($ftp, $dest_file, $source_file, FTP_BINARY, FTP_AUTORESUME);

    // while (FTP_MOREDATA == $ret)
    // {
    //   $ret = ftp_nb_continue($ftp);
    // }

    // # third
    if (ftp_fput($ftp, $dest_file, $fp, FTP_ASCII)) { // I was trying FTP_BINARY and FTP_ASCII.
        echo "Successfully uploaded\n";
    } else {
        echo "There was a problem while uploading\n";
    }
}
ftp_close($ftp);
fclose($fp);

It works fine with my own ftp, that does not asks for explicit TLS. Any ideas would be appreciated.


问:
How to apply jquery only to the element selected with if statement?
I am trying to select a certain element on a page. All the elements have the same class same everything, with the only exception that the background image is different on some of them.

What I need to do is to ONLY apply the jquery code to only the element chosen via the if statement.

Please note I cannot edit the HTML, I need to use jquery for this.

Here is my code:

```<code>$('.repeated-element').each( function(){
   if ( $(this).css('background-image').indexOf('mystringzzz') ) {
    //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
    //stop loop
      return false;
   }
});
</code>```

I have selected the element just fine and jquery is running. I know this because I get the alert popup which shows that part (if ( $(this).css('background-image').indexOf('mystringzzz') ) {) works.

However, the problem is that I can only get it to apply to either the first element (which is not the one that is selected) or to all of the elements.

If I use:

```<code>$(this).closest('div.someclass').addClass('aclassilike');
</code>```

the result is it applies to only the very first recurrence on the page, NOT the selected one.

Alternatively if I use:

```<code>$('.repeated-element').closest('div.someclass').addClass('aclassilike');
</code>```

Then the result is it applies every recurrence on the page, not only the selected ones. It is supposed to be only the selected one.

How can I ONLY apply the jquery code to only the element chosen via the if statement?

For example,

a) inside the .repeated-element,

  b) ONLY which contains a background-image css in the external stylesheet which has part of the image name as mystringzzz,

  c) then apply the new jquery (in this example adding another class).

  d) But do not apply it to elements which do not contain the mystringzzz string in background-image.

答:
The source of the problem was that you weren't checking if the index did not equate to -1 in your indexOf() call. If you were to write this in the original format of your question it would look like this:

```<code>$('.repeated-element').each(function() {
   if ($(this).css('background-image').indexOf('mystringzzz') !== -1) {
     //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
      //stop loop
      return false;
   }
});
</code>```

With all that being said jQuery's methods have certain use-cases depending on the scenario. I'd highly recommend just using filter() in this case:

```<code>$('.repeated-element').filter(function() {
  return $(this).css('background-image').indexOf('mystringzzz') !== -1;
}).closest('div.someclass').addClass('aclassilike');
</code>```

Body:
I am trying to select a certain element on a page. All the elements have the same class same everything, with the only exception that the background image is different on some of them.

What I need to do is to ONLY apply the jquery code to only the element chosen via the if statement.

Please note I cannot edit the HTML, I need to use jquery for this.

Here is my code:

$('.repeated-element').each( function(){
   if ( $(this).css('background-image').indexOf('mystringzzz') ) {
    //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
    //stop loop
      return false;
   }
});

I have selected the element just fine and jquery is running. I know this because I get the alert popup which shows that part (if ( $(this).css('background-image').indexOf('mystringzzz') ) {) works.

However, the problem is that I can only get it to apply to either the first element (which is not the one that is selected) or to all of the elements.

If I use:

$(this).closest('div.someclass').addClass('aclassilike');

the result is it applies to only the very first recurrence on the page, NOT the selected one.

Alternatively if I use:

$('.repeated-element').closest('div.someclass').addClass('aclassilike');

Then the result is it applies every recurrence on the page, not only the selected ones. It is supposed to be only the selected one.

How can I ONLY apply the jquery code to only the element chosen via the if statement?

For example,

a) inside the .repeated-element,

  b) ONLY which contains a background-image css in the external stylesheet which has part of the image name as mystringzzz,

  c) then apply the new jquery (in this example adding another class).

  d) But do not apply it to elements which do not contain the mystringzzz string in background-image.

Body:
The source of the problem was that you weren't checking if the index did not equate to -1 in your indexOf() call. If you were to write this in the original format of your question it would look like this:

$('.repeated-element').each(function() {
   if ($(this).css('background-image').indexOf('mystringzzz') !== -1) {
     //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
      //stop loop
      return false;
   }
});

With all that being said jQuery's methods have certain use-cases depending on the scenario. I'd highly recommend just using filter() in this case:

$('.repeated-element').filter(function() {
  return $(this).css('background-image').indexOf('mystringzzz') !== -1;
}).closest('div.someclass').addClass('aclassilike');


问:
MPDF Try to keep div on same page
I am developing a web application in PHP that needs to generate some invoices, and I chose mpdf to do this.

Now, I have the following challenge: the invoice exists out some divs under eachother. I want MPDF to try and see if this FULL div fits on 1 page. If this is the only div on the page, it can overflow to the next page. If it's the second or third, fourth, etc. then this whole div needs to be put on the next page.

I tried this "avoid page break"  but it bugs a lot and creates empty pages.

Does anyone have a suggestion?

答:
Not sure what you mean with 'tried "avoid page break"'

But the following seems like this worked well for me with latest MPDF:

```<code>@media print {
    div {
        page-break-inside: avoid;
    }
}
</code>```

However, it doesn't work (well) for floating divs.

Title: MPDF Try to keep div on same page

Body:
Not sure what you mean with 'tried "avoid page break"'

But the following seems like this worked well for me with latest MPDF:

@media print {
    div {
        page-break-inside: avoid;
    }
}

However, it doesn't work (well) for floating divs.


问:
increment value outside of function for every use in python
I have a function that I want to use multiple times, on every use I want a variable outside of the function to increment. Along the lines of -

```<code>def funtion1(mylists,x):
    row=1
    for elm in mylists:
        ws.write(row,x,elm)
        row+=1
    x += 1

col=0
function1(mylist1,col)
function1(mylist2,col)
function1(mylist3,col)
</code>```

etc

I thought col would increment on every use, but it stays at 0. Should I be returning a value from the function?

答:
You are incrementing a temporary variable x in the function namespace, therefore col is not modified. If you want to change col you can:

use a class with a classmethod and a class attribute

use a decorator as in Paul Panzer's answer

return the value of x and affect it to col

use a global statement.

If you are unfamiliar with namespace check this link

First using a class with a classmethod and a class attribute:

```<code>class functions:
    col = 0

    @classmethod
    def function1(cls, mylists):
        row=1
        for elm in mylists:
            ws.write(row, cls.col,elm)
            row+=1
        cls.col += 1

functions.function1(mylist1)
functions.function1(mylist2)
functions.function1(mylist3)
</code>```

This would be my preferred option as the namespaces are not polluted and the code is cleaner than with returning a value.

Now returning a value:

```<code>def funtion1(mylists,x):
    row=1
    for elm in whichlist:
        ws.write(row,x,elm)
        row=row+1
    return x + 1

col = 0
col = function1(mylist1,col)
col = function1(mylist2,col)
col = function1(mylist3,col)
</code>```

Or with a global:

```<code>def function1(mylists):
    global col
    row=1
    for elm in mylists:
        ws.write(row,col,elm)
        row+=1
    col += 1

col=0
function1(mylist1)
function1(mylist2)
function1(mylist3)
</code>```

Body:
I have a function that I want to use multiple times, on every use I want a variable outside of the function to increment. Along the lines of -

def funtion1(mylists,x):
    row=1
    for elm in mylists:
        ws.write(row,x,elm)
        row+=1
    x += 1

col=0
function1(mylist1,col)
function1(mylist2,col)
function1(mylist3,col)

etc

I thought col would increment on every use, but it stays at 0. Should I be returning a value from the function?

Body:
You are incrementing a temporary variable x in the function namespace, therefore col is not modified. If you want to change col you can:

use a class with a classmethod and a class attribute

use a decorator as in Paul Panzer's answer

return the value of x and affect it to col

use a global statement.

If you are unfamiliar with namespace check this link

First using a class with a classmethod and a class attribute:

class functions:
    col = 0

    @classmethod
    def function1(cls, mylists):
        row=1
        for elm in mylists:
            ws.write(row, cls.col,elm)
            row+=1
        cls.col += 1

functions.function1(mylist1)
functions.function1(mylist2)
functions.function1(mylist3)

This would be my preferred option as the namespaces are not polluted and the code is cleaner than with returning a value.

Now returning a value:

def funtion1(mylists,x):
    row=1
    for elm in whichlist:
        ws.write(row,x,elm)
        row=row+1
    return x + 1

col = 0
col = function1(mylist1,col)
col = function1(mylist2,col)
col = function1(mylist3,col)

Or with a global:

def function1(mylists):
    global col
    row=1
    for elm in mylists:
        ws.write(row,col,elm)
        row+=1
    col += 1

col=0
function1(mylist1)
function1(mylist2)
function1(mylist3)


问:
Windows forms tree view show folder info
I have something like Explorer, where you chose some folder, and in tree view it displays it. And I need in the list box, to show the folder info, but the thing is, the folder info should only show when a specific folder is selected, but now I have only when I select the first folder, it shows all files that are in that folder. Here is the code for now</p>

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    DirectoryInfo directoryInfo;
    private void directoryToolStripMenuItem_Click(object sender, EventArgs e)
    {
        folderbrowser_dialog.ShowDialog();
        if (folderbrowser_dialog.SelectedPath != null)
        {
            directoryInfo = new DirectoryInfo(folderbrowser_dialog.SelectedPath);
            if (directoryInfo.Exists)
            {
                BuildTree(directoryInfo, treeview.Nodes);
            }
        }
    }

    private void resetToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Restart();
    }

    private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
    {
        TreeNode root = addInMe.Add(directoryInfo.Name);
        foreach (DirectoryInfo subdir in directoryInfo.GetDirectories())
        {
            BuildTree(subdir, root.Nodes);
        }

        FileInfo[] Files = directoryInfo.GetFiles("*");
        foreach (FileInfo file in Files)
        {
            listbox.Items.Add(file.Name);
        }
    }
}
</code>```

答:
Your question is a little unclear, but it sounds like you are asking how you can show the correct files in the ListBox whenever you select a folder in the tree.  Here is how you do that:

In your BuildTree method, after you create the TreeNode, set the Name property on the node to the FullName of the folder that node represents.

```<code>private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
{
    TreeNode root = addInMe.Add(directoryInfo.Name);
    root.Name = directoryInfo.FullName;
    ...
}
</code>```

Then, add an AfterSelect event handler on the TreeView.  In the event handler, create a DirectoryInfo using the Name of the selected node (e.Node.Name).  Clear the ListBox and then use the same loop you have now in BuildTree to repopulate it.

```<code>private void treeview_AfterSelect(object sender, TreeViewEventArgs e)
{
    DirectoryInfo directoryInfo = new DirectoryInfo(e.Node.Name);
    FileInfo[] Files = directoryInfo.GetFiles("*");
    listbox.Items.Clear();
    foreach (FileInfo file in Files)
    {
        listbox.Items.Add(file.Name);
    }
}
</code>```

Body:
I have something like Explorer, where you chose some folder, and in tree view it displays it. And I need in the list box, to show the folder info, but the thing is, the folder info should only show when a specific folder is selected, but now I have only when I select the first folder, it shows all files that are in that folder. Here is the code for now

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    DirectoryInfo directoryInfo;
    private void directoryToolStripMenuItem_Click(object sender, EventArgs e)
    {
        folderbrowser_dialog.ShowDialog();
        if (folderbrowser_dialog.SelectedPath != null)
        {
            directoryInfo = new DirectoryInfo(folderbrowser_dialog.SelectedPath);
            if (directoryInfo.Exists)
            {
                BuildTree(directoryInfo, treeview.Nodes);
            }
        }
    }

    private void resetToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Restart();
    }

    private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
    {
        TreeNode root = addInMe.Add(directoryInfo.Name);
        foreach (DirectoryInfo subdir in directoryInfo.GetDirectories())
        {
            BuildTree(subdir, root.Nodes);
        }

        FileInfo[] Files = directoryInfo.GetFiles("*");
        foreach (FileInfo file in Files)
        {
            listbox.Items.Add(file.Name);
        }
    }
}

Body:
Your question is a little unclear, but it sounds like you are asking how you can show the correct files in the ListBox whenever you select a folder in the tree.  Here is how you do that:

In your BuildTree method, after you create the TreeNode, set the Name property on the node to the FullName of the folder that node represents.

private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
{
    TreeNode root = addInMe.Add(directoryInfo.Name);
    root.Name = directoryInfo.FullName;
    ...
}

Then, add an AfterSelect event handler on the TreeView.  In the event handler, create a DirectoryInfo using the Name of the selected node (e.Node.Name).  Clear the ListBox and then use the same loop you have now in BuildTree to repopulate it.

private void treeview_AfterSelect(object sender, TreeViewEventArgs e)
{
    DirectoryInfo directoryInfo = new DirectoryInfo(e.Node.Name);
    FileInfo[] Files = directoryInfo.GetFiles("*");
    listbox.Items.Clear();
    foreach (FileInfo file in Files)
    {
        listbox.Items.Add(file.Name);
    }
}


问:
Play a Shoutcast Stream on iPhone with HTML5
I know this question is already asked in past, but i finally found no answer....

So I got a shoutcast stream, encoding audio/mpeg and I want create a web-app for my iphone to listen to my stream mobile.

I tried several methods of http://mydomain.com:8000/. With semicolon, with stream.nsv, with stream.nsv&type=mp3 and so on...

I tested it everytime with the Safari browser und nothing happened. I tried several options in the html5 audio tag. preload, auto-buffering  etc..... it's still quiet...

Do you have any solutions or snippets or what else?

Thank you :)

答:
you very welcome,sorry i don't know the source for Android,here are links that might help you,good luck with it.
http://dev.opera.com/articles/view/everything-you-need-to-know-about-html5-video-and-audio/</p>