问:
Why two very similar Hive Queries return different results(one of which is clearly wrong)?
So I have this weird case in which two very similar queries return different results. The first query is this:

select src.period_num period_num,
src.flag flag,
src.week_num week_num,
((src.year_num * 100) + src.period_num) year_num,
count(distinct src.id) result_count
from src_table src
group by src.period_num,
src.flag,
src.week_num,
((src.year_num * 100) + src.period_num)
```

<p>The second query is this one:</p>

<pre class="lang-sql prettyprint-override"><code>select src.period_num period_num,
src.flag flag,
src.week_num week_num,
((src.year_num * 100) | src.period_num) year_num,
count(distinct src.id) result_count
from src_table src
group by src.period_num,
src.flag,
src.week_num,
((src.year_num * 100) | src.period_num)
</code>```

As you can see the queries have only one difference - in the first one we use addition(+), in the second one we use bit-wise OR(|)
My issue is that for the first one we receive something like this for a result(I've left only the significant part):

```<code>+-------------+---------+-----------+-----------+---------------+--+
| period_num  | flag    | week_num  | year_num  | result_count  |
+-------------+---------+-----------+-----------+---------------+--+
| 6           | true    | 21        | 201906    | 94            |
</code>```

While the second one returns this:

```<code>+-------------+---------+-----------+-----------+---------------+--+
| period_num  | flag    | week_num  | year_num  | result_count  |
+-------------+---------+-----------+-----------+---------------+--+
| 6           | true    | 21        | 201902    | 87            |
| 6           | false   | 21        | 201902    | 7             |
</code>```

The second result count is the correct one, with the correct grouping by flag, but you can see that now the year_num is messing up. Anyway my main issue is is that I can't understand what exactly is going awry with the first query, because it doesn't seem like it has something cardinally bad with it.
Any ideas and help is appreciated.

答:
A bitwise or is a completely different operation to an addition. As such, it will produce completely different results.

Consider the following two examples of binary "operations".

First addition (1 + 3 = 4):

```<code>  0001
+ 0011
  ----
= 0100
</code>```

and a bitwise or (1 | 3 = 3):

```<code>  0001
+ 0011
  ----
= 0011
</code>```

I hope this helps you with your question.

Oh, and remember that multiplying a number by 100 will introduce two trailing zeros in base 10 (decimal), but in binary, there still could be bits set at the least significant places.

For example, 201900 is 110001010010101100 in binary.

without more details, it is difficult to explain why src.flag should magically change from false to true simply by using a bitwise or instead of an addition. Is it possible that preparing your example, you accidentally changed something else?

As promised, I've run your sample data through Spark-SQL. I reduced your dataset to just those 94 records with year_num = 2019 and period_num = 6.

Here is the result of the run showing the same answer being produced for both queries. Following that is the entire sequence which you can try yourself if you have access to spark-shell. It is possible that there is a bug in hive, but I wouldn't start with that assumption.

scala> val sumDF=sql("""select src.period_num period_num,
     |   src.flag flag,
     |   src.week_num week_num,
     |   ((src.year_num * 100) + src.period_num) year_num,
     |   count(distinct src.id) result_count
     |   from src_table src
     |   group by src.period_num,
     |   src.flag,
     |   src.week_num,
     |   ((src.year_num * 100) + src.period_num)
     |   """)
sumDF: org.apache.spark.sql.DataFrame = [period_num: int, flag: boolean ... 3 more fields]

scala> sumDF.show
+----------+-----+--------+--------+------------+
|period_num| flag|week_num|year_num|result_count|
+----------+-----+--------+--------+------------+
|         6|false|      21|  201906|           7|
|         6| true|      21|  201906|          87|
+----------+-----+--------+--------+------------+

scala> val orDF=sql ("""select src.period_num period_num,
     |   src.flag flag,
     |   src.week_num week_num,
     |   ((src.year_num * 100) | src.period_num) year_num,
     |   count(distinct src.id) result_count
     |   from src_table src
     |   group by src.period_num,
     |   src.flag,
     |   src.week_num,
     |   ((src.year_num * 100) | src.period_num)
     |   """)
orDF: org.apache.spark.sql.DataFrame = [period_num: int, flag: boolean ... 3 more fields]

scala> orDF.show
+----------+-----+--------+--------+------------+
|period_num| flag|week_num|year_num|result_count|
+----------+-----+--------+--------+------------+
|         6| true|      21|  201902|          87|
|         6|false|      21|  201902|           7|
+----------+-----+--------+--------+------------+

```

<p>Here is the full job:</p>

<pre class="lang-scala prettyprint-override"><code>var dataDF=spark.read.option("header","true").option("inferSchema","true").csv("source_data_from_op_2019_06.csv")
dataDF.printSchema
dataDF.count
dataDF.show

dataDF.createOrReplaceTempView("src_table")

val sumDF=sql("""select src.period_num period_num,
  src.flag flag,
  src.week_num week_num,
  ((src.year_num * 100) + src.period_num) year_num,
  count(distinct src.id) result_count
  from src_table src
  group by src.period_num,
  src.flag,
  src.week_num,
  ((src.year_num * 100) + src.period_num)
  """)

sumDF.show

val orDF=sql ("""select src.period_num period_num,
  src.flag flag,
  src.week_num week_num,
  ((src.year_num * 100) | src.period_num) year_num,
  count(distinct src.id) result_count
  from src_table src
  group by src.period_num,
  src.flag,
  src.week_num,
  ((src.year_num * 100) | src.period_num)
  """)
orDF.show

</code>```

Are you able to try this in Spark-shell?

Body:
So I have this weird case in which two very similar queries return different results. The first query is this:

select src.period_num period_num,
src.flag flag,
src.week_num week_num,
((src.year_num * 100) + src.period_num) year_num,
count(distinct src.id) result_count
from src_table src
group by src.period_num,
src.flag,
src.week_num,
((src.year_num * 100) + src.period_num)

The second query is this one:

select src.period_num period_num,
src.flag flag,
src.week_num week_num,
((src.year_num * 100) | src.period_num) year_num,
count(distinct src.id) result_count
from src_table src
group by src.period_num,
src.flag,
src.week_num,
((src.year_num * 100) | src.period_num)

As you can see the queries have only one difference - in the first one we use addition(+), in the second one we use bit-wise OR(|)
My issue is that for the first one we receive something like this for a result(I've left only the significant part):

+-------------+---------+-----------+-----------+---------------+--+
| period_num  | flag    | week_num  | year_num  | result_count  |
+-------------+---------+-----------+-----------+---------------+--+
| 6           | true    | 21        | 201906    | 94            |

While the second one returns this:

+-------------+---------+-----------+-----------+---------------+--+
| period_num  | flag    | week_num  | year_num  | result_count  |
+-------------+---------+-----------+-----------+---------------+--+
| 6           | true    | 21        | 201902    | 87            |
| 6           | false   | 21        | 201902    | 7             |

The second result count is the correct one, with the correct grouping by flag, but you can see that now the year_num is messing up. Anyway my main issue is is that I can't understand what exactly is going awry with the first query, because it doesn't seem like it has something cardinally bad with it.
Any ideas and help is appreciated.

Body:
A bitwise or is a completely different operation to an addition. As such, it will produce completely different results.

Consider the following two examples of binary "operations".

First addition (1 + 3 = 4):

  0001
+ 0011
  ----
= 0100

and a bitwise or (1 | 3 = 3):

  0001
+ 0011
  ----
= 0011

I hope this helps you with your question.

Oh, and remember that multiplying a number by 100 will introduce two trailing zeros in base 10 (decimal), but in binary, there still could be bits set at the least significant places.

For example, 201900 is 110001010010101100 in binary.

without more details, it is difficult to explain why src.flag should magically change from false to true simply by using a bitwise or instead of an addition. Is it possible that preparing your example, you accidentally changed something else?

As promised, I've run your sample data through Spark-SQL. I reduced your dataset to just those 94 records with year_num = 2019 and period_num = 6.

Here is the result of the run showing the same answer being produced for both queries. Following that is the entire sequence which you can try yourself if you have access to spark-shell. It is possible that there is a bug in hive, but I wouldn't start with that assumption.

scala> val sumDF=sql("""select src.period_num period_num,
     |   src.flag flag,
     |   src.week_num week_num,
     |   ((src.year_num * 100) + src.period_num) year_num,
     |   count(distinct src.id) result_count
     |   from src_table src
     |   group by src.period_num,
     |   src.flag,
     |   src.week_num,
     |   ((src.year_num * 100) + src.period_num)
     |   """)
sumDF: org.apache.spark.sql.DataFrame = [period_num: int, flag: boolean ... 3 more fields]

scala> sumDF.show
+----------+-----+--------+--------+------------+
|period_num| flag|week_num|year_num|result_count|
+----------+-----+--------+--------+------------+
|         6|false|      21|  201906|           7|
|         6| true|      21|  201906|          87|
+----------+-----+--------+--------+------------+

scala> val orDF=sql ("""select src.period_num period_num,
     |   src.flag flag,
     |   src.week_num week_num,
     |   ((src.year_num * 100) | src.period_num) year_num,
     |   count(distinct src.id) result_count
     |   from src_table src
     |   group by src.period_num,
     |   src.flag,
     |   src.week_num,
     |   ((src.year_num * 100) | src.period_num)
     |   """)
orDF: org.apache.spark.sql.DataFrame = [period_num: int, flag: boolean ... 3 more fields]

scala> orDF.show
+----------+-----+--------+--------+------------+
|period_num| flag|week_num|year_num|result_count|
+----------+-----+--------+--------+------------+
|         6| true|      21|  201902|          87|
|         6|false|      21|  201902|           7|
+----------+-----+--------+--------+------------+

Here is the full job:

var dataDF=spark.read.option("header","true").option("inferSchema","true").csv("source_data_from_op_2019_06.csv")
dataDF.printSchema
dataDF.count
dataDF.show

dataDF.createOrReplaceTempView("src_table")

val sumDF=sql("""select src.period_num period_num,
  src.flag flag,
  src.week_num week_num,
  ((src.year_num * 100) + src.period_num) year_num,
  count(distinct src.id) result_count
  from src_table src
  group by src.period_num,
  src.flag,
  src.week_num,
  ((src.year_num * 100) + src.period_num)
  """)

sumDF.show

val orDF=sql ("""select src.period_num period_num,
  src.flag flag,
  src.week_num week_num,
  ((src.year_num * 100) | src.period_num) year_num,
  count(distinct src.id) result_count
  from src_table src
  group by src.period_num,
  src.flag,
  src.week_num,
  ((src.year_num * 100) | src.period_num)
  """)
orDF.show

Are you able to try this in Spark-shell?


来源: stackexchange

问:
Problem with rotating object
I've been having this problem for a while, and it would be great if someone can help. :)

http://img31.imageshack.us/i/problemsc.jpg/
(illustration of the problem)

So, I have this object with registration point at middle bottom. I want this object to follow the mouse, but to remain on the center of the screen while rotating. Here is what I used :

```<code>dx = mouseX - this.x ;
dy = mouseY - this.y ;

radians = Math.atan2(dy, dx);
angle= radians * 180/Math.PI;

this.rotation = angle + 90;
this.y = mouseY + this.height;
</code>```

The problem with this code is that when you move the mouse away from the center,e.g. the angle is not 90 degrees, there is an offset between the mouse cursor and the object. By tracing, I found out that it follows the y position of the mouse as it should, but by rotating the object, it's height and width is changing, so the object is not pointing right on the cursor.

Is there a way to compensate for this offset? Or maybe another approach?
Thanks in advance.

UPDATE: Ok, it seems that I didn't explain the problem right, sorry, English is not my native language. I need the object to follow the cursor, but the front end of the object to be on the same position as the cursor and the back end of the object to be in the middle of the screen, just on the center x axis. So when you move the mouse, front end of the object will always pointing at and will be on the mouse position. Back end should stay on same position, but rotated.

答:
You don't need to move the object, if you have the correct registration point. You should just rotate it according to the center of the stage.
Use this:

```<code>this.rotation = (Math.atan2(stage.mouseY - stage.stageHeight/2, stage.mouseX - stage.stageWidth/2) / Math.PI) * 180
</code>```

You can download a sample fla from here:
http://rapidshare.com/files/457051556/rotation_mouse.fla

ContentLicense: CC BY-SA 3.0

Title: Problem with rotating object

Body:
I've been having this problem for a while, and it would be great if someone can help. :)

http://img31.imageshack.us/i/problemsc.jpg/
(illustration of the problem)

So, I have this object with registration point at middle bottom. I want this object to follow the mouse, but to remain on the center of the screen while rotating. Here is what I used :

dx = mouseX - this.x ;
dy = mouseY - this.y ;

radians = Math.atan2(dy, dx);
angle= radians * 180/Math.PI;

this.rotation = angle + 90;
this.y = mouseY + this.height;

The problem with this code is that when you move the mouse away from the center,e.g. the angle is not 90 degrees, there is an offset between the mouse cursor and the object. By tracing, I found out that it follows the y position of the mouse as it should, but by rotating the object, it's height and width is changing, so the object is not pointing right on the cursor.

Is there a way to compensate for this offset? Or maybe another approach?
Thanks in advance.

UPDATE: Ok, it seems that I didn't explain the problem right, sorry, English is not my native language. I need the object to follow the cursor, but the front end of the object to be on the same position as the cursor and the back end of the object to be in the middle of the screen, just on the center x axis. So when you move the mouse, front end of the object will always pointing at and will be on the mouse position. Back end should stay on same position, but rotated.

Body:
You don't need to move the object, if you have the correct registration point. You should just rotate it according to the center of the stage.
Use this:

this.rotation = (Math.atan2(stage.mouseY - stage.stageHeight/2, stage.mouseX - stage.stageWidth/2) / Math.PI) * 180

You can download a sample fla from here:
http://rapidshare.com/files/457051556/rotation_mouse.fla


问:
Stretch any number of spans inside div
I have my own carousel and I am trying to make navigations.

.carousel-nav-box {
  width: 100%;
}

.carousel-nav-item {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  width: auto;
  height: 5px;
  margin-left: 2px;
  margin-right: 2px;
  background: black;
  border: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

<div class="carousel-nav-box container">
  <div class="row">
    <span class="col-sm carousel-nav-item"></span>
    <span class="col-sm carousel-nav-item"></span>
  </div>
</div></code>```

Spans inside container are dynamically generated from databse, so it could be any number.
Problem is, that spans just don´t stretch to full width of container and they occupy only part of container. I need to make them on the full width container and make their width automatic depends of their number.

答:
You can you flex to achieve this functionality.
Flex will stretch all child items; and they will stretch if you add flex: 1;

.carousel-nav-box {
  background-color: red;
  width: 100%;
}

.carousel-nav-box .row {
  display: flex;
}

.carousel-nav-item {
  min-height: 50px;
  margin-left: 2px;
  margin-right: 2px;
  background-color: black;
  border: 1px solid green;
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="carousel-nav-box container">
  <div class="row">
    <span class="col-sm carousel-nav-item"></span>
    <span class="col-sm carousel-nav-item"></span>
    <span class="col-sm carousel-nav-item"></span>
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: Stretch any number of spans inside div

Body:
I have my own carousel and I am trying to make navigations.

.carousel-nav-box {
  width: 100%;
}

.carousel-nav-item {
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  width: auto;
  height: 5px;
  margin-left: 2px;
  margin-right: 2px;
  background: black;
  border: green;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

Spans inside container are dynamically generated from databse, so it could be any number.
Problem is, that spans just don´t stretch to full width of container and they occupy only part of container. I need to make them on the full width container and make their width automatic depends of their number.

Body:
You can you flex to achieve this functionality.
Flex will stretch all child items; and they will stretch if you add flex: 1;

.carousel-nav-box {
  background-color: red;
  width: 100%;
}

.carousel-nav-box .row {
  display: flex;
}

.carousel-nav-item {
  min-height: 50px;
  margin-left: 2px;
  margin-right: 2px;
  background-color: black;
  border: 1px solid green;
  flex: 1;
}

<div class="carousel-nav-box container">
  <div class="row">
    <span class="col-sm carousel-nav-item"></span>
    <span class="col-sm carousel-nav-item"></span>
    <span class="col-sm carousel-nav-item"></span>
  </div>
</div>


问:
ImportError: No module named win32com.client
I am currently using python 2.7 and trying to open an Excel sheet.
When using the code below:

```<code>import os
from win32com.client import Dispatch

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = True
# Open the file we want in Excel
workbook = xlApp.Workbooks.Open('example.xls')
</code>```

I get this error:

ImportError: No module named win32com.client

Is there any possibility of getting the error since I am using 64-bit Windows machine?

答:
Had the exact same problem and none of the answers here helped me.
Till I find this thread and post

Short: win32 modules are not guaranted to install correctly with pip.
Install them directly from packages provided by developpers on github.
It works like a charm.

Body:
I am currently using python 2.7 and trying to open an Excel sheet.
When using the code below:

import os
from win32com.client import Dispatch

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = True
# Open the file we want in Excel
workbook = xlApp.Workbooks.Open('example.xls')

I get this error:

ImportError: No module named win32com.client

Is there any possibility of getting the error since I am using 64-bit Windows machine?


问:
Azure Function ignoring https.request
I have an azure function with this line of code.

var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();```
</div>
</div>
</p>

<p>But my code seems to just skip this part of code, with no errors. I am new to Azure and node.js so I might have missed some basic parts in setting this up. </p>

<p>Any ideas?</p>

<p>Edit:
Here is my full code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const https = require('https');
const querystring = require('querystring');

module.exports = async function (context, req) {

    if (req.query.accessCode || (req.body && req.body.accessCode)) {
        context.log('JavaScript HTTP trigger function processed a request.');
        var options = {
            host: 'httpbin.org',
            port: 80,
            path: '/post',
            method: 'POST'
        };

        var postData = querystring.stringify({
            client_id : '1234',
            client_secret: 'xyz',
            code: req.query.accessCode
        });

        var body = "";
        var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();
        context.log("help");
        context.res = {
            status: 200,
            body: "Hello " + (body)
        };
    } else {
       context.res = {
            status: 400,
           body: "Please pass a name on the query string or in the request body"
      };
    }
};</code>```

答:
Solved by doing await properly. Used this as guide.

var https = require('https');
var util = require('util');
const querystring = require('querystring');
var request = require('request')

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    /*if (req.query.name || (req.body && req.body.name)) {*/
    var getOptions = {
        contentType: 'application/json',
        headers: {
            'Authorization': <bearer_token>
         },
    };
    var postData = {
        "key": "value"
    };
    var postOptions = {
        method: 'post',
        body: postData,
        json: true,
        url: <post_url>,
        headers: {
            'Authorization': <bearer_token>
         },
    };
    try{
        var httpPost = await HttpPostFunction(context, postOptions);
        var httpGet = await HttpGetFunction(context, <get_url>, getOptions);
        return {
            res: httpPost
        };
    }catch(err){
       //handle errr
       console.log(err);
    };
};

async function HttpPostFunction(context, options) {
    context.log("Starting HTTP Post Call");
    return new Promise((resolve, reject) => {
        var data = '';
        request(options, function (err, res, body) {
            if (err) {
              console.error('error posting json: ', err)
              reject(err)
            }
            var headers = res.headers;
            var statusCode = res.statusCode;
            //context.log('headers: ', headers);
            //context.log('statusCode: ', statusCode);
            //context.log('body: ', body);
            resolve(body);
          })
    });
};

async function HttpGetFunction(context, url, options) {
    context.log("Starting HTTP Get Call");
    return new Promise((resolve, reject) => {
        var data = '';
        https.get(url, options, (resp) => {
            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            })
            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(JSON.parse(data));
            });
        }).on("error", (err) => {
            console.log("Error: " + err.message);
            reject(err.message);
        });
    });
};```

Title: Azure Function ignoring https.request

Body:
I have an azure function with this line of code.

var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();

But my code seems to just skip this part of code, with no errors. I am new to Azure and node.js so I might have missed some basic parts in setting this up.

Any ideas?

Edit:
Here is my full code

const https = require('https');
const querystring = require('querystring');

module.exports = async function (context, req) {

    if (req.query.accessCode || (req.body && req.body.accessCode)) {
        context.log('JavaScript HTTP trigger function processed a request.');
        var options = {
            host: 'httpbin.org',
            port: 80,
            path: '/post',
            method: 'POST'
        };

        var postData = querystring.stringify({
            client_id : '1234',
            client_secret: 'xyz',
            code: req.query.accessCode
        });

        var body = "";
        var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();
        context.log("help");
        context.res = {
            status: 200,
            body: "Hello " + (body)
        };
    } else {
       context.res = {
            status: 400,
           body: "Please pass a name on the query string or in the request body"
      };
    }
};


问:
Use Test listeners with callTestCase() function
Is it possible to use Test Listeners (@BeforeTestCase and @AfterTestCase) before and after WebUI.callTestCase(…) ?

Or at least, get TestCaseContext after execution of WebUI.callTestCase(...) ?

To do something like :

```<code>TestCaseContext tcc = WebUI.callTestCase(…)
System.out.println(tcc.getStatus())
...
</code>```

Because currently, I don't have any information about the execution...

Thanks a lot,

Regards

答:
No, TestCaseContext, together with @BeforeTestCase and @AfterTestCase refer to the current test case (i.e. caller TC, not callee TC).

What you could do is to create a global variable CalleeStatus and write the status of the callee TC to it in its @AfterTestCase

Callee TC:

```<code>@AfterTestCase
def afterTestcase(TestCaseContext testCaseContext) {
    GlobalVariable.calleeStatus = testCaseContext..getTestCaseStatus()
    WebUI.closeBrowser()
}
</code>```

Caller TC:

```<code>WebUI.callTestCase(…)
println(GlobalVariable.calleeStatus)
</code>```

Body:
Is it possible to use Test Listeners (@BeforeTestCase and @AfterTestCase) before and after WebUI.callTestCase(…) ?

Or at least, get TestCaseContext after execution of WebUI.callTestCase(...) ?

To do something like :

TestCaseContext tcc = WebUI.callTestCase(…)
System.out.println(tcc.getStatus())
...

Because currently, I don't have any information about the execution...

Thanks a lot,

Regards

Body:
No, TestCaseContext, together with @BeforeTestCase and @AfterTestCase refer to the current test case (i.e. caller TC, not callee TC).

What you could do is to create a global variable CalleeStatus and write the status of the callee TC to it in its @AfterTestCase

Callee TC:

@AfterTestCase
def afterTestcase(TestCaseContext testCaseContext) {
    GlobalVariable.calleeStatus = testCaseContext..getTestCaseStatus()
    WebUI.closeBrowser()
}

Caller TC:

WebUI.callTestCase(…)
println(GlobalVariable.calleeStatus)


问:
SqlAlchemy Foreign Key propagating down 3 layers
I am trying to update a simple 3 layer relational set of tables.

They are

Parent

Child

GrandChild

The SQLAlchemy code for the model looks like

```<code>class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    children = relationship("Child", back_populates="parents")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    parent_id = Column(Integer, ForeignKey('parent.id'))
    parents = relationship("Parent", back_populates="children")
    grandchildren = relationship("GrandChild",
                                back_populates="grandparent",
                                 )

class GrandChild(Base):
    __tablename__ = 'grandchild'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    parent_id = Column(Integer, ForeignKey('parent.id'))
    child_id = Column(Integer, ForeignKey('child.id'))
    grandparent = relationship("Child", back_populates="grandchildren")
</code>```

And the Insert code looks like this....

```<code>p3 = Parent(name="P3")
c5 = Child(name="C5")
c6 = Child(name="C6")
gc1 = GrandChild(name="gc1")
gc2 = GrandChild(name="gc2")
gc3 = GrandChild(name="gc3")
gc4 = GrandChild(name="gc4")

p3.children = [c5, c6]
c5.grandchildren = [gc1]
c6.grandchildren = [gc2,  gc3, gc4]

session.add_all([p2, p3])

session.commit()
</code>```

The record is added - and Parent/Child are correctly linked - but GrandChildren are missing the Parent foreign key.

I have struggled in finding the correct mechanism to add this - can anyone point me in the right direction ?

答:
You don't create the relation between grandchilds and parents.
The relationship between a grandchild and a parent isn't implicit in your data model; the parent of a child doesn't automatically become the parent of all the child's grandchildren.

You have to define that relationship explicitly, i.e. add it to the GrandChild:

```<code>class GrandChild(Base):
    [...]
    parent = relationship("Parent")
</code>```

and then create the relation on the instances:

```<code>gc1.parent = p3
gc2.parent = p3
gc3.parent = p3
gc4.parent = p3
</code>```

This will add the records accordingly:

```<code>sqlalchemy.engine.base.Engine INSERT INTO grandchild (name, parent_id, child_id) VALUES (?, ?, ?)
sqlalchemy.engine.base.Engine ('gc1', 1, 1)
[...]
</code>```

However, since the parent-child relationship in your data model doesn't imply any grandchild-parent relationship, you can create a parent without children, that has  grandchildren.

```<code>sink = Parent(name="SINK")
gc1.parent = sink

print("Name: {}, Parent: {}, Parent.children: {}, Child.parent: {}"
      .format(gc1.name, gc1.parent.name, gc1.parent.children, gc1.grandparent.parents.name))
# Name: gc1, Parent: SINK, Parent.children: [], Child.parent: P3
</code>```

Based on my understanding of a three-tier-relation, I can't think of a use case where sth. like this would find an application.

If you want an implicit and consistent relationship between an parent and a grandchild through a child, drop the direct relationship between parent and grandchild:

```<code>class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    children = relationship("Child", back_populates="parent")

    def __repr__(self):
        return "{}(name={})".format(self.__class__.__name__, self.name)

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    parent_id = Column(Integer, ForeignKey('parent.id'))
    parent = relationship("Parent", back_populates="children")
    children = relationship("GrandChild", back_populates="parent")

    # same __repr__()

class GrandChild(Base):
    __tablename__ = 'grandchild'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    child_id = Column(Integer, ForeignKey('child.id'))
    parent = relationship("Child", back_populates="children")

    # same __repr__()

p3 = Parent(name="P3")
c5 = Child(name="C5")
gc1 = GrandChild(name="gc1")
p3.children = [c5]
c5.children = [gc1]
</code>```

You can access the grandchild's grandparent through:

```<code>print(gc1.parent.parent)
# Parent(name=P3)
</code>```

The other way around is a bit more tedious though, due to the two one-to-many relationships in the hierarchy:

```<code>for child in p3.children:
    for gc in child.children:
        print(p3, child, gc)
# Parent(name=P3) Child(name=C5) GrandChild(name=gc1)
</code>```

Body:
I am trying to update a simple 3 layer relational set of tables.

They are

Parent

Child

GrandChild

The SQLAlchemy code for the model looks like

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    children = relationship("Child", back_populates="parents")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    parent_id = Column(Integer, ForeignKey('parent.id'))
    parents = relationship("Parent", back_populates="children")
    grandchildren = relationship("GrandChild",
                                back_populates="grandparent",
                                 )

class GrandChild(Base):
    __tablename__ = 'grandchild'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    parent_id = Column(Integer, ForeignKey('parent.id'))
    child_id = Column(Integer, ForeignKey('child.id'))
    grandparent = relationship("Child", back_populates="grandchildren")

And the Insert code looks like this....

p3 = Parent(name="P3")
c5 = Child(name="C5")
c6 = Child(name="C6")
gc1 = GrandChild(name="gc1")
gc2 = GrandChild(name="gc2")
gc3 = GrandChild(name="gc3")
gc4 = GrandChild(name="gc4")

p3.children = [c5, c6]
c5.grandchildren = [gc1]
c6.grandchildren = [gc2,  gc3, gc4]

session.add_all([p2, p3])

session.commit()

The record is added - and Parent/Child are correctly linked - but GrandChildren are missing the Parent foreign key.

I have struggled in finding the correct mechanism to add this - can anyone point me in the right direction ?

Body:
You don't create the relation between grandchilds and parents.
The relationship between a grandchild and a parent isn't implicit in your data model; the parent of a child doesn't automatically become the parent of all the child's grandchildren.

You have to define that relationship explicitly, i.e. add it to the GrandChild:

class GrandChild(Base):
    [...]
    parent = relationship("Parent")

and then create the relation on the instances:

gc1.parent = p3
gc2.parent = p3
gc3.parent = p3
gc4.parent = p3

This will add the records accordingly:

sqlalchemy.engine.base.Engine INSERT INTO grandchild (name, parent_id, child_id) VALUES (?, ?, ?)
sqlalchemy.engine.base.Engine ('gc1', 1, 1)
[...]

However, since the parent-child relationship in your data model doesn't imply any grandchild-parent relationship, you can create a parent without children, that has  grandchildren.

sink = Parent(name="SINK")
gc1.parent = sink

print("Name: {}, Parent: {}, Parent.children: {}, Child.parent: {}"
      .format(gc1.name, gc1.parent.name, gc1.parent.children, gc1.grandparent.parents.name))
# Name: gc1, Parent: SINK, Parent.children: [], Child.parent: P3

Based on my understanding of a three-tier-relation, I can't think of a use case where sth. like this would find an application.

If you want an implicit and consistent relationship between an parent and a grandchild through a child, drop the direct relationship between parent and grandchild:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    children = relationship("Child", back_populates="parent")

    def __repr__(self):
        return "{}(name={})".format(self.__class__.__name__, self.name)

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    parent_id = Column(Integer, ForeignKey('parent.id'))
    parent = relationship("Parent", back_populates="children")
    children = relationship("GrandChild", back_populates="parent")

    # same __repr__()

class GrandChild(Base):
    __tablename__ = 'grandchild'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    child_id = Column(Integer, ForeignKey('child.id'))
    parent = relationship("Child", back_populates="children")

    # same __repr__()

p3 = Parent(name="P3")
c5 = Child(name="C5")
gc1 = GrandChild(name="gc1")
p3.children = [c5]
c5.children = [gc1]

You can access the grandchild's grandparent through:

print(gc1.parent.parent)
# Parent(name=P3)

The other way around is a bit more tedious though, due to the two one-to-many relationships in the hierarchy:

for child in p3.children:
    for gc in child.children:
        print(p3, child, gc)
# Parent(name=P3) Child(name=C5) GrandChild(name=gc1)


问:
Can i create a new zone for my sub-submenu?
I'm actually making a menu for my homework, but I'm not really good at JS, and I want to extend my sub-submenu with an hover on a new "window"

I already tried to do it only in CSS/HTML but thats didn't work

https://codepen.io/anon/pen/JqBRGZ

```<code><body>
  <div class="area-x"></div>
  <nav class="main-menu" id="accordian">
     <div>
        <ul>
           <li id="menu1">
              <h3><i class="fa fa-user fa-2x"></i><span class="nav-text">Client</span></h3>
              <ul>
                 <li><a href="#" id="menu2">test</a>
                    <ul>
                       <li id="menu3">
                          <a href="#">test11111111111</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                       </li>
                    </ul>
                 </li>
                 <li><a href="#" id="menu2">test</a>
                    <ul>
                       <li id="menu3">
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                          <a href="#">test1</a>
                       </li>
                    </ul>
                 </li>
              </ul>
           </li>
</code>```

I think I can do what I want with javascript, but I didn't find on the internet what I want, tuto or something like that, so if you can help me and explain, that's will be great.

答:
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:150);

.fa-2x {
 font-size: 2em;
}

.fa {
 position: relative;
 display: table-cell;
 width: 60px;
 height: 36px;
 text-align: center;
 vertical-align: middle;
 font-size:20px;
}

.main-menu:hover,nav.main-menu.expanded {
 width:250px;
 overflow:visible;
}

.main-menu {
 background: #1f67f1;
 border-right:1px solid #e5e5e5;
 position:absolute;
 top:0;
 bottom:0;
 height:100%;
 left:0;
 width:60px;
 overflow:hidden;
 -webkit-transition:width .05s linear;
 transition:width .05s linear;
 -webkit-transform:translateZ(0) scale(1,1);
 z-index:1000;
}

.main-menu>ul {
 margin:7px 0;
}

.main-menu li {
 position:relative;
 display:block;
 width:250px;
}

.main-menu li>h3 {
 margin-top: 0px;
 position:relative;
 display:table;
 border-collapse:collapse;
 border-spacing:0;
 color:white;
  font-family: arial;
 font-size: 14px;
 text-decoration:none;
 -webkit-transform:translateZ(0) scale(1,1);
 -webkit-transition:all .1s linear;
 transition:all .1s linear;
 margin: 0px;
}

.main-menu .nav-icon {
 position:relative;
 display:table-cell;
 width:60px;
 height:36px;
 text-align:center;
 vertical-align:middle;
 font-size:18px;
}

.main-menu .nav-text {
 position:relative;
 display:table-cell;
 vertical-align:middle;
 width:190px;
 font-family: 'Titillium Web', sans-serif;
}

.main-menu>ul.logout {
 position:absolute;
 left:0;
 bottom:0;
}

.no-touch .scrollable.hover {
 overflow-y:hidden;
}

.no-touch .scrollable.hover:hover {
 overflow-y:auto;
 overflow:visible;
}

h3:hover,h3:focus {
 text-decoration:none;
}

nav {
 -webkit-user-select:none;
 -moz-user-select:none;
 -ms-user-select:none;
 -o-user-select:none;
 user-select:none;
}

nav ul,nav li {
 outline:0;
 margin:0;
 padding:0;
}

.main-menu li:hover>a,nav.main-menu li.active>h3,.dropdown-menu>li>h3:hover,.dropdown-menu>li>h3:focus,.dropdown-menu>.active>h3,.dropdown-menu>.active>h3:hover,.dropdown-menu>.active>h3:focus,.no-touch .dashboard-page nav.dashboard-menu ul li:hover h3,.dashboard-page nav.dashboard-menu ul li.active h3 {
 color:#fff;
 background-color: #1f67f1;
}

.area {
 float: left;
 background: #e2e2e2;
 width: 100%;
 height: 100%;
}

#accordian ul ul {
 display: none;
}

#accordian li.active ul {
 display: block;
}

