问:
Most frequent occurence in a pandas dataframe indexed by datetime
I have a large DataFrame which is indexed by datetime, in particular, by days. I am looking for an efficient function which, for each column, checks the most common non-null value in each week, and outputs a dataframe which is indexed by weeks consisting of these within-week most common values.

Here is an example. The following DataFrame consists of two weeks of daily data:

```<code>                        0      1
2015-11-12 00:00:00     8     nan
2015-11-13 00:00:00     7     nan
2015-11-14 00:00:00     nan   5
2015-11-15 00:00:00     7     nan
2015-11-16 00:00:00     8     nan
2015-11-17 00:00:00     7     nan
2015-11-18 00:00:00     5     nan
2015-11-19 00:00:00     9     nan
2015-11-20 00:00:00     8     nan
2015-11-21 00:00:00     6     nan
2015-11-22 00:00:00     6     nan
2015-11-23 00:00:00     6     nan
2015-11-24 00:00:00     6     nan
2015-11-25 00:00:00     2     nan
</code>```

and should be transformed into:

```<code>                        0    1
2015-11-12 00:00:00     7    5
2015-11-19 00:00:00     6    nan
</code>```

My DataFrame is very large so efficiency is important. Thanks.

EDIT: If possible, can someone suggest a method that would be applicable if the entries are tuples (instead of floats as in my example)?

答:
You can use resample to group your data by the weekly interval. Then, count the number of occurences via pd.value_counts and select the most common with idxmax:

```<code>df.resample("7D").apply(lambda x: x.apply(pd.value_counts).idxmax())

                     0      1
2015-11-12 00:00:00  7.0    5.0
2015-11-19 00:00:00  6.0    NaN
</code>```

Edit

Here is another numpy version which is faster than the above solution:

```<code>def numpy_mode(series):
    values = series.values
    dropped = values[~np.isnan(values)]

    # check for empty array and return NaN
    if not dropped.size:
        return np.NaN

    uniques, counts = np.unique(series.dropna(), return_counts=True)
    return uniques[np.argmax(counts)]

df2.resample("7D").apply(lambda x: x.apply(get_mode))

                     0      1
2015-11-12 00:00:00  7.0    5.0
2015-11-19 00:00:00  6.0    NaN
</code>```

And here the timings based on the dummy data (for further improvements, have a look here):

```<code>%%timeit
df2.resample("7D").apply(lambda x: x.apply(pd.value_counts).idxmax())
>>> 100 loops, best of 3: 18.6 ms per loop

%%timeit
df2.resample("7D").apply(lambda x: x.apply(get_mode))
>>> 100 loops, best of 3: 3.72 ms per loop
</code>```

I also tried scipy.stats.mode however it was also slower than the numpy solution:

```<code>size = 1000
index = pd.DatetimeIndex(start="2012-12-12", periods=size, freq="D")
dummy = pd.DataFrame(np.random.randint(0, 20, size=(size, 50)), index=index)
print(dummy.head)

            0   1   2   3   4   5   6   7   8   9   ...     40  41  42  43  44  45  46  47  48  49
2012-12-12  18  2   7   1   7   9   16  2   19  19  ...     10  2   18  16  15  10  7   19  9   6
2012-12-13  7   4   11  19  17  10  18  0   10  7   ...     19  11  5   5   11  4   0   16  12  19
2012-12-14  14  0   14  5   1   11  2   19  5   9   ...     2   9   4   2   9   5   19  2   16  2
2012-12-15  12  2   7   2   12  12  11  11  19  5   ...     16  0   4   9   13  5   10  2   14  4
2012-12-16  8   15  2   18  3   16  15  0   14  14  ...     18  2   6   13  19  10  3   16  11  4

%%timeit
dummy.resample("7D").apply(lambda x: x.apply(get_mode))
>>> 1 loop, best of 3: 926 ms per loop

%%timeit
dummy.resample("7D").apply(lambda x: x.apply(pd.value_counts).idxmax())
>>> 1 loop, best of 3: 5.84 s per loop

%%timeit
dummy.resample("7D").apply(lambda x: stats.mode(x).mode)
>>> 1 loop, best of 3: 1.32 s per loop
</code>```

Body:
I have a large DataFrame which is indexed by datetime, in particular, by days. I am looking for an efficient function which, for each column, checks the most common non-null value in each week, and outputs a dataframe which is indexed by weeks consisting of these within-week most common values.

Here is an example. The following DataFrame consists of two weeks of daily data:

                        0      1
2015-11-12 00:00:00     8     nan
2015-11-13 00:00:00     7     nan
2015-11-14 00:00:00     nan   5
2015-11-15 00:00:00     7     nan
2015-11-16 00:00:00     8     nan
2015-11-17 00:00:00     7     nan
2015-11-18 00:00:00     5     nan
2015-11-19 00:00:00     9     nan
2015-11-20 00:00:00     8     nan
2015-11-21 00:00:00     6     nan
2015-11-22 00:00:00     6     nan
2015-11-23 00:00:00     6     nan
2015-11-24 00:00:00     6     nan
2015-11-25 00:00:00     2     nan

and should be transformed into:

                        0    1
2015-11-12 00:00:00     7    5
2015-11-19 00:00:00     6    nan

My DataFrame is very large so efficiency is important. Thanks.

EDIT: If possible, can someone suggest a method that would be applicable if the entries are tuples (instead of floats as in my example)?

Body:
You can use resample to group your data by the weekly interval. Then, count the number of occurences via pd.value_counts and select the most common with idxmax:

df.resample("7D").apply(lambda x: x.apply(pd.value_counts).idxmax())

                     0      1
2015-11-12 00:00:00  7.0    5.0
2015-11-19 00:00:00  6.0    NaN

Edit

Here is another numpy version which is faster than the above solution:

def numpy_mode(series):
    values = series.values
    dropped = values[~np.isnan(values)]

    # check for empty array and return NaN
    if not dropped.size:
        return np.NaN

    uniques, counts = np.unique(series.dropna(), return_counts=True)
    return uniques[np.argmax(counts)]

df2.resample("7D").apply(lambda x: x.apply(get_mode))

                     0      1
2015-11-12 00:00:00  7.0    5.0
2015-11-19 00:00:00  6.0    NaN

And here the timings based on the dummy data (for further improvements, have a look here):

%%timeit
df2.resample("7D").apply(lambda x: x.apply(pd.value_counts).idxmax())
>>> 100 loops, best of 3: 18.6 ms per loop

%%timeit
df2.resample("7D").apply(lambda x: x.apply(get_mode))
>>> 100 loops, best of 3: 3.72 ms per loop

I also tried scipy.stats.mode however it was also slower than the numpy solution:

size = 1000
index = pd.DatetimeIndex(start="2012-12-12", periods=size, freq="D")
dummy = pd.DataFrame(np.random.randint(0, 20, size=(size, 50)), index=index)
print(dummy.head)

            0   1   2   3   4   5   6   7   8   9   ...     40  41  42  43  44  45  46  47  48  49
2012-12-12  18  2   7   1   7   9   16  2   19  19  ...     10  2   18  16  15  10  7   19  9   6
2012-12-13  7   4   11  19  17  10  18  0   10  7   ...     19  11  5   5   11  4   0   16  12  19
2012-12-14  14  0   14  5   1   11  2   19  5   9   ...     2   9   4   2   9   5   19  2   16  2
2012-12-15  12  2   7   2   12  12  11  11  19  5   ...     16  0   4   9   13  5   10  2   14  4
2012-12-16  8   15  2   18  3   16  15  0   14  14  ...     18  2   6   13  19  10  3   16  11  4

%%timeit
dummy.resample("7D").apply(lambda x: x.apply(get_mode))
>>> 1 loop, best of 3: 926 ms per loop

%%timeit
dummy.resample("7D").apply(lambda x: x.apply(pd.value_counts).idxmax())
>>> 1 loop, best of 3: 5.84 s per loop

%%timeit
dummy.resample("7D").apply(lambda x: stats.mode(x).mode)
>>> 1 loop, best of 3: 1.32 s per loop


来源: stackexchange

问:
What is the alternative to cursors to retrieve large amounts of data from a database?
Searching through stackoverflow I found a large number of answers condemning the use of cursors in database programming. However I don't really understand what the alternative is.

I'm creating a program which reads a large number of rows (hundreds of thousands) from the database and keeps them in memory, for performance reasons. I can't really run a SELECT * FROM table and process all the results at once, can I?

The best way I have found is to use cursors and retrieve the rows in increments, for example 10 at a time.

Could someone enlighten me? I use PostgreSQL 9 on linux.

Thanks

答:
A CURSOR is the best option when you have to deal with large amounts of data. You could also use the LIMIT .. OFFSET .. method, but this will get slower and slower, depending on the amount of data. PostgreSQL doesn't have any problems with cursors, use them when you handle large amounts of data.

SQL Server has/had problems with cursors, MySQL can't handle cursors outside stored functions, that might be the reason some dba's don't like cursors.

ContentLicense: CC BY-SA 2.5


问:
Database first automatic class causes CA2214: Do not call overridable methods in constructors
Auto generated class by EntityFramework 6.1:

```<code>public partial class STUDENT
{
    public STUDENT()
    {
        this.STUDENT_GROUPS = new HashSet<STUDENT_GROUPS>();
    }
    public int ID { get; set; }
    public int PERSON { get; set; }
    ...
    public virtual ICollection<STUDENT_GROUPS> STUDENT_GROUPS { get; set; }
    ...
}
</code>```

And STUDENT_GROUPS:

```<code>public partial class STUDENT_GROUPS
{
    public int ID { get; set; }
    public int GROUPS_GRP { get; set; }
    public int STUDENT { get; set; }

    public virtual STUDENT STUDENT1 { get; set; }
    public virtual GROUPS_GRP GROUPS_GRP1 { get; set; }
}
</code>```

Throws a CA2214: Do not call overridable methods in constructors, but since this is an autogenerated code, I think I am not supposed to change it, how should i approach this scenario?
Thanks in advance

答:
In this case, you can ignore the warning, but if you want to avoid it, you can make manually a private field for each virtual property (and setter/getter manually too). Then, in the constructor, set the private field, not the property.
In this way, you never execute the setter of a virtual property inside de constructor, which it´s the reason of the warning.</p>

