问:
Should a daemonising parent free() memory after forking its child?
Let's say we've got some code like this:

```<code>int main() {
    FILE *f_conf = fopen("conf.conf");
    /* File Open Error Handling */

    char *buf = malloc(128);
    /* Malloc Error Handling */

    fgets(buf, 128, f_conf);
    fclose(f_conf);

    pid_t pid = fork()
    /* Fork Error Handling */

    if (pid) {
        free(buf); /* Should this free be called? */
        return 0;
    }

    while (1) {
        /* Do Stuff */
    }

    return 0;
}
</code>```

In general, I prefer to free memory prior to returning, since any impact to impact performance is minimal, and it helps with automated tooling to detect memory leaks. That said, the performance / best practices are less clear to me here, as it makes little sense to run these tools on a daemon. This leads me to two questions:

Would freeing memory (such as *buf) of a parent process prior to return affect performance of the child? I'm thinking there could be some (either positive or negative) by the way copy-on-write is implemented.

Is it considered good practice for the parent to free leftover resources?

答:
I consider it good practice to limit the allocation of a thing to exactly the executable region that it is valid for.   To me, the free is part of the documentation -- this thing is no longer valid or accessible.   In all things programming, conciseness yields clarity; and clear programs can be improved and optimised; incoherent ones cannot.

In terms of performance across a fork, if you are down to measuring the page-cache effect, you are probably in a very dark place.   Fundamentally, the process' pages will point to the same underlying page; if one relinquishes the page, the other gets it free-of-charge [ no point in copying if refcount == 1 ].  Realistically, all that happens is a few linked list nodes get updated, and you can't really measure it.

That said, if you are carrying around an allocation for an entire DVD or something, yeah, you might consider mapping it shared.

Body:
Let's say we've got some code like this:

int main() {
    FILE *f_conf = fopen("conf.conf");
    /* File Open Error Handling */

    char *buf = malloc(128);
    /* Malloc Error Handling */

    fgets(buf, 128, f_conf);
    fclose(f_conf);

    pid_t pid = fork()
    /* Fork Error Handling */

    if (pid) {
        free(buf); /* Should this free be called? */
        return 0;
    }

    while (1) {
        /* Do Stuff */
    }

    return 0;
}

In general, I prefer to free memory prior to returning, since any impact to impact performance is minimal, and it helps with automated tooling to detect memory leaks. That said, the performance / best practices are less clear to me here, as it makes little sense to run these tools on a daemon. This leads me to two questions:

Would freeing memory (such as *buf) of a parent process prior to return affect performance of the child? I'm thinking there could be some (either positive or negative) by the way copy-on-write is implemented.

Is it considered good practice for the parent to free leftover resources?


来源: stackexchange

问:
How to fix a listing problem with CSV on Tkinter
I need help with making a set of buttons where the first button would say Camera 1 all the way to the seventh button which would say Camera 7. From what I see in my code, all 7 buttons just take the last line of the CSV file which is Camera 7. Is there a way where I can have each button have its distinctive name?

I tried changing around the list in line 24, but I'm not sure how

This is my python code:

```<code>import tkinter.messagebox
root = Tk()
root.title("Video Equipment Reservation System")

infile = open('CamCSV.txt','r')
for line in infile:
    data = line.split(',')
    button = list()
    for i in range(7):
        button.append(Button(text=data[1], background=data[2]))
        button[i].grid(row=0,column=i)
</code>```

and this is my CSV file

```<code>cam,Camera 2,green,0
cam,Camera 3,green,0
cam,Camera 4,green,0
cam,Camera 5,green,0
cam,Camera 6,green,0
cam,Camera 7,red,0
</code>```

Each button should be different.

答:
Delete the second for loop. You read the first line, then you make 7 buttons with the information from that first line. Each time you read a new line, you rewrite those 7 buttons.
Instead, make one button each time you read a line.</p>

```<code>button = list()
i = 0
for line in infile:
    data = line.split(',')
    button.append(Button(text=data[1], background=data[2]))
    button[i].grid(row=0,column=i)
    i += 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need help with making a set of buttons where the first button would say Camera 1 all the way to the seventh button which would say Camera 7. From what I see in my code, all 7 buttons just take the last line of the CSV file which is Camera 7. Is there a way where I can have each button have its distinctive name?

I tried changing around the list in line 24, but I'm not sure how

This is my python code:

import tkinter.messagebox
root = Tk()
root.title("Video Equipment Reservation System")

infile = open('CamCSV.txt','r')
for line in infile:
    data = line.split(',')
    button = list()
    for i in range(7):
        button.append(Button(text=data[1], background=data[2]))
        button[i].grid(row=0,column=i)

and this is my CSV file

cam,Camera 2,green,0
cam,Camera 3,green,0
cam,Camera 4,green,0
cam,Camera 5,green,0
cam,Camera 6,green,0
cam,Camera 7,red,0

Each button should be different.

Body:
Delete the second for loop. You read the first line, then you make 7 buttons with the information from that first line. Each time you read a new line, you rewrite those 7 buttons.
Instead, make one button each time you read a line.

button = list()
i = 0
for line in infile:
    data = line.split(',')
    button.append(Button(text=data[1], background=data[2]))
    button[i].grid(row=0,column=i)
    i += 1


问:
Named Routes Not Recognised in Method When Called From PHPUnit Test
When calling a Method from another class that contains a named route the route is not recognised

This PHPUnit test is to check that functionality of the system still meets requirements as the system is complicated.

Testing is run from a local environment (homestead vagrant)

I am calling the method form here:

```<code>$orderLines = (new EDIProcessController())->getChanges($order['ediOrder'], $order['partnerId']);
</code>```

And the named route that is causing the issue:

```<code>$orderLine->item_url = route('warehouse.products.view', $itemDetails->id);
</code>```

I get the following error:

```<code>InvalidArgumentException: Route [warehouse.products.view] not defined.

/home/vagrant/vr/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:305
/home/vagrant/vr/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:790
/home/vagrant/vr/app/Http/Controllers/Warehouse/EDI/SPS/EDIProcessController.php:1575
/home/vagrant/vr/vendor/laravel/framework/src/Illuminate/Support/Collection.php:861
/home/vagrant/vr/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php:139
/home/vagrant/vr/app/Http/Controllers/Warehouse/EDI/SPS/EDIProcessController.php:1746
</code>```

Route as defined in the routes file:

```<code>Route::get('/view/{id}', 'Warehouse\ProductController@viewProduct')->name('warehouse.products.view');
</code>```

This route works fine when called from within Laravel app but will not work within PHPUnit test

答:
Finally found the answer

There is a issue with using require_once for sub route files that is caused due to multiple instances of route files not all getting the required files.

Here is a dicussion here that I eventually found

switching the require_once to require at all levels of our route files solves the issue

Body:
When calling a Method from another class that contains a named route the route is not recognised

This PHPUnit test is to check that functionality of the system still meets requirements as the system is complicated.

Testing is run from a local environment (homestead vagrant)

I am calling the method form here:

$orderLines = (new EDIProcessController())->getChanges($order['ediOrder'], $order['partnerId']);

And the named route that is causing the issue:

$orderLine->item_url = route('warehouse.products.view', $itemDetails->id);

I get the following error:

InvalidArgumentException: Route [warehouse.products.view] not defined.

/home/vagrant/vr/vendor/laravel/framework/src/Illuminate/Routing/UrlGenerator.php:305
/home/vagrant/vr/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:790
/home/vagrant/vr/app/Http/Controllers/Warehouse/EDI/SPS/EDIProcessController.php:1575
/home/vagrant/vr/vendor/laravel/framework/src/Illuminate/Support/Collection.php:861
/home/vagrant/vr/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php:139
/home/vagrant/vr/app/Http/Controllers/Warehouse/EDI/SPS/EDIProcessController.php:1746

Route as defined in the routes file:

Route::get('/view/{id}', 'Warehouse\ProductController@viewProduct')->name('warehouse.products.view');

This route works fine when called from within Laravel app but will not work within PHPUnit test


问:
Why do query results change when using coalesce on a char field in a where clause?
I'm seeing some unexpected behavior when querying with a where clause on a coalesced char field in an Oracle database.

It seems that the results of

CASE WHEN COALESCE(char_field, 'some_val') = 'someOtherVal'
```

<p>are different than the results of</p>

<pre class="lang-sql prettyprint-override"><code>CASE WHEN char_field = 'someOtherVal'
</code>```

The specific comparisons in which I've noticed this weird output are 'between', 'in', and 'equals'. These are the weird outputs I'm seeing:

Between seems to be non-inclusive on the upper end

In and equals return false for every comparison

Here's some sql to replicate the weirdness:

CREATE TABLE delete_me( some_char CHAR(8) );

INSERT ALL
  INTO delete_me (some_char) VALUES ('1')
  INTO delete_me (some_char) VALUES ('2')
  INTO delete_me (some_char) VALUES ('4')
  INTO delete_me (some_char) VALUES ('5')
  INTO delete_me (some_char) VALUES ('abc1')
  INTO delete_me (some_char) VALUES (null)
SELECT 1 FROM DUAL;

SELECT some_char,
  COALESCE(some_char, 'wasNull') AS coalesce_some_char,
  CASE
    WHEN (some_char BETWEEN '1' AND '5')
    THEN 'true'
    ELSE 'false'
  END AS between_1_5,
  CASE
    WHEN (COALESCE(some_char, 'wasNull') BETWEEN '1' AND '5')
    THEN 'true'
    ELSE 'false'
  END AS coalesce_between_1_5,
  CASE
    WHEN (some_char IN ('1', '5'))
    THEN 'true'
    ELSE 'false'
  END AS in_1_5,
  CASE
    WHEN (COALESCE(some_char, 'wasNull') IN ('1', '5'))
    THEN 'true'
    ELSE 'false'
  END AS coalesce_in_1_5,
  CASE
    WHEN (some_char = 'abc1')
    THEN 'true'
    ELSE 'false'
  END AS equals_abc1,
  CASE
    WHEN (COALESCE(some_char, 'wasNull') = 'abc1')
    THEN 'true'
    ELSE 'false'
  END AS coalesce_equals_abc1
FROM delete_me;
```

I would have expected the output of the comparisons on coalesced fields to match those on non-coalesced fields for all operators except IS NULL.

Does anyone have any idea why these results wouldn't match up?

答:
Your problem is in the data type of some_char. When a column of type CHAR is compared to a string, Oracle blank pads the string to the length of the column (see the docs). In the tests you are doing, the values match in length ('1' vs '1') or are completely different ('1' vs 'abc1') so everything works fine. However when you use COALESCE on a CHAR field, the output of COALESCE is the fully blank padded column value returned as a VARCHAR (see the docs for NVL) and so the comparison string is not blank padded, and you are then comparing '1       ' vs '1', which fails. There are a couple of ways to work around this. You can TRIM the output of COALESCE i.e.

```<code>TRIM(COALESCE(some_char, 'wasNull'))
</code>```

or change the data type of some_char to VARCHAR(8) instead.

I've made a demo of all of this on dbfiddle

Body:
I'm seeing some unexpected behavior when querying with a where clause on a coalesced char field in an Oracle database.

It seems that the results of

CASE WHEN COALESCE(char_field, 'some_val') = 'someOtherVal'

are different than the results of

CASE WHEN char_field = 'someOtherVal'

The specific comparisons in which I've noticed this weird output are 'between', 'in', and 'equals'. These are the weird outputs I'm seeing:

Between seems to be non-inclusive on the upper end

In and equals return false for every comparison

Here's some sql to replicate the weirdness:

CREATE TABLE delete_me( some_char CHAR(8) );

INSERT ALL
  INTO delete_me (some_char) VALUES ('1')
  INTO delete_me (some_char) VALUES ('2')
  INTO delete_me (some_char) VALUES ('4')
  INTO delete_me (some_char) VALUES ('5')
  INTO delete_me (some_char) VALUES ('abc1')
  INTO delete_me (some_char) VALUES (null)