#menu2 {
 margin-left: 110px;
 color: white;
 text-decoration: none;
 font-size: 18px;
 font-family: 'Titillium Web', sans-serif;
}

#menu1:hover h3 {
 color:#fff;
 background-color:#5fa2db;
}

#menu2 a:hover {
    color:#fff;
 background-color:#5fa2db;
}

#menu2 ul li{
 position: relative;
}

#menu1 ul li:hover > ul{
 left: -100px;
 top:0px;
}

#menu2 ul li:hover > a{
 color:#fff;
 background-color:#5fa2db;
 cursor: pointer;
 display: block;
}

#menu1 li:hover ul ul {
 display:none;
}

#menu1 li:hover ul {
 display:block;
}

#menu3 a {
    display:block;
 margin-left:200px;
 text-decoration: none;
 color: #FFF;
 overflow: visible;
}

.main-menu #menu3 a:hover{
 color:#fff;
 background-color:#5fa2db;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml2/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">
   <head>
      <meta charset='utf-8' />
      <meta http-equiv="X-UA-Compatible" content="IE=11" />
      <link rel="stylesheet" href="font-awesome-4.7.0/css/font-awesome.min.css">
      <link rel="stylesheet" href="icons/css/unicons.css">
      <link rel="stylesheet" href="style.css">
      <script>
         function afficheMenu(obj){
         var idMenu     = obj.id;
         var idSousMenu = 'sous' + idMenu;
         var sousMenu   = document.getElementById(idSousMenu);
         /*****************************************************/
         /** si le sous-menu correspondant au menu cliqué    **/
         /** est caché alors on l'affiche, sinon on le cache **/
         /*****************************************************/
         if(sousMenu.style.display == "none"){
         sousMenu.style.display = "block";
         }
         else{
         sousMenu.style.display = "none";
         }
         }
      </script>
   </head>
   <body>
      <div class="area-x"></div>
      <nav class="main-menu" id="accordian">
         <div>
            <ul>
               <li id="menu1">
                  <h3><i class="fa fa-user fa-2x"></i><span class="nav-text">Client</span></h3>
                  <ul>
                     <li>test
                        <ul>
                           <li id="menu3">
                              test11111111111
                              test1
                              test1
                              test1
                              test1
                              test1
                              test1
                              test1
                              test1
                              test1
                           </li>
                        </ul>
                     </li>
                     <li>test
                        <ul>
                           <li id="menu3">
                              test1
                              test1
                              test1
                              test1
                           </li>
                        </ul>
                     </li>
                  </ul>
               </li>

               <li class="has-subnav" id="menu1">
                  <h3><i class="fa fa-user fa-2x"></i><span class="nav-text">Conducteur</span></h3>
                  <ul>
                     <li>test
                        <ul>
                           <li id="menu3">
                              test1
                              test1
                              test1
                              test1
                              test1
                              test1
                           </li>
                        </ul>
                     </li>
                     <li>test</li>
                  </ul>
               </li>

               <li class="has-subnav" id="menu1">
                  <h3><i class="fa fa-bus fa-2x"></i><span class="nav-text">Autocar</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-file-text-o fa-2x"></i><span class="nav-text">Devis</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-table fa-2x"></i><span class="nav-text">Billet</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-file fa-2x"></i><span class="nav-text">Bons Factures</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-file-text fa-2x"></i><span class="nav-text">Factures Diverses</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-binoculars fa-2x"></i><span class="nav-text">Recherche avancée...</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-home fa-2x"></i><span class="nav-text">Export des ventes</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-credit-card fa-2x"></i><span class="nav-text">Saisie des Règlements</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-bars fa-2x"></i><span class="nav-text">Gestion des bordereaux</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-list fa-2x"></i><span class="nav-text">Factures non soldées</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-thumbs-o-up fa-2x"></i><span class="nav-text">Export des Règlements</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-thumbs-up fa-2x"></i><span class="nav-text">Export des bordereaux</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-laptop fa-2x"></i><span class="nav-text">Modèles Hebdomadaires</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-tasks fa-2x"></i><span class="nav-text">Lignes Règulières</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-calendar fa-2x"></i><span class="nav-text">Affichage Planning</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-bar-chart fa-2x"></i><span class="nav-text">Statistiques</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-binoculars fa-2x"></i><span class="nav-text">Recherche avancée by evnt</span></h3>
                  <ul>
                     <li>test</li>
                     <li>test</li>
                  </ul>
               </li>
               </ul>
         </div>
         <ul class="logout">
            <li>     <h3><i class="fa fa-power-off fa-2x"></i>  <span class="nav-text">Quitter Carmagic</span></h3></li>
         </ul>
      </nav>
      </div>
   </body>
