问:
how to get first key (0 or associative ) form array and output in new array
I Would Like To Get The First Element Of This Array And Put In New Same Array Output

One Requirement: It Cannot Be Done With Passing By reference Index eg 0

This Input Array

```<code>        [ 'id','ID','dt-text' ] ,
        [ 'name','Name','dt-text' ] ,
        [ 'artistList'=>['list','mm','defalut']  ,'Artist List','dt-select'] ,
        [ 'nationality'=>['nationality','mm','defalut']  ,'Nationality','dt-select'] ,
        [ 'view','View',''],
        [ 'status','Status' ,'']

array:6 [▼
  0 => array:3 [▼
        0 => "id"
        1 => "ID"
        2 => "dt-text"
  ]
  1 => array:3 [▼
        0 => "name"
        1 => "Name"
        2 => "dt-text"
  ]
  2 => array:3 [▼
        "artistList" => array:3 [▼
              0 => "list"
              1 => "mm"
              2 => "defalut"
        ]
        0 => "Artist List"
        1 => "dt-select"
  ]
  3 => array:3 [▼
        "nationality" => array:3 [▼
              0 => "nationality"
              1 => "mm"
              2 => "defalut"
        ]
        0 => "Nationality"
        1 => "dt-select"
  ]
  4 => array:3 [▼
        0 => "view"
        1 => "View"
        2 => ""
  ]
  5 => array:3 [▼
        0 => "status"
        1 => "Status"
        2 => ""
  ]
]
</code>```

The New Array  I Needed

This IS OutPUT Array

```<code>['id','name','artistList'=>['list','mm','defalut'] ,'nationality'=>['nationality','mm','defalut'] ,'view','status']
array:6 [▼
    0 => "id"
    1 => "name"
    "artistList" => array:3 [▼
                0 => "list"
                1 => "mm"
                2 => "defalut"
                ]
    "nationality" => array:3 [▼
                0 => "nationality"
                1 => "mm"
                2 => "defalut"
                ]
    2 => "view"
    3 => "status"
]
</code>```

Note
I Can Controll in Input Array Same , I Try with foreach in php  And Tray In Laravel  Helper Function head Put I get S

```<code>array:6 [▼
  0 => "id"
  1 => "name"
  2 => array:1 [▼
    "artistList" => array:3 [▼
      0 => "list"
      1 => "mm"
      2 => "defalut"
    ]
  ]
  3 => array:1 [▼
    "nationality" => array:3 [▼
      0 => "nationality"
      1 => "mm"
      2 => "defalut"
    ]
  ]
  4 => "view"
  5 => "status"
]
</code>```

Put I Cant Get Resslut So , How Can I Do this?

答:
Since you are changing the keys (structure) of the array, there is no way to do that without either generating a new array or passing the array by reference. One way to do it by generating a new array is with array_reduce:

```<code>$array = [
        [ 'id','ID','dt-text' ] ,
        [ 'name','Name','dt-text' ] ,
        [ 'artistList'=>['list','mm','defalut']  ,'Artist List','dt-select'] ,
        [ 'nationality'=>['nationality','mm','defalut']  ,'Nationality','dt-select'] ,
        [ 'view','View',''],
        [ 'status','Status' ,'']
    ];
$array = array_reduce($array, function ($c, $v) {
    $first_key = array_keys($v)[0];
    return array_merge($c, array($first_key => $v[$first_key])); }, []);
print_r($array);
</code>```

Output:

```<code>Array (
  [0] => id
  [1] => name
  [artistList] => Array (
    [0] => list
    [1] => mm
    [2] => defalut
  )
  [nationality] => Array (
    [0] => nationality
    [1] => mm
    [2] => defalut
  )
  [2] => view
  [3] => status
)
</code>```

Demo on 3v4l.org

Body:
I Would Like To Get The First Element Of This Array And Put In New Same Array Output

One Requirement: It Cannot Be Done With Passing By reference Index eg 0

This Input Array

        [ 'id','ID','dt-text' ] ,
        [ 'name','Name','dt-text' ] ,
        [ 'artistList'=>['list','mm','defalut']  ,'Artist List','dt-select'] ,
        [ 'nationality'=>['nationality','mm','defalut']  ,'Nationality','dt-select'] ,
        [ 'view','View',''],
        [ 'status','Status' ,'']

array:6 [▼
  0 => array:3 [▼
        0 => "id"
        1 => "ID"
        2 => "dt-text"
  ]
  1 => array:3 [▼
        0 => "name"
        1 => "Name"
        2 => "dt-text"
  ]
  2 => array:3 [▼
        "artistList" => array:3 [▼
              0 => "list"
              1 => "mm"
              2 => "defalut"
        ]
        0 => "Artist List"
        1 => "dt-select"
  ]
  3 => array:3 [▼
        "nationality" => array:3 [▼
              0 => "nationality"
              1 => "mm"
              2 => "defalut"
        ]
        0 => "Nationality"
        1 => "dt-select"
  ]
  4 => array:3 [▼
        0 => "view"
        1 => "View"
        2 => ""
  ]
  5 => array:3 [▼
        0 => "status"
        1 => "Status"
        2 => ""
  ]
]

The New Array  I Needed

This IS OutPUT Array

['id','name','artistList'=>['list','mm','defalut'] ,'nationality'=>['nationality','mm','defalut'] ,'view','status']
array:6 [▼
    0 => "id"
    1 => "name"
    "artistList" => array:3 [▼
                0 => "list"
                1 => "mm"
                2 => "defalut"
                ]
    "nationality" => array:3 [▼
                0 => "nationality"
                1 => "mm"
                2 => "defalut"
                ]
    2 => "view"
    3 => "status"
]

Note
I Can Controll in Input Array Same , I Try with foreach in php  And Tray In Laravel  Helper Function head Put I get S

array:6 [▼
  0 => "id"
  1 => "name"
  2 => array:1 [▼
    "artistList" => array:3 [▼
      0 => "list"
      1 => "mm"
      2 => "defalut"
    ]
  ]
  3 => array:1 [▼
    "nationality" => array:3 [▼
      0 => "nationality"
      1 => "mm"
      2 => "defalut"
    ]
  ]
  4 => "view"
  5 => "status"
]

Put I Cant Get Resslut So , How Can I Do this?

Body:
Since you are changing the keys (structure) of the array, there is no way to do that without either generating a new array or passing the array by reference. One way to do it by generating a new array is with array_reduce:

$array = [
        [ 'id','ID','dt-text' ] ,
        [ 'name','Name','dt-text' ] ,
        [ 'artistList'=>['list','mm','defalut']  ,'Artist List','dt-select'] ,
        [ 'nationality'=>['nationality','mm','defalut']  ,'Nationality','dt-select'] ,
        [ 'view','View',''],
        [ 'status','Status' ,'']
    ];
$array = array_reduce($array, function ($c, $v) {
    $first_key = array_keys($v)[0];
    return array_merge($c, array($first_key => $v[$first_key])); }, []);
print_r($array);

Output:

Array (
  [0] => id
  [1] => name
  [artistList] => Array (
    [0] => list
    [1] => mm
    [2] => defalut
  )
  [nationality] => Array (
    [0] => nationality
    [1] => mm
    [2] => defalut
  )
  [2] => view
  [3] => status
)

Demo on 3v4l.org


来源: stackexchange

问:
C# logic question
I have those boolean values:

```<code>bool test = false && true || true; // true
bool test1 = false && (true || true); // false
</code>```

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)

答:
The && operator has precedence over || meaning that your first expression is equivalent to:

```<code>bool test = (false && true) || true;
</code>```

which gives:

```<code>bool test = false || true;
</code>```

which gives:

```<code>bool test = true;
</code>```

In the second case you are explicitly grouping the operands:

```<code>bool test1 = false && (true || true);
</code>```

which gives:

```<code>bool test1 = false && true;
</code>```

which gives:

```<code>bool test1 = false;
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# logic question

Body:
I have those boolean values:

bool test = false && true || true; // true
bool test1 = false && (true || true); // false

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)

Body:
The && operator has precedence over || meaning that your first expression is equivalent to:

bool test = (false && true) || true;

which gives:

bool test = false || true;

which gives:

bool test = true;

In the second case you are explicitly grouping the operands:

bool test1 = false && (true || true);

which gives:

bool test1 = false && true;

which gives:

bool test1 = false;


问:
Can I create a NuGet package (or other package) with legacy dll's that are not on a .NET Framework?
We have a bunch of legacy dll's (basically could be anything, some are old fortran, some .NET) and we want to move them to Azure Artifacts.  Can I create NuGet packages from these legacy dll's that are not based on .NET (like the Fortran ones) by themselves.

I've already tried creating the NuGet packages, but I get warnings on my dependencies because it looks like they are trying to load the packages on a .NET framework.  Is the only real workaround here to build a .NET say class library or something, then reference the dll through that, and create a NuGet package with that library and just add the legacy dll's as references?

答:
Can I create a NuGet package (or other package) with legacy dll's that are not on a .NET Framework?

The answer is yes.

You could target those legacy dlls to the tools folder instead of the lib folder. like:

```<code><files>
    <file src="legacy\*.dll" target="Tools" />
    <!-- Other files -->
</files>
</code>```

Then pack this .nuspec file when you build the pipeline, those legacy dlls are located in the tools folder, which will not add as references.

Check the From a convention-based working directory for some details.

Hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
Can I create a NuGet package (or other package) with legacy dll's that are not on a .NET Framework?

The answer is yes.

You could target those legacy dlls to the tools folder instead of the lib folder. like:

<files>
    <file src="legacy\*.dll" target="Tools" />
    <!-- Other files -->
</files>

Then pack this .nuspec file when you build the pipeline, those legacy dlls are located in the tools folder, which will not add as references.

Check the From a convention-based working directory for some details.

Hope this helps.


问:
how to filter out boolean fields in spark dataframe?
I have three columns in my data frame. In this second and third are boolean fields. I want to filter out the values which are true. i have tried this one nn.filter(col("col3")===true).show but it says invalid column name "true". what worng with my code? Does any help please?

my codes:

```<code>scala> nn.printSchema
root
 |-- ID: integer (nullable = true)
 |-- col2: boolean (nullable = true)
 |-- col3: boolean (nullable = true)