SELECT 1 FROM DUAL;

SELECT some_char,
  COALESCE(some_char, 'wasNull') AS coalesce_some_char,
  CASE
    WHEN (some_char BETWEEN '1' AND '5')
    THEN 'true'
    ELSE 'false'
  END AS between_1_5,
  CASE
    WHEN (COALESCE(some_char, 'wasNull') BETWEEN '1' AND '5')
    THEN 'true'
    ELSE 'false'
  END AS coalesce_between_1_5,
  CASE
    WHEN (some_char IN ('1', '5'))
    THEN 'true'
    ELSE 'false'
  END AS in_1_5,
  CASE
    WHEN (COALESCE(some_char, 'wasNull') IN ('1', '5'))
    THEN 'true'
    ELSE 'false'
  END AS coalesce_in_1_5,
  CASE
    WHEN (some_char = 'abc1')
    THEN 'true'
    ELSE 'false'
  END AS equals_abc1,
  CASE
    WHEN (COALESCE(some_char, 'wasNull') = 'abc1')
    THEN 'true'
    ELSE 'false'
  END AS coalesce_equals_abc1
FROM delete_me;

I would have expected the output of the comparisons on coalesced fields to match those on non-coalesced fields for all operators except IS NULL.

Does anyone have any idea why these results wouldn't match up?

Body:
Your problem is in the data type of some_char. When a column of type CHAR is compared to a string, Oracle blank pads the string to the length of the column (see the docs). In the tests you are doing, the values match in length ('1' vs '1') or are completely different ('1' vs 'abc1') so everything works fine. However when you use COALESCE on a CHAR field, the output of COALESCE is the fully blank padded column value returned as a VARCHAR (see the docs for NVL) and so the comparison string is not blank padded, and you are then comparing '1       ' vs '1', which fails. There are a couple of ways to work around this. You can TRIM the output of COALESCE i.e.

TRIM(COALESCE(some_char, 'wasNull'))

or change the data type of some_char to VARCHAR(8) instead.

I've made a demo of all of this on dbfiddle


问:
RegEx for removing whitespace in a string
Trying to make a very simple HTML minifier that only removes white space between tags?

I think the best way is with a JavaScript Regular Expression? but can never work out how to do them correctly.

```<code><p>leave white spaces</p> <p>leave white spaces</p>
</code>```

After  minify:

```<code> <p>leave white space</p><p>leave white space</p>
</code>```

trying to target the space bewtween > here <

答:
You might consider using DOMParser instead, and then remove-ing all text nodes which, when trimmed, are empty:

const input = `<p>leave white spaces</p> <p>leave white spaces</p>`;
const doc = new DOMParser().parseFromString(input, 'text/html');
[...doc.body.childNodes].forEach((node) => {
  if (node.nodeType === 3 && node.textContent.trim() === '') {
    node.remove();
  }
});
console.log(doc.body.innerHTML);```

Body:
Trying to make a very simple HTML minifier that only removes white space between tags?

I think the best way is with a JavaScript Regular Expression? but can never work out how to do them correctly.

leave white spaces

leave white spaces

After  minify:

leave white space

leave white space

trying to target the space bewtween > here <


问:
Invoke Manage controller GET method from account controller login page in asp.net mvc
Want to invoke AddPhoneNumber method in Manage controller from Account Controller Login Page. I have a checkbox in Login page which I have implemented for OTP.

What I want is that when checkbox is checked, it should invoke AddPhoneNumber GET method from Manage Controller to open the page.

Manage controller

```<code> // GET: /Manage/AddPhoneNumber
        public ActionResult AddPhoneNumber()
        {
            return View();
        }
</code>```

AddPhoneNumber page

```<code>@model Aayumitra.Models.AddPhoneNumberViewModel

        @using (Html.BeginForm("AddPhoneNumber", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
        {
            @Html.AntiForgeryToken()
            <h4>Add a phone number</h4>
            <hr />
            @Html.ValidationSummary("", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(m => m.Number, new { @class = "col-md-5 control-label" })
                <div class="col-md-7">
                    @Html.TextBoxFor(m => m.Number, new { @class = "form-control" })
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" class="btn btn-primary" value="Send verification code" />
                </div>
            </div>
        }
</code>```

Login Page

```<code>@using Aayumitra.Models
@model LoginViewModel

 @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {
        @Html.AntiForgeryToken()

                <div class="form-group">
                    <label for="email">Mobile Number / Email ID</label>

                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control form-control-sm", placeholder = "Mobile Number / Email ID" })
                    @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                </div>
                <div class="form-group">
                    <label for="password">Password</label>
                    @Html.PasswordFor(m => m.Password, new { @class = "form-control form-control-sm password-input", placeholder = "Password" })
                    @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                </div>
                <div class="form-group">
                     <input type="checkbox" name="remember-password" id="remember-pass-check" onclick="triggerLink()">
                    <label for="">Login with OTP instead of password</label>
                </div>
    }

function triggerLink() {
        debugger;
        var theUrl ='@Url.Action("AddPhoneNumber","Manage", Model)';
    }
</code>```

答:
See: How do I redirect to another webpage?

In your triggerLink() method, something like:

```<code><script type="text/javascript">
  function triggerLink() {
      debugger;
      var theUrl ='@Url.Action("AddPhoneNumber","Manage")';
      window.location.href = theUrl;
  }
</script>
</code>```

Also, don' tthink you need to pass the model along, since your controller action does not look like it's expecting it...

Body:
Want to invoke AddPhoneNumber method in Manage controller from Account Controller Login Page. I have a checkbox in Login page which I have implemented for OTP.

What I want is that when checkbox is checked, it should invoke AddPhoneNumber GET method from Manage Controller to open the page.

Manage controller

 // GET: /Manage/AddPhoneNumber
        public ActionResult AddPhoneNumber()
        {
            return View();
        }

AddPhoneNumber page

@model Aayumitra.Models.AddPhoneNumberViewModel

        @using (Html.BeginForm("AddPhoneNumber", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
        {
            @Html.AntiForgeryToken()

Add a phone number

            @Html.ValidationSummary("", new { @class = "text-danger" })

                @Html.LabelFor(m => m.Number, new { @class = "col-md-5 control-label" })

                    @Html.TextBoxFor(m => m.Number, new { @class = "form-control" })

                    <input type="submit" class="btn btn-primary" value="Send verification code" />

        }

Login Page

@using Aayumitra.Models
@model LoginViewModel

 @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {
        @Html.AntiForgeryToken()

                    Mobile Number / Email ID

                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control form-control-sm", placeholder = "Mobile Number / Email ID" })
                    @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })

                    Password
                    @Html.PasswordFor(m => m.Password, new { @class = "form-control form-control-sm password-input", placeholder = "Password" })
                    @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                     <input type="checkbox" name="remember-password" id="remember-pass-check" onclick="triggerLink()">
                    Login with OTP instead of password

    }

function triggerLink() {
        debugger;
        var theUrl ='@Url.Action("AddPhoneNumber","Manage", Model)';
    }

Body:
See: How do I redirect to another webpage?

In your triggerLink() method, something like:

<script type="text/javascript">
  function triggerLink() {
      debugger;
      var theUrl ='@Url.Action("AddPhoneNumber","Manage")';
      window.location.href = theUrl;
  }
</script>

Also, don' tthink you need to pass the model along, since your controller action does not look like it's expecting it...


问:
How can i disable a checkbox field in woocommerce?
I have added a checkbox field in woocommerce and I want to only view its result on the accounts screen. I have added the checkbox using an example like:

```<code>            'register-checkboxes' => array(
            'type'     => 'checkboxes',
            'label'    => __( 'Regions of Construction', 'woo' ),
            'options'  => array(
                'qld1' => __( 'QLD Zone Q1', 'woo' ),
                'qld2' => __( 'QLD Zone Q2', 'woo' ),
                'qld3' => __( 'QLD Zone Q3', 'woo' ),
            ),
            'hide_in_registration' => true,
            'required' => true,
        ),
</code>```

But when I add:

```<code>$field_args['custom_attributes'] = array( 'disabled' => 'disabled' );
</code>```

On the Account screen this works for disabling Text inputs and selects but not checkbox options.

I am using: https://rudrastyh.com/woocommerce/woocommerce_form_field.html as a guide but it seems you can't pass an array of Custom Attributes to each option of the checkboxes? What am I missing?

答:
I added:

```<code>add_filter( 'woocommerce_form_field_checkboxes', array( $this,'pm_form_field_modify' ), 10, 4);
</code>```

then

```<code>    public function pm_form_field_modify( $field, $key, $args, $value ) {
    ob_start();
    $this->pm_print_list_field( $key, $args, $value );
    $field = ob_get_clean();

    if ( $args['return'] ) {
        return $field;
    } else {
        echo $field;
    }
}
</code>```

Then the output

```<code>    public function pm_print_list_field( $key, $field_args, $value = null ) {
    $value = empty( $value ) && $field_args['type'] === 'checkboxes' ? array() : $value;
    ?>
    <div class="form-row">
        <?php

        // Disable the checkboxes for Zones
        if ($field_args['id'] == 'register-checkboxes' && !is_admin()) {
            $field_args['custom_attributes'] = array( 'disabled' => 'disabled' );
        }

        if ( ! empty( $field_args['label'] ) ) { ?>
            <label>
                <?php echo $field_args['label']; ?>
                <?php if ( ! empty( $field_args['required'] ) ) { ?>
                    <abbr class="required" title="<?php echo esc_attr__( 'required', 'woocommerce' ); ?>">*</abbr>
                <?php } ?>
            </label>
        <?php } ?>
        <ul>
            <?php foreach ( $field_args['options'] as $option_value => $option_label ) {
                $id         = sprintf( '%s_%s', $key, sanitize_title_with_dashes( $option_label ) );
                $option_key = $field_args['type'] === 'checkboxes' ? sprintf( '%s[%s]', $key, $option_value ) : $key;
                $type       = $field_args['type'] === 'checkboxes' ? 'checkbox' : $field_args['type'];
                $checked    = $field_args['type'] === 'checkboxes' ? in_array( $option_value, $value ) : $option_value == $value;
                ?>
                <li>
                    <label for="<?php echo esc_attr( $id ); ?>">
                        <input type="<?php echo esc_attr( $type ); ?>" id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $option_key ); ?>" value="<?php echo esc_attr( $option_value ); ?>" <?php checked( $checked );

                         // Disable the checkboxes
                         if ( isset($field_args['custom_attributes']['disabled']) ) {
                             echo 'disabled="disabled"';
                         }

                        ?>>
                        <?php echo $option_label; ?>
                    </label>
                </li>
            <?php } ?>
        </ul>
    </div>
    <?php
}
</code>```

This disabled the group of checkboxes.

Body:
I have added a checkbox field in woocommerce and I want to only view its result on the accounts screen. I have added the checkbox using an example like:

            'register-checkboxes' => array(
            'type'     => 'checkboxes',
            'label'    => __( 'Regions of Construction', 'woo' ),
            'options'  => array(
                'qld1' => __( 'QLD Zone Q1', 'woo' ),
                'qld2' => __( 'QLD Zone Q2', 'woo' ),
                'qld3' => __( 'QLD Zone Q3', 'woo' ),
            ),
            'hide_in_registration' => true,
            'required' => true,
        ),

But when I add:

$field_args['custom_attributes'] = array( 'disabled' => 'disabled' );

On the Account screen this works for disabling Text inputs and selects but not checkbox options.

I am using: https://rudrastyh.com/woocommerce/woocommerce_form_field.html as a guide but it seems you can't pass an array of Custom Attributes to each option of the checkboxes? What am I missing?

Body:
I added:

add_filter( 'woocommerce_form_field_checkboxes', array( $this,'pm_form_field_modify' ), 10, 4);

then

    public function pm_form_field_modify( $field, $key, $args, $value ) {
    ob_start();
    $this->pm_print_list_field( $key, $args, $value );
    $field = ob_get_clean();

    if ( $args['return'] ) {
        return $field;
    } else {
        echo $field;
    }
}

Then the output

    public function pm_print_list_field( $key, $field_args, $value = null ) {
    $value = empty( $value ) && $field_args['type'] === 'checkboxes' ? array() : $value;
    ?>
    <div class="form-row">
        <?php

        // Disable the checkboxes for Zones
        if ($field_args['id'] == 'register-checkboxes' && !is_admin()) {
            $field_args['custom_attributes'] = array( 'disabled' => 'disabled' );
        }

        if ( ! empty( $field_args['label'] ) ) { ?>
            <label>
                <?php echo $field_args['label']; ?>
                <?php if ( ! empty( $field_args['required'] ) ) { ?>
                    <abbr class="required" title="<?php echo esc_attr__( 'required', 'woocommerce' ); ?>">*</abbr>
                <?php } ?>
            </label>
        <?php } ?>
        <ul>
            <?php foreach ( $field_args['options'] as $option_value => $option_label ) {
                $id         = sprintf( '%s_%s', $key, sanitize_title_with_dashes( $option_label ) );
                $option_key = $field_args['type'] === 'checkboxes' ? sprintf( '%s[%s]', $key, $option_value ) : $key;
                $type       = $field_args['type'] === 'checkboxes' ? 'checkbox' : $field_args['type'];
                $checked    = $field_args['type'] === 'checkboxes' ? in_array( $option_value, $value ) : $option_value == $value;
                ?>
                <li>
                    <label for="<?php echo esc_attr( $id ); ?>">
                        <input type="<?php echo esc_attr( $type ); ?>" id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $option_key ); ?>" value="<?php echo esc_attr( $option_value ); ?>" <?php checked( $checked );

                         // Disable the checkboxes
                         if ( isset($field_args['custom_attributes']['disabled']) ) {
                             echo 'disabled="disabled"';
                         }

                        ?>>
                        <?php echo $option_label; ?>
                    </label>
                </li>
            <?php } ?>
        </ul>
    </div>
    <?php
}

This disabled the group of checkboxes.


问:
First name mentions in a text using discord.js
I am trying to make some sort of kick system. I would like to know how I would get the first name mentioned in a text.

```<code>client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS"],["BAN_MEMBERS"])){
    if(message.content == "!kick"){
        let member = message.mentions.members();
        console.log(member)
        member.kick("You have been kicked").then ((member) => {
        message.channel.send( member.displayName + " has been Kicked!");
        })
    }
}
});

