问:
MongoDB nested aggregation not finding inner collection
I am new to Stack and MongoDB. I have adjusted my codes based on other posts but couldn't figure out where i went wrong. I have three collections. Microbe is connected to Activities (1 to M) and Activities to Bio-Activities (1 to M). I would like to show the nest from Microbe until Bio-Activities in the form of an array.

```<code>Microbe collection
{"_id": 1, item: "abc", species: 12, quantity: 2},
{"_id": 2, item: "jkl", species: 20, quantity: 1},
{"_id": 3}

Activities collection
{"_id": 1, code: "MON1003", item: "abc", type: "Monitor", repeat: 120, size: "27", resolution: "1920x1080"},
{"_id": 2, code: "MON1012", item: "abc", type: "Monitor", repeat: 85, size: "23", resolution: "1280x800"},
{"_id": 3, code: "MON1031", item: "jkl", type: "Monitor", repeat: 60, size: "21", resolution: "1920x1080"}

Bio-Activities collection
{"_id": 1, code: "MON1003", description: "bio 1", quantity: 120},
{"_id": 2, code: "MON1003", description: "bio 2", quantity: 80},
{"_id": 3, code: "MON1012", description: "bio 3", quantity: 60},
{"_id": 4, code: "MON1012", description: "bio 4", quantity: 70},
{"_id": 5, code: "MON1012", description: "bio 5", quantity: 170},
{"_id": 6, code: "MON1031", description: "bio 6", quantity: 270}
</code>```

This is my code:

```<code>db.microbe.aggregate([
{
$lookup:
{
from: "activities",
localField: "item",
foreignField: "item",
as: "activities"
}
},{
$lookup:
{
    from: "bioactivities",
    localField: "code",
    foreignField: "code",
    as: "bioactivities"
}
},{
    $unwind: "$activities"
},{
$group: {
    _id: "$_id",
    item: {$first: "$item"},
    species: {$first: "$species"},
    quantity: {$first: "$quantity"},
    activities: {$push: {
        id: "$activities._id",
        code: "$activities.code",
        item: "$activities.item",
        type: "$activities.type",
        repeat: "$activities.repeat",
        size: "$activities.size",
        bioactivities: "$bioactivities"
    }
    }
}
}
]).pretty()
</code>```

But I get this output which shows empty "bioactivities". Where did I go wrong?

```<code>    {
    "_id" : 2,
    "item" : "jkl",
    "species" : 20,
            "quantity" : 1,
            "activities" : [
                    {
                    "id" : 3,
                    "code" : "MON1031",
                    "item" : "jkl",
                    "type" : "Monitor",
                    "repeat" : 60,
                    "size" : "21",
                    "bioactivities" : [ ]
            }
    ]
    }
    {
            "_id" : 1,
            "item" : "abc",
            "species" : 12,
            "quantity" : 2,
            "activities" : [
            {
                    "id" : 1,
                    "code" : "MON1003",
                    "item" : "abc",
                    "type" : "Monitor",
                    "repeat" : 120,
                    "size" : "27",
                    "bioactivities" : [ ]
            },
            {
                    "id" : 2,
                    "code" : "MON1012",
                    "item" : "abc",
                    "type" : "Monitor",
                    "repeat" : 85,
                    "size" : "23",
                    "bioactivities" : [ ]
            }
    ]
    }
</code>```

Thanks.

答:
It's a silly mistake which I think you overlooked.
In your second $lookup, localField should be "activities.code" like this,

```<code>{
$lookup:
{
    from: "bioactivities",
    localField: "activities.code",
    foreignField: "code",
    as: "bioactivities"
}
}
</code>```

This will give you output like following:

```<code>{
    "_id" : 2.0,
    "item" : "jkl",
    "species" : 20.0,
    "quantity" : 1.0,
    "activities" : [
        {
            "id" : 3.0,
            "code" : "MON1031",
            "item" : "jkl",
            "type" : "Monitor",
            "repeat" : 60.0,
            "size" : "21",
            "bioactivities" : [
                {
                    "_id" : 6.0,
                    "code" : "MON1031",
                    "description" : "bio 6",
                    "quantity" : 270.0
                }
            ]
        }
    ]
}
</code>```

I hope this is what you're looking for.

Body:
I am new to Stack and MongoDB. I have adjusted my codes based on other posts but couldn't figure out where i went wrong. I have three collections. Microbe is connected to Activities (1 to M) and Activities to Bio-Activities (1 to M). I would like to show the nest from Microbe until Bio-Activities in the form of an array.

Microbe collection
{"_id": 1, item: "abc", species: 12, quantity: 2},
{"_id": 2, item: "jkl", species: 20, quantity: 1},
{"_id": 3}

Activities collection
{"_id": 1, code: "MON1003", item: "abc", type: "Monitor", repeat: 120, size: "27", resolution: "1920x1080"},
{"_id": 2, code: "MON1012", item: "abc", type: "Monitor", repeat: 85, size: "23", resolution: "1280x800"},
{"_id": 3, code: "MON1031", item: "jkl", type: "Monitor", repeat: 60, size: "21", resolution: "1920x1080"}

Bio-Activities collection
{"_id": 1, code: "MON1003", description: "bio 1", quantity: 120},
{"_id": 2, code: "MON1003", description: "bio 2", quantity: 80},
{"_id": 3, code: "MON1012", description: "bio 3", quantity: 60},
{"_id": 4, code: "MON1012", description: "bio 4", quantity: 70},
{"_id": 5, code: "MON1012", description: "bio 5", quantity: 170},
{"_id": 6, code: "MON1031", description: "bio 6", quantity: 270}

This is my code:

db.microbe.aggregate([
{
$lookup:
{
from: "activities",
localField: "item",
foreignField: "item",
as: "activities"
}
},{
$lookup:
{
    from: "bioactivities",
    localField: "code",
    foreignField: "code",
    as: "bioactivities"
}
},{
    $unwind: "$activities"
},{
$group: {
    _id: "$_id",
    item: {$first: "$item"},
    species: {$first: "$species"},
    quantity: {$first: "$quantity"},
    activities: {$push: {
        id: "$activities._id",
        code: "$activities.code",
        item: "$activities.item",
        type: "$activities.type",
        repeat: "$activities.repeat",
        size: "$activities.size",
        bioactivities: "$bioactivities"
    }
    }
}
}
]).pretty()

But I get this output which shows empty "bioactivities". Where did I go wrong?

    {
    "_id" : 2,
    "item" : "jkl",
    "species" : 20,
            "quantity" : 1,
            "activities" : [
                    {
                    "id" : 3,
                    "code" : "MON1031",
                    "item" : "jkl",
                    "type" : "Monitor",
                    "repeat" : 60,
                    "size" : "21",
                    "bioactivities" : [ ]
            }
    ]
    }
    {
            "_id" : 1,
            "item" : "abc",
            "species" : 12,
            "quantity" : 2,
            "activities" : [
            {
                    "id" : 1,
                    "code" : "MON1003",
                    "item" : "abc",
                    "type" : "Monitor",
                    "repeat" : 120,
                    "size" : "27",
                    "bioactivities" : [ ]
            },
            {
                    "id" : 2,
                    "code" : "MON1012",
                    "item" : "abc",
                    "type" : "Monitor",
                    "repeat" : 85,
                    "size" : "23",
                    "bioactivities" : [ ]
            }
    ]
    }

Thanks.

Body:
It's a silly mistake which I think you overlooked.
In your second $lookup, localField should be "activities.code" like this,

{
$lookup:
{
    from: "bioactivities",
    localField: "activities.code",
    foreignField: "code",
    as: "bioactivities"
}
}

This will give you output like following:

{
    "_id" : 2.0,
    "item" : "jkl",
    "species" : 20.0,
    "quantity" : 1.0,
    "activities" : [
        {
            "id" : 3.0,
            "code" : "MON1031",
            "item" : "jkl",
            "type" : "Monitor",
            "repeat" : 60.0,
            "size" : "21",
            "bioactivities" : [
                {
                    "_id" : 6.0,
                    "code" : "MON1031",
                    "description" : "bio 6",
                    "quantity" : 270.0
                }
            ]
        }
    ]
}

I hope this is what you're looking for.


来源: stackexchange

问:
log version of boost binomial_coefficient?
Fairly simple question but I've been having trouble finding anything online.

I'm looking for a log version of boost::math::binomial_coefficient, which can handle some of the larger values generated by my code.

In R there is lchoose which provides this, however I can't seem to find the equivalent in c++

Any help would be much appreciated

答:
I think you have to calculate it yourself.  However this question asks how to do that, and it turns out not to be too bad.  A first approximation is:

```<code>n log n − m log m − (n−m) log (n−m)
</code>```

A better approximation can be obtained by using another term of the Stirling approximation for log(n!)

```<code>n log n − m log m − (n−m) log (n−m) + ½(log n − log m − log(n−m) − log 2π)
</code>```

With all of these you are subtracting two terms which are potentially of similar size, so you are vulnerable to loss of accuracy.

ContentLicense: CC BY-SA 3.0

Body:
I think you have to calculate it yourself.  However this question asks how to do that, and it turns out not to be too bad.  A first approximation is:

n log n − m log m − (n−m) log (n−m)

A better approximation can be obtained by using another term of the Stirling approximation for log(n!)

n log n − m log m − (n−m) log (n−m) + ½(log n − log m − log(n−m) − log 2π)

With all of these you are subtracting two terms which are potentially of similar size, so you are vulnerable to loss of accuracy.


问:
Partitioning join to limit records in SQL
I have 2 tables:
- first one containing spatial data - geometry of circles
- second contains geometries of lines.

I want to find all lines which are inside each circle. I have a query which can do that, however there are millions of records so it is unusably slow.
There is a column in both tables which is area_id and essentially all circles are assigned to particular area and all lines as well, so if I can do the intersect of the circles only with the lines in the matching area this will reduce the load a lot. The problem is I can't think of solution e.g. using windowing function. The query I am using is:

```<code>Select ct.AREA_ID, ct.Circle_descr,  lt.Line_descr from circles_table as ct
JOIN lines_table as lt
ON
circles_table.Circle_location.STIntersects(points_table.Point_location)=1
</code>```

*using a where clause at the end makes no difference as it is essentially part of the slow join...

```<code>+---------------+----------------------+--------------------------+
| AREA_ID (int) | Circle_descr(varchar) | Circle_location(geometry)|
+---------------+----------------------+--------------------------+

+---------------+---------------------+-------------------------+
| AREA_ID (int) | Line_descr(varchar) | Line_location(geometry) |
+---------------+---------------------+-------------------------+
</code>```

答:
Add an additional join criterion to partition the rows by area_id before comparing them.  Something like</p>