ContentLicense: CC BY-SA 3.0

Body:
Auto generated class by EntityFramework 6.1:

public partial class STUDENT
{
    public STUDENT()
    {
        this.STUDENT_GROUPS = new HashSet<STUDENT_GROUPS>();
    }
    public int ID { get; set; }
    public int PERSON { get; set; }
    ...
    public virtual ICollection<STUDENT_GROUPS> STUDENT_GROUPS { get; set; }
    ...
}

And STUDENT_GROUPS:

public partial class STUDENT_GROUPS
{
    public int ID { get; set; }
    public int GROUPS_GRP { get; set; }
    public int STUDENT { get; set; }

    public virtual STUDENT STUDENT1 { get; set; }
    public virtual GROUPS_GRP GROUPS_GRP1 { get; set; }
}

Throws a CA2214: Do not call overridable methods in constructors, but since this is an autogenerated code, I think I am not supposed to change it, how should i approach this scenario?
Thanks in advance


问:
Jar issue while deploying a war
well I have an application which I am building using Maven and running on eclipse(tomcat runtime) , it is working fine. But when I deploy the WAR of the project on tomcat (not using eclipse), its failing. The error is due to a coustome jar which I have included.

Stack trace are as follows:-

```<code>Aug 26, 2013 3:18:16 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error in dependencyCheck
java.io.IOException: Jar: smartcharging-model.jar
    at org.apache.catalina.util.ExtensionValidator.validateApplication(ExtensionValidator.java:207)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5256)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1256)
    at org.apache.catalina.manager.HTMLManagerServlet.start(HTMLManagerServlet.java:714)
    at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:219)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:212)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:611)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.util.zip.ZipException: invalid distance too far back
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at java.util.zip.ZipInputStream.read(Unknown Source)
    at java.util.jar.JarInputStream.read(Unknown Source)
    at java.io.BufferedInputStream.read1(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at java.util.jar.JarInputStream.getBytes(Unknown Source)
    at java.util.jar.JarInputStream.checkManifest(Unknown Source)
    at java.util.jar.JarInputStream.<init>(Unknown Source)
    at java.util.jar.JarInputStream.<init>(Unknown Source)
    at org.apache.catalina.util.ExtensionValidator.getManifest(ExtensionValidator.java:395)
    at org.apache.catalina.util.ExtensionValidator.validateApplication(ExtensionValidator.java:196)
    ... 29 more

Aug 26, 2013 3:18:16 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error getConfigured
Aug 26, 2013 3:18:16 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/Smart-0.0.1-SNAPSHOT] startup failed due to previous errors
Aug 26, 2013 3:18:16 PM org.apache.catalina.util.LifecycleBase stop
INFO: The stop() method was called on component [WebappLoader[/Smart-0.0.1-SNAPSHOT]] after stop() had already been called. The second call will be ignored.
</code>```

答:
I had the same issue and it was caused by encoding problems during the transfer of the war file from a Windows to a Unix system.

For this task I used WinSCP with the "Standard" file transfer option. As soon as I switched to the "Binary" format it worked and the war could be read by the application server.

Title: Jar issue while deploying a war

Body:
well I have an application which I am building using Maven and running on eclipse(tomcat runtime) , it is working fine. But when I deploy the WAR of the project on tomcat (not using eclipse), its failing. The error is due to a coustome jar which I have included.

Stack trace are as follows:-

Aug 26, 2013 3:18:16 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error in dependencyCheck
java.io.IOException: Jar: smartcharging-model.jar
    at org.apache.catalina.util.ExtensionValidator.validateApplication(ExtensionValidator.java:207)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5256)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.manager.ManagerServlet.start(ManagerServlet.java:1256)
    at org.apache.catalina.manager.HTMLManagerServlet.start(HTMLManagerServlet.java:714)
    at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:219)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:212)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:611)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.util.zip.ZipException: invalid distance too far back
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at java.util.zip.ZipInputStream.read(Unknown Source)
    at java.util.jar.JarInputStream.read(Unknown Source)
    at java.io.BufferedInputStream.read1(Unknown Source)
    at java.io.BufferedInputStream.read(Unknown Source)
    at java.util.jar.JarInputStream.getBytes(Unknown Source)
    at java.util.jar.JarInputStream.checkManifest(Unknown Source)
    at java.util.jar.JarInputStream.<init>(Unknown Source)
    at java.util.jar.JarInputStream.<init>(Unknown Source)
    at org.apache.catalina.util.ExtensionValidator.getManifest(ExtensionValidator.java:395)
    at org.apache.catalina.util.ExtensionValidator.validateApplication(ExtensionValidator.java:196)
    ... 29 more

Aug 26, 2013 3:18:16 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error getConfigured
Aug 26, 2013 3:18:16 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/Smart-0.0.1-SNAPSHOT] startup failed due to previous errors
Aug 26, 2013 3:18:16 PM org.apache.catalina.util.LifecycleBase stop
INFO: The stop() method was called on component [WebappLoader[/Smart-0.0.1-SNAPSHOT]] after stop() had already been called. The second call will be ignored.


问:
How to get value of "extract" key from a Wikipedia JSON response
I want read the value of "extract" key in a Wikipedia JSON response in Python3. The URL I'm testing with is https://en.wikipedia.org/w/api.php?action=query&titles=San%20Francisco&prop=extracts&format=json.

The response looks like this

```<code>{
  "batchcomplete": "",
  "query": {
    "pages": {
      "49728": {
        "pageid": 49728,
        "ns": 0,
        "title": "San Francisco",
        "extract": "<p><b>San Francisco</b></p>"
      }
    }
  }
}
</code>```

I removed the content as it was a lot.

Now the problem is how do I read the page number programmatically. The page number changes with different searches. I definitely don't want to hard code the page number. What do I put instead of page number

```<code>content = response.query.pages.<page number>.extract
</code>```

Is there any way to extract the key from the pages tag and then proceed to get it's value?

答:
One possible way to do this using the .keys() method

page_number = list(json["query"]["pages"].keys())[0]

Body:
I want read the value of "extract" key in a Wikipedia JSON response in Python3. The URL I'm testing with is https://en.wikipedia.org/w/api.php?action=query&titles=San%20Francisco&prop=extracts&format=json.

The response looks like this

{
  "batchcomplete": "",
  "query": {
    "pages": {
      "49728": {
        "pageid": 49728,
        "ns": 0,
        "title": "San Francisco",
        "extract": "
San Francisco
"
      }
    }
  }
}

I removed the content as it was a lot.

Now the problem is how do I read the page number programmatically. The page number changes with different searches. I definitely don't want to hard code the page number. What do I put instead of page number

content = response.query.pages.<page number>.extract

Is there any way to extract the key from the pages tag and then proceed to get it's value?


问:
SQL Select producing slightly different results in phpAdmin vs. phpHTML
I consistently miss the first row result, which is more noticeable when there is only one row result.

I have a problem with my PDO commands. Any suggestions for how to correct please? If I remove the $pod->prepare nothing works. Not sure what to do?

```<code><?php
$sql = "SELECT  * FROM Order_Items
        JOIN    Parts ON Parts.id = Order_Items.part_id
        WHERE   Order_Items.orders_id = $id
        AND     qty <> 0
        ORDER BY Parts.id";

        $q = $pdo->prepare($sql);
        $q->execute(array());
        $row = $q->fetch(PDO::FETCH_ASSOC); // Roy says this is not needed

        while ($row = $q->fetch(PDO::FETCH_ASSOC))
        {
            echo    '<tr>';
            echo    '<td>' . $row['part_num'] . '</td>';
            echo    '<td>' . $row['part_desc'] . '</td>';
            echo    '<td>' . $row['qty'] . '</td>';
        }

    Database::disconnect();
?>
</code>```

答:
You are not getting an SQL error. This has nothing to do with the value of the line_item_id database column.

You are getting a PHP error. The variable $line_item_id is undefined.

Body:
I consistently miss the first row result, which is more noticeable when there is only one row result.

I have a problem with my PDO commands. Any suggestions for how to correct please? If I remove the $pod->prepare nothing works. Not sure what to do?

<?php
$sql = "SELECT  * FROM Order_Items
        JOIN    Parts ON Parts.id = Order_Items.part_id
        WHERE   Order_Items.orders_id = $id
        AND     qty <> 0
        ORDER BY Parts.id";

        $q = $pdo->prepare($sql);
        $q->execute(array());
        $row = $q->fetch(PDO::FETCH_ASSOC); // Roy says this is not needed

        while ($row = $q->fetch(PDO::FETCH_ASSOC))
        {
            echo    '
';
            echo    '' . $row['part_num'] . '	';
            echo    '' . $row['part_desc'] . '	';
            echo    '' . $row['qty'] . '	';
        }

    Database::disconnect();
?>


问:
Javascript timeout restart
I have a module in my node app, which has a setTimeout function, which calls after every let's say 60 minutes. For sake of simplicity, you can understand that after every 60 minutes,

it connects to some cloud

query some data from it

and saves it in my Mongo collection

```<code>  setTimeout(() => {
    fetchData();
  }, 3600000); // = 1 hour
</code>```

Problem is that if any error comes in fetchData function then I throw an error and server's code flow stops and obviously setTimeout never starts again.

```<code>throw new Error(err);
</code>```

Possible ways of errors:

login to cloud

fetch data by some query

logging out from cloud, and many more

So, I need some kind of solution where after throwing an error I can restart this setTimeout function, so that my fetching process will keep going on. I'm not sure if it's even possible, that's why I am posting here.

Please also note that, in real, this fetchData function is a module which consists of more than 10 files and lots of JavaScript promises.

Let me know in comments for any clarification guys.

答:
It's definitely possible.  You need to properly handle the errors.  This can be achieved with a simple try catch block:</p>

