问:
How to return a model back (or anything for that matter) on an update mutation in Sequelize?
I am using the update model method to update an entry in Sequelize using the mysql2 dialect. It seems as if with MySQL you can only return a count of rows affected. I would like to pass it back as a boolean.

It should be noted that I am fairly new to JS/ES6, Node, pretty much all of this, I am more versed in PHP so I apologize in advance if the answer is obvious or a fundamental misunderstanding of JS, but I promise I have worked on this for hours. The online documentation and online examples for the update method are fairly light.

The closest answer I can find is at: Sequelize on GraphQL update not return anything

I have removed irrelevant bits of this code for brevity.

Model:

export default (sequelize, DataTypes) => {
    const Payment = sequelize.define('payment', {
        ...
        processed: {
            type: DataTypes.INTEGER(1).UNSIGNED,
            allowNull: false,
            defaultValue: '0'
        },
        ...
    return Payment;
```

<p>Schema:</p>

<pre class="lang-js prettyprint-override"><code>...
type Payment {
id: Int!
amount: Float!
processedTime: Int
processed: Int!
dueDate: Int!
status: PaymentStatuses

Employee: Employee
Client: Client!
Merchant: Merchant
PaymentType: PaymentType
}

type Query {
getPayment(id: Int!): Payment
}
type Mutation {

updatePaymentStatus(id: Int!, processed: Int!): Boolean

}
</code>```

What I was originally trying to do was:

updatePaymentStatus(id: Int!, processed: Int!): Payment!
```

<p>Resolver:</p>

<pre class="lang-js prettyprint-override"><code>Mutation {
updatePaymentStatus: async (parent, {id, processed}, {models}) =>
{await models.Payment.update({processed}, {where: {id}})
.then((datareturned) => {return datareturned[0]})}
}
</code>```

If I check my database, the update is actually working correctly. If I console.log(datareturned[0]) I get a 1 (or 0 if no rows were updated).

I would like to be able to return at least a Boolean as described in my schema but no matter what I try, I get null or some other error because the returned value is null. I realize I may be incorrectly assuming returning 1 will be assumed as true but I have also tried:

```<code>.then((datareturned) => {if (datareturned[0] === 1) {return true}})}
</code>```

In GraphiQL:

```<code>mutation{
  updatePaymentStatus(id:1, processed:0)
}
</code>```

Response:

```<code>{
  "data": {
    "updatePaymentStatus": null
  }
}
</code>```

I am not sure if the problem is with my lack of JS knowledge, or that Sequelize does not return much using the MySQL dialect, or somewhere in between.

答:
This eventually ended up working for me, changing the Resolver for this to:

```<code>updatePaymentStatus: async (parent, {id, processed}, {models}) => {
            try {
                const foundPayment = await models.Payment.findByPk(id)
                if (foundPayment){
                models.Payment.update({processed: id}, {where: {id: id}})

                return true;
                }
                else{
                    return false;
                }
            }
            catch (e) {
                console.log(e);
                return false;
            }

        },
</code>```

I wanted to be sure the payment id existed before running the update because the update would run regardless if the row existed or not. I'm not sure if I even need the try catch, but I left it in there just in case.

Body:
I am using the update model method to update an entry in Sequelize using the mysql2 dialect. It seems as if with MySQL you can only return a count of rows affected. I would like to pass it back as a boolean.

It should be noted that I am fairly new to JS/ES6, Node, pretty much all of this, I am more versed in PHP so I apologize in advance if the answer is obvious or a fundamental misunderstanding of JS, but I promise I have worked on this for hours. The online documentation and online examples for the update method are fairly light.

The closest answer I can find is at: Sequelize on GraphQL update not return anything

I have removed irrelevant bits of this code for brevity.

Model:

export default (sequelize, DataTypes) => {
    const Payment = sequelize.define('payment', {
        ...
        processed: {
            type: DataTypes.INTEGER(1).UNSIGNED,
            allowNull: false,
            defaultValue: '0'
        },
        ...
    return Payment;

Schema:

...
type Payment {
id: Int!
amount: Float!
processedTime: Int
processed: Int!
dueDate: Int!
status: PaymentStatuses

Employee: Employee
Client: Client!
Merchant: Merchant
PaymentType: PaymentType
}

type Query {
getPayment(id: Int!): Payment
}
type Mutation {

updatePaymentStatus(id: Int!, processed: Int!): Boolean

}

What I was originally trying to do was:

updatePaymentStatus(id: Int!, processed: Int!): Payment!

Resolver:

Mutation {
updatePaymentStatus: async (parent, {id, processed}, {models}) =>
{await models.Payment.update({processed}, {where: {id}})
.then((datareturned) => {return datareturned[0]})}
}

If I check my database, the update is actually working correctly. If I console.log(datareturned[0]) I get a 1 (or 0 if no rows were updated).

I would like to be able to return at least a Boolean as described in my schema but no matter what I try, I get null or some other error because the returned value is null. I realize I may be incorrectly assuming returning 1 will be assumed as true but I have also tried:

.then((datareturned) => {if (datareturned[0] === 1) {return true}})}

In GraphiQL:

mutation{
  updatePaymentStatus(id:1, processed:0)
}

Response:

{
  "data": {
    "updatePaymentStatus": null
  }
}

I am not sure if the problem is with my lack of JS knowledge, or that Sequelize does not return much using the MySQL dialect, or somewhere in between.

Body:
This eventually ended up working for me, changing the Resolver for this to:

updatePaymentStatus: async (parent, {id, processed}, {models}) => {
            try {
                const foundPayment = await models.Payment.findByPk(id)
                if (foundPayment){
                models.Payment.update({processed: id}, {where: {id: id}})

                return true;
                }
                else{
                    return false;
                }
            }
            catch (e) {
                console.log(e);
                return false;
            }

        },

I wanted to be sure the payment id existed before running the update because the update would run regardless if the row existed or not. I'm not sure if I even need the try catch, but I left it in there just in case.


来源: stackexchange

问:
How to fix stack overflow on overloaded addition operator in c++
I'm trying to learn the concept of operator overloading in c++ but I have got stuck on a problem that I'm trying to solve using the operator+ where in the my main-function I add to userdefiend classes together.
The class constructor takes a string pointer as a parameter.

My understanding of the operatoroverloading concept is that you declare a function in a class, using the keyword operatorX, and replace X with the operator that you will like to overload. Like if i would like to overload the '-' operator I should write like this operator-. But when I debug my code it results in an Stack overflow and the program stops.

The class looks as follows:

```<code>class Hello{
public:
    Hello(string str):pstr(&str){

    }
    //The overloaded function below
    Hello operator+(Hello& h1){
        Hello temp(*this);//creates a copy of the current Hello-object
        temp = temp + h1;//adds the new value to the temporary object
        return temp;
    }
private:
    string* pstr;//pointer to string-object
}
</code>```

I know that i get the stack overflow in the overloaded function.

In the main method i have the following code:

```<code>void main(){
    Hello h1("Hello ");
    h1 + Hello("World");
}
</code>```

I'm not shore that i've coded this in the right way but the result should be Hello World in the return object if i'm not mistaken.

How can I solve this so that I dont get the stack overflow when the code is running, and also how can I get the right return value?

答:
in

```<code>Hello operator+(Hello& h1){
    Hello temp(*this);//creates a copy of the current Hello-object
    temp = temp + h1;//adds the new value to the temporary object
    return temp;
}
</code>```

the operator+ recursively calls itself, you have to really implement the addition

probably you wanted :

```<code>Hello operator+(const Hello& h1) {
    Hello temp(*pstr + *(h1.pstr))
    return temp;
}
</code>```

Out of that, why do you have pstr as a pointer to a std::string rather than to have just a std::string str; ?

It is much more practical to have for instance :

```<code>class Hello{
  public:
    Hello(string s) : str(s) {  }

    Hello operator+(const Hello& h1){
       Hello temp(str + h1.str);

       return temp;
    }
  private:
    string str;
};
</code>```

Note if you really want to have string* pstr; your constructor

```<code>Hello(string str):pstr(&str){}
</code>```

is wrong because you save the address of the parameter, you need to change it to for instance :

```<code>Hello(string str) : pstr(new string(str)) {}
</code>```

and having a pointer you need to add the destructor to delete the string, and the copy constructor, the operator= etc look at rule_of_three

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to learn the concept of operator overloading in c++ but I have got stuck on a problem that I'm trying to solve using the operator+ where in the my main-function I add to userdefiend classes together.
The class constructor takes a string pointer as a parameter.

My understanding of the operatoroverloading concept is that you declare a function in a class, using the keyword operatorX, and replace X with the operator that you will like to overload. Like if i would like to overload the '-' operator I should write like this operator-. But when I debug my code it results in an Stack overflow and the program stops.

The class looks as follows:

class Hello{
public:
    Hello(string str):pstr(&str){

    }
    //The overloaded function below
    Hello operator+(Hello& h1){
        Hello temp(*this);//creates a copy of the current Hello-object
        temp = temp + h1;//adds the new value to the temporary object
        return temp;
    }
private:
    string* pstr;//pointer to string-object
}

I know that i get the stack overflow in the overloaded function.

In the main method i have the following code:

void main(){
    Hello h1("Hello ");
    h1 + Hello("World");
}

I'm not shore that i've coded this in the right way but the result should be Hello World in the return object if i'm not mistaken.

How can I solve this so that I dont get the stack overflow when the code is running, and also how can I get the right return value?

Body:
in

Hello operator+(Hello& h1){
    Hello temp(*this);//creates a copy of the current Hello-object
    temp = temp + h1;//adds the new value to the temporary object
    return temp;
}

the operator+ recursively calls itself, you have to really implement the addition

probably you wanted :

Hello operator+(const Hello& h1) {
    Hello temp(*pstr + *(h1.pstr))
    return temp;
}

Out of that, why do you have pstr as a pointer to a std::string rather than to have just a std::string str; ?

It is much more practical to have for instance :

class Hello{
  public:
    Hello(string s) : str(s) {  }

    Hello operator+(const Hello& h1){
       Hello temp(str + h1.str);

       return temp;
    }
  private:
    string str;
};

Note if you really want to have string* pstr; your constructor

Hello(string str):pstr(&str){}

is wrong because you save the address of the parameter, you need to change it to for instance :

Hello(string str) : pstr(new string(str)) {}

and having a pointer you need to add the destructor to delete the string, and the copy constructor, the operator= etc look at rule_of_three


问:
Identifying object fields with strings in Scala
In ES6 we can refer to a field of an object as:

```<code>seller['firstname']
</code>```

to represent

```<code>seller.firstname
</code>```

Is there a way to do the same in Scala? I mean, to use strings to refer to object fields?

答: No. I don't think so. As Scala based on JVM which require static type. Unless you want to use reflection </p>

Body:
In ES6 we can refer to a field of an object as:

seller['firstname']

to represent

seller.firstname

Is there a way to do the same in Scala? I mean, to use strings to refer to object fields?


问:
Delete items from a dict list containing google drive flies
I need to delete some items from a dict list. This list is produced by a call to Google Drive Rest Api.

I've tried several code samples but I can't make it work. I'm a Python newbie.

```<code>#this is the Google Api call
theFiles = drive_service.files().list(fields="files(id,name,modifiedTime, size, fileExtension)").execute()

#here I am trying to iterate the results and delete all items that refer to a "temp" file:

for k, v in theFiles.items():
    if v[4]=="tmp":
        del theFiles[k]
</code>```

I was expecting that records containing a "tmp" extension would be deleted from this list, however I can't make it work.

I thought that v[4] whould refer to the "fileExtension" field of the dictionary. However, when I debug I see that v[4] contains the whole item, for example:

```<code>{'fileExtension': 'docx', 'id': '1u7zrCm3waGr9CiEmPl...F2acV7NvC', 'modifiedTime': '2019-05-03T18:59:19.000Z', 'name': '~$ LENGUA PROG.docx', 'size': '162'}
</code>```

Please help me understand how to write the right code to delete items with the ".tmp" extension.

答:
You can use the enumerate() function to generate the index along with the elements of the sequence you are looping over. I assume that items is similar to this:

```<code>items = [{'fileExtension': 'docx', 'id': '1u7zrCm3waGr9CiEmPl...F2acV7NvC',
 'modifiedTime': '2019-05-03T18:59:19.000Z',
'name': '~$ LENGUA PROG.docx', 'size': '162'}]
</code>```

So you can delete all items that refer to a "temp" file like below:

```<code>for index,item in enumerate(items):
    if item['fileExtension'] =="tmp":
        del items[index]
</code>```

Body:
I need to delete some items from a dict list. This list is produced by a call to Google Drive Rest Api.

I've tried several code samples but I can't make it work. I'm a Python newbie.

#this is the Google Api call
theFiles = drive_service.files().list(fields="files(id,name,modifiedTime, size, fileExtension)").execute()

#here I am trying to iterate the results and delete all items that refer to a "temp" file:

for k, v in theFiles.items():
    if v[4]=="tmp":
        del theFiles[k]

I was expecting that records containing a "tmp" extension would be deleted from this list, however I can't make it work.

I thought that v[4] whould refer to the "fileExtension" field of the dictionary. However, when I debug I see that v[4] contains the whole item, for example:

{'fileExtension': 'docx', 'id': '1u7zrCm3waGr9CiEmPl...F2acV7NvC', 'modifiedTime': '2019-05-03T18:59:19.000Z', 'name': '~$ LENGUA PROG.docx', 'size': '162'}

Please help me understand how to write the right code to delete items with the ".tmp" extension.

Body:
You can use the enumerate() function to generate the index along with the elements of the sequence you are looping over. I assume that items is similar to this:

items = [{'fileExtension': 'docx', 'id': '1u7zrCm3waGr9CiEmPl...F2acV7NvC',
 'modifiedTime': '2019-05-03T18:59:19.000Z',
'name': '~$ LENGUA PROG.docx', 'size': '162'}]

So you can delete all items that refer to a "temp" file like below:

for index,item in enumerate(items):
    if item['fileExtension'] =="tmp":
        del items[index]


问:
Regex to match Telephone Pattern logic
I am trying to create a regex string to match telephone numbers using the following logic:

1) For NPA (area code), 3 digits,  the first digit is [2-9], 2nd and 3rd digit [0-9]

2) For NXX (exchange – next 3 digits after NPA) same rules as NPA.  In addition, the 3rd digit cannot be ‘1’ if the 2nd digit is ‘1’ (reserved for public service)

3) For XXXX (number – next 4 digits after NXX), [0-9] for each of the 4 digits.

I've completed steps 1 and 3 and part of 2 with the following string:

```<code>^\(?([2-9]{1})\)?([0-9]{2})?[-.*]?([2-9]{1})\)?([0-9]{2})?[-.*]?([0-9]{4})$
</code>```

But I am stuck on trying to incorporate the logic stated here:

For NXX (exchange – next 3 digits after NPA) same rules as NPA.  In addition, the 3rd digit cannot be ‘1’ if the 2nd digit is ‘1’ (reserved for public service)

If anyone can help shine some light on this, it would be greatly appreciated.

False is what I want my regex not to match, while true is what I would want it continuing to match. It currently matches both sets .

False: 4807119320 4805119439 4809114739

True: 4805218482 4805123848 4809128327 4809418482

答:
If in the second part the second digit can not be 1 if the third digit is 1, you could use a negative lookahead (?!11)to assert what is on the right is not 11.

Adding that to your pattern, it would look like:

```<code>^\(?([2-9])\)?([0-9]{2})?[-.*]?([2-9])\)?((?!11)[0-9]{2})?[-.*]?([0-9]{4})$
                                          ^^^^^^
</code>```

Regex demo

Note that a lot of parts are optional due to the question mark like \(? and \)? and for the second closing parenthesis there is an opening parenthesis missing so this would also match (2)33-2)21-2222

If the opening and closing parenthesis should for the second part be the same as the first it could look like:

```<code>^\(?([2-9])\)?([0-9]{2})?[-.*]?\(?([2-9])\)?((?!11)[0-9]{2})?[-.*]?([0-9]{4})$
                               ^^^
</code>```

If what is match in the first character class should be the same as in the second character class, you might also use another capturing group ([-.*]?) and  a backreference \3 so (2)33-(2)212222 would not match:

Regex demo

Title: Regex to match Telephone Pattern logic

Body:
I am trying to create a regex string to match telephone numbers using the following logic:

1) For NPA (area code), 3 digits,  the first digit is [2-9], 2nd and 3rd digit [0-9]

