问:
Is there a way to define implicit operator in C# that defines cast from Expression to selected class
I'm trying to implement class that defines filter, to make it more explicit when it will be passed as argument to methods in my repository class (EF).

And I have a problem with definition of implicit operator from Expression to my class.
Is it possible to make implementation for syntax near fd4 variable?

```<code>public class FilterDefinition<TEntity>
    where TEntity : class
{
    public FilterDefinition() { }

    public FilterDefinition(Expression<Func<TEntity, bool>> filter)
    {
        this.Filter = filter;
    }

    public virtual Expression<Func<TEntity, bool>> Filter { get; set; }

    public static implicit operator FilterDefinition<TEntity>(Expression<Func<TEntity, bool>> filter) => new FilterDefinition<TEntity>(filter);
}

public class SomeEntity
{
    public bool SomeBool { get; set; }
}

class Program
{
    static void Main()
    {
        FilterDefinition<SomeEntity> fd1 = new FilterDefinition<SomeEntity>(x => x.SomeBool);
        FilterDefinition<SomeEntity> fd2 = new FilterDefinition<SomeEntity> { Filter = x => x.SomeBool };
        FilterDefinition<SomeEntity> fd3 = (Expression<Func<SomeEntity, bool>>)(x => x.SomeBool);
        //FilterDefinition<SomeEntity> fd4 = x => x.SomeBool;

        Console.ReadKey();
    }
}
</code>```

The purpose of FilterDefinition class was to pass as argument to generic repository of queries. And using inheritance define commonly used filters.

```<code>public class Repository<TEntity> : IRepository<TEntity>
    where TEntity : class
{
    private readonly DbSet<TEntity> dbSet;

    public Repository(DbContext context)
    {
        this.dbSet = context.Set<TEntity>();
    }

    public async Task<IEnumerable<TEntity>> GetAsync(
        FilterDefinition<TEntity> filter = null,
        OrderDefinition<TEntity> order = null,
        PagingDefinition paging = null)
    {
        return await new QueryBuilder<TEntity>(this.dbSet)
            .ApplyFilter(filter)
            .ApplyOrder(order)
            .ApplyPaging(paging)
            .ToQuery()
            .ToListAsync();
    }
</code>```

答: The short answer would be "not in this scenario", because syntactically, in fd4 you're not actually casting from an Expression[...] to your type. The compiler doesn't know that the lambda represents an Expression[...] until it knows what it is trying to do with the value; a lambda (x => x.SomeBool) can be interpreted as a wide range of both expression-tree types and delegate types (for anonymous methods), and the compiler here would not understand that you mean "treat the lambda as an Expression<Func<SomeEntity, bool>>, then use the implicit conversion operator to change the expression to a FilterDefinition". It simply can't (and doesn't) make that leap. You can get close, as with your fd3 example, but... a large part of me is wondering what FilterDefinition actually does here, because to an outside observer it doesn't really seem to add anything over the raw expression tree.

Body:
I'm trying to implement class that defines filter, to make it more explicit when it will be passed as argument to methods in my repository class (EF).

And I have a problem with definition of implicit operator from Expression to my class.
Is it possible to make implementation for syntax near fd4 variable?

public class FilterDefinition<TEntity>
    where TEntity : class
{
    public FilterDefinition() { }

    public FilterDefinition(Expression<Func<TEntity, bool>> filter)
    {
        this.Filter = filter;
    }

    public virtual Expression<Func<TEntity, bool>> Filter { get; set; }

    public static implicit operator FilterDefinition<TEntity>(Expression<Func<TEntity, bool>> filter) => new FilterDefinition<TEntity>(filter);
}

public class SomeEntity
{
    public bool SomeBool { get; set; }
}

class Program
{
    static void Main()
    {
        FilterDefinition<SomeEntity> fd1 = new FilterDefinition<SomeEntity>(x => x.SomeBool);
        FilterDefinition<SomeEntity> fd2 = new FilterDefinition<SomeEntity> { Filter = x => x.SomeBool };
        FilterDefinition<SomeEntity> fd3 = (Expression<Func<SomeEntity, bool>>)(x => x.SomeBool);
        //FilterDefinition<SomeEntity> fd4 = x => x.SomeBool;

        Console.ReadKey();
    }
}

The purpose of FilterDefinition class was to pass as argument to generic repository of queries. And using inheritance define commonly used filters.