```<code>Select ct.AREA_ID, ct.Circle_descr,  lt.Line_descr
from circles_table as ct
JOIN lines_table as lt
  ON ct.Circle_location.STIntersects(lt.Point_location)=1
 AND ct.area_id = lt.area_id
</code>```

Body:
I have 2 tables:
- first one containing spatial data - geometry of circles
- second contains geometries of lines.

I want to find all lines which are inside each circle. I have a query which can do that, however there are millions of records so it is unusably slow.
There is a column in both tables which is area_id and essentially all circles are assigned to particular area and all lines as well, so if I can do the intersect of the circles only with the lines in the matching area this will reduce the load a lot. The problem is I can't think of solution e.g. using windowing function. The query I am using is:

Select ct.AREA_ID, ct.Circle_descr,  lt.Line_descr from circles_table as ct
JOIN lines_table as lt
ON
circles_table.Circle_location.STIntersects(points_table.Point_location)=1

*using a where clause at the end makes no difference as it is essentially part of the slow join...

+---------------+----------------------+--------------------------+
| AREA_ID (int) | Circle_descr(varchar) | Circle_location(geometry)|
+---------------+----------------------+--------------------------+

+---------------+---------------------+-------------------------+
| AREA_ID (int) | Line_descr(varchar) | Line_location(geometry) |
+---------------+---------------------+-------------------------+

Body:
Add an additional join criterion to partition the rows by area_id before comparing them.  Something like

Select ct.AREA_ID, ct.Circle_descr,  lt.Line_descr
from circles_table as ct
JOIN lines_table as lt
  ON ct.Circle_location.STIntersects(lt.Point_location)=1
 AND ct.area_id = lt.area_id


问:
group all directly and indirectly related records using python pandas
thanks in advance:

I am trying to generate a group identifier in a many to many relationship table which has 2 columns defining IDs of parent entities and a child entities:

Example dataframe below: (parent (p), and child (c))

```<code>df = pd.DataFrame(np.array([[1,7],[1,3],[1,4],[3,2],[5,1],[6,0]]))
df.columns= ['p', 'c']
</code>```

Table looks like below:

```<code>p  c
1  7
1  3
1  4
3  2
5  1
6  0
</code>```

I am trying to get all directly and indirectly linked records in a group. For example:

Parent Record 1 is parent of [7,3,4], and

Parent Record 5 is the parent of 1

Parent Record 3 has is parent of 2 and 2 is grand-child of 1

So I want to generate an ID for all related record. where parent record 6 is not related to any record, I will move it to another group, a sample result like below:

```<code>p  c  grp
1  7  A
1  3  A
1  4  A
3  2  A
5  1  A
6  0  B
</code>```

My current way of thinking :

For each record, if it doesn't have a group yet:

Getting all directly related record IDs

Then for each directly related record IDs Recursively perform the same function to find all related record for the child until they have no child record

Then assign a group to the group of record IDs (list)

I am not sure if it is the right way to do it, and it seemed to be unnecessarily slow, and I have to pass down all the parent records in the chain to the child record in order for it not to perform the same search for already searched results.

Would really appreciate if someone can give me a better solution. :)

答:
I'll post my solution because it is faster (for this small dataset) and hoping someone will make it more efficient.

```<code>import netowrkx as nx
import pandas as pd
df = pd.DataFrame(np.array([[1,7],[1,3],[1,4],[3,2],[5,1],[6,0]]))
df.columns= ['p', 'c']

G = nx.from_pandas_dataframe(df, 'p','c')
subgraphs = list(nx.connected_components(G))
grouplist = list('BA')

def defineGrouping(x):
    return grouplist[[n for n,i in enumerate(subgraphs) if x in i][0]]

df['grp'] = df.c.map(defineGrouping)
df
</code>```

Output:

```<code>   p  c grp
0  1  7   A
1  1  3   A
2  1  4   A
3  3  2   A
4  5  1   A
5  6  0   B
</code>```

Timing because I suspected that Pandas overhead is significant

@Wen's method converting connected_components back to pandas dataframe

100 loops, best of 3: 6.47 ms per loop

This method of using list comprehension and enumerate:

1000 loops, best of 3: 1.14 ms per loop

Body:
thanks in advance:

I am trying to generate a group identifier in a many to many relationship table which has 2 columns defining IDs of parent entities and a child entities:

Example dataframe below: (parent (p), and child (c))

df = pd.DataFrame(np.array([[1,7],[1,3],[1,4],[3,2],[5,1],[6,0]]))
df.columns= ['p', 'c']

Table looks like below:

p  c
1  7
1  3
1  4
3  2
5  1
6  0

I am trying to get all directly and indirectly linked records in a group. For example:

Parent Record 1 is parent of [7,3,4], and

Parent Record 5 is the parent of 1

Parent Record 3 has is parent of 2 and 2 is grand-child of 1

So I want to generate an ID for all related record. where parent record 6 is not related to any record, I will move it to another group, a sample result like below:

p  c  grp
1  7  A
1  3  A
1  4  A
3  2  A
5  1  A
6  0  B

My current way of thinking :

For each record, if it doesn't have a group yet:

Getting all directly related record IDs

Then for each directly related record IDs Recursively perform the same function to find all related record for the child until they have no child record

Then assign a group to the group of record IDs (list)

I am not sure if it is the right way to do it, and it seemed to be unnecessarily slow, and I have to pass down all the parent records in the chain to the child record in order for it not to perform the same search for already searched results.

Would really appreciate if someone can give me a better solution. :)

Body:
I'll post my solution because it is faster (for this small dataset) and hoping someone will make it more efficient.

import netowrkx as nx
import pandas as pd
df = pd.DataFrame(np.array([[1,7],[1,3],[1,4],[3,2],[5,1],[6,0]]))
df.columns= ['p', 'c']

G = nx.from_pandas_dataframe(df, 'p','c')
subgraphs = list(nx.connected_components(G))
grouplist = list('BA')

def defineGrouping(x):
    return grouplist[[n for n,i in enumerate(subgraphs) if x in i][0]]

df['grp'] = df.c.map(defineGrouping)
df

Output:

   p  c grp
0  1  7   A
1  1  3   A
2  1  4   A
3  3  2   A
4  5  1   A
5  6  0   B

Timing because I suspected that Pandas overhead is significant

@Wen's method converting connected_components back to pandas dataframe

100 loops, best of 3: 6.47 ms per loop

This method of using list comprehension and enumerate:

1000 loops, best of 3: 1.14 ms per loop


问:
Adding a delay to inline onmouseover
I am working on a page which allows you to view items on a google map. You can hover over a business address and it will move the map to that location and open an infowindow.  It works perfectly, but the onmouseover event is inline because every onmouseover has a different id, which is set by a php variable.

The problem is, I need to find a way to add a delay to the onmouseover event, so that the user has to hover over the item for a couple of seconds before the onmouseover is triggered.

I've looked around at some possible solutions, but nothing seems to add the delay.

The onmouseover link looks like this...

```<code><a onmouseover="javascript:triggerClick(<?php echo $id; ?>)" href="<?php echo $listingurl; ?>">
</code>```

Any suggestions would be appreciated.

答:
You could create something yourself. Split the onmouseover event into onmouseenter and onmouseleave. This will allow you to start a timeout in the onmouseenter event and clear it in the onmouseleave event.

```<code>function onEnter(){
  timeout = setTimeout(function(){
    //your code
  }, 1000);
}

function onLeave(){
  //in case the user leaves early stop the excution of your code
  clearTimeout(timeout);
}
</code>```

This way you will have a 1 second timeout before your actions triggers and it will not trigger if the user leaves before the time runs out.

EDIT

This is the practical use case https://codepen.io/anon/pen/YEMpBx

```<code><a onmouseover="triggerClick(<?php echo $id; ?>, this)">Foo</a>

function triggerClick(id, element){
  var timeout = setTimeout(function(){
    //your code here
  }, 1000);

  element.addEventListener('mouseleave', function triggerLeave(event){
    clearTimeout(timeout);
    element.removeEventListener('mouseleave', triggerLeave);
  });
}
</code>```

Title: Adding a delay to inline onmouseover

Body:
I am working on a page which allows you to view items on a google map. You can hover over a business address and it will move the map to that location and open an infowindow.  It works perfectly, but the onmouseover event is inline because every onmouseover has a different id, which is set by a php variable.

The problem is, I need to find a way to add a delay to the onmouseover event, so that the user has to hover over the item for a couple of seconds before the onmouseover is triggered.

I've looked around at some possible solutions, but nothing seems to add the delay.

The onmouseover link looks like this...

<a onmouseover="javascript:triggerClick(<?php echo $id; ?>)" href="<?php echo $listingurl; ?>">

Any suggestions would be appreciated.

Body:
You could create something yourself. Split the onmouseover event into onmouseenter and onmouseleave. This will allow you to start a timeout in the onmouseenter event and clear it in the onmouseleave event.

function onEnter(){
  timeout = setTimeout(function(){
    //your code
  }, 1000);
}

function onLeave(){
  //in case the user leaves early stop the excution of your code
  clearTimeout(timeout);
}

This way you will have a 1 second timeout before your actions triggers and it will not trigger if the user leaves before the time runs out.

EDIT

This is the practical use case https://codepen.io/anon/pen/YEMpBx

<a onmouseover="triggerClick(<?php echo $id; ?>, this)">Foo</a>

function triggerClick(id, element){
  var timeout = setTimeout(function(){
    //your code here
  }, 1000);

  element.addEventListener('mouseleave', function triggerLeave(event){
    clearTimeout(timeout);
    element.removeEventListener('mouseleave', triggerLeave);
  });
}


问:
Print out a list of items with Django
I'm developing a Django project and i'm trying to solve an issue.

My main scope is getting a JSON file through a url and print out the data into a table(HTML).

To be more clearly, i got an Object like referred below and every record i would like to printed into my table.

```<code>{
"myData": [{
            "name": "John",
            "surname": "Williams",
            "birthday": "05/12/1997",
        }, {
            "name": "John",
            "surname": "Williams",
            "birthday": "05/12/1997",
        },]}

<table class="table table-striped table-hover table-bordered">
          <thead class="thead-dark">
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Birth Day</th>
            </tr>
          </thead>
          <tbody>
              {% for myData in range(20) %}
                <tr>
                    <td> {{ myData.name }} </td>
                    <td> {{ myData.surname }} </td>
                    <td> {{ myData.birthday }} </td>
                </tr>
              {% endfor %}
          </tbody>
        </table>
</code>```

I find it as a very common implementation but still i can't find a solution. Also when i'm trying to run the code below inside my views.py file everything works great but If i'm trying to send data into an .html file i got multiple errors.

```<code>for i in range(5):
    print name[i]
</code>```

The first one when i wrote

```<code>{% for x in range(20) %}
</code>```

I got this error :

Could not parse the remainder: '(20)' from 'range(20)'