2) For NXX (exchange – next 3 digits after NPA) same rules as NPA.  In addition, the 3rd digit cannot be ‘1’ if the 2nd digit is ‘1’ (reserved for public service)

3) For XXXX (number – next 4 digits after NXX), [0-9] for each of the 4 digits.

I've completed steps 1 and 3 and part of 2 with the following string:

^\(?([2-9]{1})\)?([0-9]{2})?[-.*]?([2-9]{1})\)?([0-9]{2})?[-.*]?([0-9]{4})$

But I am stuck on trying to incorporate the logic stated here:

For NXX (exchange – next 3 digits after NPA) same rules as NPA.  In addition, the 3rd digit cannot be ‘1’ if the 2nd digit is ‘1’ (reserved for public service)

If anyone can help shine some light on this, it would be greatly appreciated.

False is what I want my regex not to match, while true is what I would want it continuing to match. It currently matches both sets .

False: 4807119320 4805119439 4809114739

True: 4805218482 4805123848 4809128327 4809418482

Body:
If in the second part the second digit can not be 1 if the third digit is 1, you could use a negative lookahead (?!11)to assert what is on the right is not 11.

Adding that to your pattern, it would look like:

^\(?([2-9])\)?([0-9]{2})?[-.*]?([2-9])\)?((?!11)[0-9]{2})?[-.*]?([0-9]{4})$
                                          ^^^^^^

Regex demo

Note that a lot of parts are optional due to the question mark like \(? and \)? and for the second closing parenthesis there is an opening parenthesis missing so this would also match (2)33-2)21-2222

If the opening and closing parenthesis should for the second part be the same as the first it could look like:

^\(?([2-9])\)?([0-9]{2})?[-.*]?\(?([2-9])\)?((?!11)[0-9]{2})?[-.*]?([0-9]{4})$
                               ^^^

If what is match in the first character class should be the same as in the second character class, you might also use another capturing group ([-.*]?) and  a backreference \3 so (2)33-(2)212222 would not match:

Regex demo


问:
Zoom in and out on mouse click with CSS
I want to zoom image with only CSS. The code below zooms the image when the left button of the mouse is kept pressed but I want to zoom in and out with a mouse click. How can I achieve that?</p>

```<code>.container img {
  transition: transform 0.25s ease;
  cursor: zoom-in;
}

.container img:active {
  -webkit-transform: scale(2);
  transform: scale(2);
  cursor: zoom-out;
}
</code>```

答:
Building on @Nhan answer: https://stackoverflow.com/a/39859268/661872

Shorter, scoped and does not require tracking ids for multiple elements.

.click-zoom input[type=checkbox] {
  display: none
}

.click-zoom img {
  margin: 100px;
  transition: transform 0.25s ease;
  cursor: zoom-in
}