</html>
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js" type="text/javascript" type="text/javascript"></script>
<!-- JQuery -->
<script src="http://thecodeplayer.com/uploads/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script>
   $(document).ready(function(){
    $("#accordian h3").click(function(){
     $("#accordian ul ul").slideUp();
     if(!$(this).next().is(":visible"))
     {
      $(this).next().slideDown();
     }
    })
   })
</script>

<script>
   $(document).ready(function(){
      $("#menu2").hover(function(){

      })
   })
</script></code>```

i dont know why, but my js didnt work on stack overflow

Body:
I'm actually making a menu for my homework, but I'm not really good at JS, and I want to extend my sub-submenu with an hover on a new "window"

I already tried to do it only in CSS/HTML but thats didn't work

https://codepen.io/anon/pen/JqBRGZ

Client

test

                          test11111111111
                          test1
                          test1
                          test1
                          test1
                          test1
                          test1
                          test1
                          test1
                          test1

test

                          test1
                          test1
                          test1
                          test1

I think I can do what I want with javascript, but I didn't find on the internet what I want, tuto or something like that, so if you can help me and explain, that's will be great.

Body:
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:150);

.fa-2x {
 font-size: 2em;
}

.fa {
 position: relative;
 display: table-cell;
 width: 60px;
 height: 36px;
 text-align: center;
 vertical-align: middle;
 font-size:20px;
}

.main-menu:hover,nav.main-menu.expanded {
 width:250px;
 overflow:visible;
}

.main-menu {
 background: #1f67f1;
 border-right:1px solid #e5e5e5;
 position:absolute;
 top:0;
 bottom:0;
 height:100%;
 left:0;
 width:60px;
 overflow:hidden;
 -webkit-transition:width .05s linear;
 transition:width .05s linear;
 -webkit-transform:translateZ(0) scale(1,1);
 z-index:1000;
}

.main-menu>ul {
 margin:7px 0;
}

.main-menu li {
 position:relative;
 display:block;
 width:250px;
}

.main-menu li>h3 {
 margin-top: 0px;
 position:relative;
 display:table;
 border-collapse:collapse;
 border-spacing:0;
 color:white;
  font-family: arial;
 font-size: 14px;
 text-decoration:none;
 -webkit-transform:translateZ(0) scale(1,1);
 -webkit-transition:all .1s linear;
 transition:all .1s linear;
 margin: 0px;
}

.main-menu .nav-icon {
 position:relative;
 display:table-cell;
 width:60px;
 height:36px;
 text-align:center;
 vertical-align:middle;
 font-size:18px;
}

.main-menu .nav-text {
 position:relative;
 display:table-cell;
 vertical-align:middle;
 width:190px;
 font-family: 'Titillium Web', sans-serif;
}

.main-menu>ul.logout {
 position:absolute;
 left:0;
 bottom:0;
}

.no-touch .scrollable.hover {
 overflow-y:hidden;
}

.no-touch .scrollable.hover:hover {
 overflow-y:auto;
 overflow:visible;
}

h3:hover,h3:focus {
 text-decoration:none;
}

nav {
 -webkit-user-select:none;
 -moz-user-select:none;
 -ms-user-select:none;
 -o-user-select:none;
 user-select:none;
}

nav ul,nav li {
 outline:0;
 margin:0;
 padding:0;
}

.main-menu li:hover>a,nav.main-menu li.active>h3,.dropdown-menu>li>h3:hover,.dropdown-menu>li>h3:focus,.dropdown-menu>.active>h3,.dropdown-menu>.active>h3:hover,.dropdown-menu>.active>h3:focus,.no-touch .dashboard-page nav.dashboard-menu ul li:hover h3,.dashboard-page nav.dashboard-menu ul li.active h3 {
 color:#fff;
 background-color: #1f67f1;
}

.area {
 float: left;
 background: #e2e2e2;
 width: 100%;
 height: 100%;
}

#accordian ul ul {
 display: none;
}

#accordian li.active ul {
 display: block;
}

#menu2 {
 margin-left: 110px;
 color: white;
 text-decoration: none;
 font-size: 18px;
 font-family: 'Titillium Web', sans-serif;
}

#menu1:hover h3 {
 color:#fff;
 background-color:#5fa2db;
}

#menu2 a:hover {
    color:#fff;
 background-color:#5fa2db;
}

#menu2 ul li{
 position: relative;
}

#menu1 ul li:hover > ul{
 left: -100px;
 top:0px;
}

#menu2 ul li:hover > a{
 color:#fff;
 background-color:#5fa2db;
 cursor: pointer;
 display: block;
}

#menu1 li:hover ul ul {
 display:none;
}

#menu1 li:hover ul {
 display:block;
}

#menu3 a {
    display:block;
 margin-left:200px;
 text-decoration: none;
 color: #FFF;
 overflow: visible;
}

.main-menu #menu3 a:hover{
 color:#fff;
 background-color:#5fa2db;
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml2/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">
   <head>
      <meta charset='utf-8' />
      <meta http-equiv="X-UA-Compatible" content="IE=11" />
      <link rel="stylesheet" href="font-awesome-4.7.0/css/font-awesome.min.css">
      <link rel="stylesheet" href="icons/css/unicons.css">
      <link rel="stylesheet" href="style.css">
      <script>
         function afficheMenu(obj){
         var idMenu     = obj.id;
         var idSousMenu = 'sous' + idMenu;
         var sousMenu   = document.getElementById(idSousMenu);
         /*****************************************************/
         /** si le sous-menu correspondant au menu cliqué    **/
         /** est caché alors on l'affiche, sinon on le cache **/
         /*****************************************************/
         if(sousMenu.style.display == "none"){
         sousMenu.style.display = "block";
         }
         else{
         sousMenu.style.display = "none";
         }
         }
      </script>
   </head>
   <body>
      <div class="area-x"></div>
      <nav class="main-menu" id="accordian">
         <div>
            <ul>
               <li id="menu1">
                  <h3><i class="fa fa-user fa-2x"></i><span class="nav-text">Client</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a>
                        <ul>
                           <li id="menu3">
                              <a href="#">test11111111111</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                           </li>
                        </ul>
                     </li>
                     <li><a href="#" id="menu2">test</a>
                        <ul>
                           <li id="menu3">
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                           </li>
                        </ul>
                     </li>
                  </ul>
               </li>

               <li class="has-subnav" id="menu1">
                  <h3><i class="fa fa-user fa-2x"></i><span class="nav-text">Conducteur</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a>
                        <ul>
                           <li id="menu3">
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                              <a href="#">test1</a>
                           </li>
                        </ul>
                     </li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li class="has-subnav" id="menu1">
                  <h3><i class="fa fa-bus fa-2x"></i><span class="nav-text">Autocar</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-file-text-o fa-2x"></i><span class="nav-text">Devis</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-table fa-2x"></i><span class="nav-text">Billet</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-file fa-2x"></i><span class="nav-text">Bons Factures</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-file-text fa-2x"></i><span class="nav-text">Factures Diverses</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-binoculars fa-2x"></i><span class="nav-text">Recherche avancée...</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-home fa-2x"></i><span class="nav-text">Export des ventes</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-credit-card fa-2x"></i><span class="nav-text">Saisie des Règlements</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-bars fa-2x"></i><span class="nav-text">Gestion des bordereaux</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-list fa-2x"></i><span class="nav-text">Factures non soldées</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-thumbs-o-up fa-2x"></i><span class="nav-text">Export des Règlements</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-thumbs-up fa-2x"></i><span class="nav-text">Export des bordereaux</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-laptop fa-2x"></i><span class="nav-text">Modèles Hebdomadaires</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-tasks fa-2x"></i><span class="nav-text">Lignes Règulières</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-calendar fa-2x"></i><span class="nav-text">Affichage Planning</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-bar-chart fa-2x"></i><span class="nav-text">Statistiques</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>

               <li id="menu1">
                  <h3><i class="fa fa-binoculars fa-2x"></i><span class="nav-text">Recherche avancée by evnt</span></h3>
                  <ul>
                     <li><a href="#" id="menu2">test</a></li>
                     <li><a href="#" id="menu2">test</a></li>
                  </ul>
               </li>
               </ul>
         </div>
         <ul class="logout">
            <li>     <h3><i class="fa fa-power-off fa-2x"></i>  <span class="nav-text">Quitter Carmagic</span></h3></li>
         </ul>
      </nav>
      </div>
   </body>
</html>
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js" type="text/javascript" type="text/javascript"></script>
<!-- JQuery -->
<script src="http://thecodeplayer.com/uploads/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script>
   $(document).ready(function(){
    $("#accordian h3").click(function(){
     $("#accordian ul ul").slideUp();
     if(!$(this).next().is(":visible"))
     {
      $(this).next().slideDown();
     }
    })
   })
</script>

<script>
   $(document).ready(function(){
      $("#menu2").hover(function(){

      })
   })
</script>

i dont know why, but my js didnt work on stack overflow


问:
Generic way to update pojos via getters and setters
Let's say I have POJO with getters and setters of different types. I want to write some generic algorithm for updating data from one to another based on just defining getters and setters via lambdas.
I'm trying to create it this way

```<code>private static final Map<Function<Entity, Object>, BiConsumer<Entity, Object>> ACCESSORS = new HashMap
        <Function<Entity, Object>, BiConsumer<Entity, Object>>() {{
    put(Entity::getAreaCode, Entity::setAreaCode);
}});
</code>```

Then I go through all entries applying target entity to them and if result of getter is not null then I want to apply corresponding setter for other entity.

But it won't work because Object is not castable to String. And I want to use it for different types not only String but also Integers, etc...

Is is solvable in some simple approach without creating special converter and associate it with every entry?

答:
I know you already have an answer but for anyone needing something like this in the future: I have developed a small library around this context - datus.

Here is an example which shows some of its features:

```<code>class Person {
  //getters + setters omitted for brevity
  private String firstName;
  private String lastName;
}