Then I'm trying to pass range(20) as a variable from views.py file so i change the object line of code as

```<code>Object = {'name': name, .... , 'range': range(20)}
</code>```

This time i was lucky with the remainder error but still unlucky with my data.

答: Try to use a cycle of this kind {%for element in myData%} and in table you will  write  {{ element.name }} , etc.</p>

Title: Print out a list of items with Django

Body:
I'm developing a Django project and i'm trying to solve an issue.

My main scope is getting a JSON file through a url and print out the data into a table(HTML).

To be more clearly, i got an Object like referred below and every record i would like to printed into my table.

{
"myData": [{
            "name": "John",
            "surname": "Williams",
            "birthday": "05/12/1997",
        }, {
            "name": "John",
            "surname": "Williams",
            "birthday": "05/12/1997",
        },]}

                First Name
                Last Name
                Birth Day

              {% for myData in range(20) %}

                     {{ myData.name }}
                     {{ myData.surname }}
                     {{ myData.birthday }}

              {% endfor %}

I find it as a very common implementation but still i can't find a solution. Also when i'm trying to run the code below inside my views.py file everything works great but If i'm trying to send data into an .html file i got multiple errors.

for i in range(5):
    print name[i]

The first one when i wrote

{% for x in range(20) %}

I got this error :

Could not parse the remainder: '(20)' from 'range(20)'

Then I'm trying to pass range(20) as a variable from views.py file so i change the object line of code as

Object = {'name': name, .... , 'range': range(20)}

This time i was lucky with the remainder error but still unlucky with my data.


问:
How to force relative paths in Android Lint baseline
I'm attempting to create a baseline lint file for my Android project. I've got a block set up in my main module's build.gradle:

```<code>lintOptions {
    <some includes/excludes>

    baseline file("lint-baseline.xml")

    checkAllWarnings true
    warningsAsErrors true
    abortOnError false
}
</code>```

I then create the baseline with ./gradlew lint<flavor/variant> and have set up my unit test task to depend on lint.

However, this gives a baseline file that includes some absolute paths. The culprits seem to be either a) in a submodule (but only some submodules, not all), or b) in my local gradle cache. When I push the baseline to our CI, it comes up with a bunch of new warnings because the paths don't match exactly.

Some examples include:

```<code><location
        file="/Users/.../android/<submodule>/src/main/res/values/strings.xml"
        line="4"
        column="13"/>

<location
        file="/Users/.../.gradle/caches/modules-2/files-2.1/com.google.auto.value/auto-value/1.3/4961194f62915eb45e21940537d60ac53912c57d/auto-value-1.3.jar"/>
</code>```

How do I force lint to create the baseline using relative paths?

答:
use own baseline.xml for each module. paths will be relative to module root directory.

UPDATE
try to use only one baseline.xml put put it to the root gradle project above modules like this

```<code>project/app/build.gradle
project/module1/build.gradle
project/build.gradle
project/lint-baseline.xml
</code>```

in module's build.gradle use such snippet

```<code>lintOptions {
    baselineFile = rootProject.file('lint-baseline.xml')
}
</code>```

UPDATE 2
use own baseline.xml for each module. paths will be relative to module root directory.
in module's build.gradle use such snippet

```<code>lintOptions {
    baselineFile = project.file('lint-baseline.xml')
    checkDependencies = false
}
</code>```

Body:
I'm attempting to create a baseline lint file for my Android project. I've got a block set up in my main module's build.gradle:

lintOptions {
    <some includes/excludes>

    baseline file("lint-baseline.xml")

    checkAllWarnings true
    warningsAsErrors true
    abortOnError false
}

I then create the baseline with ./gradlew lint<flavor/variant> and have set up my unit test task to depend on lint.

However, this gives a baseline file that includes some absolute paths. The culprits seem to be either a) in a submodule (but only some submodules, not all), or b) in my local gradle cache. When I push the baseline to our CI, it comes up with a bunch of new warnings because the paths don't match exactly.

Some examples include:

<location
        file="/Users/.../android/<submodule>/src/main/res/values/strings.xml"
        line="4"
        column="13"/>

<location
        file="/Users/.../.gradle/caches/modules-2/files-2.1/com.google.auto.value/auto-value/1.3/4961194f62915eb45e21940537d60ac53912c57d/auto-value-1.3.jar"/>

How do I force lint to create the baseline using relative paths?

Body:
use own baseline.xml for each module. paths will be relative to module root directory.

UPDATE
try to use only one baseline.xml put put it to the root gradle project above modules like this

project/app/build.gradle
project/module1/build.gradle
project/build.gradle
project/lint-baseline.xml

in module's build.gradle use such snippet

lintOptions {
    baselineFile = rootProject.file('lint-baseline.xml')
}

UPDATE 2
use own baseline.xml for each module. paths will be relative to module root directory.
in module's build.gradle use such snippet

lintOptions {
    baselineFile = project.file('lint-baseline.xml')
    checkDependencies = false
}


问:
Return manager's samacountname for users
I've got a requirement to create a CSV file of all active users from AD including the line manager attribute, however I need the line managers sAMAccountName, not the cn.  Here is what I have so far:

Get-ADUser -server server_ip -Filter { mail -like "*" -and ObjectClass -eq "user" } `
  -SearchBase "OU=Active Users,DC=eu,DC=ad,DC=some_company,DC=com" `
  -Properties objectGUID,displayName,office,division,department,employeeNumber,
    employeeID,mobilePhone,officePhone,ipphone,title,givenName,surname,mail,
    manager,sAMAccountName |
  Export-CSV "EU_AD_Properties.csv"
```

<p>This returns all the data I want, but gives me the line manager's <code>cn</code>, not the <code>samacountname</code>.</p>

<p>Any ideas?</p>

<p>I've tried this:</p>

<pre class="lang-psh prettyprint-override"><code>Get-ADUser -server server_ip -Filter { mail -like "*" -and ObjectClass -eq "user" } `
  -SearchBase "OU=Active Users,DC=eu,DC=ad,DC=some_company,DC=com" `
  -Properties objectGUID,displayName,office,division,department,employeeNumber,
    employeeID,mobilePhone,officePhone,ipphone,title,givenName,surname,mail,
    @{Label="Manager";Expression={(Get-aduser -filter {sAMAccountName -eq $_.Manager}.sAMAaccountName)}},
    sAMAccountName |
  Export-CSV "EU_AD_Properties.csv"
</code>```

However this errors out.

答:
```<code>Get-ADUser -Filter * -Properties Name,SamAccountName,AccountExpirationDate,Manager | select Name,SamAccountName,AccountExpirationDate,@{N='Manager';E={(Get-ADUser $_.Manager).sAMAccountName}} | Export-Csv "Userdata.csv"
</code>```

Body:
I've got a requirement to create a CSV file of all active users from AD including the line manager attribute, however I need the line managers sAMAccountName, not the cn.  Here is what I have so far:

Get-ADUser -server server_ip -Filter { mail -like "*" -and ObjectClass -eq "user" } `
  -SearchBase "OU=Active Users,DC=eu,DC=ad,DC=some_company,DC=com" `
  -Properties objectGUID,displayName,office,division,department,employeeNumber,
    employeeID,mobilePhone,officePhone,ipphone,title,givenName,surname,mail,
    manager,sAMAccountName |
  Export-CSV "EU_AD_Properties.csv"

This returns all the data I want, but gives me the line manager's cn, not the samacountname.

Any ideas?

I've tried this:

Get-ADUser -server server_ip -Filter { mail -like "*" -and ObjectClass -eq "user" } `
  -SearchBase "OU=Active Users,DC=eu,DC=ad,DC=some_company,DC=com" `
  -Properties objectGUID,displayName,office,division,department,employeeNumber,
    employeeID,mobilePhone,officePhone,ipphone,title,givenName,surname,mail,
    @{Label="Manager";Expression={(Get-aduser -filter {sAMAccountName -eq $_.Manager}.sAMAaccountName)}},
    sAMAccountName |
  Export-CSV "EU_AD_Properties.csv"

However this errors out.


问:
How to list all available locale files in Android app?
How to dynamically list all available locale files in an Android app?

I wish to add the option for the user to override the default locale in my app, and select from a list of the ones I've already created, however did not want to hardcode such a list and having to touch the code for every new localization file I create.

Is it possible to obtain such a listing dynamically?

答:
You can use getAssets().getLocales() from Activity. This is much more prefered way of getting all the Locales as it get's the locales that this AssetManager contains data for.

OR

You can also use the Locale.getAvailableLocales() method, which returns an array of all installed Locales. It's available in API level 1

Once you get this list you can populate it in a Spinner or any widget you wish.


问:
jQuery add or remove class based on menu item clicked
I tried this, searched on StackOverflow.

```<code>$(".sub>li>a").click(function(e) {
    if( $(this).hasClass("open") ) {
        $(this).removeClass("open").addClass("closed");
    } else {
        // if other menus are open remove open class and add closed
        $(this).siblings().removeClass("open").addClass("closed");
        $(this).removeClass("closed").addClass("open");
    }
});
</code>```

But it does not work.

Here is my fiddle. https://jsfiddle.net/v2oLfcnf/

答:
Here you go with a solution https://jsfiddle.net/v2oLfcnf/8/

$('.sub > li > a').click(function(){
  $('.sublist').fadeOut();
  $(this).closest('ul.sub').next('ul.sublist').fadeIn();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a{
  text-decoration: none;
  color: white;
}
a:hover{
  color: #D8B490;
}

li{
  text-decoration: none;
  list-style: none;

}
.sub{
 position: relative;
 top: 20%;
}

#info,#study,#edu,#sup{
  display: inline-block;z-index: 5;
  position: relative;
  margin: 2%;
}

#top{
  z-index: 80;
  background:#D8B490;
  width: 100%;
}

.menu{
  position: absolute;
  top:5%;
  background: /*#69341C;*/ #302F42;
  color: white;
  height: 100px;
  z-index:55;
  width: 100%;
}
.sub{
  display: inline-block;
}

/*hide menu, if clicked .sub>li>a , fadeIn() below*/
.one{
  width: 50%;
  height: 20%;
  display: block;
  background: white;
  position: absolute;
  left: 40%;
  top: 88%;
  color: red;
  display: none;
}

.two{
  display: none;
  color: red;
  width: 50%;
  height: 20%;
  background: white;
  position: absolute;
  left: 40%;
  top: 88%;
}

.three{
  display: none;
  color: red;
  width: 50%;
  height: 20%;
  background: white;
  position: absolute;
  left: 40%;
  top: 88%;
}

.four{
  display: none;
  width: 50%;
  height: 20%;
  color: red;
  background: white;
  position: absolute;
  left: 40%;
  top: 88%;
}</code>```

       infomation

a

b

       study

c

d

      edu

e

f

      support

g

h

```

