问:
Real meaning of the 3rd parameter of _IOR
I have one driver and daemon, daemon access driver using ioctl, I am a bit confused about the third parameter of _IOR:

```<code>#define _IOR(type,nr,size)  _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size)))
</code>```

I have some code as following,
ioctl cmd defetnition:

```<code>#define TEST_GET_NUM_A  _IOR(TESTIO, 0x01, uint8_t *)
#define TEST_GET_NUM_B  _IOR(TESTIO, 0x02, uint8_t)
</code>```

ioctl in driver:

```<code>case TEST_GET_NUM_A:
    rc = put_user(data->num_keys, (uint8_t __user *) arg);
    break;
case TEST_GET_NUM_B:
    rc = put_user(data->num_keys, (uint8_t __user *) arg);
    break;
</code>```

ioctl in daemon:

```<code>uint8_t num_keys = 0;
rc = ioctl(fd, TEST_GET_NUM_A/TEST_GET_NUM_B, &num_keys);
if (rc < 0) {
    ALOGE("ioctl failed %d", rc);
    close(fd);
    return rc;
}
</code>```

both TEST_GET_NUM_A and TEST_GET_NUM_B work well, no crash happen.
My question is which one is correct one, or both?

_IOR(type,nr,size) size means the size of 3rd parameter in ioctl(fd, TEST_GET_NUM_A/B, &num_keys) or means the size of the data passed from kernel to user space?

答:
The size of the type becomes part of the ioctl number. This is intended to catch errors where the kernel and userspace accidentally use different types (or different definitions of the same type).

But that field has no effect on the behaviour of the ioctl (unless your driver explicitly reads it).

Body:
I have one driver and daemon, daemon access driver using ioctl, I am a bit confused about the third parameter of _IOR:

#define _IOR(type,nr,size)  _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size)))

I have some code as following,
ioctl cmd defetnition:

#define TEST_GET_NUM_A  _IOR(TESTIO, 0x01, uint8_t *)
#define TEST_GET_NUM_B  _IOR(TESTIO, 0x02, uint8_t)

ioctl in driver:

case TEST_GET_NUM_A:
    rc = put_user(data->num_keys, (uint8_t __user *) arg);
    break;
case TEST_GET_NUM_B:
    rc = put_user(data->num_keys, (uint8_t __user *) arg);
    break;

ioctl in daemon:

uint8_t num_keys = 0;
rc = ioctl(fd, TEST_GET_NUM_A/TEST_GET_NUM_B, &num_keys);
if (rc < 0) {
    ALOGE("ioctl failed %d", rc);
    close(fd);
    return rc;
}

both TEST_GET_NUM_A and TEST_GET_NUM_B work well, no crash happen.
My question is which one is correct one, or both?

_IOR(type,nr,size) size means the size of 3rd parameter in ioctl(fd, TEST_GET_NUM_A/B, &num_keys) or means the size of the data passed from kernel to user space?


来源: stackexchange

问:
Where can I find documentation for the preview() and show() function for VideoClips?
I just want to see how exactly they work, and I can't seem to find them in either moviepy or pygame's websites. Basically I just want to see at what time a user presses a specific key during a clip, and record that time/possibly insert an image at that time while the movie is playing. I know moviepy does that already to some extent, but it's only for mouse clicks.

Thank you for your time.

答:
I found the source code but no answer. I ended up editing the source code, and while that works, I would much rather do something else than that if possible.

To have a more elaborate answer to the rest of my question, basically it's not something I think is feasible to directly edit the video file WHILE it's playing. I also don't know if it would be a good idea to save every single and just combine them. I was able to find an extremely efficient, but niche solution by modifying the preview frame while it plays, and having that persist across every new frame. Then I saved JUST the overlay to a file, and can use that however else I feel.

I have seen no other threads/users actually deal with moviepy in this way, so feel free to PM me or ask on the thread if you want more info.

Source code here

ContentLicense: CC BY-SA 4.0


问:
Is there any annotation to ignore from the change of the response type in fasterxml?
I have an Android app (written by Kotlin).

It uses an external server and the server provide an XML as the response.

Last week, the server response was changed.
A new element was added into the response.

So my app crashed...

To resolve this, I added an annotation:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
</code>```

And it works fine.

But I have a question.
If the server change the response data type, how can I handle it?
For example, here is the response:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <data>
        <sessionid>hello</sessionid>
        <endpoint>https://test.com</endpoint>
        <id>123</id>
        <pw>testpassword</pw>
    </data>
</response>
```

<p>Now, if the type of "pw" element is changed to "Integer" like below, Exception occurs.</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<response>
    <data>
        <sessionid>hello</sessionid>
        <endpoint>https://test.com</endpoint>
        <id>123</id>
        <pw>0000</pw>    <!-- server response type is changed from String to Integer -->
    </data>
</response>
</code>```

```<code>Cannot deserialize value of type `java.lang.Integer` from String "pw": not a valid Integer value
</code>```

And my app will be crash.

I want to prevent the crash from this kind of change.
Is there any good solution? or annotation like "@JsonIgnoreProperties"?

I think that the "Any" type can be a solution.
But this is the last solution...
I want to find a smarter solution.

答:
Yes, you could use a custom setter for the pw variable that coerces types:

```<code>class ResponseData(pw: String) {
    var pw: String
        set(value: Any) {
            field = when(value) {
                is String -> value
                else -> value.toString()
            }
        }
}
</code>```

Note: this will still throw exceptions if the type cannot be coerced to a string via the toString method.

For a data class to use a custom setter see this example

```<code>data class C(private val _propertyWithSetter: String) {
    val propertyWithSetter: String
        get() = _propertyWithSetter
        set(value) {
            /* execute setter logic */
            _propertyWithSetter = value
        }
}
</code>```

Body:
I have an Android app (written by Kotlin).

It uses an external server and the server provide an XML as the response.

Last week, the server response was changed.
A new element was added into the response.

So my app crashed...

To resolve this, I added an annotation:

@JsonIgnoreProperties(ignoreUnknown = true)

And it works fine.

But I have a question.
If the server change the response data type, how can I handle it?
For example, here is the response:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <data>
        <sessionid>hello</sessionid>
        <endpoint>https://test.com</endpoint>
        <id>123</id>
        <pw>testpassword</pw>
    </data>
</response>

Now, if the type of "pw" element is changed to "Integer" like below, Exception occurs.

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <data>
        <sessionid>hello</sessionid>
        <endpoint>https://test.com</endpoint>
        <id>123</id>
        <pw>0000</pw>
    </data>
</response>

Cannot deserialize value of type `java.lang.Integer` from String "pw": not a valid Integer value

And my app will be crash.

I want to prevent the crash from this kind of change.
Is there any good solution? or annotation like "@JsonIgnoreProperties"?

I think that the "Any" type can be a solution.
But this is the last solution...
I want to find a smarter solution.

Body:
Yes, you could use a custom setter for the pw variable that coerces types:

class ResponseData(pw: String) {
    var pw: String
        set(value: Any) {
            field = when(value) {
                is String -> value
                else -> value.toString()
            }
        }
}

Note: this will still throw exceptions if the type cannot be coerced to a string via the toString method.

For a data class to use a custom setter see this example

data class C(private val _propertyWithSetter: String) {
    val propertyWithSetter: String
        get() = _propertyWithSetter
        set(value) {
            /* execute setter logic */
            _propertyWithSetter = value
        }
}


问:
calling a function within a function
I've had a look through several of the related questions and just can't seem to see the issue!

the following two functions are within my function include file and for some reason I cannot seem to get the check_orientation function to return scale to the display_months_news function.

I'm fairly sure I'm just missing something really obviously.

the display_news function

```<code>function display_months_news()
{
    //header('Content-type: image/jpeg');
    $year = date("y");
    $year = "20" .$year;
    $month = date("m");
    if ($month) {
        switch ($month){
            case "01": $month = "January"; break;
            case "02": $month = "February"; break;
            case "03": $month = "March"; break;
            case "04": $month = "April"; break;
            case "05": $month = "May"; break;
            case "06": $month = "June"; break;
            case "07": $month = "July"; break;
            case "08": $month = "August"; break;
            case "09": $month = "September"; break;
            case "10": $month = "October"; break;
            case "11": $month = "November"; break;
            case "12": $month = "December"; break;
        }
    } else {
        echo '<p>The date field is empty.</p>';
    }
    $nowdate = $month." ".$year;

    $result = mysql_query("SELECT * FROM news ORDER BY sqldate DESC LIMIT 6") or die(mysql_error());

    while ($row = mysql_fetch_array($result)) {
        global $imgurl;
        $imgurl = $row['img1'];

        check_orientation4($imgurl);

        $comcount = comment_count($row['nid']);
        if ($comcount == NULL) {$comcount = 0;}

        echo '<div class="news-preview-container">';
        echo '<div class="news-preview-container-date">';
        echo "<P>" .$row['mmonth']. " ".$row['dday']. ", " .$row['yyear']. "</p><BR>";
        echo '</div>';
        echo '<div class="news-preview-container-title">';
        echo "<p><a href='article.php?id=" .$row['nid']."'>" .$row['title']."</a></p><BR>";
        echo '</div>';
        echo '<div class="news-preview-container-inner">';
        echo '<div class="news-preview-container-text">';
        echo '<p>'.ShortenText($row['body']).'</p>';
        echo '</div>';
        echo '<div class="news-preview-container-image"><img src="'.$imgurl.'"'.$scale.'"></div><BR></div>';
        echo '<div class="news-preview-container-bottombar">Posted in '.$row[tag].' / '.$comcount.' Comments</div>';
        echo '</div>';

    }
}
</code>```

and the check_orientation function

```<code>function check_orientation4($imgurls){

if ($imgurls == NULL){ echo "";  }
else {
        $imgurlshrunk = NULL;
        $maxsize = 120;
        $filename = NULL;
        $height = NULL;
        $width = NULL;
        $scale = NULL;
        $imgurlshrunk = $imgurls;
        $filename = basename($imgurlshrunk);
        $filename = "admin/uploads/" . $filename;
        list($width,$height,$type,$attr) = getimagesize("$filename");
        $wRatio = $maxsize / $width;
        $hRatio= $maxsize / $height;

    global $scale;

    if ( ($width <= $maxsize) && ($height <= $maxsize))
      {

        $scale = "";
        return $scale;
      }
    elseif ( ($wRatio * $height) < $maxsize)
    {
        $scale = "width = '100%'";
        return $scale;
    }
    elseif  ($height == NULL)
    {

        echo "empty height";
    }
    else
    {
    global $height;
        $scale = "height = '100%'";
        return $scale;
    }       }}