class PersonDTO {
  //getters + setters + empty constructor omitted for brevity
  private String firstName;
  private String lastName;
}

  //the mutable API defines a mapping process by multiple getter-setter steps
  Mapper<Person, PersonDTO> mapper = Datus.forTypes(Person.class, PersonDTO.class).mutable(PersonDTO::new)
      .from(Person::getFirstName).into(PersonDTO.setFirstName)
      .from(Person::getLastName)
      .given(Objects::nonNull, ln -> ln.toUpperCase()).orElse("fallback")
      .into(PersonDTO::setLastName)
      .from(/*...*/).into(/*...*/)
      .build();

  Person person = new Person();
person.setFirstName("firstName");
    person.setLastName(null);
    PersonDTO personDto = mapper.convert(person);
/*
    personDto = PersonDTO [
        firstName = "firstName",
        lastName = "fallback"
    ]
*/
    person.setLastName("lastName");
    personDto = mapper.convert(person);
/*
    personDto = PersonDTO [
        firstName = "firstName",
        lastName = "LASTNAME"
    ]
*/
</code>```

Body:
Let's say I have POJO with getters and setters of different types. I want to write some generic algorithm for updating data from one to another based on just defining getters and setters via lambdas.
I'm trying to create it this way

private static final Map<Function<Entity, Object>, BiConsumer<Entity, Object>> ACCESSORS = new HashMap
        <Function<Entity, Object>, BiConsumer<Entity, Object>>() {{
    put(Entity::getAreaCode, Entity::setAreaCode);
}});

Then I go through all entries applying target entity to them and if result of getter is not null then I want to apply corresponding setter for other entity.

But it won't work because Object is not castable to String. And I want to use it for different types not only String but also Integers, etc...

Is is solvable in some simple approach without creating special converter and associate it with every entry?

Body:
I know you already have an answer but for anyone needing something like this in the future: I have developed a small library around this context - datus.

Here is an example which shows some of its features:

class Person {
  //getters + setters omitted for brevity
  private String firstName;
  private String lastName;
}

class PersonDTO {
  //getters + setters + empty constructor omitted for brevity
  private String firstName;
  private String lastName;
}

  //the mutable API defines a mapping process by multiple getter-setter steps
  Mapper<Person, PersonDTO> mapper = Datus.forTypes(Person.class, PersonDTO.class).mutable(PersonDTO::new)
      .from(Person::getFirstName).into(PersonDTO.setFirstName)
      .from(Person::getLastName)
      .given(Objects::nonNull, ln -> ln.toUpperCase()).orElse("fallback")
      .into(PersonDTO::setLastName)
      .from(/*...*/).into(/*...*/)
      .build();

  Person person = new Person();
person.setFirstName("firstName");
    person.setLastName(null);
    PersonDTO personDto = mapper.convert(person);
/*
    personDto = PersonDTO [
        firstName = "firstName",
        lastName = "fallback"
    ]
*/
    person.setLastName("lastName");
    personDto = mapper.convert(person);
/*
    personDto = PersonDTO [
        firstName = "firstName",
        lastName = "LASTNAME"
    ]
*/


问:
casein admin user got error when running project
I'm using casein gem in my project

all around my app I give casein error in casein/admin_user.rb model that says:
NoMethodError: undefined method 'validate_email_field=' for #<Class:xxxxxx>
Did you mean?  validates_numericality_of

whats the problem?

casein version: 5.3.0

ruby version: jruby 9.2.5.0

rails version: 5.2.1

答: Use Casein version 5.4.0 because 5.3.0 version is not compatible with this rails version.</p>


问:
Subdomain cookie sharing in Rails 3 is not working (on Heroku)?
I'm trying to have cookies on my site dapshare.com work for both the root address and the 'www' subdomain.

A lot of other stackoverflow answers (and the great Railscasts vid on this topic) have suggested adding this line to session_store.rb:

```<code>Dapshare::Application.config.session_store :cookie_store, :key => '_dapshare_session', :domain => :all
</code>```

This doesn't seem to make a difference: if I log in at dapshare.com, I still am not logged in at www.dapshare.com.

Am I doing something wrong here? I am using the following code to store information in the cookie:

```<code>cookies.permanent.signed[:thing_to_store] = store_information
</code>```

Thanks for any help!

答:
I encountered this issue, when passing :all doesn't seems to work properly. If you want to use only for subdomains try the following:</p>

```<code>Dapshare::Application.config.session_store :cookie_store, :key => '_dapshare_session', :domain => '.dapshare.com'
</code>```

Body:
I'm trying to have cookies on my site dapshare.com work for both the root address and the 'www' subdomain.

A lot of other stackoverflow answers (and the great Railscasts vid on this topic) have suggested adding this line to session_store.rb:

Dapshare::Application.config.session_store :cookie_store, :key => '_dapshare_session', :domain => :all

This doesn't seem to make a difference: if I log in at dapshare.com, I still am not logged in at www.dapshare.com.

Am I doing something wrong here? I am using the following code to store information in the cookie:

cookies.permanent.signed[:thing_to_store] = store_information

Thanks for any help!

Body:
I encountered this issue, when passing :all doesn't seems to work properly. If you want to use only for subdomains try the following:

Dapshare::Application.config.session_store :cookie_store, :key => '_dapshare_session', :domain => '.dapshare.com'


问:
javascript find object in array by value and append additional value
I think the title explains it well enough. I've got an array that has two values per object and I need to look up the object by one of those values then assign a third to it.

Here are the guts:

```<code>$slides.push({
    img: el.attr('href'),
    desc: el.attr('title').split('Photo #')[1]
});
</code>```

Which builds an array as such:

```<code>Object
    desc: 127
    img: img/aaron1.jpg