scala> nn.show
+---+-----+-----+
| ID| col2| col3|
+---+-----+-----+
|  4| true|false|
|  5|false|false|
|  6|false|false|
|  7|false|false|
| 12|false|false|
| 13|false|false|
| 14|false|false|
| 15|false| true|
| 16|false|false|
| 17|false|false|
| 18|false|false|
| 22|false|false|
| 36|false|false|
| 37|false|false|
| 38|false|false|
| 39|false|false|
| 40|false|false|
| 41| true|false|
| 42|false|false|
+---+-----+-----+

scala> nn.filter(col("col3")===true).show
[Stage 14:>                                                         (0 + 1) / 1]19/05/26 22:44:16 ERROR executor.Executor: Exception in task 0.0 in stage 14.0 (TID 14)
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'true'.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
        at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:297)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:301)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
        at org.apache.spark.scheduler.Task.run(Task.scala:109)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:345)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
</code>```

答:
=== is re-defined is Column.scala(reference to Spark code)

The overriden method gets invoked in your case.

To avoid this,

1. Add a space after the column object like nn.filter(col("col3") === true)(space after col("col3")) or

2. Use the method suggested by @Learner like nn.filter(col("col3"))

Body:
I have three columns in my data frame. In this second and third are boolean fields. I want to filter out the values which are true. i have tried this one nn.filter(col("col3")===true).show but it says invalid column name "true". what worng with my code? Does any help please?

my codes:

scala> nn.printSchema
root
 |-- ID: integer (nullable = true)
 |-- col2: boolean (nullable = true)
 |-- col3: boolean (nullable = true)

scala> nn.show
+---+-----+-----+
| ID| col2| col3|
+---+-----+-----+
|  4| true|false|
|  5|false|false|
|  6|false|false|
|  7|false|false|
| 12|false|false|
| 13|false|false|
| 14|false|false|
| 15|false| true|
| 16|false|false|
| 17|false|false|
| 18|false|false|
| 22|false|false|
| 36|false|false|
| 37|false|false|
| 38|false|false|
| 39|false|false|
| 40|false|false|
| 41| true|false|
| 42|false|false|
+---+-----+-----+

scala> nn.filter(col("col3")===true).show
[Stage 14:>                                                         (0 + 1) / 1]19/05/26 22:44:16 ERROR executor.Executor: Exception in task 0.0 in stage 14.0 (TID 14)
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'true'.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
        at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:297)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:301)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
        at org.apache.spark.scheduler.Task.run(Task.scala:109)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:345)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)


问:
Browser doesn't set cookie even if it is present in response headers
My response  has a set-cookie header present but the browser doesn't seem to store it (in postman it works like a charm). My API is written in .NET Core, and im using axios (React) on the client. The client requests are, however, proxied through an express server for SSR purposes.

I have tried multiple solutions posted here. From the basics of setting withCredentials to true in axios to setting the MinimumSameSitePolicy on the server to none which can be seen in the code.

Server

```<code>services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.ConsentCookie.HttpOnly = false;
            });
..........
 app.UseCookiePolicy(new CookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.None,
                HttpOnly = HttpOnlyPolicy.None
            });
</code>```

Client

```<code>const axiosInstance = axios.create({
  baseURL: '/api',
  withCredentials: true,
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:3000/',
    'Content-Type': 'application/json'
  }
});
</code>```

Proxy

```<code>app.use(
  '/api',
  proxy('https://localhost:44364/', {
    proxyReqOptDecorator(opts) {
      opts.rejectUnauthorized = false;
      opts.headers['x-forwarded-host'] = 'localhost:3000';
      return opts;
    },
    proxyReqPathResolver(req) {
      return `/api${req.url}`;
    }
  })
);
</code>```

The response with cookie:

```<code>HTTP/1.1 200 OK
x-powered-by: ASP.NET
cache-control: no-cache
pragma: no-cache
content-type: text/plain; charset=utf-8
expires: Thu, 01 Jan 1970 00:00:00 GMT
server: Kestrel
set-cookie: .AspNetCore.Cookies=CfDJ8KvV0sFM8_FJqzJkoUey_LvYSADPHUA20Mq40db0KYSbL9Q2ZjS2JW87G8CzcTDBIpG1H6mZ_nuThzOniga7oRpguIgi3xIFCjkY5D0DXwT98ZVejY7nzLaCmV9rGLMkkqqADbr0zzwUkzXQqtWMtubY0cdHXPskTWFucMjjYk0BU4eCuWOjRzooL-QtwYtDClP720LVetm8lZGvAS6jfYpk-HWZIQiDo1ERKqhyIWKYqSFBEN0nV4ykL6KhfqEjcK8URzTEnBxdV7dCpk287smjAzTvOziRWfO6BtpxXC2tZ9NBeTLLqitn_CaAypewt9qMnjMi75zazo6yicRlTsDp-i3LT0OkD_ls1celSeG1VPlTg0OMVm0nADpZurMT9LSrijsSrcFT0wvNSTeW9vE; path=/; secure; samesite=lax; httponly
x-sourcefiles: =?UTF-8?B?QzpcVXNlcnNcTWFrYWxhXERlc2t0b3BcUm91dG9yaWFsXFJvdXRvcmlhbEFQSVxSb3V0b3JpYWxBUElcUm91dG9yaWFsQVBJXGFwaVxhY2NvdW50XGxvZ2luU3VibWl0?=
date: Sun, 26 May 2019 15:47:32 GMT
connection: close
Content-Length: 6
ETag: W/"6-+3OfqLi6+pGCkKvbVPPQANDiBD4"
</code>```

答:
In version 2.0, asp.net core introduced a new behavior: by default it adds a samesite=lax attribute to all set-cookie headers.

The Cookie Policy Middleware setting for MinimumSameSitePolicy can affect your setting of Cookie.SameSite in CookieAuthenticationOptions

Try to explicitly override this default behavior in Startup.ConfigureServices:

```<code>services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options => options.Cookie.SameSite = SameSiteMode.None;
            });
</code>```

Refer to:
AspNet Core Identity, how set options.Cookie.SameSite?

Body:
My response  has a set-cookie header present but the browser doesn't seem to store it (in postman it works like a charm). My API is written in .NET Core, and im using axios (React) on the client. The client requests are, however, proxied through an express server for SSR purposes.

I have tried multiple solutions posted here. From the basics of setting withCredentials to true in axios to setting the MinimumSameSitePolicy on the server to none which can be seen in the code.

Server

services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.ConsentCookie.HttpOnly = false;
            });
..........
 app.UseCookiePolicy(new CookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.None,
                HttpOnly = HttpOnlyPolicy.None
            });

Client

const axiosInstance = axios.create({
  baseURL: '/api',
  withCredentials: true,
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:3000/',
    'Content-Type': 'application/json'
  }
});

Proxy

app.use(
  '/api',
  proxy('https://localhost:44364/', {
    proxyReqOptDecorator(opts) {
      opts.rejectUnauthorized = false;
      opts.headers['x-forwarded-host'] = 'localhost:3000';
      return opts;
    },
    proxyReqPathResolver(req) {
      return `/api${req.url}`;
    }
  })
);

The response with cookie:

HTTP/1.1 200 OK
x-powered-by: ASP.NET
cache-control: no-cache
pragma: no-cache
content-type: text/plain; charset=utf-8
expires: Thu, 01 Jan 1970 00:00:00 GMT
server: Kestrel
set-cookie: .AspNetCore.Cookies=CfDJ8KvV0sFM8_FJqzJkoUey_LvYSADPHUA20Mq40db0KYSbL9Q2ZjS2JW87G8CzcTDBIpG1H6mZ_nuThzOniga7oRpguIgi3xIFCjkY5D0DXwT98ZVejY7nzLaCmV9rGLMkkqqADbr0zzwUkzXQqtWMtubY0cdHXPskTWFucMjjYk0BU4eCuWOjRzooL-QtwYtDClP720LVetm8lZGvAS6jfYpk-HWZIQiDo1ERKqhyIWKYqSFBEN0nV4ykL6KhfqEjcK8URzTEnBxdV7dCpk287smjAzTvOziRWfO6BtpxXC2tZ9NBeTLLqitn_CaAypewt9qMnjMi75zazo6yicRlTsDp-i3LT0OkD_ls1celSeG1VPlTg0OMVm0nADpZurMT9LSrijsSrcFT0wvNSTeW9vE; path=/; secure; samesite=lax; httponly
x-sourcefiles: =?UTF-8?B?QzpcVXNlcnNcTWFrYWxhXERlc2t0b3BcUm91dG9yaWFsXFJvdXRvcmlhbEFQSVxSb3V0b3JpYWxBUElcUm91dG9yaWFsQVBJXGFwaVxhY2NvdW50XGxvZ2luU3VibWl0?=
date: Sun, 26 May 2019 15:47:32 GMT
connection: close
Content-Length: 6
ETag: W/"6-+3OfqLi6+pGCkKvbVPPQANDiBD4"

Body:
In version 2.0, asp.net core introduced a new behavior: by default it adds a samesite=lax attribute to all set-cookie headers.

The Cookie Policy Middleware setting for MinimumSameSitePolicy can affect your setting of Cookie.SameSite in CookieAuthenticationOptions

Try to explicitly override this default behavior in Startup.ConfigureServices:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options => options.Cookie.SameSite = SameSiteMode.None;
            });

Refer to:
AspNet Core Identity, how set options.Cookie.SameSite?


问:
How to combine path with WebRootPath
I need to upload some files to server using my app and I need to deliver a full path of the folder where I want to save files.
I am using Path.Combine method with webHostEnvironment.WebRootPath additional folders path from appsettings.json and file name.
The code looks like this:

```<code>var pathString = configuration.GetValue<string>("UploadPaths:Pictures");
var path = Path.Combine(webHostEnvironment.WebRootPath, pathString, picture.Name);
</code>```

And the problem is that the webHostEnvironment.WebRootPath is just ommited in the path variable (path looks like pathString + picture.Name).

Any idea how to get proper path?

答:
In ASP.NET Core, the physical paths to both the web root and the content root directories can be retrieved by injecting and querying the IHostingEnvironment service:

```<code> public class HomeController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public HomeController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    public ActionResult Post(Picture picture)
    {
        var pathString = configuration.GetValue<string>("UploadPaths:Pictures");
        var path = Path.Combine(_hostingEnvironment.WebRootPath, pathString, picture.Name);
        return Content(path);
    }
}
</code>```

You could take a look at Getting the Web Root Path and the Content Root Path in ASP.NET Core.

Title: How to combine path with WebRootPath

Body:
I need to upload some files to server using my app and I need to deliver a full path of the folder where I want to save files.
I am using Path.Combine method with webHostEnvironment.WebRootPath additional folders path from appsettings.json and file name.
The code looks like this:

var pathString = configuration.GetValue<string>("UploadPaths:Pictures");
var path = Path.Combine(webHostEnvironment.WebRootPath, pathString, picture.Name);

And the problem is that the webHostEnvironment.WebRootPath is just ommited in the path variable (path looks like pathString + picture.Name).

Any idea how to get proper path?

Body:
In ASP.NET Core, the physical paths to both the web root and the content root directories can be retrieved by injecting and querying the IHostingEnvironment service:

 public class HomeController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public HomeController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    public ActionResult Post(Picture picture)
    {
        var pathString = configuration.GetValue<string>("UploadPaths:Pictures");
        var path = Path.Combine(_hostingEnvironment.WebRootPath, pathString, picture.Name);
        return Content(path);
    }
}

You could take a look at Getting the Web Root Path and the Content Root Path in ASP.NET Core.


问:
PHP if previous page was certain page on my site then show alert box with message
How could I use PHP or Javascript to check if a user's previous page was a certain page on my site and then if so, show an alert box?</p>

答:
This could be circumvented if a person really wanted to.</p>

```<code>//on the page for the alert
session_start();
if($_SESSION['lastPage']=='??'){
echo 'alert';
}