</code>```

Thanks in advance to whoever points out the silly mistake i'm missing!

答:
Shouldn't you be returning scale into a variable of some kind?  Right now you're just running the function.  You should do something like:</p>

```<code>$toScale = check_orientation4($imgurl);
</code>```

ContentLicense: CC BY-SA 3.0

Title: calling a function within a function

Body:
I've had a look through several of the related questions and just can't seem to see the issue!

the following two functions are within my function include file and for some reason I cannot seem to get the check_orientation function to return scale to the display_months_news function.

I'm fairly sure I'm just missing something really obviously.

the display_news function

function display_months_news()
{
    //header('Content-type: image/jpeg');
    $year = date("y");
    $year = "20" .$year;
    $month = date("m");
    if ($month) {
        switch ($month){
            case "01": $month = "January"; break;
            case "02": $month = "February"; break;
            case "03": $month = "March"; break;
            case "04": $month = "April"; break;
            case "05": $month = "May"; break;
            case "06": $month = "June"; break;
            case "07": $month = "July"; break;
            case "08": $month = "August"; break;
            case "09": $month = "September"; break;
            case "10": $month = "October"; break;
            case "11": $month = "November"; break;
            case "12": $month = "December"; break;
        }
    } else {
        echo '
The date field is empty.
';
    }
    $nowdate = $month." ".$year;

    $result = mysql_query("SELECT * FROM news ORDER BY sqldate DESC LIMIT 6") or die(mysql_error());

    while ($row = mysql_fetch_array($result)) {
        global $imgurl;
        $imgurl = $row['img1'];

        check_orientation4($imgurl);

        $comcount = comment_count($row['nid']);
        if ($comcount == NULL) {$comcount = 0;}

        echo '
';
        echo '
';
        echo "
" .$row['mmonth']. " ".$row['dday']. ", " .$row['yyear']. "

";
        echo '
';
        echo '
';
        echo "
" .$row['title']."

";
        echo '
';
        echo '
';
        echo '
';
        echo '
'.ShortenText($row['body']).'
';
        echo '
';
        echo '

';
        echo '
Posted in '.$row[tag].' / '.$comcount.' Comments
';
        echo '
';

    }
}

and the check_orientation function

function check_orientation4($imgurls){

if ($imgurls == NULL){ echo "";  }
else {
        $imgurlshrunk = NULL;
        $maxsize = 120;
        $filename = NULL;
        $height = NULL;
        $width = NULL;
        $scale = NULL;
        $imgurlshrunk = $imgurls;
        $filename = basename($imgurlshrunk);
        $filename = "admin/uploads/" . $filename;
        list($width,$height,$type,$attr) = getimagesize("$filename");
        $wRatio = $maxsize / $width;
        $hRatio= $maxsize / $height;

    global $scale;

    if ( ($width <= $maxsize) && ($height <= $maxsize))
      {

        $scale = "";
        return $scale;
      }
    elseif ( ($wRatio * $height) < $maxsize)
    {
        $scale = "width = '100%'";
        return $scale;
    }
    elseif  ($height == NULL)
    {

        echo "empty height";
    }
    else
    {
    global $height;
        $scale = "height = '100%'";
        return $scale;
    }       }}

Thanks in advance to whoever points out the silly mistake i'm missing!

Body:
Shouldn't you be returning scale into a variable of some kind?  Right now you're just running the function.  You should do something like:

$toScale = check_orientation4($imgurl);


问:
Lodash uniqWith, how say lodash keep last duplicate
Hello i'm using lodash uniqWith method for remove duplicated items which have same id in my array.

but lodash keep first duplicated item.
But i wan't to keep last duplicated item.

what can i do for that ?

```<code>var result = _.uniqWith(editedData, function(arrVal, othVal) {
      return arrVal.id === othVal.id;
    });
    console.log(result)
</code>```

答:
You can create a uniqByLast function using _.flow(). Use _.keyBy() to get an object by id, and _.values() to get an an array:

const { flow, partialRight: pr, keyBy, values } = _

const lastUniqBy = iteratee => flow(
  pr(keyBy, iteratee),
  values
)

const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]

const result = lastUniqBy('id')(arr)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script></code>```

And the same idea using lodash/fp:

const { flow, keyBy, values } = _

const lastUniqBy = iteratee => flow(
  keyBy(iteratee),
  values
)

const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]

const result = lastUniqBy('id')(arr)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script></code>```

Body:
Hello i'm using lodash uniqWith method for remove duplicated items which have same id in my array.

but lodash keep first duplicated item.
But i wan't to keep last duplicated item.

what can i do for that ?

var result = _.uniqWith(editedData, function(arrVal, othVal) {
      return arrVal.id === othVal.id;
    });
    console.log(result)

Body:
You can create a uniqByLast function using _.flow(). Use _.keyBy() to get an object by id, and _.values() to get an an array:

const { flow, partialRight: pr, keyBy, values } = _

const lastUniqBy = iteratee => flow(
  pr(keyBy, iteratee),
  values
)

const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]

const result = lastUniqBy('id')(arr)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

And the same idea using lodash/fp:

const { flow, keyBy, values } = _

const lastUniqBy = iteratee => flow(
  keyBy(iteratee),
  values
)

const arr = [{ id: 1, val: 1 }, { id: 1, val: 2 }, { id: 2, val: 1 }, { id: 2, val: 2 }]

const result = lastUniqBy('id')(arr)

console.log(result)

<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>


问:
Use Flask-SqlAlchemy to query relationship database
I'm trying to use Flask-SQLAlchemy to query out database for the user profile page

So far I don't have a solution for this problem, only able to query all the User data by using users.query.all()

Each user has their own role_id, department_id, researchfield_id.

How can i query out all the Role, Department, ResearchField data that has relationship with User through ID?

```<code>class User(UserMixin, db.Model):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    password_hash = db.Column(db.String(128))
    is_admin = db.Column(db.Boolean, default=False)
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    research_id = db.Column(db.Integer, db.ForeignKey('researchfields.id'))

class Department(db.Model):
    __tablename__ = "departments"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    user = db.relationship('User', backref='department',
                                lazy='dynamic')

class Role(db.Model):

    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    users = db.relationship('User', backref='role',
                                lazy='dynamic')

class ResearchField(db.Model):

    __tablename__ = "researchfields"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), index=True)
    parent_id = db.Column(db.Integer, db.ForeignKey("researchfields.id") , nullable=True)
    users = db.relationship('User', backref='researchfield', lazy='dynamic')
</code>```

答:
If I understand correctly, what you're seeking for is a way to filter out users based on a specific model. Because in your example, the other way around is redundant - every user has only one department, so no need to filter out departments for that user. In order to achieve that, I would use the backref method provided by SQLAlchemy from the User model.

Here's an example consisting of two of the models:

from sqlalchemy.orm import backref

class User(UserMixin, db.Model):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    password_hash = db.Column(db.String(128))
    is_admin = db.Column(db.Boolean, default=False)
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'))
    department = db.relationship("Department", backref=backref("users", lazy="dynamic"))

class Department(db.Model):
    __tablename__ = "departments"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
```

<p>Now you can use:</p>

<pre class="lang-py prettyprint-override"><code>department = Department.query.filter_by(id=1).first()
print(department.users.filter_by(is_admin=True).all()) # get all admins with that department
</code>```

Every user has only one department, so you could just get the user's department by:

user = User.query.filter_by(id=1).first()
print(user.department) # prints Department object
```

Body:
I'm trying to use Flask-SQLAlchemy to query out database for the user profile page

So far I don't have a solution for this problem, only able to query all the User data by using users.query.all()

Each user has their own role_id, department_id, researchfield_id.

How can i query out all the Role, Department, ResearchField data that has relationship with User through ID?

class User(UserMixin, db.Model):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    password_hash = db.Column(db.String(128))
    is_admin = db.Column(db.Boolean, default=False)
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    research_id = db.Column(db.Integer, db.ForeignKey('researchfields.id'))

class Department(db.Model):
    __tablename__ = "departments"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    user = db.relationship('User', backref='department',
                                lazy='dynamic')

class Role(db.Model):

    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    users = db.relationship('User', backref='role',
                                lazy='dynamic')

class ResearchField(db.Model):

    __tablename__ = "researchfields"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), index=True)
    parent_id = db.Column(db.Integer, db.ForeignKey("researchfields.id") , nullable=True)
    users = db.relationship('User', backref='researchfield', lazy='dynamic')

Body:
If I understand correctly, what you're seeking for is a way to filter out users based on a specific model. Because in your example, the other way around is redundant - every user has only one department, so no need to filter out departments for that user. In order to achieve that, I would use the backref method provided by SQLAlchemy from the User model.

Here's an example consisting of two of the models:

from sqlalchemy.orm import backref

class User(UserMixin, db.Model):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    password_hash = db.Column(db.String(128))
    is_admin = db.Column(db.Boolean, default=False)
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'))
    department = db.relationship("Department", backref=backref("users", lazy="dynamic"))

class Department(db.Model):
    __tablename__ = "departments"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)

Now you can use:

department = Department.query.filter_by(id=1).first()
print(department.users.filter_by(is_admin=True).all()) # get all admins with that department

Every user has only one department, so you could just get the user's department by:

user = User.query.filter_by(id=1).first()
print(user.department) # prints Department object


问:
Delete same Ids in array by id, after sum total (price) value
I have php order array and I'm sending this array to shipping service but my clients have 2-3 order with same shop_id. I'm sending 3th shipping this is problem must be send only 1 shipping with shop_id and must be sum(total) price.

How can I do this? My array output under below.