Object
    desc: 128
    img: img/aaron2.jpg
</code>```

I'd like to look up the desc value, then assign a third value of in: yes

```<code>$slides.findInArray('desc', '127').addValueToObject('in','yes')
</code>```

答:
With modern JS it can be simply done:</p>

```<code>var obj = $slides.find(e => e.desc === '127');
if (obj) {
    obj.in = 'yes';
}
</code>```

Body:
I think the title explains it well enough. I've got an array that has two values per object and I need to look up the object by one of those values then assign a third to it.

Here are the guts:

$slides.push({
    img: el.attr('href'),
    desc: el.attr('title').split('Photo #')[1]
});

Which builds an array as such:

Object
    desc: 127
    img: img/aaron1.jpg
Object
    desc: 128
    img: img/aaron2.jpg

I'd like to look up the desc value, then assign a third value of in: yes

$slides.findInArray('desc', '127').addValueToObject('in','yes')

Body:
With modern JS it can be simply done:

var obj = $slides.find(e => e.desc === '127');
if (obj) {
    obj.in = 'yes';
}


问:
Python multiprocessing - reassigning jobs dynamically from pool - without async?
So I have a batch of 1000 tasks that I assign using parmap/python multiprocessing module to 8 cores (dual xeon machine 16 physical cores). Currently this runs using synchronized.

The issue is that usually 1 of the cores lags well behind the other cores and still has several jobs/tasks to complete after all the other cores  finished their work. This may be related to core speed (older computer) but more likely due to some of the tasks being more difficult than others - so the 1 core that gets the slightly more difficult jobs gets laggy...

I'm a little confused here - but is this what asynch parallelization does?  I've tried using it before, but because this step is part of a very large processing step - it wasn't clear how to create a barrier to force the program to wait until all async processes are done.

Any advice/links to similar questions/answers are appreciated.

[EDIT] To clarify, the processes are ok to run independently, they all save data to disk and do not share variables.

答:
parmap author here

By default, both in multiprocessing and in parmap, tasks are divided in chunks and chunks are sent to each multiprocessing process (see the multiprocessing documentation). The reason behind this is that sending tasks individually to a process would introduce significant computational overhead in many situations. The overhead is reduced if several tasks are sent at once, in chunks.

The number of tasks on each chunk is controlled with chunksize in multiprocessing (and pm_chunksize in parmap). By default, chunksize is computed as "number of tasks"/(4*"pool size"), rounded up (see the multiprocessing source code). So for your case, 1000/(4*4) = 62.5 -> 63 tasks per chunk.

If, as in your case, many computationally expensive tasks fall into the same chunk, that chunk will take a long time to finish.

One "cheap and easy" way to workaround this is to pass a smaller chunksize value. Note that using the extreme chunksize=1 may introduce undesired larger cpu overhead.

A proper queuing system as suggested in other answers is a better solution on the long term, but maybe an overkill for a one-time problem.


问:
Extending python - to swig, not to swig or Cython
I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance.

With the help of swig you almost don't need to care about arguments etc. Everything works fine.

Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwigObject' before calling the actual .pyd or .so code.

Does anyone of you have any experience whether there is some more performance to gain if you hand-write this file or let swig do it.

答:
There is an article worth reading on the topic Cython, pybind11, cffi – which tool should you choose?

Quick recap for the impatient:

Cython compiles your python to C/C++ allowing you to embed your C/C++ into python code. Uses static binding. For python programmers.

pybind11 (and boost.python) is the opposite. Bind your stuff at compile time from the C++ side. For C++ programmers.

CFFI allows you to bind the native stuff dynamically at runtime. Simple to use, but higher performance penalty.

OwnerDisplayName: RSabet

LastEditorDisplayName: John Mulder


问:
PHP mkdir() Invalid Path
I'm trying to save files on my server, and as a prerequisite, create directories that don't exist.

I am running a script, dl.php, at /home/public_html/www3/scripts/dl.php:

```<code>$request['savedir'] = '/home/public_html/www3/scripts/images/logs';
if( !is_dir($request['savedir']) )
    mkdir($request['savedir']);