</code>```

No error is thrown that I know of.

答:
First off, if you want to check multiple permissions in GuildMember.hasPermission(), you need to pass an array. The way your code is written now, you're passing an array with "KICK_MEMBERS" as the permissions to check and an array with "BAN_MEMBERS" for the explicit parameter.

Solution: message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMEBRS"])

Secondly, you're declaring member as a Collection, when it should be a GuildMember.

Solution: const member = message.mentions.members.first()

client.on("message", async message => {
  if (message.content === "!kick" && message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])) {
    try {
      const member = message.mentions.members.first();
      if (!member) return await message.channel.send(`No user mentioned.`);

      await member.kick(`Kicked by ${message.author.tag}`);
      await message.channel.send(`${member.user.tag} has been kicked.`);
    } catch(err) {
      console.error(err);
    }
  }
});
```

Body:
I am trying to make some sort of kick system. I would like to know how I would get the first name mentioned in a text.

client.on("message", (message) => {
if (message.member.hasPermission(["KICK_MEMBERS"],["BAN_MEMBERS"])){
    if(message.content == "!kick"){
        let member = message.mentions.members();
        console.log(member)
        member.kick("You have been kicked").then ((member) => {
        message.channel.send( member.displayName + " has been Kicked!");
        })
    }
}
});

No error is thrown that I know of.


问:
OpenCV how do conversions of Matrix elements work
I am having trouble understanding the inner workings of OpenCV. Consider the following code:

```<code>Scalar getAverageColor(Mat img, vector<Rect>& rois) {

    int n = static_cast<int>(rois.size());
    Mat avgs(1, n, CV_8UC3);
    for (int i = 0; i < n; ++i) {
        // What is the correct way to assign the color elements in
        // the matrix?
        avgs.at<Scalar>(i) = mean(Mat(img, rois[i]));
        /*
        This seems to always work, but there has to be a better way.
        avgs.at<Vec3b>(i)[0] = mean(Mat(img, rois[i]))[0];
        avgs.at<Vec3b>(i)[1] = mean(Mat(img, rois[i]))[1];
        avgs.at<Vec3b>(i)[2] = mean(Mat(img, rois[i]))[2];
        */
    }
    // If I access the first element it seems to be set correctly.
    Scalar first = avgs.at<Scalar>(0);
    // However mean returns [0 0 0 0] if I did the assignment above using scalar, why???
    Scalar avg = mean(avgs);
    return avg;
}
</code>```

If I use avgs.at<Scalar>(i) = mean(Mat(img, rois[i])) for the assignment in the loop the first element looks correct, but then the mean calculation always returns zero (even thought the first element looks correct). If I assign all the color elements by hand using Vec3b it seems to work, but why???

答:
Note: cv::Scalar is a typedef for cv::Scalar_<double>, which derives from cv::Vec<double, 4>, which derives from cv::Matx<double, 4, 1>.
Similarly, cv::Vec3b is cv::Vec<uint8_t, 3> which derives from cv::Matx<uint8_t, 3, 1> -- this means that we can use any of those 3 in cv::Mat::at and get identical (correct) behaviour.

It's important to be aware that cv::Mat::at is basically a reinterpret_cast on the underlying data array. You need to be extremely careful to use an appropriate data type for the template argument, one which corresponds to the type of elements (including channel count) of the cv::Mat you're invoking it on.

The documentation mentions the following:

Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends on the image from which you are trying to retrieve the data. The table below gives a better insight in this:

If matrix is of type CV_8U then use Mat.at<uchar>(y,x).

If matrix is of type CV_8S then use Mat.at<schar>(y,x).

If matrix is of type CV_16U then use Mat.at<ushort>(y,x).

If matrix is of type CV_16S then use Mat.at<short>(y,x).

If matrix is of type CV_32S then use Mat.at<int>(y,x).

If matrix is of type CV_32F then use Mat.at<float>(y,x).

If matrix is of type CV_64F then use Mat.at<double>(y,x).

It doesn't seem to mention there what to do in case of multiple channels -- in that case you use cv::Vec<...> (or rather one of the typedefs provided). cv::Vec<...> is basically a wrapper around an fixed-size array of N values of given type.

In your case, the matrix avgs is CV_8UC3 -- each element consists of 3 unsigned byte values (i.e. 3 bytes total). However, by using avgs.at<Scalar>(i), you interpret each element as 4 doubles (32 bytes in total). That means that:

The actual element you tried to write to (if interpreted correctly) will only hold the 3 most significant bytes of the (8 byte floating point) mean of the first channel -- i.e. complete garbage.

You actually overwrite the next 10 elements (the last one partially, 3rd channel escapes unscathed) with more garbage.

At some point, you are bound to overflow the buffer and potentially trash other data structures. This issue is rather serious.

We can demonstrate it using the following simple program.

Example:

```<code>#include <opencv2/opencv.hpp>

int main()
{
    cv::Mat test_mat(cv::Mat::zeros(1, 12, CV_8UC3)); // 12 * 3 = 36 bytes of data
    std::cout << "Before: " << test_mat << "\n";

    cv::Scalar test_scalar(cv::Scalar::all(1234.5678));
    test_mat.at<cv::Scalar>(0, 0) = test_scalar;
    std::cout << "After: " << test_mat << "\n";

    return 0;
}
</code>```

Output:

```<code>Before: [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0]
After: [173, 250,  92, 109,  69,  74, 147,  64, 173, 250,  92, 109,  69,  74, 147,  64, 173, 250,  92, 109,  69,  74, 147,  64, 173, 250,  92, 109,  69,  74, 147,  64,   0,   0,   0,   0]
</code>```

This clearly shows we're writing way more than we should.

In Debug mode, the incorrect use of at also triggers an assertion:

```<code>OpenCV(3.4.3) Error: Assertion failed (((((sizeof(size_t)<<28)|0x8442211) >> ((traits::Depth<_Tp>::value) & ((1 << 3) - 1))*4) & 15) == elemSize1()) in cv::Mat::at, file D:\code\shit\so07\deps\include\opencv2/core/mat.inl.hpp, line 1102
</code>```

To allow assignment of the result from cv::mean (which is a cv::Scalar) to our CV_8UC3 matrix, we need to do two things (not necessarily in this order):

Convert the values from double to uint8_t -- OpenCV will do a saturate_cast, but given that the mean won't go past the min/max of the input items, we'd be fine with a regular cast.

Get rid of the 4th element.

To remove the 4th element, we can use cv::Matx::get_minor (The documentation is a bit lacking, but a look at the implementation explains it fairly well). The result is a cv::Matx, so we have to use that instead of cv::Vec when using cv::Mat::at.

The two possible options then are:

Get rid of the 4th element and then
cast result to convert the cv::Matx to uint8_t element type.

Cast the cv::Scalar to cv::Scalar_<uint8_t> first, and then get rid of the 4th element.

Example:

```<code>#include <opencv2/opencv.hpp>

typedef cv::Matx<uint8_t, 3, 1> Mat31b; // Convenience, OpenCV only has typedefs for double and float variants

int main()
{
    cv::Mat test_mat(1, 12, CV_8UC3); // 12 * 3 = 36 bytes of data
    test_mat = cv::Scalar(1, 1, 1); // Set all elements to 1
    std::cout << "Before: " << test_mat << "\n";

    cv::Scalar test_scalar{ 2,3,4,0 };
    cv::Matx31d temp = test_scalar.get_minor<3, 1>(0, 0);
    test_mat.at<Mat31b>(0, 0) = static_cast<Mat31b>(temp);

    // or
    // cv::Scalar_<uint8_t> temp(static_cast<cv::Scalar_<uint8_t>>(test_scalar));
    // test_mat.at<Mat31b>(0, 0) = temp.get_minor<3, 1>(0, 0);

    std::cout << "After: " << test_mat << "\n";

    return 0;
}
</code>```

NB: You can get rid of the explicit temporaries, they're here just for easier readability.

Output:

Both options produce the following output:

```<code>Before: [  1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1]
After: [  2,   3,   4,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1]
</code>```

As we can see, only the first 3 bytes were changed, so it behaves correctly.

Some thoughts about performance.

It's hard to guess which of the two approaches is better. Casting first means you allocate smaller amount of memory for the temporary, but then you have to do 4 saturate_casts instead of 3. Some benchmarking would have to be done (excercise for the reader). The calculation of mean will outweigh it significantly, so it's likely to be irrelevant.

Given that we don't really need the saturate_casts, perhaps the simple, but more verbose approach (optimized version of the thing that worked for you) might perform better in a tight loop.

```<code>cv::Vec3b& current_element(avgs.at<cv::Vec3b>(i));
cv::Scalar current_mean(cv::mean(cv::Mat(img, rois[i])));
for (int n(0); n < 3; ++n) {
    current_element[n] = static_cast<uint8_t>(current_mean[n]);
}
</code>```

Update:

One more idea that came up in discussion with @alkasm. The assignment operator for a cv::Mat is vectorized when given a cv::Scalar (it assigns the same value to all elements), and it ignores the additional channel values the cv::Scalar may hold relative to the target cv::Mat type. (e.g. for a 3-channel Mat it ignores the 4th value).

We could take a 1x1 ROI of the target Mat, and assign it the mean Scalar. Necessary type conversions will happen, and the 4th channel will be discared. Probably not optimal, but it's by far the least amount of code so far.

```<code>test_mat(cv::Rect(0, 0, 1, 1)) = test_scalar;
</code>```

The result is the same as before.