Hope this will help you.

Body:
I tried this, searched on StackOverflow.

$(".sub>li>a").click(function(e) {
    if( $(this).hasClass("open") ) {
        $(this).removeClass("open").addClass("closed");
    } else {
        // if other menus are open remove open class and add closed
        $(this).siblings().removeClass("open").addClass("closed");
        $(this).removeClass("closed").addClass("open");
    }
});

But it does not work.

Here is my fiddle. https://jsfiddle.net/v2oLfcnf/

Body:
Here you go with a solution https://jsfiddle.net/v2oLfcnf/8/

$('.sub > li > a').click(function(){
  $('.sublist').fadeOut();
  $(this).closest('ul.sub').next('ul.sublist').fadeIn();
});

a{
  text-decoration: none;
  color: white;
}
a:hover{
  color: #D8B490;
}

li{
  text-decoration: none;
  list-style: none;

}
.sub{
 position: relative;
 top: 20%;
}

#info,#study,#edu,#sup{
  display: inline-block;z-index: 5;
  position: relative;
  margin: 2%;
}

#top{
  z-index: 80;
  background:#D8B490;
  width: 100%;
}

.menu{
  position: absolute;
  top:5%;
  background: /*#69341C;*/ #302F42;
  color: white;
  height: 100px;
  z-index:55;
  width: 100%;
}
.sub{
  display: inline-block;
}

/*hide menu, if clicked .sub>li>a , fadeIn() below*/
.one{
  width: 50%;
  height: 20%;
  display: block;
  background: white;
  position: absolute;
  left: 40%;
  top: 88%;
  color: red;
  display: none;
}

.two{
  display: none;
  color: red;
  width: 50%;
  height: 20%;
  background: white;
  position: absolute;
  left: 40%;
  top: 88%;
}

.three{
  display: none;
  color: red;
  width: 50%;
  height: 20%;
  background: white;
  position: absolute;
  left: 40%;
  top: 88%;
}