</code>```

And I get:

```<code>Warning: mkdir(): Invalid path in /home/public_html/www3/scripts/dl.php
</code>```

The "images" does exist.

答:
Open the config.php on application/config folder

Browse all the way down to the $config['sess_save_path'] =  NULL; line.

Change the NULL value to BASEPATH.'sessions'

Title: PHP mkdir() Invalid Path

Body:
I'm trying to save files on my server, and as a prerequisite, create directories that don't exist.

I am running a script, dl.php, at /home/public_html/www3/scripts/dl.php:

$request['savedir'] = '/home/public_html/www3/scripts/images/logs';
if( !is_dir($request['savedir']) )
    mkdir($request['savedir']);

And I get:

Warning: mkdir(): Invalid path in /home/public_html/www3/scripts/dl.php

The "images" does exist.


问:
All frequencies of my bar plot are the same height?
Trying to barplot a CSV file and the plot shows all categories as the same height despite the frequencies varying from 450-800

Below is the plot I receive

!https://imgur.com/9HZuiaK

I have tried implementing a height=x, width=x
This results in completely removing the labels and does not fix the initial problem.

```<code>setwd("~/Desktop")
causes<-read.csv('causes.csv')
head(causes)

table(causes$Intentional.self.harm..suicide)

barplot(table(causes$Intentional.self.harm..suicide))
barplot(table(causes$Intentional.self.harm..suicide), ylab='Frequency',
        main='Barplot of Intentional self-harm (suicide)', col='lightblue'

dput(head(causes, 20))

Intentional.self.harm..suicide. = c(535L,
579L, 480L, 541L, 499L, 537L, 466L, 453L, 459L, 494L, 520L, 553L,
525L, 588L, 578L, 631L, 676L, 656L, 757L, 673L)
</code>```

答:
I believe you are using wrongly the table function since you already calculated the numbers of modalities. So it is not a graphical nor a functional problem. All you have to do is calculate the frequency as follow :

Intentional.self.harm..suicide. = c(535L,
                                    579L, 480L, 541L, 499L, 537L, 466L, 453L, 459L, 494L, 520L, 553L,
                                    525L, 588L, 578L, 631L, 676L, 656L, 757L, 673L)

df <- Intentional.self.harm..suicide.
barplot(height = df) # correct barplot with counts

df_prop <- table(df) # gives a table that count modalities (all unique ie 1)
str(df_prop)

# With a data.frame if you want to include labels
df_prop <- data.frame(
        "type" = paste0("t", 1:20),
        "freq" = df/sum(df) # alternatively use prop.table(df)
)

# sum(df_prop$freq) # to check
barplot(height = df_prop$freq) # same 'profile' than first barplot

# --- EDIT / Follow up
# looking at documentation of barplot to set labels and ordinate limits
?barplot

barplot(height = df_prop$freq, names.arg = df_prop$type, ylim=c(0, max(df_prop$freq * 1.2)))
```

Body:
Trying to barplot a CSV file and the plot shows all categories as the same height despite the frequencies varying from 450-800

Below is the plot I receive

!https://imgur.com/9HZuiaK

I have tried implementing a height=x, width=x
This results in completely removing the labels and does not fix the initial problem.

setwd("~/Desktop")
causes<-read.csv('causes.csv')
head(causes)

table(causes$Intentional.self.harm..suicide)

barplot(table(causes$Intentional.self.harm..suicide))
barplot(table(causes$Intentional.self.harm..suicide), ylab='Frequency',
        main='Barplot of Intentional self-harm (suicide)', col='lightblue'

dput(head(causes, 20))

Intentional.self.harm..suicide. = c(535L,
579L, 480L, 541L, 499L, 537L, 466L, 453L, 459L, 494L, 520L, 553L,
525L, 588L, 578L, 631L, 676L, 656L, 757L, 673L)


问:
The Microsoft Office Access database engine cannot open or write to the file
I am getting this below exception

"The Microsoft Office Access database engine cannot open or write to
  the file ''. It is already opened exclusively by another user, or you
  need permission to view and write its data." at  Econ.Open();

```<code>public partial class LBMIS1New : System.Web.UI.Page
{
    OleDbConnection Econ;
    SqlConnection con;

    string constr, Query, sqlconn;
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void ExcelConn(string FilePath)
    {

        constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);
        Econ = new OleDbConnection(constr);

    }
    private void connection()
    {
        sqlconn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        con = new SqlConnection(sqlconn);

    }

    private void InsertExcelRecords(string FilePath)
    {
        ExcelConn(FilePath);

        Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]", "Sheet1$");
        OleDbCommand Ecom = new OleDbCommand(Query, Econ);
        Econ.Open();

        DataSet ds = new DataSet();
        OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
        Econ.Close();
        oda.Fill(ds);
        DataTable Exceldt = ds.Tables[0];
        connection();
        //creating object of SqlBulkCopy
        SqlBulkCopy objbulk = new SqlBulkCopy(con);
        //assigning Destination table name
        objbulk.DestinationTableName = "Employee";
        //Mapping Table column
        objbulk.ColumnMappings.Add("Name", "Name");
        objbulk.ColumnMappings.Add("City", "City");
        objbulk.ColumnMappings.Add("Address", "Address");
        objbulk.ColumnMappings.Add("Designation", "Designation");
        //inserting Datatable Records to DataBase
        con.Open();
        objbulk.WriteToServer(Exceldt);
        con.Close();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
        InsertExcelRecords(CurrentFilePath);
    }
}
</code>```

答:
You can solve this problem by an innovative solution. Work with a duplicate version of your file. Such as changing your FilePath to the copy version of that.
Don`t forget! Finally you should delete the copy version.
Below is your new InsertExcelRecords:

```<code>   private void NewInsertExcelRecords(string FilePath)
    {
        try{
                File.Copy(FilePath,FilePath += "tmp" + Path.GetExtension(FilePath));
                InsertExcelRecords(FilePath);
        }
        finally{File.Delete(FilePath);}
    }
</code>```

Enjoy...

Body:
I am getting this below exception

"The Microsoft Office Access database engine cannot open or write to
  the file ''. It is already opened exclusively by another user, or you
  need permission to view and write its data." at  Econ.Open();

public partial class LBMIS1New : System.Web.UI.Page
{
    OleDbConnection Econ;
    SqlConnection con;

    string constr, Query, sqlconn;
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void ExcelConn(string FilePath)
    {

        constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);
        Econ = new OleDbConnection(constr);

    }
    private void connection()
    {
        sqlconn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        con = new SqlConnection(sqlconn);

    }

    private void InsertExcelRecords(string FilePath)
    {
        ExcelConn(FilePath);

        Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]", "Sheet1$");
        OleDbCommand Ecom = new OleDbCommand(Query, Econ);
        Econ.Open();

        DataSet ds = new DataSet();
        OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
        Econ.Close();
        oda.Fill(ds);
        DataTable Exceldt = ds.Tables[0];
        connection();
        //creating object of SqlBulkCopy
        SqlBulkCopy objbulk = new SqlBulkCopy(con);
        //assigning Destination table name
        objbulk.DestinationTableName = "Employee";
        //Mapping Table column
        objbulk.ColumnMappings.Add("Name", "Name");
        objbulk.ColumnMappings.Add("City", "City");
        objbulk.ColumnMappings.Add("Address", "Address");
        objbulk.ColumnMappings.Add("Designation", "Designation");
        //inserting Datatable Records to DataBase
        con.Open();
        objbulk.WriteToServer(Exceldt);
        con.Close();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
        InsertExcelRecords(CurrentFilePath);
    }
}

Body:
You can solve this problem by an innovative solution. Work with a duplicate version of your file. Such as changing your FilePath to the copy version of that.
Don`t forget! Finally you should delete the copy version.
Below is your new InsertExcelRecords:

   private void NewInsertExcelRecords(string FilePath)
    {
        try{
                File.Copy(FilePath,FilePath += "tmp" + Path.GetExtension(FilePath));
                InsertExcelRecords(FilePath);
        }
        finally{File.Delete(FilePath);}
    }

Enjoy...


问:
Unable to fetch page properties in the head script
I am trying to get a page property in the head of my page basically to make it universally available so that the front end developers can use it in their scripts as they will.

This is on AEM 6.3. And I've already tried to include a script in the head.html but it can't read the page properties in a script tag.

```<code><script>
    window.myAppEndpoint = {
        baseURL: "${properties.myappendpoint}"
    };
</script>
</code>```

I expect the window object to populate with my endpoint value be able to use it anywhere in the application.

答:
You should be able to do this provided:

The myappendpoint property is defined for the page jcr:content node

You are using the proper display context: baseURL: "${properties.myappendpoint @ context='uri'}"

Body:
I am trying to get a page property in the head of my page basically to make it universally available so that the front end developers can use it in their scripts as they will.

This is on AEM 6.3. And I've already tried to include a script in the head.html but it can't read the page properties in a script tag.

I expect the window object to populate with my endpoint value be able to use it anywhere in the application.


问:
what is the most pythonic way to implement dotProduct?
I am trying to implement dot product in Python using numpy arrays. So far, the code I am using works:

```<code>x = np.random.rand(5,5)
w = np.random.rand(5,1)
dot_product = np.zeros((5,1), dtype = np.dtype('O'))

for j in range(len(dot_product[:,0])):
     for i in range(len(dot_product[0,:])):
         sumt = 0
         for column in range(len(x[0,:])):
             temp_x = x[j,column]
             temp_plain = w[column,i]
             sumt += temp_x * temp_plain
         dot_product[j,i] = sumt
</code>```

However, I am wondering if there is a more pythonic way to do it.

Of course, I know about the existance of numpy.dot, which will compute the dot product but I want to implement it myself, this is because I am working with encrypted data, so I can not use the common multiplication and addition.

The goal of the question is to know how to optimize the code, not to use an existing function.

答:
```<code>def dot_prod(x,w):
   if not ( x.shape[1]==w.shape[0]):
       raise Exception( 'The number of columns of the first matrix  does not match the number of rows of the second matrix ')

   dot_product = np.zeros((x.shape[0], w.shape[1]), dtype=np.dtype('O'))
   for i1,a in enumerate(x):
      for i2,y in enumerate(w.T):
         dot_product[i1,i2]= np.sum(a*y)
   return dot_product
</code>```

Output:

```<code>>x = np.random.rand(5,3)
>w = np.random.rand(3,2)
>dot_prod(x,w)
array([[1.0216453677132162, 1.0520242959212602],
       [0.7139675035454871, 0.7616075739263084],
       [0.9126062852861008, 0.9864445729083398],
       [0.42673040494581216, 0.4203998986679549],
       [0.9638211885773351, 1.0142282080627387]], dtype=object)

>x.dot(w)
array([[1.02164537, 1.0520243 ],
       [0.7139675 , 0.76160757],
       [0.91260629, 0.98644457],
       [0.4267304 , 0.4203999 ],
       [0.96382119, 1.01422821]])

>x = np.random.rand(5,3)
>w = np.random.rand(2,2)
>dot_prod(x,w)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/alperen/Projects/tmp.py", line 8, in dot_prod
    raise Exception( 'The number of columns of the first matrix  does not match the number of rows of the second matrix ')
Exception: The number of columns of the first matrix  does not match the number of rows of the second matrix
</code>```

Body:
I am trying to implement dot product in Python using numpy arrays. So far, the code I am using works:

x = np.random.rand(5,5)
w = np.random.rand(5,1)
dot_product = np.zeros((5,1), dtype = np.dtype('O'))

for j in range(len(dot_product[:,0])):
     for i in range(len(dot_product[0,:])):
         sumt = 0
         for column in range(len(x[0,:])):
             temp_x = x[j,column]
             temp_plain = w[column,i]
             sumt += temp_x * temp_plain
         dot_product[j,i] = sumt

However, I am wondering if there is a more pythonic way to do it.

Of course, I know about the existance of numpy.dot, which will compute the dot product but I want to implement it myself, this is because I am working with encrypted data, so I can not use the common multiplication and addition.

The goal of the question is to know how to optimize the code, not to use an existing function.

Body:
def dot_prod(x,w):
   if not ( x.shape[1]==w.shape[0]):
       raise Exception( 'The number of columns of the first matrix  does not match the number of rows of the second matrix ')

   dot_product = np.zeros((x.shape[0], w.shape[1]), dtype=np.dtype('O'))
   for i1,a in enumerate(x):
      for i2,y in enumerate(w.T):
         dot_product[i1,i2]= np.sum(a*y)
   return dot_product

Output:

>x = np.random.rand(5,3)
>w = np.random.rand(3,2)
>dot_prod(x,w)
array([[1.0216453677132162, 1.0520242959212602],
       [0.7139675035454871, 0.7616075739263084],
       [0.9126062852861008, 0.9864445729083398],
       [0.42673040494581216, 0.4203998986679549],
       [0.9638211885773351, 1.0142282080627387]], dtype=object)

>x.dot(w)
array([[1.02164537, 1.0520243 ],
       [0.7139675 , 0.76160757],
       [0.91260629, 0.98644457],
       [0.4267304 , 0.4203999 ],
       [0.96382119, 1.01422821]])

>x = np.random.rand(5,3)
>w = np.random.rand(2,2)
>dot_prod(x,w)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/alperen/Projects/tmp.py", line 8, in dot_prod
    raise Exception( 'The number of columns of the first matrix  does not match the number of rows of the second matrix ')
Exception: The number of columns of the first matrix  does not match the number of rows of the second matrix


答:
Use a nested list comp.</p>

```<code>def vdot(a, b):
    return sum(a*b)

a = np.arange(25).reshape((5, 5))
b = np.arange(15).reshape((5, 3))

res = np.array([[vdot(a_row, b_col) for b_col in b.T] for a_row in a])

assert np.all(res == np.dot(a, b))
</code>```

Title: what is the most pythonic way to implement dotProduct?

Body:
Use a nested list comp.

def vdot(a, b):
    return sum(a*b)

a = np.arange(25).reshape((5, 5))
b = np.arange(15).reshape((5, 3))

res = np.array([[vdot(a_row, b_col) for b_col in b.T] for a_row in a])

assert np.all(res == np.dot(a, b))


问:
I accidentally uploaded .env file with google key in it to github but edited the file and removed the key. Can the change be seen somewhere?
So I created an .env file and had the impression that .env files do not get commited, however, it did. Since it contains a Google API key, I edited the .env file straight away and removed the key from it, however, I wonder if there's a way for people to see what changes have been done to that .env file ( like removing text which in my case is the API key )</p>

答:
You must consider this key already exposed, revoke it and create a new one.

After that, it's at your convenience if you want to take time and efforts to remove it from your history...

For the future, you could use git-secrets to prevent committing it as it is explained in google best practices to keep key safe


问:
Regular Expression in .NET
I should write a regex pattern in c# that checks for input string whether it conains certain characters and does not conain another characters, for example:
I want that the string contain only a-z, not contain (d,b) and the length of all the string longer than 5, I write "[a-z]{5,}", how can I avoid that the input contain d and b?

Additional question: Can I have option to condition in the regex, in other words if whichever boolian var equals true check somthing and if it equals false not check it?

Thanks

答:
simple regex:

```<code>/[ace-z]{5}/
</code>```

matches five occurrences of: characters 'a', 'c', or any character between 'e' and 'z'.

Title: Regular Expression in .NET

Body:
simple regex:

/[ace-z]{5}/

matches five occurrences of: characters 'a', 'c', or any character between 'e' and 'z'.


问:
Wait for detached container to be running
I am using docker-py to help write some quite complex BDD tests via behave.

I am using containers.run with detach=True since I need to be able to continue my script. A Given step creates a container than is then used by a when step to do something within it, and finally as expected, a then step asserts that the right things were done.

However, I cannot fathom how to have my code wait for the Docker container to be ready to accept data/commands. At the moment, I have an ugly sleep(60) in there which clearly is the wrong way to do it.

How can I wait for the container to be ready?

答:
If the container you're waiting for runs a service that can clearly communicate its state to the outside world (say, a database that refuses or accepts connections), then you can easily build some try-catch functionality in your tests to check whether the container is ready before the tests start.

However, if there isn't such a thing, you cannot do much besides sleep, because (from Docker's perspective) a container can be ready before the  main process inside it is ready (again, a database container could be fully started before the DB process inside it is ready to accept connections, and Docker cannot do much about this).

A possible approach would be to define a new ENTRYPOINT for the container you're waiting for that puts a file somewhere that your tests could look for. If the file is there, the tests can start, otherwise sleep(1) and look again. Example for an entrypoint.sh (not tested):

```<code>#!/bin/sh

set -e

# run the process you need here

touch /tmp/i-am-ready

exec "$@"
</code>```

Your tests could then either check for this file in the container directly, or you mount this somewhere as a volume. You would also have to make sure that there still is an attached process after the touch thing, otherwise your container will probably exit 0.

Body:
If the container you're waiting for runs a service that can clearly communicate its state to the outside world (say, a database that refuses or accepts connections), then you can easily build some try-catch functionality in your tests to check whether the container is ready before the tests start.

However, if there isn't such a thing, you cannot do much besides sleep, because (from Docker's perspective) a container can be ready before the  main process inside it is ready (again, a database container could be fully started before the DB process inside it is ready to accept connections, and Docker cannot do much about this).