Body:
I am having trouble understanding the inner workings of OpenCV. Consider the following code:

Scalar getAverageColor(Mat img, vector<Rect>& rois) {

    int n = static_cast<int>(rois.size());
    Mat avgs(1, n, CV_8UC3);
    for (int i = 0; i < n; ++i) {
        // What is the correct way to assign the color elements in
        // the matrix?
        avgs.at<Scalar>(i) = mean(Mat(img, rois[i]));
        /*
        This seems to always work, but there has to be a better way.
        avgs.at<Vec3b>(i)[0] = mean(Mat(img, rois[i]))[0];
        avgs.at<Vec3b>(i)[1] = mean(Mat(img, rois[i]))[1];
        avgs.at<Vec3b>(i)[2] = mean(Mat(img, rois[i]))[2];
        */
    }
    // If I access the first element it seems to be set correctly.
    Scalar first = avgs.at<Scalar>(0);
    // However mean returns [0 0 0 0] if I did the assignment above using scalar, why???
    Scalar avg = mean(avgs);
    return avg;
}

If I use avgs.at<Scalar>(i) = mean(Mat(img, rois[i])) for the assignment in the loop the first element looks correct, but then the mean calculation always returns zero (even thought the first element looks correct). If I assign all the color elements by hand using Vec3b it seems to work, but why???

Body:
Note: cv::Scalar is a typedef for cv::Scalar_<double>, which derives from cv::Vec<double, 4>, which derives from cv::Matx<double, 4, 1>.
Similarly, cv::Vec3b is cv::Vec<uint8_t, 3> which derives from cv::Matx<uint8_t, 3, 1> -- this means that we can use any of those 3 in cv::Mat::at and get identical (correct) behaviour.

It's important to be aware that cv::Mat::at is basically a reinterpret_cast on the underlying data array. You need to be extremely careful to use an appropriate data type for the template argument, one which corresponds to the type of elements (including channel count) of the cv::Mat you're invoking it on.

The documentation mentions the following:

Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends on the image from which you are trying to retrieve the data. The table below gives a better insight in this:

If matrix is of type CV_8U then use Mat.at<uchar>(y,x).

If matrix is of type CV_8S then use Mat.at<schar>(y,x).

If matrix is of type CV_16U then use Mat.at<ushort>(y,x).

If matrix is of type CV_16S then use Mat.at<short>(y,x).

If matrix is of type CV_32S then use Mat.at<int>(y,x).

If matrix is of type CV_32F then use Mat.at<float>(y,x).

If matrix is of type CV_64F then use Mat.at<double>(y,x).

It doesn't seem to mention there what to do in case of multiple channels -- in that case you use cv::Vec<...> (or rather one of the typedefs provided). cv::Vec<...> is basically a wrapper around an fixed-size array of N values of given type.

In your case, the matrix avgs is CV_8UC3 -- each element consists of 3 unsigned byte values (i.e. 3 bytes total). However, by using avgs.at<Scalar>(i), you interpret each element as 4 doubles (32 bytes in total). That means that:

The actual element you tried to write to (if interpreted correctly) will only hold the 3 most significant bytes of the (8 byte floating point) mean of the first channel -- i.e. complete garbage.

You actually overwrite the next 10 elements (the last one partially, 3rd channel escapes unscathed) with more garbage.

At some point, you are bound to overflow the buffer and potentially trash other data structures. This issue is rather serious.

We can demonstrate it using the following simple program.

Example:

#include <opencv2/opencv.hpp>

int main()
{
    cv::Mat test_mat(cv::Mat::zeros(1, 12, CV_8UC3)); // 12 * 3 = 36 bytes of data
    std::cout << "Before: " << test_mat << "\n";

    cv::Scalar test_scalar(cv::Scalar::all(1234.5678));
    test_mat.at<cv::Scalar>(0, 0) = test_scalar;
    std::cout << "After: " << test_mat << "\n";

    return 0;
}

Output:

Before: [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0]
After: [173, 250,  92, 109,  69,  74, 147,  64, 173, 250,  92, 109,  69,  74, 147,  64, 173, 250,  92, 109,  69,  74, 147,  64, 173, 250,  92, 109,  69,  74, 147,  64,   0,   0,   0,   0]

This clearly shows we're writing way more than we should.

In Debug mode, the incorrect use of at also triggers an assertion:

OpenCV(3.4.3) Error: Assertion failed (((((sizeof(size_t)<<28)|0x8442211) >> ((traits::Depth<_Tp>::value) & ((1 << 3) - 1))*4) & 15) == elemSize1()) in cv::Mat::at, file D:\code\shit\so07\deps\include\opencv2/core/mat.inl.hpp, line 1102

To allow assignment of the result from cv::mean (which is a cv::Scalar) to our CV_8UC3 matrix, we need to do two things (not necessarily in this order):

Convert the values from double to uint8_t -- OpenCV will do a saturate_cast, but given that the mean won't go past the min/max of the input items, we'd be fine with a regular cast.

Get rid of the 4th element.

To remove the 4th element, we can use cv::Matx::get_minor (The documentation is a bit lacking, but a look at the implementation explains it fairly well). The result is a cv::Matx, so we have to use that instead of cv::Vec when using cv::Mat::at.

The two possible options then are:

Get rid of the 4th element and then
cast result to convert the cv::Matx to uint8_t element type.

Cast the cv::Scalar to cv::Scalar_<uint8_t> first, and then get rid of the 4th element.

Example:

#include <opencv2/opencv.hpp>

typedef cv::Matx<uint8_t, 3, 1> Mat31b; // Convenience, OpenCV only has typedefs for double and float variants

int main()
{
    cv::Mat test_mat(1, 12, CV_8UC3); // 12 * 3 = 36 bytes of data
    test_mat = cv::Scalar(1, 1, 1); // Set all elements to 1
    std::cout << "Before: " << test_mat << "\n";

    cv::Scalar test_scalar{ 2,3,4,0 };
    cv::Matx31d temp = test_scalar.get_minor<3, 1>(0, 0);
    test_mat.at<Mat31b>(0, 0) = static_cast<Mat31b>(temp);

    // or
    // cv::Scalar_<uint8_t> temp(static_cast<cv::Scalar_<uint8_t>>(test_scalar));
    // test_mat.at<Mat31b>(0, 0) = temp.get_minor<3, 1>(0, 0);

    std::cout << "After: " << test_mat << "\n";

    return 0;
}

NB: You can get rid of the explicit temporaries, they're here just for easier readability.

Output:

Both options produce the following output:

Before: [  1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1]
After: [  2,   3,   4,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1,   1]

As we can see, only the first 3 bytes were changed, so it behaves correctly.

Some thoughts about performance.

It's hard to guess which of the two approaches is better. Casting first means you allocate smaller amount of memory for the temporary, but then you have to do 4 saturate_casts instead of 3. Some benchmarking would have to be done (excercise for the reader). The calculation of mean will outweigh it significantly, so it's likely to be irrelevant.

Given that we don't really need the saturate_casts, perhaps the simple, but more verbose approach (optimized version of the thing that worked for you) might perform better in a tight loop.

cv::Vec3b& current_element(avgs.at<cv::Vec3b>(i));
cv::Scalar current_mean(cv::mean(cv::Mat(img, rois[i])));
for (int n(0); n < 3; ++n) {
    current_element[n] = static_cast<uint8_t>(current_mean[n]);
}

Update:

One more idea that came up in discussion with @alkasm. The assignment operator for a cv::Mat is vectorized when given a cv::Scalar (it assigns the same value to all elements), and it ignores the additional channel values the cv::Scalar may hold relative to the target cv::Mat type. (e.g. for a 3-channel Mat it ignores the 4th value).

We could take a 1x1 ROI of the target Mat, and assign it the mean Scalar. Necessary type conversions will happen, and the 4th channel will be discared. Probably not optimal, but it's by far the least amount of code so far.

test_mat(cv::Rect(0, 0, 1, 1)) = test_scalar;

The result is the same as before.


问:
Test jsonb array to see if it contains one or more elements?
I have a user table with a data jsonb column. In that, I have a cars array that can have 0-N cars in it.

I'm trying to do a query like this to find if the user's cars array contains either Toyota or Mitsubishi, but it's throwing an error

```<code>await knex('users.record')
    .where('created_at', '>', '2019-05-21')
    .select('data')
    .whereRaw('cars', ['Toyota', 'Mitsubishi']) // this seems wrong
    .returning('*');
</code>```

One example user's cars array is ['Toyota', 'Mitsubishi', 'Honda', 'Ford']

答:
You can use the jsonb contains operator @>:

```<code>SELECT * FROM users
WHERE  created_at > '2019-05-21'
AND   (data @> '{"cars":["Toyota"]}' OR
       data @> '{"cars":["Mitsubishi"]}');
</code>```

Pure SQL, I am not familiar with knex.

This can be supported with an index. See:

What's the proper index for querying structures in arrays in Postgres jsonb?

Body:
I have a user table with a data jsonb column. In that, I have a cars array that can have 0-N cars in it.

I'm trying to do a query like this to find if the user's cars array contains either Toyota or Mitsubishi, but it's throwing an error

await knex('users.record')
    .where('created_at', '>', '2019-05-21')
    .select('data')
    .whereRaw('cars', ['Toyota', 'Mitsubishi']) // this seems wrong
    .returning('*');

One example user's cars array is ['Toyota', 'Mitsubishi', 'Honda', 'Ford']

Body:
You can use the jsonb contains operator @>:

SELECT * FROM users
WHERE  created_at > '2019-05-21'
AND   (data @> '{"cars":["Toyota"]}' OR
       data @> '{"cars":["Mitsubishi"]}');

Pure SQL, I am not familiar with knex.

This can be supported with an index. See:

What's the proper index for querying structures in arrays in Postgres jsonb?


问:
Take an array of any value type as formal parameter
I would like to be able to declare a function as

```<code>void foo(<any value type>[] data){}
</code>```

in C# 2.0.  If I declare it as

```<code>void foo(ValueType[] data){}
</code>```

it compiles, but then the elements in data[] are treated as though they're derived from object, e.g. I can't say something like

```<code>fixed (void* pData = data){}
</code>```

I'd like to avoid taking the void* as the parameter -- I just want to be able to accept any value-type array and then do unmanaged things to it.

ETA: Also, this has the same problem:

```<code>public static unsafe void foo<T>(T[] data) where T:struct{
  fixed(void *p = data){}
}
</code>```

in case you were wondering.  Fixed fails because it's treated as a managed type -- CS0208, cannot declare a pointer to a managed type.  See "mm" below.  I think he's right... it probably just can't be done.

答:
I don't think this is possible using C#. Structs do not inherit (however loosely) from System.ValueType until after compile time so you can't match Foo's method signature via polymorphism. Generics are also out according to the language specification:

"An unmanaged-type is any type that isn’t a reference-type, a type-parameter, or a generic struct-type and
  contains no fields whose type is not an unmanaged-type."

So that's why you can't take the address of T[] regardless of the struct constraint.

You could declare a struct type (say, Bar) as the argument to Foo, compile the code, and change the method signature at the IL level:

.method private hidebysig static void  Foo(valuetype [mscorlib]System.ValueType[] args) cil managed

And then the call as well:

IL_0020:  call       void ConsoleApplication1.Program::Foo(valuetype [mscorlib]System.ValueType[])

While I was able to run the resulting program I don't know what kind of side effects this has. Also, even if you could reference the modified function you wouldn't be able to call it from C# because again structs don't inherit from System.ValueType until after compilation so the method signature wouldn't match.

OwnerDisplayName: Coderer

ContentLicense: CC BY-SA 2.5

Body:
I would like to be able to declare a function as

void foo(<any value type>[] data){}

in C# 2.0.  If I declare it as

void foo(ValueType[] data){}

it compiles, but then the elements in data[] are treated as though they're derived from object, e.g. I can't say something like

fixed (void* pData = data){}