//on the page you want to detect if the user came from
session_start();
$_SESSION['lastPage']=$_SERVER['REQUEST_URI'];
</code>```

Body:
This could be circumvented if a person really wanted to.

//on the page for the alert
session_start();
if($_SESSION['lastPage']=='??'){
echo 'alert';
}

//on the page you want to detect if the user came from
session_start();
$_SESSION['lastPage']=$_SERVER['REQUEST_URI'];


问:
python / django, where is the root of the namespace?
coming from php, the namespaces are always well defined in php, typically using psr-4 from composer

https://getcomposer.org/doc/04-schema.md#psr-4

e.g. you have a folder

src/Foo/Bar/Baz

you then define in the composer.json file that
src/Foo is where the namespace Foo starts

thereafter, all subfolders are by convention, a new sub namespace e.g.

src/Foo/Bar/Baz/MyClass.php turns into

Foo.Bar.Baz.MyClass

Say I want to drop a utility python class into my django project, that I want to use in all django "apps"

Where would I drop it, and how to properly define the namespace? what is the transparent way to understand namespaces in python?

答:
From this document:

https://docs.djangoproject.com/en/2.2/ref/applications/#projects-and-applications

Is this snippet:

A project’s root directory (the one that contains manage.py) is usually the container for all of a project’s applications which aren’t installed separately.

You can create whatever hierarchy you chose under that directory for utilities, which can conform to python's package system:

https://docs.python.org/3/tutorial/modules.html#packages


问:
How do I upgrade from PHP 7.0 to 7.3 on google cloud platform?
I am running the Wordpress multisite click to deploy on the compute engine.

```<code>Operating system
    Debian 9.8
Package contents
        Apache 2.4.25
        Google-Fluentd 1.6.9
        MySQL-Client 5.7.26
        MySQL-Server 5.7.26
        PHP 7.0.33
            Stackdriver-Agent 5.5.2
            WP-CLI 2.2.0
            WordPress 5.1.1
            phpMyAdmin 4.6.6
</code>```

I would like to upgrade PHP to 7.3

答:
You can use a third-party repository to install php7.3</p>

```<code>apt-get install ca-certificates apt-transport-https
wget -q https://packages.sury.org/php/apt.gpg -O- | sudo apt-key add -
echo "deb https://packages.sury.org/php/ stretch main" | sudo tee /etc/apt/sources.list.d/php.list
apt-get update
apt-get install php7.3
</code>```

Body:
I am running the Wordpress multisite click to deploy on the compute engine.

Operating system
    Debian 9.8
Package contents
        Apache 2.4.25
        Google-Fluentd 1.6.9
        MySQL-Client 5.7.26
        MySQL-Server 5.7.26
        PHP 7.0.33
            Stackdriver-Agent 5.5.2
            WP-CLI 2.2.0
            WordPress 5.1.1
            phpMyAdmin 4.6.6

I would like to upgrade PHP to 7.3

Body:
You can use a third-party repository to install php7.3

apt-get install ca-certificates apt-transport-https
wget -q https://packages.sury.org/php/apt.gpg -O- | sudo apt-key add -
echo "deb https://packages.sury.org/php/ stretch main" | sudo tee /etc/apt/sources.list.d/php.list
apt-get update
apt-get install php7.3


问:
Data Vault in Redshift and ETL Strategy
I have a bunch of data in files stored in Amazon S3 and am planning to use it to build a Data Vault in Redshift. My first question is if the right approach is to build the DV and Data Marts all in Redshift or if I should consider the S3 as my Data Lake and have only the Data Marts in Redshift?

In my architecture I'm currently considering the former (i.e. S3 Data Lake + Redshift Vault and Marts). However, I don't know if I can create ETL processes directly in Redshift to populate the Marts with data in the Vault or if I'll have to for example use Amazon EMR to process the raw data in S3, generate new files there and finally load them in the Marts.

So, my second question is: What should the ETL strategy be? Thanks.

答:
I strongly recommend you check out Matillion for Redshift: https://redshiftsupport.matillion.com/customer/en/portal/articles/2775397-building-a-data-vault

It's fantastic and affordable for Redshift ETL and has a Data Vault sample project.

Title: Data Vault in Redshift and ETL Strategy


问:
nodejs application on web server causing fork bomb - bash: fork: retry: No child processes
I'm hosting a website on a web host using a nodejs application (expressjs, request, etc.). The web host has an apache terminal from where I can call node app.js & or forever start app.js and the app runs fine.
However, once the terminal is closed, the number of  processes being used balloons to about 30, meaning that the next time I open the terminal, instead of being greeted with [hostname@server ~] $ I instead get:

```<code>bash: fork: retry: No child processes
bash: fork: retry: No child processes
bash: fork: retry: No child processes
bash: fork: retry: No child processes
bash: fork: Resource temporarily unavailable
bash-4.2$
</code>```

Somehow I believe a fork bomb is being created, and I can't seem to figure out where or why? I'm not using fork() anywhere, and if I use forever to start my app, the logs show no signs of errors or new processes being created.

When this happens, I can't use any terminal commands half the time, until I manage to pkill/pgrep.

I tried calling bash-4.2$ top, and got this:

```<code>top - 13:41:13 up 71 days, 20:57, 0 users, load average: 1.82, 1.81, 1.72
Tasks: 14 total, 1 running, 2 sleeping, 11 stopped, 0 zombie
%Cpu(s): 11.7 us, 2.7 sy, 0.1 ni, 85.5 id, 0.1 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 41034544 total, 2903992 free, 6525792 used, 31604760 buff/cache
KiB Swap: 0 total, 0 free, 0 used. 28583704 avail Mem

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1001511 xxxxxxxx 20 0 11880 3692 1384 S 0.0 0.0 0:00.02 bash
1001578 xxxxxxxx 20 0 11880 2840 524 T 0.0 0.0 0:00.00 bash
1001598 xxxxxxxx 20 0 11880 2672 348 T 0.0 0.0 0:00.00 bash
1001599 xxxxxxxx 20 0 11880 2896 524 T 0.0 0.0 0:00.00 bash
1001600 xxxxxxxx 20 0 11880 2720 396 T 0.0 0.0 0:00.00 bash
1001607 xxxxxxxx 20 0 11880 2928 532 T 0.0 0.0 0:00.00 bash
1001613 xxxxxxxx 20 0 11880 2964 532 T 0.0 0.0 0:00.00 bash
1001618 xxxxxxxx 20 0 11880 2780 348 T 0.0 0.0 0:00.00 bash
1001619 xxxxxxxx 20 0 12012 3024 544 T 0.0 0.0 0:00.00 bash
1001620 xxxxxxxx 20 0 11880 2804 372 T 0.0 0.0 0:00.00 bash
1001651 xxxxxxxx 20 0 12012 2836 352 T 0.0 0.0 0:00.00 bash
1001653 xxxxxxxx 20 0 12016 3392 896 T 0.0 0.0 0:00.00 bash
1004463 xxxxxxxx 20 0 9904 1840 1444 S 0.0 0.0 0:00.00 bash
1005200 xxxxxxxx 20 0 56364 1928 1412 R 0.0 0.0 0:00.00 top
</code>```

Which looks like somehow bash processes are being repeatedly made?

My actual nodejs app.js is a typical expressjs web app, with code such as (shortened example code):

```<code>var app = express();

app.use(express.static('..//'))
   .use(cors())
   .use(cookieParser());
</code>```

...

```<code>app.post('/profile', function(req,res){
    "use strict";
    var id = req.query.id;
    con.query("SELECT * FROM xxxxxxx WHERE xxxxx=" + id, function(err,result){
        res.send(result);
    });
});
</code>```

...

```<code>app.get('*', function(req, res) {
    "use strict";
    res.redirect('/404.html');
});