.click-zoom input[type=checkbox]:checked~img {
  transform: scale(2);
  cursor: zoom-out
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="click-zoom">
  <label>
    <input type="checkbox">
    <img src="https://via.placeholder.com/200">
  </label>
</div>

<div class="click-zoom">
  <label>
    <input type="checkbox">
    <img src="https://via.placeholder.com/200">
  </label>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Zoom in and out on mouse click with CSS

Body:
I want to zoom image with only CSS. The code below zooms the image when the left button of the mouse is kept pressed but I want to zoom in and out with a mouse click. How can I achieve that?

.container img {
  transition: transform 0.25s ease;
  cursor: zoom-in;
}

.container img:active {
  -webkit-transform: scale(2);
  transform: scale(2);
  cursor: zoom-out;
}

Body:
Building on @Nhan answer: https://stackoverflow.com/a/39859268/661872

Shorter, scoped and does not require tracking ids for multiple elements.

.click-zoom input[type=checkbox] {
  display: none
}

.click-zoom img {
  margin: 100px;
  transition: transform 0.25s ease;
  cursor: zoom-in
}

.click-zoom input[type=checkbox]:checked~img {
  transform: scale(2);
  cursor: zoom-out
}

<div class="click-zoom">
  <label>
    <input type="checkbox">
    <img src="https://via.placeholder.com/200">
  </label>
</div>

<div class="click-zoom">
  <label>
    <input type="checkbox">
    <img src="https://via.placeholder.com/200">
  </label>
</div>


问:
Is @Import annotation necessary with Spring Boot?
I'm working with Spring Boot 2.1.5. I have multiple classes annotated with @Configuration.

I want to know if it's necessary to list all of these configuration classes with @Import? Or will the component scanner find all the @Configuration annotated classes and do it automatically?

答: You don’t need to do that, scanning will be done for you automatically , all you need is to make your main class on the root package, and all other stereotypes classes including configuration  in sub packages</p>


问:
RenderFlex overflowed by 388 pixels on the bottom and overflowing RenderFlex has an orientation of Axis.vertical
I am learning flutter development and want to make a screen in which a container should be placed at bottom of screen and also the remaining screen have content which should be Scrollable.
here is the body of Scaffold widget

```<code>body:Stack(

        children: <Widget>[
      Container(
      margin: const EdgeInsets.fromLTRB(0.0, 10.0  , 0.0 , 0.0 ),
      height: double.infinity,
          child:SingleChildScrollView(
            child: Container(
              height: MediaQuery.of(context).size.height * 0.9,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                 Container(
                   height: 100,
                   child: Text(description),
                 ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                ],
              ),
            ),
          )
      ) ,
          Positioned(
            left: 0,
            right: 0,
            bottom:0,
            child:  new Container(
                transform: Matrix4.translationValues(0.0, 0.0, -20.0),
                child: new Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    new Column(

                      children: <Widget>[

                        InkWell(
                          child:  Image.asset('assets/bt1.png'),
                          onTap: (){
                            Navigator.pushNamed(context, '/help');
                          },
                        ),
                        Text("FIND HELP",
                          style: TextStyle(fontSize: 14.0,color: Colors.white),
                        ),
                      ],
                    ),
                    new Column(

                      children: <Widget>[
                        InkWell(
                          child:  Image.asset('assets/bt2.png'),
                          onTap: (){
//                                        Navigator.push(context, new MaterialPageRoute(
//                                          builder: (BuildContext context) => new Home(title: 'Bright Sky'),
//                                        ));
                          },
                        ),

                        Text("HOME",
                          style: TextStyle(fontSize: 14.0,color: Colors.white),
                        ),
                      ],
                    ),
                    new Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[

                        new InkWell(
                          child: Image.asset('assets/bt3.png'),
                          onTap: () {
                            //UrlLauncher.launch("tel://911");
                          },
                        ),
                        Text("CALL 999",
                          style: TextStyle(fontSize: 14.0,color: Colors.white),
                        ),
                      ],
                    ),

                  ],
                ),
//              color: Colors.blue,
            ),
          )
        ],
      )

</code>```

I have put Container with Text just for testing purpose.
But above code gives me error that.

```<code>A RenderFlex overflowed by 388 pixels on the bottom.
The overflowing RenderFlex has an orientation of Axis.vertical.
</code>```

What i am doing wrong here?
Thanks in advance.

答:
Flutter was not designed for UIs in which you just manually place which exact pixel you want your widgets to be. Instead, design your UI so that the composition itself determines where the widgets will end up being.

For example, you are using Stack and Positioned to try and float a container below another widget, when all you need to do is use an Expanded widget to make the first widget expand to fill all remaining space.

Also, you are using a Container with a fixed height inside a SingleChildScrollView, and the child of that is a Column with a bunch of fixed height Containers. This is the exact scenario that ListView was made for.

```<code>body: Column(
  children: [
    Expanded(
      child: ListView(
        children: [
          // The list of containers
        ],
      ),
    ),
    Row(
      children: [
        Column(
          children: <Widget>[
            InkWell(
              child:  Image.asset('assets/bt2.png'),
              onTap: (){},
            ),
            Text("HOME",
              style: TextStyle(fontSize: 14.0,color: Colors.white),
            ),
          ],
        ),
        Column(
          children: <Widget>[
            InkWell(
              child:  Image.asset('assets/bt3.png'),
              onTap: (){},
            ),
            Text("CALL 999",
              style: TextStyle(fontSize: 14.0,color: Colors.white),
            ),
          ],
        ),
      ],
    ),
  ],
),
</code>```

But to take this a step further, it looks like all you want to do is put some navigation buttons at the bottom of the screen. Scaffold already allows this with the bottomNavigationBar property. And when you do that, you no longer need a Column or Expanded to size your body as the only thing left to go there is the ListView.

```<code>Scaffold(
  body: ListView(
    children: [
      // The list of containers
    ],
  ),
  bottomNavigationBar: BottomNavigationBar(
    items: [
      BottomNavigationBarItem(
        icon: Image.asset('assets/bt2.png'),
        title: Text(
          "HOME",
          style: TextStyle(fontSize: 14.0,color: Colors.white),
        ),
      ),
      BottomNavigationBarItem(
        icon: Image.asset('assets/bt3.png'),
        title: Text(
          "CALL 999",
          style: TextStyle(fontSize: 14.0,color: Colors.white),
        ),
      ),
    ],
  ),
),
</code>```

There is power in composition. Do some research on the various widgets that Flutter offers. Check out the Flutter Widget of the Week series on youtube. You'd be amazed at how many responsive and fluid UIs you can make without ever once manually specifying a fixed width and height of a widget.

Body:
I am learning flutter development and want to make a screen in which a container should be placed at bottom of screen and also the remaining screen have content which should be Scrollable.
here is the body of Scaffold widget

body:Stack(

        children: <Widget>[
      Container(
      margin: const EdgeInsets.fromLTRB(0.0, 10.0  , 0.0 , 0.0 ),
      height: double.infinity,
          child:SingleChildScrollView(
            child: Container(
              height: MediaQuery.of(context).size.height * 0.9,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                 Container(
                   height: 100,
                   child: Text(description),
                 ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                  Container(
                    height: 100,
                    child: Text(description),
                  ),
                ],
              ),
            ),
          )
      ) ,
          Positioned(
            left: 0,
            right: 0,
            bottom:0,
            child:  new Container(
                transform: Matrix4.translationValues(0.0, 0.0, -20.0),
                child: new Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    new Column(

                      children: <Widget>[

                        InkWell(
                          child:  Image.asset('assets/bt1.png'),
                          onTap: (){
                            Navigator.pushNamed(context, '/help');
                          },
                        ),
                        Text("FIND HELP",
                          style: TextStyle(fontSize: 14.0,color: Colors.white),
                        ),
                      ],
                    ),
                    new Column(

                      children: <Widget>[
                        InkWell(
                          child:  Image.asset('assets/bt2.png'),
                          onTap: (){
//                                        Navigator.push(context, new MaterialPageRoute(
//                                          builder: (BuildContext context) => new Home(title: 'Bright Sky'),
//                                        ));
                          },
                        ),

                        Text("HOME",
                          style: TextStyle(fontSize: 14.0,color: Colors.white),
                        ),
                      ],
                    ),
                    new Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[

                        new InkWell(
                          child: Image.asset('assets/bt3.png'),
                          onTap: () {
                            //UrlLauncher.launch("tel://911");
                          },
                        ),
                        Text("CALL 999",
                          style: TextStyle(fontSize: 14.0,color: Colors.white),
                        ),
                      ],
                    ),

                  ],
                ),
//              color: Colors.blue,
            ),
          )
        ],
      )

I have put Container with Text just for testing purpose.
But above code gives me error that.

A RenderFlex overflowed by 388 pixels on the bottom.
The overflowing RenderFlex has an orientation of Axis.vertical.

What i am doing wrong here?
Thanks in advance.

Body:
Flutter was not designed for UIs in which you just manually place which exact pixel you want your widgets to be. Instead, design your UI so that the composition itself determines where the widgets will end up being.

For example, you are using Stack and Positioned to try and float a container below another widget, when all you need to do is use an Expanded widget to make the first widget expand to fill all remaining space.

Also, you are using a Container with a fixed height inside a SingleChildScrollView, and the child of that is a Column with a bunch of fixed height Containers. This is the exact scenario that ListView was made for.

body: Column(
  children: [
    Expanded(
      child: ListView(
        children: [
          // The list of containers
        ],
      ),
    ),
    Row(
      children: [
        Column(
          children: <Widget>[
            InkWell(
              child:  Image.asset('assets/bt2.png'),
              onTap: (){},
            ),
            Text("HOME",
              style: TextStyle(fontSize: 14.0,color: Colors.white),
            ),
          ],
        ),
        Column(
          children: <Widget>[
            InkWell(
              child:  Image.asset('assets/bt3.png'),
              onTap: (){},
            ),
            Text("CALL 999",
              style: TextStyle(fontSize: 14.0,color: Colors.white),
            ),
          ],
        ),
      ],
    ),
  ],
),

But to take this a step further, it looks like all you want to do is put some navigation buttons at the bottom of the screen. Scaffold already allows this with the bottomNavigationBar property. And when you do that, you no longer need a Column or Expanded to size your body as the only thing left to go there is the ListView.

Scaffold(
  body: ListView(
    children: [
      // The list of containers
    ],
  ),
  bottomNavigationBar: BottomNavigationBar(
    items: [
      BottomNavigationBarItem(
        icon: Image.asset('assets/bt2.png'),
        title: Text(
          "HOME",
          style: TextStyle(fontSize: 14.0,color: Colors.white),
        ),
      ),
      BottomNavigationBarItem(
        icon: Image.asset('assets/bt3.png'),
        title: Text(
          "CALL 999",
          style: TextStyle(fontSize: 14.0,color: Colors.white),
        ),
      ),
    ],
  ),
),

There is power in composition. Do some research on the various widgets that Flutter offers. Check out the Flutter Widget of the Week series on youtube. You'd be amazed at how many responsive and fluid UIs you can make without ever once manually specifying a fixed width and height of a widget.


问:
awk ignore quoted delimiters `echo 'a "b1 b2" c'| awk '{print $2}'`
The following will output "b1 as it recognizes the quoted space as a field delimiter. How do I tell awk to ignore quoted delimiters so that this would output b1 b2 or "b1 b2"