I'd like to avoid taking the void* as the parameter -- I just want to be able to accept any value-type array and then do unmanaged things to it.

ETA: Also, this has the same problem:

public static unsafe void foo<T>(T[] data) where T:struct{
  fixed(void *p = data){}
}

in case you were wondering.  Fixed fails because it's treated as a managed type -- CS0208, cannot declare a pointer to a managed type.  See "mm" below.  I think he's right... it probably just can't be done.

LastEditorDisplayName: Coderer


问:
Transposing and Concatenating strings
How do I transpose and concatenate a pandas dataframe without using a for loop?

Here is the input data:

```<code>input_data =  pandas.DataFrame({'a': ['fruit', 'fruit', 'fruit', 'food', 'food', 'food', 'food'],
                      'b': ['banana', '', 'apple', 'rice', '', 'yam', 'chicken']})
</code>```

Resulting output should look like this:

```<code>result = pandas.DataFrame({'a': ['fruit', 'food'],
                      'b': ['banana  apple', 'rice  yam  chicken']})
</code>```

Here is my for loop solution:

```<code>stuff_list = input_data.a.drop_duplicates().tolist()
result = pandas.DataFrame()

for s in stuff_list:
    step1 = input_data[input_data.a == s]
    step2 = ' '.join(step1.b.tolist())
    step3 = pandas.DataFrame({'a':[s], 'b':[step2]})
    result = result.append(step3)

print(result)
</code>```

答:
Try groupby:

```<code>>>> input_data.groupby('a')['b'].apply(lambda x: ' '.join(x)).reset_index()
       a                  b
0   food  rice  yam chicken
1  fruit      banana  apple
>>>
</code>```

Title: Transposing and Concatenating strings

Body:
How do I transpose and concatenate a pandas dataframe without using a for loop?

Here is the input data:

input_data =  pandas.DataFrame({'a': ['fruit', 'fruit', 'fruit', 'food', 'food', 'food', 'food'],
                      'b': ['banana', '', 'apple', 'rice', '', 'yam', 'chicken']})

Resulting output should look like this:

result = pandas.DataFrame({'a': ['fruit', 'food'],
                      'b': ['banana  apple', 'rice  yam  chicken']})

Here is my for loop solution:

stuff_list = input_data.a.drop_duplicates().tolist()
result = pandas.DataFrame()

for s in stuff_list:
    step1 = input_data[input_data.a == s]
    step2 = ' '.join(step1.b.tolist())
    step3 = pandas.DataFrame({'a':[s], 'b':[step2]})
    result = result.append(step3)

print(result)

Body:
Try groupby:

>>> input_data.groupby('a')['b'].apply(lambda x: ' '.join(x)).reset_index()
       a                  b
0   food  rice  yam chicken
1  fruit      banana  apple
>>>


问:
ffmpeg: Image2 => Error while opening encoder
I get the following error ffmpeg.

Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height

```<code>ffmpeg -f image2 -i %05d.jpg -vcodec libx264 foo.mp4
</code>```

I'm pretty sure I've used this exact command before and it's been fine. This is my terminal output. Any help would be appreciated.

```<code>$ ffmpeg -f image2 -i %05d.jpg -vcodec libx264 foo.mp4
ffmpeg version 1.0 Copyright (c) 2000-2012 the FFmpeg developers
  built on Nov 22 2012 17:59:05 with Apple clang version 4.1 (tags/Apple/clang-421.11.66) (based on LLVM 3.1svn)
  configuration: --prefix=/opt/local --enable-swscale --enable-avfilter --enable-libmp3lame --enable-libvorbis --enable-libopus --enable-libtheora --enable-libschroedinger --enable-libopenjpeg --enable-libmodplug --enable-libvpx --enable-libspeex --enable-libfreetype --mandir=/opt/local/share/man --enable-shared --enable-pthreads --cc=/usr/bin/clang --arch=x86_64 --enable-yasm --enable-gpl --enable-postproc --enable-libx264 --enable-libxvid
  libavutil      51. 73.101 / 51. 73.101

  libavcodec     54. 59.100 / 54. 59.100

  libavformat    54. 29.104 / 54. 29.104

  libavdevice    54.  2.101 / 54.  2.101

  libavfilter     3. 17.100 /  3. 17.100

  libswscale      2.  1.101 /  2.  1.101

  libswresample   0. 15.100 /  0. 15.100

  libpostproc    52.  0.100 / 52.  0.100

Input #0, image2, from '%05d.jpg':
  Duration: 00:00:04.44, start: 0.000000, bitrate: N/A
    Stream #0:0: Video: mjpeg, yuvj420p, 1201x900 [SAR 1:1 DAR 1201:900], 25 fps, 25 tbr, 25 tbn, 25 tbc
[libx264 @ 0x7fab0881aa00] width not divisible by 2 (1201x900)
Output #0, mp4, to 'foo.mp4':
    Stream #0:0: Video: h264, yuvj420p, 1201x900 [SAR 1:1 DAR 1201:900], q=-1--1, 90k tbn, 25 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (mjpeg -> libx264)
Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height
</code>```

答:
A solution which worked for me was to use

```<code>-vf scale=1920:1080
</code>```

As an option before the output video, i.e.

```<code>ffmpeg -y -loop 1 -i "input.png" -c:v libx264 -t 5 -pix_fmt yuv420p -vf scale=1920:1080 out.mp4
</code>```

It automatically resizes images correctly, though I never tested what happens when the resolution was larger than 1920:1080 (TBD).

ContentLicense: CC BY-SA 3.0

Body:
I get the following error ffmpeg.

Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height

ffmpeg -f image2 -i %05d.jpg -vcodec libx264 foo.mp4

I'm pretty sure I've used this exact command before and it's been fine. This is my terminal output. Any help would be appreciated.

$ ffmpeg -f image2 -i %05d.jpg -vcodec libx264 foo.mp4
ffmpeg version 1.0 Copyright (c) 2000-2012 the FFmpeg developers
  built on Nov 22 2012 17:59:05 with Apple clang version 4.1 (tags/Apple/clang-421.11.66) (based on LLVM 3.1svn)
  configuration: --prefix=/opt/local --enable-swscale --enable-avfilter --enable-libmp3lame --enable-libvorbis --enable-libopus --enable-libtheora --enable-libschroedinger --enable-libopenjpeg --enable-libmodplug --enable-libvpx --enable-libspeex --enable-libfreetype --mandir=/opt/local/share/man --enable-shared --enable-pthreads --cc=/usr/bin/clang --arch=x86_64 --enable-yasm --enable-gpl --enable-postproc --enable-libx264 --enable-libxvid
  libavutil      51. 73.101 / 51. 73.101

  libavcodec     54. 59.100 / 54. 59.100

  libavformat    54. 29.104 / 54. 29.104

  libavdevice    54.  2.101 / 54.  2.101

  libavfilter     3. 17.100 /  3. 17.100

  libswscale      2.  1.101 /  2.  1.101

  libswresample   0. 15.100 /  0. 15.100

  libpostproc    52.  0.100 / 52.  0.100

Input #0, image2, from '%05d.jpg':
  Duration: 00:00:04.44, start: 0.000000, bitrate: N/A
    Stream #0:0: Video: mjpeg, yuvj420p, 1201x900 [SAR 1:1 DAR 1201:900], 25 fps, 25 tbr, 25 tbn, 25 tbc
[libx264 @ 0x7fab0881aa00] width not divisible by 2 (1201x900)
Output #0, mp4, to 'foo.mp4':
    Stream #0:0: Video: h264, yuvj420p, 1201x900 [SAR 1:1 DAR 1201:900], q=-1--1, 90k tbn, 25 tbc
Stream mapping:
  Stream #0:0 -> #0:0 (mjpeg -> libx264)
Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height

Body:
A solution which worked for me was to use

-vf scale=1920:1080

As an option before the output video, i.e.

ffmpeg -y -loop 1 -i "input.png" -c:v libx264 -t 5 -pix_fmt yuv420p -vf scale=1920:1080 out.mp4

It automatically resizes images correctly, though I never tested what happens when the resolution was larger than 1920:1080 (TBD).


问:
Generically determining arity of data types
I want to calculate the "arity" of a certain class of data types. Namely data-types with a single constructor and some number of fields. E.g. data T a = T Int () String a. The "arity" will then be the number of fields. For T a this will be 4. I envisage a function with a signature something like this:

```<code>forall a . C a => Int
</code>```

for some appropriate choice of C. I know that if I have Generic a for some type a I get from :: a -> Rep a x, but note that this will require a concrete value for a and I'm interested in calculating it statically. Is this possible somehow? I've also thought about Typeable, but I don't really understand the API.

答:
We can use generics. Quite a few extensions are used throughout this answer, common for this variety of metaprogramming. I'll mention the first time they are used but for more details refer to other resources such as the GHC user guide (list of extensions)
 or the Haskell wiki.

```<code>data T = T Int Bool String deriving Generic

-- Used extension: DeriveGeneric
</code>```

The derived instance includes a type family instance for Rep, which constructs a generic representation of the type T. Rep T uses a fixed set of types found in the GHC.Generics module:

```<code>type Rep T = M1 D _ ((M1 C _ (K1 _ Int) :*: M1 C _ (K1 _ Bool)) :*: M1 C _ (K1 _ String))
--
-- Irrelevant details hidden in underscores.
-- There's actually a few more M1's as well
--
-- You can see the full and real details in a ghci session with this command
--   :kind! Rep T
</code>```

The Arity function

We will define a type-level function to inspect that structure and compute the number of fields. This is its signature:

```<code>type family Arity (f :: Type -> Type) :: Nat
-- If T is a type with one constructor (C x1 ... xn),
-- Arity (Rep T) is the arity n of that constructor

-- Used extensions: TypeFamilies, DataKinds
</code>```

When it comes to generic representation, we can pretend that TT = (Type->Type) is like an ADT with the following constructors:

```<code>-- We can pretend that there is this data type TT
-- such that Arity is a function (TT -> Nat)
data TT
  = M1 Type Meta TT
  | (:+:) TT TT
  | V1
  | (:*:) TT TT
  | U1
  | K1 Type Type
</code>```

Very (too?) brief overview. M1 contains information such as type names (including the module and package), constructor names, whether the constructor uses record notation, strictness of fields... V1 and (:+:) are used for types with zero or many constructors, so they are not relevant to us. U1 represents nullary constructors, while (:*:) splits n-ary constructors, with a representation of half of the fields on either side. K1 marks one constructor field.

We define the function Arity by giving it type family instances. But really, for a first understanding, ignore the type instance keywords and pretend Arity is a function defined by pattern-matching as usual.

Looking at the representation Rep T above, we first encounter an M1 node, which we ignore and recursively call Arity on its contents.

```<code>type instance Arity (M1 i c f) = Arity f
</code>```

Then we see (:*:) which splits a set of fields in two parts; we calculate their arities recursively and add them up.

```<code>type instance Arity (f :*: g) = Arity f + Arity g

-- Used extensions: TypeOperators, UndecidableInstances
</code>```

U1 represents nullary constructors,

```<code>type instance Arity U1 = 0
</code>```

and K1 is a single field.

```<code>type instance (K1 i a) = 1
</code>```

Now, given a generic type T (i.e., with an instance of Generic), Arity (Rep T) is its arity, as a type-level Nat. In ghci, we can test it with

```<code>:kind! Arity (Rep T)
</code>```

Use GHC.TypeNats.natVal to convert it to a Natural value (like Integer, but nonnegative).

```<code>-- Calculate the arity of the constructor of a generic type `a`.
-- `a` must have a single constructor.
arity :: forall a. (Generic a, KnownNat (Arity (Rep a))) => Natural
arity = natVal (Proxy @(Arity (Rep a)))

-- Used extensions:
--   ScopedTypeVariables,
--   AllowAmbiguousTypes, TypeApplications,
--   FlexibleContexts
</code>```

We get the arity of any generic type T as a value arity @T, which can be converted using fromIntegral :: Natural -> Integer for example.