console.log('Listening on 8080');
app.listen(8080);
</code>```

Any ideas on why this issue is occurring? I'm relatively new to node so any help is appreciated, and apologies if any noob mistakes have been made.

答:
So it seems that the problem is actually stemming from my ~/.bashrc file which contains these lines:

```<code># User specific aliases and functions

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
</code>```

If these lines are commented out, then the problem ceases to occur. However I obviously can't use node commands because nvm isn't started.

Somehow that code is looping creating multiple bash instances whenever the terminal is accessed.

Body:
I'm hosting a website on a web host using a nodejs application (expressjs, request, etc.). The web host has an apache terminal from where I can call node app.js & or forever start app.js and the app runs fine.
However, once the terminal is closed, the number of  processes being used balloons to about 30, meaning that the next time I open the terminal, instead of being greeted with [hostname@server ~] $ I instead get:

bash: fork: retry: No child processes
bash: fork: retry: No child processes
bash: fork: retry: No child processes
bash: fork: retry: No child processes
bash: fork: Resource temporarily unavailable
bash-4.2$

Somehow I believe a fork bomb is being created, and I can't seem to figure out where or why? I'm not using fork() anywhere, and if I use forever to start my app, the logs show no signs of errors or new processes being created.

When this happens, I can't use any terminal commands half the time, until I manage to pkill/pgrep.

I tried calling bash-4.2$ top, and got this:

top - 13:41:13 up 71 days, 20:57, 0 users, load average: 1.82, 1.81, 1.72
Tasks: 14 total, 1 running, 2 sleeping, 11 stopped, 0 zombie
%Cpu(s): 11.7 us, 2.7 sy, 0.1 ni, 85.5 id, 0.1 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 41034544 total, 2903992 free, 6525792 used, 31604760 buff/cache
KiB Swap: 0 total, 0 free, 0 used. 28583704 avail Mem

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1001511 xxxxxxxx 20 0 11880 3692 1384 S 0.0 0.0 0:00.02 bash
1001578 xxxxxxxx 20 0 11880 2840 524 T 0.0 0.0 0:00.00 bash
1001598 xxxxxxxx 20 0 11880 2672 348 T 0.0 0.0 0:00.00 bash
1001599 xxxxxxxx 20 0 11880 2896 524 T 0.0 0.0 0:00.00 bash
1001600 xxxxxxxx 20 0 11880 2720 396 T 0.0 0.0 0:00.00 bash
1001607 xxxxxxxx 20 0 11880 2928 532 T 0.0 0.0 0:00.00 bash
1001613 xxxxxxxx 20 0 11880 2964 532 T 0.0 0.0 0:00.00 bash
1001618 xxxxxxxx 20 0 11880 2780 348 T 0.0 0.0 0:00.00 bash
1001619 xxxxxxxx 20 0 12012 3024 544 T 0.0 0.0 0:00.00 bash
1001620 xxxxxxxx 20 0 11880 2804 372 T 0.0 0.0 0:00.00 bash
1001651 xxxxxxxx 20 0 12012 2836 352 T 0.0 0.0 0:00.00 bash
1001653 xxxxxxxx 20 0 12016 3392 896 T 0.0 0.0 0:00.00 bash
1004463 xxxxxxxx 20 0 9904 1840 1444 S 0.0 0.0 0:00.00 bash
1005200 xxxxxxxx 20 0 56364 1928 1412 R 0.0 0.0 0:00.00 top

Which looks like somehow bash processes are being repeatedly made?

My actual nodejs app.js is a typical expressjs web app, with code such as (shortened example code):

var app = express();

app.use(express.static('..//'))
   .use(cors())
   .use(cookieParser());

...

app.post('/profile', function(req,res){
    "use strict";
    var id = req.query.id;
    con.query("SELECT * FROM xxxxxxx WHERE xxxxx=" + id, function(err,result){
        res.send(result);
    });
});

...

app.get('*', function(req, res) {
    "use strict";
    res.redirect('/404.html');
});

console.log('Listening on 8080');
app.listen(8080);

Any ideas on why this issue is occurring? I'm relatively new to node so any help is appreciated, and apologies if any noob mistakes have been made.

Body:
So it seems that the problem is actually stemming from my ~/.bashrc file which contains these lines:

# User specific aliases and functions

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

If these lines are commented out, then the problem ceases to occur. However I obviously can't use node commands because nvm isn't started.

Somehow that code is looping creating multiple bash instances whenever the terminal is accessed.


问:
PHP, loop through dynamic array by count
So I am working on a JQuery Step Form. It is being populated with dynamic information from the database. I have a particular list of items that is 21 items in the array. I would like to break these down into groups of 5 or 6 per step, so the form isn't so long.

I know I could use array_slice for example, but since this list is dynamic, I don't know how many there will always be. It will kind of be paginated in a sense but I don't need pagination links and such. Just a way to return 5 items, then 5 items and if the last iteration only has 2 items then that is it.

So for example:

```<code>$array = (
  array(
    "name" => "Peter Parker",
    "alterego" => "Spiderman",
  ),
  array(
    "name" => "Clark Kent",
    "alterego" => "Superman",
  ),
  array(
    "name" => "Bruce Wayne",
    "alterego" => "Batman",
  ),
);
</code>```

And then I want to break this down to only list 2 items per group.

答:
Andreas' initial advice is great. Maybe here, we might want to design some callback functions based on the pagination sizes that we wish to have:

```<code>array_slice($array, getChunkStart($array), getChunkLength($array));
</code>```

or if we just look for a specific column size:

```<code>array_chunk($array, sizeof(array_column($array, "column_key")));
</code>```

Body:
So I am working on a JQuery Step Form. It is being populated with dynamic information from the database. I have a particular list of items that is 21 items in the array. I would like to break these down into groups of 5 or 6 per step, so the form isn't so long.

I know I could use array_slice for example, but since this list is dynamic, I don't know how many there will always be. It will kind of be paginated in a sense but I don't need pagination links and such. Just a way to return 5 items, then 5 items and if the last iteration only has 2 items then that is it.

So for example:

$array = (
  array(
    "name" => "Peter Parker",
    "alterego" => "Spiderman",
  ),
  array(
    "name" => "Clark Kent",
    "alterego" => "Superman",
  ),
  array(
    "name" => "Bruce Wayne",
    "alterego" => "Batman",
  ),
);

And then I want to break this down to only list 2 items per group.

Body:
Andreas' initial advice is great. Maybe here, we might want to design some callback functions based on the pagination sizes that we wish to have:

array_slice($array, getChunkStart($array), getChunkLength($array));

or if we just look for a specific column size:

array_chunk($array, sizeof(array_column($array, "column_key")));


问:
Keras Multi-layer Neural Network Accuracy
I've built a simplistic multi-layer NN using Keras with precipitation data in Australia.  The code takes 4 input columns: ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed'] and trains against the RainTomorrow output.

I've partitioned the data into training/test buckets, transformed all values into 0 <= n <= 1.  When I trying to run model.fit, my loss values steady at ~13.2, but my accuracy is always 0.0.  An example of logged fitting intervals are:

```<code>...
Epoch 37/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1274 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 38/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1457 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 39/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1315 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 40/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1797 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 41/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1844 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 42/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.2205 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 43/200
...
</code>```

How can I amend the following script, so my accuracy grows, and my predication output returns a value between 0 and 1 (0: no rain, 1: rain)?

```<code>import keras
import sklearn.model_selection
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler

labelencoder = LabelEncoder()

# read data, replace NaN with 0.0
csv_data = pd.read_csv('weatherAUS.csv', header=0)
csv_data = csv_data.replace(np.nan, 0.0, regex=True)

# Input/output columns scaled to 0<=n<=1
x = csv_data.loc[:, ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed']]
y = labelencoder.fit_transform(csv_data['RainTomorrow'])
scaler_x = MinMaxScaler(feature_range =(-1, 1))
x = scaler_x.fit_transform(x)
scaler_y = MinMaxScaler(feature_range =(-1, 1))
y = scaler_y.fit_transform([y])[0]

# Partitioned data for training/testing
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2)

# model
model = keras.models.Sequential()
model.add( keras.layers.normalization.BatchNormalization(input_shape=tuple([x_train.shape[1]])))
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.core.Dense(1,   activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=["accuracy"])

callback_early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto')

model.fit(x_train, y_train, batch_size=1024, epochs=200, validation_data=(x_test, y_test), verbose=1, callbacks=[callback_early_stopping])

y_test = model.predict(x_test.values)
</code>```

答:
So the sigmoid Ranges from 0 to 1.
Your MinMaxscaler scales data from -1 to 1.

You can fix it by replacing 'sigmoid' in the output layer with 'tanh', as tanh has output ranging from -1 to 1

Body:
I've built a simplistic multi-layer NN using Keras with precipitation data in Australia.  The code takes 4 input columns: ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed'] and trains against the RainTomorrow output.

I've partitioned the data into training/test buckets, transformed all values into 0 <= n <= 1.  When I trying to run model.fit, my loss values steady at ~13.2, but my accuracy is always 0.0.  An example of logged fitting intervals are:

...
Epoch 37/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1274 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 38/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1457 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 39/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1315 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 40/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1797 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 41/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1844 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 42/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.2205 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 43/200
...

How can I amend the following script, so my accuracy grows, and my predication output returns a value between 0 and 1 (0: no rain, 1: rain)?

import keras
import sklearn.model_selection
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler

labelencoder = LabelEncoder()

# read data, replace NaN with 0.0
csv_data = pd.read_csv('weatherAUS.csv', header=0)
csv_data = csv_data.replace(np.nan, 0.0, regex=True)

# Input/output columns scaled to 0<=n<=1
x = csv_data.loc[:, ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed']]
y = labelencoder.fit_transform(csv_data['RainTomorrow'])
scaler_x = MinMaxScaler(feature_range =(-1, 1))
x = scaler_x.fit_transform(x)
scaler_y = MinMaxScaler(feature_range =(-1, 1))
y = scaler_y.fit_transform([y])[0]

# Partitioned data for training/testing
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2)

# model
model = keras.models.Sequential()
model.add( keras.layers.normalization.BatchNormalization(input_shape=tuple([x_train.shape[1]])))
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.core.Dense(1,   activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=["accuracy"])

callback_early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto')

model.fit(x_train, y_train, batch_size=1024, epochs=200, validation_data=(x_test, y_test), verbose=1, callbacks=[callback_early_stopping])

y_test = model.predict(x_test.values)


问:
C# Manage windows events
I would like to delete an event from the Windows event log using C#.

Can anyone point me in the right direction of how to achieve this?

答:
I don't believe you can delete one specific event from the eventlog. It's all or nothing.  If you want to get rid of one, you have to clear the whole log.

Edit:  The only thing you can do is Clear the log.  Well, okay, you can delete the entire log from the computer, if it's not Security, Application, or System, but you definitely can't remove one entry.

OwnerDisplayName: Jade M

Title: C# Manage windows events

OwnerDisplayName: Moose

ContentLicense: CC BY-SA 2.5


问:
Sending an Email via Python
I'm attempting to send an email with Python. From what I can tell, all the following code needs is a valid recipient and a host HOST. I'm unsure on how to get the host. What is the simplest way?

```<code>import smtplib
import string