```<code>function simulateError(){
    return (Math.floor(Math.random() * 5) + 1) == 3;
}

function cloudConnect(){
    if (simulateError()){
        throw new Error("Cloud connect error");
    }
    else {
        return "Connection";
    }
}

function cloudQuery(){
    if (simulateError()){
        throw new Error("Query error");
    }
    else {
       return "Query results";
    }
}

function saveCollection(){
    if (simulateError()){
        throw new Error("Save error");
    }
    else {
        return "Save results";
    }
 }

function fetchData(){
      try {
          cloudConnect();
          cloudQuery();
          saveCollection();
      }
      catch(error){
          console.log("Error fetching data: ",error, " will retry in N seconds");
      }
}

//Now that fetchData handles errors with a try/catch block, the interval will continue to run every 60 seconds,
//regardless of whether or not any errors are thrown
setInterval(function(){
     fetchData();
}, 60000);
</code>```

Title: Javascript timeout restart

Body:
I have a module in my node app, which has a setTimeout function, which calls after every let's say 60 minutes. For sake of simplicity, you can understand that after every 60 minutes,

it connects to some cloud

query some data from it

and saves it in my Mongo collection

  setTimeout(() => {
    fetchData();
  }, 3600000); // = 1 hour

Problem is that if any error comes in fetchData function then I throw an error and server's code flow stops and obviously setTimeout never starts again.

throw new Error(err);

Possible ways of errors:

login to cloud

fetch data by some query

logging out from cloud, and many more

So, I need some kind of solution where after throwing an error I can restart this setTimeout function, so that my fetching process will keep going on. I'm not sure if it's even possible, that's why I am posting here.

Please also note that, in real, this fetchData function is a module which consists of more than 10 files and lots of JavaScript promises.

Let me know in comments for any clarification guys.

Body:
It's definitely possible.  You need to properly handle the errors.  This can be achieved with a simple try catch block:

function simulateError(){
    return (Math.floor(Math.random() * 5) + 1) == 3;
}

function cloudConnect(){
    if (simulateError()){
        throw new Error("Cloud connect error");
    }
    else {
        return "Connection";
    }
}

function cloudQuery(){
    if (simulateError()){
        throw new Error("Query error");
    }
    else {
       return "Query results";
    }
}

function saveCollection(){
    if (simulateError()){
        throw new Error("Save error");
    }
    else {
        return "Save results";
    }
 }

function fetchData(){
      try {
          cloudConnect();
          cloudQuery();
          saveCollection();
      }
      catch(error){
          console.log("Error fetching data: ",error, " will retry in N seconds");
      }
}

//Now that fetchData handles errors with a try/catch block, the interval will continue to run every 60 seconds,
//regardless of whether or not any errors are thrown
setInterval(function(){
     fetchData();
}, 60000);


问:
How to filter an ordered list stored into a string
Is it possible in bash to filter out a part of a string with another given string ?

I have a fixed list of motifs defined in a string. The order IS important and I want to keep only the parts that are passed as a parameter ?

```<code>myDefaultList="s,t,a,c,k"  #order is important
toRetains="k,t,c,u"  #provided by the user, order is not enforced

retained=filter $myDefaultList $toRetains # code to filter

echo $retained  # will print t,c,k"
</code>```

I can write an ugly method that will use IFS, arrays and loops, but I wonder if there's a 'clever' way to do that, using built-in commands ?

答:
here is another approach

```<code>tolines() { echo $1 | tr ',' '\n'; }
grep -f <(tolines "$toRetains") <(tolines "$myDefaultList") | paste -sd,
</code>```

will print

```<code>t,c,k
</code>```

assign to a variable as usual.

Body:
Is it possible in bash to filter out a part of a string with another given string ?

I have a fixed list of motifs defined in a string. The order IS important and I want to keep only the parts that are passed as a parameter ?

myDefaultList="s,t,a,c,k"  #order is important
toRetains="k,t,c,u"  #provided by the user, order is not enforced

retained=filter $myDefaultList $toRetains # code to filter

echo $retained  # will print t,c,k"

I can write an ugly method that will use IFS, arrays and loops, but I wonder if there's a 'clever' way to do that, using built-in commands ?

Body:
here is another approach

tolines() { echo $1 | tr ',' '\n'; }
grep -f <(tolines "$toRetains") <(tolines "$myDefaultList") | paste -sd,

will print

t,c,k

assign to a variable as usual.


问:
Hudson Free Temp Space location
I have just installed Hudson on a Weblogic server and I am having issues with the nodes going off line due to the Free Temp Space falling below the 1gig threshold. Now I have checked my /tmp folder (thinking Hudson uses that) but it is sitting at 10gigs free.

Would anybody be able to point me to the folder Hudson uses? Also I am using a SunOS box.

答:
In addition to Bill's answer, you can change this through the registry.

Key: HKLM\SOFTWARE\Apache Software Foundation\Procrun 2.0\Tomcat6\Parameters\Java

Value: Options (look for java.io.tmpdir)

Title: Hudson Free Temp Space location


问:
Possible to open the newer, slicker AVD Manager window from the command line?
I know of two ways to open the Android Virtual Device (AVD) Manager window: to open it via Android Studio or by running the android avd command in Terminal.

I'm seeing however that the AVD Manager window which opens via Android Studio is considerably slicker and better than the window that opens with the android avd command.

Is there any way to open the slicker and better AVD Manager window by means of the command line... or outside of Android Studio? (I notice also in Android Studio that I have to open a project to be able to open the AVD Manager window which is a tad bit annoying.)

答:
Configure you device in Android Studio via AVD Manager.

Get a list of working devices with emulator -list-avds

Start the desired device with emulator -avd Nexus_5X_API_23

Recently there is an bug in Android SDK which let you result in a QT-Lib-Missing-Bug. See Cannot launch AVD in emulator:QT library not found

Just use the emulator out of his directory (~/Library/Android/sdk/tools/) solves the problem for me.


问:
How to get sticky footer on every page
Hi I have troubles to get the footer sticky.

The other pages are sticky because of the content. But on a empty page or page with few content not working.

The code:

```<code>html, body {
    height: 100%;
}
footer {
    position: absolute;
    bottom: 0;
}
</code>```

If I use

```<code>position: absolute;
bottom: 0;
</code>```

it works on this page but not on the other pages. Also tried with min-height

答:
Try this:</p>

```<code>#page {
    min-height: 100vh;
    position: relative;
}

footer {
    bottom: 0;
    position: absolute;
}
</code>```

Title: How to get sticky footer on every page

Body:
Hi I have troubles to get the footer sticky.

The other pages are sticky because of the content. But on a empty page or page with few content not working.

The code:

html, body {
    height: 100%;
}
footer {
    position: absolute;
    bottom: 0;
}

If I use

position: absolute;
bottom: 0;

it works on this page but not on the other pages. Also tried with min-height

Body:
Try this:

#page {
    min-height: 100vh;
    position: relative;
}

footer {
    bottom: 0;
    position: absolute;
}


问:
C# generics - overload based on type traits
I'm new to C# and I want to create a function that accepts any numeric parameter, no matter if it's int/float, signed/unsigned, short/long etc and another function that accepts any other type.

In C++ this can be easily done using SFINAE and std::is_arithmetic:

```<code>template<typename T>
typename std::enable_if<std::is_arithmetic<T>::value>::type DoSomething(T)
{
    std::cout<<"int/float/char..."<<std::endl;
}

template<typename T>
typename std::enable_if<!std::is_arithmetic<T>::value>::type DoSomething(T)
{
    std::cout<<"any other type except int/float..."<<std::endl;
}
</code>```

How may I achieve similar behavior in C#? I don't want to create an overload for every numeric type as the code for all numeric types as the code is exactly the same.

答:
I've been able to come up with something that is along the lines of what you're looking for; it's far less elegant than what can be done in C++.

The root of it is a struct that looks like

```<code>namespace TypeTraits
{
struct Number<T, TOperations> : IComparable, IFormattable, IConvertible, IComparable<Number<T, TOperations>>, IEquatable<Number<T, TOperations>>, IComparable<T>, IEquatable<T>
    where T : IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
    where TOperations : Operations<Number<T, TOperations>>, new()
{
    static readonly Operations<Number<T, TOperations>> Operations = new TOperations();

    public T Value { get; }
    public Number(T value)
    {
        Value = value;
    }
    public static implicit operator Number<T, TOperations>(T source) => new Number<T, TOperations>(source);
    public static implicit operator T(Number<T, TOperations> source) => source.Value;

    public override bool Equals(object obj) => Value.Equals(obj);
    public override int GetHashCode() => Value.GetHashCode();
    public override string ToString() => Value.ToString();

    public bool Equals(T other) => Value.Equals(other);
    public bool Equals(Number<T, TOperations> other) => Equals(other.Value);

    public int CompareTo(object obj) => Value.CompareTo(obj);
    public int CompareTo(T other) => Value.CompareTo(other);
    public int CompareTo(Number<T, TOperations> other) => CompareTo(other.Value);

    public string ToString(string format, IFormatProvider formatProvider) => Value.ToString(format, formatProvider);

    public TypeCode GetTypeCode() => Value.GetTypeCode();
    public bool ToBoolean(IFormatProvider provider) => Value.ToBoolean(provider);
    public byte ToByte(IFormatProvider provider) => Value.ToByte(provider);
    public char ToChar(IFormatProvider provider) => Value.ToChar(provider);
    public DateTime ToDateTime(IFormatProvider provider) => Value.ToDateTime(provider);
    public decimal ToDecimal(IFormatProvider provider) => Value.ToDecimal(provider);
    public double ToDouble(IFormatProvider provider) => Value.ToDouble(provider);
    public short ToInt16(IFormatProvider provider) => Value.ToInt16(provider);
    public int ToInt32(IFormatProvider provider) => Value.ToInt32(provider);
    public long ToInt64(IFormatProvider provider) => Value.ToInt64(provider);
    public sbyte ToSByte(IFormatProvider provider) => Value.ToSByte(provider);
    public float ToSingle(IFormatProvider provider) => Value.ToSingle(provider);
    public string ToString(IFormatProvider provider) => Value.ToString(provider);
    public object ToType(Type conversionType, IFormatProvider provider) => Value.ToType(conversionType, provider);
    public ushort ToUInt16(IFormatProvider provider) => Value.ToUInt16(provider);
    public uint ToUInt32(IFormatProvider provider) => Value.ToUInt32(provider);
    public ulong ToUInt64(IFormatProvider provider) => Value.ToUInt64(provider);

    public static Number<T, TOperations> operator+(Number<T, TOperations> lhs, Number<T, TOperations> rhs) => Operations.Add(lhs, rhs);
}
}
</code>```