```<code>type Rep T = M1 D _ ((M1 C _ (K1 _ Int) :*: M1 C _ (K1 _ Bool)) :*: M1 C _ (K1 _ String))
--
-- Irrelevant details hidden in underscores.
-- There's actually a few more M1's as well
--
-- You can see the full and real details in a ghci session with this command
--   :kind! Rep T
</code>```0

Full gist: https://gist.github.com/Lysxia/10f1da354f051b2d2eb24f6aace1bf9c

Body:
I want to calculate the "arity" of a certain class of data types. Namely data-types with a single constructor and some number of fields. E.g. data T a = T Int () String a. The "arity" will then be the number of fields. For T a this will be 4. I envisage a function with a signature something like this:

forall a . C a => Int

for some appropriate choice of C. I know that if I have Generic a for some type a I get from :: a -> Rep a x, but note that this will require a concrete value for a and I'm interested in calculating it statically. Is this possible somehow? I've also thought about Typeable, but I don't really understand the API.

Body:
We can use generics. Quite a few extensions are used throughout this answer, common for this variety of metaprogramming. I'll mention the first time they are used but for more details refer to other resources such as the GHC user guide (list of extensions)
 or the Haskell wiki.

data T = T Int Bool String deriving Generic

-- Used extension: DeriveGeneric

The derived instance includes a type family instance for Rep, which constructs a generic representation of the type T. Rep T uses a fixed set of types found in the GHC.Generics module:

type Rep T = M1 D _ ((M1 C _ (K1 _ Int) :*: M1 C _ (K1 _ Bool)) :*: M1 C _ (K1 _ String))
--
-- Irrelevant details hidden in underscores.
-- There's actually a few more M1's as well
--
-- You can see the full and real details in a ghci session with this command
--   :kind! Rep T

The Arity function

We will define a type-level function to inspect that structure and compute the number of fields. This is its signature:

type family Arity (f :: Type -> Type) :: Nat
-- If T is a type with one constructor (C x1 ... xn),
-- Arity (Rep T) is the arity n of that constructor

-- Used extensions: TypeFamilies, DataKinds

When it comes to generic representation, we can pretend that TT = (Type->Type) is like an ADT with the following constructors:

-- We can pretend that there is this data type TT
-- such that Arity is a function (TT -> Nat)
data TT
  = M1 Type Meta TT
  | (:+:) TT TT
  | V1
  | (:*:) TT TT
  | U1
  | K1 Type Type

Very (too?) brief overview. M1 contains information such as type names (including the module and package), constructor names, whether the constructor uses record notation, strictness of fields... V1 and (:+:) are used for types with zero or many constructors, so they are not relevant to us. U1 represents nullary constructors, while (:*:) splits n-ary constructors, with a representation of half of the fields on either side. K1 marks one constructor field.

We define the function Arity by giving it type family instances. But really, for a first understanding, ignore the type instance keywords and pretend Arity is a function defined by pattern-matching as usual.

Looking at the representation Rep T above, we first encounter an M1 node, which we ignore and recursively call Arity on its contents.

type instance Arity (M1 i c f) = Arity f

Then we see (:*:) which splits a set of fields in two parts; we calculate their arities recursively and add them up.

type instance Arity (f :*: g) = Arity f + Arity g

-- Used extensions: TypeOperators, UndecidableInstances

U1 represents nullary constructors,

type instance Arity U1 = 0

and K1 is a single field.

type instance (K1 i a) = 1

Now, given a generic type T (i.e., with an instance of Generic), Arity (Rep T) is its arity, as a type-level Nat. In ghci, we can test it with

:kind! Arity (Rep T)

Use GHC.TypeNats.natVal to convert it to a Natural value (like Integer, but nonnegative).

-- Calculate the arity of the constructor of a generic type `a`.
-- `a` must have a single constructor.
arity :: forall a. (Generic a, KnownNat (Arity (Rep a))) => Natural
arity = natVal (Proxy @(Arity (Rep a)))

-- Used extensions:
--   ScopedTypeVariables,
--   AllowAmbiguousTypes, TypeApplications,
--   FlexibleContexts

We get the arity of any generic type T as a value arity @T, which can be converted using fromIntegral :: Natural -> Integer for example.

main = print (arity @T)

Full gist: https://gist.github.com/Lysxia/10f1da354f051b2d2eb24f6aace1bf9c


问:
Returning 404 Error ASP.NET MVC 3
I have tried the following 2 things to have a page return a 404 error:

```<code>public ActionResult Index()
{
    return new HttpStatusCodeResult(404);
}

public ActionResult NotFound()
{
    return HttpNotFound();
}
</code>```

but both of them just render a blank page.  How can I manually return a 404 error from within ASP.NET MVC 3?

答:
I'm successfully using this:</p>

```<code>return new HttpNotFoundResult();
</code>```

Title: Returning 404 Error ASP.NET MVC 3

Body:
I have tried the following 2 things to have a page return a 404 error:

public ActionResult Index()
{
    return new HttpStatusCodeResult(404);
}

public ActionResult NotFound()
{
    return HttpNotFound();
}

but both of them just render a blank page.  How can I manually return a 404 error from within ASP.NET MVC 3?

Body:
I'm successfully using this:

return new HttpNotFoundResult();


问:
How to drop temp table in try catch block with transaction SQL
Hello i have the following query with a transaction in a try catch block and i rollback transaction on the catch block if fails. Problem is that I am creating a temporary table and i don't know how to handle it with a transaction. So how can I safely get rid of temporary table in this situation? I tried to add it on catch block but i'm not sure if this is a good practice

```<code>ALTER PROCEDURE GetDataForNewListaAbastecimento
    @UAP NVARCHAR(20),
    @ColaboradorId INT
AS
BEGIN

    DECLARE @TransactionName nvarchar(20) = 'GetDataForNewListaAbastecimento'
    DECLARE @Status INT
    DECLARE @CurrentWeekDay INT
    SET DATEFIRST 1
    SET @CurrentWeekDay = DATEPART (WEEKDAY, GETDATE()) - 1

    CREATE TABLE #tempTable
    (
        Id INT PRIMARY KEY,
        Referencia NVARCHAR(15),
        UAP NVARCHAR(20),
        ConsumoWeek01 FLOAT,
        ConsumoWeek02 FLOAT,
        Stock INT,
        QtdPecasPorCaixa INT
        UNIQUE (Id)
    )

    BEGIN TRY
    BEGIN TRAN @TransactionName

        DECLARE @SQL NVARCHAR(MAX)
        SELECT @SQL = 'INSERT INTO #tempTable
        SELECT
            Id,
            Referencia,
            UAP,
            ConsumoWeek01 AS ConsumoWeek01,
            ConsumoWeek02,
            CASE
                WHEN Stock IS NULL THEN 0
            ELSE
                Stock
            END AS Stock,
            QtdPecasPorCaixa
        FROM OPENQUERY(MACPAC,
        ''WITH maxFornecedorByDate AS
         (
            SELECT
                YDA3REP.A3ARCD,
                YDA3REP.A3D5CD,
                ROW_NUMBER() OVER ( PARTITION BY YDA3REP.A3D5CD ORDER BY YDA3REP.A3A3DT DESC) AS Number
            FROM
                AUTO.YSACHAPOR.YDA3REP YDA3REP
         )

        SELECT
            ROW_NUMBER() OVER(ORDER BY A.RH6001 ASC) AS Id,
            A.RH6001 as Referencia,
            A.RH6002 as UAP,
            A.RH6030 as ConsumoWeek01,
            A.RH6031 as ConsumoWeek02,
            IC130M.LLBLT1 as Stock,
            M.AUQCON AS QtdPecasPorCaixa
        FROM AUTO.D805DATPOR.TRP060H AS A
        LEFT JOIN AUTO.D805DATPOR.IC130M IC130M
        ON A.RH6001 = IC130M.LLPPN AND
             IC130M.LLSTLC =
                 CASE A.RH6002
                      WHEN ''''UAP1'''' THEN ''''M1''''
                      WHEN ''''UAP2'''' THEN ''''M2''''
                      WHEN ''''UAP3'''' THEN ''''M3''''
                      WHEN ''''UAP4'''' THEN ''''M4''''
                      WHEN ''''UAP5'''' THEN ''''M5''''
                      WHEN ''''UAP6'''' THEN ''''M6''''
                      WHEN ''''UAPP'''' THEN ''''PROTOS''''
                      WHEN ''''EXT'''' THEN ''''EXTR''''
                    END
        LEFT JOIN
        (
            SELECT
                YDAUREP.AUD5CD,
                YDAUREP.AUQCON
            FROM maxFornecedorByDate F
            join AUTO.YSACHAPOR.YDAUREP YDAUREP
            ON F.A3ARCD = YDAUREP.AUARCD
            AND F.A3D5CD = YDAUREP.AUD5CD
            WHERE F.Number = 1 AND YDAUREP.AUD5CD LIKE ''''M%''''
            AND YDAUREP.AUD5CD NOT LIKE ''''%P%''''
            AND YDAUREP.AUA0NB > 1
            AND YDAUREP.AUG6ST= ''''O''''
        ) M
        ON M.AUD5CD = A.RH6001
        WHERE A.RH6001 Not Like ''''FS%''''
        AND A.RH6030 <> 0
        AND A.RH6002 = ''''' + @UAP + ''''' '')'
        EXEC sp_executesql @SQL

        INSERT INTO hListasAbastecimento (UAP,DataCriacao,ColaboradorId) VALUES (@UAP,GETDATE(),@ColaboradorId)

        INSERT INTO
            hReferenciasAbastecimento
            (
                Referencia,
                QtdAbastecimento,
                QtdCaixas,
                QtdPecasPorCaixa,
                ListaAbastecimentoId
            )
        SELECT
            C.Id,
            C.Referencia,
            ( T.ConsumoWeek01 / ( ( P.NumDias - @CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento AS QtdAbastecimento,
            T.QtdPecasPorCaixa,
            CASE
                WHEN ((T.ConsumoWeek01 / ( ( P.NumDias - @CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento) / NULLIF(T.QtdPecasPorCaixa,0) IS NULL THEN NULL
            ELSE
                CAST( CEILING(((T.ConsumoWeek01 / ( ( P.NumDias - @CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento) / T.QtdPecasPorCaixa )  AS INT)
            END AS QtdCaixas,
            SCOPE_IDENTITY()
        FROM
            #tempTable T
        INNER JOIN hParametros P
        ON P.Referencia = T.Referencia
        AND P.UAP = @UAP
        INNER JOIN hConsumos C
        ON C.Referencia = P.Referencia
        AND C.UAP = @UAP
        WHERE T.Stock < ( T.ConsumoWeek01 / ( ( P.NumDias - @CurrentWeekDay ) * P.NumPAB )) * P.QtdMin
        ORDER BY QtdAbastecimento DESC

        COMMIT TRANSACTION @TransactionName

        DROP TABLE #tempTable

        -- Success, Lista de abastecimento foi criada sem errors --
        SELECT @Status = 200
        RETURN @Status

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
        ROLLBACK TRAN @TransactionName
        DROP TABLE #tempTable
        SELECT
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_STATE() AS ErrorState,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_PROCEDURE() AS ErrorProcedure,
            ERROR_LINE() AS ErrorLine,
            ERROR_MESSAGE() AS ErrorMessage;

            -- Erro, Nao foi possivel criar lista de abastecimento, verificar dynamic query --
            SELECT @Status = 400
        RETURN @Status

    END CATCH

END
</code>```

EDIT

I'm calling the SP from an Asp .NET Core application with Entity Framework Core

```<code>  await _context.Database
        .ExecuteSqlCommandAsync("EXEC @Status = GetDataForNewListaAbastecimento @UAP, @ColaboradorId", @params);
</code>```

答:
try add this:

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results