```<code>Array
(
    [date] => 2019-05-23
    [name] => Alex
    [shop_id] => 1
    [price] => 13.45
)

Array
(
    [date] => 2019-05-23
    [name] => Alex
    [shop_id] => 1
    [price] => 22.45
)

Array
(
    [date] => 2019-05-23
    [name] => Alan
    [shop_id] => 3
    [price] => 83.56
)
</code>```

My array code:

```<code>    print("```".print_r($orders,true)."```");
</code>```

My array must be:

```<code>   Array
    (
        [date] => 2019-05-23
        [name] => Alex
        [shop_id] => 1  // LOOK AT SAME shop_id ones in array and
        [price] => 35.90 // do total price them and delete 1 more items.
    )

    Array
    (
        [date] => 2019-05-23
        [name] => Alan
        [shop_id] => 3
        [price] => 83.56
    )
</code>```

My codes;

```<code>  $newarray = array();
        foreach($arr as $ar)
        {
            foreach($ar as $k => $v)
            {
                if(array_key_exists($v, $newarray))
                    $newarray[$v]['price'] = $newarray[$v]['price'] + $ar['price'];
                else if($k == 'shop_id')
                    $newarray[$v] = $ar;
            }
        }

        print("```".print_r($newarray,true)."```");
</code>```

Output

```<code>Array
(
)
</code>```

答:
You can build an result-array that is indexed by the shop-id. Then iterate over the data-array and check if that key already exists. If the key does not exists add the item to the results-array. If the item exists just update the price.

$data = [
    [
        "date"      => "2019-05-23",
        "name"      => "Alex",
        "shop_id"   => 1,
        "price"     => 12.34,
    ],
    [
        "date"      => "2019-05-23",
        "name"      => "Alex",
        "shop_id"   => 2,
        "price"     => 12.34,
    ],
    [
        "date"      => "2019-05-23",
        "name"      => "Alex",
        "shop_id"   => 1,
        "price"     => 23.45,
    ],
];

$result = [];
foreach ($data as $item) {
    $key = 'SHOP-ID-'.$item['shop_id'];
    if (!array_key_exists($key, $result)) {
        $result[$key] = $item;
    } else {
        $result[$key]['price'] += $item['price'];
    }
}

var_dump($result);
```

Body:
I have php order array and I'm sending this array to shipping service but my clients have 2-3 order with same shop_id. I'm sending 3th shipping this is problem must be send only 1 shipping with shop_id and must be sum(total) price.

How can I do this? My array output under below.

Array
(
    [date] => 2019-05-23
    [name] => Alex
    [shop_id] => 1
    [price] => 13.45
)

Array
(
    [date] => 2019-05-23
    [name] => Alex
    [shop_id] => 1
    [price] => 22.45
)

Array
(
    [date] => 2019-05-23
    [name] => Alan
    [shop_id] => 3
    [price] => 83.56
)

My array code:

    print("
".print_r($orders,true)."
");

My array must be:

   Array
    (
        [date] => 2019-05-23
        [name] => Alex
        [shop_id] => 1  // LOOK AT SAME shop_id ones in array and
        [price] => 35.90 // do total price them and delete 1 more items.
    )

    Array
    (
        [date] => 2019-05-23
        [name] => Alan
        [shop_id] => 3
        [price] => 83.56
    )

My codes;

  $newarray = array();
        foreach($arr as $ar)
        {
            foreach($ar as $k => $v)
            {
                if(array_key_exists($v, $newarray))
                    $newarray[$v]['price'] = $newarray[$v]['price'] + $ar['price'];
                else if($k == 'shop_id')
                    $newarray[$v] = $ar;
            }
        }

        print("
".print_r($newarray,true)."
");

Output

Array
(
)


问:
ListBox showing one property in different rows
I am using the following code for binding ListBox to a list i.e. List and set the binding Path=Name. But the list box shows just the one name with letter divided in rows. Like if a Name is JOHN, the list box row 1 shows "J", row 2 shows "O", row 3 shows "H", row 4 shows "N". Here's the code.

Xaml

```<code><ListBox Height="Auto" ItemsSource="{Binding Path=Name}" HorizontalAlignment="Stretch" Margin="0,80,0,0" Name="ledgerListView" VerticalAlignment="Stretch" Width="200" KeyDown="ledgerListView_KeyDown" MouseDoubleClick="ledgerListView_MouseDoubleClick" IsSynchronizedWithCurrentItem="True" />
</code>```

Code-Behind

```<code>List<Ledgers> ledgers = new List<Ledgers>();
        ledgers = DAL_Ledgers.LoadLedgers();
        this.DataContext = ledgers;
</code>```

答:
The ItemsSource property needs to be bound to the source collection that you want to generate the list box's items from. In this case that would just be the DataContext. To show the name for each item you can either apply a DataTemplate to the ItemTemplate property containing what you want to show for each item, or for a simple case like this just use the DisplayMemberPath to specify the Name property.</p>

```<code><ListBox ItemsSource="{Binding}" DisplayMemberPath="Name" x:Name="ledgerListView"/>
</code>```

Body:
I am using the following code for binding ListBox to a list i.e. List and set the binding Path=Name. But the list box shows just the one name with letter divided in rows. Like if a Name is JOHN, the list box row 1 shows "J", row 2 shows "O", row 3 shows "H", row 4 shows "N". Here's the code.

Xaml

<ListBox Height="Auto" ItemsSource="{Binding Path=Name}" HorizontalAlignment="Stretch" Margin="0,80,0,0" Name="ledgerListView" VerticalAlignment="Stretch" Width="200" KeyDown="ledgerListView_KeyDown" MouseDoubleClick="ledgerListView_MouseDoubleClick" IsSynchronizedWithCurrentItem="True" />

Code-Behind

List<Ledgers> ledgers = new List<Ledgers>();
        ledgers = DAL_Ledgers.LoadLedgers();
        this.DataContext = ledgers;

Body:
The ItemsSource property needs to be bound to the source collection that you want to generate the list box's items from. In this case that would just be the DataContext. To show the name for each item you can either apply a DataTemplate to the ItemTemplate property containing what you want to show for each item, or for a simple case like this just use the DisplayMemberPath to specify the Name property.

<ListBox ItemsSource="{Binding}" DisplayMemberPath="Name" x:Name="ledgerListView"/>


问:
How to write MongoDB aggregation in Kotlin/JS
I'm trying to use Kotlin JS with the MongoDB Browser SDK.
The SDK allows a function in JavaScript like:

```<code>const someData = db("database")
        .collection("stories")
        .aggregate(
                [
                    {
                        $lookup:
                            { from: "person",
                              localField: "person_id",
                              foreignField: "_id",
                              as: "people"
                            }
                    }
                ]
        )
</code>```

This is how I am converting it into Kotlin:

```<code>val aggregate = mapOf(
        "\$lookup" to mapOf(
                "from" to "people",
                "localField" to "people_id",
                "foreignField" to "_id",
                "as" to "people"
        )
)
val someData = mongodb
    .db("database")
    .collection("stories")
    .aggregate(aggregate)
</code>```

But I get the following error: Uncaught RangeError: Maximum call stack size exceeded

Any ideas?

答:
Kotlin/JS mapOf is not compatible with plain JavaScript key-value objects. Use json function instead.

```<code>import kotlin.js.json

val aggregate = arrayOf(
    json(
        "\$lookup" to json(
            "from" to "people",
            "localField" to "people_id",
            "foreignField" to "_id",
            "as" to "people"
        )
    )
)
</code>```

Body:
I'm trying to use Kotlin JS with the MongoDB Browser SDK.
The SDK allows a function in JavaScript like:

const someData = db("database")
        .collection("stories")
        .aggregate(
                [
                    {
                        $lookup:
                            { from: "person",
                              localField: "person_id",
                              foreignField: "_id",
                              as: "people"
                            }
                    }
                ]
        )

This is how I am converting it into Kotlin:

val aggregate = mapOf(
        "\$lookup" to mapOf(
                "from" to "people",
                "localField" to "people_id",
                "foreignField" to "_id",
                "as" to "people"
        )
)
val someData = mongodb
    .db("database")
    .collection("stories")
    .aggregate(aggregate)

But I get the following error: Uncaught RangeError: Maximum call stack size exceeded

Any ideas?

Body:
Kotlin/JS mapOf is not compatible with plain JavaScript key-value objects. Use json function instead.

import kotlin.js.json

val aggregate = arrayOf(
    json(
        "\$lookup" to json(
            "from" to "people",
            "localField" to "people_id",
            "foreignField" to "_id",
            "as" to "people"
        )
    )
)


问:
How do I register a variable in ansible-console?
Well, the title says pretty much all.

When running a playbook, you can always:

```<code>- name: my task
  register: variable_name
  some_module:
    some_args: true