yes, that's a lot of code; but most of it is simple pass-through.

You then have an abstract Operations class and a couple of concrete implementations.  This is the "trick" to get things into a type so it can be used as a generic parameter.

```<code>namespace TypeTraits
{
class Operations<T>
    where T : IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
{
    // names from https://msdn.microsoft.com/en-us/library/ms182355.aspx
    public virtual T Add(T a, T b)
    {
        throw new NotImplementedException();
    }
}

sealed class OperationsInt32 : Operations<Int32>
{
    public override Int32 Add(Int32 a, Int32 b)
    {
        return a.Value + b.Value;
    }
}

sealed class OperationsDouble : Operations<Double>
{
    public override Double Add(Double a, Double b)
    {
        return a.Value + b.Value;
    }
}
}
</code>```

Finally, at the top-level (outside of namespace), some using aliases

```<code>using Int32 = TypeTraits.Number<System.Int32, TypeTraits.OperationsInt32>;
using Double = TypeTraits.Number<System.Double, TypeTraits.OperationsDouble>;
</code>```

With all that in place, you can now write code like:

```<code>class Program
{
    static void DoSomething<T>(T t)
    {
        Console.WriteLine("DoSomething<T>");
    }

    static void DoSomething<T, TOperations>(Number<T, TOperations> t)
        where T : IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
        where TOperations : Operations<Number<T, TOperations>>, new()
    {
        Number<T, TOperations> t2 = t;
        var t3 = t + t2;
        Console.WriteLine("DoSomething<Number<T, TOperations>>");
    }

    static void Main(string[] args)
    {
        string s = "314";
        Int32 i = 314;
        Double d = 3.14;

        DoSomething(s);
        DoSomething(i);
        DoSomething(d);
    }
}
</code>```

It might be possible to simplify this a bit by removing some constraints ...

Body:
I'm new to C# and I want to create a function that accepts any numeric parameter, no matter if it's int/float, signed/unsigned, short/long etc and another function that accepts any other type.

In C++ this can be easily done using SFINAE and std::is_arithmetic:

template<typename T>
typename std::enable_if<std::is_arithmetic<T>::value>::type DoSomething(T)
{
    std::cout<<"int/float/char..."<<std::endl;
}

template<typename T>
typename std::enable_if<!std::is_arithmetic<T>::value>::type DoSomething(T)
{
    std::cout<<"any other type except int/float..."<<std::endl;
}

How may I achieve similar behavior in C#? I don't want to create an overload for every numeric type as the code for all numeric types as the code is exactly the same.

Body:
I've been able to come up with something that is along the lines of what you're looking for; it's far less elegant than what can be done in C++.

The root of it is a struct that looks like

namespace TypeTraits
{
struct Number<T, TOperations> : IComparable, IFormattable, IConvertible, IComparable<Number<T, TOperations>>, IEquatable<Number<T, TOperations>>, IComparable<T>, IEquatable<T>
    where T : IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
    where TOperations : Operations<Number<T, TOperations>>, new()
{
    static readonly Operations<Number<T, TOperations>> Operations = new TOperations();

    public T Value { get; }
    public Number(T value)
    {
        Value = value;
    }
    public static implicit operator Number<T, TOperations>(T source) => new Number<T, TOperations>(source);
    public static implicit operator T(Number<T, TOperations> source) => source.Value;

    public override bool Equals(object obj) => Value.Equals(obj);
    public override int GetHashCode() => Value.GetHashCode();
    public override string ToString() => Value.ToString();

    public bool Equals(T other) => Value.Equals(other);
    public bool Equals(Number<T, TOperations> other) => Equals(other.Value);

    public int CompareTo(object obj) => Value.CompareTo(obj);
    public int CompareTo(T other) => Value.CompareTo(other);
    public int CompareTo(Number<T, TOperations> other) => CompareTo(other.Value);

    public string ToString(string format, IFormatProvider formatProvider) => Value.ToString(format, formatProvider);

    public TypeCode GetTypeCode() => Value.GetTypeCode();
    public bool ToBoolean(IFormatProvider provider) => Value.ToBoolean(provider);
    public byte ToByte(IFormatProvider provider) => Value.ToByte(provider);
    public char ToChar(IFormatProvider provider) => Value.ToChar(provider);
    public DateTime ToDateTime(IFormatProvider provider) => Value.ToDateTime(provider);
    public decimal ToDecimal(IFormatProvider provider) => Value.ToDecimal(provider);
    public double ToDouble(IFormatProvider provider) => Value.ToDouble(provider);
    public short ToInt16(IFormatProvider provider) => Value.ToInt16(provider);
    public int ToInt32(IFormatProvider provider) => Value.ToInt32(provider);
    public long ToInt64(IFormatProvider provider) => Value.ToInt64(provider);
    public sbyte ToSByte(IFormatProvider provider) => Value.ToSByte(provider);
    public float ToSingle(IFormatProvider provider) => Value.ToSingle(provider);
    public string ToString(IFormatProvider provider) => Value.ToString(provider);
    public object ToType(Type conversionType, IFormatProvider provider) => Value.ToType(conversionType, provider);
    public ushort ToUInt16(IFormatProvider provider) => Value.ToUInt16(provider);
    public uint ToUInt32(IFormatProvider provider) => Value.ToUInt32(provider);
    public ulong ToUInt64(IFormatProvider provider) => Value.ToUInt64(provider);

    public static Number<T, TOperations> operator+(Number<T, TOperations> lhs, Number<T, TOperations> rhs) => Operations.Add(lhs, rhs);
}
}

yes, that's a lot of code; but most of it is simple pass-through.

You then have an abstract Operations class and a couple of concrete implementations.  This is the "trick" to get things into a type so it can be used as a generic parameter.

namespace TypeTraits
{
class Operations<T>
    where T : IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
{
    // names from https://msdn.microsoft.com/en-us/library/ms182355.aspx
    public virtual T Add(T a, T b)
    {
        throw new NotImplementedException();
    }
}

sealed class OperationsInt32 : Operations<Int32>
{
    public override Int32 Add(Int32 a, Int32 b)
    {
        return a.Value + b.Value;
    }
}

sealed class OperationsDouble : Operations<Double>
{
    public override Double Add(Double a, Double b)
    {
        return a.Value + b.Value;
    }
}
}

Finally, at the top-level (outside of namespace), some using aliases

using Int32 = TypeTraits.Number<System.Int32, TypeTraits.OperationsInt32>;
using Double = TypeTraits.Number<System.Double, TypeTraits.OperationsDouble>;

With all that in place, you can now write code like:

class Program
{
    static void DoSomething<T>(T t)
    {
        Console.WriteLine("DoSomething<T>");
    }

    static void DoSomething<T, TOperations>(Number<T, TOperations> t)
        where T : IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
        where TOperations : Operations<Number<T, TOperations>>, new()
    {
        Number<T, TOperations> t2 = t;
        var t3 = t + t2;
        Console.WriteLine("DoSomething<Number<T, TOperations>>");
    }

    static void Main(string[] args)
    {
        string s = "314";
        Int32 i = 314;
        Double d = 3.14;

        DoSomething(s);
        DoSomething(i);
        DoSomething(d);
    }
}

It might be possible to simplify this a bit by removing some constraints ...


问:
Matching Powershell XML output to schema
I have a monitoring system that returns JSON data. I am using Powershell to get all of the monitored servers and a subset of their properties. Then I want to export those properties to an XML file that matches an XSD, but I am not sure how to do that.

When I run

```<code>$allServers | get-member
</code>```

I can see all of the properties for the servers in a System.Management.Automation.PSCustomObject. So I run:

```<code>$filtered = $allServers | Select-Object Id,HostName,Description,Status
</code>```

Okay, now I have the properties I want and I can run something like this:

```<code>$filtered = ($filtered | ConvertTo-Xml)
</code>```

and now I have a System.Xml.XmlDocument object. Super. I can use the save method:

```<code>$filtered.Save("c:\test\test.xml")
</code>```

The output looks okay, but does not match the required schema file.

```<code><?xml version="1.0" encoding="utf-8"?>
<Objects>
  <Object Type="System.Management.Automation.PSCustomObject">
    <Property Name="id" Type="System.Int32">6</Property>
    <Property Name="hostname" Type="System.String">server1</Property>
    <Property Name="description" Type="System.String">dc</Property>
    <Property Name="status" Type="System.Int32">1</Property>
  </Object>
</Objects>
</code>```

My schema looks like this:

```<code><?xml version="1.0" encoding="Windows-1252"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xsd:element name="ServerImport">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Servers">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element maxOccurs="unbounded" name="Server">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element name="Id" type="xsd:int" />
                    <xsd:element name="HostName" type="xsd:string" />
                    <xsd:element name="Description" type="xsd:string" />
                    <xsd:element name="Status" type="xsd:int" />
                  </xsd:sequence>
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xs:schema>
</code>```

So, how do I make my output match the schema?

Thanks.

答:
v5 of PowerShell supports proper class structures. Therefore, you could create a class which contains the information you desire and a small-ish function to convert the class to an XmlNode:

```<code>function makeXML($parentNode, $class) {

    $d = $parentNode.OwnerDocument.CreateElement($class.GetType().Name);
    $class.psobject.properties | foreach {
        $p = $doc.CreateElement($_.Name);
        $p.InnerText = $_.Value;
        $d.AppendChild($p);
    }

    $parentNode.AppendChild($d);
}

class Server {
    [int]$Id;
    [string]$HostName;
    [string]$Description;
    [int]$Status
};

# Here you would need to convert the output from
#     Select-Object ID,HostName,Description,Status
# to instances of type Server

$s = New-Object server;
$s.Id = 1;
$s.HostName = "localhost";
$s.Description = "Local Server";
$s.Status = 3;

# Create the empty XML document to save your results to with root node of "Servers"
$doc = New-Object System.Xml.XmlDocument;
$doc.LoadXml("<ServerImport><Servers></Servers></ServerImport>");
$serversNode = $doc.SelectSingleNode("/ServerImport/Servers");

# This could likely be a pipe operation against your list of Server objects
# $filtered | { makeXml $serversNode $_ }
makeXML $serversNode $s;
# Save your xml to a file
$doc.Save("C:\test\test.xml");
</code>```