(Replace Name your temp table #Result)

Body:
Hello i have the following query with a transaction in a try catch block and i rollback transaction on the catch block if fails. Problem is that I am creating a temporary table and i don't know how to handle it with a transaction. So how can I safely get rid of temporary table in this situation? I tried to add it on catch block but i'm not sure if this is a good practice

ALTER PROCEDURE GetDataForNewListaAbastecimento
    @UAP NVARCHAR(20),
    @ColaboradorId INT
AS
BEGIN

    DECLARE @TransactionName nvarchar(20) = 'GetDataForNewListaAbastecimento'
    DECLARE @Status INT
    DECLARE @CurrentWeekDay INT
    SET DATEFIRST 1
    SET @CurrentWeekDay = DATEPART (WEEKDAY, GETDATE()) - 1

    CREATE TABLE #tempTable
    (
        Id INT PRIMARY KEY,
        Referencia NVARCHAR(15),
        UAP NVARCHAR(20),
        ConsumoWeek01 FLOAT,
        ConsumoWeek02 FLOAT,
        Stock INT,
        QtdPecasPorCaixa INT
        UNIQUE (Id)
    )

    BEGIN TRY
    BEGIN TRAN @TransactionName

        DECLARE @SQL NVARCHAR(MAX)
        SELECT @SQL = 'INSERT INTO #tempTable
        SELECT
            Id,
            Referencia,
            UAP,
            ConsumoWeek01 AS ConsumoWeek01,
            ConsumoWeek02,
            CASE
                WHEN Stock IS NULL THEN 0
            ELSE
                Stock
            END AS Stock,
            QtdPecasPorCaixa
        FROM OPENQUERY(MACPAC,
        ''WITH maxFornecedorByDate AS
         (
            SELECT
                YDA3REP.A3ARCD,
                YDA3REP.A3D5CD,
                ROW_NUMBER() OVER ( PARTITION BY YDA3REP.A3D5CD ORDER BY YDA3REP.A3A3DT DESC) AS Number
            FROM
                AUTO.YSACHAPOR.YDA3REP YDA3REP
         )

        SELECT
            ROW_NUMBER() OVER(ORDER BY A.RH6001 ASC) AS Id,
            A.RH6001 as Referencia,
            A.RH6002 as UAP,
            A.RH6030 as ConsumoWeek01,
            A.RH6031 as ConsumoWeek02,
            IC130M.LLBLT1 as Stock,
            M.AUQCON AS QtdPecasPorCaixa
        FROM AUTO.D805DATPOR.TRP060H AS A
        LEFT JOIN AUTO.D805DATPOR.IC130M IC130M
        ON A.RH6001 = IC130M.LLPPN AND
             IC130M.LLSTLC =
                 CASE A.RH6002
                      WHEN ''''UAP1'''' THEN ''''M1''''
                      WHEN ''''UAP2'''' THEN ''''M2''''
                      WHEN ''''UAP3'''' THEN ''''M3''''
                      WHEN ''''UAP4'''' THEN ''''M4''''
                      WHEN ''''UAP5'''' THEN ''''M5''''
                      WHEN ''''UAP6'''' THEN ''''M6''''
                      WHEN ''''UAPP'''' THEN ''''PROTOS''''
                      WHEN ''''EXT'''' THEN ''''EXTR''''
                    END
        LEFT JOIN
        (
            SELECT
                YDAUREP.AUD5CD,
                YDAUREP.AUQCON
            FROM maxFornecedorByDate F
            join AUTO.YSACHAPOR.YDAUREP YDAUREP
            ON F.A3ARCD = YDAUREP.AUARCD
            AND F.A3D5CD = YDAUREP.AUD5CD
            WHERE F.Number = 1 AND YDAUREP.AUD5CD LIKE ''''M%''''
            AND YDAUREP.AUD5CD NOT LIKE ''''%P%''''
            AND YDAUREP.AUA0NB > 1
            AND YDAUREP.AUG6ST= ''''O''''
        ) M
        ON M.AUD5CD = A.RH6001
        WHERE A.RH6001 Not Like ''''FS%''''
        AND A.RH6030 <> 0
        AND A.RH6002 = ''''' + @UAP + ''''' '')'
        EXEC sp_executesql @SQL

        INSERT INTO hListasAbastecimento (UAP,DataCriacao,ColaboradorId) VALUES (@UAP,GETDATE(),@ColaboradorId)

        INSERT INTO
            hReferenciasAbastecimento
            (
                Referencia,
                QtdAbastecimento,
                QtdCaixas,
                QtdPecasPorCaixa,
                ListaAbastecimentoId
            )
        SELECT
            C.Id,
            C.Referencia,
            ( T.ConsumoWeek01 / ( ( P.NumDias - @CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento AS QtdAbastecimento,
            T.QtdPecasPorCaixa,
            CASE
                WHEN ((T.ConsumoWeek01 / ( ( P.NumDias - @CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento) / NULLIF(T.QtdPecasPorCaixa,0) IS NULL THEN NULL
            ELSE
                CAST( CEILING(((T.ConsumoWeek01 / ( ( P.NumDias - @CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento) / T.QtdPecasPorCaixa )  AS INT)
            END AS QtdCaixas,
            SCOPE_IDENTITY()
        FROM
            #tempTable T
        INNER JOIN hParametros P
        ON P.Referencia = T.Referencia
        AND P.UAP = @UAP
        INNER JOIN hConsumos C
        ON C.Referencia = P.Referencia
        AND C.UAP = @UAP
        WHERE T.Stock < ( T.ConsumoWeek01 / ( ( P.NumDias - @CurrentWeekDay ) * P.NumPAB )) * P.QtdMin
        ORDER BY QtdAbastecimento DESC

        COMMIT TRANSACTION @TransactionName

        DROP TABLE #tempTable

        -- Success, Lista de abastecimento foi criada sem errors --
        SELECT @Status = 200
        RETURN @Status

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
        ROLLBACK TRAN @TransactionName
        DROP TABLE #tempTable
        SELECT
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_STATE() AS ErrorState,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_PROCEDURE() AS ErrorProcedure,
            ERROR_LINE() AS ErrorLine,
            ERROR_MESSAGE() AS ErrorMessage;

            -- Erro, Nao foi possivel criar lista de abastecimento, verificar dynamic query --
            SELECT @Status = 400
        RETURN @Status

    END CATCH

END

EDIT

I'm calling the SP from an Asp .NET Core application with Entity Framework Core

  await _context.Database
        .ExecuteSqlCommandAsync("EXEC @Status = GetDataForNewListaAbastecimento @UAP, @ColaboradorId", @params);


问:
How to specify a default value for argument list processed by click?
I have this line of code that is expected to grab all the file names passed to my Python script:

```<code>@click.argument("logs", nargs=-1, type=click.File('r'), required=1)
</code>```

When no file names are passed, I want to default to -, that is, the standard input.  So, if I try:

```<code>@click.argument("logs", nargs=-1, type=click.File('r'), required=1, default="-")
</code>```

click becomes unhappy and throws this error:

TypeError: nargs=-1 in combination with a default value is not supported.

Is there a workaround for this? I tried setting nargs=0 but that throws a different error:

IndexError: tuple index out of range

答:
The following code:

```<code>import click

@click.command()
@click.option('--logs', '-l', multiple=True, default='-')
def cli(logs):
    click.echo('\n'.join(logs))
</code>```

Will produce the following:

```<code>$ myhello -l foo.log -l bar.log -l baz.log
foo.log
bar.log
baz.log
$ myhello
-
</code>```

So if you just could call your program differently with repeated parameters instead that would the workaround you are looking for.

Body:
I have this line of code that is expected to grab all the file names passed to my Python script:

@click.argument("logs", nargs=-1, type=click.File('r'), required=1)

When no file names are passed, I want to default to -, that is, the standard input.  So, if I try:

@click.argument("logs", nargs=-1, type=click.File('r'), required=1, default="-")

click becomes unhappy and throws this error:

TypeError: nargs=-1 in combination with a default value is not supported.

Is there a workaround for this? I tried setting nargs=0 but that throws a different error:

IndexError: tuple index out of range

Body:
The following code:

import click

@click.command()
@click.option('--logs', '-l', multiple=True, default='-')
def cli(logs):
    click.echo('\n'.join(logs))

Will produce the following:

$ myhello -l foo.log -l bar.log -l baz.log
foo.log
bar.log
baz.log
$ myhello
-

So if you just could call your program differently with repeated parameters instead that would the workaround you are looking for.


问:
Count across dataframe columns based on str.contains (or similar)
I would like to count the number of cells within each row that contain a particular character string, cells which have the particular string more than once should be counted once only.

I can count the number of cells across a row which equal a given value, but when I expand this logic to use str.contains, I have issues, as shown below

d = {'col1': ["a#", "b","c#"], 'col2': ["a", "b","c#"]}
df = pd.DataFrame(d)

#can correctly count across rows using equality
thisworks =( df =="a#" ).sum(axis=1)

#can count across  a column using str.contains
thisworks1=df['col1'].str.contains('#').sum()

#but cannot use str.contains with a dataframe so what is the alternative
thisdoesnt =( df.str.contains('#') ).sum(axis=1)
```

Output should be a series showing the number of cells in each row that contain the given character string.

答:
A solution using df.apply:

```<code>df = pd.DataFrame({'col1': ["a#", "b","c#"],
                   'col2': ["a", "b","c#"]})
df
  col1 col2
0   a#    a
1    b    b
2   c#   c#

df['sum'] = df.apply(lambda x: x.str.contains('#'), axis=1).sum(axis=1)

  col1 col2  sum
0   a#    a    1
1    b    b    0
2   c#   c#    2
</code>```

Body:
I would like to count the number of cells within each row that contain a particular character string, cells which have the particular string more than once should be counted once only.

I can count the number of cells across a row which equal a given value, but when I expand this logic to use str.contains, I have issues, as shown below

d = {'col1': ["a#", "b","c#"], 'col2': ["a", "b","c#"]}
df = pd.DataFrame(d)

#can correctly count across rows using equality
thisworks =( df =="a#" ).sum(axis=1)

#can count across  a column using str.contains
thisworks1=df['col1'].str.contains('#').sum()

#but cannot use str.contains with a dataframe so what is the alternative
thisdoesnt =( df.str.contains('#') ).sum(axis=1)

Output should be a series showing the number of cells in each row that contain the given character string.

Body:
A solution using df.apply:

df = pd.DataFrame({'col1': ["a#", "b","c#"],
                   'col2': ["a", "b","c#"]})
df
  col1 col2
0   a#    a
1    b    b
2   c#   c#

df['sum'] = df.apply(lambda x: x.str.contains('#'), axis=1).sum(axis=1)

  col1 col2  sum
0   a#    a    1
1    b    b    0
2   c#   c#    2


问:
Embedding javascript into html in Vue
So I've linked Firebase to my Vue project and now I want to display a portion of the content of a blog. I know that to display the entire blog content I can simple write the following within an html tag.

```<code>{{blogs[0].content}}
</code>```

My question is, how do you display just a portion of it, for example the first 100 characters of the content? I've tried,

```<code>{{blogs[0].content[:100]}}
</code>```

However that gives a compile error.

Also I have a second question, I have using bootstrap with Vue. More specifically the card cascade. Below shows a section of the bootstrap card cascade.

```<code><b-card
        title= blogs[0].title
        img-src="https://placekitten.com/g/400/450"
        img-alt="Image"
        img-top
      >
        <b-card-text>
          {{blogs[0].content[:10]}}
        </b-card-text>
</b-card>
</code>```

I want the title to be the title of blogs[0] but the way I have done it above just prints out "blogs[0].title"

答:
you can add a method that will get a portion of blog content.

```<code>methods: {
       getContentPortion (content, maxSize) {
          if(maxSize >= content.length) {
             return content;
           }

       return `${content.substr(0, maxSize)}...`;
    }
  },
</code>```

And then you can update your template with:

```<code><b-card
        title= blogs[0].title
        img-src="https://placekitten.com/g/400/450"
        img-alt="Image"
        img-top
      >
        <b-card-text>
          {{ getContentPortion(blogs[0].content, 10) }}
        </b-card-text>
</b-card>
</code>```

Title: Embedding javascript into html in Vue

Body:
So I've linked Firebase to my Vue project and now I want to display a portion of the content of a blog. I know that to display the entire blog content I can simple write the following within an html tag.

{{blogs[0].content}}

My question is, how do you display just a portion of it, for example the first 100 characters of the content? I've tried,

{{blogs[0].content[:100]}}

However that gives a compile error.

Also I have a second question, I have using bootstrap with Vue. More specifically the card cascade. Below shows a section of the bootstrap card cascade.

          {{blogs[0].content[:10]}}

I want the title to be the title of blogs[0] but the way I have done it above just prints out "blogs[0].title"

Body:
you can add a method that will get a portion of blog content.

methods: {
       getContentPortion (content, maxSize) {
          if(maxSize >= content.length) {
             return content;
           }

       return `${content.substr(0, maxSize)}...`;
    }
  },

And then you can update your template with:

<b-card
        title= blogs[0].title
        img-src="https://placekitten.com/g/400/450"
        img-alt="Image"
        img-top
      >
        <b-card-text>
          {{ getContentPortion(blogs[0].content, 10) }}
        </b-card-text>
</b-card>


问:
Create a vector of inclusive numbers in a dataframe in R
Reproducible data:

```<code>Start_Curr_Job <- c(2009, 2011, 2014)
End_Curr_Job <- c(2012, 2015, 2019)
data_clean <- data.frame(Start_Curr_Job, End_Curr_Job)
</code>```

I have a data frame with columns "startyear" and "endyear". I am trying to create a 3rd column that will contain an inclusive list of all the years in between, but my code below is not working out.

For example, for startyear = 2009 and endyear = 2012, allyears should equal 2009, 2010, 2011, 2012.

Any suggestions will be appreciated. My code below:

```<code>data_clean <- data_raw %>%
  filter(!is.na(Start_Curr_Job), !is.na(End_Curr_Job),
         Start_Curr_Job != "NA", End_Curr_Job != "NA" ) %>%
  mutate(Start_Curr_Job = as.numeric(Start_Curr_Job),
         End_Curr_Job = as.numeric(End_Curr_Job)) %>%
mutate(all_years = seq(from = Start_Curr_Job, to = End_Curr_Job, by = 1))
</code>```

Error Message: "Error in seq.default(from = Start_Curr_Job, to = End_Curr_Job, by = 1) :
  'from' must be of length 1"

I also tried the following, but it produced allyears = "2019:2012", which is also not what I want.

```<code>  for (row in 1:nrow(data_clean)) {
    data_clean$years[row] <- list(data_clean$Start_Curr_Job[row]:data_clean$End_Curr_Job[row])
  }
</code>```

Body:
Reproducible data:

Start_Curr_Job <- c(2009, 2011, 2014)
End_Curr_Job <- c(2012, 2015, 2019)
data_clean <- data.frame(Start_Curr_Job, End_Curr_Job)

I have a data frame with columns "startyear" and "endyear". I am trying to create a 3rd column that will contain an inclusive list of all the years in between, but my code below is not working out.

For example, for startyear = 2009 and endyear = 2012, allyears should equal 2009, 2010, 2011, 2012.

Any suggestions will be appreciated. My code below:

data_clean <- data_raw %>%
  filter(!is.na(Start_Curr_Job), !is.na(End_Curr_Job),
         Start_Curr_Job != "NA", End_Curr_Job != "NA" ) %>%
  mutate(Start_Curr_Job = as.numeric(Start_Curr_Job),
         End_Curr_Job = as.numeric(End_Curr_Job)) %>%
mutate(all_years = seq(from = Start_Curr_Job, to = End_Curr_Job, by = 1))

Error Message: "Error in seq.default(from = Start_Curr_Job, to = End_Curr_Job, by = 1) :
  'from' must be of length 1"

I also tried the following, but it produced allyears = "2019:2012", which is also not what I want.

  for (row in 1:nrow(data_clean)) {
    data_clean$years[row] <- list(data_clean$Start_Curr_Job[row]:data_clean$End_Curr_Job[row])
  }

Body:
You can use apply() with paste() and seq() from base R -

data_clean$years <- apply(data_clean, 1, function(x) paste(seq(x[1], x[2]), collapse = ", "))

  Start_Curr_Job End_Curr_Job                              years
1           2009         2012             2009, 2010, 2011, 2012
2           2011         2015       2011, 2012, 2013, 2014, 2015
3           2014         2019 2014, 2015, 2016, 2017, 2018, 2019


答:
If you use agg, you don't need lambda

```<code>input_data.groupby('a', sort=False).b.agg(' '.join).reset_index()

Out[2266]:
       a                  b
0  fruit      banana  apple
1   food  rice  yam chicken
</code>```

Title: Transposing and Concatenating strings

Body:
How do I transpose and concatenate a pandas dataframe without using a for loop?

Here is the input data:

input_data =  pandas.DataFrame({'a': ['fruit', 'fruit', 'fruit', 'food', 'food', 'food', 'food'],
                      'b': ['banana', '', 'apple', 'rice', '', 'yam', 'chicken']})

Resulting output should look like this:

result = pandas.DataFrame({'a': ['fruit', 'food'],
                      'b': ['banana  apple', 'rice  yam  chicken']})

Here is my for loop solution:

stuff_list = input_data.a.drop_duplicates().tolist()
result = pandas.DataFrame()

for s in stuff_list:
    step1 = input_data[input_data.a == s]
    step2 = ' '.join(step1.b.tolist())
    step3 = pandas.DataFrame({'a':[s], 'b':[step2]})
    result = result.append(step3)

print(result)

Body:
If you use agg, you don't need lambda

input_data.groupby('a', sort=False).b.agg(' '.join).reset_index()

Out[2266]:
       a                  b
0  fruit      banana  apple
1   food  rice  yam chicken


问:
C# MS Chart Control - highlight today's date in Gantt Chart
The title of this question says it all.

I've got a gantt chart (RangeBar) made using the MS Chart Control, and at present I have some StripLines to highlight weekends and the start of each month, but I need one to appear on today's date only so the user can see where we are at the mo.

Is this possible with this control, or am I fishing for unicorns?

If it's possible, how?

Cheers

答:
Nevermind, figured it out:</p>

```<code>StripLine strpToday = new StripLine();
        strpToday.IntervalOffset = DateTime.Today.ToOADate();
        strpToday.StripWidth = 1;
        strpToday.BackColor = Color.ForestGreen;
        chtHC.ChartAreas[0].AxisY.StripLines.Add(strpToday);
</code>```

Body:
Nevermind, figured it out:

StripLine strpToday = new StripLine();
        strpToday.IntervalOffset = DateTime.Today.ToOADate();
        strpToday.StripWidth = 1;
        strpToday.BackColor = Color.ForestGreen;
        chtHC.ChartAreas[0].AxisY.StripLines.Add(strpToday);


问:
PyHook doesn't detect key pressed in some windows
I ran this PyHook sample code:

```<code>    import pythoncom, pyHook

def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'

# return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()
</code>```

To try it out and it works in most windows but when I try it inside a game window it acts like I'm not pressing anything.

Is there a way to listen to keypresses from a specific process? what should I do?

答:
Your problem might be caused by the fact that your computer is giving the game priority over your keypress program, so when you press a key, the input goes directly to your game instead of through your program.

EDIT:

Actually, there is a way to do this. If you go into press ctrl+alt+del and select task manager (windows), you should be able to see the name of your python program. Now, right click on that and select Go to details. This should change the format completely. Without clicking anything else, right click on the highlighted thing (should be highlighted in blue) and hover over Set priority. This should bring up a dropdown menu, where you can either set as High or Realtime.

Another way to make sure to do this is to set your game's priority to Below Normal using the same steps, but click on the game instead.

Body:
I ran this PyHook sample code:

    import pythoncom, pyHook

def OnKeyboardEvent(event):
    print 'MessageName:',event.MessageName
    print 'Message:',event.Message
    print 'Time:',event.Time
    print 'Window:',event.Window
    print 'WindowName:',event.WindowName
    print 'Ascii:', event.Ascii, chr(event.Ascii)
    print 'Key:', event.Key
    print 'KeyID:', event.KeyID
    print 'ScanCode:', event.ScanCode
    print 'Extended:', event.Extended
    print 'Injected:', event.Injected
    print 'Alt', event.Alt
    print 'Transition', event.Transition
    print '---'

# return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

To try it out and it works in most windows but when I try it inside a game window it acts like I'm not pressing anything.

Is there a way to listen to keypresses from a specific process? what should I do?


问:
How to get the value of one of the key-value pairs of JSON in JavaScript？
I want to get the value of gid in JavaScript

```<code>alert(JSON.stringify(data); √
alert(JSON.stringify(data['responseJSON']['gid'])); ×
</code>```

I tried to use it like this but I got an error.

I found a lot of answers but still can't get the value I need.

{
  "form": {},
  "files": [{}],
  "filenames": ["timg.jpg"],
  "filescount": 1,
  "extra": {},
  "response": {
    "success": true,
    "msg": "image url after upload",
    "gid": 81
  },
  "reader": {},
  "jqXHR": {
    "readyState": 4,
    "responseText": "{\"success\":true,\"msg\":\"image url after upload\",\"gid\":81}",
    "responseJSON": {
      "success": true,
      "msg": "image url after upload",
      "gid": 81
    },
    "status": 200,
    "statusText": "OK"
  }
}

alert(JSON.stringify(data));
```

I want to get the value of gid (81)，but it is not use.

答:
ouhre! Welcome to Stackoverflow. Here is a way to get the value of 'gid'.

```<code>let json = {
  form: {},
  files: [{}],
  filenames: ["timg.jpg"],
  filescount: 1,
  extra: {},
  response: { success: true, msg: "image url after upload", gid: 81 },
  reader: {},
  jqXHR: {
    readyState: 4,
    responseText: '{"success":true,"msg":"image url after upload","gid":81}',
    responseJSON: { success: true, msg: "image url after upload", gid: 81 },
    status: 200,
    statusText: "OK"
  }
};

alert(json.jqXHR.responseJSON.gid)
</code>```

You can check this out live at this Codesandbox, here, or read more about handling JSON and Objects in Javscript, here and here!

Body:
I want to get the value of gid in JavaScript

alert(JSON.stringify(data); √
alert(JSON.stringify(data['responseJSON']['gid'])); ×

I tried to use it like this but I got an error.

I found a lot of answers but still can't get the value I need.

{
  "form": {},
  "files": [{}],
  "filenames": ["timg.jpg"],
  "filescount": 1,
  "extra": {},
  "response": {
    "success": true,
    "msg": "image url after upload",
    "gid": 81
  },
  "reader": {},
  "jqXHR": {
    "readyState": 4,
    "responseText": "{\"success\":true,\"msg\":\"image url after upload\",\"gid\":81}",
    "responseJSON": {
      "success": true,
      "msg": "image url after upload",
      "gid": 81
    },
    "status": 200,
    "statusText": "OK"
  }
}

alert(JSON.stringify(data));

I want to get the value of gid (81)，but it is not use.

Body:
ouhre! Welcome to Stackoverflow. Here is a way to get the value of 'gid'.

let json = {
  form: {},
  files: [{}],
  filenames: ["timg.jpg"],
  filescount: 1,
  extra: {},
  response: { success: true, msg: "image url after upload", gid: 81 },
  reader: {},
  jqXHR: {
    readyState: 4,
    responseText: '{"success":true,"msg":"image url after upload","gid":81}',
    responseJSON: { success: true, msg: "image url after upload", gid: 81 },
    status: 200,
    statusText: "OK"
  }
};

alert(json.jqXHR.responseJSON.gid)

You can check this out live at this Codesandbox, here, or read more about handling JSON and Objects in Javscript, here and here!