SUBJECT = "Test email from Python"
TO = "python@mydomain.com"
FROM = "python@mydomain.com"
text = "blah blah blah"
BODY = string.join((
        "From: %s" % FROM,
        "To: %s" % TO,
        "Subject: %s" % SUBJECT ,
        "",
        text
        ), "\r\n")
server = smtplib.SMTP(HOST)
server.sendmail(FROM, [TO], BODY)
server.quit()
</code>```

答: We are not in the position to tell you a valid mail host aka smtp server. You should know where to send your mail to: either ask your organization IT or ask your mail provider.</p>

Title: Sending an Email via Python

Body:
I'm attempting to send an email with Python. From what I can tell, all the following code needs is a valid recipient and a host HOST. I'm unsure on how to get the host. What is the simplest way?

import smtplib
import string

SUBJECT = "Test email from Python"
TO = "python@mydomain.com"
FROM = "python@mydomain.com"
text = "blah blah blah"
BODY = string.join((
        "From: %s" % FROM,
        "To: %s" % TO,
        "Subject: %s" % SUBJECT ,
        "",
        text
        ), "\r\n")
server = smtplib.SMTP(HOST)
server.sendmail(FROM, [TO], BODY)
server.quit()


问:
how to center a popoverview in swift
I have the following code to show a popoverview (dialog) without an arrow, which works fine. The only problem is, that the dialog is shown in the top left (IPad). I would like to center the view on the screen.

What to change or add in my following code ? :

```<code>func show_help(){

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewControllerWithIdentifier("Help") as! UIViewController

    controller.modalPresentationStyle = UIModalPresentationStyle.popover

    let popoverPresentationController = controller.popoverPresentationController

    // result is an optional (but should not be nil if modalPresentationStyle is popover)
    if let _popoverPresentationController = popoverPresentationController {

        // set the view from which to pop up
        _popoverPresentationController.sourceView = self.view;
        _popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.allZeros;
        // present (id iPhone it is a modal automatic full screen)
        self.presentViewController(controller, animated: true, completion: nil)
    }

}
</code>```

Additional Infos

In my view, which is linked to my viewcontroller I set the preffered size like this:

```<code>override func viewDidLoad() {
        let dialogheigth:CGFloat = self.view.frame.height * 0.5;
        let dialogwidth:CGFloat = self.view.frame.width * 0.5;
        self.preferredContentSize = CGSizeMake(dialogwidth,dialogheigth);
}
</code>```

答:
Add the below mentioned line of code to make it centre.</p>

```<code>popoverController.popoverPresentationController?.sourceView = view

popoverController.popoverPresentationController?.sourceRect = view.bounds
</code>```

Title: how to center a popoverview in swift

Body:
I have the following code to show a popoverview (dialog) without an arrow, which works fine. The only problem is, that the dialog is shown in the top left (IPad). I would like to center the view on the screen.

What to change or add in my following code ? :

func show_help(){

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewControllerWithIdentifier("Help") as! UIViewController

    controller.modalPresentationStyle = UIModalPresentationStyle.popover

    let popoverPresentationController = controller.popoverPresentationController

    // result is an optional (but should not be nil if modalPresentationStyle is popover)
    if let _popoverPresentationController = popoverPresentationController {

        // set the view from which to pop up
        _popoverPresentationController.sourceView = self.view;
        _popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.allZeros;
        // present (id iPhone it is a modal automatic full screen)
        self.presentViewController(controller, animated: true, completion: nil)
    }

}

Additional Infos

In my view, which is linked to my viewcontroller I set the preffered size like this:

override func viewDidLoad() {
        let dialogheigth:CGFloat = self.view.frame.height * 0.5;
        let dialogwidth:CGFloat = self.view.frame.width * 0.5;
        self.preferredContentSize = CGSizeMake(dialogwidth,dialogheigth);
}

Body:
Add the below mentioned line of code to make it centre.

popoverController.popoverPresentationController?.sourceView = view

popoverController.popoverPresentationController?.sourceRect = view.bounds


问:
SpeechRecognizer: no selected voice recognition service
This is how i start my RecogniseListener intent:

```<code>Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

intent.putExtra("android.speech.extra.DICTATION_MODE", true);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,this.getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
sr.startListening(intent);
</code>```

However, i get a strange behavior. It works on some phones (Samsung galaxy S5, in this case), but i get the following error on Lenovo K50-T5:

```<code>E/SpeechRecognizer: no selected voice recognition service
</code>```

This is my AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="lips.deafcommunication.deaflips">

<uses-permission android:name="android.permission.RECORD_AUDIO" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppThemeNoBar">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ChatInProgressActivity" android:screenOrientation="portrait"
                android:windowSoftInputMode="adjustPan"
                android:configChanges="keyboardHidden|orientation|screenSize"
        ></activity>
</application>
</manifest>
</code>```

答:
To make Hamza's solution fool-proof, you can add the following checks, to pre-empt the different errors in the logs on startVoiceRecognition()

```<code>private static final String GOOGLE_RECOGNITION_SERVICE_NAME = "com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService"

public static boolean isSpeechRecognizerAvailable() {
    if (sIsSpeechRecognizerAvailable == null) {
        boolean isRecognitionAvailable = context != null && context.getPackageManager() != null
                && SpeechRecognizer.isRecognitionAvailable(context);
        if (isRecognitionAvailable) {
            ServiceConnection connection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {

                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };
            Intent serviceIntent = new Intent(RecognitionService.SERVICE_INTERFACE);
            ComponentName recognizerServiceComponent = ComponentName.unflattenFromString(GOOGLE_RECOGNITION_SERVICE_NAME);
            if (recognizerServiceComponent == null) {
                return false;
            }

            serviceIntent.setComponent(recognizerServiceComponent);
            boolean isServiceAvailableToBind = context.bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
            if (isServiceAvailableToBind) {
                context.unbindService(connection);
            }
            sIsSpeechRecognizerAvailable = isServiceAvailableToBind;
        } else {
            sIsSpeechRecognizerAvailable = false;
        }
    }
    return sIsSpeechRecognizerAvailable;
}
</code>```

and then use the same component name to initialise the speech recogniser

```<code>this.speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context, ComponentName.unflattenFromString(GOOGLE_RECOGNITION_SERVICE_NAME));
</code>```

Body:
This is how i start my RecogniseListener intent:

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

intent.putExtra("android.speech.extra.DICTATION_MODE", true);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,this.getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
sr.startListening(intent);

However, i get a strange behavior. It works on some phones (Samsung galaxy S5, in this case), but i get the following error on Lenovo K50-T5:

E/SpeechRecognizer: no selected voice recognition service

This is my AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="lips.deafcommunication.deaflips">

<uses-permission android:name="android.permission.RECORD_AUDIO" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppThemeNoBar">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".ChatInProgressActivity" android:screenOrientation="portrait"
                android:windowSoftInputMode="adjustPan"
                android:configChanges="keyboardHidden|orientation|screenSize"
        ></activity>
</application>
</manifest>

Body:
To make Hamza's solution fool-proof, you can add the following checks, to pre-empt the different errors in the logs on startVoiceRecognition()

private static final String GOOGLE_RECOGNITION_SERVICE_NAME = "com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService"

public static boolean isSpeechRecognizerAvailable() {
    if (sIsSpeechRecognizerAvailable == null) {
        boolean isRecognitionAvailable = context != null && context.getPackageManager() != null
                && SpeechRecognizer.isRecognitionAvailable(context);
        if (isRecognitionAvailable) {
            ServiceConnection connection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {

                }

                @Override
                public void onServiceDisconnected(ComponentName name) {

                }
            };
            Intent serviceIntent = new Intent(RecognitionService.SERVICE_INTERFACE);
            ComponentName recognizerServiceComponent = ComponentName.unflattenFromString(GOOGLE_RECOGNITION_SERVICE_NAME);
            if (recognizerServiceComponent == null) {
                return false;
            }

            serviceIntent.setComponent(recognizerServiceComponent);
            boolean isServiceAvailableToBind = context.bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
            if (isServiceAvailableToBind) {
                context.unbindService(connection);
            }
            sIsSpeechRecognizerAvailable = isServiceAvailableToBind;
        } else {
            sIsSpeechRecognizerAvailable = false;
        }
    }
    return sIsSpeechRecognizerAvailable;
}

and then use the same component name to initialise the speech recogniser

this.speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context, ComponentName.unflattenFromString(GOOGLE_RECOGNITION_SERVICE_NAME));


问:
Getting fragment ids from a dbid
I'm struggling a little with seeming inconsistencies between the type definitions, documentation, and behaviour of the viewer.

I've written a simple extension to colour elements (which I can't get to work anyway, but that's a different question).

When I try to get the fragments for a given node using the InstanceTree#enumNodeFragments method, I get an empty array:

getFragmentsForNode(dbId: number): number[] {
    const fragments: number[] = [];
    this.viewer.model.getInstanceTree().enumNodeFragments(dbId, (fragId) => fragments.push(fragId));
    return fragments;
}
```

<p>The documentation gives no indication of the expected arguments for this callback, but from online examples I'm guessing the signature is something like the following:</p>

<pre class="lang-js prettyprint-override"><code>enumNodeFragments(dbId: number, callback: (fragId: number) => void, recursive?: boolean): void;
</code>```