public class Repository<TEntity> : IRepository<TEntity>
    where TEntity : class
{
    private readonly DbSet<TEntity> dbSet;

    public Repository(DbContext context)
    {
        this.dbSet = context.Set<TEntity>();
    }

    public async Task<IEnumerable<TEntity>> GetAsync(
        FilterDefinition<TEntity> filter = null,
        OrderDefinition<TEntity> order = null,
        PagingDefinition paging = null)
    {
        return await new QueryBuilder<TEntity>(this.dbSet)
            .ApplyFilter(filter)
            .ApplyOrder(order)
            .ApplyPaging(paging)
            .ToQuery()
            .ToListAsync();
    }


来源: stackexchange

问:
Trying to get the duplicate serial numbers repeating more than three times from this list using perl or awk command
For example: From the below example I was trying to get the duplicated serial numbers which only repeats more than three times.

```<code>Time     serial no's     oui   product class
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
22:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
23:07:51 G1A114080901301|D4A928|FiOS-Gen4
23:10:36 G1A114080901301|D4A928|FiOS-Gen4
20:11:51 G1A114080901301|D4A928|FiOS-Gen4
</code>```

So if I return the output it should be something like this:

Only duplicated serial no's

output should be:

```<code>G1A114080901301|D4A928|FiOS-Gen4
G1A114071803436|D4A928|FiOS-Gen4
</code>```

(as this serial no's are only repeating more than two times)

Commands I used:

```<code>sort  sed2file.csv | uniq -id > sortedfile.csv
perl -ne 'print if $a{$_}++' filename
</code>```

答:
You can do it trivially with awk, e.g.

```<code>awk '{seen[$2]++; if(seen[$2]==3) print $2}' serials.txt
</code>```

Output:

```<code>G1A114071803436|D4A928|FiOS-Gen4
G1A114080901301|D4A928|FiOS-Gen4
</code>```

Above you keep the seen array indexed by the second field holding the number of times the serial|oui|product class is seen. When it equals 3, just output that set of values (it will not print before the count equals 3 and ignore occurrences afterwards due to the == used)

ContentLicense: CC BY-SA 4.0

Body:
For example: From the below example I was trying to get the duplicated serial numbers which only repeats more than three times.

Time     serial no's     oui   product class
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
22:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
23:07:51 G1A114080901301|D4A928|FiOS-Gen4
23:10:36 G1A114080901301|D4A928|FiOS-Gen4
20:11:51 G1A114080901301|D4A928|FiOS-Gen4

So if I return the output it should be something like this:

Only duplicated serial no's

output should be:

G1A114080901301|D4A928|FiOS-Gen4
G1A114071803436|D4A928|FiOS-Gen4

(as this serial no's are only repeating more than two times)

Commands I used:

sort  sed2file.csv | uniq -id > sortedfile.csv
perl -ne 'print if $a{$_}++' filename

Body:
You can do it trivially with awk, e.g.

awk '{seen[$2]++; if(seen[$2]==3) print $2}' serials.txt

Output:

G1A114071803436|D4A928|FiOS-Gen4
G1A114080901301|D4A928|FiOS-Gen4

Above you keep the seen array indexed by the second field holding the number of times the serial|oui|product class is seen. When it equals 3, just output that set of values (it will not print before the count equals 3 and ignore occurrences afterwards due to the == used)


问:
image uploading works properly with all devices except iphone
php (codeigniter): image uploading working properly in all devices but on working on iphone devices

Only iphone-captuered images are getting uploaded, but not working for non-captured/other images

My Code Snippet:
(too lengthy code, I am just some part of that code)

```<code><?php
    .....
    .....
    $this->load->library("upload");
    $this->upload->initialize($this->set_upload_options());

    if($this->upload->do_upload()){

          $ppimagedata = $this -> upload -> data();
          $ppnewimagename = $ppimagedata["file_name"];

          $this -> load -> library("image_lib");
          $config['image_library']   = 'gd2';
          $config['source_image']    = $ppimagedata["full_path"];
          $config['create_thumb']    = TRUE;
          $config['maintain_ratio']  = FALSE;

          $config['new_image']    = './uploads/Property/300X300/';
          $config['width']       = 300;
          $config['height']       = 300;
          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();
    }

    private function set_upload_options() {
        $config = array ();
        $config ['upload_path'] = './uploads/Property';
        $config ['allowed_types'] = 'gif|jpg|png';
        return $config;
    }
    ....
    ....
?>
</code>```

above php (codeigniter) script working properly for all devices but not working for iphone

Please suggest me the changes or idea to resolve this issue.

答: In windows or android..  "jpg" auto-consider as "jpeg". But for iPhone, you have to mention it separately in "allow-types"</p>

Body:
php (codeigniter): image uploading working properly in all devices but on working on iphone devices

Only iphone-captuered images are getting uploaded, but not working for non-captured/other images

My Code Snippet:
(too lengthy code, I am just some part of that code)

<?php
    .....
    .....
    $this->load->library("upload");
    $this->upload->initialize($this->set_upload_options());

    if($this->upload->do_upload()){

          $ppimagedata = $this -> upload -> data();
          $ppnewimagename = $ppimagedata["file_name"];

          $this -> load -> library("image_lib");
          $config['image_library']   = 'gd2';
          $config['source_image']    = $ppimagedata["full_path"];
          $config['create_thumb']    = TRUE;
          $config['maintain_ratio']  = FALSE;

          $config['new_image']    = './uploads/Property/300X300/';
          $config['width']       = 300;
          $config['height']       = 300;
          $this -> image_lib -> initialize($config);
          $this -> image_lib -> resize();
    }

    private function set_upload_options() {
        $config = array ();
        $config ['upload_path'] = './uploads/Property';
        $config ['allowed_types'] = 'gif|jpg|png';
        return $config;
    }
    ....
    ....
?>

above php (codeigniter) script working properly for all devices but not working for iphone

Please suggest me the changes or idea to resolve this issue.


问:
Remove duplicates key from list of dictionaries python
I am trying to remove the duplicates from following list:

```<code>distinct_cur = [
    {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 195, 'st': 0.0, 'htc': 2, '_id': ObjectId('58e86a550a0aeff4e14ca6bb'), 'ftc': 0},
    {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 454, 'st': 0.8, 'htc': 1, '_id': ObjectId('58e8d03958ae6d179c2b4413'), 'ftc': 1},
    {'rtc': 0, 'vf': 2, 'mtc': 1, 'doc': 'test', 'foc': 45, 'st': 0.8, 'htc': 12, '_id': ObjectId('58e8d03958ae6d180c2b4446'), 'ftc': 0}
]
</code>```

Of dictionaries based on condition that if 'doc' key value text is same then one of the dictionary should be removed. I have tried the following solution:

```<code>distinct_cur = [dict(y) for y in set(tuple(x.items()) for x in cur)]
</code>```

But duplicates are still present in the final list.

Below is the desired output as in 1st and 2nd distinct_cur text of key 'doc' value is same (good job):

```<code>[
    {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 195, 'st': 0.0, 'htc': 2, '_id': ObjectId('58e86a550a0aeff4e14ca6bb'), 'ftc': 0},
    {'rtc': 0, 'vf': 2, 'mtc': 1, 'doc': 'test', 'foc': 45, 'st': 0.8, 'htc': 12, '_id': ObjectId('58e8d03958ae6d180c2b4446'), 'ftc': 0}
]
</code>```

答:
One liner to deduplicate the list of dictionaries distinct_cur on the primary_key of doc

```<code>[i for n, i in enumerate(distinct_cur) if i.get('doc') not in [y.get('doc') for y in distinct_cur[n + 1:]]]
</code>```

Body:
I am trying to remove the duplicates from following list:

distinct_cur = [
    {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 195, 'st': 0.0, 'htc': 2, '_id': ObjectId('58e86a550a0aeff4e14ca6bb'), 'ftc': 0},
    {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 454, 'st': 0.8, 'htc': 1, '_id': ObjectId('58e8d03958ae6d179c2b4413'), 'ftc': 1},
    {'rtc': 0, 'vf': 2, 'mtc': 1, 'doc': 'test', 'foc': 45, 'st': 0.8, 'htc': 12, '_id': ObjectId('58e8d03958ae6d180c2b4446'), 'ftc': 0}
]

Of dictionaries based on condition that if 'doc' key value text is same then one of the dictionary should be removed. I have tried the following solution:

distinct_cur = [dict(y) for y in set(tuple(x.items()) for x in cur)]

But duplicates are still present in the final list.

Below is the desired output as in 1st and 2nd distinct_cur text of key 'doc' value is same (good job):

[
    {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 195, 'st': 0.0, 'htc': 2, '_id': ObjectId('58e86a550a0aeff4e14ca6bb'), 'ftc': 0},
    {'rtc': 0, 'vf': 2, 'mtc': 1, 'doc': 'test', 'foc': 45, 'st': 0.8, 'htc': 12, '_id': ObjectId('58e8d03958ae6d180c2b4446'), 'ftc': 0}
]

Body:
One liner to deduplicate the list of dictionaries distinct_cur on the primary_key of doc

[i for n, i in enumerate(distinct_cur) if i.get('doc') not in [y.get('doc') for y in distinct_cur[n + 1:]]]


问:
Combine image channels of two images using oiiotool
There is command in the oiiotool to swap the channels of a image by using the --ch command like so:

```<code>oiiotool rgba.tif --ch R=B,G,B=R,A -o bgra.tif
</code>```

What Im asking is if there is an option to load two images to the stack and add lets say the Red channel from Image A to the green channel of image B.

答:
In case somebody needs the answer here it is:

```<code>oiiotool A.exr --ch R  B.exr --ch B  --chappend  A.exr --ch G  --chappend  --chnames R,G,B  -o mix.exr
</code>```

To break down what that means,

```<code>* read A, take just its R channel
* read B, take just its G channel
* Append channels of the the top two images, yielding A.r,B.g on the top of the stack
* read A again, take just its B channel
* Append the channels of the top two images, now you have A.r,B.g,A.b
* Force new channel names R,G,B just in case they carry their old names or got confused
* Output to mix.exr
</code>```

Body:
There is command in the oiiotool to swap the channels of a image by using the --ch command like so:

oiiotool rgba.tif --ch R=B,G,B=R,A -o bgra.tif

What Im asking is if there is an option to load two images to the stack and add lets say the Red channel from Image A to the green channel of image B.

Body:
In case somebody needs the answer here it is:

oiiotool A.exr --ch R  B.exr --ch B  --chappend  A.exr --ch G  --chappend  --chnames R,G,B  -o mix.exr

To break down what that means,

* read A, take just its R channel
* read B, take just its G channel
* Append channels of the the top two images, yielding A.r,B.g on the top of the stack
* read A again, take just its B channel
* Append the channels of the top two images, now you have A.r,B.g,A.b
* Force new channel names R,G,B just in case they carry their old names or got confused
* Output to mix.exr


问:
MongoDB query with multiple variations in $or query where at least x statements must match
The given data:

```<code>{_id: 1, group: {value1: true, value2: true, value3: false, value4: true, value5: false, value6: true}}
{_id: 2, group: {value1: true, value2: true, value3: false, value4: true, value5: false, value6: true}}
{_id: 3, group: {value1: false, value2: false, value3: true, value4: false, value5: false, value6: true}}
</code>```

Now we want to query all documents where the following object matches

```<code> $or: [
    {value1: true},
    {value2: true},
    {value3: true},
    {value4: true}
  ]
</code>```

but with the option that at least e.g. 3 (passed parameter - minMatchCount) of the 6 statements have to match. The other way around: 1 statement can fail.

Is there a solution without building a huge $and - $or query with each possible variation ?

Example output:

```<code>[
 {_id:1, ...},
 {_id:2, ...}
]
</code>```

答:
You could use $expr, $sum and $cond to count the matches, and $gte to require a minimum:

```<code>db.collection.find({
  $expr: {
    $gte: [
      {$sum: [
          { $cond: [ { $eq: [ "$group.value1", true ] }, 1, 0 ] },
          { $cond: [ { $eq: [ "$group.value2", true ] }, 1, 0 ] },
          { $cond: [ { $eq: [ "$group.value3", true ] }, 1, 0 ] },
          { $cond: [ { $eq: [ "$group.value4", true ] }, 1, 0 ] },
          ]},
      3 ] } })
</code>```

Body:
The given data:

{_id: 1, group: {value1: true, value2: true, value3: false, value4: true, value5: false, value6: true}}
{_id: 2, group: {value1: true, value2: true, value3: false, value4: true, value5: false, value6: true}}
{_id: 3, group: {value1: false, value2: false, value3: true, value4: false, value5: false, value6: true}}

Now we want to query all documents where the following object matches

 $or: [
    {value1: true},
    {value2: true},
    {value3: true},
    {value4: true}
  ]

but with the option that at least e.g. 3 (passed parameter - minMatchCount) of the 6 statements have to match. The other way around: 1 statement can fail.

Is there a solution without building a huge $and - $or query with each possible variation ?

Example output:

[
 {_id:1, ...},
 {_id:2, ...}
]

Body:
You could use $expr, $sum and $cond to count the matches, and $gte to require a minimum:

db.collection.find({
  $expr: {
    $gte: [
      {$sum: [
          { $cond: [ { $eq: [ "$group.value1", true ] }, 1, 0 ] },
          { $cond: [ { $eq: [ "$group.value2", true ] }, 1, 0 ] },
          { $cond: [ { $eq: [ "$group.value3", true ] }, 1, 0 ] },
          { $cond: [ { $eq: [ "$group.value4", true ] }, 1, 0 ] },
          ]},
      3 ] } })


问:
Keras CNN issue
I am trying to write a Siamese Network, using Negative Sampling, Code with just 20 examples (positive & Negative included)
Each example include 2 images (x1,x2) and an output indicating if the images are same or not

```<code>image1           image1        1
image1           image2        0
</code>```

For this i am interested in getting just the last layer, which is Dense() layer in Keras, both X1 and X2 seperately.

The shape of X1 is 20,28,28,1 and X2 is 20,28,28,1
Both have type as numpy.ndarray

But when i apply CNN model, it gives the following error.

"TypeError: The added layer must be an instance of class Layer. Found: (28, 28, 1)

See the python code below

```<code>model = Sequential([(Image1[0].shape),
            Conv2D(16,kernel_size=(3,3),strides=[1,1],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv1'),
            Activation('relu'),
            MaxPool2D(pool_size=(2, 2)),
            Conv2D(32,kernel_size=(3,3),strides=[2,2],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv2'),
            Activation('relu'),
            Conv2D(64,kernel_size=(3,3),strides=[2,2],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv3'),
            Activation('relu'),
            MaxPool2D(pool_size=(2, 2)),
            Flatten(),
            Dense(20)
          ])

</code>```

Can someone help me on how to fix this error ?

Thanks
Sachin

答:
The first model layer should specify the shape of the images that you are going to feed. In your case you are adding the image shape as a layer.

Take a look on how to do it:

```<code>IM_WIDTH = 128
IM_HEIGHT = 128

model = Sequential(
Conv2D(16, input_size=(IM_HEIGHT, IM_WIDTH, 3), kernel_size=(3,3),strides=[1,1],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv1'),
            Activation('relu'),
            MaxPool2D(pool_size=(2, 2)),
            Conv2D(32,kernel_size=(3,3),strides=[2,2],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv2'),
            Activation('relu'),
            Conv2D(64,kernel_size=(3,3),strides=[2,2],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv3'),
            Activation('relu'),
            MaxPool2D(pool_size=(2, 2)),
            Flatten(),
            Dense(20)
          ])
</code>```

Title: Keras CNN issue

Body:
I am trying to write a Siamese Network, using Negative Sampling, Code with just 20 examples (positive & Negative included)
Each example include 2 images (x1,x2) and an output indicating if the images are same or not

image1           image1        1
image1           image2        0

For this i am interested in getting just the last layer, which is Dense() layer in Keras, both X1 and X2 seperately.

The shape of X1 is 20,28,28,1 and X2 is 20,28,28,1
Both have type as numpy.ndarray

But when i apply CNN model, it gives the following error.

"TypeError: The added layer must be an instance of class Layer. Found: (28, 28, 1)

See the python code below

model = Sequential([(Image1[0].shape),
            Conv2D(16,kernel_size=(3,3),strides=[1,1],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv1'),
            Activation('relu'),
            MaxPool2D(pool_size=(2, 2)),
            Conv2D(32,kernel_size=(3,3),strides=[2,2],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv2'),
            Activation('relu'),
            Conv2D(64,kernel_size=(3,3),strides=[2,2],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv3'),
            Activation('relu'),
            MaxPool2D(pool_size=(2, 2)),
            Flatten(),
            Dense(20)
          ])

Can someone help me on how to fix this error ?

Thanks
Sachin

Body:
The first model layer should specify the shape of the images that you are going to feed. In your case you are adding the image shape as a layer.

Take a look on how to do it:

IM_WIDTH = 128
IM_HEIGHT = 128

model = Sequential(
Conv2D(16, input_size=(IM_HEIGHT, IM_WIDTH, 3), kernel_size=(3,3),strides=[1,1],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv1'),
            Activation('relu'),
            MaxPool2D(pool_size=(2, 2)),
            Conv2D(32,kernel_size=(3,3),strides=[2,2],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv2'),
            Activation('relu'),
            Conv2D(64,kernel_size=(3,3),strides=[2,2],padding='same',kernel_initializer=keras.initializers.glorot_uniform(),name='conv3'),
            Activation('relu'),
            MaxPool2D(pool_size=(2, 2)),
            Flatten(),
            Dense(20)
          ])


问:
Page Redirection
To help better explain my Question, here is what i have:

I am using a Precoded service, on it i have access to the Template HTML Files Only.

The URL to the Login page is : DynamicPage.aspx?Site=Mysite&WebCode=LoginRequired

The Main site URL would look like : DynamicPage.aspx?Site=Mysite&WebCode= or DynamicPage.aspx?Site=Mysite

What i need is a JavaScript I could put into the main header template file that would view "WebCode" And depending on whats entered redirect to a certain page.

I got from "Sitifensys" a code

Sitifensys

if (window.location.href!="foo.bar/login.php") window.location.href="login.php";

The problem with this code is even when i go to the main page it still redirects me to login.php which i do not want it to. I need this code to Read the "WebCode" If it is "LoginRequired" Redirect to "Login.php" else if redirect to "Test.php"

Hope this explanation is a bit better.

答:
Try </p>

```
window.location.href = "http://www.something.com/"
```

ContentLicense: CC BY-SA 3.0

Title: Page Redirection

Body:
Try

window.location.href = "http://www.something.com/"


问:
Why: appengine to firebase Authentication fails with error referer forbidden
I have this web app project which I deploy on a google cloud appengine.

```<code>gcloud app deploy
</code>```

The appengine is basically just a webserver serving static files. But I had to use the appengine for prerendring the website for SEO.

In the webapp, I use the firebase authentication API.
https://www.gstatic.com/firebasejs/7.8.0/firebase-auth.js

In firebase console, I activated the anonymous authentication.
preview of firebase auth providers

When I deploy a new version of my static content on the appengine, I create a new version named "stag" only to preview and test everything before deploying to production. I can then preview my work on the version specific url which is something like this:

```<code>https://stag-dot-frb-proj1.appspot.com/
</code>```

frb-proj1: is my firebase project id.

When I preview my work on the url: https://stag-dot-frb-proj1.appspot.com/
I got the following error:

```<code>{
  "error": {
    "code": 403,
    "message": "Requests from referer https://stag-dot-frb-proj1.appspot.com/ are blocked.",
    "errors": [
      {
        "message": "Requests from referer https://stag-dot-frb-proj1.appspot.com/ are blocked.",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}
</code>```

I spotted the error in the chrome dev tools on the network tab. It happens when the app tries to access the following url:

```<code>https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=AIza....CcpT0
</code>```

I assume this api call if for creating a new anonymous user on the firebase auth api.

All the used domains are authorized in the firebase console as expected.

Authorized DOMAINS

frb-proj1.firebaseapp.com

frb-proj1.web.app

stag-dot-frb-proj1.appspot.com

frb-proj1.appspot.com

Tried solution

I tried to follow this example https://cloud.google.com/appengine/docs/standard/python/authenticating-users-firebase-appengine

And setup the environment variable FIREBASE_PROJECT_ID in my app.yaml for the appengine

QUESTION

Any idea what is wrong ?

答:
Considering this error, it seems that this problem is related to your API Key. As per these other similar cases - that you can access in the below links - it seems that the API Key configured doesn't have all the needed permissions.

I would recommend you to take a look at the below cases and give it a try on the solutions informed there - all of them informed that it solved their problems.

Requests for referrer are blocked when trying to sign in anonymously to Firebase

firebaseui Internal error: {"error":{"code":403,"message":"Requests from referer  are blocked.","errors":{"message":"Requests from referer

App hosted on firebase does not have access to firebase authentication? PERMISSION_DENIED

Let me know if the information helped you!

Body:
I have this web app project which I deploy on a google cloud appengine.

gcloud app deploy

The appengine is basically just a webserver serving static files. But I had to use the appengine for prerendring the website for SEO.

In the webapp, I use the firebase authentication API.
https://www.gstatic.com/firebasejs/7.8.0/firebase-auth.js

In firebase console, I activated the anonymous authentication.
preview of firebase auth providers

When I deploy a new version of my static content on the appengine, I create a new version named "stag" only to preview and test everything before deploying to production. I can then preview my work on the version specific url which is something like this:

https://stag-dot-frb-proj1.appspot.com/

frb-proj1: is my firebase project id.

When I preview my work on the url: https://stag-dot-frb-proj1.appspot.com/
I got the following error:

{
  "error": {
    "code": 403,
    "message": "Requests from referer https://stag-dot-frb-proj1.appspot.com/ are blocked.",
    "errors": [
      {
        "message": "Requests from referer https://stag-dot-frb-proj1.appspot.com/ are blocked.",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

I spotted the error in the chrome dev tools on the network tab. It happens when the app tries to access the following url:

https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=AIza....CcpT0

I assume this api call if for creating a new anonymous user on the firebase auth api.

All the used domains are authorized in the firebase console as expected.

Authorized DOMAINS

frb-proj1.firebaseapp.com

frb-proj1.web.app

stag-dot-frb-proj1.appspot.com

frb-proj1.appspot.com

Tried solution

I tried to follow this example https://cloud.google.com/appengine/docs/standard/python/authenticating-users-firebase-appengine

And setup the environment variable FIREBASE_PROJECT_ID in my app.yaml for the appengine

QUESTION

Any idea what is wrong ?


问:
vue - Pass index to method onLoad
Is there a way to pass a v-for index to a method on page load? The common way I pass index is using @change event with a select drop down, but this time I'm creating a report without a select drop down.

```<code><div v-for="(item, index) in items">
    <span>{{item.name}}</item>
    @onLoad='getData(index)'
</div>

methods: {
    getData(index) {
      axios.get('api', {
        params: { id: this.items[index].item_id}
      })
      .then({response=>})
    }
  }
</code>```

答:
Use the mounted() component's function to populate items on the component load.

```<code>mounted()
{

    this.items.forEach((item, index) => {
        axios.get('api', {
            params: {id: this.items[index].item_id}
        })
            .then(response => {

                item.updated_property = response.data;
                Vue.set(this.items, index, item);
     });

    });
}
</code>```

Title: vue - Pass index to method onLoad

Body:
Is there a way to pass a v-for index to a method on page load? The common way I pass index is using @change event with a select drop down, but this time I'm creating a report without a select drop down.

    {{item.name}}</item>
    @onLoad='getData(index)'

methods: {
    getData(index) {
      axios.get('api', {
        params: { id: this.items[index].item_id}
      })
      .then({response=>})
    }
  }

Body:
Use the mounted() component's function to populate items on the component load.

mounted()
{

    this.items.forEach((item, index) => {
        axios.get('api', {
            params: {id: this.items[index].item_id}
        })
            .then(response => {

                item.updated_property = response.data;
                Vue.set(this.items, index, item);
     });

    });
}


问:
How to create new DataFrame with dict
I had one dict, like:

```<code>cMap = {"k1" : "v1", "k2" : "v1", "k3" : "v2", "k4" : "v2"}
</code>```

and one DataFrame A, like:

```<code>+---+
|key|
+----
| k1|
| k2|
| k3|
| k4|
+---+
</code>```

to create the DataFame above with code:

```<code>data = [('k1'),
    ('k2'),
    ('k3'),
    ('k4')]
A = spark.createDataFrame(data, ['key'])
</code>```

I want to get the new DataFrame, like:

```<code>+---+----------+----------+
|key|   v1     |    v2    |
+---+----------+----------+
| k1|true      |false     |
| k2|true      |false     |
| k3|false     |true      |
| k4|false     |true      |
+---+----------+----------+
</code>```

I wish to get some suggestions, thanks!

答:
```<code>from pyspark import SparkContext,SparkConf

from pyspark.sql import SQLContext
sc = SparkContext()
spark = SQLContext(sc)
val_dict = {
            'key1':val1,
            'key2':val2,
            'key3':val3
            }

rdd = sc.parallelize([val_dict])

bu_zdf = spark.read.json(rdd)
</code>```

Title: How to create new DataFrame with dict

Body:
I had one dict, like:

cMap = {"k1" : "v1", "k2" : "v1", "k3" : "v2", "k4" : "v2"}

and one DataFrame A, like:

+---+
|key|
+----
| k1|
| k2|
| k3|
| k4|
+---+

to create the DataFame above with code:

data = [('k1'),
    ('k2'),
    ('k3'),
    ('k4')]
A = spark.createDataFrame(data, ['key'])

I want to get the new DataFrame, like:

+---+----------+----------+
|key|   v1     |    v2    |
+---+----------+----------+
| k1|true      |false     |
| k2|true      |false     |
| k3|false     |true      |
| k4|false     |true      |
+---+----------+----------+

I wish to get some suggestions, thanks!


问:
CLang-Tidy warning that rand() has limited randomness
```<code>toZero = rand() % N;
</code>```

This line of code is giving me Clang-Tidy: rand() has limited randomness. Why is this warning coming up? How can I fix it?

答:
Would it be possible to send me a code snippet where Clang-Tidy doesn't warn me while using rand()?

If you are sticking with rand(), you must disable the warning:

```<code>toZero = rand() % N; // NOLINT(cert-msc30-c, cert-msc50-cpp)
</code>```

A better option would be to use the <random> library and functions instead.

One example:

```<code>#include <iostream>
#include <random>
#include <type_traits>

// A function to return a seeded random number generator.
inline std::mt19937& generator() {
    // the generator will only be seeded once (per thread) since it's static
    static thread_local std::mt19937 gen(std::random_device{}());
    return gen;
}

// A function to generate integers in the range [min, max]
template<typename T, std::enable_if_t<std::is_integral_v<T>>* = nullptr>
T my_rand(T min, T max) {
    std::uniform_int_distribution<T> dist(min, max);
    return dist(generator());
}

// A function to generate floats in the range [min, max)
template<typename T, std::enable_if_t<std::is_floating_point_v<T>>* = nullptr>
T my_rand(T min, T max) {
    std::uniform_real_distribution<T> dist(min, max);
    return dist(generator());
}

int main() {
    unsigned N = 100;
    std::cout << my_rand(0U, N - 1) << '\n'; // unsigned int:s instead of rand() % N
    std::cout << my_rand(-5., 5.) << '\n';   // double's
}
</code>```

Body:
toZero = rand() % N;

This line of code is giving me Clang-Tidy: rand() has limited randomness. Why is this warning coming up? How can I fix it?

Body:
Would it be possible to send me a code snippet where Clang-Tidy doesn't warn me while using rand()?

If you are sticking with rand(), you must disable the warning:

toZero = rand() % N; // NOLINT(cert-msc30-c, cert-msc50-cpp)

A better option would be to use the <random> library and functions instead.

One example:

#include <iostream>
#include <random>
#include <type_traits>

// A function to return a seeded random number generator.
inline std::mt19937& generator() {
    // the generator will only be seeded once (per thread) since it's static
    static thread_local std::mt19937 gen(std::random_device{}());
    return gen;
}

// A function to generate integers in the range [min, max]
template<typename T, std::enable_if_t<std::is_integral_v<T>>* = nullptr>
T my_rand(T min, T max) {
    std::uniform_int_distribution<T> dist(min, max);
    return dist(generator());
}

// A function to generate floats in the range [min, max)
template<typename T, std::enable_if_t<std::is_floating_point_v<T>>* = nullptr>
T my_rand(T min, T max) {
    std::uniform_real_distribution<T> dist(min, max);
    return dist(generator());
}

int main() {
    unsigned N = 100;
    std::cout << my_rand(0U, N - 1) << '\n'; // unsigned int:s instead of rand() % N
    std::cout << my_rand(-5., 5.) << '\n';   // double's
}


问:
How to update data in Laravel controller?
I am trying to update my template details in the controller. But currently, my code is not working. It is not updating the fields. Anyhow if I add $template->save(). It saves the updated record as a new record. How to make my current code work? Why I am facing this situation? Please, someone, explain to me and correct my code as still, I am learning Laravel. Thanks in advance.

update function in TemplateController

```<code>public function update(Request $request, $id)
    {
        if(! lara_club_has_permission('edit-template') ){
            return view('403');
        }

        $this->validate($request, [
                'title'=>'required',
                'start_date'=> 'required',
                'end_date'=>'required',
                'template_content'=>'required',
            ]
        );

        //check status response
        if(isset($request->status)&&$request->status=='on'){
            $status='1';
        }else{
            $status="0";
        }

        $template=new Template();

        $template->title=$request->title;
        $template->start_date=convert_to_sql_date_format($request->start_date);
        $template->end_date=convert_to_sql_date_format($request->end_date);
        $template->is_active=$status;
        $template->template_content=$request->template_content;

        $input = $request->all();

        $template->update($input);

        $name = $input['title'];

        return redirect()->route('templates.index')->with('success', 'Template <b>'. $name.'</b> Updated!');
    }
</code>```

答:
In my case I specify the table name in the method name, like this.</p>

```<code>public function update(Request $request, Template $id)
{
    $id->title=$request->title;
    $id->start_date=convert_to_sql_date_format($request->start_date);
    $id->end_date=convert_to_sql_date_format($request->end_date);
    $id->is_active=$status;
    $id->template_content=$request->template_content;

    $input = $request->all();

    $id->update($input);
}
</code>```

Body:
I am trying to update my template details in the controller. But currently, my code is not working. It is not updating the fields. Anyhow if I add $template->save(). It saves the updated record as a new record. How to make my current code work? Why I am facing this situation? Please, someone, explain to me and correct my code as still, I am learning Laravel. Thanks in advance.

update function in TemplateController

public function update(Request $request, $id)
    {
        if(! lara_club_has_permission('edit-template') ){
            return view('403');
        }

        $this->validate($request, [
                'title'=>'required',
                'start_date'=> 'required',
                'end_date'=>'required',
                'template_content'=>'required',
            ]
        );

        //check status response
        if(isset($request->status)&&$request->status=='on'){
            $status='1';
        }else{
            $status="0";
        }

        $template=new Template();

        $template->title=$request->title;
        $template->start_date=convert_to_sql_date_format($request->start_date);
        $template->end_date=convert_to_sql_date_format($request->end_date);
        $template->is_active=$status;
        $template->template_content=$request->template_content;

        $input = $request->all();

        $template->update($input);

        $name = $input['title'];

        return redirect()->route('templates.index')->with('success', 'Template '. $name.' Updated!');
    }

Body:
In my case I specify the table name in the method name, like this.

public function update(Request $request, Template $id)
{
    $id->title=$request->title;
    $id->start_date=convert_to_sql_date_format($request->start_date);
    $id->end_date=convert_to_sql_date_format($request->end_date);
    $id->is_active=$status;
    $id->template_content=$request->template_content;

    $input = $request->all();

    $id->update($input);
}


问:
React - Firebase - RecaptchaVerifier is not a constructor
I am trying to create a React application that uses an "onSubmit" button to trigger handleSignUp(). However, each time I call handleSignUp() it gives this error

TypeError:
  _base__WEBPACK_IMPORTED_MODULE_2__.default.auth.RecaptchaVerifier is not a constructor

firebase initialize  -base.js

```<code>import * as firebase from "firebase/app";
import "firebase/auth";

const app = firebase.initializeApp({
  apiKey: process.env.REACT_APP_FIREBASE_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID
});

export default app;
</code>```

SignUp.js

```<code>import React, { Component } from "react";
import { withRouter } from "react-router";
import app from "./base";

class SignUp extends Component {
  componentDidMount() {
    window.recaptchaVerifier = new app.auth.RecaptchaVerifier(this.recaptcha, {
      size: "normal",
      callback: function(response) {
        console.log("reCAPTCHA solved, allow signInWithPhoneNumber.");
      },
      "expired-callback": function() {
        console.log("Response expired. Ask user to solve reCAPTCHA again.");
      }
    });
    window.recaptchaVerifier.render().then(function(widgetId) {
      window.recaptchaWidgetId = widgetId;
    });
  }

  handleSignUp = async () => {
    var phoneNumber = "+16505554567";
    var appVerifier = new app.auth.RecaptchaVerifier("recaptcha-container");

    try {
      await app
        .auth()
        .signInWithPhoneNumber(phoneNumber, appVerifier)
        .then(function(confirmationResult) {
          window.confirmationResult = confirmationResult;
        });
    } catch (error) {
      alert(error);
    }
  };
  render() {
    return (
      <div ref={ref => (this.recaptcha = ref)}>
        <h1>Sign up</h1>
        <form onSubmit={this.handleSignUp}>
          <button type="submit">Sign Up</button>
        </form>
      </div>
    );
  }
}

export default withRouter(SignUp);
</code>```

and also run  var appVerifier = new app.auth.RecaptchaVerifier("recaptcha-container"); automatically refresh the web page

答: RecaptchaVerifier constructor resides in firebase.auth. You need to pass window.recaptchaVerifier as the second argument to signInWithPhoneNumber.

Body:
I am trying to create a React application that uses an "onSubmit" button to trigger handleSignUp(). However, each time I call handleSignUp() it gives this error

TypeError:
  _base__WEBPACK_IMPORTED_MODULE_2__.default.auth.RecaptchaVerifier is not a constructor

firebase initialize  -base.js

import * as firebase from "firebase/app";
import "firebase/auth";

const app = firebase.initializeApp({
  apiKey: process.env.REACT_APP_FIREBASE_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID
});

export default app;

SignUp.js

import React, { Component } from "react";
import { withRouter } from "react-router";
import app from "./base";

class SignUp extends Component {
  componentDidMount() {
    window.recaptchaVerifier = new app.auth.RecaptchaVerifier(this.recaptcha, {
      size: "normal",
      callback: function(response) {
        console.log("reCAPTCHA solved, allow signInWithPhoneNumber.");
      },
      "expired-callback": function() {
        console.log("Response expired. Ask user to solve reCAPTCHA again.");
      }
    });
    window.recaptchaVerifier.render().then(function(widgetId) {
      window.recaptchaWidgetId = widgetId;
    });
  }

  handleSignUp = async () => {
    var phoneNumber = "+16505554567";
    var appVerifier = new app.auth.RecaptchaVerifier("recaptcha-container");

    try {
      await app
        .auth()
        .signInWithPhoneNumber(phoneNumber, appVerifier)
        .then(function(confirmationResult) {
          window.confirmationResult = confirmationResult;
        });
    } catch (error) {
      alert(error);
    }
  };
  render() {
    return (

 (this.recaptcha = ref)}>

Sign up

        <form onSubmit={this.handleSignUp}>
          <button type="submit">Sign Up</button>
        </form>

    );
  }
}

export default withRouter(SignUp);

and also run  var appVerifier = new app.auth.RecaptchaVerifier("recaptcha-container"); automatically refresh the web page


问:
What is the difference between initiating a vector as vector < class > ( value ) and vector < class > [ value ]
When my initialization is :

vector < pair < int , int > > v ( 100 );

i can't execute :

vecini[x].push_back( make_pair( y , z ) ) ;

but it works when i initiate it like:

vector < pair < int , int > > v [100];

答:
vector>v(100); initialize a vector of 100 elements where each element is of type pair with all values initialized to 0

vector>v[100]; initializes an array of 100 elements where each element is a vector of type pair


问:
Java's prepared statement with oracle merge/upsert - Missing IN or OUT Parameter at index
I am trying to perform a MERGE on single table (insert if not present else update).

my prepared statement looks like this:

```<code>merge into table USING DUAL ON (primarykey=?)
when not matched then insert (colum1,colum2,columnprimarykey,column4,column5,column6,column7,column8,column9,column10,column11,column12) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
when matched then update set column1=?,column2=?,column4=?,column5=?,column6=?,column7=?,column8=?,column9=?,column10=?,column11=?,column12=?
</code>```

But I get following error when the prepared statement is executed:

Caused by: java.sql.SQLException: Missing IN or OUT parameter at index:: 13
          at oracle.jdbc.driver.OraclePreparedStatement.processCompletedBindRow(OraclePreparedStatement.java:1937) ~[ojdbc8-19.3.0.0.jar!/:19.3.0.0.0]

following works fine when executed directly in SQL developer, it will insert a new record with 12 columns if a primarykeycolumn=99 is not found in the table. It will update rest of the 11 columns if primarykeycolumn=99 is found in the table.

```<code>merge into table USING DUAL ON (primarykey=99)
when not matched then insert
(colum1,colum2,column3/primarykey,column4,column5,column6,column7,column8,column9,column10,column11,column12) VALUES (somevalue,somevalue,99,somevalue,somevalue,somevalue,somevalue,somevalue,somevalue,somevalue,somevalue,somevalue)
when matched then update set
column1=somevalue,column2=somevalue,column4=somevalue,column5=somevalue,column6=somevalue,column7=somevalue,column8=somevalue,column9=somevalue,column10=somevalue,column11=somevalue,column12=somevalue
</code>```

Java code:

```<code>public Mono<String> createData(final Mono<Record> inputMono) {
    final String someID = UUID.randomUUID().toString();

    final Mono<Integer> asyncUpdate = inputMono.flatMap(record -> {
        return beginUpdate(dataSource,
  sqlStatementSharedAbove).withStatementEnricher(stmt -> {
            stmt.setString(1, record.getFirstName());
            stmt.setString(2, record.getLastName());
            stmt.setInt(3, record.getUserId());
            stmt.setString(4, record.getCOMPANYNAME());
            stmt.setInt(5, record.getCOMPANYID());
            stmt.setString(6, record.getEMAILID());
            stmt.setTimestamp(7,Timestamp.valueOf(now));
            stmt.setTimestamp(8,Timestamp.valueOf(now));
            stmt.setString(9,record.getDEPARTMENTNAME());
            stmt.setInt(10, record.getActiveInd());
            stmt.setInt(11, record.getTypeCode());
            stmt.setString(12, record..getTypeName());
        }).build();

    });
    return asyncUpdate.doOnSuccess(affectedRows -> LOGGER.debug("Added
 {} rows with ID {}", affectedRows, someID))
        .map(affectedRows -> someID);
}
</code>```

答:
The UPDATE part can only use column values returning by the table (query) from the USING part.

So you need to rewrite your statement to something like this:

```<code>merge into the_table USING
(
  select ? as primarykey,
         ? as column1,
         ? as column2,
         ? as column3,
         ....
  from dual
) x ON (x.primarykey = the_table.primarykey)
when not matched then
  insert (column1,column2,primarykey,column3, ...)
  VALUES (x.column1, x.column2, x.primarykey, x.column3, ...)
when matched then update
  set column1 = x.column1,
      column2 = x.column2,
      ....
</code>```

Body:
I am trying to perform a MERGE on single table (insert if not present else update).

my prepared statement looks like this:

merge into table USING DUAL ON (primarykey=?)
when not matched then insert (colum1,colum2,columnprimarykey,column4,column5,column6,column7,column8,column9,column10,column11,column12) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
when matched then update set column1=?,column2=?,column4=?,column5=?,column6=?,column7=?,column8=?,column9=?,column10=?,column11=?,column12=?

But I get following error when the prepared statement is executed:

Caused by: java.sql.SQLException: Missing IN or OUT parameter at index:: 13
          at oracle.jdbc.driver.OraclePreparedStatement.processCompletedBindRow(OraclePreparedStatement.java:1937) ~[ojdbc8-19.3.0.0.jar!/:19.3.0.0.0]

following works fine when executed directly in SQL developer, it will insert a new record with 12 columns if a primarykeycolumn=99 is not found in the table. It will update rest of the 11 columns if primarykeycolumn=99 is found in the table.

merge into table USING DUAL ON (primarykey=99)
when not matched then insert
(colum1,colum2,column3/primarykey,column4,column5,column6,column7,column8,column9,column10,column11,column12) VALUES (somevalue,somevalue,99,somevalue,somevalue,somevalue,somevalue,somevalue,somevalue,somevalue,somevalue,somevalue)
when matched then update set
column1=somevalue,column2=somevalue,column4=somevalue,column5=somevalue,column6=somevalue,column7=somevalue,column8=somevalue,column9=somevalue,column10=somevalue,column11=somevalue,column12=somevalue

Java code:

public Mono<String> createData(final Mono<Record> inputMono) {
    final String someID = UUID.randomUUID().toString();

    final Mono<Integer> asyncUpdate = inputMono.flatMap(record -> {
        return beginUpdate(dataSource,
  sqlStatementSharedAbove).withStatementEnricher(stmt -> {
            stmt.setString(1, record.getFirstName());
            stmt.setString(2, record.getLastName());
            stmt.setInt(3, record.getUserId());
            stmt.setString(4, record.getCOMPANYNAME());
            stmt.setInt(5, record.getCOMPANYID());
            stmt.setString(6, record.getEMAILID());
            stmt.setTimestamp(7,Timestamp.valueOf(now));
            stmt.setTimestamp(8,Timestamp.valueOf(now));
            stmt.setString(9,record.getDEPARTMENTNAME());
            stmt.setInt(10, record.getActiveInd());
            stmt.setInt(11, record.getTypeCode());
            stmt.setString(12, record..getTypeName());
        }).build();

    });
    return asyncUpdate.doOnSuccess(affectedRows -> LOGGER.debug("Added
 {} rows with ID {}", affectedRows, someID))
        .map(affectedRows -> someID);
}

Body:
The UPDATE part can only use column values returning by the table (query) from the USING part.

So you need to rewrite your statement to something like this:

merge into the_table USING
(
  select ? as primarykey,
         ? as column1,
         ? as column2,
         ? as column3,
         ....
  from dual
) x ON (x.primarykey = the_table.primarykey)
when not matched then
  insert (column1,column2,primarykey,column3, ...)
  VALUES (x.column1, x.column2, x.primarykey, x.column3, ...)
when matched then update
  set column1 = x.column1,
      column2 = x.column2,
      ....


问:
How can I check a radio button before submitting the form with a button?
I have a form with a table and each row of that table is a different offer. So, I also have some buttons in each row to download the documentation of the offer or delete the offer. That buttons submit the form and they go to another php file that does the desired action.

My problem is that the radio button of the desired row has to be checked before I submit the form. Is there any way with javascript that when you click one of those two button, first it selects automatically the radio button of that row and then submits the form?

```<code><form class="filterSelection" action="../php/editOffer/getInfo.php" method="POST">
    <table class="accountsTable">
        <thead>
            <tr>
                <th>Selected</th>
                <th>Project ID</th>
                <th>Revision</th>
                <th>Project Description</th>
                <th>Customer</th>
                <th>Date</th>
                <th>Creator</th>
                <th>Documentation</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="radio" name="selectedOffer" id="selectedOffer" required="" value="1-1"></td>
                <td>1</td>
                <td>1</td>
                <td>Test</td>
                <td>Info</td>
                <td>2020-02-10</td>
                <td>Name</td>
                <td>
                    <button type="submit" class="download" name="action" value="Download"><i class="fa fa-download" aria-hidden="true"></i></button>
                </td>
                <td>
                    <button type="submit" class="delete" name="action" value="Delete" onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')">
                        <i class="far fa-trash-alt"></i>
                    </button>
                </td>
            </tr>
        </tbody>
    </table>
    <br>
    <button name="action" class="nextButton" type="submit" value="Next"><i class="fas fa-arrow-alt-circle-right fa-2x"></i></button>
</form>
</code>```

答:
Finally I solved adding a hidden input and deleting the radio buttons. I have also change the structure of the forms. Now, this is my code that works:</p>

```<code><table class = "accountsTable">
            <thead>
                <tr>
                    <th>Project ID</th>
                    <th>Revision</th>
                    <th>Project Description</th>
                    <th>Customer</th>
                    <th>Date</th>
                    <th>Creator</th>
                    <th>Download</th>
                    <th>Delete</th>
                    <th>Edit</th>
                </tr>
            </thead>
            <tbody>
              <tr>
                    <form class="filterSelection" action="../php/editOffer/getInfo.php" method="POST">
                        <td>1</td>
                        <td>1</td>
                        <td>Test</td>
                        <td>Info</td>
                        <td>2020-02-10</td>
                        <td>Name</td>
                        <td><button type="submit" class="download" name="action" value="Download"><i class="fa fa-download" aria-hidden="true"></i></button>
                            </td>
                        <td><button type="submit" class="delete" name="action" value="Delete"
                                    onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')">
                                <i class="far fa-trash-alt"></i></button></td>
                        <td><button name="action" class="edit" type="submit" value="Next"><i class="fas fa-edit"></i></button></td>
                        <input type="hidden" name="selectedOffer" value="1-1"/>
                    </form>
                </tr>
                                        <tr>
                    <form class="filterSelection" action="../php/editOffer/getInfo.php" method="POST">
                        <td>1</td>
                        <td>2</td>
                        <td>Demo</td>
                        <td>Info1</td>
                        <td>2020-02-13</td>
                        <td>Name1</td>
                        <td></td>
                        <td><button type="submit" class="delete" name="action" value="Delete"
                                    onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')">
                                <i class="far fa-trash-alt"></i></button></td>
                        <td><button name="action" class="edit" type="submit" value="Next"><i class="fas fa-edit"></i></button></td>
                        <input type="hidden" name="selectedOffer" value="1-2"/>
                    </form>
                </tr>
</code>```

Body:
I have a form with a table and each row of that table is a different offer. So, I also have some buttons in each row to download the documentation of the offer or delete the offer. That buttons submit the form and they go to another php file that does the desired action.

My problem is that the radio button of the desired row has to be checked before I submit the form. Is there any way with javascript that when you click one of those two button, first it selects automatically the radio button of that row and then submits the form?

<form class="filterSelection" action="../php/editOffer/getInfo.php" method="POST">

                Selected
                Project ID
                Revision
                Project Description
                Customer
                Date
                Creator
                Documentation
                Delete

                <input type="radio" name="selectedOffer" id="selectedOffer" required="" value="1-1">
                1
                1
                Test
                Info
                2020-02-10
                Name

                    <button type="submit" class="download" name="action" value="Download"></button>

                    <button type="submit" class="delete" name="action" value="Delete" onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')">

                    </button>

    <button name="action" class="nextButton" type="submit" value="Next"></button>
</form>

Body:
Finally I solved adding a hidden input and deleting the radio buttons. I have also change the structure of the forms. Now, this is my code that works:

<table class = "accountsTable">
            <thead>
                <tr>
                    <th>Project ID</th>
                    <th>Revision</th>
                    <th>Project Description</th>
                    <th>Customer</th>
                    <th>Date</th>
                    <th>Creator</th>
                    <th>Download</th>
                    <th>Delete</th>
                    <th>Edit</th>
                </tr>
            </thead>
            <tbody>
              <tr>
                    <form class="filterSelection" action="../php/editOffer/getInfo.php" method="POST">
                        <td>1</td>
                        <td>1</td>
                        <td>Test</td>
                        <td>Info</td>
                        <td>2020-02-10</td>
                        <td>Name</td>
                        <td><button type="submit" class="download" name="action" value="Download"><i class="fa fa-download" aria-hidden="true"></i></button>
                            </td>
                        <td><button type="submit" class="delete" name="action" value="Delete"
                                    onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')">
                                <i class="far fa-trash-alt"></i></button></td>
                        <td><button name="action" class="edit" type="submit" value="Next"><i class="fas fa-edit"></i></button></td>
                        <input type="hidden" name="selectedOffer" value="1-1"/>
                    </form>
                </tr>
                                        <tr>
                    <form class="filterSelection" action="../php/editOffer/getInfo.php" method="POST">
                        <td>1</td>
                        <td>2</td>
                        <td>Demo</td>
                        <td>Info1</td>
                        <td>2020-02-13</td>
                        <td>Name1</td>
                        <td></td>
                        <td><button type="submit" class="delete" name="action" value="Delete"
                                    onclick="return confirm('Do you want to delete the selected offer? This action can´t be undone')">
                                <i class="far fa-trash-alt"></i></button></td>
                        <td><button name="action" class="edit" type="submit" value="Next"><i class="fas fa-edit"></i></button></td>
                        <input type="hidden" name="selectedOffer" value="1-2"/>
                    </form>
                </tr>


问:
Remove specific array from multiple array set using jquery
I have two checkboxes. When I check one, the code will get status and id of that checkbox and push into array, if that value is not present already

The array set become like this

```<code>  [8,0] [10,0]
</code>```

Requirements:

It is inserting [8,0] [8,0] twice if I check and then uncheck and again check it so this should not insert multiple times same values

Remove specific array from set of array so if I uncheck chkecbox then remove only [8,0] but keep  [10,0]

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) { // if click on check
    if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
    positions.push([id, status]); //  it will  insert  like [8,10] but geting duplicate  [8,10] [8,10]
    console.log(positions);
  } else {
    // if uncheck checkbox

    //  remove specific  value like  [8,0] or if value present [10,0] then remove this
    console.log(positions);
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0"></code>```

答:
If the array is small, just recreate it each time

let positions;
$("body").on('click', '.check_box', function() {
  positions = [];
  $(".check_box:checked").each(function() {
    positions.push([
     $(this).data('id'), $(this).data('status')
   ]);
  });
  console.log(positions);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0"></code>```

Body:
I have two checkboxes. When I check one, the code will get status and id of that checkbox and push into array, if that value is not present already

The array set become like this

  [8,0] [10,0]

Requirements:

It is inserting [8,0] [8,0] twice if I check and then uncheck and again check it so this should not insert multiple times same values

Remove specific array from set of array so if I uncheck chkecbox then remove only [8,0] but keep  [10,0]

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) { // if click on check
    if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
    positions.push([id, status]); //  it will  insert  like [8,10] but geting duplicate  [8,10] [8,10]
    console.log(positions);
  } else {
    // if uncheck checkbox

    //  remove specific  value like  [8,0] or if value present [10,0] then remove this
    console.log(positions);
  }

});

<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0">

Body:
If the array is small, just recreate it each time

let positions;
$("body").on('click', '.check_box', function() {
  positions = [];
  $(".check_box:checked").each(function() {
    positions.push([
     $(this).data('id'), $(this).data('status')
   ]);
  });
  console.log(positions);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0">


问:
How do I escape a string for a shell command in node?
In nodejs, the only way to execute external commands is via sys.exec(cmd). I'd like to call an external command and give it data via stdin. In nodejs there does yet not appear to be a way to open a command and then push data to it (only to exec and receive its standard+error outputs), so it appears the only way I've got to do this right now is via a single string command such as:

```<code>var dangerStr = "bad stuff here";
sys.exec("echo '" + dangerStr + "' | somecommand");
</code>```

Most answers to questions like this have focused on either regex which doesn't work for me in nodejs (which uses Google's V8 Javascript engine) or native features from other languages like Python.

I'd like to escape dangerStr so that it's safe to compose an exec string like the one above. If it helps, dangerStr will contain JSON data.

答:
I second the opinion of Will, whenever possible you should avoid escaping by hand and prefer spawn.

However, in the case that escaping is unavoidable, for example if you need to use exec or you are executing a command through ssh. Then you can use base64 to pass safe characters to bash and rely on bash to escape the unknown.

```<code>const dangerStr = 'bad stuff here'
// base64 has safe characters [A-Za-z=0-9+/]
const dangerBase64 = btoa(dangerStr)

sys.exec(`echo "$(echo ${dangerBase64} | base64 -d)" | somecommand`)
</code>```

The explanation is the following:

dangerBase64 is unknown but it does not contain unsafe characters in bash. Hence echo ${dangerBase64} will output what we want.

Finally the double quote around $(echo ${dangerBase64} | base64 -d) escape the actual value passed by the user inside bash, which is safe and has the same value that the user wanted.

Body:
In nodejs, the only way to execute external commands is via sys.exec(cmd). I'd like to call an external command and give it data via stdin. In nodejs there does yet not appear to be a way to open a command and then push data to it (only to exec and receive its standard+error outputs), so it appears the only way I've got to do this right now is via a single string command such as:

var dangerStr = "bad stuff here";
sys.exec("echo '" + dangerStr + "' | somecommand");

Most answers to questions like this have focused on either regex which doesn't work for me in nodejs (which uses Google's V8 Javascript engine) or native features from other languages like Python.

I'd like to escape dangerStr so that it's safe to compose an exec string like the one above. If it helps, dangerStr will contain JSON data.

Body:
I second the opinion of Will, whenever possible you should avoid escaping by hand and prefer spawn.

However, in the case that escaping is unavoidable, for example if you need to use exec or you are executing a command through ssh. Then you can use base64 to pass safe characters to bash and rely on bash to escape the unknown.

const dangerStr = 'bad stuff here'
// base64 has safe characters [A-Za-z=0-9+/]
const dangerBase64 = btoa(dangerStr)

sys.exec(`echo "$(echo ${dangerBase64} | base64 -d)" | somecommand`)

The explanation is the following:

dangerBase64 is unknown but it does not contain unsafe characters in bash. Hence echo ${dangerBase64} will output what we want.

Finally the double quote around $(echo ${dangerBase64} | base64 -d) escape the actual value passed by the user inside bash, which is safe and has the same value that the user wanted.


问:
Merge similar properties in a object into one property
I am new to python. I have a query to make.

```<code>b = [{a:"1",b:"6"},{a:"1",b:"89"},{a:"2",b:"16"},{a:"2",b:"99"}]
</code>```

i want to convert this into:

```<code>[{a:"1", b: "6. 89"}, {a:"2", "b": "16. 99"}]
</code>```

Any idea?

答:
```<code># Set up initial data
unmerged = [{"a":"1","b":"6"},{"a":"1","b":"89"},{"a":"2","b":"16"},{"a":"2","b":"99"}]

merged = {}
for entry in unmerged:
    entry_a = entry['a']
    entry_b = entry['b']
    composite_key = entry_a
    if composite_key in merged:
        merged[composite_key]['b'].append(entry_b)
    else:
        merged[composite_key] = {
            'a': entry_a,
            'b': [entry_b]
        }
# reconstruct your list with just your unique entries
cleaned = []
for key, value in merged.items():
    cleaned.append({
        'a': value['a'],
        'b': '.'.join(value['b']) # string join b by ". "
    })
new_list = [ clean for clean in cleaned ]
print(new_list)
</code>```

Output:

```<code>[{'a': '1', 'b': '6.89'}, {'a': '2', 'b': '16.99'}]
</code>```

Body:
I am new to python. I have a query to make.

b = [{a:"1",b:"6"},{a:"1",b:"89"},{a:"2",b:"16"},{a:"2",b:"99"}]

i want to convert this into:

[{a:"1", b: "6. 89"}, {a:"2", "b": "16. 99"}]

Any idea?

Body:
# Set up initial data
unmerged = [{"a":"1","b":"6"},{"a":"1","b":"89"},{"a":"2","b":"16"},{"a":"2","b":"99"}]

merged = {}
for entry in unmerged:
    entry_a = entry['a']
    entry_b = entry['b']
    composite_key = entry_a
    if composite_key in merged:
        merged[composite_key]['b'].append(entry_b)
    else:
        merged[composite_key] = {
            'a': entry_a,
            'b': [entry_b]
        }
# reconstruct your list with just your unique entries
cleaned = []
for key, value in merged.items():
    cleaned.append({
        'a': value['a'],
        'b': '.'.join(value['b']) # string join b by ". "
    })
new_list = [ clean for clean in cleaned ]
print(new_list)

Output:

[{'a': '1', 'b': '6.89'}, {'a': '2', 'b': '16.99'}]


问:
What's the difference between XSL Pattern and XPath in syntax?
I'm updating codes to use MSXML6.0 from MSXML3.0.
However, I noticed that, for MSXML3.0, the default "SelectionLanguage" is "XSL Pattern", while MSXML6.0 only support XPath.
I have concerns that this change would introduce differences in the query syntax.

Can somebody list the difference of syntax between these two syntax?

答:
The one thing that has tripped me up is selecting the first node in a node set. For example, we'd been using MSXML 3.0 (which uses XSLPattern) and has queries like this:

```<code>/root/book[0]
</code>```

This query was supposed to select the first book. This works with XSLPattern. But with XPath, this is correct:

```<code>/root/book[1]
</code>```

So when I switched us to using MSXML 6.0, which uses correct XPath, all those queries with "[0]" stopped working.

Update:
I just found this link that talks some more about XSLPattern and XPath:

MSDN Magazine: MSXML 3.0 Supports XPath 1.0, XSLT 1.0, XDR, and SAX2

http://msdn.microsoft.com/en-us/magazine/cc302348.aspx

Update #2:

Here's the W3C Spec on XSLT which includes XSL Patterns:

http://www.w3.org/TR/1998/WD-xsl-19981216.html#AEN376

Update #3

Here's another post that describes the same thing I mentioned above:

http://www.eggheadcafe.com/software/aspnet/29579789/xml-parsing.aspx

ContentLicense: CC BY-SA 2.5

Body:
The one thing that has tripped me up is selecting the first node in a node set. For example, we'd been using MSXML 3.0 (which uses XSLPattern) and has queries like this:

/root/book[0]

This query was supposed to select the first book. This works with XSLPattern. But with XPath, this is correct:

/root/book[1]

So when I switched us to using MSXML 6.0, which uses correct XPath, all those queries with "[0]" stopped working.

Update:
I just found this link that talks some more about XSLPattern and XPath:

MSDN Magazine: MSXML 3.0 Supports XPath 1.0, XSLT 1.0, XDR, and SAX2

http://msdn.microsoft.com/en-us/magazine/cc302348.aspx

Update #2:

Here's the W3C Spec on XSLT which includes XSL Patterns:

http://www.w3.org/TR/1998/WD-xsl-19981216.html#AEN376

Update #3

Here's another post that describes the same thing I mentioned above:

http://www.eggheadcafe.com/software/aspnet/29579789/xml-parsing.aspx


问:
File permissions issue with python/Spyder/Anaconda after upgrading mac to Catalina
After upgrading macOS to Catalina, my Anaconda installation was helpfully reconfigured by Apple.  Advice from the Anaconda website suggested a fresh install was the best way to go.  Did that and all seemed good.  I use spyder from the Anaconda navigator.  But trying a previously running python code failed due to apparent file permission problems. For example,

file='/Users/stingay/Documents/Coaching/WAIS/2019:20/041019/Race Walk Test-2019-10-04T16.29.13.774-C5612E80FB1D-Accelerometer.csv'

with open(file,'rt') as f:

```<code>data = csv.reader(f)
next(data)
</code>```

results in:

PermissionError: [Errno 1] Operation not permitted: '/Users/stingay/Documents/Coaching/WAIS/2019:20/041019/Race Walk Test-2019-10-04T16.29.13.774-C5612E80FB1D-Accelerometer.csv'

I can't see an issue with the permissions on the file or the directory structure in which the file sits.  If I move the file to~/.spyder-py3 (the working directory), it works.

Looks like there is some extra python/spyder/anaconda permissions issue with the file/directory I can't spot.  Any ideas?

答:
I guess you have solved this by now, but for future reference, I still post my answer.

TLDR: I opened a file (from the folder causing the problem) directly in
the spyder editor (File | open). As a consequence, the editor should have triggered the pop-up dialog question whether you want to allow access or not. In my case, the mac silently granted python/spyder access to the folder.  Now I can run the code in spyder without more problems than I have caused myself.

Longer version:
The source of your problem is described here:
https://www.howtogeek.com/443611/how-macos-catalinas-new-security-features-work/
Knowing that links are something frown upon, here's a summary:
The problem is that the folders  "Documents" and "Downloads" folders nowadays are protected and you would need to go to the security & privacy settings and "Files and Folder,s" and allow the applications to access these. Unfortunately, spyder does not show up here. So, if you want to run your python program from the terminal, you should probably grant the terminal access to the folders.

Body:
After upgrading macOS to Catalina, my Anaconda installation was helpfully reconfigured by Apple.  Advice from the Anaconda website suggested a fresh install was the best way to go.  Did that and all seemed good.  I use spyder from the Anaconda navigator.  But trying a previously running python code failed due to apparent file permission problems. For example,

file='/Users/stingay/Documents/Coaching/WAIS/2019:20/041019/Race Walk Test-2019-10-04T16.29.13.774-C5612E80FB1D-Accelerometer.csv'

with open(file,'rt') as f:

data = csv.reader(f)
next(data)

results in:

PermissionError: [Errno 1] Operation not permitted: '/Users/stingay/Documents/Coaching/WAIS/2019:20/041019/Race Walk Test-2019-10-04T16.29.13.774-C5612E80FB1D-Accelerometer.csv'

I can't see an issue with the permissions on the file or the directory structure in which the file sits.  If I move the file to~/.spyder-py3 (the working directory), it works.

Looks like there is some extra python/spyder/anaconda permissions issue with the file/directory I can't spot.  Any ideas?