echo 'a "b1 b2" c'| awk '{print $2}'
```

I see the following two related posts, but I'm having trouble getting the solutions to work. I was hoping to find a simple solution. Field parsing is awk's specialty, right?

awk ignore delimiter inside single quote within a parenthesis
What's the most robust way to efficiently parse CSV using awk?

答:
You can get what you look for this way:

```<code>awk '{split($0,a,/^"|" "| "|" |"$/);j=a[1]!=""?0:1;print a[2+j]}'
</code>```

I think you can get a way where it fail ...

Body:
The following will output "b1 as it recognizes the quoted space as a field delimiter. How do I tell awk to ignore quoted delimiters so that this would output b1 b2 or "b1 b2"

echo 'a "b1 b2" c'| awk '{print $2}'

I see the following two related posts, but I'm having trouble getting the solutions to work. I was hoping to find a simple solution. Field parsing is awk's specialty, right?

awk ignore delimiter inside single quote within a parenthesis
What's the most robust way to efficiently parse CSV using awk?

Body:
You can get what you look for this way:

awk '{split($0,a,/^"|" "| "|" |"$/);j=a[1]!=""?0:1;print a[2+j]}'

I think you can get a way where it fail ...


问:
Unmarshal GO YAML to either a Map or a String
I'm trying to unmarshal YAML entries that can be either a string or a list of key: value strings (a map as per Go). I cannot figure out how to get this done sadly. I know I can write my own unmarshaller but that seems to only work with structs.

I have the first part working:

```<code>package main

import (
    "log"

    "gopkg.in/yaml.v2"
)

type Data struct {
    Entry []Entry `yaml:"entries"`
}

type Entry map[string]string

var dat string = `
entries:
  - keya1: val1
    keya2: val2
  - keyb1: val1
    keyb2: val2
  - val3`

func main() {
    out := Data{}
    if err := yaml.Unmarshal([]byte(dat), &out); err != nil {
        log.Fatal(err)
    }

    log.Printf("%+v", out)
}
</code>```

But the  - val3 entry causes an error now, obviously. How can I get it to recognise both lists and single string entries?

Thank you

答:
This is just a followup to the excellent @Benjamin Kadish answer above, but here's a somewhat more complete version and this uses yaml.v3, which makes it just a bit more obvious. Note that the type of the unmarshalled items is map[string]interface{} instead of map[interface{}]interface{} in yaml v3.

package main

import (
    "gopkg.in/yaml.v3"
    "log"
)

type Data struct {
    Entry []Entry `yaml:"entries"`
}

type Entry interface {}

var dat string = `
entries:
  - keya1: val1
    keya2: val2
  - keyb1: val1
    keyb2: val2
  - val3`

func main() {
    out := Data{}
    if err := yaml.Unmarshal([]byte(dat), &out); err != nil {
        log.Fatal(err)
    }

    for _, entry := range out.Entry {

        switch i := entry.(type) {
        case string:
            log.Printf("i is a string: %+v\n", i)
        case map[string]interface{}:
            log.Printf("i is a map.")
            for k,v := range i {
                log.Printf("%s=%v\n",k,v)
            }
        default:
            log.Printf("Type i=%s", i)
        }
    }
}

```

Body:
I'm trying to unmarshal YAML entries that can be either a string or a list of key: value strings (a map as per Go). I cannot figure out how to get this done sadly. I know I can write my own unmarshaller but that seems to only work with structs.

I have the first part working:

package main

import (
    "log"

    "gopkg.in/yaml.v2"
)

type Data struct {
    Entry []Entry `yaml:"entries"`
}

type Entry map[string]string

var dat string = `
entries:
  - keya1: val1
    keya2: val2
  - keyb1: val1
    keyb2: val2
  - val3`

func main() {
    out := Data{}
    if err := yaml.Unmarshal([]byte(dat), &out); err != nil {
        log.Fatal(err)
    }

    log.Printf("%+v", out)
}

But the  - val3 entry causes an error now, obviously. How can I get it to recognise both lists and single string entries?

Thank you


问:
What technique I should use for this web UI feature? (HTML frame or table or others)
I am not quite experienced with web UI design, so I ask here for some opinions of the UI feature I am currently working on. Basically, I would like to know which techniques I should use for the following feature:

I would like to implement a page, the left side of the page occupy 1/3 width of the page, and contain text field, buttons and checkboxes. The right side of the page occupy 2/3 width of the page, it will show some dynamic content based on the left side user input. The right side of the page is mainly implemented by using javascript, jQuery and ajax.

Should I use HTML frame for left and right sides of the page or should I just use a table to divide the page to two parts? or what else? which is better?

答:
You should use neither.

Instead, you should use a combination of the
 tag for the markup and CSS to define the desired layout.

Body:
You should use neither.

Instead, you should use a combination of the <div> tag for the markup and CSS to define the desired layout.


问:
Unity GoogleVR1.2 Cardboard displays upside down on Samsung
Currently, I am trying to make the Virtual Tour app to play with cardboard, then get the demo completed and it's working like a charm in Editor Play mode and on my Lenovo Phab 2 phone. Unfortunately, when I install it on Samsung Note 9, the app displays upside down. I have tried change the orientation in player setting and edit the android manifest but still no luck are there any one know the solution? or is it the bug in GoogleVRSDK or Unity ,caused at first there is the lack in app build that Unity build the app as normal app not Cardboard one even GoogleVR Demo scene, but after restart Unity it works fine. </p>

答:
This is apparently an issue with Unity 2019.1.x and both Android and iOS.

Either, switch rendering from Vulkan to OpenGLES3 (Android, not sure about iOS)

Or, downgrade to 2018.3.14f (is said to work for both iOS and Android)

Track updates here:

https://github.com/googlevr/gvr-unity-sdk/issues/1030

https://github.com/googlevr/gvr-unity-sdk/issues/1031


问:
twilio Automatic retry call
I use the restful api for voice calls. I used this to call myself. When my phone rings, I don't connect and hang up. After about 20 seconds, I received another call from twilio.

curl 'https://api.twilio.com/2010-04-01/Accounts/AccountSid/Calls.json' -X POST --data-urlencode 'To=+1111111' --data-urlencode 'From=+22222' --data-urlencode 'Url=http://demo.twilio.com/docs/voice.xml' -u AccountSid:authToken

I hope that when I hang up for the first time, I won't receive a second call.

答: Did you answer and then hang up or did you decline the call? If you decline the call, the carrier may reattempt the call.</p>

Title: twilio Automatic retry call


问:
Does variable declaration hoist to the top of if scope block?
When hoisting is occurring to the variable which declaring with keyword var inside an if block scope, does the ( var x;) hoisting to the top of current if block? or to the top of the global scope in this case?
Suppose we wrote the following piece of code directly in the global scope</p>

```<code>if (true) {
   some code;
   var x = 1;
}
</code>```

答:
When using var (or omitting the definition key at all e.g just x = 1) as per your example, it would be hoisted to the closest scope which in your example would be the global scope (window).

If it would be wrapped in a function, then the function would be the closest scope.

function a() {
    if(true){
       var x=1;
    }
    console.log(x) // 1
    console.log(window.x) // undefined
}
a()
console.log(x) // Throws error (x is not defined)```
</div>
</div>
</p>

<p>If you want the variable to be completely block scope, then you would need to use <code>let</code> or <code>const</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>if(true){
    const x=1;
}
console.log(x) // Throws error (x is not defined)</code>```

Body:
When hoisting is occurring to the variable which declaring with keyword var inside an if block scope, does the ( var x;) hoisting to the top of current if block? or to the top of the global scope in this case?
Suppose we wrote the following piece of code directly in the global scope

if (true) {
   some code;
   var x = 1;
}

Body:
When using var (or omitting the definition key at all e.g just x = 1) as per your example, it would be hoisted to the closest scope which in your example would be the global scope (window).

If it would be wrapped in a function, then the function would be the closest scope.

function a() {
    if(true){
       var x=1;
    }
    console.log(x) // 1
    console.log(window.x) // undefined
}
a()
console.log(x) // Throws error (x is not defined)

If you want the variable to be completely block scope, then you would need to use let or const.

if(true){
    const x=1;
}
console.log(x) // Throws error (x is not defined)


问:
Convert List of Lists to Dictionary with unique keys and all related values
I'm python newbie and I'am currently struggling with one problem. I have a list of lists:

[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

My aim is to make a dictionary from it with the following format:

{0:[1],1:[2,8],2:[8,1,4,5],3:[4],5:[6,7,2],6:[5,7],7:[5,6],8:[1,2,10,9,11,12],9:[8,10,11,12],10:[8,9,11,12],11:[12,10,9,8],12:[11,9,10,8]}.

In short:

It has to make a dictionary with unique keys from 1 to 12 in this case (all unique numbers in a list), and to each key it assigns a list of values, which is a common subset for this key i.e for key 2 it appears in lists [4,2], [2,5], [1,2,8] so it has to assign to a key 2 a value which is a list of numbers in those 3 lists except 2.

Thus the output for key 2 should be: 2:[8,1,4,5] etc.

I've made some code:

```<code>data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

graph = {}
for i in range(13):
    graph[i] = 3

numbers = list(range(0,13))
for row in data:
    for i in graph.keys():
        if i in row:
            graph[i] = row

for key,value in graph.items():
    graph[key] = graph[key][1:]

print(graph)
</code>```

Yet, it gives me output:

{0: [1], 1: [2, 8], 2: [5], 3: [4], 4: [2], 5: [6, 7], 6: [6, 7], 7: [6, 7], 8: [9, 10, 11, 12], 9: [9, 10, 11, 12], 10: [9, 10, 11, 12], 11: [9, 10, 11, 12], 12: [9, 10, 11, 12]}

I really don't know how to combine those lists from this in such a way that I will get desired output.

Body:
I'm python newbie and I'am currently struggling with one problem. I have a list of lists:

[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

My aim is to make a dictionary from it with the following format:

{0:[1],1:[2,8],2:[8,1,4,5],3:[4],5:[6,7,2],6:[5,7],7:[5,6],8:[1,2,10,9,11,12],9:[8,10,11,12],10:[8,9,11,12],11:[12,10,9,8],12:[11,9,10,8]}.

In short:

It has to make a dictionary with unique keys from 1 to 12 in this case (all unique numbers in a list), and to each key it assigns a list of values, which is a common subset for this key i.e for key 2 it appears in lists [4,2], [2,5], [1,2,8] so it has to assign to a key 2 a value which is a list of numbers in those 3 lists except 2.

Thus the output for key 2 should be: 2:[8,1,4,5] etc.

I've made some code:

data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

graph = {}
for i in range(13):
    graph[i] = 3

numbers = list(range(0,13))
for row in data:
    for i in graph.keys():
        if i in row:
            graph[i] = row

for key,value in graph.items():
    graph[key] = graph[key][1:]

print(graph)

Yet, it gives me output:

{0: [1], 1: [2, 8], 2: [5], 3: [4], 4: [2], 5: [6, 7], 6: [6, 7], 7: [6, 7], 8: [9, 10, 11, 12], 9: [9, 10, 11, 12], 10: [9, 10, 11, 12], 11: [9, 10, 11, 12], 12: [9, 10, 11, 12]}

I really don't know how to combine those lists from this in such a way that I will get desired output.

Body:
a=[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]
from collections import defaultdict

dic=defaultdict(list)
for i,v in enumerate(a):
    for j, v2 in enumerate(v):
        new_s=a[i][:j]+a[i][j+1:]
        dic[v2].extend(new_s)

for i in dic:
    dic[i]=list(set(dic[i]))

print(dict(dic))

output

{0: [1],
 1: [0, 8, 2],
 2: [8, 1, 4, 5],
 8: [1, 2, 9, 10, 11, 12],
 3: [4],
 4: [2, 3],
 5: [2, 6, 7],
 6: [5, 7],
 7: [5, 6],
 9: [8, 10, 11, 12],
 10: [8, 9, 11, 12],
 11: [8, 9, 10, 12],
 12: [8, 9, 10, 11]
 }


问:
array of radio - jquery
i have the code below and it shows a list of radio buttons
My question is how i can make a list of buttons, the equivalent for this in an array mode (jquery)

```<code>  <input type="radio" name="name1" value="450" /> 450€<br />
  <input type="radio" name="name2" value="500" /> 500€<br />
  <input type="radio" name="name3" value="550" /> 550€<br />
  <input type="radio" name="name4" value="600" /> 600€<br />
  <input type="radio" name="name5" value="650" /> 650€<br />
  <input type="radio" name="name6" value="700" /> 700€<br />
</code>```

this simple make an array without change anything. And another question, how i will can access the values when i will have this in an array mode?

thanks

答:
This will create 20 inputs and increment value and text by 50

```<code>var count = 20;
var increment = 50;

for (y = 0; y < count; y++) {
    var inp = '<input type="radio" name="name1" value="' + increment + '" /> ' + increment + '<br />';
    $(inp).appendTo('#lista');
    increment = increment + 50;
}
</code>```

Check working example at http://jsfiddle.net/fxmmN/1/

Title: array of radio - jquery

Body:
i have the code below and it shows a list of radio buttons
My question is how i can make a list of buttons, the equivalent for this in an array mode (jquery)

  <input type="radio" name="name1" value="450" /> 450€

  <input type="radio" name="name2" value="500" /> 500€

  <input type="radio" name="name3" value="550" /> 550€

  <input type="radio" name="name4" value="600" /> 600€

  <input type="radio" name="name5" value="650" /> 650€

  <input type="radio" name="name6" value="700" /> 700€

this simple make an array without change anything. And another question, how i will can access the values when i will have this in an array mode?

thanks

Body:
This will create 20 inputs and increment value and text by 50

var count = 20;
var increment = 50;

for (y = 0; y < count; y++) {
    var inp = '<input type="radio" name="name1" value="' + increment + '" /> ' + increment + '<br />';
    $(inp).appendTo('#lista');
    increment = increment + 50;
}

Check working example at http://jsfiddle.net/fxmmN/1/


问:
Loading a YarnCluster through dask-yarn leads to java error
I'm trying to setup and run Dask-Yarn as described in the page: https://yarn.dask.org/en/latest/quickstart.html#usage.

I packaged my conda environment using conda-pack to the file environment.tar.gz and then tried to run the following in python (from the same folder):

```<code>python
>>> from dask_yarn import YarnCluster
>>> cluster = YarnCluster(environment='environment.tar.gz')
</code>```

This resulted in a java error pasted below.

```<code>19/05/28 15:45:39 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
19/05/28 15:45:40 ERROR skein.Driver: Error running Driver
java.lang.UnsupportedClassVersionError: com/google/cloud/hadoop/fs/gcs/GoogleHadoopFileSystem : Unsupported major.minor version 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:278)
        at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:363)
        at java.util.ServiceLoader$1.next(ServiceLoader.java:445)
        at org.apache.hadoop.fs.FileSystem.loadFileSystems(FileSystem.java:2750)
        at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2777)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2794)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:99)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2830)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2812)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:390)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:179)
        at com.anaconda.skein.Driver.getFs(Driver.java:304)
        at com.anaconda.skein.Driver.run(Driver.java:279)
        at com.anaconda.skein.Driver.main(Driver.java:174)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/dask_yarn/core.py", line 295, in __init__
    self._start_cluster(spec, skein_client)
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/dask_yarn/core.py", line 339, in _start_cluster
    skein_client = _get_skein_client(skein_client)
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/dask_yarn/core.py", line 46, in _get_skein_client
    return skein.Client(security=security)
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/skein/core.py", line 353, in __init__
    java_options=java_options)
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/skein/core.py", line 266, in _start_driver
    raise DriverError("Failed to start java process")
skein.exceptions.DriverError: Failed to start java process
</code>```

Some searching seems to indicate the error is related to version mismatch between compilation and run time. I tried setting environment variables as show below, but that didn't work either. Any other ideas how to solve this error?

```<code>export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk.x86_64
export JRE_HOME=$JAVA_HOME/jre
export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH
</code>```

答: The resolution for this was using Java 1.8 instead of Java 1.7. See this for example. </p>

Body:
I'm trying to setup and run Dask-Yarn as described in the page: https://yarn.dask.org/en/latest/quickstart.html#usage.

I packaged my conda environment using conda-pack to the file environment.tar.gz and then tried to run the following in python (from the same folder):

python
>>> from dask_yarn import YarnCluster
>>> cluster = YarnCluster(environment='environment.tar.gz')

This resulted in a java error pasted below.

19/05/28 15:45:39 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
19/05/28 15:45:40 ERROR skein.Driver: Error running Driver
java.lang.UnsupportedClassVersionError: com/google/cloud/hadoop/fs/gcs/GoogleHadoopFileSystem : Unsupported major.minor version 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:278)
        at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:363)
        at java.util.ServiceLoader$1.next(ServiceLoader.java:445)
        at org.apache.hadoop.fs.FileSystem.loadFileSystems(FileSystem.java:2750)
        at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2777)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2794)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:99)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2830)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2812)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:390)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:179)
        at com.anaconda.skein.Driver.getFs(Driver.java:304)
        at com.anaconda.skein.Driver.run(Driver.java:279)
        at com.anaconda.skein.Driver.main(Driver.java:174)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/dask_yarn/core.py", line 295, in __init__
    self._start_cluster(spec, skein_client)
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/dask_yarn/core.py", line 339, in _start_cluster
    skein_client = _get_skein_client(skein_client)
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/dask_yarn/core.py", line 46, in _get_skein_client
    return skein.Client(security=security)
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/skein/core.py", line 353, in __init__
    java_options=java_options)
  File "/home/.conda/envs/dask_yarn/lib/python3.7/site-packages/skein/core.py", line 266, in _start_driver
    raise DriverError("Failed to start java process")
skein.exceptions.DriverError: Failed to start java process

Some searching seems to indicate the error is related to version mismatch between compilation and run time. I tried setting environment variables as show below, but that didn't work either. Any other ideas how to solve this error?

export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk.x86_64
export JRE_HOME=$JAVA_HOME/jre
export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH


问:
Create counter column based on values in 2 dataframe columns
I am looking to create a counter column based on row values in 2 dataframe columns, represented here at Col1 and Col2.

An example of the dataset is as follows:

```<code>Col1    Col2
 a       0
 a       0
 a       0
 a       1
 a       0
 a       0
 a       0
 a       1
 a       1
 b       0
 b       0
 b       1
 b       1
 b       0
 b       0
</code>```

Where Col1 is an identification variable, and where I want the counter to start over when a new identification variable comes across (so when 'a' switches to 'b', the counter returns to 0).

Col2 is an indication of a new input in the data. When a 1 arises, a new input arises, and the 0s after that correspond to measurements in that input. Each time a 1 arises, I want the counter variable to increment 1. Each time the 1 returns to a 0 (and vice versa), I also want the counter to increment 1. Based on the above dataset, I want the output to look like the following in Col3:

```<code>Col1    Col2    Col3
 a       0       0
 a       0       0
 a       0       0
 a       1       1
 a       0       2
 a       0       2
 a       0       2
 a       1       3
 a       1       4
 b       0       0
 b       0       0
 b       1       1
 b       1       2
 b       0       3
 b       0       3
</code>```

So basically every time Col2 switches from a 0 to a 1, and each time a 1 arises, I want the counter to increment. Each time a 0 is present in Col2, I want the counter to remain the same value. And every time Col1 changes to a new ID (in this case, from 'a' to 'b') I want the counter to start over at 0.

I've been mainly doing this with conditional statements, but there are a ton of them and I'm looking to run this on a large dataset, which would take hours to run. Is there a quick and easy way to run something like this, with these conditions on both columns? Or does anyone have suggestions on transformations to this data that would make running a categorization like this easier?

I understand that this is a slightly confusing request, so please let me know if there is anything I can do to provide more clarity into what I'm looking for.

Thanks!

Body:
I am looking to create a counter column based on row values in 2 dataframe columns, represented here at Col1 and Col2.

An example of the dataset is as follows:

Col1    Col2
 a       0
 a       0
 a       0
 a       1
 a       0
 a       0
 a       0
 a       1
 a       1
 b       0
 b       0
 b       1
 b       1
 b       0
 b       0

Where Col1 is an identification variable, and where I want the counter to start over when a new identification variable comes across (so when 'a' switches to 'b', the counter returns to 0).

Col2 is an indication of a new input in the data. When a 1 arises, a new input arises, and the 0s after that correspond to measurements in that input. Each time a 1 arises, I want the counter variable to increment 1. Each time the 1 returns to a 0 (and vice versa), I also want the counter to increment 1. Based on the above dataset, I want the output to look like the following in Col3:

Col1    Col2    Col3
 a       0       0
 a       0       0
 a       0       0
 a       1       1
 a       0       2
 a       0       2
 a       0       2
 a       1       3
 a       1       4
 b       0       0
 b       0       0
 b       1       1
 b       1       2
 b       0       3
 b       0       3

So basically every time Col2 switches from a 0 to a 1, and each time a 1 arises, I want the counter to increment. Each time a 0 is present in Col2, I want the counter to remain the same value. And every time Col1 changes to a new ID (in this case, from 'a' to 'b') I want the counter to start over at 0.

I've been mainly doing this with conditional statements, but there are a ton of them and I'm looking to run this on a large dataset, which would take hours to run. Is there a quick and easy way to run something like this, with these conditions on both columns? Or does anyone have suggestions on transformations to this data that would make running a categorization like this easier?

I understand that this is a slightly confusing request, so please let me know if there is anything I can do to provide more clarity into what I'm looking for.

Thanks!

Body:
df.assign(Col4=df1.groupby('Col1').Col2.apply(lambda x:
     pd.Series(pd.np.r_[False,(x[1:]==1) |(x.values[1:] != x.values[:-1])].cumsum())).values)
   Col1  Col2  Col3  Col4
0     a     0     0     0
1     a     0     0     0
2     a     0     0     0
3     a     1     1     1
4     a     0     2     2
5     a     0     2     2
6     a     0     2     2
7     a     1     3     3
8     a     1     4     4
9     b     0     0     0
10    b     0     0     0
11    b     1     1     1
12    b     1     2     2
13    b     0     3     3
14    b     0     3     3


问:
Optimistic Concurrency Exception During Synchronous Update Call
I am attempting to modify a single boolean property on my Invoice entity.

This is my class:

```<code>public class Invoice : SoftDeletableEntity, IIsActive
{
    public Invoice()
    {
        IsEditable = true;
    }

    [ForeignKey("Booking")]
    public int BookingId { get; set; }
    public Booking Booking { get; set; }
    [ForeignKey("Customer")]
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
    public string OurReference { get; set; }
    public string CustomerReference { get; set; }
    public DateTime InvoiceDate { get; set; }
    public string InvoiceNumber { get; set; }
    [ForeignKey("AccountInformation")]
    public int AccountInformationId { get; set; }
    public AccountInformation AccountInformation { get; set; }
    public string Summary { get; set; }
    public List<InvoiceInformation> ImportantInformation { get; set; }
    [ForeignKey("InvoiceItem")]
    public List<int> InvoiceItemIds { get; set; }
    public List<InvoiceLineItem> InvoiceLineItems { get; set; }

    [ForeignKey("InvoiceDocument")]
    public List<int> InvoiceDocumentIds { get; set; }
    public List<InvoiceDocument> InvoiceDocuments { get; set; }
    public string CreatedBy { get; set; }
    public string Terms { get; set; }
    public bool IsReversal { get; set; }
    public bool IsEditable { get; set; }
    public int? ParentInvoiceId { get; set; }
}
</code>```

These classes are exported as a formatted PDF. That process works quite well, and then I have this code that checks whether or not the PDF was constructed correctly, then if the export succeeds, the code sets the invoice as ineditable like so:

```<code>    var doc = pdf.CreateInvoicePdf(resultModel, user);
    var bytes = GetPdfBytes(doc);

    if (bytes != null)
    {
        result.IsEditable = false;
    }

    unitOfWork.Commit();
</code>```

When I call this "unitOfWork.Commit();" I get the following exception:

```<code>System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while saving entities that do not expose foreign key properties for their relationships.
</code>```

The inner exception:

```<code>Message "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions."
</code>```

The most recently added foreign key reference was for CustomerId, but it is set up just like all of the other foreign keys. I have checked the database for FK = 0 for all foreign key entities and there are no missing references. Also this is running on my local, so I am certain the entity was not modified by sources other than my browser.

Any help is greatly appreciated.

答:
Here are some possible reasons which might cause such problem:

You trying to update entity with primary key Id == 0 or another default value (Guid.Empty or string.Empty). So, verify that Id is set properly.

When you try to create a new object and tell EF that it's modified using the EntityState.Modified. Then it will throw this error as it doesn't yet exist in the database. So, try to use EntityState.Added.

You tried to update or delete a row but the row doesn't exist.

Body:
I am attempting to modify a single boolean property on my Invoice entity.

This is my class:

public class Invoice : SoftDeletableEntity, IIsActive
{
    public Invoice()
    {
        IsEditable = true;
    }

    [ForeignKey("Booking")]
    public int BookingId { get; set; }
    public Booking Booking { get; set; }
    [ForeignKey("Customer")]
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
    public string OurReference { get; set; }
    public string CustomerReference { get; set; }
    public DateTime InvoiceDate { get; set; }
    public string InvoiceNumber { get; set; }
    [ForeignKey("AccountInformation")]
    public int AccountInformationId { get; set; }
    public AccountInformation AccountInformation { get; set; }
    public string Summary { get; set; }
    public List<InvoiceInformation> ImportantInformation { get; set; }
    [ForeignKey("InvoiceItem")]
    public List<int> InvoiceItemIds { get; set; }
    public List<InvoiceLineItem> InvoiceLineItems { get; set; }

    [ForeignKey("InvoiceDocument")]
    public List<int> InvoiceDocumentIds { get; set; }
    public List<InvoiceDocument> InvoiceDocuments { get; set; }
    public string CreatedBy { get; set; }
    public string Terms { get; set; }
    public bool IsReversal { get; set; }
    public bool IsEditable { get; set; }
    public int? ParentInvoiceId { get; set; }
}

These classes are exported as a formatted PDF. That process works quite well, and then I have this code that checks whether or not the PDF was constructed correctly, then if the export succeeds, the code sets the invoice as ineditable like so:

    var doc = pdf.CreateInvoicePdf(resultModel, user);
    var bytes = GetPdfBytes(doc);

    if (bytes != null)
    {
        result.IsEditable = false;
    }

    unitOfWork.Commit();

When I call this "unitOfWork.Commit();" I get the following exception:

System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while saving entities that do not expose foreign key properties for their relationships.

The inner exception:

Message "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions."

The most recently added foreign key reference was for CustomerId, but it is set up just like all of the other foreign keys. I have checked the database for FK = 0 for all foreign key entities and there are no missing references. Also this is running on my local, so I am certain the entity was not modified by sources other than my browser.

Any help is greatly appreciated.


问:
Getting first day of the month, is outputting the wrong first day of the month
I want to display the first day of the month in 'day of the week' format.
For example, The below code should select the month of August and say the day of the week 01 falls on which is Thursday, but for some reason, the below code outputs Friday which is wrong, on some months such as May it correctly says Wednesday.

```<code>$monthNumber = 3;
$base = strtotime(date('Y-m',time()) . '-01 00:00:01');
$dateTest = date("Ym" . 1, strtotime($monthNumber . " month", $base));
$unixTimestamp = strtotime($dateTest, $base);
echo date("l", $unixTimestamp);
</code>```

Does anyone have any ideas to make it show the correct day?

$base fixes a bug with it not showing the correct month.

答:
And why won't you use the dateTime?

```<code>echo (new \DateTime('first day of august 2019'))->format('l');
</code>```

Read more about Relative formats.

Body:
I want to display the first day of the month in 'day of the week' format.
For example, The below code should select the month of August and say the day of the week 01 falls on which is Thursday, but for some reason, the below code outputs Friday which is wrong, on some months such as May it correctly says Wednesday.

$monthNumber = 3;
$base = strtotime(date('Y-m',time()) . '-01 00:00:01');
$dateTest = date("Ym" . 1, strtotime($monthNumber . " month", $base));
$unixTimestamp = strtotime($dateTest, $base);
echo date("l", $unixTimestamp);

Does anyone have any ideas to make it show the correct day?

$base fixes a bug with it not showing the correct month.

Body:
And why won't you use the dateTime?

echo (new \DateTime('first day of august 2019'))->format('l');

Read more about Relative formats.


问:
bash looping through file to find beginning of string
I have a large textfile with ~ 10,000 lines of data, whereby each line may have a different number of columns. For example:

```<code>789 KKPP 2018 08 09 10 20 30 AUTO A2987 10SM 5-MIN 22/13
790 KGOX 2018 08 09 10 20 35 AUTO P0002 21/19
...
798 KLXZ 2018 08 09 10 20 40 AUTO 18013GT 7SM 21/16 RMK A02 T02060156
799 KMNO 2018 08 09 10 20 45 AUTO 10SM P0001
...
...
</code>```

I want to loop through every line and extract the 2nd column in which the prefix "P00*" appears. For example, in the above snippet of the file, I would want:

```<code>KGOX P0002
KMNO P0001
</code>```

Which correspond to the lines 790 and 799. The number of columns are completely random, and can change from one row to the next. The most important thing is that somewhere in the row, some column of text starts with "P00".

I have a simple while read loop:

```<code> while IFS='' read -r line || [[ -n "${line}" ]];
 do
 temp=$(echo ${line} | awk '{print $7}')
 if [[ ${temp:0:3} == "P00" ]];
 then
 data=${temp}
 fi
 done
</code>```

But this gets messy quickly, as the column numbers can exceed 30. Is there a simpler way to get this information and, perhaps, write to a text file? I know awk can do something that might work but can't get anything to work properly.

答:
Another simple awk script (standard Linux gawk)

```<code>awk 'match($0,/P000[^ ]+/,a){print $2, a[0]}' input.txt
</code>```

Body:
I have a large textfile with ~ 10,000 lines of data, whereby each line may have a different number of columns. For example:

789 KKPP 2018 08 09 10 20 30 AUTO A2987 10SM 5-MIN 22/13
790 KGOX 2018 08 09 10 20 35 AUTO P0002 21/19
...
798 KLXZ 2018 08 09 10 20 40 AUTO 18013GT 7SM 21/16 RMK A02 T02060156
799 KMNO 2018 08 09 10 20 45 AUTO 10SM P0001
...
...

I want to loop through every line and extract the 2nd column in which the prefix "P00*" appears. For example, in the above snippet of the file, I would want:

KGOX P0002
KMNO P0001

Which correspond to the lines 790 and 799. The number of columns are completely random, and can change from one row to the next. The most important thing is that somewhere in the row, some column of text starts with "P00".