The typescript definition is confusing as it lists node: any as the first argument, which implies it might not be an id but something else.

When I run this for any element, I always get an empty array which is a bit baffling, as without access to the fragments I can't really set colours etc..

答:
Unfortunately I was unable to reproduce the issue with a valid dbid and model - see live sample here

```<code>viewer.model.getInstanceTree().enumNodeFragments(dbId, fragId=> console.log(fragId));
</code>```

Did you provide a valid dbid?

Title: Getting fragment ids from a dbid

Body:
I'm struggling a little with seeming inconsistencies between the type definitions, documentation, and behaviour of the viewer.

I've written a simple extension to colour elements (which I can't get to work anyway, but that's a different question).

When I try to get the fragments for a given node using the InstanceTree#enumNodeFragments method, I get an empty array:

getFragmentsForNode(dbId: number): number[] {
    const fragments: number[] = [];
    this.viewer.model.getInstanceTree().enumNodeFragments(dbId, (fragId) => fragments.push(fragId));
    return fragments;
}

The documentation gives no indication of the expected arguments for this callback, but from online examples I'm guessing the signature is something like the following:

enumNodeFragments(dbId: number, callback: (fragId: number) => void, recursive?: boolean): void;

The typescript definition is confusing as it lists node: any as the first argument, which implies it might not be an id but something else.

When I run this for any element, I always get an empty array which is a bit baffling, as without access to the fragments I can't really set colours etc..

Body:
Unfortunately I was unable to reproduce the issue with a valid dbid and model - see live sample here

viewer.model.getInstanceTree().enumNodeFragments(dbId, fragId=> console.log(fragId));

Did you provide a valid dbid?


问:
C# logic question
I have those boolean values:

```<code>bool test = false && true || true; // true
bool test1 = false && (true || true); // false
</code>```

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)

答: The && is evaluated first in your first expression - meaning you end up with the result of false || true, rather than false && true in the second expression.

Title: C# logic question

Body:
I have those boolean values:

bool test = false && true || true; // true
bool test1 = false && (true || true); // false

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)


问:
Can -Exclude and -Filter be used together?
I have the following script in which I am trying to get any LATEST csv file with Members in its name but not members AND server[-1] in its name

suppose server is an array holding servers in it. as an example, the file that should be left out would be Members_server1.domain.com.csv

```<code>Get-ChildItem "$csvLocation" -Filter '*Members*.csv' -Exclude "*Members_$($Server[-1])*.csv" | Where-Object {
                    $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today
                } | Move-Item -Destination "$csvLocation\$($DBName)_Members_$($Server[-1]).csv" -Force
</code>```

However, it doesn't look like exclude is working.

what am I doing wrong?

答:
No, the filters don't seem to require include and exclude instead of filter.
Using Where-Object (?) you can specify the Name or FullName as part of the filter:

```<code>Get-ChildItem "$csvLocation" | Where-Object { $_.Name -like '*Members*.csv' -and $_.Name -notlike "*Members_$($Server[-1])*.csv" -and $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today } | Move-Item -Destination "$csvLocation\$($DBName)_Members_$($Server[-1]).csv" -Force
</code>```

Or specify your own function

```<code># setup example
$today = [datetime]::Today.GetDateTimeFormats()[44]
$Server = @('server1')
$DBName = 'dbname'

echo test > 'members.csv'
echo test > 'members_server1.csv'

# functions
function FilterCsvFiles() {

    param(
        [System.IO.FileSystemInfo[]] $fileInfos
    )

    return $fileInfos | Where-Object { $_.Name -like '*Members*.csv' -and $_.Name -notlike "*Members_$($Server[-1])*.csv" -and $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today }
}
# move items
Get-ChildItem "$csvLocation" | FilterCsvFiles | Move-Item -Destination "$csvLocation\$($DBName)_Members_$($Server[-1]).csv" -Force
</code>```

Body:
I have the following script in which I am trying to get any LATEST csv file with Members in its name but not members AND server[-1] in its name

suppose server is an array holding servers in it. as an example, the file that should be left out would be Members_server1.domain.com.csv

Get-ChildItem "$csvLocation" -Filter '*Members*.csv' -Exclude "*Members_$($Server[-1])*.csv" | Where-Object {
                    $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today
                } | Move-Item -Destination "$csvLocation\$($DBName)_Members_$($Server[-1]).csv" -Force

However, it doesn't look like exclude is working.

what am I doing wrong?

Body:
No, the filters don't seem to require include and exclude instead of filter.
Using Where-Object (?) you can specify the Name or FullName as part of the filter:

Get-ChildItem "$csvLocation" | Where-Object { $_.Name -like '*Members*.csv' -and $_.Name -notlike "*Members_$($Server[-1])*.csv" -and $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today } | Move-Item -Destination "$csvLocation\$($DBName)_Members_$($Server[-1]).csv" -Force

Or specify your own function

# setup example
$today = [datetime]::Today.GetDateTimeFormats()[44]
$Server = @('server1')
$DBName = 'dbname'

echo test > 'members.csv'
echo test > 'members_server1.csv'

# functions
function FilterCsvFiles() {

    param(
        [System.IO.FileSystemInfo[]] $fileInfos
    )

    return $fileInfos | Where-Object { $_.Name -like '*Members*.csv' -and $_.Name -notlike "*Members_$($Server[-1])*.csv" -and $_.LastWriteTime.GetDateTimeFormats()[44] -eq $today }
}
# move items
Get-ChildItem "$csvLocation" | FilterCsvFiles | Move-Item -Destination "$csvLocation\$($DBName)_Members_$($Server[-1]).csv" -Force


问:
I have an MFC legacy C++ that I wish to remotely debug, but the Deploy box is greyed out on the configuration. How do I enable it?
Following the steps at https://learn.microsoft.com/en-us/visualstudio/debugger/remote-debugging-cpp?view=vs-2019

I have completed the steps up to where I must click the Deploy checkboxes in the Configuration Manager, but they are greyed out.

This is a legacy MFC 32 bit application.

Am I missing something?

答:
I have completed the steps up to where I must click the Deploy
  checkboxes in the Configuration Manager, but they are greyed out.

1.Please make sure you've set the Debugger to launch to Remote Windows Debugger.

2.And after my check, you should configure the Deployment Directory so that the project is deployable and the Deploy Checkbox is able to click.

3.Also, please check the Configuration and Platform you selected in Project properties and Configuration Manager, they should be corresponding to work.

e.g:

If we complete the settings in this way:

In Configuration Manager,only when we choose Debug+X86(Active Configuration and Active Platform) the Deploy checkbox is available, and if we change the X86 to X64, the checkbox would be grayed.

Hope it helps:)


问:
Data Vault Hubs from different sources
So I'm trying to implement a data vault.
I have some difficulties modeling the hub.
I have 2 systems that don't talk to each other. I want to know how to represent the same item from different sources in the hub.

In our ordering system, it generates a number to distinguish customers.
So lets say we have a customer named "Bob" and he needs our service in 5 locations. So we treat those 5 locations as separate customers. So we get 5 different customer IDs(10004-10008). Easy peasy so far in the Data Vault.

Now the tricky part is in our operations system. We have a compound business key. So we get a unique customer name "bob' and a sequence number (1-5) for each of his locations. So (bob,1) is unique but we can also have a (joe,1).

In our operations system, there's no way to put in the ordering system's ID. In our ordering system, the (bob,1) information isn't filled in until well after (bob,1) was already created.

So the timelines can be like this
Bob comes in and says I need 5 locations. Ordering system gives him IDs (10004-10008).
A week later he gets created in our operations system (bob,1), (bob,2)...(bob,5)
Then maybe 2 weeks later we'll see (10004,bob,1), (10005,bob,2) in the ordering system.

How would one deal with this scenario?

Thanks

答:
I would possibly create two hubs in the raw data vault, aligned with the source systems, and then create a single hub in the business vault where you apply the necessary business rules to build a single hub view of the customer.  That way you preserve source-system semantics completely, but still add value to the business by trying to merge the data sets.

As mentioned above, some same-as links could also be used.

Title: Data Vault Hubs from different sources


问:
issue with positioning of pop over view
When I am switching between Portrait to Landscape view (&Vice Versa) in iPad, position of my popover view gets garbled. Here is how I am calculating frame of my popover view:

```<code>aRect = self.myElement.frame;
aRect.origin.x += aRect.size.width;

[aPopOver presentPopoverFromRect:aRect inView:self.myElement.superview permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];
</code>```

Please tell me whats wrong here?

答:
Use the below mentioned UIPopoverPresentationControllerDelegate method in the viewcontroller.</p>

```<code>func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController,
                                   willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>,
                                   in view: AutoreleasingUnsafeMutablePointer<UIView>) {
    rect.pointee = self.view.bounds
}
</code>```

Title: issue with positioning of pop over view

Body:
When I am switching between Portrait to Landscape view (&Vice Versa) in iPad, position of my popover view gets garbled. Here is how I am calculating frame of my popover view:

aRect = self.myElement.frame;
aRect.origin.x += aRect.size.width;

[aPopOver presentPopoverFromRect:aRect inView:self.myElement.superview permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];

Please tell me whats wrong here?

Body:
Use the below mentioned UIPopoverPresentationControllerDelegate method in the viewcontroller.

func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController,
                                   willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>,
                                   in view: AutoreleasingUnsafeMutablePointer<UIView>) {
    rect.pointee = self.view.bounds
}


问:
Pip on only installs to python27 while i need it to install on python37
I have multiple instances of python in my computer namely python27, python3.6 and python 3.7.

The import module for docx worked daily on python27 until suddenly it stopped working today. I tried installing the module again using pip in windows command line.

It says only installed in python27 directory. But there's an
  importError on my script.

I guess I should be high time i transferred into python37 but I can't seem to make pip install into python 3.7

Can someone offer some advice as to the messy situation I'm in?
I want to transfer to python3 and install docx in python3

Already checked modules using pip and docx is not there.

答:
You should try setting your command prompt on the version of Python you want the module to install. Then, just use "pip", to install.