</code>```

However, when running ansible-console, how do I register the result of a module execution in a variable?

答:
register is only accessible in playbooks launched with ansible-playbook. ansible-console is just a wrapper over the base ansible to launch ad_hoc commands. You would have to parse the returned json yourself and call set_fact with the result. I didn't see any command available in the console to do that.

Meanwhile, you can have a look at this similar question where there is an interesting possible workaround using callback plugin that might be usable with console.

Body:
Well, the title says pretty much all.

When running a playbook, you can always:

- name: my task
  register: variable_name
  some_module:
    some_args: true

However, when running ansible-console, how do I register the result of a module execution in a variable?


问:
bigquery - save large query results
I have a question about saving large query results to either an external csv or to google sheets. I have a simple query that generates about 23,000 results:

```<code>#standardSQL
SELECT DISTINCT id1, id2
FROM `tableA`
WHERE A LIKE "%abcdefg%"
AND B LIKE "%some text%"
AND ts >= TIMESTAMP("2019-04-25 00:00:00")
AND ts < TIMESTAMP("2019-05-29 23:59:00")
</code>```

I can't save more than 16,000 of these results to a csv file or output to google sheets. I want to be able to save all 23,000 results either into 1 file or into several files, but I don't know how to go about doing this. My permissions don't allow me to save the query output to a new table.

答:
Run the query as usual, then click the "Job information" tab.

There will be a "Destination table" entry with a link that says, "Temporary table." Click the link.

From this page, click "Export," then "Export to GCS."

Now you can export the contents of the table as CSV.

Title: bigquery - save large query results

Body:
I have a question about saving large query results to either an external csv or to google sheets. I have a simple query that generates about 23,000 results:

#standardSQL
SELECT DISTINCT id1, id2
FROM `tableA`
WHERE A LIKE "%abcdefg%"
AND B LIKE "%some text%"
AND ts >= TIMESTAMP("2019-04-25 00:00:00")
AND ts < TIMESTAMP("2019-05-29 23:59:00")

I can't save more than 16,000 of these results to a csv file or output to google sheets. I want to be able to save all 23,000 results either into 1 file or into several files, but I don't know how to go about doing this. My permissions don't allow me to save the query output to a new table.


问:
Virtual address space in 64 bit systems running in compatibility mode
I saw that on a 64 bit windows OS the user virtual address space available is 8 terra bytes. But if the program we are executing on this is running in 32 bit compatibility mode is this much of user space still available ? or does it behave like a normal 32 bit OS and gives only 2GB user address space?</p>

答: It should be noted that running a 32-bit process on IIS 6.0+ with a 64-bit machine/OS, a process can address up to 4GB of memory.</p>

OwnerDisplayName: Naveen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Naveen


问:
Call Method that inside Another Component - React Js
i need to know how to fetch state of component from other component by calling the seconed component method inside of first component ?
like :

class General extends Component {

  state = {
    input:"
   }

   fetchState() {
    return this.state;
   }

  handleChange () {
    this.setState({[e.target.name]: e.traget.value});
  }

  render() {
    return <input type="text" name="input" onChange={this.handleChange.bind(this}>
  }

}

class Car extends Component {

  render() {
    console.log( General.fetchState() );
    return null;
  }

}```

i know i can use static method but i don't have access to this keyword.

答:
There are many approaches, I suggest using a general state accessible from both components.

Check ReactN for simplicity or Redux for a more robust solution. Note Redux has a big learning curve and quite some boilerplate that, depending on the size of your App, it could not be necessary.

Using globals is not advisable on many situations, but to answer your question, you could also do this:

General component:

```<code>class General extends Component {
    constructor(){
        global.fetchGeneralState = this.fetchState;
    }
    fetchState = () => {
        return this.state;
    }
}
</code>```

Then from the Car component, you can just call: global.fetchGeneralState(); and you will get the state from the General component.

Body:
i need to know how to fetch state of component from other component by calling the seconed component method inside of first component ?
like :

class General extends Component {

  state = {
    input:"
   }

   fetchState() {
    return this.state;
   }

  handleChange () {
    this.setState({[e.target.name]: e.traget.value});
  }

  render() {
    return <input type="text" name="input" onChange={this.handleChange.bind(this}>
  }

}

class Car extends Component {

  render() {
    console.log( General.fetchState() );
    return null;
  }

}

i know i can use static method but i don't have access to this keyword.

Body:
There are many approaches, I suggest using a general state accessible from both components.

Check ReactN for simplicity or Redux for a more robust solution. Note Redux has a big learning curve and quite some boilerplate that, depending on the size of your App, it could not be necessary.

Using globals is not advisable on many situations, but to answer your question, you could also do this:

General component:

class General extends Component {
    constructor(){
        global.fetchGeneralState = this.fetchState;
    }
    fetchState = () => {
        return this.state;
    }
}

Then from the Car component, you can just call: global.fetchGeneralState(); and you will get the state from the General component.


问:
CSRF token missing or incorrect (Django)
My form is created like so

```<code><form class="k-form" id="k_form" novalidate="novalidate">{% csrf_token %}
</code>```

and closed later in the html.

This is my AJAX post:

```<code>    $('#submit').on("click",function(e){
    var ready_to_submit = true;
    if(ready_to_submit){
        e.preventDefault();
        var local_data = new Object();
        local_data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();

        console.log(local_data.csrfmiddlewaretoken);
        var json_data = JSON.stringify(local_data);

        console.log(json_data);
        $.ajax({
            type:'POST',
            url:'/create_new_group/create_group/',
            data:json_data ,
            success:function(data){
                    if(data.status == 1){
                            //success!
                            console.log('Success!')
                    }
                    else if(data.status == 2){
                            //failed
                            console.log('Failed!')
                    }
            }
    });

    }
});
</code>```

This returns Forbidden (CSRF token missing or incorrect.): /create_new_group/create_group/ on my Django server. What am I doing wrong?

答:
Try adding to your imports:

```<code>from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
</code>```

and above your view function:

```<code>@method_decorator(csrf_exempt, name='dispatch')
</code>```

It solved my Forbidden (CSRF token missing or incorrect.):

Body:
My form is created like so

<form class="k-form" id="k_form" novalidate="novalidate">{% csrf_token %}

and closed later in the html.

This is my AJAX post:

    $('#submit').on("click",function(e){
    var ready_to_submit = true;
    if(ready_to_submit){
        e.preventDefault();
        var local_data = new Object();
        local_data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();

        console.log(local_data.csrfmiddlewaretoken);
        var json_data = JSON.stringify(local_data);

        console.log(json_data);
        $.ajax({
            type:'POST',
            url:'/create_new_group/create_group/',
            data:json_data ,
            success:function(data){
                    if(data.status == 1){
                            //success!
                            console.log('Success!')
                    }
                    else if(data.status == 2){
                            //failed
                            console.log('Failed!')
                    }
            }
    });

    }
});

This returns Forbidden (CSRF token missing or incorrect.): /create_new_group/create_group/ on my Django server. What am I doing wrong?

Body:
Try adding to your imports:

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

and above your view function:

@method_decorator(csrf_exempt, name='dispatch')

It solved my Forbidden (CSRF token missing or incorrect.):


问:
How to input values into already defined arrays?
Write a program which outputs 10 given numbers into two rows, one for odd and one for even numbers. Use arrays.

After declaring an input array for 10 numbers which the user enters, I tried declaring separate arrays for odd and even values which would later be sorted by a for-loop.

I get stuck when I need to assign these values n to odd or even arrays.

```<code>int input[10];
int odd[]{};
int even[]{};
int n;

for(n=0;n<10;n++)
{
    if ((input[n])%2==0)
    {
      odd[n] = n;
    }
    else
    {
      even[n] = n;
    }
</code>```

答:
A nice trick to avoid dynamic allocation or any additional storage is to partition the set.  This appears in algorithms such as quicksort, so every computer scientist should learn it.

All you have to do is start with two indexes or pointers, one moving forward and one backward.  As long as an item is in the correct partition, move the pointer past it.  Once both pointers have found elements in the wrong partition, swap them and continue.  Once the pointers converge, the partition is complete.

Or, if you want to leave the input unchanged, this allows you to do a single allocation equal to the size of the entire input, without reallocation or moving already-processed items to a new buffer.

Body:
Write a program which outputs 10 given numbers into two rows, one for odd and one for even numbers. Use arrays.

After declaring an input array for 10 numbers which the user enters, I tried declaring separate arrays for odd and even values which would later be sorted by a for-loop.

I get stuck when I need to assign these values n to odd or even arrays.

int input[10];
int odd[]{};
int even[]{};
int n;

for(n=0;n<10;n++)
{
    if ((input[n])%2==0)
    {
      odd[n] = n;
    }
    else
    {
      even[n] = n;
    }


问:
Trouble with dividing a multiplies number by two
I've created a variable that adds two numbers together than another which multiplies that number by 2. After these two functions I try to then divide the result of these two functions by two. It will not work. Is it because I did not make the result of the previous function a global variable?

I've tried making it a global var but it doesn't work.

```<code>def add(num1,num2):
    return num1 + num2

def multiply():
    mult = add(1,2)*2
    print(mult)

def divide():
    start = multiply() /2
    print(start)

divide()
</code>```

I expected the result 3 but instead it threw up an error message instead. What did I do wrong?

答:
Your multiply() doesn't return anything so when the divide() starts to work, it tries to divide None to 2 and raises an error. Here is a bit fixed code:

```<code>def add(num1,num2):
    return num1 + num2

def multiply():
    mult = add(1,2)*2
    return mult

def divide():
    start = multiply() /2
    return start

print(divide())
</code>```

It will print:

3.0

But here is deeper problem:

Your multiply and divide functions have no inputs so they are useless and multiply function and divide function. You can rewrite them as:

```<code>def add(num1,num2):
    return num1 + num2

def multiply(num1,num2):
    return num1 * num2

def divide(num1,num2):
    return num1 / num2

print(divide(add(1, 3), multiply(2, 5)))
</code>```

0.4

Body:
I've created a variable that adds two numbers together than another which multiplies that number by 2. After these two functions I try to then divide the result of these two functions by two. It will not work. Is it because I did not make the result of the previous function a global variable?

I've tried making it a global var but it doesn't work.

def add(num1,num2):
    return num1 + num2

def multiply():
    mult = add(1,2)*2
    print(mult)

def divide():
    start = multiply() /2
    print(start)

divide()

I expected the result 3 but instead it threw up an error message instead. What did I do wrong?

Body:
Your multiply() doesn't return anything so when the divide() starts to work, it tries to divide None to 2 and raises an error. Here is a bit fixed code:

def add(num1,num2):
    return num1 + num2

def multiply():
    mult = add(1,2)*2
    return mult

def divide():
    start = multiply() /2
    return start

print(divide())

It will print:

3.0

But here is deeper problem:

Your multiply and divide functions have no inputs so they are useless and multiply function and divide function. You can rewrite them as:

def add(num1,num2):
    return num1 + num2

def multiply(num1,num2):
    return num1 * num2

def divide(num1,num2):
    return num1 / num2

print(divide(add(1, 3), multiply(2, 5)))

0.4


问:
AngularJS 1.6.7 custom directive not rendering
I am learning AngularJS and I am trying to create a custom directive. In my index.html file I have the following

```<code><h3><product-title></product-title></h3>
</code>```

In my app.js file I have:

```<code>var app = angular.module('store', []);

app.directive('productTitle', function(){
    return {
      restrict: 'E',
      templateUrl: 'product-title.html'
  };
});
</code>```

The product-title.html is in the same directory as the html file and I am also running this on an Apache service so there should not be any issues with Angular's Ajax call. The template is not rendering for some reason. Does anyone have an idea about what the problem is? Also, side note, the console is showing no errors and the network is not showing a call to product-title.html. I also have the ng-app="store" in my index.html file.

In product-title.html

```<code>{{product.name}}
<em class="pull-right">{{product.price | currency}}</em>
</code>```

答: It was a caching issue. Clearing the cache (using developer tools) solved the problem. </p>

Body:
I am learning AngularJS and I am trying to create a custom directive. In my index.html file I have the following

<product-title></product-title>

In my app.js file I have:

var app = angular.module('store', []);

app.directive('productTitle', function(){
    return {
      restrict: 'E',
      templateUrl: 'product-title.html'
  };
});

The product-title.html is in the same directory as the html file and I am also running this on an Apache service so there should not be any issues with Angular's Ajax call. The template is not rendering for some reason. Does anyone have an idea about what the problem is? Also, side note, the console is showing no errors and the network is not showing a call to product-title.html. I also have the ng-app="store" in my index.html file.

In product-title.html

{{product.name}}
{{product.price | currency}}


问:
How to loop through two lists simultaneously?
I have referred to the following question at: Using foreach loop to iterate through two lists. My question is this, with regards to the chosen answer: Can the o.DoSomething be a comparison? As in:

```<code>For Each a in ListA.Concat(ListB)
    If(a from ListA=a from ListB) Then
        Do Something here
    End If
Next
</code>```

As you might've guessed, I'm using VB.Net and would like to know how I can do what I have shown here. That would basically be to iterate through a joined list separately/independently. Thanks!

答:
On solution would be to have a dictionary with items from the second list, then loop through your first list and retrieve the corresponding item in the second one, using the dictionary. Here's an example, assuming you want to compare items with an ID property:</p>

```<code>Dim DictB = ListB.ToDictionary(Function(x) x.ID)
For each itemA in ListA
    If DictB.ContainsKey(itemA.ID)
        'Item is in both lists
        Dim itemB = DictB(itemA.ID)
        'Do something here
    End If
Next
</code>```

Body:
I have referred to the following question at: Using foreach loop to iterate through two lists. My question is this, with regards to the chosen answer: Can the o.DoSomething be a comparison? As in:

For Each a in ListA.Concat(ListB)
    If(a from ListA=a from ListB) Then
        Do Something here
    End If
Next

As you might've guessed, I'm using VB.Net and would like to know how I can do what I have shown here. That would basically be to iterate through a joined list separately/independently. Thanks!

Body:
On solution would be to have a dictionary with items from the second list, then loop through your first list and retrieve the corresponding item in the second one, using the dictionary. Here's an example, assuming you want to compare items with an ID property:

Dim DictB = ListB.ToDictionary(Function(x) x.ID)
For each itemA in ListA
    If DictB.ContainsKey(itemA.ID)
        'Item is in both lists
        Dim itemB = DictB(itemA.ID)
        'Do something here
    End If
Next


问:
How to round (or perhaps cut) of a float based on some conditions
I am trying to make a cryptocurrency bot and I am stuck at a problem. I want to round of the balances based on the data from the exchange because otherwise the exchange doesn’t accept the order request. For example my account contains 0.0044859999999999995 btc and the exchange Stepsize(a fancy name for rounding factor) is 0.00000100, how do I get 0.004485 and not rounded up because then the exchange will give error.
I have tried to do it with the following code.but doesn’t work </p>

```<code>import sys, signal, json, time
import random
import math
num = 0.0044859999999999995
numCoins = num - math.fmod(num, 0.000001)
print (numCoins) # want to get 0.004485 `
</code>```

答:
Try this:</p>

```<code>>>> import decimal
>>> decimal.getcontext().rounding = decimal.ROUND_DOWN
>>> decimal.getcontext().prec = 28
>>> amount = decimal.Decimal('0.0044859999999999995')
>>> step = decimal.Decimal('0.00000100')
>>> rounded_amount=int(amount/step)*step
>>> print(rounded_amount)
0.00448500
>>>
</code>```

Body:
I am trying to make a cryptocurrency bot and I am stuck at a problem. I want to round of the balances based on the data from the exchange because otherwise the exchange doesn’t accept the order request. For example my account contains 0.0044859999999999995 btc and the exchange Stepsize(a fancy name for rounding factor) is 0.00000100, how do I get 0.004485 and not rounded up because then the exchange will give error.
I have tried to do it with the following code.but doesn’t work

import sys, signal, json, time
import random
import math
num = 0.0044859999999999995
numCoins = num - math.fmod(num, 0.000001)
print (numCoins) # want to get 0.004485 `

Body:
Try this:

>>> import decimal
>>> decimal.getcontext().rounding = decimal.ROUND_DOWN
>>> decimal.getcontext().prec = 28
>>> amount = decimal.Decimal('0.0044859999999999995')
>>> step = decimal.Decimal('0.00000100')
>>> rounded_amount=int(amount/step)*step
>>> print(rounded_amount)
0.00448500
>>>


问:
How do i remove a like from a photo in my code
I have written a program for a photo upload site where users can like photos, I have a test script to like the photo then display all the likes then i want to remove the like and display all the likes now. How do i do this?

```<code>import java.util.*;

public class Likes {
    private static Hashtable<Photo, TreeSet<User>> likes = new Hashtable<>();

    //like photo
    public static void like(Photo photo, User user) {
        try {
            likes.get(photo).add(user);
        }
        catch (NullPointerException e) {
            likes.put(photo, new TreeSet<>());
            likes.get(photo).add(user);
        }
    }

    //unlike photo
    public static void unlike(Photo photo, User user) {
        try {
            likes.get(photo.remove(user));
        }
        catch (NullPointerException e) {

        }
    }

    //has liked photo
    public boolean hasliked(Photo photo, User user) {
        try {
            return likes.get(photo).contains(user);
        }
        catch (NullPointerException e) {
            return false;
        }
    }

    //get all likes
    public List<Photo> getAllLikes(User user){
        // new empty list
        List<Photo> likedphotos = new ArrayList<Photo>();

        for (Photo photo : likes.keySet()) {
            if(hasliked(photo, user)){
                // add photo to list
                likedphotos.add(photo);
            }
            // return that initial list
        }

        return likedphotos;

    }

    public String toString() {
        return likes.toString();
    }

    public void get(Photo remove) {
    }

    public void remove(Photo photo1, User user1) {
    }
}
</code>```

Tests:

```<code>import java.sql.SQLOutput;
import java.util.*;

public class TestDrive {

    public static void main(String[] args) throws InputValidationException {

        //create 2 photo object
        Photo photo1 = new Photo();
        Photo photo2 = new Photo();

        //create 1 user object
        User user1 = new User();

        //create 1 like object
        Likes likes1 = new Likes();

        //set 2 photos
        photo1.setimageURL("photo of user 2");
        photo2.setimageURL("photo of user 1");

        //print the 2 photos
        System.out.println(photo1.getimageURL());
        System.out.println(photo2.getimageURL());

        //set 1 user
        user1.setUserName("oopnoob");

        //print the username
        System.out.println(user1.getUserName());

        //Like the 2 photos

        Likes.like(photo1, user1);
        Likes.like(photo2, user1);

        //Test the hasliked method to see if user1 has liked both photos - both should return true

        System.out.println("Should be true: " + likes1.hasliked(photo1, user1));
        System.out.println("Should be true: " + likes1.hasliked(photo2, user1));

        //Test the getAllLikes for user1. Should print 2 photos.

        System.out.println("user1 liked: " + likes1.getAllLikes(user1));

//i dont know how to remove the like from the photo

        //Test the unlike feature by unliking photo1

        likes1.unlike(photo1, user1);

        //Test the getAllLikes - should only print one photo

        System.out.println("user1 liked: " + likes1.getAllLikes(user1));

    }

}
</code>```

答:
Based on this part of your code

```<code>   //unlike photo
public static void unlike(Photo photo, User user) {
    try {
        likes.get(photo.remove(user));
    }
    catch (NullPointerException e) {

    }
}
</code>```

It looks like you are removing the photo and not the 'like'

The code should be

```<code>    //unlike photo
public static void unlike(Photo photo, User user) {
    try {
        likes.get(photo).remove(user);
    }
    catch (NullPointerException e) {

    }
}
</code>```

Note: Catching a NullPointerException in a class is a really bad idea. If you think a value like photo or user can be null, its best to check before you use the value.  It's also not smart to catch an exception and then  ignore it.
Thanks to @Ghostcat for pointing that out to me.

Body:
I have written a program for a photo upload site where users can like photos, I have a test script to like the photo then display all the likes then i want to remove the like and display all the likes now. How do i do this?

import java.util.*;

public class Likes {
    private static Hashtable<Photo, TreeSet<User>> likes = new Hashtable<>();

    //like photo
    public static void like(Photo photo, User user) {
        try {
            likes.get(photo).add(user);
        }
        catch (NullPointerException e) {
            likes.put(photo, new TreeSet<>());
            likes.get(photo).add(user);
        }
    }

    //unlike photo
    public static void unlike(Photo photo, User user) {
        try {
            likes.get(photo.remove(user));
        }
        catch (NullPointerException e) {

        }
    }

    //has liked photo
    public boolean hasliked(Photo photo, User user) {
        try {
            return likes.get(photo).contains(user);
        }
        catch (NullPointerException e) {
            return false;
        }
    }

    //get all likes
    public List<Photo> getAllLikes(User user){
        // new empty list
        List<Photo> likedphotos = new ArrayList<Photo>();

        for (Photo photo : likes.keySet()) {
            if(hasliked(photo, user)){
                // add photo to list
                likedphotos.add(photo);
            }
            // return that initial list
        }

        return likedphotos;

    }

    public String toString() {
        return likes.toString();
    }

    public void get(Photo remove) {
    }

    public void remove(Photo photo1, User user1) {
    }
}

Tests:

import java.sql.SQLOutput;
import java.util.*;

public class TestDrive {

    public static void main(String[] args) throws InputValidationException {

        //create 2 photo object
        Photo photo1 = new Photo();
        Photo photo2 = new Photo();

        //create 1 user object
        User user1 = new User();

        //create 1 like object
        Likes likes1 = new Likes();

        //set 2 photos
        photo1.setimageURL("photo of user 2");
        photo2.setimageURL("photo of user 1");

        //print the 2 photos
        System.out.println(photo1.getimageURL());
        System.out.println(photo2.getimageURL());

        //set 1 user
        user1.setUserName("oopnoob");

        //print the username
        System.out.println(user1.getUserName());

        //Like the 2 photos

        Likes.like(photo1, user1);
        Likes.like(photo2, user1);

        //Test the hasliked method to see if user1 has liked both photos - both should return true

        System.out.println("Should be true: " + likes1.hasliked(photo1, user1));
        System.out.println("Should be true: " + likes1.hasliked(photo2, user1));

        //Test the getAllLikes for user1. Should print 2 photos.

        System.out.println("user1 liked: " + likes1.getAllLikes(user1));

//i dont know how to remove the like from the photo

        //Test the unlike feature by unliking photo1

        likes1.unlike(photo1, user1);

        //Test the getAllLikes - should only print one photo

        System.out.println("user1 liked: " + likes1.getAllLikes(user1));

    }

}

Body:
Based on this part of your code

   //unlike photo
public static void unlike(Photo photo, User user) {
    try {
        likes.get(photo.remove(user));
    }
    catch (NullPointerException e) {

    }
}

It looks like you are removing the photo and not the 'like'

The code should be

    //unlike photo
public static void unlike(Photo photo, User user) {
    try {
        likes.get(photo).remove(user);
    }
    catch (NullPointerException e) {

    }
}

Note: Catching a NullPointerException in a class is a really bad idea. If you think a value like photo or user can be null, its best to check before you use the value.  It's also not smart to catch an exception and then  ignore it.
Thanks to @Ghostcat for pointing that out to me.


问:
Connect to Kubernetes mongo db in different namespace
Can anyone point out how to connect to the mongo db instance using mongo client using either command line client or from .net core programs with connection strings?

We have created a sample cluster in digitalocean with a namespace, let's say mongodatabase.

We installed the mongo statefulset with 3 replicas. We are able to successfully connect with the below command
 kubectl --kubeconfig=configfile.yaml -n mongodatabase exec -ti mongo-0 mongo
But when we connect from a different namespace or from default namespace with the pod names in the below format, it doesn't work.

```<code> kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0.mongo.mongodatabase.cluster.svc.local mongo
</code>```

where mongo-0.mongo.mongodatabase.cluster.svc.local is in pod-0.service_name.namespace.cluster.svc.local (also tried pod-0.statfulset_name.namespace.cluster.svc.local and pod-0.service_name.statefulsetname.namespace.cluster.svc.local) etc.,

Can any one help with the correct dns name/connection string to be used while connecting with mongo client in command line and also from the programs like java/.net core etc.,?

Also should we use kubernetes deployment instead of statefulsets here?

答:
Your question about Deployments vs StatefulSets should be a different question.  But the answer is that the StatefulSet is used when you want "Stable Persistent Storage" kubernetes.io.

Also from the same page "stable is synonymous with persistence across Pod (re)scheduling".  So basically your mongo instance is backed by a PeristentVolume and you want the volume reattached after the pod is rescheduled.

Body:
Can anyone point out how to connect to the mongo db instance using mongo client using either command line client or from .net core programs with connection strings?

We have created a sample cluster in digitalocean with a namespace, let's say mongodatabase.

We installed the mongo statefulset with 3 replicas. We are able to successfully connect with the below command
 kubectl --kubeconfig=configfile.yaml -n mongodatabase exec -ti mongo-0 mongo
But when we connect from a different namespace or from default namespace with the pod names in the below format, it doesn't work.

 kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0.mongo.mongodatabase.cluster.svc.local mongo

where mongo-0.mongo.mongodatabase.cluster.svc.local is in pod-0.service_name.namespace.cluster.svc.local (also tried pod-0.statfulset_name.namespace.cluster.svc.local and pod-0.service_name.statefulsetname.namespace.cluster.svc.local) etc.,

Can any one help with the correct dns name/connection string to be used while connecting with mongo client in command line and also from the programs like java/.net core etc.,?

Also should we use kubernetes deployment instead of statefulsets here?


问:
running a command as a super user from a python script
So I'm trying to get a process to be run as a super user from within a python script using subprocess.  In the ipython shell something like

```<code>proc = subprocess.Popen('sudo apach2ctl restart',
                        shell=True, stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
</code>```

works fine, but as soon as I stick it into a script I start getting: sudo: apach2ctl: command not found.

I would guess this is due to the way sudo handles environments on ubuntu. (I've also tried sudo -E apche2ctl restart and sudo env path=$PATH apache2ctl restart with no avail)

So my question is basically, if I want to run apache2ctl restart as super user that prompts the user for the super user password when required, how should I go about doing this?  I have no intention of storing passwords in the script.

Edit:

I've tried passing in the commands as both a string and tokenized into a list.  In the python interpreter, with a string I'll get the password prompt properly (still doesnt work in a python script as in my original problem), a list just gives the help screen for sudo.

Edit 2:

So what I gather is that while Popen will work with some commands just as strings when shell=True, it takes

```<code>proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart'])
</code>```

without 'shell=True' to get sudo to work.

Thanks!

答:
The safest way to do this is to prompt for the password beforehand and then pipe it into the command. Prompting for the password will avoid having the password saved anywhere in your code and it also won't show up in your bash history. Here's an example:</p>

```<code>from getpass import getpass
from subprocess import Popen, PIPE

password = getpass("Please enter your password: ")
# sudo requires the flag '-S' in order to take input from stdin
proc = Popen("sudo -S apach2ctl restart".split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
# Popen only accepts byte-arrays so you must encode the string
proc.communicate(password.encode())
</code>```

OwnerDisplayName: Silfheed

Body:
So I'm trying to get a process to be run as a super user from within a python script using subprocess.  In the ipython shell something like

proc = subprocess.Popen('sudo apach2ctl restart',
                        shell=True, stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)

works fine, but as soon as I stick it into a script I start getting: sudo: apach2ctl: command not found.

I would guess this is due to the way sudo handles environments on ubuntu. (I've also tried sudo -E apche2ctl restart and sudo env path=$PATH apache2ctl restart with no avail)

So my question is basically, if I want to run apache2ctl restart as super user that prompts the user for the super user password when required, how should I go about doing this?  I have no intention of storing passwords in the script.

Edit:

I've tried passing in the commands as both a string and tokenized into a list.  In the python interpreter, with a string I'll get the password prompt properly (still doesnt work in a python script as in my original problem), a list just gives the help screen for sudo.

Edit 2:

So what I gather is that while Popen will work with some commands just as strings when shell=True, it takes

proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart'])

without 'shell=True' to get sudo to work.

Thanks!

LastEditorDisplayName: Silfheed

Body:
The safest way to do this is to prompt for the password beforehand and then pipe it into the command. Prompting for the password will avoid having the password saved anywhere in your code and it also won't show up in your bash history. Here's an example:

from getpass import getpass
from subprocess import Popen, PIPE

password = getpass("Please enter your password: ")
# sudo requires the flag '-S' in order to take input from stdin
proc = Popen("sudo -S apach2ctl restart".split(), stdin=PIPE, stdout=PIPE, stderr=PIPE)
# Popen only accepts byte-arrays so you must encode the string
proc.communicate(password.encode())


问:
Make a background image transparent using CSS
I have a scenario where I need a transparent background image but I have no control over the dynamically generated images I use. For that reason Transparent PNG is out of the question. All child elements within the same div should NOT be effected and should be fully visible.

I know how to apply transparency to background colours and block level elements but can you do this for a background image?

答:
No. Not technically. You'd have to apply a background-color in order to get this to work because you'd be fading the color and image, rather than just the image. Remember that a background image is not styleable content.

You could probably hack it by using an image instead of a background image and there a mixture of relative and absolute positioning with some z-indexing on top. But that's the only way I can think of!


问:
What if password has an '@' when using command line proxy at pip install?
Trying to install a package using pip in which the network has a firewall and we needed to set a proxy on the command.

This is the syntax we followed:
pip install --proxy=domain\username:passwd@proxy.address:port package_name

But it fails (error message below):

```<code> Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 authenticationrequired'))'
</code>```

The tricky part is that user's password has an '@' in the middle, I'm wondering if it's messing the syntax (as the system understands the proxy address is right after the first '@').

We tried to escape the @ from the password with: @ and also using %40, and even \%40. None of them worked.

Also tried to SET a variable to pass the proxy URL with the credentials to overcome the command line chars read, but didn't work as well.

Any suggestions?

答:
[SOLVED]
I had to ask the user to change the password and then it worked out.</p>

Body:
Trying to install a package using pip in which the network has a firewall and we needed to set a proxy on the command.

This is the syntax we followed:
pip install --proxy=domain\username:passwd@proxy.address:port package_name

But it fails (error message below):

 Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 authenticationrequired'))'

The tricky part is that user's password has an '@' in the middle, I'm wondering if it's messing the syntax (as the system understands the proxy address is right after the first '@').

We tried to escape the @ from the password with: @ and also using %40, and even \%40. None of them worked.

Also tried to SET a variable to pass the proxy URL with the credentials to overcome the command line chars read, but didn't work as well.

Any suggestions?


问:
Docker container registers Enter Key on terminal continuously
I am building an image with Dockerfile. I am pulling latest Ubuntu and golang images.

After importing all the directories and building the executable with go build inside the image, I want to run the executable. For that reason, I tried using either ENTRYPOINT or CMD, so that the executable runs when the container starts.

The issue is that when I do that and I am running the container in either attached or detached mode, it keeps registering the Enter Key repeatedly all the time (and CPU usage goes crazy). I can understand this because my script waits for a key to be registered and then some input to terminate, but since the Enter key is registered immediately again, it prints a message and then the same loop happens again.

When I build my image without executing (no CMD or ENTRYPOINT) the binary, I then run the container (the binary is still built inside the image) with a bash terminal and I execute the binary and all goes normal as it should, without any Enter Key registering all the time.

Any ideas why this might be happening???

Brief description of my Dockerfile:

```<code># Import Images
FROM ubuntu:18.04
FROM golang:1.10

# Open ports
EXPORT ...

# Copy dependencies to GOPATH in docker file
COPY github.com/user/dependencies /go/src/github.com/user/dependencies
...

# Set working directory and build executable
WORKDIR /go/src/github.com/user/app-folder
RUN go build

# Run the binary (or not)
CMD ["app_name"]
-----OR-----
CMD ["./app_name"]
-----OR-----
ENTRYPOINT app_name
-----OR-----
ENTRYPOINT /go/src/github.com/user/app-folder/app_name
</code>```

In the end, I tried all these, one at a time, I just included them like this for display. The result was always the same. The result in the terminal is:

```<code>...
Are you sure you want to exit? y/n
running. press enter to stop.

Are you sure you want to exit? y/n
running. press enter to stop.
...
</code>```

The go script is as follows:

```<code>// running flag is set to True and then it scans for a newline
    for running {
        fmt.Println("running. press enter to stop.")
        fmt.Scanln()
        fmt.Println("Are you sure you want to exit? y/n")
        if models.ConfirmUserAction() {
            running = false
            close(models.DbBuffer)
        }
    }
</code>```

and the models package that includes the ConfirmUserAction function:

```<code>//ConfirmUserAction waits (blocks) for user input, returns true if input was Y/y, else false.
func ConfirmUserAction() bool {
    var confirm string
    fmt.Scanln(&confirm)
    if confirm == "y" || confirm == "Y" {
        return true
    }

    return false
}
</code>```

答:
I found a way to bypass this issue by creating a shell script inside the container, which then runs the executable (maybe a bit hacky way, but the Enter Key is not registering any more all the time).

So now, instead of running the executable at the ENTRYPOINT on my Dockerfile, I am running the shell script at the ENTRYPOINT which simply includes something like this:

```<code>#! /bin/sh
sleep 1;

echo "Starting Metrics Server..."
./metrics_server
</code>```

The metrics_server is my compiled executable and I am setting the working directory WORKDIR, inside my Dockerfile to be were the executable and the shell script are.

Something worth mentioning about this, is that I already have imported the Ubuntu image in my Dockerfile (FROM ubuntu:18.04), as I need it anyways. I am saying this because it might not work without it (not entirely sure, I did not try it).

Body:
I am building an image with Dockerfile. I am pulling latest Ubuntu and golang images.

After importing all the directories and building the executable with go build inside the image, I want to run the executable. For that reason, I tried using either ENTRYPOINT or CMD, so that the executable runs when the container starts.

The issue is that when I do that and I am running the container in either attached or detached mode, it keeps registering the Enter Key repeatedly all the time (and CPU usage goes crazy). I can understand this because my script waits for a key to be registered and then some input to terminate, but since the Enter key is registered immediately again, it prints a message and then the same loop happens again.

When I build my image without executing (no CMD or ENTRYPOINT) the binary, I then run the container (the binary is still built inside the image) with a bash terminal and I execute the binary and all goes normal as it should, without any Enter Key registering all the time.

Any ideas why this might be happening???

Brief description of my Dockerfile:

# Import Images
FROM ubuntu:18.04
FROM golang:1.10

# Open ports
EXPORT ...

# Copy dependencies to GOPATH in docker file
COPY github.com/user/dependencies /go/src/github.com/user/dependencies
...

# Set working directory and build executable
WORKDIR /go/src/github.com/user/app-folder
RUN go build

# Run the binary (or not)
CMD ["app_name"]
-----OR-----
CMD ["./app_name"]
-----OR-----
ENTRYPOINT app_name
-----OR-----
ENTRYPOINT /go/src/github.com/user/app-folder/app_name

In the end, I tried all these, one at a time, I just included them like this for display. The result was always the same. The result in the terminal is:

...
Are you sure you want to exit? y/n
running. press enter to stop.

Are you sure you want to exit? y/n
running. press enter to stop.
...

The go script is as follows:

// running flag is set to True and then it scans for a newline
    for running {
        fmt.Println("running. press enter to stop.")
        fmt.Scanln()
        fmt.Println("Are you sure you want to exit? y/n")
        if models.ConfirmUserAction() {
            running = false
            close(models.DbBuffer)
        }
    }

and the models package that includes the ConfirmUserAction function:

//ConfirmUserAction waits (blocks) for user input, returns true if input was Y/y, else false.
func ConfirmUserAction() bool {
    var confirm string
    fmt.Scanln(&confirm)
    if confirm == "y" || confirm == "Y" {
        return true
    }

    return false
}

Body:
I found a way to bypass this issue by creating a shell script inside the container, which then runs the executable (maybe a bit hacky way, but the Enter Key is not registering any more all the time).

So now, instead of running the executable at the ENTRYPOINT on my Dockerfile, I am running the shell script at the ENTRYPOINT which simply includes something like this:

#! /bin/sh
sleep 1;

echo "Starting Metrics Server..."
./metrics_server

The metrics_server is my compiled executable and I am setting the working directory WORKDIR, inside my Dockerfile to be were the executable and the shell script are.

Something worth mentioning about this, is that I already have imported the Ubuntu image in my Dockerfile (FROM ubuntu:18.04), as I need it anyways. I am saying this because it might not work without it (not entirely sure, I did not try it).


问:
how to fix '403 (Forbidden)' on a $http.get request to etherpad
[header][1]
[header][2]

i am trying to send a get request to  etherpad  hosted in a different domain.   the OPTIONS preflight  request goes through but the get request returns  403 status.

however  when  i install  CORS for chrome extension  the request goes through

when i install cors chrome extension the request goes through

here is my code:
/* ........ export draft to html/pdf/word ........ */

```<code>            //get content for this template
            var url = Drafting.domain + Drafting.port + '/p/' + Drafting.padID + '/export/html?' + 'apikey=' + Drafting.apikey;

            $http.get(url).then(function(response, status){
                if(typeof(callback)==='function' && callback)
                {
                    callback(response.data);
                }
            });
        ```}

  [1]: https://i.stack.imgur.com/25dsj.png
  [2]: https://i.stack.imgur.com/ivHnn.png
```

答: i just passed 'withCredentials:true' together with the url and then modified the importexport.js inside the etherpad files  where 'AccessControlAllowOrigin' was set to '*' i replaced it with a specific domain and it worked.</p>

Body:
[header][1]
[header][2]

i am trying to send a get request to  etherpad  hosted in a different domain.   the OPTIONS preflight  request goes through but the get request returns  403 status.

however  when  i install  CORS for chrome extension  the request goes through

when i install cors chrome extension the request goes through

here is my code:
/* ........ export draft to html/pdf/word ........ */

            //get content for this template
            var url = Drafting.domain + Drafting.port + '/p/' + Drafting.padID + '/export/html?' + 'apikey=' + Drafting.apikey;

            $http.get(url).then(function(response, status){
                if(typeof(callback)==='function' && callback)
                {
                    callback(response.data);
                }
            });
        ```}

  [1]: https://i.stack.imgur.com/25dsj.png
  [2]: https://i.stack.imgur.com/ivHnn.png


问:
go get on forked github repo got "unexpected module path" error
I'm currently working something on AWS Cloudformation which using this repo https://github.com/awslabs/goformation. Because I did some customise so I made a fork https://github.com/vrealzhou/goformation.

Now in my other project (using go module) I'm trying to using go get github.com/vrealzhou/goformation@v2.3.1 and I've got this error:

go: github.com/vrealzhou/goformation@v0.0.0-20190513073615-ff3b65adb278: parsing go.mod: unexpected module path "github.com/awslabs/goformation"
go: error loading module requirements
```

Does anyone know the reason and how to solve this problem? Thanks

答:
You can use replace in your go.mod to use a fork instead of the upstream version. That way, you can make whatever modifications you need to the code without having to update the module path or import paths.

To be specific, in this case, you can do the following in your go.mod (I tested this by forking the repo, making a small change, and confirming it showed up):

```<code>require github.com/awslabs/goformation v1.4.1

replace github.com/awslabs/goformation => github.com/vrealzhou/goformation master
</code>```

The first time you build or test, master will be replaced by the latest pseudo-version for your fork to make sure you get repeatable builds. The replace requires a specific version for the replacement.

Body:
I'm currently working something on AWS Cloudformation which using this repo https://github.com/awslabs/goformation. Because I did some customise so I made a fork https://github.com/vrealzhou/goformation.

Now in my other project (using go module) I'm trying to using go get github.com/vrealzhou/goformation@v2.3.1 and I've got this error:

go: github.com/vrealzhou/goformation@v0.0.0-20190513073615-ff3b65adb278: parsing go.mod: unexpected module path "github.com/awslabs/goformation"
go: error loading module requirements

Does anyone know the reason and how to solve this problem? Thanks

Body:
You can use replace in your go.mod to use a fork instead of the upstream version. That way, you can make whatever modifications you need to the code without having to update the module path or import paths.

To be specific, in this case, you can do the following in your go.mod (I tested this by forking the repo, making a small change, and confirming it showed up):

require github.com/awslabs/goformation v1.4.1

replace github.com/awslabs/goformation => github.com/vrealzhou/goformation master

The first time you build or test, master will be replaced by the latest pseudo-version for your fork to make sure you get repeatable builds. The replace requires a specific version for the replacement.


问:
How to avoid branching for a call where the number of arguments is dependent on conditionals?
I'm converting some code from using CreateProcess to use boost-process instead. I need to replace my CreateProcess usages with boost::process::child. The problem is they have incompatible ways for me to say "I want to use the default value". What used to be a one line command has become sixteen if statements.

The function I currently use works like this (simplified):

```<code>void CreateProcess(int, float);
</code>```

Each parameter had a value you could use to indicate you wanted the default. I'll use 0 in this example:

```<code>int int_param = ...;
float float_param = ...;

CreateProcess(0, 0); //Use both defaults
CreateProcess(int_param, 0); //Use default float
CreateProcess(0, float_param); //Use default int
CreateProcess(int_param, float_param); //No defaults
</code>```

This is a common design. You know what I am talking about. Whether I wanted to use the default value or not could be decided with a simple conditional, such as (... ? 0 : int_param). This allowed every CreateProcess call to be a single line of code.

```<code>CreateProcess( (... ? 0 : int_param), (... ? 0 : float_param) );
</code>```

Where I used to call CreateProcess, I now want to create a child class. The constructor for child works like this:

```<code>template<typename ...Args>
explicit child(Args&&...args);
</code>```

Instead of passing a specific value to use a default, I have to pass nothing.

```<code>int int_param = ...;
float float_param = ...;

child c; //Use both defaults
child c(int_param); //Use default float
child c(float_param); //Use default int
child c(int_param, float_param); //No defaults
child c(float_param, int_param); //Argument order is irrelevant
</code>```

So far my only "solution" is to use if branches.

```<code>if (...) {
    if (...)
        child c;
    else
        child c(float_param);
} else {
    if (...)
        child c(int_param);
    else
        child c(int_param, float_param);
}
</code>```

This example has only two possible arguments and it becomes four branches. The real child has four possible arguments, so every instance has sixteen branches.

What I would like is some way of building the call to avoid this branching. A solution specific to boost::process is also fine.

FYI, the last two arguments to child may or may not be the same type.

答:
If you want to be able to leave out parameters in the call, and do things like:

```<code>create_child();
create_child(std::make_optional(int_param));
create_child(std::make_optional(float_param),
             (... ? std::optional<int>{} : int_param);
</code>```

You can use some templates and a recursive function. The following code is an example. There are ways to make this better, like only creating one child and not returning a bunch, or using perfect forwarding.

```<code>//Recursion base case
//Recieves values to pass to child in a tuple
//Returns created child
template <typename... Ts>
child create_child_detail(std::tuple<Ts...> t)
{
    //Is there a better way to apply a tuple to a ctor?
    return std::apply([](Ts... ts){ return child(ts...); }, t);
}

//Recursive function
//Removes arguments from variadic template and adds arguments to tuple
template <typename... Ts, typename O, typename... Os>
child create_child_detail(std::tuple<Ts...> t, std::optional<O> o, std::optional<Os>... os)
{
    if (o) //Valid optional, add value to tuple to send to child
        return create_child_detail(std::tuple_cat(t, std::make_tuple(*o)), os...);
    else //Invalid optional, value should not be added to child
        return create_child_detail(t, os...);
}

//Called by user
//Just calls create_child_detail
template <typename... Ts>
child create_child(std::optional<Ts>... ts)
{
    return create_child_detail(std::tuple<>{}, ts...);
}
</code>```

Empty optionals are removed. The arguments are passed to child in the order you wrote them. It can take any number of arguments. I tested it out on Coliru here so you can play with it.

Body:
I'm converting some code from using CreateProcess to use boost-process instead. I need to replace my CreateProcess usages with boost::process::child. The problem is they have incompatible ways for me to say "I want to use the default value". What used to be a one line command has become sixteen if statements.

The function I currently use works like this (simplified):

void CreateProcess(int, float);

Each parameter had a value you could use to indicate you wanted the default. I'll use 0 in this example:

int int_param = ...;
float float_param = ...;

CreateProcess(0, 0); //Use both defaults
CreateProcess(int_param, 0); //Use default float
CreateProcess(0, float_param); //Use default int
CreateProcess(int_param, float_param); //No defaults

This is a common design. You know what I am talking about. Whether I wanted to use the default value or not could be decided with a simple conditional, such as (... ? 0 : int_param). This allowed every CreateProcess call to be a single line of code.

CreateProcess( (... ? 0 : int_param), (... ? 0 : float_param) );

Where I used to call CreateProcess, I now want to create a child class. The constructor for child works like this:

template<typename ...Args>
explicit child(Args&&...args);

Instead of passing a specific value to use a default, I have to pass nothing.

int int_param = ...;
float float_param = ...;

child c; //Use both defaults
child c(int_param); //Use default float
child c(float_param); //Use default int
child c(int_param, float_param); //No defaults
child c(float_param, int_param); //Argument order is irrelevant

So far my only "solution" is to use if branches.

if (...) {
    if (...)
        child c;
    else
        child c(float_param);
} else {
    if (...)
        child c(int_param);
    else
        child c(int_param, float_param);
}

This example has only two possible arguments and it becomes four branches. The real child has four possible arguments, so every instance has sixteen branches.

What I would like is some way of building the call to avoid this branching. A solution specific to boost::process is also fine.

FYI, the last two arguments to child may or may not be the same type.

Body:
If you want to be able to leave out parameters in the call, and do things like:

create_child();
create_child(std::make_optional(int_param));
create_child(std::make_optional(float_param),
             (... ? std::optional<int>{} : int_param);

You can use some templates and a recursive function. The following code is an example. There are ways to make this better, like only creating one child and not returning a bunch, or using perfect forwarding.

//Recursion base case
//Recieves values to pass to child in a tuple
//Returns created child
template <typename... Ts>
child create_child_detail(std::tuple<Ts...> t)
{
    //Is there a better way to apply a tuple to a ctor?
    return std::apply([](Ts... ts){ return child(ts...); }, t);
}

//Recursive function
//Removes arguments from variadic template and adds arguments to tuple
template <typename... Ts, typename O, typename... Os>
child create_child_detail(std::tuple<Ts...> t, std::optional<O> o, std::optional<Os>... os)
{
    if (o) //Valid optional, add value to tuple to send to child
        return create_child_detail(std::tuple_cat(t, std::make_tuple(*o)), os...);
    else //Invalid optional, value should not be added to child
        return create_child_detail(t, os...);
}

//Called by user
//Just calls create_child_detail
template <typename... Ts>
child create_child(std::optional<Ts>... ts)
{
    return create_child_detail(std::tuple<>{}, ts...);
}

Empty optionals are removed. The arguments are passed to child in the order you wrote them. It can take any number of arguments. I tested it out on Coliru here so you can play with it.


问:
Can we execute multiple insert queries in JDBCIO.write function in single CloudSQL connection with an apache beam pipeline?
I am using JDBCIO.write() function of apache beam to write streaming data into cloudSQL. As per my requirement I have to write same data in two different tables.

Actually I am creating two differnt JDBCIO connection to write data in cloudSQL tables.

Is there any way to write two insert queries in single JDBCIO.write() function?

```<code>outputStringPcollection
            .apply("Write to CloudSQL table",
                    JdbcIO.<String> write()
                            .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration
                                    .create(DRIVER_CLASS_NAME,
                                            URL)
                                    .withUsername(USERNAME)
                                    .withPassword(PASSWORD)
                            .withStatement(insertQueryTable1)
                            .withPreparedStatementSetter(new SetQueryParameter())
                            .withStatement(insertQueryTable2)
                            .withPreparedStatementSetter(new SetQueryParameter()));
</code>```

I tried to execute above code by writing two different insert queries in single JDBC connection but data is inserting in only one table (i.e. Table2).

So, can we execute multiple queries in single connection? If yes, is there any other way to do?

Thanks in advance.

答:
No, you can't do it in a single connection. The best you can do is: </p>

```<code>JdbcIO<String> configuredWrite = JdbcIO.<String>.withDataSourceConfiguration(...);

outputStringPcollection.apply(configuredWrite.withStatement(s1)...);

outputStringPcollection.apply(configuredWrite.withStatement(s2)...);
</code>```

Body:
I am using JDBCIO.write() function of apache beam to write streaming data into cloudSQL. As per my requirement I have to write same data in two different tables.

Actually I am creating two differnt JDBCIO connection to write data in cloudSQL tables.

Is there any way to write two insert queries in single JDBCIO.write() function?

outputStringPcollection
            .apply("Write to CloudSQL table",
                    JdbcIO.<String> write()
                            .withDataSourceConfiguration(JdbcIO.DataSourceConfiguration
                                    .create(DRIVER_CLASS_NAME,
                                            URL)
                                    .withUsername(USERNAME)
                                    .withPassword(PASSWORD)
                            .withStatement(insertQueryTable1)
                            .withPreparedStatementSetter(new SetQueryParameter())
                            .withStatement(insertQueryTable2)
                            .withPreparedStatementSetter(new SetQueryParameter()));

I tried to execute above code by writing two different insert queries in single JDBC connection but data is inserting in only one table (i.e. Table2).

So, can we execute multiple queries in single connection? If yes, is there any other way to do?

Thanks in advance.

Body:
No, you can't do it in a single connection. The best you can do is:

JdbcIO<String> configuredWrite = JdbcIO.<String>.withDataSourceConfiguration(...);

outputStringPcollection.apply(configuredWrite.withStatement(s1)...);

outputStringPcollection.apply(configuredWrite.withStatement(s2)...);


问:
How to get a thread and heap dump of a Java process on Windows that's not running in a console
I have a Java application that I run from a console which in turn executes an another Java process. I want to get a thread/heap dump of that child process.

On Unix, I could do a kill -3 <pid> but on Windows AFAIK the only way to get a thread dump is Ctrl-Break in the console. But that only gives me the dump of the parent process, not the child.

Is there another way to get that heap dump?

答:
Maybe jcmd?

Jcmd utility is used to send diagnostic command requests to the JVM, where these requests are useful for controlling Java Flight Recordings, troubleshoot, and diagnose JVM and Java Applications.

The jcmd tool was introduced with Oracle's Java 7 and is particularly useful in troubleshooting issues with JVM applications by using it to identify Java processes' IDs (akin to jps), acquiring heap dumps (akin to jmap), acquiring thread dumps (akin to jstack), viewing virtual machine characteristics such as system properties and command-line flags (akin to jinfo), and acquiring garbage collection statistics (akin to jstat). The jcmd tool has been called "a swiss-army knife for investigating and resolving issues with your JVM application" and a "hidden gem."

Here’s the process you’ll need to use in invoking the jcmd:

Go to jcmd <pid> GC.heap_dump <file-path>

In which

pid: is a Java Process Id, for which the heap dump will be captured Also, the

file-path: is a file path in which the heap dump is be printed.

Check it out for more information about taking Java heap dump.

OwnerDisplayName: macgreg