I have a simple while read loop:

 while IFS='' read -r line || [[ -n "${line}" ]];
 do
 temp=$(echo ${line} | awk '{print $7}')
 if [[ ${temp:0:3} == "P00" ]];
 then
 data=${temp}
 fi
 done

But this gets messy quickly, as the column numbers can exceed 30. Is there a simpler way to get this information and, perhaps, write to a text file? I know awk can do something that might work but can't get anything to work properly.

Body:
Another simple awk script (standard Linux gawk)

awk 'match($0,/P000[^ ]+/,a){print $2, a[0]}' input.txt


问:
List rows order by oldest time
I am a bit new in sql and I have this problem to get an specific information from three tables. I have those three tables.

employee table

company table

employment table

EmployeeID in Employment is FK
CompanyID in Company is FK
EmploymentID in Emplyment is PK
NULL in EmploymentEndDate in Employment means that worker is currently working there.

I have been trying this but is not working

```<code>select Company.CompanyName as CompanyName , CONCAT( Employee.FirstName, ' ' ,Employee.LastName) as EmployeeName , Employment.EmploymentStartDate from Employment LEFT JOIN Employee on Employee.EmployeeID = Employment.EmployeeID
LEFT JOIN Company on Company.CompanyID = Employment.CompanyID
where Employment.EmploymentEndDate is null
and EXISTS(SELECT Employment.CompanyID, MAX(DATEDIFF( DAY,Employment.EmploymentStartDate ,GETDATE())) as MaxDate FROM  Employment where  Employment.EmploymentEndDate is null group by CompanyID)
</code>```

and is giving me this result:

which is wrong because from company "Steve's Widgets Inc" I expect only John Doe which is the most old worker.

This is exactly what I want, List all Companies and gives the name and start date of the Employee that has been working in the Company the longest out of all Employees that are currently working there.
(Expected Columns: CompanyName, EmployeeName, EmploymentStartDate)

答:
If you want to use first value it would look something like this, note I have not used first value on sql server (only on db2) and I did not test this since I don't have an sql server on hand.</p>

```<code>SELECT DISTINCT
  Company.CompanyName,
  CONCAT(Employee.FirstName, ' ', Employee.LastName) AS EmployeeName,
  FIRST_VALUE(Employment.EmploymentStartDate)
    OVER (PARTITION BY Company.CompanyName, CONCAT(Employee.FirstName, ' ', Employee.LastName)
      ORDER BY Employment.EmploymentStartDate ASC
      RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    ) AS StartDate
FROM Employment
JOIN Company ON Employment.CompanyID = Company.CompanyID
JOIN Employee ON Employment.EmployeeID = Employee.EmployeeID
WHERE Employment.EmploymentEndDate IS NULL
</code>```

Title: List rows order by oldest time

Body:
I am a bit new in sql and I have this problem to get an specific information from three tables. I have those three tables.

employee table

company table

employment table

EmployeeID in Employment is FK
CompanyID in Company is FK
EmploymentID in Emplyment is PK
NULL in EmploymentEndDate in Employment means that worker is currently working there.

I have been trying this but is not working

select Company.CompanyName as CompanyName , CONCAT( Employee.FirstName, ' ' ,Employee.LastName) as EmployeeName , Employment.EmploymentStartDate from Employment LEFT JOIN Employee on Employee.EmployeeID = Employment.EmployeeID
LEFT JOIN Company on Company.CompanyID = Employment.CompanyID
where Employment.EmploymentEndDate is null
and EXISTS(SELECT Employment.CompanyID, MAX(DATEDIFF( DAY,Employment.EmploymentStartDate ,GETDATE())) as MaxDate FROM  Employment where  Employment.EmploymentEndDate is null group by CompanyID)

and is giving me this result:

which is wrong because from company "Steve's Widgets Inc" I expect only John Doe which is the most old worker.

This is exactly what I want, List all Companies and gives the name and start date of the Employee that has been working in the Company the longest out of all Employees that are currently working there.
(Expected Columns: CompanyName, EmployeeName, EmploymentStartDate)

Body:
If you want to use first value it would look something like this, note I have not used first value on sql server (only on db2) and I did not test this since I don't have an sql server on hand.

SELECT DISTINCT
  Company.CompanyName,
  CONCAT(Employee.FirstName, ' ', Employee.LastName) AS EmployeeName,
  FIRST_VALUE(Employment.EmploymentStartDate)
    OVER (PARTITION BY Company.CompanyName, CONCAT(Employee.FirstName, ' ', Employee.LastName)
      ORDER BY Employment.EmploymentStartDate ASC
      RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    ) AS StartDate
FROM Employment
JOIN Company ON Employment.CompanyID = Company.CompanyID
JOIN Employee ON Employment.EmployeeID = Employee.EmployeeID
WHERE Employment.EmploymentEndDate IS NULL


问:
Converting VB6 varables to C#
I am converting old VB6 code and am having an issue with these constants:

VB6 code:

```<code>Private Const GENERIC_WRITE = &H40000000
Private Const GENERIC_READ = &H80000000
</code>```

C# code:

```<code>private const int GENERIC_WRITE = 0x40000000;
private const uint GENERIC_READ = 0x80000000;
</code>```

Why does the second line have to be uint?
If I do it as int, it gives me an error?

答:
The correct C# translation is:

```<code>const int GENERIC_READ = unchecked((int)0x80000000);
</code>```

In VB, 'GENERIC_READ' is implicitly an Integer with a negative value.  The only way to reproduce this in C# is to cast the unsigned integer literal to an int in an unchecked context.

The source of the confusion is a historical difference between VB and C# regarding hex literals:
0x80000000 == 2147483648 in C# but not in VB.NET

In the absence of a type suffix on the literal, hex literals in VB.NET are either of type Integer or Long, never unsigned types.

Title: Converting VB6 varables to C#

Body:
I am converting old VB6 code and am having an issue with these constants:

VB6 code:

Private Const GENERIC_WRITE = &H40000000
Private Const GENERIC_READ = &H80000000

C# code:

private const int GENERIC_WRITE = 0x40000000;
private const uint GENERIC_READ = 0x80000000;

Why does the second line have to be uint?
If I do it as int, it gives me an error?

Body:
The correct C# translation is:

const int GENERIC_READ = unchecked((int)0x80000000);

In VB, 'GENERIC_READ' is implicitly an Integer with a negative value.  The only way to reproduce this in C# is to cast the unsigned integer literal to an int in an unchecked context.

The source of the confusion is a historical difference between VB and C# regarding hex literals:
0x80000000 == 2147483648 in C# but not in VB.NET

In the absence of a type suffix on the literal, hex literals in VB.NET are either of type Integer or Long, never unsigned types.


问:
Prepared satements with bind_param() in PHP
Is there any way to write this code using prepared statements?

```<code>$sql = "SELECT *
    FROM exercises
    WHERE exercise_id IN (
        SELECT DISTINCT e.exercise_id
        FROM users u,users_subjects us, exercises e
        WHERE u.username='".$_SESSION['username']."' AND us.user_id_fk=u.id AND e.subjects=us.subject_id_fk
    );";
$result = $conn->query($sql);
</code>```

I'm trying this way, but with the sencente ‘IN’, I’m not sure how to do it:

```<code>$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username='".$_SESSION['username']."' and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");
$stmt->bind_param("" );
$stmt->execute();
$stmt->close();
</code>```

答:
```<code>$username = $_SESSION['username'];

// use ?'s in prepare
$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username=? and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");

// then pass $username to bind_param()
$stmt->bind_param("s", $username);
</code>```

Then the rest of your code should work. I'd also recommend testing your stmt commands for error handling. They all return booleans.

```<code>// use ?'s in prepare
$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username='?' and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");

if(!$stmt) echo "prepare failed: " . mysqli_error($conn);
</code>```

Same can be done for bind_param() and execute().

Body:
Is there any way to write this code using prepared statements?

$sql = "SELECT *
    FROM exercises
    WHERE exercise_id IN (
        SELECT DISTINCT e.exercise_id
        FROM users u,users_subjects us, exercises e
        WHERE u.username='".$_SESSION['username']."' AND us.user_id_fk=u.id AND e.subjects=us.subject_id_fk
    );";
$result = $conn->query($sql);

I'm trying this way, but with the sencente ‘IN’, I’m not sure how to do it:

$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username='".$_SESSION['username']."' and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");
$stmt->bind_param("" );
$stmt->execute();
$stmt->close();

Body:
$username = $_SESSION['username'];

// use ?'s in prepare
$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username=? and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");

// then pass $username to bind_param()
$stmt->bind_param("s", $username);

Then the rest of your code should work. I'd also recommend testing your stmt commands for error handling. They all return booleans.

// use ?'s in prepare
$stmt = $mysqli->prepare("SELECT * FROM exercises where exercise_id in (select distinct e.exercise_id from users u,users_subjects us, exercises e where u.username='?' and us.user_id_fk=u.id and e.subjects=us.subject_id_fk");

if(!$stmt) echo "prepare failed: " . mysqli_error($conn);

Same can be done for bind_param() and execute().


问:
firebase deploy skips exported function
I recently added a new cloud function to my project, and for some reason when I deploy it gets skipped:

```<code>firebase deploy --only functions:stripeOperation
</code>```

which results in

⚠  functions: the following filters were specified but do not match
  any functions in the project: stripeOperation

The file structure is like this:

```<code>functions/
├── src/
│   ├── stripe
│   │    ├── index.ts
│   │    ├── myTrigger.ts
│   │    ├── anotherTrigger.ts
│   │    └── stripeOperation.ts
│   ├── index.ts
</code>```

functions/src/stripe/index exports all 3 of the functions in the stripe folder.
functions/src/index exports them from the stripe folder:

```<code>export { stripeOperation, myTrigger, anotherTrigger } from './stripe';
</code>```

Here's where it gets weird - myTrigger and anotherTrigger successfully deploy, but stripeOperation doesn't. There are no build errors. Firebase isn't giving me any clues as to why it's skipped. I checked and the transpiled code looks fine. stripeOperation is a callable function but the other 2 are firestore triggers. This is the signature of stripeOperation:

```<code>export const stripeOperation = functions.https.onCall((data, context) => {
  ...
});
</code>```

Is there any way to determine why firebase won't deploy my function? I am using "firebase-functions": "^2.3.1"

Update: I have tried renaming the function, and completely switching out the function body with a previously deployed function, and neither worked.