This is how you can do this:
Go into File Explorer (hopefully you have windows) and press and hold the shift key, then right click the folder that you want command prompt to look at. In this case, the folder with the version of Python. Then you click on the command prompt selection, and you're golden. Just use "pip install xyz" from there on. Glad to help
- BURAK ILOGLU


问:
How can I get the yesterday's data and show it to my form today?
The idea is that I have this 'Present' form that is a textbox one that the user can input the data.

Now, I want to show yesterday's data(readonly) for comparing the result yesterday vs the result today.

Ex:
Attendance: (yesterday- readonly textbox)

```<code>Andy Shrob
Paula Guinto
Mylene Miles
</code>```

Attendance (TODAY)

```<code>Paula Guinto
Mylene Miles
</code>```

How can I get yesterday and show it so I can see who's present yesterday and who's present today? I'm coding PHP and Javascript

I was thinking of this:

```<code>mysql_query("Select prestoday, presyesterday
FROM attendance
WHERE ???)
</code>```

All ideas are welcome. ;) Whether it be PHP code or Javascript or MYSQL Query

TABLE STRUCTURE:
mysql_select_db("csdcon", $con);

$sql="INSERT INTO attendance (prestoday, presyesterday, userdateinp, yesterdate)
                            VALUES
('$_POST[prestoday]','$_POST[presyesterday]','$_POST[userdateinp]','$_POST[yesterdate]')";

答:
You can get Date From JavaScript as</p>

```<code>var today= new Date();
var yesterday = new Date();
yesterday .setDate(today.getDate()-1);

alert('today'+today);
alert('yesterday '+yesterday );
</code>```

Body:
The idea is that I have this 'Present' form that is a textbox one that the user can input the data.

Now, I want to show yesterday's data(readonly) for comparing the result yesterday vs the result today.

Ex:
Attendance: (yesterday- readonly textbox)

Andy Shrob
Paula Guinto
Mylene Miles

Attendance (TODAY)

Paula Guinto
Mylene Miles

How can I get yesterday and show it so I can see who's present yesterday and who's present today? I'm coding PHP and Javascript

I was thinking of this:

mysql_query("Select prestoday, presyesterday
FROM attendance
WHERE ???)

All ideas are welcome. ;) Whether it be PHP code or Javascript or MYSQL Query

TABLE STRUCTURE:
mysql_select_db("csdcon", $con);

$sql="INSERT INTO attendance (prestoday, presyesterday, userdateinp, yesterdate)
                            VALUES
('$_POST[prestoday]','$_POST[presyesterday]','$_POST[userdateinp]','$_POST[yesterdate]')";

Body:
You can get Date From JavaScript as

var today= new Date();
var yesterday = new Date();
yesterday .setDate(today.getDate()-1);

alert('today'+today);
alert('yesterday '+yesterday );


问:
What is the difference between process.stderr.on('data') and process.on('error')?
I'm setting up error handling for a child process in my node application, and I'm wondering about these two options:

```<code>    childProcess.on('error', err => {
        // omitted
    });

    // do we need both this and the preceding handler?
    childProcess.stderr.on('data', data => {
        // omitted
    });
</code>```

What's the difference? Are both needed?

答:
The child process error event is fired when node has a problem starting, stopping or managing the child process.

stderr is one of the output channels for the child process once it's running. The data event can be fired many times in normal operation of a process and can often include important information about error conditions of the process. You would normally handle stdout in a similar fashion to stderr.

The exit events code value can also be important for a child process. Often processes will exit with a non 0 return code to signal an issue occurred.

Body:
I'm setting up error handling for a child process in my node application, and I'm wondering about these two options:

    childProcess.on('error', err => {
        // omitted
    });

    // do we need both this and the preceding handler?
    childProcess.stderr.on('data', data => {
        // omitted
    });

What's the difference? Are both needed?


问:
How does findstr "^" equate to an empty directory?
Batch files in Windows can be confusing at the best of times. How does

```<code>  findstr "^"
</code>```

equate to finding an empty folder, when ^ means the start of the line?

```<code>for /d /r %1 %%A in (.) do (
  dir /ad /b "%%~fA" 2>nul | findstr "^" >nul || echo %%~fA
)
</code>```

taken from dbenham's answer

Unless I'm reading this wrong and it's

```<code>dir /ad /b "%%~fA" 2>nul
</code>```

that finds empty folders.

答:
I believe the piece of this that you're missing is the || (logical OR) operation.

It runs the command after it only if the preceding command fails.

Knowing this, it will make sense that dir /ad /b "%%~fA" 2>nul | findstr "^" >nul is not looking for empty directories.  It is succeeding when the list generated by dir is NOT empty.  It fails when the listing is empty.

Body:
Batch files in Windows can be confusing at the best of times. How does

  findstr "^"

equate to finding an empty folder, when ^ means the start of the line?

for /d /r %1 %%A in (.) do (
  dir /ad /b "%%~fA" 2>nul | findstr "^" >nul || echo %%~fA
)

taken from dbenham's answer

Unless I'm reading this wrong and it's

dir /ad /b "%%~fA" 2>nul

that finds empty folders.


问:
Gmail API Quickstart: Can't install Python Google Client Library
I'm trying to run the Gmail API Python Quickstart on my Mac (Mojave 10.14.5)

I've installed the Google Client library as such:

```<code>sudo -H pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
</code>```

This is the output:

```<code>DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Requirement already up-to-date: google-api-python-client in /private/var/root/Library/Python/2.7/lib/python/site-packages (1.7.9)
Requirement already up-to-date: google-auth-httplib2 in /private/var/root/Library/Python/2.7/lib/python/site-packages (0.0.3)
Requirement already up-to-date: google-auth-oauthlib in /private/var/root/Library/Python/2.7/lib/python/site-packages (0.3.0)
Requirement already satisfied, skipping upgrade: httplib2<1dev,>=0.9.2 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-api-python-client) (0.12.3)
Requirement already satisfied, skipping upgrade: uritemplate<4dev,>=3.0.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-api-python-client) (3.0.0)
Requirement already satisfied, skipping upgrade: six<2dev,>=1.6.1 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-api-python-client) (1.12.0)
Requirement already satisfied, skipping upgrade: google-auth>=1.4.1 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-api-python-client) (1.6.3)
Requirement already satisfied, skipping upgrade: requests-oauthlib>=0.7.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-auth-oauthlib) (1.2.0)
Requirement already satisfied, skipping upgrade: cachetools>=2.0.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-auth>=1.4.1->google-api-python-client) (3.1.1)
Requirement already satisfied, skipping upgrade: rsa>=3.1.4 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-auth>=1.4.1->google-api-python-client) (4.0)
Requirement already satisfied, skipping upgrade: pyasn1-modules>=0.2.1 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-auth>=1.4.1->google-api-python-client) (0.2.5)
Requirement already satisfied, skipping upgrade: requests>=2.0.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib) (2.22.0)
Requirement already satisfied, skipping upgrade: oauthlib>=3.0.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib) (3.0.1)
Requirement already satisfied, skipping upgrade: pyasn1>=0.1.3 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from rsa>=3.1.4->google-auth>=1.4.1->google-api-python-client) (0.4.5)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google-auth-oauthlib) (1.25.3)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google-auth-oauthlib) (2019.3.9)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google-auth-oauthlib) (3.0.4)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google-auth-oauthlib) (2.8)
</code>```

But when I try to run the quickstart:

```<code>>python quickstart.py
Traceback (most recent call last):
  File "quickstart.py", line 4, in <module>
    from googleapiclient.discovery import build
ImportError: No module named googleapiclient.discovery
</code>```

Now if I comment out line 4, I get this:

```<code>>python quickstart.py
Traceback (most recent call last):
  File "quickstart.py", line 5, in <module>
    from google_auth_oauthlib.flow import InstalledAppFlow
ImportError: No module named google_auth_oauthlib.flow
</code>```

And if I comment out line 5, I get this:

```<code>>python quickstart.py
Traceback (most recent call last):
  File "quickstart.py", line 6, in <module>
    from google.auth.transport.requests import Request
ImportError: No module named google.auth.transport.request
</code>```

I also tried to restart my terminal - and also to restart my machine.

Why aren't any of the Google Client Library modules found?

答:
I'm not sure why - but perhaps Python 2.x is not supported?

Once I moved onto Python 3.x everything worked:

Installation:

```<code>sudo -H pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
</code>```

Run script:

```<code>python3 quickstart.py
</code>```

Body:
I'm trying to run the Gmail API Python Quickstart on my Mac (Mojave 10.14.5)

I've installed the Google Client library as such:

sudo -H pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

This is the output:

DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Requirement already up-to-date: google-api-python-client in /private/var/root/Library/Python/2.7/lib/python/site-packages (1.7.9)
Requirement already up-to-date: google-auth-httplib2 in /private/var/root/Library/Python/2.7/lib/python/site-packages (0.0.3)
Requirement already up-to-date: google-auth-oauthlib in /private/var/root/Library/Python/2.7/lib/python/site-packages (0.3.0)
Requirement already satisfied, skipping upgrade: httplib2<1dev,>=0.9.2 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-api-python-client) (0.12.3)
Requirement already satisfied, skipping upgrade: uritemplate<4dev,>=3.0.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-api-python-client) (3.0.0)
Requirement already satisfied, skipping upgrade: six<2dev,>=1.6.1 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-api-python-client) (1.12.0)
Requirement already satisfied, skipping upgrade: google-auth>=1.4.1 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-api-python-client) (1.6.3)
Requirement already satisfied, skipping upgrade: requests-oauthlib>=0.7.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-auth-oauthlib) (1.2.0)
Requirement already satisfied, skipping upgrade: cachetools>=2.0.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-auth>=1.4.1->google-api-python-client) (3.1.1)
Requirement already satisfied, skipping upgrade: rsa>=3.1.4 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-auth>=1.4.1->google-api-python-client) (4.0)
Requirement already satisfied, skipping upgrade: pyasn1-modules>=0.2.1 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from google-auth>=1.4.1->google-api-python-client) (0.2.5)
Requirement already satisfied, skipping upgrade: requests>=2.0.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib) (2.22.0)
Requirement already satisfied, skipping upgrade: oauthlib>=3.0.0 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib) (3.0.1)
Requirement already satisfied, skipping upgrade: pyasn1>=0.1.3 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from rsa>=3.1.4->google-auth>=1.4.1->google-api-python-client) (0.4.5)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google-auth-oauthlib) (1.25.3)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google-auth-oauthlib) (2019.3.9)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google-auth-oauthlib) (3.0.4)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /private/var/root/Library/Python/2.7/lib/python/site-packages (from requests>=2.0.0->requests-oauthlib>=0.7.0->google-auth-oauthlib) (2.8)