Which results in the following XML:

```<code><ServerImport>
  <Servers>
    <Server>
      <Id>1</Id>
      <HostName>localhost</HostName>
      <Description>Local Server</Description>
      <Status>3</Status>
    </Server>
  </Servers>
</ServerImport>
</code>```

Note: I am sure there are more elegant solutions and there are probably a dozen enhancements the above code endure. But, this should get you started.

Edit - overlooked the needed structure of the XML (missed the ServerImport root node).

Body:
I have a monitoring system that returns JSON data. I am using Powershell to get all of the monitored servers and a subset of their properties. Then I want to export those properties to an XML file that matches an XSD, but I am not sure how to do that.

When I run

$allServers | get-member

I can see all of the properties for the servers in a System.Management.Automation.PSCustomObject. So I run:

$filtered = $allServers | Select-Object Id,HostName,Description,Status

Okay, now I have the properties I want and I can run something like this:

$filtered = ($filtered | ConvertTo-Xml)

and now I have a System.Xml.XmlDocument object. Super. I can use the save method:

$filtered.Save("c:\test\test.xml")

The output looks okay, but does not match the required schema file.

<?xml version="1.0" encoding="utf-8"?>
<Objects>
  <Object Type="System.Management.Automation.PSCustomObject">
    <Property Name="id" Type="System.Int32">6</Property>
    <Property Name="hostname" Type="System.String">server1</Property>
    <Property Name="description" Type="System.String">dc</Property>
    <Property Name="status" Type="System.Int32">1</Property>
  </Object>
</Objects>

My schema looks like this:

<?xml version="1.0" encoding="Windows-1252"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xsd:element name="ServerImport">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="Servers">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element maxOccurs="unbounded" name="Server">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element name="Id" type="xsd:int" />
                    <xsd:element name="HostName" type="xsd:string" />
                    <xsd:element name="Description" type="xsd:string" />
                    <xsd:element name="Status" type="xsd:int" />
                  </xsd:sequence>
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xs:schema>

So, how do I make my output match the schema?

Thanks.

Body:
v5 of PowerShell supports proper class structures. Therefore, you could create a class which contains the information you desire and a small-ish function to convert the class to an XmlNode:

function makeXML($parentNode, $class) {

    $d = $parentNode.OwnerDocument.CreateElement($class.GetType().Name);
    $class.psobject.properties | foreach {
        $p = $doc.CreateElement($_.Name);
        $p.InnerText = $_.Value;
        $d.AppendChild($p);
    }

    $parentNode.AppendChild($d);
}

class Server {
    [int]$Id;
    [string]$HostName;
    [string]$Description;
    [int]$Status
};

# Here you would need to convert the output from
#     Select-Object ID,HostName,Description,Status
# to instances of type Server

$s = New-Object server;
$s.Id = 1;
$s.HostName = "localhost";
$s.Description = "Local Server";
$s.Status = 3;

# Create the empty XML document to save your results to with root node of "Servers"
$doc = New-Object System.Xml.XmlDocument;
$doc.LoadXml("<ServerImport><Servers></Servers></ServerImport>");
$serversNode = $doc.SelectSingleNode("/ServerImport/Servers");

# This could likely be a pipe operation against your list of Server objects
# $filtered | { makeXml $serversNode $_ }
makeXML $serversNode $s;
# Save your xml to a file
$doc.Save("C:\test\test.xml");

Which results in the following XML:

<ServerImport>
  <Servers>
    <Server>
      <Id>1</Id>
      <HostName>localhost</HostName>
      <Description>Local Server</Description>
      <Status>3</Status>
    </Server>
  </Servers>
</ServerImport>

Note: I am sure there are more elegant solutions and there are probably a dozen enhancements the above code endure. But, this should get you started.

Edit - overlooked the needed structure of the XML (missed the ServerImport root node).


问:
Aurelia framework update model from javascript callback function
I'm trying to migrate a piece of code from plain JavaScript to Aurelia, and I can't seem to figure out the following code (executed from within a view-model):

```<code>var callbackFunction = 'DmsToWorkflowsCallback';
var treeEnum = new BrowseTreeNodeEnums();
var contentType = treeEnum.Document;
var url = dmsUrlPrefix +
          "BrowseDlgEx.aspx?" +
          "multiSelect=1" +
          "&title=Attach" +
          "&callback=" + callbackFunction +
          "&contentType=" + contentType +
          "&context=btworkflows;" + domain;
window.open(url, "_blank", "height=600, width=800,status=0,toolbar=0,menubar=0,location=no,modal=1,dialog=yes,top=100,left=100");
</code>```

In plain JavaScript, the calling window (which is a custom plugin with no documentation) was able to locate the callback function (line 1) and execute the rest of the business logic correctly; in Aurelia, however, it doesn't seem able to locate the provided function!

I tried specifying the callback function both inside and outside the class (using regular function declaration), as well as using this.DmsToWorkflowsCallback as the callback function specification, without success...

I even tried adding a dummy callback function inside the View using a

答:
You just need to set the callback function on the window object. If the function you want to call is a function on your VM, then it would be best to wrap the call in a fat arrow function:

```<code>window.theCallback = () => this.theCallback();
window.open('http://localhost:9000/foo.html', '_blank');
</code>```

Then, in the child page, you'll call this function using the opener reference.

```<code>opener.theCallback();
</code>```

Body:
I'm trying to migrate a piece of code from plain JavaScript to Aurelia, and I can't seem to figure out the following code (executed from within a view-model):

var callbackFunction = 'DmsToWorkflowsCallback';
var treeEnum = new BrowseTreeNodeEnums();
var contentType = treeEnum.Document;
var url = dmsUrlPrefix +
          "BrowseDlgEx.aspx?" +
          "multiSelect=1" +
          "&title=Attach" +
          "&callback=" + callbackFunction +
          "&contentType=" + contentType +
          "&context=btworkflows;" + domain;
window.open(url, "_blank", "height=600, width=800,status=0,toolbar=0,menubar=0,location=no,modal=1,dialog=yes,top=100,left=100");

In plain JavaScript, the calling window (which is a custom plugin with no documentation) was able to locate the callback function (line 1) and execute the rest of the business logic correctly; in Aurelia, however, it doesn't seem able to locate the provided function!

I tried specifying the callback function both inside and outside the class (using regular function declaration), as well as using this.DmsToWorkflowsCallback as the callback function specification, without success...

I even tried adding a dummy callback function inside the View using a

Body:
You just need to set the callback function on the window object. If the function you want to call is a function on your VM, then it would be best to wrap the call in a fat arrow function:

window.theCallback = () => this.theCallback();
window.open('http://localhost:9000/foo.html', '_blank');

Then, in the child page, you'll call this function using the opener reference.

opener.theCallback();


问:
How to pass csharp binding variable to Javascript function
I want to pass c# binding variable to javascript function. Here is my code:

```<code><asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%#Bind(variable)%>'); "></asp:LinkButton>
</code>```

But it always generates an error : "htmlfile: Not implemented".

And the code is not intepreted onclick="passAccessory('<%#Bind(variable)%>');"

Does anyone knows how to solve it ?

Thanks.

Edit: I have changed the code to

```<code><asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%# Eval("lblTest.ClientID") %>');"></asp:LinkButton>
</code>```

And this is the code it's related to, it uses the lblTest.ClientID

<asp:Label ID="lblTest" runat="server" Text='<%#Bind("reference")%>' />

But i received an error: HttpException. Databinding ... does not contain a property with the name lblTest. Is there any wrong with my code.

Edit:  These posts gave me a clue.

http://www.west-wind.com/Weblog/posts/5364.aspx

I am trying to learn how to bind an IEnumerable LINQ collection to a repeater

Now i have want to use

```<code><asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>' OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>'></asp:LinkButton>
</code>```

答:
You can do this easily by changing the OnClientClick event from Code-Behind.</p>

```<code>lbID.OnClientClick = "passAccessory(' " + variable + "')";
</code>```

Body:
I want to pass c# binding variable to javascript function. Here is my code:

<asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%#Bind(variable)%>'); "></asp:LinkButton>

But it always generates an error : "htmlfile: Not implemented".

And the code is not intepreted onclick="passAccessory('<%#Bind(variable)%>');"

Does anyone knows how to solve it ?

Thanks.

Edit: I have changed the code to

<asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%# Eval("lblTest.ClientID") %>');"></asp:LinkButton>

And this is the code it's related to, it uses the lblTest.ClientID

<asp:Label ID="lblTest" runat="server" Text='<%#Bind("reference")%>' />

But i received an error: HttpException. Databinding ... does not contain a property with the name lblTest. Is there any wrong with my code.

Edit:  These posts gave me a clue.

http://www.west-wind.com/Weblog/posts/5364.aspx

I am trying to learn how to bind an IEnumerable LINQ collection to a repeater

Now i have want to use

<asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>' OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>'></asp:LinkButton>

Body:
You can do this easily by changing the OnClientClick event from Code-Behind.

lbID.OnClientClick = "passAccessory(' " + variable + "')";


问:
Finding many duplicates based on multiple properties in one database hit
I'm trying to perform a check on the database to see if the combination of two properties exists in the database check (pre-Unique constraint check for better UX). Doing the check with a single property is easy, no matter how many you're trying to check. I'm unable to find how to do it with multiple properties in an enumerable.

```<code>public class Foo
{
    public int Id { get; set; }
    public int Bar { get; set; }
    public int Bat { get; set; }
    public string Name { get; set; }
    //...
}

public class FooDupeCheckModel
{
    public int Bar { get; set; }
    public int Bat { get; set; }
}

public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    return _db.Foos
              .Where(f => matches.Any(m => m.BarId == f.BarId &&
                                           m.BatId == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}
</code>```

This unfortunately gives an exception because the complex property matches cannot be converted into a SQL script. Only primitive types can be included into a query.

I also tried converting matches to a multidimensional array before using it within the query, but indexes are not supported within a query. .First() is not allowed to be used their either.