.four{
  display: none;
  width: 50%;
  height: 20%;
  color: red;
  background: white;
  position: absolute;
  left: 40%;
  top: 88%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <ul class="sub">
    <li>
      <a href="#" id="info"> infomation</a>
    </li>
  </ul>
 <ul class="one sublist">
    <li>a</li>
    <li>b</li>
  </ul>
 <ul class="sub">
    <li>
      <a href="#" id="study"> study</a>
    </li>
 </ul>
  <ul class="two sublist">
    <li>c</li>
    <li>d</li>
  </ul>

 <ul class="sub">
    <li>
      <a href="#" id="edu">edu</a>
    </li>
  </ul>
  <ul class="three sublist">
    <li>e</li>
    <li>f</li>
  </ul>
 <ul class="sub">
    <li>
      <a href="#" id="sup">support</a>
    </li>
  </ul>

  <ul class="four sublist">
    <li>g</li>
    <li>h</li>
  </ul>
</div>

Hope this will help you.


问:
C#: How do I do simple math, with rounding, on integers?
i want the result of an equation rounded to the nearest integer.
e.g.

```<code>137 * (3/4) = 103
</code>```

Consider the following incorrect code.

```<code>int width1 = 4;
int height1 = 3;

int width2 = 137;
int height2 = width2 * (height1 / width1);
</code>```

What is the proper way to perform "integer" math in C#?

Do i really have to do:

```<code>int height2 = (int)Math.Round(
      (float)width2 * ((float)height1 / (float)width1)
   );
</code>```

答: Never cast to float, it has even less precision than a 32-bit integer. If you're going to use floating point, always use double instead of float.</p>

ContentLicense: CC BY-SA 2.5

Body:
i want the result of an equation rounded to the nearest integer.
e.g.

137 * (3/4) = 103

Consider the following incorrect code.

int width1 = 4;
int height1 = 3;

int width2 = 137;
int height2 = width2 * (height1 / width1);

What is the proper way to perform "integer" math in C#?

Do i really have to do:

int height2 = (int)Math.Round(
      (float)width2 * ((float)height1 / (float)width1)
   );

OwnerDisplayName: rwallace


问:
Source Code Protection
When you compile a program to publish with Visual Studio 2010, does that have any advanced methods to keep your program being decompiled to source code? Are there any methods you would use to encrypt yoursource code before compiling?</p>

答:
VS and any other good compiler make optimalizations. Solely these optimalizations are often enough to make your application resist reverse engineering attempts.

This will not encrypt constants in your program so mypass will still be found as mypass in the binary. You need an encryption program for that.

Alas I have no idea what the good and bad encryption programs are for binaries so I won't suggest any.

Title: Source Code Protection


问:
Restoring screen brightness when terminating app in iOS
I've seen the previous posts about the inability to ensure you can restore the screen brightness to the value it was before the user adjusted it within your app (i.e. capture the brightness level of the screen before your app loads and reset to that screen brightness before your app terminates or goes into the background). It appears that this might have been something that Apple did on purpose as to not make a dramatic change the user doesn't know about upon termination of the app. But it appears that Apple is somehow pulling this off with the Passbook app. Notice that when you launch into the Passbook app the screen brightness increases to allow scanners to read the bar codes better, but when you hit the home button and exit the Passbook app the screen brightness returns to what it was previously. If Apple can do this why can't we? Anybody know how the Passbook app does this?</p>

答:
In Swift</p>

```<code>static var defaultBrightNess:CGFloat = 0.5;
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
{
        AppDelegate.defaultBrightNess = UIScreen.main.brightness;
        UIScreen.main.brightness = 1.0;
        return true
}

func applicationWillEnterForeground(_ application: UIApplication) {
        UIScreen.main.brightness = 1.0
}

func applicationWillResignActive(_ application: UIApplication) {
        UIScreen.main.brightness = CGFloat(AppDelegate.defaultBrightNess)
}
</code>```

Body:
In Swift

static var defaultBrightNess:CGFloat = 0.5;
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
{
        AppDelegate.defaultBrightNess = UIScreen.main.brightness;
        UIScreen.main.brightness = 1.0;
        return true
}

func applicationWillEnterForeground(_ application: UIApplication) {
        UIScreen.main.brightness = 1.0
}

func applicationWillResignActive(_ application: UIApplication) {
        UIScreen.main.brightness = CGFloat(AppDelegate.defaultBrightNess)
}


问:
How to set React to production mode when using Gulp
I need to run React in production mode, which presumably entails defining the following somewhere in the enviornment:

```<code>process.env.NODE_ENV = 'production';
</code>```

The issue is that I'm running this behind Tornado (a python web-server), not Node.js. I also use Supervisord to manage the tornado instances, so it's not abundantly clear how to set this in the running environment.

I do however use Gulp to build my jsx files to javascript.

Is it possible to somehow set this inside Gulp? And if so, how do I check that React is running in production mode?

Here is my Gulpfile.js:

```<code>'use strict';

var gulp = require('gulp'),
        babelify = require('babelify'),
        browserify = require('browserify'),
        browserSync = require('browser-sync'),
        source = require('vinyl-source-stream'),
        uglify = require('gulp-uglify'),
        buffer = require('vinyl-buffer');

var vendors = [
    'react',
    'react-bootstrap',
    'jquery',
];

gulp.task('vendors', function () {
        var stream = browserify({
                        debug: false,
                        require: vendors
                });

        stream.bundle()
                    .pipe(source('vendors.min.js'))
                    .pipe(buffer())
                    .pipe(uglify())
                    .pipe(gulp.dest('build/js'));

        return stream;
});

gulp.task('app', function () {
        var stream = browserify({
                        entries: ['./app/app.jsx'],
                        transform: [babelify],
                        debug: false,
                        extensions: ['.jsx'],
                        fullPaths: false
                });

        vendors.forEach(function(vendor) {
                stream.external(vendor);
        });

        return stream.bundle()
                                 .pipe(source('build.min.js'))
                                 .pipe(buffer())
                                 .pipe(uglify())
                                 .pipe(gulp.dest('build/js'));

});

gulp.task('watch', [], function () {
    // gulp.watch(['./app/**/*.jsx'], ['app', browserSync.reload]);
    gulp.watch(['./app/**/*.jsx'], ['app']);
});

gulp.task('browsersync',['vendors','app'], function () {
        browserSync({
            server: {
                baseDir: './',
            },
            notify: false,
            browser: ["google chrome"]
    });
});

gulp.task('default',['browsersync','watch'], function() {});
</code>```

答:
Unfortunately none of the above answers work, because setting process.env.NODE_ENV has no effect in Browserify. The resulting bundle still has process.env.NODE_ENV references in it and hence

Browserify will not require() the React production version modules,

the minifier will not be able to remove dead code, and

the application will still be running in debug mode.

This is unfortunately not the only place where this approach is offered as the correct answer :-(

The correct approach can be found in e.g.

https://github.com/hughsk/envify/issues/15#issuecomment-62229101

https://reactjs.org/docs/optimizing-performance.html#browserify

You need to switch the envify transform to be a global one, e.g.

```<code># note the "-g" instead of the usual "-t"
$ browserify ... -g [ envify --NODE_ENV production ] ....
</code>```

or in gulpfile.js

```<code>browserify(...)
    ...
    .transform('envify', {
        global:   true, // also apply to node_modules
        NODE_ENV: debug ? 'development' : 'production',
    })
    ...
    .bundle()
    ...
    .pipe(gulpif(!debug, babelMinify())) // my example uses gulp-babel-minify
    ...
</code>```

Body:
I need to run React in production mode, which presumably entails defining the following somewhere in the enviornment:

process.env.NODE_ENV = 'production';

The issue is that I'm running this behind Tornado (a python web-server), not Node.js. I also use Supervisord to manage the tornado instances, so it's not abundantly clear how to set this in the running environment.

I do however use Gulp to build my jsx files to javascript.

Is it possible to somehow set this inside Gulp? And if so, how do I check that React is running in production mode?

Here is my Gulpfile.js:

'use strict';

var gulp = require('gulp'),
        babelify = require('babelify'),
        browserify = require('browserify'),
        browserSync = require('browser-sync'),
        source = require('vinyl-source-stream'),
        uglify = require('gulp-uglify'),
        buffer = require('vinyl-buffer');

var vendors = [
    'react',
    'react-bootstrap',
    'jquery',
];

gulp.task('vendors', function () {
        var stream = browserify({
                        debug: false,
                        require: vendors
                });

        stream.bundle()
                    .pipe(source('vendors.min.js'))
                    .pipe(buffer())
                    .pipe(uglify())
                    .pipe(gulp.dest('build/js'));

        return stream;
});

gulp.task('app', function () {
        var stream = browserify({
                        entries: ['./app/app.jsx'],
                        transform: [babelify],
                        debug: false,
                        extensions: ['.jsx'],
                        fullPaths: false
                });

        vendors.forEach(function(vendor) {
                stream.external(vendor);
        });

        return stream.bundle()
                                 .pipe(source('build.min.js'))
                                 .pipe(buffer())
                                 .pipe(uglify())
                                 .pipe(gulp.dest('build/js'));

});

gulp.task('watch', [], function () {
    // gulp.watch(['./app/**/*.jsx'], ['app', browserSync.reload]);
    gulp.watch(['./app/**/*.jsx'], ['app']);
});

gulp.task('browsersync',['vendors','app'], function () {
        browserSync({
            server: {
                baseDir: './',
            },
            notify: false,
            browser: ["google chrome"]
    });
});

gulp.task('default',['browsersync','watch'], function() {});

Body:
Unfortunately none of the above answers work, because setting process.env.NODE_ENV has no effect in Browserify. The resulting bundle still has process.env.NODE_ENV references in it and hence

Browserify will not require() the React production version modules,

the minifier will not be able to remove dead code, and

the application will still be running in debug mode.

This is unfortunately not the only place where this approach is offered as the correct answer :-(

The correct approach can be found in e.g.

https://github.com/hughsk/envify/issues/15#issuecomment-62229101

https://reactjs.org/docs/optimizing-performance.html#browserify

You need to switch the envify transform to be a global one, e.g.

# note the "-g" instead of the usual "-t"
$ browserify ... -g [ envify --NODE_ENV production ] ....

or in gulpfile.js

browserify(...)
    ...
    .transform('envify', {
        global:   true, // also apply to node_modules
        NODE_ENV: debug ? 'development' : 'production',
    })
    ...
    .bundle()
    ...
    .pipe(gulpif(!debug, babelMinify())) // my example uses gulp-babel-minify
    ...


问:
Is there standard way to get numerical consistency in Julia
```<code>└─╼ julia
 Version 0.6.0 (2017-06-19 13:05 UTC)
 julia> 1.0 + 0.1 - 1.0 - 0.1 == 0
  false
 julia> 1.0 + 0.1 - 1.0 - 0.1
  8.326672684688674e-17
</code>```

i understand that decimals like 0.1 cannot be represented exactly in binary based point without some additional effort e.g.

```<code>julia> 1//10
 1//10
julia> 1 + 1//10
 11//10
julia> 1 + 1//10 - 1
 1//10
julia> 1 + 1//10 - 1 - 1//10
 0//1
julia> 1 + 1//10 - 1 - 1//10 == 0
 true
</code>```

or going purely symbolic.

there are several rounding options:
    julia> Round
    RoundDown            RoundNearest          RoundNearestTiesUp    RoundUp
    RoundFromZero        RoundNearestTiesAway  RoundToZero     RoundingMode

Without launching into a protracted discussion of numerical stability, does Julia have a recommended style?

thx

答:
Generally speaking, it is useless to worry about this "inconsistency". Your number is wrong in the sixteenth decimal, which is much less than the size of an atom when you measure the circumference of the Earth.

In practice the quantities you are dealing with are measured with some resolution and accuracy, are described by approximate models and computed with truncated methods.

It matters to take care of the real sources of errors and the numerical processes that amplify them. In other words, have a feeling for error calculus. Moving to exact arithmetic is often a nonsense.

Body:
└─╼ julia
 Version 0.6.0 (2017-06-19 13:05 UTC)
 julia> 1.0 + 0.1 - 1.0 - 0.1 == 0
  false
 julia> 1.0 + 0.1 - 1.0 - 0.1
  8.326672684688674e-17

i understand that decimals like 0.1 cannot be represented exactly in binary based point without some additional effort e.g.

julia> 1//10
 1//10
julia> 1 + 1//10
 11//10
julia> 1 + 1//10 - 1
 1//10
julia> 1 + 1//10 - 1 - 1//10
 0//1
julia> 1 + 1//10 - 1 - 1//10 == 0
 true

or going purely symbolic.

there are several rounding options:
    julia> Round
    RoundDown            RoundNearest          RoundNearestTiesUp    RoundUp
    RoundFromZero        RoundNearestTiesAway  RoundToZero     RoundingMode

Without launching into a protracted discussion of numerical stability, does Julia have a recommended style?

thx


问:
What does the '&' sign do when using 'auto' for iteration
recently I've encountered very very peculiar question when using auto in C++, just ... just look at the following code snippet :

my main function:

```<code>#include <list>
#include <iostream>
#include <stdio.h>
int main(){
    int a = 10, b = 20, c = 30;
    list<int> what;
    what.push_back(a);
    what.push_back(b);
    what.push_back(c);

    read(what);

    return 0;
}
</code>```

And here's function read:

```<code>void read(const list<int>& con){

    for (auto it : con){
        printf("%p\n", &it);
        cout << it << endl;
    }
    return ;
}
</code>```

And here's is the output :

```<code>0x7fffefff66a4
10
0x7fffefff66a4
20
0x7fffefff66a4
30
</code>```

What the heck is that? Same address with different content !?

And more strange this is, if I modify the for-loop by adding an '&'

that is:

```<code>for (auto& it : con){
</code>```

All the output makes sense immediately, the addresses would change by iteration

So my question is,

Why does the '&' sign make a change under this circumstance?

答:
Note that auto is standing in for int in your case. So it's a red herring. Consider

```<code>for (int i = 0; i < 10; ++i){
    int j = i;
    cout << (void*)&j << '\n';
}
</code>```

Since j has automatic storage duration, it is most likely created each time with the same address - but points to a different value - , j is being pushed then popped from a stack on each iteration (let's set aside compiler optimisations). That is what is happening in your case with for (auto it : con){. it has automatic storage duration.

When you write

```<code>for (auto& it : con){
</code>```

it is a reference to an int within the container con, so its address will differ on each iteration.

Body:
recently I've encountered very very peculiar question when using auto in C++, just ... just look at the following code snippet :

my main function:

#include <list>
#include <iostream>
#include <stdio.h>
int main(){
    int a = 10, b = 20, c = 30;
    list<int> what;
    what.push_back(a);
    what.push_back(b);
    what.push_back(c);

    read(what);

    return 0;
}

And here's function read:

void read(const list<int>& con){

    for (auto it : con){
        printf("%p\n", &it);
        cout << it << endl;
    }
    return ;
}

And here's is the output :

0x7fffefff66a4
10
0x7fffefff66a4
20
0x7fffefff66a4
30

What the heck is that? Same address with different content !?

And more strange this is, if I modify the for-loop by adding an '&'

that is:

for (auto& it : con){

All the output makes sense immediately, the addresses would change by iteration

So my question is,

Why does the '&' sign make a change under this circumstance?

Body:
Note that auto is standing in for int in your case. So it's a red herring. Consider

for (int i = 0; i < 10; ++i){
    int j = i;
    cout << (void*)&j << '\n';
}

Since j has automatic storage duration, it is most likely created each time with the same address - but points to a different value - , j is being pushed then popped from a stack on each iteration (let's set aside compiler optimisations). That is what is happening in your case with for (auto it : con){. it has automatic storage duration.

When you write

for (auto& it : con){

it is a reference to an int within the container con, so its address will differ on each iteration.


问:
number as a result in select in mysql database

I run query:

```<code>SELECT ifnull(TIME_TO_SEC( TIMEDIFF( a.ending, a.begining ))/60,0)
FROM visits` a
</code>```

and I wouls like  NUMBER as a result

but i recived like this

```<code>0.0000
50.0000
50.0000
0.0000
0.0000
50.0000
</code>```

I expect as below:

```<code>0
50
50
0
0
50
</code>```

or 50,00

it means I need return number

答:
To get integer result, use DIV insted of /. Something like this:

```<code>SELECT IFNULL( TIME_TO_SEC( TIMEDIFF( a.ending, a.begining ) ) DIV 60, 0 )
FROM visits a
</code>```

Body:
I run query:

SELECT ifnull(TIME_TO_SEC( TIMEDIFF( a.ending, a.begining ))/60,0)
FROM visits` a

and I wouls like  NUMBER as a result

but i recived like this

0.0000
50.0000
50.0000
0.0000
0.0000
50.0000

I expect as below:

0
50
50
0
0
50

or 50,00

it means I need return number

Body:
To get integer result, use DIV insted of /. Something like this:

SELECT IFNULL( TIME_TO_SEC( TIMEDIFF( a.ending, a.begining ) ) DIV 60, 0 )
FROM visits a


问:
aspnet web forms An item with the same key has already been added
I am using asp net 4.5.2 with model binding; I have a problem that whenever I try to use model binding on DropDownList It raises the error An item with the same key has already been added but if I change it to SQLDataSource the error goes away.
Thanks in advance

Update

Sample Code

```<code><asp:ListView runat="server" ID="lvChairItem" DataKeyNames="ChairItemId" InsertItemPosition="FirstItem" OnItemCanceling="lv_ItemCanceling" OnItemUpdated="lv_ItemUpdated" OnItemEditing="lv_ItemEditing" ClientIDMode="AutoID" OnCallingDataMethods="ChairItem_CallingDataMethods" SelectMethod="GetByChairId" InsertMethod="InsertItem" UpdateMethod="UpdateItem" DeleteMethod="DeleteItem" ItemType="App.Model.ChairItem">
.............
<InsertItemTemplate>
    <tr>
        ........
        <td>
            <asp:DropDownList ID="ddlRoomId" CssClass="" DataValueField="Value" DataTextField="Text" AppendDataBoundItems="true" Text='<%# BindItem.RoomId %>' Width="100%" OnCallingDataMethods="Room_CallingDataMethods" SelectMethod="GetAllForDDL" runat="server" EnableViewState="true">
                <asp:ListItem Value="">--Select--</asp:ListItem>
            </asp:DropDownList>
        </td>
        ........
    </tr>
</InsertItemTemplate>
.....................
</asp:ListView>
</code>```

答: Then the issue is likely because you are populating it on page load without checking for Page.IsPostBack. You don't want to re-populate the controls on each postback. You do want to (often) allow ViewState. So I would re-enable, and wrap your populate method in (not page.ispostback). </p>

Body:
I am using asp net 4.5.2 with model binding; I have a problem that whenever I try to use model binding on DropDownList It raises the error An item with the same key has already been added but if I change it to SQLDataSource the error goes away.
Thanks in advance

Update

Sample Code

<asp:ListView runat="server" ID="lvChairItem" DataKeyNames="ChairItemId" InsertItemPosition="FirstItem" OnItemCanceling="lv_ItemCanceling" OnItemUpdated="lv_ItemUpdated" OnItemEditing="lv_ItemEditing" ClientIDMode="AutoID" OnCallingDataMethods="ChairItem_CallingDataMethods" SelectMethod="GetByChairId" InsertMethod="InsertItem" UpdateMethod="UpdateItem" DeleteMethod="DeleteItem" ItemType="App.Model.ChairItem">
.............
<InsertItemTemplate>

        ........

            <asp:DropDownList ID="ddlRoomId" CssClass="" DataValueField="Value" DataTextField="Text" AppendDataBoundItems="true" Text='<%# BindItem.RoomId %>' Width="100%" OnCallingDataMethods="Room_CallingDataMethods" SelectMethod="GetAllForDDL" runat="server" EnableViewState="true">
                <asp:ListItem Value="">--Select--</asp:ListItem>
            </asp:DropDownList>

        ........

</InsertItemTemplate>
.....................
</asp:ListView>


答:
```<code>for (auto it : con){
</code>```

Same address with different content !?

This is very typical for variables with automatic storage duration. This has nothing to do with auto in C++†. You would get the same result if you had used int:

```<code>for (int it : con){
</code>```

The lifetime of it (as well as each automatic variable within the loop) is just a single iteration. Since the lifetime of the it in last iteration was ended, the next iteration can re-use the same memory, and that's why the address is the same.

```<code>Why does the '&' sign make a change under this circumstance?
</code>```

Because T& declares a reference to type T. Reference variables are different from non-references (object variables). Instead of holding a value such as an object would, a reference instead "refers" to another object.

When you use the addressof operator on a reference, the result will be the address of the referred object; not the address of the reference (which might not even have an address, since it's not an object). That is why the address changes in the latter case. In this case, the references would refer to the int objects that are stored in the nodes of what (because con itself is a reference, and refers to the passed object).

† I mention in C++, because in C auto is in fact a storage class modifier that signifies automatic storage class. It has never had that meaning in standard C++, and its use obsolete in C as well. It's a vestigial keyword from the B language.

In C++, auto declares a type that will be deduced from context.

Title: What does the '&' sign do when using 'auto' for iteration

Body:
for (auto it : con){

Same address with different content !?

This is very typical for variables with automatic storage duration. This has nothing to do with auto in C++†. You would get the same result if you had used int:

for (int it : con){

The lifetime of it (as well as each automatic variable within the loop) is just a single iteration. Since the lifetime of the it in last iteration was ended, the next iteration can re-use the same memory, and that's why the address is the same.

Why does the '&' sign make a change under this circumstance?

Because T& declares a reference to type T. Reference variables are different from non-references (object variables). Instead of holding a value such as an object would, a reference instead "refers" to another object.

When you use the addressof operator on a reference, the result will be the address of the referred object; not the address of the reference (which might not even have an address, since it's not an object). That is why the address changes in the latter case. In this case, the references would refer to the int objects that are stored in the nodes of what (because con itself is a reference, and refers to the passed object).

† I mention in C++, because in C auto is in fact a storage class modifier that signifies automatic storage class. It has never had that meaning in standard C++, and its use obsolete in C as well. It's a vestigial keyword from the B language.

In C++, auto declares a type that will be deduced from context.


问:
Invalid number of arguments PhpStorm
I have a little problem with PhpStorm 2017. I get this error message even if my code is working properly:

I don't know how to deactivate this message. Thank you for your help.

答:
Try adding jquery as a library in your project. File -> Settings -> Languages & Frameworks -> JavaScript -> Libraries then enable the global jQuery. You might need to restart your IDE.

If that doesn't work you can use the "on" syntax to add the click event handler.
http://api.jquery.com/on/

E.G

```<code>$('#cookie_btn').click(function (){})
</code>```

Becomes

```<code>$('#cookie_btn').on('click',function (){})
</code>```

Title: Invalid number of arguments PhpStorm

Body:
Try adding jquery as a library in your project. File -> Settings -> Languages & Frameworks -> JavaScript -> Libraries then enable the global jQuery. You might need to restart your IDE.

If that doesn't work you can use the "on" syntax to add the click event handler.
http://api.jquery.com/on/

E.G

$('#cookie_btn').click(function (){})

Becomes

$('#cookie_btn').on('click',function (){})


问:
How mpesa ssl handshake failure
With the mpesa B2C integration. am trying to use Curl

```<code>        $url = "https://196.201.214.136:18423/mminterface/request";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
    // curl_setopt($ch, CURLOPT_PORT, 18423);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXml);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                           'Content-type: text/xml',
                                           'Content-length: ' . strlen($requestXml)
                                         ));
    $output = curl_exec($ch);

    if(curl_errno($ch)){
        var_dump(curl_error($ch));
    } else{
        curl_close($ch);
    }
</code>```

I get an error

error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure'

This is after changing ssl version from nss to openssl.
How do I solve the handshake failure.

答: Safaricom has released M-Pesa APIs as RESTful APIs accessible through their developer portal . You need not have SSL certificates signed by Safaricom in order to consume the APIs. As long as your server has a publicly signed certificate, the Safaricom API Gateway should be able to receive requests and send responses to your server.</p>

Title: How mpesa ssl handshake failure

Body:
With the mpesa B2C integration. am trying to use Curl

        $url = "https://196.201.214.136:18423/mminterface/request";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
    // curl_setopt($ch, CURLOPT_PORT, 18423);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXml);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                           'Content-type: text/xml',
                                           'Content-length: ' . strlen($requestXml)
                                         ));
    $output = curl_exec($ch);

    if(curl_errno($ch)){
        var_dump(curl_error($ch));
    } else{
        curl_close($ch);
    }

I get an error

error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure'

This is after changing ssl version from nss to openssl.
How do I solve the handshake failure.


问:
R - Add trace in Plotly if condition is met
I am creating a scatter plot graph and I would like the points connected by a trace if a condition is met. My data is separated into sequences, if an X and Y coordinate is part of the same sequence, I would like there to be a trace. My sample data and code snippet is below.

Sample Data:

```<code>X   Y   Seq
1   3    1
2   5    1
1   4    1
3   1    2
4   5    2
6   3    3
3   4    3
</code>```

In this example I would like points (1, 3), (2, 5), (1, 4) traced, points (3, 1), (4, 5) traced, and points (6, 3), (3, 4) traced. There should be a break in the trace if a new sequence starts.

Code:

```<code> plot_ly (data, x = data$X , y = data$Y,
          type = "scatter",
          mode="markers")%>%
          add_trace(data$Seq==shift(data$Seq, type="lag"), mode="lines")
</code>```

Here is an image of the plot that my actual data is giving me. You can see the points are being plotted but there is no break.

答:
The problem lies in your use of add_trace.  You're passing what I assume is a subset of your data to the first argument of add_trace when this argument expects an existing plot/trace. The problem is, since you're piping in with %>% the function is inheriting the original data and ignoring your subset.

Note that the below will give the same plot even though my variable NO has nothing to do with the plot:

```<code>X=c(1,2,1,3,4,6,3)
Y=c(3,5,4,1,5,3,4)
seq=c(1,1,1,2,2,3,3)
dataX <- data.frame(X,Y,seq)

NO <- "this won't work"
plot_ly plot_ly (dataX, x = dataX$X , y = dataX$Y,
         type = "scatter",
         mode="markers") %>%
          add_trace(NO, mode="lines")
</code>```

You can fix this with inherit=F, but then it won't work because add_trace is trying to add something to the plot NO which isn't a plot (and your subset wouldn't work either)

```<code>plot_ly (dataX, x = dataX$X , y = dataX$Y,
         type = "scatter",
         mode="markers") %>%
  add_trace(NO, mode="lines", inherit=FALSE)

## No trace type specified:
</code>```

When you add traces you want to be explicit in the x= and y=. Then you can allow it to automatically inherit the previous plot/trace, or specify one. As for what you're trying to do, you could build it up with a loop:

```<code>#make the plot
p <- plot_ly (dataX, x = dataX$X , y = dataX$Y,
         type = "scatter",
         mode="markers")

#build it up
for(i in levels(factor(dataX$seq))){
  #subset data
  dataFilt <- dataX[dataX$seq==i,]
  #add it
  p <- add_trace(p, x=dataFilt$X, y=dataFilt$Y,mode="lines",color ='yellow')
}
p
</code>```

This makes a new series each time so it's a bit of a work around. You can hide the legend and it looks correct:

```<code>p %>%
  layout(showlegend = FALSE)
</code>```

Body:
I am creating a scatter plot graph and I would like the points connected by a trace if a condition is met. My data is separated into sequences, if an X and Y coordinate is part of the same sequence, I would like there to be a trace. My sample data and code snippet is below.

Sample Data:

X   Y   Seq
1   3    1
2   5    1
1   4    1
3   1    2
4   5    2
6   3    3
3   4    3

In this example I would like points (1, 3), (2, 5), (1, 4) traced, points (3, 1), (4, 5) traced, and points (6, 3), (3, 4) traced. There should be a break in the trace if a new sequence starts.

Code:

 plot_ly (data, x = data$X , y = data$Y,
          type = "scatter",
          mode="markers")%>%
          add_trace(data$Seq==shift(data$Seq, type="lag"), mode="lines")

Here is an image of the plot that my actual data is giving me. You can see the points are being plotted but there is no break.

Body:
The problem lies in your use of add_trace.  You're passing what I assume is a subset of your data to the first argument of add_trace when this argument expects an existing plot/trace. The problem is, since you're piping in with %>% the function is inheriting the original data and ignoring your subset.

Note that the below will give the same plot even though my variable NO has nothing to do with the plot:

X=c(1,2,1,3,4,6,3)
Y=c(3,5,4,1,5,3,4)
seq=c(1,1,1,2,2,3,3)
dataX <- data.frame(X,Y,seq)

NO <- "this won't work"
plot_ly plot_ly (dataX, x = dataX$X , y = dataX$Y,
         type = "scatter",
         mode="markers") %>%
          add_trace(NO, mode="lines")

You can fix this with inherit=F, but then it won't work because add_trace is trying to add something to the plot NO which isn't a plot (and your subset wouldn't work either)

plot_ly (dataX, x = dataX$X , y = dataX$Y,
         type = "scatter",
         mode="markers") %>%
  add_trace(NO, mode="lines", inherit=FALSE)

## No trace type specified:

When you add traces you want to be explicit in the x= and y=. Then you can allow it to automatically inherit the previous plot/trace, or specify one. As for what you're trying to do, you could build it up with a loop:

#make the plot
p <- plot_ly (dataX, x = dataX$X , y = dataX$Y,
         type = "scatter",
         mode="markers")

#build it up
for(i in levels(factor(dataX$seq))){
  #subset data
  dataFilt <- dataX[dataX$seq==i,]
  #add it
  p <- add_trace(p, x=dataFilt$X, y=dataFilt$Y,mode="lines",color ='yellow')
}
p

This makes a new series each time so it's a bit of a work around. You can hide the legend and it looks correct:

p %>%
  layout(showlegend = FALSE)


问:
Rails Devise only redirects to a fixed path. Need to redirect back where the user came from when authentication was triggered
Working on a Ruby on Rails app with Devise.

Devise only redirects to a fixed path, root app path by default.
There are protected urls, and if the user click some links (e.g. "Ask Question" here), he is sent to the /sign_in page. On successful logon, the user is not sent back to the "Ask Question", but rather to "/".
Any idea how to fix that?

答:
Try with this method in your application_controller.rb</p>

```<code>def after_sign_in_path_for(resource)
  (session[:"user.return_to"].nil?) ? "/" : session[:"user.return_to"].to_s
end
</code>```

Body:
Try with this method in your application_controller.rb

def after_sign_in_path_for(resource)
  (session[:"user.return_to"].nil?) ? "/" : session[:"user.return_to"].to_s
end


问:
How to open desired figure by dialogue box in MATLAB
Is there any possible way to open the desired figures from a lot of plotted figures in MATLAB?

If it is possible with dialogue box then it will be perfect.

I have like 75 figures plotted after my code but I have closed the figures at end of loops as they are too much.

Is it possible to open just one figure by just entering values necessary for plotting figure in MATLAB at end of program?

答:
From Wikibooks: MATLAB Programming/Handle Graphics (emphasis mine):

Every time you close a figure, either by using the close function OR by hitting the 'X', you can no longer access the data, and
  attempts to do so will result in an error. Closing a figure also
  destroys all the handles to the axes and annotations that depended on
  it.

This means that once you close your 75 figures, they are gone for good.

I would suggest saving all your figures to .fig file format, because this will allow you to open them later in MATLAB.

Take the following example:

```<code>x = linspace(0, 2*pi);  % Sample data.

for i = 1:3                             % Loop 3 times.
   h = figure;                          % Create figure window and capture its handle.
   plot(i*sin(x));                      % Plot some data.
   saveas(h, sprintf('fig%d.fig', i));  % Save figure to .fig file format.
   close(h);                            % Delete the figure.
end
</code>```

Now you can tell MATLAB to open one of the figures using the openfig function. For example, let's open the second figure fig2.fig. Go to the Command Window and type openfig('fig2') (including the .fig extension in the file name is optional).

```<code>>> openfig('fig2')

ans =

  Figure (1) with properties:

      Number: 1
        Name: ''
       Color: [0.9400 0.9400 0.9400]
    Position: [520 371 560 420]
       Units: 'pixels'

  Show all properties
</code>```

Body:
From Wikibooks: MATLAB Programming/Handle Graphics (emphasis mine):

Every time you close a figure, either by using the close function OR by hitting the 'X', you can no longer access the data, and
  attempts to do so will result in an error. Closing a figure also
  destroys all the handles to the axes and annotations that depended on
  it.

This means that once you close your 75 figures, they are gone for good.

I would suggest saving all your figures to .fig file format, because this will allow you to open them later in MATLAB.

Take the following example:

x = linspace(0, 2*pi);  % Sample data.

for i = 1:3                             % Loop 3 times.
   h = figure;                          % Create figure window and capture its handle.
   plot(i*sin(x));                      % Plot some data.
   saveas(h, sprintf('fig%d.fig', i));  % Save figure to .fig file format.
   close(h);                            % Delete the figure.
end

Now you can tell MATLAB to open one of the figures using the openfig function. For example, let's open the second figure fig2.fig. Go to the Command Window and type openfig('fig2') (including the .fig extension in the file name is optional).

>> openfig('fig2')

ans =

  Figure (1) with properties:

      Number: 1
        Name: ''
       Color: [0.9400 0.9400 0.9400]
    Position: [520 371 560 420]
       Units: 'pixels'

  Show all properties


问:
react-native justifying content center is causing items to jump around on android
I'm trying to build a simple login screen. However when I try to justify the content to center, the elements will not stop jumping up and down. . If I remove flex or justifyContent attributes it stops jumping. My code looks like this

```<code>export default class LoginScreen extends React.Component {

  render() {
    return (
      <View style={Styles.container} >
        <Text>Hello world</Text>
     </View>
  )}

let Styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    // padding: 15,
    // backgroundColor: 'red',
    justifyContent: 'center',
    alignItems: 'center',
  },
)
</code>```

My App.js looks like this

```<code>import { Platform } from 'react-native';
import { Navigation } from 'react-native-navigation';
import registerScreens from './app/Screens';

import {
  AppRegistry,
  Text,
} from 'react-native';
registerScreens();

let tabs = [
    {
      label: 'Login',
      screen: 'tasks.LoginScreen', // this is a registered name for a screen
      icon: require('./assets/account_circle.png'),
      // selectedIcon: require('../img/one_selected.png'), // iOS only
      title: 'Hello world'
    },
    {
      label: 'Two',
      screen: 'tasks.CreateUserScreen',
      icon: require('./assets/account_circle.png'),
      // selectedIcon: require('../img/two_selected.png'), // iOS only
      title: 'Screen Two'
    }
  ]

Navigation.startTabBasedApp({
  tabs,
  animationType: Platform.OS === 'ios' ? 'slide-down' : 'fade',
  tabsStyle: {
    tabBarBackgroundColor: '#003a66',
    tabBarButtonColor: '#ffffff',
    tabBarSelectedButtonColor: '#ff505c',
    tabFontFamily: 'BioRhyme-Bold',
  },
  appStyle: {
    tabBarBackgroundColor: '#003a66',
    navBarButtonColor: '#ffffff',
    tabBarButtonColor: '#ffffff',
    navBarTextColor: '#ffffff',
    tabBarSelectedButtonColor: '#ff505c',
    navigationBarColor: '#003a66',
    navBarBackgroundColor: '#003a66',
    statusBarColor: '#002b4c',
    tabFontFamily: 'BioRhyme-Bold',
  },
  drawer: {
    left: {
      screen: 'tasks.LoginScreen'
    }
  }
});
</code>```

答: After trying to solve this issue in my own application, I've come to the point where the only solution is to downgrade React-Native from 0.50.x to 0.49.x - At least, that's what fixed it on my end.</p>

Body:
I'm trying to build a simple login screen. However when I try to justify the content to center, the elements will not stop jumping up and down. . If I remove flex or justifyContent attributes it stops jumping. My code looks like this

export default class LoginScreen extends React.Component {

  render() {
    return (
      <View style={Styles.container} >
        <Text>Hello world</Text>
     </View>
  )}

let Styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    // padding: 15,
    // backgroundColor: 'red',
    justifyContent: 'center',
    alignItems: 'center',
  },
)

My App.js looks like this

import { Platform } from 'react-native';
import { Navigation } from 'react-native-navigation';
import registerScreens from './app/Screens';

import {
  AppRegistry,
  Text,
} from 'react-native';
registerScreens();

let tabs = [
    {
      label: 'Login',
      screen: 'tasks.LoginScreen', // this is a registered name for a screen
      icon: require('./assets/account_circle.png'),
      // selectedIcon: require('../img/one_selected.png'), // iOS only
      title: 'Hello world'
    },
    {
      label: 'Two',
      screen: 'tasks.CreateUserScreen',
      icon: require('./assets/account_circle.png'),
      // selectedIcon: require('../img/two_selected.png'), // iOS only
      title: 'Screen Two'
    }
  ]

Navigation.startTabBasedApp({
  tabs,
  animationType: Platform.OS === 'ios' ? 'slide-down' : 'fade',
  tabsStyle: {
    tabBarBackgroundColor: '#003a66',
    tabBarButtonColor: '#ffffff',
    tabBarSelectedButtonColor: '#ff505c',
    tabFontFamily: 'BioRhyme-Bold',
  },
  appStyle: {
    tabBarBackgroundColor: '#003a66',
    navBarButtonColor: '#ffffff',
    tabBarButtonColor: '#ffffff',
    navBarTextColor: '#ffffff',
    tabBarSelectedButtonColor: '#ff505c',
    navigationBarColor: '#003a66',
    navBarBackgroundColor: '#003a66',
    statusBarColor: '#002b4c',
    tabFontFamily: 'BioRhyme-Bold',
  },
  drawer: {
    left: {
      screen: 'tasks.LoginScreen'
    }
  }
});


问:
How to do Canvas Path animation?
I am trying to add animation to my Canvas. I have one ArrayList of Points, which i am using to draw the path.

MyCode :

```<code>for (int i = 0; i < points.size(); i++) {

            Point point = points.get(i);

            if (pId == 0) {
                path.moveTo(point.x, point.y);
            } else {
                float midX = (prevPoint.x + point.x) / 2;
                float midY = (prevPoint.y + point.y) / 2;

                if (pId == 1) {
                    path.lineTo(midX, midY);
                } else {
                    path.quadTo(prevPoint.x, prevPoint.y, midX, midY);
                }
              pId++;
            }
            prevPoint = point;
}
</code>```

this is the above code. So, now i am tying to draw the path using animation.

Please kindly suggest me some solutions.

答:
you need create class extend view and draw in by animationValue.</p>

```<code>public class XXX extends View {

    //...

    int valueAnimation;

    void animationStart() {

        ValueAnimator valueAnimatorLoading = ValueAnimator.ofInt(startValue, endValue);
        valueAnimatorLoading.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                valueAnimation = (int) (Integer) valueAnimator.getAnimatedValue(); //factor for use in onDraw()
                invalidate();// call onDraw
            }
        });
        valueAnimatorLoading.start();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //draw in canvas by valueAnimation
    }

}
</code>```

Title: How to do Canvas Path animation?

Body:
I am trying to add animation to my Canvas. I have one ArrayList of Points, which i am using to draw the path.

MyCode :

for (int i = 0; i < points.size(); i++) {

            Point point = points.get(i);

            if (pId == 0) {
                path.moveTo(point.x, point.y);
            } else {
                float midX = (prevPoint.x + point.x) / 2;
                float midY = (prevPoint.y + point.y) / 2;

                if (pId == 1) {
                    path.lineTo(midX, midY);
                } else {
                    path.quadTo(prevPoint.x, prevPoint.y, midX, midY);
                }
              pId++;
            }
            prevPoint = point;
}

this is the above code. So, now i am tying to draw the path using animation.

Please kindly suggest me some solutions.

Body:
you need create class extend view and draw in by animationValue.

public class XXX extends View {

    //...

    int valueAnimation;

    void animationStart() {

        ValueAnimator valueAnimatorLoading = ValueAnimator.ofInt(startValue, endValue);
        valueAnimatorLoading.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                valueAnimation = (int) (Integer) valueAnimator.getAnimatedValue(); //factor for use in onDraw()
                invalidate();// call onDraw
            }
        });
        valueAnimatorLoading.start();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //draw in canvas by valueAnimation
    }

}


问:
Cannot read property 'minDate' of undefined
I'm using bootstrap datetimepicker's Linked Pickers and I am getting following error message:

Cannot read property 'minDate' of undefined for following line

$("#from_date").data("DateTimePicker").minDate(e.date);

答:
DateTimePicker needs some time to be initialised. Try wrapping the minDate setting call into a setTimeout so it gets executed later.</p>

```<code>setTimeout(() => {
     $("#from_date").data("DateTimePicker").minDate(e.date);
}, 0);
</code>```

Body:
DateTimePicker needs some time to be initialised. Try wrapping the minDate setting call into a setTimeout so it gets executed later.

setTimeout(() => {
     $("#from_date").data("DateTimePicker").minDate(e.date);
}, 0);


问:
Why using explicit interpreter in bash doesn't use path variable
Say I have a script /tmp/printy.py containing only:

```<code>#! /usr/bin/python2.7
print "hello world"
</code>```

Why does this work:

```<code>chmod +x /tmp/printy.py
export PATH=$PATH:/tmp/
printy.py
</code>```

But this doesn't:

```<code>chmod +x /tmp/printy.py
export PATH=$PATH:/tmp/
python printy.py
</code>```

And what can be added to, say, a cron job which is supposed to run printy.py with a specific interpreter, to make it work?

Quite possibly duplicate but I can't find anything, maybe I'm using the wrong search terms?

答:
Path lookups in the shell only apply to commands, not arbitrary files. In your first example, printy.py is the command name. In the second, it is just an argument to Python, and Python doesn't use PATH to find the script to run; it expects printy.py to be in the current working directory.

You can use a combination of PYTHONPATH and -m to simulate this:

```<code>PYTHONPATH=$PATH python -m printy
</code>```

Body:
Say I have a script /tmp/printy.py containing only:

#! /usr/bin/python2.7
print "hello world"

Why does this work:

chmod +x /tmp/printy.py
export PATH=$PATH:/tmp/
printy.py

But this doesn't:

chmod +x /tmp/printy.py
export PATH=$PATH:/tmp/
python printy.py

And what can be added to, say, a cron job which is supposed to run printy.py with a specific interpreter, to make it work?

Quite possibly duplicate but I can't find anything, maybe I'm using the wrong search terms?

Body:
Path lookups in the shell only apply to commands, not arbitrary files. In your first example, printy.py is the command name. In the second, it is just an argument to Python, and Python doesn't use PATH to find the script to run; it expects printy.py to be in the current working directory.

You can use a combination of PYTHONPATH and -m to simulate this:

PYTHONPATH=$PATH python -m printy


问:
Server shutting down itself using twitter api with nodejs and expressjs
I have an web app with using Twitter API. Main focus is to get the users that are not following back based on given twitter user name. It works fine until this point but when I get an error because of the fact that user name does not exist on Twitter, Server shuts down itself. Using Nodejs, expressjs.

The Error Message :

```<code>App is running on port : 3000
[ { code: 34, message: 'Sorry, that page does not exist.' } ]
_http_outgoing.js:494
    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:494:11)
    at ServerResponse.setHeader (_http_outgoing.js:501:3)
    at ServerResponse.header (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/express/lib/response.js:170:12)
    at /home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/twitter-api.js:30:21
    at Request._callback (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/twitter/lib/twitter.js:215:14)
    at Request.self.callback (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/request/request.js:186:22)
    at emitTwo (events.js:126:13)
    at Request.emit (events.js:214:7)
    at Request.<anonymous> (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/request/request.js:1163:10)
</code>```

Problematic part of the code is below. The question is : How can I avoid this situation ? Or is it even possible ?

```<code>client.get('followers/ids', params, function(error, followers_results, response) {
        if (error) {
          res.send("error");
          console.log(error);
        }

         let followers = followers_results.ids;

         client.get('friends/ids', params, function(error, following_results, response ) {
            if (error) {
                res.send("error");
                console.log(error);
            }

            let following = following_results.ids;

            following.forEach(function(person){
                if(followers.indexOf(person) === -1){
                    one_way_following.push(person);
                }
            });

            // console.log(one_way_following);

            one_way_following = one_way_following.slice(0, 100);

            one_way_following_string = one_way_following.join();

           // console.log("----------------------------------------------------");
           // console.log(one_way_following_string);
           // console.log("----------------------------------------------------");

           client.get('users/lookup', {user_id: one_way_following_string}, function(error, user_results, response, next) {
               if (error) {
                   res.send("error");
                   console.log(error);
               }

               user_results.forEach(function(user){
                   let userObject = {
                       name : user.name,
                       screen_name : user.screen_name,
                       avatar: user.profile_image_url
                   }
               //   console.log(user.name);

               users.push(userObject);
               })
               res.render("results.ejs",{users:users});
            //    console.log(users);
           });
       });
   });
</code>```

答:
This error is actually happening because, you can't call res.render("results.ejs",{users:users}); or res.send("error"); multiple times, because headers can't be changed once set.

Easiest solution would be to break out of the function once you've caught an error (if (error) { on line 2), or handle it appropriately (render something blank, or render your friendly error view).

For more information, about this, check out the answer to this question, Error: Can't set headers after they are sent to the client

Hope that helps :)

Body:
I have an web app with using Twitter API. Main focus is to get the users that are not following back based on given twitter user name. It works fine until this point but when I get an error because of the fact that user name does not exist on Twitter, Server shuts down itself. Using Nodejs, expressjs.

The Error Message :

App is running on port : 3000
[ { code: 34, message: 'Sorry, that page does not exist.' } ]
_http_outgoing.js:494
    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:494:11)
    at ServerResponse.setHeader (_http_outgoing.js:501:3)
    at ServerResponse.header (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/express/lib/response.js:170:12)
    at /home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/twitter-api.js:30:21
    at Request._callback (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/twitter/lib/twitter.js:215:14)
    at Request.self.callback (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/request/request.js:186:22)
    at emitTwo (events.js:126:13)
    at Request.emit (events.js:214:7)
    at Request.<anonymous> (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/request/request.js:1163:10)

Problematic part of the code is below. The question is : How can I avoid this situation ? Or is it even possible ?

client.get('followers/ids', params, function(error, followers_results, response) {
        if (error) {
          res.send("error");
          console.log(error);
        }

         let followers = followers_results.ids;

         client.get('friends/ids', params, function(error, following_results, response ) {
            if (error) {
                res.send("error");
                console.log(error);
            }

            let following = following_results.ids;

            following.forEach(function(person){
                if(followers.indexOf(person) === -1){
                    one_way_following.push(person);
                }
            });

            // console.log(one_way_following);

            one_way_following = one_way_following.slice(0, 100);

            one_way_following_string = one_way_following.join();

           // console.log("----------------------------------------------------");
           // console.log(one_way_following_string);
           // console.log("----------------------------------------------------");

           client.get('users/lookup', {user_id: one_way_following_string}, function(error, user_results, response, next) {
               if (error) {
                   res.send("error");
                   console.log(error);
               }

               user_results.forEach(function(user){
                   let userObject = {
                       name : user.name,
                       screen_name : user.screen_name,
                       avatar: user.profile_image_url
                   }
               //   console.log(user.name);

               users.push(userObject);
               })
               res.render("results.ejs",{users:users});
            //    console.log(users);
           });
       });
   });


问:
Loop to 100 then change change row x times
I am trying to create a vba loop that loops to 100 then continues value 101 at row 1 on the next column.

Column A data would have 1-100, B = 101-200, C = 201-300 etc.,

This is some code I got online and I am trying to modify it.

```<code>Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
    strCBName = CB.Name

    'Set wbTemp = Workbooks.Add(xlWBATWorksheet)
    'Set wks = wbTemp.Worksheets(1)
    Set wks = ThisWorkbook.Worksheets(1)
    Set rngInput = wks.Range("A:A")

    rngInput.Offset(, -1).ColumnWidth = 6.5
    rngInput.ColumnWidth = 6.5
    rngInput.HorizontalAlignment = xlRight

    For i = 1 To 100
        ctl.FaceId = i
        ctl.CopyFace
        rngInput.Cells(i).PasteSpecial
        rngInput.Cells(i).Value = i
    Next

    rngInput.Cells(1).Select

    On Error Resume Next
    Set CB = CommandBars(strCBName)
    On Error GoTo 0

    If Not CB Is Nothing Then
        CB.Delete
    Else
        MsgBox "no toolbar!", 0, vbNullString
    End If
End Sub
</code>```

Thanks for any help

答:
You can do this with a loop and nested loop, such that:

```<code>Dim i as Long, j as Long, k as Long
k = 0
For j = 1 to 3 Step 1
    For i = 1 to 100 Step 1
        'Something using Cells(i+k, j)
    Next i
    k = k + 100
Next j
</code>```

Note that the row (i) is the 1 to 100 which occurs inside each column (j), so you will go 1 to 100, then switch column and go 1 to 100.  I only listed 3 columns in this example, but you can make it whatever you would like (1 = A, 2 = B, etc.).

The use of k is to increase by 100 for each column you move to, which is added to your row (i) as it loops 1 to 100.

Body:
I am trying to create a vba loop that loops to 100 then continues value 101 at row 1 on the next column.

Column A data would have 1-100, B = 101-200, C = 201-300 etc.,

This is some code I got online and I am trying to modify it.

Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
    strCBName = CB.Name

    'Set wbTemp = Workbooks.Add(xlWBATWorksheet)
    'Set wks = wbTemp.Worksheets(1)
    Set wks = ThisWorkbook.Worksheets(1)
    Set rngInput = wks.Range("A:A")

    rngInput.Offset(, -1).ColumnWidth = 6.5
    rngInput.ColumnWidth = 6.5
    rngInput.HorizontalAlignment = xlRight

    For i = 1 To 100
        ctl.FaceId = i
        ctl.CopyFace
        rngInput.Cells(i).PasteSpecial
        rngInput.Cells(i).Value = i
    Next

    rngInput.Cells(1).Select

    On Error Resume Next
    Set CB = CommandBars(strCBName)
    On Error GoTo 0

    If Not CB Is Nothing Then
        CB.Delete
    Else
        MsgBox "no toolbar!", 0, vbNullString
    End If
End Sub

Thanks for any help

Body:
You can do this with a loop and nested loop, such that:

Dim i as Long, j as Long, k as Long
k = 0
For j = 1 to 3 Step 1
    For i = 1 to 100 Step 1
        'Something using Cells(i+k, j)
    Next i
    k = k + 100
Next j

Note that the row (i) is the 1 to 100 which occurs inside each column (j), so you will go 1 to 100, then switch column and go 1 to 100.  I only listed 3 columns in this example, but you can make it whatever you would like (1 = A, 2 = B, etc.).

The use of k is to increase by 100 for each column you move to, which is added to your row (i) as it loops 1 to 100.