A possible approach would be to define a new ENTRYPOINT for the container you're waiting for that puts a file somewhere that your tests could look for. If the file is there, the tests can start, otherwise sleep(1) and look again. Example for an entrypoint.sh (not tested):

#!/bin/sh

set -e

# run the process you need here

touch /tmp/i-am-ready

exec "$@"

Your tests could then either check for this file in the container directly, or you mount this somewhere as a volume. You would also have to make sure that there still is an attached process after the touch thing, otherwise your container will probably exit 0.


问:
python regex extract string between characters
I have a string:

```<code>x = "abc/xyz/foo/bar/foobar.mp3"
</code>```

How to extract foobar out of it?

I have done it in this way:

```<code>import re
re.search(r'\/[a-z]+.mp3', x)
</code>```

Although, I do not know how to extract the matched string without '.' and without '.mp3'.

I do not want to do Python splits, rplist, partition etc. as it adds extra functions. I want it to be as simple and short as possible.

EDIT:

Yes, it is a path.

I do not know the length of the path.

As mentioned, I do not want to use splits.

答:
Match non-slashes, then lookahead for \.mp3$:

```<code>re.search(r'[^/]+(?=\.mp3$)', x)
</code>```

Make sure to escape the . with a backslash, else it will match any character.

Body:
I have a string:

x = "abc/xyz/foo/bar/foobar.mp3"

How to extract foobar out of it?

I have done it in this way:

import re
re.search(r'\/[a-z]+.mp3', x)

Although, I do not know how to extract the matched string without '.' and without '.mp3'.

I do not want to do Python splits, rplist, partition etc. as it adds extra functions. I want it to be as simple and short as possible.

EDIT:

Yes, it is a path.

I do not know the length of the path.

As mentioned, I do not want to use splits.

Body:
Match non-slashes, then lookahead for \.mp3$:

re.search(r'[^/]+(?=\.mp3$)', x)

Make sure to escape the . with a backslash, else it will match any character.


答:
You can use this

```<code>[a-z]+(?=\.mp3$)
</code>```

[a-z]+ - matches alphabets one or more time

(?=\.mp3$) - positive lookahead to check match must be followed by .mp3 and end of line

Demo

Title: python regex extract string between characters

Body:
You can use this

[a-z]+(?=\.mp3$)

[a-z]+ - matches alphabets one or more time

(?=\.mp3$) - positive lookahead to check match must be followed by .mp3 and end of line

Demo