```<code>public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    var matchArray = matches.Select(m => new [] {m.BarId, m.BatId})
                            .ToArray();

    return _db.Foos
              .Where(f => matchArray.Any(m => m[0] == f.BarId &&
                                              m[1] == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}
</code>```

This may be one of those situations that is such a niche case, or requires a SQL query that is too complex for Entity Framework that it is not possible. If it is possible, then this would be very helpful if someone else runs into the same issue.

I did get around this by looping through and calling the database for each element in matches, but if I could do this in one database call, that'd be quicker.

答:
SQL Server doesn't support comparing tuples. However, you can compare two+ properties by OR-ing together comparisons:

```<code>SELECT *
FROM Foo f
WHERE
(
    (f.Bar = 1 AND f.Bat = 1)
    OR
    (f.Bar = 3 AND f.Bat = 2)
)
</code>```

Unfortunately, there's no easy way to build up an IQueryable<T> involving an OR. You can, however, build it up using Expression tree builders:

```<code>var models = new FooDupeCheckModel[]
{
    new FooDupeCheckModel() { Bar = 1, Bat = 2 },
    new FooDupeCheckModel() { Bar = 1, Bat = 3 }
};
var comparison = getComparison(models);

IQueryable<Foo> foos = new Foo[]
{
    new Foo() { Bar = 1, Bat = 1 },
    new Foo() { Bar = 1, Bat = 2 },
    new Foo() { Bar = 1, Bat = 3 },
    new Foo() { Bar = 1, Bat = 4 }
}.AsQueryable();
var results = foos.Where(comparison).ToArray();

...

private static Expression<Func<Foo, bool>> getComparison(IEnumerable<FooDupeCheckModel> models)
{
    ParameterExpression pe = Expression.Parameter(typeof(Foo), "f");
    var ands = models.Select(m =>
    {
        // Compare Bars
        Expression pBarId = Expression.Property(pe, "Bar");
        Expression vBarId = Expression.Constant(m.Bar);
        Expression bar = Expression.Equal(pBarId, vBarId);

        // Compare Bats
        Expression pBatId = Expression.Property(pe, "Bat");
        Expression vBatId = Expression.Constant(m.Bat);
        Expression bat = Expression.Equal(pBatId, vBatId);

        Expression and = Expression.And(bar, bat);
        return and;
    }).ToArray();
    if (ands.Length == 0)
    {
        return Expression.Lambda<Func<Foo, bool>>(Expression.Constant(true), pe);
    }
    else
    {
        Expression ors = ands.First();
        foreach (Expression and in ands.Skip(1))
        {
            ors = Expression.OrElse(ors, and);
        }
        return Expression.Lambda<Func<Foo, bool>>(ors, pe);
    }
}
</code>```

This works against in-memory data structures. Test it again SQL Server; it should generate the corresponding SQL.

Here is a version that supports an arbitrary number of properties with any names:

```<code>public class Foo
{
    public int Id { get; set; }
    public int Bar { get; set; }
    public int Bat { get; set; }
    public string Name { get; set; }
}

public class FooDupeCheckModel
{
    public int Bar { get; set; }
    public int Bat { get; set; }
}

static void Main(string[] args)
{
    var models = new FooDupeCheckModel[]
    {
        new FooDupeCheckModel() { Bar = 1, Bat = 2 },
        new FooDupeCheckModel() { Bar = 1, Bat = 3 }
    };
    var comparison = getComparison<Foo, FooDupeCheckModel>(
        models,
        compare((Foo f) => f.Bar, (FooDupeCheckModel f) => f.Bar),
        compare((Foo f) => f.Bat, (FooDupeCheckModel f) => f.Bat)
    );

    IQueryable<Foo> foos = new Foo[]
    {
        new Foo() { Bar = 1, Bat = 1 },
        new Foo() { Bar = 1, Bat = 2 },
        new Foo() { Bar = 1, Bat = 3 },
        new Foo() { Bar = 1, Bat = 4 }
    }.AsQueryable();
    var query = foos.Where(comparison);
    var results = query.ToArray();
}

private class PropertyComparison
{
    public PropertyInfo FromProperty { get; set; }

    public PropertyInfo ToProperty { get; set; }
}

private static PropertyComparison compare<TFrom, TFromValue, TTo, TToValue>(
    Expression<Func<TFrom, TFromValue>> fromAccessor,
    Expression<Func<TTo, TToValue>> toAccessor)
{
    MemberExpression fromMemberAccessor = (MemberExpression)fromAccessor.Body;
    PropertyInfo fromProperty = (PropertyInfo)fromMemberAccessor.Member;
    MemberExpression toMemberAccessor = (MemberExpression)toAccessor.Body;
    PropertyInfo toProperty = (PropertyInfo)toMemberAccessor.Member;
    return new PropertyComparison() { FromProperty = fromProperty, ToProperty = toProperty };
}

private static Expression<Func<TFrom, bool>> getComparison<TFrom, TTo>(
    IEnumerable<TTo> models,
    params PropertyComparison[] comparisons)
{
    ParameterExpression pe = Expression.Parameter(typeof(TFrom), "f");
    if (!models.Any() || !comparisons.Any())
    {
        return Expression.Lambda<Func<TFrom, bool>>(Expression.Constant(true), pe);
    }
    var ands = models.Select(m =>
    {
        var equals = comparisons.Select(p =>
        {
            PropertyInfo fromProperty = p.FromProperty;
            PropertyInfo toProperty = p.ToProperty;
            object value = toProperty.GetValue(m);

            Expression fromValue = Expression.Property(pe, fromProperty);
            Expression toValue = Expression.Constant(value);
            Expression equal = Expression.Equal(fromValue, toValue);
            return equal;
        }).ToArray();
        var and = equals.First();
        foreach (var equal in equals.Skip(1))
        {
            and = Expression.AndAlso(and, equal);
        }
        return and;
    }).ToArray();
    Expression ors = ands.First();
    foreach (Expression and in ands.Skip(1))
    {
        ors = Expression.OrElse(ors, and);
    }
    return Expression.Lambda<Func<TFrom, bool>>(ors, pe);
}
</code>```

Body:
I'm trying to perform a check on the database to see if the combination of two properties exists in the database check (pre-Unique constraint check for better UX). Doing the check with a single property is easy, no matter how many you're trying to check. I'm unable to find how to do it with multiple properties in an enumerable.

public class Foo
{
    public int Id { get; set; }
    public int Bar { get; set; }
    public int Bat { get; set; }
    public string Name { get; set; }
    //...
}

public class FooDupeCheckModel
{
    public int Bar { get; set; }
    public int Bat { get; set; }
}