But when I try to run the quickstart:

>python quickstart.py
Traceback (most recent call last):
  File "quickstart.py", line 4, in <module>
    from googleapiclient.discovery import build
ImportError: No module named googleapiclient.discovery

Now if I comment out line 4, I get this:

>python quickstart.py
Traceback (most recent call last):
  File "quickstart.py", line 5, in <module>
    from google_auth_oauthlib.flow import InstalledAppFlow
ImportError: No module named google_auth_oauthlib.flow

And if I comment out line 5, I get this:

>python quickstart.py
Traceback (most recent call last):
  File "quickstart.py", line 6, in <module>
    from google.auth.transport.requests import Request
ImportError: No module named google.auth.transport.request

I also tried to restart my terminal - and also to restart my machine.

Why aren't any of the Google Client Library modules found?

Body:
I'm not sure why - but perhaps Python 2.x is not supported?

Once I moved onto Python 3.x everything worked:

Installation:

sudo -H pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Run script:

python3 quickstart.py


问:
EVP_DecryptFinal_ex:bad decrypt when using Node.js
Using the following node js:

```<code>var crypto = require('crypto');
var encrypt = function (input, password, callback) {
    var m = crypto.createHash('md5');
    m.update(password);
    var key = m.digest('hex');

    m = crypto.createHash('md5');
    m.update(password + key);
    var iv = m.digest('hex');
    console.log(iv);

    var data = new Buffer(input, 'utf8').toString('binary');

    var cipher = crypto.createCipheriv('aes-256-cbc', key, iv.slice(0,16));
    var encrypted = cipher.update(data, 'binary') + cipher.final('binary');
    var encoded = new Buffer(encrypted, 'binary').toString('base64');
    callback(encoded);
};

var decrypt = function (input, password, callback) {
    // Convert urlsafe base64 to normal base64
    input = input.replace(/\-/g, '+').replace(/_/g, '/');
    // Convert from base64 to binary string
    var edata = new Buffer(input, 'base64').toString('binary');

    // Create key from password
    var m = crypto.createHash('md5');
    m.update(password);
    var key = m.digest('hex');

    // Create iv from password and key
    m = crypto.createHash('md5');
    m.update(password + key);
    var iv = m.digest('hex');

    // Decipher encrypted data
    var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv.slice(0,16));
    var decrypted = decipher.update(edata, 'binary') + decipher.final('binary');
    var plaintext = new Buffer(decrypted, 'binary').toString('utf8');

    callback(plaintext);
};
</code>```

To execute I ran this:

```<code>encrypt("uWeShxRrCKyK4pcs", "secret", function (encoded) {
    console.log(encoded);
    decrypt(encoded, "secret", function (output) {
        console.log(output);
    });
});
</code>```

Encrypting seems to work fine, but when I try to decrypt, I receive the following error:

Error: error:06065064:digital envelope
  routines:EVP_DecryptFinal_ex:bad decrypt
      at Error (native)
      at Decipheriv.Cipher.final (crypto.js:202:26)

I am pretty new to cryptography, so don't really know why I am receiving this error. I just need to get it fixed for now.

答:
I found out the reason for this, is using different key's or iv's for encryption & decryption. We must use the same key & iv used for encryption, for decrypting the content. An only workaround is to save the iv & key in an array used during encrypting the data or concatenating iv & key with the encrypted data with the help of separators

Example One:

```<code>function encrypt(text) {
    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return encrypted.toString('hex') + ':' + iv.toString('hex') + '=' +
    key.toString('hex');
    //returns encryptedData:iv=key
}

function decrypt(text) {
    let iv = Buffer.from((text.split(':')[1]).split('=')[0], 'hex')//will return iv;
    let enKey = Buffer.from(text.split('=')[1], 'hex')//will return key;
    let encryptedText = Buffer.from(text.split(':')[0], 'hex');//returns encrypted Data
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(enKey), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
    //returns decryptedData
}
</code>```

Example Two:

```<code>function encrypt(text) {
    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return {
        "encryptedData": encrypted.toString('hex'),
        "iv" : iv.toString('hex'),
        "key" : key.toString('hex');
    //returns an Array of key, iv & encryptedData
  }
}

function decrypt(text) {
    let iv = Buffer.from((text.iv, 'hex')//will return iv;
    let enKey = Buffer.from(text.key, 'hex')//will return key;
    let encryptedText = Buffer.from(text.encryptedData, 'hex');//returns encrypted Data
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(enKey), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
    //returns decryptedData
}
</code>```

Body:
Using the following node js:

var crypto = require('crypto');
var encrypt = function (input, password, callback) {
    var m = crypto.createHash('md5');
    m.update(password);
    var key = m.digest('hex');

    m = crypto.createHash('md5');
    m.update(password + key);
    var iv = m.digest('hex');
    console.log(iv);

    var data = new Buffer(input, 'utf8').toString('binary');

    var cipher = crypto.createCipheriv('aes-256-cbc', key, iv.slice(0,16));
    var encrypted = cipher.update(data, 'binary') + cipher.final('binary');
    var encoded = new Buffer(encrypted, 'binary').toString('base64');
    callback(encoded);
};

var decrypt = function (input, password, callback) {
    // Convert urlsafe base64 to normal base64
    input = input.replace(/\-/g, '+').replace(/_/g, '/');
    // Convert from base64 to binary string
    var edata = new Buffer(input, 'base64').toString('binary');

    // Create key from password
    var m = crypto.createHash('md5');
    m.update(password);
    var key = m.digest('hex');

    // Create iv from password and key
    m = crypto.createHash('md5');
    m.update(password + key);
    var iv = m.digest('hex');

    // Decipher encrypted data
    var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv.slice(0,16));
    var decrypted = decipher.update(edata, 'binary') + decipher.final('binary');
    var plaintext = new Buffer(decrypted, 'binary').toString('utf8');

    callback(plaintext);
};

To execute I ran this:

encrypt("uWeShxRrCKyK4pcs", "secret", function (encoded) {
    console.log(encoded);
    decrypt(encoded, "secret", function (output) {
        console.log(output);
    });
});

Encrypting seems to work fine, but when I try to decrypt, I receive the following error:

Error: error:06065064:digital envelope
  routines:EVP_DecryptFinal_ex:bad decrypt
      at Error (native)
      at Decipheriv.Cipher.final (crypto.js:202:26)

I am pretty new to cryptography, so don't really know why I am receiving this error. I just need to get it fixed for now.

Body:
I found out the reason for this, is using different key's or iv's for encryption & decryption. We must use the same key & iv used for encryption, for decrypting the content. An only workaround is to save the iv & key in an array used during encrypting the data or concatenating iv & key with the encrypted data with the help of separators

Example One:

function encrypt(text) {
    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return encrypted.toString('hex') + ':' + iv.toString('hex') + '=' +
    key.toString('hex');
    //returns encryptedData:iv=key
}

function decrypt(text) {
    let iv = Buffer.from((text.split(':')[1]).split('=')[0], 'hex')//will return iv;
    let enKey = Buffer.from(text.split('=')[1], 'hex')//will return key;
    let encryptedText = Buffer.from(text.split(':')[0], 'hex');//returns encrypted Data
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(enKey), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
    //returns decryptedData
}

Example Two:

function encrypt(text) {
    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return {
        "encryptedData": encrypted.toString('hex'),
        "iv" : iv.toString('hex'),
        "key" : key.toString('hex');
    //returns an Array of key, iv & encryptedData
  }
}

function decrypt(text) {
    let iv = Buffer.from((text.iv, 'hex')//will return iv;
    let enKey = Buffer.from(text.key, 'hex')//will return key;
    let encryptedText = Buffer.from(text.encryptedData, 'hex');//returns encrypted Data
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(enKey), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
    //returns decryptedData
}


问:
Mootools - tween or morph effects at the same time
Is there a way to trigger two morph or tween effects for two different dom elements at the exact same time?

I created this demo. http://jsfiddle.net/jLmAS/ Click the green block to test.

It seems to work alright although it doesn't seem technically correct. I can imagine if there were 1000 blocks you would see a lag with the bottom blocks.

Any thoughts or ideas?

答: If what the animation does is the same on both elements, there's no reason for using morph and tween. Otherwise, what you're looking for is Fx.Elements (http://mootools.net/docs/more/Fx/Fx.Elements), it takes an Element Collection and applies different animations to them. Fx.Elements is there for the sole reason of animating multiple elements at the same time.

OwnerDisplayName: Paul Mason


问:
Yes to all overwrites in interactive mv/cp/rm?
So I've aliased the commands rm/cp/mv to use interactive (-i) mode by default to avoid accidentally deleting things, but sometimes this is pretty inconvenient.

I would like to be able to say 'y' to all the prompts of the form:

```<code>mv: overwrite `file_1'? y
mv: overwrite `file_2'? y
</code>```

without typing 'y' many many times.  Is there a way to do this?

答:
you can use back slash before cp</p>

```<code>\cp -rf /from/directory/* to/directory
</code>```

Body:
So I've aliased the commands rm/cp/mv to use interactive (-i) mode by default to avoid accidentally deleting things, but sometimes this is pretty inconvenient.

I would like to be able to say 'y' to all the prompts of the form:

mv: overwrite `file_1'? y
mv: overwrite `file_2'? y

without typing 'y' many many times.  Is there a way to do this?

Body:
you can use back slash before cp

\cp -rf /from/directory/* to/directory