答:
You have to export callable functions separately from trigger functions. This doesn't make sense, so I filed an issue.

functions/src/index:

```<code>export { stripeOperation } from './stripe/stripeOperation';
export { myTrigger, anotherTrigger } from './stripe';
</code>```

Title: firebase deploy skips exported function

Body:
I recently added a new cloud function to my project, and for some reason when I deploy it gets skipped:

firebase deploy --only functions:stripeOperation

which results in

⚠  functions: the following filters were specified but do not match
  any functions in the project: stripeOperation

The file structure is like this:

functions/
├── src/
│   ├── stripe
│   │    ├── index.ts
│   │    ├── myTrigger.ts
│   │    ├── anotherTrigger.ts
│   │    └── stripeOperation.ts
│   ├── index.ts

functions/src/stripe/index exports all 3 of the functions in the stripe folder.
functions/src/index exports them from the stripe folder:

export { stripeOperation, myTrigger, anotherTrigger } from './stripe';

Here's where it gets weird - myTrigger and anotherTrigger successfully deploy, but stripeOperation doesn't. There are no build errors. Firebase isn't giving me any clues as to why it's skipped. I checked and the transpiled code looks fine. stripeOperation is a callable function but the other 2 are firestore triggers. This is the signature of stripeOperation:

export const stripeOperation = functions.https.onCall((data, context) => {
  ...
});

Is there any way to determine why firebase won't deploy my function? I am using "firebase-functions": "^2.3.1"

Update: I have tried renaming the function, and completely switching out the function body with a previously deployed function, and neither worked.

Body:
You have to export callable functions separately from trigger functions. This doesn't make sense, so I filed an issue.

functions/src/index:

export { stripeOperation } from './stripe/stripeOperation';
export { myTrigger, anotherTrigger } from './stripe';


问:
How to fix stack overflow on overloaded addition operator in c++
I'm trying to learn the concept of operator overloading in c++ but I have got stuck on a problem that I'm trying to solve using the operator+ where in the my main-function I add to userdefiend classes together.
The class constructor takes a string pointer as a parameter.

My understanding of the operatoroverloading concept is that you declare a function in a class, using the keyword operatorX, and replace X with the operator that you will like to overload. Like if i would like to overload the '-' operator I should write like this operator-. But when I debug my code it results in an Stack overflow and the program stops.

The class looks as follows:

```<code>class Hello{
public:
    Hello(string str):pstr(&str){

    }
    //The overloaded function below
    Hello operator+(Hello& h1){
        Hello temp(*this);//creates a copy of the current Hello-object
        temp = temp + h1;//adds the new value to the temporary object
        return temp;
    }
private:
    string* pstr;//pointer to string-object
}
</code>```

I know that i get the stack overflow in the overloaded function.

In the main method i have the following code:

```<code>void main(){
    Hello h1("Hello ");
    h1 + Hello("World");
}
</code>```

I'm not shore that i've coded this in the right way but the result should be Hello World in the return object if i'm not mistaken.

How can I solve this so that I dont get the stack overflow when the code is running, and also how can I get the right return value?

答:
In operator overloading, the key concept to think is how would the behavior be if the type you were defining was a primitive type. For example, what would adding a pointer to string with another pointer to string look like.

As mentioned above, your definition is recursively calling operator+.

Here is an example that might be useful: https://www.geeksforgeeks.org/operator-overloading-c/

Body:
I'm trying to learn the concept of operator overloading in c++ but I have got stuck on a problem that I'm trying to solve using the operator+ where in the my main-function I add to userdefiend classes together.
The class constructor takes a string pointer as a parameter.

My understanding of the operatoroverloading concept is that you declare a function in a class, using the keyword operatorX, and replace X with the operator that you will like to overload. Like if i would like to overload the '-' operator I should write like this operator-. But when I debug my code it results in an Stack overflow and the program stops.

The class looks as follows:

class Hello{
public:
    Hello(string str):pstr(&str){

    }
    //The overloaded function below
    Hello operator+(Hello& h1){
        Hello temp(*this);//creates a copy of the current Hello-object
        temp = temp + h1;//adds the new value to the temporary object
        return temp;
    }
private:
    string* pstr;//pointer to string-object
}

I know that i get the stack overflow in the overloaded function.

In the main method i have the following code:

void main(){
    Hello h1("Hello ");
    h1 + Hello("World");
}

I'm not shore that i've coded this in the right way but the result should be Hello World in the return object if i'm not mistaken.

How can I solve this so that I dont get the stack overflow when the code is running, and also how can I get the right return value?


问:
Converting CSV to JSON in bash
Trying to convert a CSV file into a JSON

Here is two sample lines :

```<code>-21.3214077;55.4851413;Ruizia cordata
-21.3213078;55.4849803;Cossinia pinnata
</code>```

I would like to get something like :

```<code>"occurrences": [
                 {
                "position": [-21.3214077, 55.4851413],
                "taxo": {
                    "espece": "Ruizia cordata"
                 },
                 ...
             }]
</code>```

Here is my script :

```<code>    echo '"occurences": [ '

cat se.csv | while read -r line
  do
      IFS=';' read -r -a array <<< $line;
      echo -n -e '{ "position": [' ${array[0]}
      echo -n -e ',' ${array[1]} ']'
      echo -e ', "taxo": {"espece":"' ${array[2]} '"'
done
echo "]";
</code>```

I get really strange results :

```<code>   "occurences": [
 ""position": [ -21.3214077, 55.4851413 ], "taxo": {"espece":" Ruizia cordata
 ""position": [ -21.3213078, 55.4849803 ], "taxo": {"espece":" Cossinia pinnata
</code>```

What is wrong with my code ?

答:
The accepted answer uses jq to parse the input. This works but jq doesn't handle escapes i.e. input from a CSV produced from Excel or similar tools is quoted like this:

```<code>foo,"bar,baz",gaz
</code>```

will result in the incorrect output, as jq will see 4 fields, not 3.

One option is to use tab-separated values instead of comma (as long as your input data doesn't contain tabs!), along with the accepted answer.

Another option is to combine your tools, and use the best tool for each part: a CSV parser for reading the input and turning it into JSON, and jq for transforming the JSON into the target format.

The python-based csvkit will intelligently parse the CSV, and comes with a tool csvjson which will do a much better job of turning the CSV into JSON. This can then be piped through jq to convert the flat JSON output by csvkit into the target form.

With the data provided by the OP, for the desired output, this as as simple as:

```<code>csvjson --no-header-row  |
  jq '.[] | {occurrences: [{ position: [.a, .b], taxo: {espece: .c}}]}'
</code>```

Note that csvjson automatically detects ; as the delimiter, and without a header row in the input, assigns the json keys as a, b, and c.

The same also applies to writing to CSV files -- csvkit can read a JSON array or new-line delimited JSON, and intelligently output a CSV via in2csv.

Title: Converting CSV to JSON in bash

Body:
Trying to convert a CSV file into a JSON

Here is two sample lines :

-21.3214077;55.4851413;Ruizia cordata
-21.3213078;55.4849803;Cossinia pinnata

I would like to get something like :

"occurrences": [
                 {
                "position": [-21.3214077, 55.4851413],
                "taxo": {
                    "espece": "Ruizia cordata"
                 },
                 ...
             }]

Here is my script :

    echo '"occurences": [ '

cat se.csv | while read -r line
  do
      IFS=';' read -r -a array <<< $line;
      echo -n -e '{ "position": [' ${array[0]}
      echo -n -e ',' ${array[1]} ']'
      echo -e ', "taxo": {"espece":"' ${array[2]} '"'
done
echo "]";

I get really strange results :

   "occurences": [
 ""position": [ -21.3214077, 55.4851413 ], "taxo": {"espece":" Ruizia cordata
 ""position": [ -21.3213078, 55.4849803 ], "taxo": {"espece":" Cossinia pinnata

What is wrong with my code ?

Body:
The accepted answer uses jq to parse the input. This works but jq doesn't handle escapes i.e. input from a CSV produced from Excel or similar tools is quoted like this:

foo,"bar,baz",gaz

will result in the incorrect output, as jq will see 4 fields, not 3.

One option is to use tab-separated values instead of comma (as long as your input data doesn't contain tabs!), along with the accepted answer.

Another option is to combine your tools, and use the best tool for each part: a CSV parser for reading the input and turning it into JSON, and jq for transforming the JSON into the target format.

The python-based csvkit will intelligently parse the CSV, and comes with a tool csvjson which will do a much better job of turning the CSV into JSON. This can then be piped through jq to convert the flat JSON output by csvkit into the target form.

With the data provided by the OP, for the desired output, this as as simple as:

csvjson --no-header-row  |
  jq '.[] | {occurrences: [{ position: [.a, .b], taxo: {espece: .c}}]}'

Note that csvjson automatically detects ; as the delimiter, and without a header row in the input, assigns the json keys as a, b, and c.

The same also applies to writing to CSV files -- csvkit can read a JSON array or new-line delimited JSON, and intelligently output a CSV via in2csv.


问:
What is the source: attribute of a tweet sent from a tweet button using the Twitter Search API?
I'm trying to use Twitter search to find all mentions of a word that DIDN'T come from a "tweet this" button. I'm trying to build a stream of all brand mentions, but I don't want to sift through all of the retweets coming from our blog, which uses Twitter's button.

As a first step, I tried looking searching for all of the tweets that came from my personal account, filtering by source:txt. It showed all of the tweets I texted in. Then source:web. It showed all of the tweets I entered on twitter.com.

But then I tried searching with source:twitterbutton. Nothing. Then source:tweetbutton. Nothing. Same with source:tweet button. I tried searching through all of Twitter's documentation on the Tweet button to see what the source: attribute is, but couldn't find anything.

When I go through my stream of tweets without filtering for the source, I see some that say via Tweet Button so I know they exist, but I can't seem to find the right source: operator to find them automatically.

FYI: I'm using the Twitter Search API Method.

Bonus points to whoever can tell me how to negate a source (return everything EXCEPT that source)

答:
I started tweeting with the fine folks over at Tweet Deck since their application lets you look for ones that came from the Tweet Button. It turns out I was only one character away. D'oh!

Use source:tweet_button to get only tweets from Tweet Buttons. And, as Abraham mentioned, all you need is a - before the parameter for it to negate that source. Example search.

Thanks for all the assistance! Especially from @DesktopDeck!