public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    return _db.Foos
              .Where(f => matches.Any(m => m.BarId == f.BarId &&
                                           m.BatId == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}

This unfortunately gives an exception because the complex property matches cannot be converted into a SQL script. Only primitive types can be included into a query.

I also tried converting matches to a multidimensional array before using it within the query, but indexes are not supported within a query. .First() is not allowed to be used their either.

public IEnumerable<FooDupeCheckModel> MatchExists(IEnumerable<FooDupeCheckModel> matches)
{
    var matchArray = matches.Select(m => new [] {m.BarId, m.BatId})
                            .ToArray();

    return _db.Foos
              .Where(f => matchArray.Any(m => m[0] == f.BarId &&
                                              m[1] == f.BatId))
              .Select(f => new FooDupeCheckModel
              {
                  BarId = f.BarId,
                  BatId = f.BatId
              });
}

This may be one of those situations that is such a niche case, or requires a SQL query that is too complex for Entity Framework that it is not possible. If it is possible, then this would be very helpful if someone else runs into the same issue.

I did get around this by looping through and calling the database for each element in matches, but if I could do this in one database call, that'd be quicker.

Body:
SQL Server doesn't support comparing tuples. However, you can compare two+ properties by OR-ing together comparisons:

SELECT *
FROM Foo f
WHERE
(
    (f.Bar = 1 AND f.Bat = 1)
    OR
    (f.Bar = 3 AND f.Bat = 2)
)

Unfortunately, there's no easy way to build up an IQueryable<T> involving an OR. You can, however, build it up using Expression tree builders:

var models = new FooDupeCheckModel[]
{
    new FooDupeCheckModel() { Bar = 1, Bat = 2 },
    new FooDupeCheckModel() { Bar = 1, Bat = 3 }
};
var comparison = getComparison(models);

IQueryable<Foo> foos = new Foo[]
{
    new Foo() { Bar = 1, Bat = 1 },
    new Foo() { Bar = 1, Bat = 2 },
    new Foo() { Bar = 1, Bat = 3 },
    new Foo() { Bar = 1, Bat = 4 }
}.AsQueryable();
var results = foos.Where(comparison).ToArray();

...

private static Expression<Func<Foo, bool>> getComparison(IEnumerable<FooDupeCheckModel> models)
{
    ParameterExpression pe = Expression.Parameter(typeof(Foo), "f");
    var ands = models.Select(m =>
    {
        // Compare Bars
        Expression pBarId = Expression.Property(pe, "Bar");
        Expression vBarId = Expression.Constant(m.Bar);
        Expression bar = Expression.Equal(pBarId, vBarId);

        // Compare Bats
        Expression pBatId = Expression.Property(pe, "Bat");
        Expression vBatId = Expression.Constant(m.Bat);
        Expression bat = Expression.Equal(pBatId, vBatId);

        Expression and = Expression.And(bar, bat);
        return and;
    }).ToArray();
    if (ands.Length == 0)
    {
        return Expression.Lambda<Func<Foo, bool>>(Expression.Constant(true), pe);
    }
    else
    {
        Expression ors = ands.First();
        foreach (Expression and in ands.Skip(1))
        {
            ors = Expression.OrElse(ors, and);
        }
        return Expression.Lambda<Func<Foo, bool>>(ors, pe);
    }
}

This works against in-memory data structures. Test it again SQL Server; it should generate the corresponding SQL.

Here is a version that supports an arbitrary number of properties with any names:

public class Foo
{
    public int Id { get; set; }
    public int Bar { get; set; }
    public int Bat { get; set; }
    public string Name { get; set; }
}

public class FooDupeCheckModel
{
    public int Bar { get; set; }
    public int Bat { get; set; }
}

static void Main(string[] args)
{
    var models = new FooDupeCheckModel[]
    {
        new FooDupeCheckModel() { Bar = 1, Bat = 2 },
        new FooDupeCheckModel() { Bar = 1, Bat = 3 }
    };
    var comparison = getComparison<Foo, FooDupeCheckModel>(
        models,
        compare((Foo f) => f.Bar, (FooDupeCheckModel f) => f.Bar),
        compare((Foo f) => f.Bat, (FooDupeCheckModel f) => f.Bat)
    );

    IQueryable<Foo> foos = new Foo[]
    {
        new Foo() { Bar = 1, Bat = 1 },
        new Foo() { Bar = 1, Bat = 2 },
        new Foo() { Bar = 1, Bat = 3 },
        new Foo() { Bar = 1, Bat = 4 }
    }.AsQueryable();
    var query = foos.Where(comparison);
    var results = query.ToArray();
}

private class PropertyComparison
{
    public PropertyInfo FromProperty { get; set; }

    public PropertyInfo ToProperty { get; set; }
}

private static PropertyComparison compare<TFrom, TFromValue, TTo, TToValue>(
    Expression<Func<TFrom, TFromValue>> fromAccessor,
    Expression<Func<TTo, TToValue>> toAccessor)
{
    MemberExpression fromMemberAccessor = (MemberExpression)fromAccessor.Body;
    PropertyInfo fromProperty = (PropertyInfo)fromMemberAccessor.Member;
    MemberExpression toMemberAccessor = (MemberExpression)toAccessor.Body;
    PropertyInfo toProperty = (PropertyInfo)toMemberAccessor.Member;
    return new PropertyComparison() { FromProperty = fromProperty, ToProperty = toProperty };
}

private static Expression<Func<TFrom, bool>> getComparison<TFrom, TTo>(
    IEnumerable<TTo> models,
    params PropertyComparison[] comparisons)
{
    ParameterExpression pe = Expression.Parameter(typeof(TFrom), "f");
    if (!models.Any() || !comparisons.Any())
    {
        return Expression.Lambda<Func<TFrom, bool>>(Expression.Constant(true), pe);
    }
    var ands = models.Select(m =>
    {
        var equals = comparisons.Select(p =>
        {
            PropertyInfo fromProperty = p.FromProperty;
            PropertyInfo toProperty = p.ToProperty;
            object value = toProperty.GetValue(m);

            Expression fromValue = Expression.Property(pe, fromProperty);
            Expression toValue = Expression.Constant(value);
            Expression equal = Expression.Equal(fromValue, toValue);
            return equal;
        }).ToArray();
        var and = equals.First();
        foreach (var equal in equals.Skip(1))
        {
            and = Expression.AndAlso(and, equal);
        }
        return and;
    }).ToArray();
    Expression ors = ands.First();
    foreach (Expression and in ands.Skip(1))
    {
        ors = Expression.OrElse(ors, and);
    }
    return Expression.Lambda<Func<TFrom, bool>>(ors, pe);
}


问:
PHP array_search for multi dimensional array and return key
I'm trying to search for a value in a multi dimensional array (below is only a part of the big array) and get the key for that value but I can't manage it by myself. Here is what I have tried :

```<code>Array
(
    [0] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => -
            [4] => -
            [5] => ALES
            [6] => 44-
            [7] => -
            [8] => FR*S30*E36*1*1
            [9] => FR*S30*E36*1*1
            [10] => US*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )

    [1] => Array  // <-- wanted key
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => Chemin Des Sports
            [4] => -
            [5] => ALES
            [6] => -
            [7] => -
            [8] => FR*S30*E37*2*1  // <-- wanted value
            [9] => FR*S30*E37*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 33762
            [13] => Normale
            [14] => -
        )

    [2] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => 0
            [3] => Ecole Des Mines
            [4] => -
            [5] => ALES
            [6] => 4-
            [7] => -
            [8] => FR*S30*E38*2*1
            [9] => FR*S30*E38*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )
)

$key = array_search("FR*S30*E37*2*1", array_column($data, '8'));
var_dump($data[$key]);
</code>```

With this code I can't get the key of desired array. What am I doing wrong ?

答:
Try this function for recursive searching:</p>

```<code>function array_search_recursive($needle, array $haystack)
    {
        foreach ($haystack as $key => $value) {
            $current_key = $key;

            if ($needle === $value or (is_array($value) && array_search_recursive($needle, $value) !== false)) {
                return $current_key;
            }
        }
        return false;
    }

$key = array_search_recursive("FR*S30*E37*2*1", $data);
</code>```

Body:
I'm trying to search for a value in a multi dimensional array (below is only a part of the big array) and get the key for that value but I can't manage it by myself. Here is what I have tried :

Array
(
    [0] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => -
            [4] => -
            [5] => ALES
            [6] => 44-
            [7] => -
            [8] => FR*S30*E36*1*1
            [9] => FR*S30*E36*1*1
            [10] => US*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )

    [1] => Array  // <-- wanted key
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => Chemin Des Sports
            [4] => -
            [5] => ALES
            [6] => -
            [7] => -
            [8] => FR*S30*E37*2*1  // <-- wanted value
            [9] => FR*S30*E37*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 33762
            [13] => Normale
            [14] => -
        )

    [2] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => 0
            [3] => Ecole Des Mines
            [4] => -
            [5] => ALES
            [6] => 4-
            [7] => -
            [8] => FR*S30*E38*2*1
            [9] => FR*S30*E38*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )
)

$key = array_search("FR*S30*E37*2*1", array_column($data, '8'));
var_dump($data[$key]);

With this code I can't get the key of desired array. What am I doing wrong ?

Body:
Try this function for recursive searching:

function array_search_recursive($needle, array $haystack)
    {
        foreach ($haystack as $key => $value) {
            $current_key = $key;

            if ($needle === $value or (is_array($value) && array_search_recursive($needle, $value) !== false)) {
                return $current_key;
            }
        }
        return false;
    }

$key = array_search_recursive("FR*S30*E37*2*1", $data);


问:
Facebook Sharing in iOS
I implemented Facebook sharing in my app.

```<code>FBSDKShareLinkContent *content=[[FBSDKShareLinkContent alloc]init];
        [content setContentDescription:theDescription];
        [content setContentTitle:theTitle];
        //[content setContentURL:[NSURL URLWithString:itemURL]];
       // content.contentURL = [NSURL URLWithString:@"http://developers.facebook.com"];
       [content setImageURL:[NSURL URLWithString:imageURL]];
    [FBSDKShareDialog showFromViewController:self withContent:content delegate:self];
</code>```

But the "Sharing" dialog shows empty. Why does it not show/post the title & description which I set?

答:
For FBSDK 4.12.0 version:

Facebook link share work like this:

```<code> FBSDKShareLinkContent *content =[[FBSDKShareLinkContent alloc] init];
 content.contentURL = [NSURL URLWithString:songUrl];
 content.imageURL = [NSURL URLWithString:artWorkURL];
 content.contentTitle= [NSString stringWithFormat: @"%@", trackName];
 content.contentDescription=[NSString stringWithFormat:@"Some text"];
 [FBSDKShareDialog showFromViewController:self withContent:content delegate:self];
</code>```

Title: Facebook Sharing in iOS

Body:
I implemented Facebook sharing in my app.

FBSDKShareLinkContent *content=[[FBSDKShareLinkContent alloc]init];
        [content setContentDescription:theDescription];
        [content setContentTitle:theTitle];
        //[content setContentURL:[NSURL URLWithString:itemURL]];
       // content.contentURL = [NSURL URLWithString:@"http://developers.facebook.com"];
       [content setImageURL:[NSURL URLWithString:imageURL]];
    [FBSDKShareDialog showFromViewController:self withContent:content delegate:self];

But the "Sharing" dialog shows empty. Why does it not show/post the title & description which I set?

Body:
For FBSDK 4.12.0 version:

Facebook link share work like this:

 FBSDKShareLinkContent *content =[[FBSDKShareLinkContent alloc] init];
 content.contentURL = [NSURL URLWithString:songUrl];
 content.imageURL = [NSURL URLWithString:artWorkURL];
 content.contentTitle= [NSString stringWithFormat: @"%@", trackName];
 content.contentDescription=[NSString stringWithFormat:@"Some text"];
 [FBSDKShareDialog showFromViewController:self withContent:content delegate:self];


问:
Use text field in MATLAB GUI as timer
I have a simple GUI where I want to use a text field to display a constantly changing value generated in a loop. I just don't now how to get it working. From the help files and some forum thread I have the following:

First I create my text object:

```<code>hTimer  = uicontrol('Style','text','String','Time',...
           'Position',[450,300,60,15],...
           'Callback',@Timer_CreateFcn);
</code>```

I create some function:

```<code>function Timer_CreateFcn(hObject, eventdata, handles)
global statText
statText = hObject;
end
</code>```

and then I have have my loop where the values are generated:

```<code>while ...
            textString=['TestCycleTime = ',num2str(datestr(tsNum(idx-5)-tsNumDoor(1),'MM:SS.FFF')),' [Min:Sec]'];
            global statText;
            set(statText, 'String', textString);
end
</code>```

The script is running without errors, but still the timer is not updating.
Could someone please give me a hint?

答:
The issue is that you are updating the 'String' property of your text object within a while loop which prevents MATLAB from automatically taking the time to actually render the change. To alter this behavior, you can explicitly call drawnow after settings the 'String' property to explicitly render the current figure.

```<code>set(hTimer, 'String', textString);
drawnow
</code>```

As a side-note, I would recomment looking into the ways to pass data around your app rather than using global variables.

Title: Use text field in MATLAB GUI as timer

Body:
I have a simple GUI where I want to use a text field to display a constantly changing value generated in a loop. I just don't now how to get it working. From the help files and some forum thread I have the following:

First I create my text object:

hTimer  = uicontrol('Style','text','String','Time',...
           'Position',[450,300,60,15],...
           'Callback',@Timer_CreateFcn);

I create some function:

function Timer_CreateFcn(hObject, eventdata, handles)
global statText
statText = hObject;
end

and then I have have my loop where the values are generated:

while ...
            textString=['TestCycleTime = ',num2str(datestr(tsNum(idx-5)-tsNumDoor(1),'MM:SS.FFF')),' [Min:Sec]'];
            global statText;
            set(statText, 'String', textString);
end

The script is running without errors, but still the timer is not updating.
Could someone please give me a hint?

Body:
The issue is that you are updating the 'String' property of your text object within a while loop which prevents MATLAB from automatically taking the time to actually render the change. To alter this behavior, you can explicitly call drawnow after settings the 'String' property to explicitly render the current figure.

set(hTimer, 'String', textString);
drawnow

As a side-note, I would recomment looking into the ways to pass data around your app rather than using global variables.


问:
Kubernetes - How to know which minions are hosting Pods
I have a 6 minion cluster and would like to know how many of these minions are actually hosting pods at any given time. Is there a specific command for that ? Right now Im using a very generic command.

```<code>kubectl get po | grep Running > RUNNING.txt
for i in `cat RUNNING.txt `; do kubectl describe po $i; done | grep "Started container with docker
</code>```

"

Any direct command to fetch the info I want ?

答:
Just add -o wide:

```<code>kubectl get pod -o wide
</code>```

Body:
I have a 6 minion cluster and would like to know how many of these minions are actually hosting pods at any given time. Is there a specific command for that ? Right now Im using a very generic command.

kubectl get po | grep Running > RUNNING.txt
for i in `cat RUNNING.txt `; do kubectl describe po $i; done | grep "Started container with docker

"

Any direct command to fetch the info I want ?

Body:
Just add -o wide:

kubectl get pod -o wide


问:
Passing parameters to public void run() from the parent
I'm 50% hopeless :P. I tried (at the beginning) to update the GUI from the code of a Thread, and got NullException. After reading for a while, I understood that the Thread flooded the JavaFX application window and in order for me to update the GUI from a Thread, I need to use the following code:

```<code>Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });
</code>```

So I did use this code, and it indeed allow me to edit the GUI of my main class. However, my question is simple. => this code, which I'm running from a thread, is a code which sits inside a public void run()  (of the thread I run the code from). It looks something like this:

```<code>@Override
    public void run() {

    String tmpVar;

    ... (Some code)
    ... (Some code)
    ... (Some code)

        Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });

    ... (Some code)
    ... (Some code)
    ... (Some code)
}
</code>```

How can I pass parameters from the parent's public void run() into this one?.
For example, the String tmpString (I want to pass it on).

Do note that if I declare it outside the public void run() as a static (for example) => I run a lot of threads, so updating a static var might not always be accurate (cause lots of threads will update it simultaneity)

Thank you!.

答:
One option, as James_D posted, is using  final var inside inner class (anonymous or not)

Anoter options such as new MyRunnable(someString) or using Consumer<T> you could find here

Body:
I'm 50% hopeless :P. I tried (at the beginning) to update the GUI from the code of a Thread, and got NullException. After reading for a while, I understood that the Thread flooded the JavaFX application window and in order for me to update the GUI from a Thread, I need to use the following code:

Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });

So I did use this code, and it indeed allow me to edit the GUI of my main class. However, my question is simple. => this code, which I'm running from a thread, is a code which sits inside a public void run()  (of the thread I run the code from). It looks something like this:

@Override
    public void run() {

    String tmpVar;

    ... (Some code)
    ... (Some code)
    ... (Some code)

        Platform.runLater(new Runnable() {
            @Override public void run() {

            //Update UI here
            for (int i=0; i<2000;i++)
                {
                 MyMainClass.leftPaneTextArea.appendText("Goodi!\n");
                }

            }
        });

    ... (Some code)
    ... (Some code)
    ... (Some code)
}

How can I pass parameters from the parent's public void run() into this one?.
For example, the String tmpString (I want to pass it on).

Do note that if I declare it outside the public void run() as a static (for example) => I run a lot of threads, so updating a static var might not always be accurate (cause lots of threads will update it simultaneity)

Thank you!.


问:
For Loop to Count Letters in a Word
I'm just learning python and I came to a problem that required me to put a string as an input in my "count letters function."

The function is supposed to count how many "a"s are in a word given (specifically, a fruit inputed by the user).

The final value is correct, but in my function, it lists me the programs "procedure" if you will by listing how many "a"s are at each index and adding everything that was before.

I just want one final value, not a list.

If I'm not too clear, here is my program and test it out for yourself to see what I mean, and maybe help me come to a solution?

```<code>def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
        print count

a=raw_input("Name a fruit and I will tell you how many letters are in it." + '\n')
print count_letters(a)
</code>```

答:
You just put print function in for loop.
Tray this:

```<code>def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
        count+=1
    print count
</code>```

Indentation is important in python

Title: For Loop to Count Letters in a Word

Body:
I'm just learning python and I came to a problem that required me to put a string as an input in my "count letters function."

The function is supposed to count how many "a"s are in a word given (specifically, a fruit inputed by the user).

The final value is correct, but in my function, it lists me the programs "procedure" if you will by listing how many "a"s are at each index and adding everything that was before.

I just want one final value, not a list.

If I'm not too clear, here is my program and test it out for yourself to see what I mean, and maybe help me come to a solution?

def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
        print count

a=raw_input("Name a fruit and I will tell you how many letters are in it." + '\n')
print count_letters(a)

Body:
You just put print function in for loop.
Tray this:

def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
        count+=1
    print count

Indentation is important in python


问:
How do I put indexes and words together to make 1 final string/array? (Java)
Background to question

I have been working on developing code that is able to read a string, compress it an send it to a new file in a compressed form. (e.g. "hello, hello" -> "hello[0, 1]) and this works great at the moment. Here is the link for anyone who wants to use it: https://pastebin.com/v6YF34mU . The next stage is being able to re-create the file using the indexes and the words.

Question

I currently have got this code:

```<code>public static void main(String[] args) {
        // TODO code application logic here
        Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
            String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
            Matcher seaMatcher = seaPattern.matcher(compressedSea);
            while (seaMatcher.find()) {
                String seaWords = seaMatcher.group(1);
                String[] seaIndexes = seaMatcher.group(2).split(", ");
                for (String str : seaIndexes) {
                    int seaIndex = Integer.parseInt(str);
                    System.out.print(seaIndex);
                    }
</code>```

In short. I reads the string and splits it up into to different arrays. One of the arrays contains the indexes and the other contains the words. The next stage is putting these together and creating 1 string that is able to be compressed. I am relatively new to Java so I am not completely sure how I would go about doing this.

If anyone has got any ideas on how to do this it would be much appreciated!

答:
If I understood it correctly.

Create a new array with the highest index in index array.

```<code>String[] finalString = new Array[highestIndex];
</code>```

now loop through your words array

```<code>for(String str: wordsArray){
  //grab the index of each str
    //put your str in the new array at the same indexes
    finalString [index] = str;
  }
}
</code>```

Body:
Background to question

I have been working on developing code that is able to read a string, compress it an send it to a new file in a compressed form. (e.g. "hello, hello" -> "hello[0, 1]) and this works great at the moment. Here is the link for anyone who wants to use it: https://pastebin.com/v6YF34mU . The next stage is being able to re-create the file using the indexes and the words.

Question

I currently have got this code:

public static void main(String[] args) {
        // TODO code application logic here
        Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
            String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
            Matcher seaMatcher = seaPattern.matcher(compressedSea);
            while (seaMatcher.find()) {
                String seaWords = seaMatcher.group(1);
                String[] seaIndexes = seaMatcher.group(2).split(", ");
                for (String str : seaIndexes) {
                    int seaIndex = Integer.parseInt(str);
                    System.out.print(seaIndex);
                    }

In short. I reads the string and splits it up into to different arrays. One of the arrays contains the indexes and the other contains the words. The next stage is putting these together and creating 1 string that is able to be compressed. I am relatively new to Java so I am not completely sure how I would go about doing this.

If anyone has got any ideas on how to do this it would be much appreciated!

Body:
If I understood it correctly.

Create a new array with the highest index in index array.

String[] finalString = new Array[highestIndex];

now loop through your words array

for(String str: wordsArray){
  //grab the index of each str
    //put your str in the new array at the same indexes
    finalString [index] = str;
  }
}


问:
How to obtain graph feature values for multiple rna sequences at once?
I need to obtain graph feature values (like maybe around 20) for multiple rna sequences at once.

So if I input the file containing rna sequences the output file should contain these 20 features per line for each sequence. I have looked into GraPPLE but it gives feature values only for one at a time. Similar case for igraph.

I have a 500 sequence file for which I need to obtain these feature values and then further training it.

答:
You may want to have a look at recent articles citing GraPPLE:

https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2685108/citedby/

Specifically, RNAcon is also graph-based approach:

https://www.ncbi.nlm.nih.gov/pubmed/24521294

Lastly, this review may be of interest:

https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5153550/


问:
Javascript - Read value of a JSON property, if that key doesn't exist return null, in a single line
Let me give a python analogy of what I am looking for:

```<code>fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)
</code>```

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

```<code>var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);
</code>```

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

答:
You're looking for a ternary operator:

```<code>var fruits_obj = {"banana": 4, "apple": 3};

var num_apples = fruits_obj.hasOwnProperty("apple") ? fruits_obj["apple"] : null;
var num_oranges = fruits_obj.hasOwnProperty("orange") ? fruits_obj["orange"] : null;

console.log(num_apples, num_oranges);
</code>```

If you want to create a function like python get it could be something like the following:

```<code>var getProp = function(object, key, default){
    return object.hasOwnProperty(key) ? object[key] : default;
};

var num_oranges = getProp(fruits_obj, "orange", null);
</code>```

Body:
Let me give a python analogy of what I am looking for:

fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

Body:
You're looking for a ternary operator:

var fruits_obj = {"banana": 4, "apple": 3};

var num_apples = fruits_obj.hasOwnProperty("apple") ? fruits_obj["apple"] : null;
var num_oranges = fruits_obj.hasOwnProperty("orange") ? fruits_obj["orange"] : null;

console.log(num_apples, num_oranges);

If you want to create a function like python get it could be something like the following:

var getProp = function(object, key, default){
    return object.hasOwnProperty(key) ? object[key] : default;
};

var num_oranges = getProp(fruits_obj, "orange", null);