问:
Trying to figure out how to go around Promise: Pending situation
I could not find a proper way to get my GET handler working. In the code below, when I send a GET request to that endpoint, my array element are all showing as 'Promise: Pending'. Can you suggest a way to go around it? I tried using setTimeout() method but I feel like it is not a proper solution.

Thank you in advance.

```<code>apiRouter.get('/photos', (req,res,next) => {
    axios.get("https://graph.instagram.com/me/media?fields=id,caption&access_token={some_access_token}")
    .then(response => {
        const photosArr = response.data.data;
        const arr = photosArr.map(id => {
            return axios.get(`https://graph.instagram.com/${id.id}?fields=id,media_type,media_url,username,timestamp&access_token={some_acces_token}`)
            .then(response => {
                 return response.data.media_url;
            })
        })
        res.send(arr);
        next();
    })
})

</code>```

答:
This would be a useful case to use async / await

The problem is that you are returning the promise in your Array.map(). Even though you have a .then block after your promise, the promise itself is what is being returned because this is running asynchronously.

Something like this should be close

```<code>apiRouter.get('/photos', async (req,res,next) => {
    const response = await axios.get("https://graph.instagram.com/me/media?fields=id,caption&access_token={some_access_token}")
    const photosArr = response.data.data;
    const arr = photosArr.map(async (id) => {
        const resp await axios.get(`https://graph.instagram.com/${id.id}?fields=id,media_type,media_url,username,timestamp&access_token={some_acces_token}`)
         return resp.data.media_url;
    };
    const final = await Promise.all(arr);
    res.send(final);
    next();
})
</code>```

Body:
I could not find a proper way to get my GET handler working. In the code below, when I send a GET request to that endpoint, my array element are all showing as 'Promise: Pending'. Can you suggest a way to go around it? I tried using setTimeout() method but I feel like it is not a proper solution.

Thank you in advance.

apiRouter.get('/photos', (req,res,next) => {
    axios.get("https://graph.instagram.com/me/media?fields=id,caption&access_token={some_access_token}")
    .then(response => {
        const photosArr = response.data.data;
        const arr = photosArr.map(id => {
            return axios.get(`https://graph.instagram.com/${id.id}?fields=id,media_type,media_url,username,timestamp&access_token={some_acces_token}`)
            .then(response => {
                 return response.data.media_url;
            })
        })
        res.send(arr);
        next();
    })
})

Body:
This would be a useful case to use async / await

The problem is that you are returning the promise in your Array.map(). Even though you have a .then block after your promise, the promise itself is what is being returned because this is running asynchronously.

Something like this should be close

apiRouter.get('/photos', async (req,res,next) => {
    const response = await axios.get("https://graph.instagram.com/me/media?fields=id,caption&access_token={some_access_token}")
    const photosArr = response.data.data;
    const arr = photosArr.map(async (id) => {
        const resp await axios.get(`https://graph.instagram.com/${id.id}?fields=id,media_type,media_url,username,timestamp&access_token={some_acces_token}`)
         return resp.data.media_url;
    };
    const final = await Promise.all(arr);
    res.send(final);
    next();
})


来源: stackexchange

问:
Storage::move giving “File not found at path:”
I am trying to move an image from one folder into another folder by using:

```<code>Storage::move(storage_path('app/public/temporary/').$imageName, storage_path('app/public/profilePic/'.$imageName));
</code>```

But when i run it gave me the error:

File not found at path: home/vagrant/code/avida/storage/app/public/temporary/5bfb7272e9dc9.download.jpeg

i google and found the following solution:

```<code>Storage::disk('local')->move(storage_path('app/public/temporary/').$imageName, storage_path('app/public/profilePic/'.$imageName));
</code>```

but then it gave another error:

Method 'disk' not found in \Illuminate\Support\Facades\Storage

Can anyone please help me how can i move this file ?
Thank you

答:
Storage class operate in storage directory so there is no need to use storage_path() helper.

Change your code to the one below:

```<code>Storage::move('public/temporary/'.$imageName, 'public/profilePic/'.$imageName);
</code>```

I hope that helps :)

ContentLicense: CC BY-SA 4.0

Body:
I am trying to move an image from one folder into another folder by using:

Storage::move(storage_path('app/public/temporary/').$imageName, storage_path('app/public/profilePic/'.$imageName));

But when i run it gave me the error:

File not found at path: home/vagrant/code/avida/storage/app/public/temporary/5bfb7272e9dc9.download.jpeg

i google and found the following solution:

Storage::disk('local')->move(storage_path('app/public/temporary/').$imageName, storage_path('app/public/profilePic/'.$imageName));

but then it gave another error:

Method 'disk' not found in \Illuminate\Support\Facades\Storage

Can anyone please help me how can i move this file ?
Thank you

Body:
Storage class operate in storage directory so there is no need to use storage_path() helper.

Change your code to the one below:

Storage::move('public/temporary/'.$imageName, 'public/profilePic/'.$imageName);

I hope that helps :)


问:
How to show a popup alert in laravel
In my database i have a table called tasks and it has a column named file where files are stored. Now i want when a user click in the file he will show a pop-up message which ask either to download or view a file.

partially try like this

```<code><a href="" id="popup">{{ $task->file }}
</code>```

And i created a sweet-alert message for this like below

```<code>$(document).ready(function () {
          $('popup').on('click', 'td.warning input', function () {
            Swal.fire({
                    title: "Wow!",
                    text: "Message!",
                    type: "success",
                    showCancelButton: true,
                    cancelButtonText: "View",
                    confirmButtonText: 'Download!',
                },
                function (isConfirm) {
                    if (isConfirm) {
                        swal("Deleted!", "Your imaginary file has been deleted!", "success");
                    } else {
                        swal("Cancelled", "Your imaginary file is safe :)", "error");
                    }
                });
          });
      });
    </script
</code>```

Please help me to achieve this

答:
Add some html code to the sweet alert, so you can show messages or images, something as i did here, you can see the documentation for more examples of what you can do:
https://sweetalert2.github.io/

```<code><a href="" id="popup">{{ $task->file }}
<script>
$(document).ready(function () {
          $('popup').on('click', 'td.warning input', function () {
            Swal.fire({
                    title: "Wow!",
                    text: "Message!",
                    type: "success",
                    showCancelButton: true,
                    cancelButtonText: "View",
                    confirmButtonText: 'Download!',
                },
                function (isConfirm) {
                    if (isConfirm) {
                        swal("Deleted!", "Your imaginary file has been deleted!", "success");
                    } else {
                        swal("Cancelled", "Your imaginary file is safe :)", "error");
                    }
                });
          });
      });
    </script>
</code>```

Then you can add on sweet alert, some kind of messaging by adding on if and else swal's some of html code:

```<code>if (isConfirm) {
        swal(
        title:"Deleted!",
        text: "Your imaginary file has been deleted!",
        type: "success",
        html: '<h1>Text here to download or to view</h1>'+
        '<p>show some more text or show image</p>'
        );
} else {
        swal(
        title:"Cancelled",
        text: "Your imaginary file is safe :)",
        type: "error",
        html: '<h1>Text here to download or to view</h1>'+
        '<p>show some more text or show image</p>'
);
}
</code>```

Hope this works for you...

Title: How to show a popup alert in laravel

Body:
In my database i have a table called tasks and it has a column named file where files are stored. Now i want when a user click in the file he will show a pop-up message which ask either to download or view a file.

partially try like this

{{ $task->file }}

And i created a sweet-alert message for this like below

$(document).ready(function () {
          $('popup').on('click', 'td.warning input', function () {
            Swal.fire({
                    title: "Wow!",
                    text: "Message!",
                    type: "success",
                    showCancelButton: true,
                    cancelButtonText: "View",
                    confirmButtonText: 'Download!',
                },
                function (isConfirm) {
                    if (isConfirm) {
                        swal("Deleted!", "Your imaginary file has been deleted!", "success");
                    } else {
                        swal("Cancelled", "Your imaginary file is safe :)", "error");
                    }
                });
          });
      });
    </script

Please help me to achieve this

Body:
Add some html code to the sweet alert, so you can show messages or images, something as i did here, you can see the documentation for more examples of what you can do:
https://sweetalert2.github.io/

<a href="" id="popup">{{ $task->file }}
<script>
$(document).ready(function () {
          $('popup').on('click', 'td.warning input', function () {
            Swal.fire({
                    title: "Wow!",
                    text: "Message!",
                    type: "success",
                    showCancelButton: true,
                    cancelButtonText: "View",
                    confirmButtonText: 'Download!',
                },
                function (isConfirm) {
                    if (isConfirm) {
                        swal("Deleted!", "Your imaginary file has been deleted!", "success");
                    } else {
                        swal("Cancelled", "Your imaginary file is safe :)", "error");
                    }
                });
          });
      });
    </script>

Then you can add on sweet alert, some kind of messaging by adding on if and else swal's some of html code:

if (isConfirm) {
        swal(
        title:"Deleted!",
        text: "Your imaginary file has been deleted!",
        type: "success",
        html: '<h1>Text here to download or to view</h1>'+
        '<p>show some more text or show image</p>'
        );
} else {
        swal(
        title:"Cancelled",
        text: "Your imaginary file is safe :)",
        type: "error",
        html: '<h1>Text here to download or to view</h1>'+
        '<p>show some more text or show image</p>'
);
}

Hope this works for you...


答:
You can use Promise.all() to wait for all promises in an array to resolve:

```<code>apiRouter.get('/photos', (req,res,next) => {
    axios.get("https://graph.instagram.com/me/media?fields=id,caption&access_token={some_access_token}")
    .then(response => {
        const photosArr = response.data.data;
        Promise.all(photosArr.map(id => {
            return axios.get(`https://graph.instagram.com/${id.id}?fields=id,media_type,media_url,username,timestamp&access_token={some_acces_token}`)
            .then(response => {
                 return response.data.media_url;
            })
        })).then(photos => {
          res.send(photos);
          next();
        })
    })
})```
```

Title: Trying to figure out how to go around Promise: Pending situation

Body:
You can use Promise.all() to wait for all promises in an array to resolve:

apiRouter.get('/photos', (req,res,next) => {
    axios.get("https://graph.instagram.com/me/media?fields=id,caption&access_token={some_access_token}")
    .then(response => {
        const photosArr = response.data.data;
        Promise.all(photosArr.map(id => {
            return axios.get(`https://graph.instagram.com/${id.id}?fields=id,media_type,media_url,username,timestamp&access_token={some_acces_token}`)
            .then(response => {
                 return response.data.media_url;
            })
        })).then(photos => {
          res.send(photos);
          next();
        })
    })
})```


问:
filter dataframe columns as you iterate through rows and create dictionary
I have the following table of data in a spreadsheet:

```<code>Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8
</code>```

I'm reading the spreadsheet and passing the data as a dataframe.

I need to transform this table of data to json following a specific schema.

I have the following script:

```<code>for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            print(row.to_dict())
</code>```

which return:

```<code>{'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}
</code>```

I want to be able to filter out a specific column. For example, to return this:

```<code>{'Name': 'bar', 'Description': 'foofoo'}
</code>```

I know that I can print only the columns I want with this print(row['Name'],row['Description']) however this is only returning me values when I also want to return the key.

How can I do this?

答:
After converting to dictionary you can delete the key which you don't need with:

```<code>del(row[value])
</code>```

Now the dictionary will have only name and description.

Body:
I have the following table of data in a spreadsheet:

Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8

I'm reading the spreadsheet and passing the data as a dataframe.

I need to transform this table of data to json following a specific schema.

I have the following script:

for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            print(row.to_dict())

which return:

{'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}

I want to be able to filter out a specific column. For example, to return this:

{'Name': 'bar', 'Description': 'foofoo'}

I know that I can print only the columns I want with this print(row['Name'],row['Description']) however this is only returning me values when I also want to return the key.

How can I do this?

Body:
After converting to dictionary you can delete the key which you don't need with:

del(row[value])

Now the dictionary will have only name and description.


问:
Find all indices of each letter in a string
I'm trying to get a list consisting of the indexes for each item of another sequence.
Sounds easy enough in theory.

```<code>a = 'string of letters'
b = [a.index(x) for x in a]
</code>```

But it doesn't work. I've tried list comprehensions, simple for loops, using enumerate etc, but every time b will return the same index for duplicates in a.
That is, 's' in a, for example, will return '0' in b for both the first and last item because they're the same character.
I'm guessing is cache or something like that as a way for Python to speed things up.

In any case, I can't figure this out and I'd appreciate some help as to how I can get this working as well as maybe an explanation of why this happens.

答:
Thanks a lot for the input. I did figure it out with enumerate, actually.
To elaborate, I had two lists, a and b. a contains both uppercase and lowercase characters. b consists of the same characters as a, but shifted by a certain number of positions, like in a cipher.
I wanted to keep the case of the characters in b at the same position, after the 'encoding', but I needed the index of each character in 'A'. </p>

<p>Anyway, it was as simple as this: </p>

```<code>a = 'tEXt'
c = [x for x,y in enumerate(a) if y.isupper()]
b = ['x', 't', 't', 'e'] #(this is the encoded version of 'a', returned from a different place as a string, but converted here to a list)
for x in c:
  b[x] = b[x].upper()
b = ''.join[b]
b
  'xTTe'
</code>```

Body:
I'm trying to get a list consisting of the indexes for each item of another sequence.
Sounds easy enough in theory.

a = 'string of letters'
b = [a.index(x) for x in a]

But it doesn't work. I've tried list comprehensions, simple for loops, using enumerate etc, but every time b will return the same index for duplicates in a.
That is, 's' in a, for example, will return '0' in b for both the first and last item because they're the same character.
I'm guessing is cache or something like that as a way for Python to speed things up.

In any case, I can't figure this out and I'd appreciate some help as to how I can get this working as well as maybe an explanation of why this happens.

Body:
Thanks a lot for the input. I did figure it out with enumerate, actually.
To elaborate, I had two lists, a and b. a contains both uppercase and lowercase characters. b consists of the same characters as a, but shifted by a certain number of positions, like in a cipher.
I wanted to keep the case of the characters in b at the same position, after the 'encoding', but I needed the index of each character in 'A'.

Anyway, it was as simple as this:

a = 'tEXt'
c = [x for x,y in enumerate(a) if y.isupper()]
b = ['x', 't', 't', 'e'] #(this is the encoded version of 'a', returned from a different place as a string, but converted here to a list)
for x in c:
  b[x] = b[x].upper()
b = ''.join[b]
b
  'xTTe'


问:
Is it possible to populate objects in map schema type?
I have schema type Map in my mongoose model. In this map, each element has reference to another model. I know that it's possible to populate attributes in array, but how about Map type? Be cause nesting like "map_type_attribute.some_attribute_to_populate" doesn't work. :)

This is my model:

const Mongoose = require('mongoose');

const parameter = Mongoose.Schema({
  definition: {
    type: Mongoose.Schema.Types.ObjectId,
    ref:  'Definition',
  },
  value:      {},
}, {_id: false});

const schema = Mongoose.Schema({
  model:      {
    type: Mongoose.Schema.Types.ObjectId,
    ref:  'Model'
  },
  name:       String,
  objectid:   Number,
  externalId: String,
  properties: Mongoose.Schema.Types.Mixed,
  parameters: {
    type: Map,
    of:   parameter
  }
});

module.exports = Mongoose.model('Element', schema);
```
<p>This is how i'm trying to populate definition field:</p>
<pre class="lang-js prettyprint-override"><code> const request = Element.find(query, projection);
  request.populate('parameters.definition');
  request.exec( (err, docs) => {
...
</code>```

答:
I also trying to find answer on this question. It seems that deep-populate work, but only if you put keys from the Map to populate method/function. In your case, if you have data like:

    {
        model: ObjectId("111"),
        name:       "MyName",
        objectid:   111,
        externalId: "ExternalId",
        properties: ...,
        parameters:{
            "parameter1":{
                "definition":ObjectId("333"),
                "value":"value of parameter 1"
        },
            "parameter2":{
                "definition": ObjectId("444"),
                "value": "value of parameter 2"
            }
        }
    }
```
<p>Then you may find and populate like this:</p>
<pre class="lang-js prettyprint-override"><code>Element.find({}).populate("parameters.parameter1.definiton")
</code>```

But it's not a good solution. It would be nice if we have something like regexp inside this populate path.

Currently I've managed only to grab all inner collection, and then manually work with Map to substitude collections.
It shouldn't be a huge overhead, since you have only 2 queries to DB. In you case it can be like:

    const elements = Element.find({});
    const parameters = Parameter.find({});
    // go through the elements.parameters and replace it with appropriate value from parameters collection.
```

Body:
I have schema type Map in my mongoose model. In this map, each element has reference to another model. I know that it's possible to populate attributes in array, but how about Map type? Be cause nesting like "map_type_attribute.some_attribute_to_populate" doesn't work. :)

This is my model:

const Mongoose = require('mongoose');

const parameter = Mongoose.Schema({
  definition: {
    type: Mongoose.Schema.Types.ObjectId,
    ref:  'Definition',
  },
  value:      {},
}, {_id: false});

const schema = Mongoose.Schema({
  model:      {
    type: Mongoose.Schema.Types.ObjectId,
    ref:  'Model'
  },
  name:       String,
  objectid:   Number,
  externalId: String,
  properties: Mongoose.Schema.Types.Mixed,
  parameters: {
    type: Map,
    of:   parameter
  }
});

module.exports = Mongoose.model('Element', schema);

This is how i'm trying to populate definition field:

 const request = Element.find(query, projection);
  request.populate('parameters.definition');
  request.exec( (err, docs) => {
...

Body:
I also trying to find answer on this question. It seems that deep-populate work, but only if you put keys from the Map to populate method/function. In your case, if you have data like:

    {
        model: ObjectId("111"),
        name:       "MyName",
        objectid:   111,
        externalId: "ExternalId",
        properties: ...,
        parameters:{
            "parameter1":{
                "definition":ObjectId("333"),
                "value":"value of parameter 1"
        },
            "parameter2":{
                "definition": ObjectId("444"),
                "value": "value of parameter 2"
            }
        }
    }

Then you may find and populate like this:

Element.find({}).populate("parameters.parameter1.definiton")

But it's not a good solution. It would be nice if we have something like regexp inside this populate path.

Currently I've managed only to grab all inner collection, and then manually work with Map to substitude collections.
It shouldn't be a huge overhead, since you have only 2 queries to DB. In you case it can be like:

    const elements = Element.find({});
    const parameters = Parameter.find({});
    // go through the elements.parameters and replace it with appropriate value from parameters collection.


问:
Copy cell background color and paste it to corresponding cell of another sheet
I have values on Sheet 1 and I gave the background color using conditional formatting.

I want to copy only the color and paste it to the corresponding cell of  sheet 2 without pasting the value.

Example if sheet 1 cell A1 has red color for specific value, transfer the color to sheet 2 A1.

I use two colors, red and white. Red is for higher value and white is for lower value.

```<code>Sub copycolor()
    Dim intRow As Integer
    Dim rngCopy As Range
    Dim rngPaste As Range

    For intRow = 1 To 20

        Set rngCopy = Sheet1.Range("A" & intRow + 0)
        Set rngPaste = Sheet2.Range("b" & intRow)

        'Test to see if rows 500+ have a value
        If rngCopy.Value <> "" Then

            'Since it has a value, copy the value and color
            rngPaste.Value = rngCopy.Value
            rngPaste.Interior.Color = rngCopy.Interior.Color

        End If
    Next intRow
End Sub
</code>```

答:
Appreciating this was some time ago. I would like to do a similar thing however would like to append the Interior Color Reference ie. 255 to the cells value.

so if cell A1 has Hello in the cell and is Colored Red I'd want in the other worksheet cell A1: Hello | 255

Just used | as a delimiter but anything sensible...

Body:
I have values on Sheet 1 and I gave the background color using conditional formatting.

I want to copy only the color and paste it to the corresponding cell of  sheet 2 without pasting the value.

Example if sheet 1 cell A1 has red color for specific value, transfer the color to sheet 2 A1.

I use two colors, red and white. Red is for higher value and white is for lower value.

Sub copycolor()
    Dim intRow As Integer
    Dim rngCopy As Range
    Dim rngPaste As Range

    For intRow = 1 To 20

        Set rngCopy = Sheet1.Range("A" & intRow + 0)
        Set rngPaste = Sheet2.Range("b" & intRow)

        'Test to see if rows 500+ have a value
        If rngCopy.Value <> "" Then

            'Since it has a value, copy the value and color
            rngPaste.Value = rngCopy.Value
            rngPaste.Interior.Color = rngCopy.Interior.Color

        End If
    Next intRow
End Sub


问:
need to group records based on matching reversals
This question is continuation to my earlier post.

Need to group records based on matching reversal in sql

I will be more clear with one complex example from my transaction table.

```<code>Row_Number  LOAN_ID TXN_ENTRY_API_NAME          TXN_AMT
        1   100     ReverseSpreadPayment        2250
        2   100     SpreadPayment               -2250
        3   100     ReverseSpreadPayment        2250
        4   100     SpreadPayment               -2250
        5   100     ReverseSpreadPayment        2250
        6   100     SpreadPayment               -2250
        7   100     ReverseSpreadPayment        2250
        8   100     ReverseSpreadPayment        2250
        9   100     SpreadPayment               1000
</code>```

In the above example

rownumber 1&2 are matched records bcoz payment has an associated reverse payment, hence sum these two.
rownumber 3&4 are matched records bcoz payment has an associated reverse payment, hence sum these two.
rownumber 5&6 are matched records bcoz payment has an associated reverse payment, hence sum these two.
rownumber 7 does not have an associated matching payment amount, hence is ophan. Keep it as it is.
rownumber 8 does not have an associated matching payment amount, hence is ophan. Keep it as it is.
rownumber 9 does not have an associated matching reverse payment amount, hence is ophan. Keep it as it is.

To understand you better i just added row_number column here, where as in my transaction table we dont have any row_number column.

My expected output should be like below table.

```<code>                    LOAN_ID     TXN_ENTRY_API_NAME                 TXN_AMT
                        100     ReverseSpreadPayment,SpreadPayment  0
                        100     ReverseSpreadPayment,SpreadPayment  0
                        100     ReverseSpreadPayment,SpreadPayment  0
                        100     ReverseSpreadPayment                2250
                        100     ReverseSpreadPayment                2250
                        100     SpreadPayment                       1000
</code>```

What I am expecting to generate row number function like below so that i can group by using row number column.

The Row number is an ordering column which is generated by me, thats it.

答:
I think this is just row_number() and aggregation:

```<code>select listagg(row_number, ',') within group (order by row_number) as row_numbers,
       loan_id, txn_entry_api_name, sum(txn_amt) as txn_amt,
       listagg(txn_entry_api_name, ',') within group (order by row_number) as txn_entry_api_name
from (select t.*,
             row_number() over (partition by loan_id, txn_entry_api_name, abs(txn_amt) order by row_number) as seqnum
      from t
     ) t
group by seqnum;
</code>```

Body:
This question is continuation to my earlier post.

Need to group records based on matching reversal in sql

I will be more clear with one complex example from my transaction table.

Row_Number  LOAN_ID TXN_ENTRY_API_NAME          TXN_AMT
        1   100     ReverseSpreadPayment        2250
        2   100     SpreadPayment               -2250
        3   100     ReverseSpreadPayment        2250
        4   100     SpreadPayment               -2250
        5   100     ReverseSpreadPayment        2250
        6   100     SpreadPayment               -2250
        7   100     ReverseSpreadPayment        2250
        8   100     ReverseSpreadPayment        2250
        9   100     SpreadPayment               1000

In the above example

rownumber 1&2 are matched records bcoz payment has an associated reverse payment, hence sum these two.
rownumber 3&4 are matched records bcoz payment has an associated reverse payment, hence sum these two.
rownumber 5&6 are matched records bcoz payment has an associated reverse payment, hence sum these two.
rownumber 7 does not have an associated matching payment amount, hence is ophan. Keep it as it is.
rownumber 8 does not have an associated matching payment amount, hence is ophan. Keep it as it is.
rownumber 9 does not have an associated matching reverse payment amount, hence is ophan. Keep it as it is.

To understand you better i just added row_number column here, where as in my transaction table we dont have any row_number column.

My expected output should be like below table.

                    LOAN_ID     TXN_ENTRY_API_NAME                 TXN_AMT
                        100     ReverseSpreadPayment,SpreadPayment  0
                        100     ReverseSpreadPayment,SpreadPayment  0
                        100     ReverseSpreadPayment,SpreadPayment  0
                        100     ReverseSpreadPayment                2250
                        100     ReverseSpreadPayment                2250
                        100     SpreadPayment                       1000

What I am expecting to generate row number function like below so that i can group by using row number column.

The Row number is an ordering column which is generated by me, thats it.

Body:
I think this is just row_number() and aggregation:

select listagg(row_number, ',') within group (order by row_number) as row_numbers,
       loan_id, txn_entry_api_name, sum(txn_amt) as txn_amt,
       listagg(txn_entry_api_name, ',') within group (order by row_number) as txn_entry_api_name
from (select t.*,
             row_number() over (partition by loan_id, txn_entry_api_name, abs(txn_amt) order by row_number) as seqnum
      from t
     ) t
group by seqnum;


问:
Having an issue with e.target.value returning Undefined in React
I have a feature where you can click an img and see a a list of names which are clickable....when you click a name, that persons image should take the place of the original img. Im working with an artist api and rather then me getting an error in the console, the image changes to an img of an artist whos name is 'undefined'...strange. might not be a huge fix but ive been tormented by this issue for some time now.

```<code>searchForArtist(query) {
    request.get(`https://api.spotify.com/v1/search?q=${query}&type=artist`)
      .then((response) => {
        const artist = response.body.artists.items[0];
        const name = artist.name;
        const id = artist.id;
        const img_url = artist.images[0].url;
        this.setState({
          selectedArtist: {
            name,
            id,
            img_url,
          },
        });
      })
      .then(() => {
        this.getArtistAlbums();
      })
      .catch((err) => {
        console.error(err);
      });
  }

  getSubsequentCollabs(artist) {
    this.setState({
      selectedArtist: {},
      selectedAlbums: {},
      artistCounts: {},
    });
    console.log(artist);
    this.searchForArtist(artist);
  }

  artistOnClick(e) {
    console.log(e);
    let artist = e.target.value;
    this.getSubsequentCollabs(artist);
  }
</code>```

I have another component doing this:

```<code>const Artist = ({name, artistOnClick}) => {
  return (
    <div name={name} onClick={artistOnClick}>
      {name}
    </div>
  )
}

export default Artist;
</code>```

答:
In React, e.target.value will appear null if it's not saved in another variable.

For example:

```<code>const onChange = e => {
    console.log(e.target.value);
    setState({blah: e.target.value})
}
</code>```

In the above example console.log(e.target.value) would appear as the value but then in setState, e.target.value would be undefined.

You would need to save e.target.value in a new variable, to be able to use it:

```<code>const eTarget = e.target.value;
</code>```

React versions before 17 (and React Native) use event pooling. Read about it here:

From the docs:

Note:

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

and

Note:

As of v17, e.persist() doesn't do anything because the SyntheticEvent is no longer pooled.

ContentLicense: CC BY-SA 3.0

Body:
I have a feature where you can click an img and see a a list of names which are clickable....when you click a name, that persons image should take the place of the original img. Im working with an artist api and rather then me getting an error in the console, the image changes to an img of an artist whos name is 'undefined'...strange. might not be a huge fix but ive been tormented by this issue for some time now.

searchForArtist(query) {
    request.get(`https://api.spotify.com/v1/search?q=${query}&type=artist`)
      .then((response) => {
        const artist = response.body.artists.items[0];
        const name = artist.name;
        const id = artist.id;
        const img_url = artist.images[0].url;
        this.setState({
          selectedArtist: {
            name,
            id,
            img_url,
          },
        });
      })
      .then(() => {
        this.getArtistAlbums();
      })
      .catch((err) => {
        console.error(err);
      });
  }

  getSubsequentCollabs(artist) {
    this.setState({
      selectedArtist: {},
      selectedAlbums: {},
      artistCounts: {},
    });
    console.log(artist);
    this.searchForArtist(artist);
  }

  artistOnClick(e) {
    console.log(e);
    let artist = e.target.value;
    this.getSubsequentCollabs(artist);
  }

I have another component doing this:

const Artist = ({name, artistOnClick}) => {
  return (

      {name}

  )
}

export default Artist;

Body:
In React, e.target.value will appear null if it's not saved in another variable.

For example:

const onChange = e => {
    console.log(e.target.value);
    setState({blah: e.target.value})
}

In the above example console.log(e.target.value) would appear as the value but then in setState, e.target.value would be undefined.

You would need to save e.target.value in a new variable, to be able to use it:

const eTarget = e.target.value;

React versions before 17 (and React Native) use event pooling. Read about it here:

From the docs:

Note:

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

and

Note:

As of v17, e.persist() doesn't do anything because the SyntheticEvent is no longer pooled.


问:
CORS issue when calling a localhost API hosted on one port from another port
I have a localhost Rest API POST query hosted using Docker at port 8501: http://localhost:8501/v1/models/model:predict. I have an HTML file which runs with a JavaScript script and it is hosted at http://127.0.0.1:8887/ using WebServer for Chrome. I am able to call global Rest API POST queries from my HTML-JS files and my local Rest API works fine from POSTMAN. But I am unable to call my API from my HTML-JS files.

Below is my JS file:

```<code>function foo() {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Access-Control-Allow-Origin", "*");
    myHeaders.append("Access-Control-Allow-Methods", "POST");

    var raw = JSON.stringify({"instances":[[0]]});

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: raw,
        redirect: 'follow'
    };

    fetch("http://localhost:8501/v1/models/model:predict", requestOptions)
        .then(response => console.log(response.text()))
        .then(result => console.log(result))
        .catch(error => console.log('error', error));

}
</code>```

I get the below error:

Access to fetch at
  'http://localhost:8501/v1/models/model:predict' from origin
  'http://127.0.0.1:8887' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. If an opaque response serves your needs, set the request's
  mode to 'no-cors' to fetch the resource with CORS disabled.

Can anyone please help me?

答:
You seem to have understood CORS slightly "backwards" -- the Access-Control-Allow-Origin and Access-Control-Allow-Methods headers are specified on HTTP responses, not requests. This obviously implies that it's the HTTP server that sets them, not the client.

It would make for a terrible cross site security model if a script of arbitrary origin could effectively dictate to the HTTP server what kind of requests and from which origins the latter must accept.

It's the HTTP service that ultimately controls access by specifying appropriate headers in the responses it serves, and the user agent validates the cross origin request where it refuses to proceed if the server didn't indicate it allows requests from the different origin the script was served from -- the response will be discarded and an error will be thrown.

In short, you need to add the headers to the responses your REST service at localhost:8501 generates, instead of specifying them for requests your client side script creates where they don't do anything.

Body:
I have a localhost Rest API POST query hosted using Docker at port 8501: http://localhost:8501/v1/models/model:predict. I have an HTML file which runs with a JavaScript script and it is hosted at http://127.0.0.1:8887/ using WebServer for Chrome. I am able to call global Rest API POST queries from my HTML-JS files and my local Rest API works fine from POSTMAN. But I am unable to call my API from my HTML-JS files.

Below is my JS file:

function foo() {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Access-Control-Allow-Origin", "*");
    myHeaders.append("Access-Control-Allow-Methods", "POST");

    var raw = JSON.stringify({"instances":[[0]]});

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: raw,
        redirect: 'follow'
    };

    fetch("http://localhost:8501/v1/models/model:predict", requestOptions)
        .then(response => console.log(response.text()))
        .then(result => console.log(result))
        .catch(error => console.log('error', error));

}

I get the below error:

Access to fetch at
  'http://localhost:8501/v1/models/model:predict' from origin
  'http://127.0.0.1:8887' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. If an opaque response serves your needs, set the request's
  mode to 'no-cors' to fetch the resource with CORS disabled.

Can anyone please help me?


问:
React - toggle class: useState hook form several button
I have some buttons and I'm trying to add active class for clicked button. But when I click one of the buttons, all buttons are getting active class.

```<code>const { useState } = React;
const { render } = ReactDOM;
const node = document.getElementById("root");

const Button = ({ message }) => {
  const [condition, setCondition] = useState(false);
  return (
    <div>
    {
    Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(!condition)}
     }}
     ))
      }
    </div>
  );
   //Updated
   Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(condition === "off" ? "on" : "off")}
     }}
     ))
      }
    </div>
  ); //This can be modified to work for button clicked. Because active class is added to all buttons, if one of them is clicked
};
render(<Button message="Click me if you dare!" />, node);
</code>```

This is working if I click the first button, but if I click again the same button, this active class should be removed

答: You could create component Button with state within and use this component to populate buttons. Probably you can use :active CSS selector and avoid js at all</p>

Body:
I have some buttons and I'm trying to add active class for clicked button. But when I click one of the buttons, all buttons are getting active class.

const { useState } = React;
const { render } = ReactDOM;
const node = document.getElementById("root");

const Button = ({ message }) => {
  const [condition, setCondition] = useState(false);
  return (

    {
    Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(!condition)}
     }}
     ))
      }

  );
   //Updated
   Object.keys(res).map((data) => (
    <Button className={condition ? "button toggled" : "button"} onClick=.
     {() => {
      setCondition(condition === "off" ? "on" : "off")}
     }}
     ))
      }

  ); //This can be modified to work for button clicked. Because active class is added to all buttons, if one of them is clicked
};
render(<Button message="Click me if you dare!" />, node);

This is working if I click the first button, but if I click again the same button, this active class should be removed


问:
I am trying to store a list of strings from a file into an array in C
I am trying to read a file containing a list of words and store them in an array. After storing I randomly tried to print the 10th element to ensure that the code did what it's supposed to but I was unsuccessful.
I also get the following warning and I don't get what it's telling me:

warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
   22 |             dict[i][j]=word_scanned;

#include <stdio.h>

#include <stdlib.h>

int main() {

    char word_scanned[50];

    char dict[102402][50];

    int i,j;

    FILE *fptr;

    if ((fptr = fopen("/usr/share/dict/words", "r")) == NULL) {

        printf("Error! opening file\n");

        // Program exits if file pointer returns NULL.

        exit(1);

    }

   for(i=0; !feof(fptr); i++){

        fscanf(fptr,"%s", word_scanned);

       for (j=0; j<50; j++){

            dict[i][j]=word_scanned;

       }

   }

    printf("%s\n",dict[9]);

    fclose(fptr);

    return 0;
}```

答:
dict[i][j]=word_scanned[j]; is the answer.

But also read about strncpy, and also FYI fscanf(fptr,"%s", word_scanned); is not safer than directly scanning into fscanf(fptr,"%s", dict[i]); because word_scanned is 50 bytes long, too. Any string longer than 50 characters will cause memory error, so this additional buffer does not help at all.


问:
Image is visible but text is not visible in ListView
I am trying to create a custom layout for list view in android studio. I was able to successfully get image in the in ListView on runtime but wasn't able to print text in the list view . When i run my program in emulator it runs without any error but it doesn't show any text it only shows image from drawables.

MainActivity.java

```<code>    import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    private final  static String[] names={"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A",
            "A","A","A","A","A","A","A","A","A","A","A","A","A","A",};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView ls = findViewById((R.id.customlistview));
        ls.setAdapter(new CustomListAdapter(getApplicationContext(),names,R.drawable.za));
    }
}
</code>```

activity_main.xml

```<code>   <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/customlistview"
        android:layout_width="409dp"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="1dp"
        android:layout_marginBottom="1dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

CustomListAdapter.java

```<code>    import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomListAdapter extends BaseAdapter {
    private final Context context;
    private final String[] names;
    private final int image;
    private final LayoutInflater layoutInflater;

    public  CustomListAdapter(Context context,String[] names,int image) {

        this.context=context;
        this.image=image;
        this.names=names;
        layoutInflater= (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return names.length;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rootview;
        rootview = layoutInflater.inflate(R.layout.list_item_layout, null);
        TextView tv= rootview.findViewById(R.id.textView);
        ImageView iv=rootview.findViewById(R.id.imageView);
        tv.setText(names[position]);
        iv.setImageResource(image);
        return rootview;

    }
}
</code>```

list_item_layout.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:height="70dp"
        android:gravity="center"
        android:text="TextView"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_weight="2"
        app:srcCompat="@mipmap/ic_launcher" />
</LinearLayout>
</code>```

答:
The issue is in your list_item_layout file. There is an issue with match_parent in your layout try using below code

```<code> <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="3"
android:orientation="horizontal">

<TextView
    android:id="@+id/textView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:height="70dp"
    android:gravity="center"
    android:text="TextView"
    android:textSize="18sp" />

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="70dp"
    android:layout_weight="2"
    app:srcCompat="@mipmap/ic_launcher" />
</code>```

Body:
I am trying to create a custom layout for list view in android studio. I was able to successfully get image in the in ListView on runtime but wasn't able to print text in the list view . When i run my program in emulator it runs without any error but it doesn't show any text it only shows image from drawables.

MainActivity.java

    import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    private final  static String[] names={"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A",
            "A","A","A","A","A","A","A","A","A","A","A","A","A","A",};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView ls = findViewById((R.id.customlistview));
        ls.setAdapter(new CustomListAdapter(getApplicationContext(),names,R.drawable.za));
    }
}

activity_main.xml

   <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/customlistview"
        android:layout_width="409dp"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="1dp"
        android:layout_marginBottom="1dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

CustomListAdapter.java

    import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomListAdapter extends BaseAdapter {
    private final Context context;
    private final String[] names;
    private final int image;
    private final LayoutInflater layoutInflater;

    public  CustomListAdapter(Context context,String[] names,int image) {

        this.context=context;
        this.image=image;
        this.names=names;
        layoutInflater= (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return names.length;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rootview;
        rootview = layoutInflater.inflate(R.layout.list_item_layout, null);
        TextView tv= rootview.findViewById(R.id.textView);
        ImageView iv=rootview.findViewById(R.id.imageView);
        tv.setText(names[position]);
        iv.setImageResource(image);
        return rootview;

    }
}

list_item_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:height="70dp"
        android:gravity="center"
        android:text="TextView"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_weight="2"
        app:srcCompat="@mipmap/ic_launcher" />
</LinearLayout>

Body:
The issue is in your list_item_layout file. There is an issue with match_parent in your layout try using below code

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="3"
android:orientation="horizontal">

<TextView
    android:id="@+id/textView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:height="70dp"
    android:gravity="center"
    android:text="TextView"
    android:textSize="18sp" />

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="70dp"
    android:layout_weight="2"
    app:srcCompat="@mipmap/ic_launcher" />


问:
NSPredicate with Multiple Conditions
I am trying to create a NSPredicate with multiple conditions. I've found several solutions, but none of them appear to be working with my method. The best looking one I've found is below.

This is my single predicate method, and it works just fine:

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@",
searchText];
filteredBusinesses = [businesses filteredArrayUsingPredicate:predicate];
</code>```

Here is my edited version with multiple conditions. I'm not sure whats going wrong. Any ideas?

```<code>NSPredicate *p1 = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
NSPredicate *p2 = [NSPredicate predicateWithFormat:@"businessArea contains[c] %@",
searchText];

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[p1, p2]];
filteredBusinesses = [businesses filteredArrayUsingPredicate:predicate];
</code>```

答:
NSCompoundPredicate received a facelift. Just in case someone's looking for a Swift 5+ version:

AND

```<code>let predicatesAND = NSCompoundPredicate(andPredicateWithSubpredicates:[pred1,pred2])
</code>```

OR

```<code>let predicatesOR = NSCompoundPredicate(orPredicateWithSubpredicates:[pred1,pred2])
</code>```

Title: NSPredicate with Multiple Conditions

Body:
I am trying to create a NSPredicate with multiple conditions. I've found several solutions, but none of them appear to be working with my method. The best looking one I've found is below.

This is my single predicate method, and it works just fine:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@",
searchText];
filteredBusinesses = [businesses filteredArrayUsingPredicate:predicate];

Here is my edited version with multiple conditions. I'm not sure whats going wrong. Any ideas?

NSPredicate *p1 = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
NSPredicate *p2 = [NSPredicate predicateWithFormat:@"businessArea contains[c] %@",
searchText];

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[p1, p2]];
filteredBusinesses = [businesses filteredArrayUsingPredicate:predicate];

Body:
NSCompoundPredicate received a facelift. Just in case someone's looking for a Swift 5+ version:

AND

let predicatesAND = NSCompoundPredicate(andPredicateWithSubpredicates:[pred1,pred2])

OR

let predicatesOR = NSCompoundPredicate(orPredicateWithSubpredicates:[pred1,pred2])


问:
Input control in Angular: invalid input not detected
I'm using Angular 8 for my client application.
I want an error message to be displayed under the input box for the user when she inserts a wrong input. I'm using this inside my HTML:

```<code>  <!-- Score input -->
  <div class="form-group">
    <label for="score">Score</label>
    <input type="number" class="form-control"
           placeholder="0.0 ÷ 10.0"
           min="0.0" max="10.0" step="0.1" name="score"
           id="score"
           [(ngModel)]="model.score"
           #score="ngModel">
    <div [hidden]="score.valid" class="alert alert-danger">
      Insert a value between 0.0 and 10.0
    </div>
  </div>
</code>```

I would expect it to be displayed if the user was to input "asdf" for example instead of a number like "6.7". But it never appears. I tried removing [hidden]="score.valid" and it gets correctly displayed. Why is Angular considering "asdf" a valid input even if I set all those attributes: type="number" min="0.0" max="10.0" step="0.1" ?

答:
Input fields of type number allow users to type in characters that are not part of a number. See here for details.

I do not see how you handle setting the value of score.valid variable. However, it can be achieved by using CSS pseudo classes.

input:invalid+span:after {
  content: 'Insert a value between 0.0 and 10.0';
  padding-left: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Score input -->
<div class="form-group">
  <label for="score">Score</label>
  <input id="input-validator" type="number" class="form-control"
         placeholder="0.0 ÷ 10.0"
         min="0.0" max="10.0" step="0.1" name="score"
         id="score"
         [(ngModel)]="model.score"
         #score="ngModel">
  <span class="alert alert-danger"></span>
</div></code>```

Update: To include 'Submit' button.

Template:

```<code><form  #scoreValue="ngForm" (ngSubmit)="submitScore(scoreValue.value)">

  <label>Score: </label>
  <input type="number" class="form-control" (keyup)="onKeyUp($event)"
    placeholder="0.0 ÷ 10.0"
    [min]="min" [max]="max" [step]="step" name="score"
    id="score"
    [(ngModel)]="score"/>
  <span class="alert alert-danger"></span>
  <br /><br />
  <span> Does not work as expected -> </span>
  <button [disabled]="scoreValue.invalid">Submit</button>
  <br /><br />
  <span> Works as expected -> </span>
  <button [disabled]="disableSubmit">Submit</button>

</form>
</code>```

Component:

```<code>public onKeyUp(event){
  let score = event.currentTarget.value;
  if ((score === '') || ((score.split('.')[1] || []).length > 1)) {
    this.disableSubmit = true;
  } else {
    score = Number(score);
    if ((score >= this.min) && (score <= this.max)) {
      this.disableSubmit = false;
    } else {
      this.disableSubmit = true;
    }
  }
}
</code>```

Working example: Stackblitz

The min and max attributes set only the minimum and maximum values of the stepper arrows. That is why scoreValue.invalid does not work as expected.

Body:
I'm using Angular 8 for my client application.
I want an error message to be displayed under the input box for the user when she inserts a wrong input. I'm using this inside my HTML:

    Score
    <input type="number" class="form-control"
           placeholder="0.0 ÷ 10.0"
           min="0.0" max="10.0" step="0.1" name="score"
           id="score"
           [(ngModel)]="model.score"
           #score="ngModel">

      Insert a value between 0.0 and 10.0

I would expect it to be displayed if the user was to input "asdf" for example instead of a number like "6.7". But it never appears. I tried removing [hidden]="score.valid" and it gets correctly displayed. Why is Angular considering "asdf" a valid input even if I set all those attributes: type="number" min="0.0" max="10.0" step="0.1" ?

Body:
Input fields of type number allow users to type in characters that are not part of a number. See here for details.

I do not see how you handle setting the value of score.valid variable. However, it can be achieved by using CSS pseudo classes.

input:invalid+span:after {
  content: 'Insert a value between 0.0 and 10.0';
  padding-left: 5px;
}

<!-- Score input -->
<div class="form-group">
  <label for="score">Score</label>
  <input id="input-validator" type="number" class="form-control"
         placeholder="0.0 ÷ 10.0"
         min="0.0" max="10.0" step="0.1" name="score"
         id="score"
         [(ngModel)]="model.score"
         #score="ngModel">
  <span class="alert alert-danger"></span>
</div>

Update: To include 'Submit' button.

Template:

<form  #scoreValue="ngForm" (ngSubmit)="submitScore(scoreValue.value)">

  <label>Score: </label>
  <input type="number" class="form-control" (keyup)="onKeyUp($event)"
    placeholder="0.0 ÷ 10.0"
    [min]="min" [max]="max" [step]="step" name="score"
    id="score"
    [(ngModel)]="score"/>
  <span class="alert alert-danger"></span>
  <br /><br />
  <span> Does not work as expected -> </span>
  <button [disabled]="scoreValue.invalid">Submit</button>
  <br /><br />
  <span> Works as expected -> </span>
  <button [disabled]="disableSubmit">Submit</button>

</form>

Component:

public onKeyUp(event){
  let score = event.currentTarget.value;
  if ((score === '') || ((score.split('.')[1] || []).length > 1)) {
    this.disableSubmit = true;
  } else {
    score = Number(score);
    if ((score >= this.min) && (score <= this.max)) {
      this.disableSubmit = false;
    } else {
      this.disableSubmit = true;
    }
  }
}

Working example: Stackblitz

The min and max attributes set only the minimum and maximum values of the stepper arrows. That is why scoreValue.invalid does not work as expected.


问:
is it possible to make certain part of the JsonFormat datetime optional?
I have a field which is defined with the seconds part, (i.e.: "ss") as follows

```<code>@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")
private Date date;
</code>```

Is it possible to make the seconds part optional? so that both the following date String will work:

"2020-02-13T16:02:11 EST" will be parsed to "Thu Feb 13 16:02:11 EST 2020"

"2020-02-13T16:02 EST" will be parsed to "Thu Feb 13 16:02 EST 2020"

I am thinking about somethinglike (this does not work though...):
"yyyy-MM-dd'T'HH:mm[:ss] z"

thanks.

答:
I got the answer.

add a customerized Deserializer class 'DateDeserializer.class'

the DateDeserializer.class implement both pattern with and without the second part.

code sample is attched:

```<code>@JsonDeserialize(using = DateDeserializer.class)
@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")

public class DateDeserializer extends StdDeserializer<Date> {

private static final SimpleDateFormat withSeconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z");
private static final SimpleDateFormat withoutSeconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm z");

public DateDeserializer() {
    this(null);
}

public DateDeserializer(Class<?> vc) {
    super(vc);
}

@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String dateString = p.getText();
    if (dateString.isEmpty()) {
        //handle empty strings however you want,
        //but I am setting the Date objects null
        return null;
    }

    try {
        return withSeconds.parse(dateString);
    } catch (ParseException e) {
        try {
            return withoutSeconds.parse(dateString);
        } catch (ParseException e1) {
            throw new RuntimeException("Unable to parse date", e1);
        }
    }
}
}
</code>```

Body:
I have a field which is defined with the seconds part, (i.e.: "ss") as follows

@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")
private Date date;

Is it possible to make the seconds part optional? so that both the following date String will work:

"2020-02-13T16:02:11 EST" will be parsed to "Thu Feb 13 16:02:11 EST 2020"

"2020-02-13T16:02 EST" will be parsed to "Thu Feb 13 16:02 EST 2020"

I am thinking about somethinglike (this does not work though...):
"yyyy-MM-dd'T'HH:mm[:ss] z"

thanks.

Body:
I got the answer.

add a customerized Deserializer class 'DateDeserializer.class'

the DateDeserializer.class implement both pattern with and without the second part.

code sample is attched:

@JsonDeserialize(using = DateDeserializer.class)
@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")

public class DateDeserializer extends StdDeserializer<Date> {

private static final SimpleDateFormat withSeconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z");
private static final SimpleDateFormat withoutSeconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm z");

public DateDeserializer() {
    this(null);
}

public DateDeserializer(Class<?> vc) {
    super(vc);
}

@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    String dateString = p.getText();
    if (dateString.isEmpty()) {
        //handle empty strings however you want,
        //but I am setting the Date objects null
        return null;
    }

    try {
        return withSeconds.parse(dateString);
    } catch (ParseException e) {
        try {
            return withoutSeconds.parse(dateString);
        } catch (ParseException e1) {
            throw new RuntimeException("Unable to parse date", e1);
        }
    }
}
}


问:
Passing an array through params as multiple parameters
If I have a method like this:

```<code>Foo(params string[] parameters)
</code>```

I would like to pass in both "regular parameters" and an array in a single call like this:

```<code>string[] myArray = new[] { "param3", "param4" };
Foo("param1", "param2", myArray);
</code>```

such that it is equivalent to this:

```<code>Foo("param1", "param2", "param3", "param4");
</code>```

Is there a function I can call on the array or some sort of way that I can modify my Foo method? Currently I'm doing something like this:

```<code>string[] myArray = new[] { "param3", "param4" };
List<string> arguments = new List<string>
{
  "param1",
  "param2"
};
arguments.AddRange(myArray);
Foo(arguments.ToArray());
</code>```

but I'm wondering if there's a better way

答:
If by "regular" parameters you mean separately defined arguments with names, and you want them to be optional, then we can define them with default values. Then we can define the last one as a params array (which may also be null or empty):

```<code>public static void Foo(string first = null, string second = null, params string[] others)
</code>```

Now we can call the method as you described (the first two arguments are optional, followed by zero-to-many string arguments in the params array):

```<code>Foo();
Foo("param1");
Foo("param1", "param2");
Foo("param1", "param2", "param3");
Foo("param1", "param2", "param3", "param4");  // etc...

// Or call it with two regular arguments and an array
var myArray = new[] {"param3", "param4"};
Foo("param1", "param2", myArray);
</code>```

The one thing we can't do in this case is pass in just an array, or just one of the strings and an array, unless we used the named argument syntax:

```<code>Foo("param1", others:myArray); // Don't have to name the first one if we place it first
Foo(second:"param2", others:myArray);
Foo(others:myArray);
</code>```

Body:
If I have a method like this:

Foo(params string[] parameters)

I would like to pass in both "regular parameters" and an array in a single call like this:

string[] myArray = new[] { "param3", "param4" };
Foo("param1", "param2", myArray);

such that it is equivalent to this:

Foo("param1", "param2", "param3", "param4");

Is there a function I can call on the array or some sort of way that I can modify my Foo method? Currently I'm doing something like this:

string[] myArray = new[] { "param3", "param4" };
List<string> arguments = new List<string>
{
  "param1",
  "param2"
};
arguments.AddRange(myArray);
Foo(arguments.ToArray());

but I'm wondering if there's a better way

Body:
If by "regular" parameters you mean separately defined arguments with names, and you want them to be optional, then we can define them with default values. Then we can define the last one as a params array (which may also be null or empty):

public static void Foo(string first = null, string second = null, params string[] others)

Now we can call the method as you described (the first two arguments are optional, followed by zero-to-many string arguments in the params array):

Foo();
Foo("param1");
Foo("param1", "param2");
Foo("param1", "param2", "param3");
Foo("param1", "param2", "param3", "param4");  // etc...

// Or call it with two regular arguments and an array
var myArray = new[] {"param3", "param4"};
Foo("param1", "param2", myArray);

The one thing we can't do in this case is pass in just an array, or just one of the strings and an array, unless we used the named argument syntax:

Foo("param1", others:myArray); // Don't have to name the first one if we place it first
Foo(second:"param2", others:myArray);
Foo(others:myArray);


问:
Firebase database rules that prevent any write but only allow delete?
Is there any option to create a rule that prevent any writes or updates, but only allow delete nodes ?

My example is that i want to create cupon codes for game, so if i create a cupon in database, everyone will be able to read this and access it but when first person will use it in-game he will also delete this cupon in database. I can create that but in this case everyone can also create new nodes in database, and i dont want that because everyone can fully spam my base.

Hope anyone will understand what i mean.

Edit: i'm working in realtime db

Regards

答:
To allow writing initial data, and deleting data, but not updating it:</p>

```<code>"(!data.exists() &&  newData.exists()) ||
 ( data.exists() && !newData.exists())"
</code>```

Body:
To allow writing initial data, and deleting data, but not updating it:

"(!data.exists() &&  newData.exists()) ||
 ( data.exists() && !newData.exists())"


问:
Getting errors with os.listdir within flask and heroku
I have an application that, takes the url and returns a files corresponding to it. I wanted to push it on heroku but i get this error :
 **File "/app/server.py", line 1525, in upload1

```<code>music = os.listdir(foldername)
</code>```

FileNotFoundError: [Errno 2] No such file or directory: 'favicon.ico'**

Then i tried to add favicon.ico in all of the folders and i am getting

**File "/app/server.py", line 1525, in upload1

```<code>music = os.listdir(foldername)
</code>```

NotADirectoryError: [Errno 20] Not a directory: 'favicon.ico'**

The part where it looks to struggle is

    @app.route('/<path:foldername>')
    def upload1(foldername):
        music = os.listdir(foldername)
        print(music)
        path_to_file = music[0]

        return send_file(
        foldername+"/"+path_to_file,
        mimetype="audio/mp3",
        as_attachment=True,
        attachment_filename=path_to_file )

```

答:
what you can do is, you have to set UPLOAD_FOLDER path in config like.

UPLOAD_FOLDER = "your folder name"
then you can get the file path like.

file_path = os.path.abspath(os.path.join(app.config["UPLOAD_FOLDER"], filename))

you can get more information from here

Body:
I have an application that, takes the url and returns a files corresponding to it. I wanted to push it on heroku but i get this error :
 **File "/app/server.py", line 1525, in upload1

music = os.listdir(foldername)

FileNotFoundError: [Errno 2] No such file or directory: 'favicon.ico'**

Then i tried to add favicon.ico in all of the folders and i am getting

**File "/app/server.py", line 1525, in upload1

music = os.listdir(foldername)

NotADirectoryError: [Errno 20] Not a directory: 'favicon.ico'**

The part where it looks to struggle is

    @app.route('/<path:foldername>')
    def upload1(foldername):
        music = os.listdir(foldername)
        print(music)
        path_to_file = music[0]

        return send_file(
        foldername+"/"+path_to_file,
        mimetype="audio/mp3",
        as_attachment=True,
        attachment_filename=path_to_file )


问:
Dotnet publish looking for dependency in Debug directory instead of Release
I have a project Project.Api that references another project Project.DomainModel. When I build the API project for release by running

```<code>dotnet restore && dotnet build -c Release
</code>```

It builds successfully. However, when I try to publish

```<code> dotnet publish -c Release -o published --no-restore --no-build ./Project.Api
</code>```

I get this error:

```<code>/usr/local/share/dotnet/sdk/2.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.Publish.targets(168,5): error MSB3030: Could not copy the file "xxxx/Project.DomainModels/bin/Debug/netcoreapp2.1/Project.DomainModels.dll" because it was not found. [xxxx/Project.Api/Project.Api.csproj]
</code>```

According to the error, it's looking for the referenced project in the Debug directory, but of course it won't find it there because it will be in the Release directory.

Project.Api.csproj file looks like this:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="8.0.0" />
  </ItemGroup>
  <ItemGroup>
      <ProjectReference Include="..\Project.DomainModels\Project.DomainModels.csproj" />
  </ItemGroup>
</Project>
</code>```

Any idea why it is looking in the Debug directory instead of Release?
Getting this on both a Mac and linux machine.

答:
tl;dr Create a Release publish profile with a <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration> property and also specify the publish profile in the dotnet publish command, i.e.,

```<code>dotnet publish -c Release /p:PublishProfile=Release -o published --no-restore --no-build ./Project.Api
</code>```

I know this is an old question, but in case anyone else runs into it, I had a similar issue, and in my case, the solution was to make sure I had a Release publish profile, or create one if I did not.  The publish profile contains a LastUsedBuildConfiguration property with a value of Release, which seems to be the key issue.

Essentially, dotnet publish -c Release says we will build and then publish the Release build configuration.  When we also specify --no-build, we are saying to skip the build step.  So, we specify a build configuration to use, then tell it not to build.

Enter the LastUsedBuildConfiguration property.  This property can be set in a publish profile, or is set dynamically by MSBuild during the build step.  I haven't delved too far into the SDK, but here's what I suspect is happening.  Since we're skipping the build step, LastUsedBuildConfiguration is not being set and is therefore not available to dotnet publish.  In this case, dotnet publish assumes its default build configuration, which is Debug.

To test this, I ran the following dotnet publish commands:

When I run this command, it looks in bin/Debug (no PublishProfile specified):

```<code>dotnet publish -c Release --no-restore --no-build
</code>```

When I run this command, it looks in bin/Debug (PublishProfile, but no -c Release):

```<code>dotnet publish --no-restore --no-build /p:PublishProfile=Release
</code>```

When I run this command, it finally looks in bin/Release (both -c Release and PublishProfile):

```<code>dotnet publish -c Release --no-restore --no-build /p:PublishProfile=Release
</code>```

Only in the last case, when both -c Release and /p:PublishProfile=Release was dotnet publish using the bin/Release directory.

That sorted it for me, hope it helps someone else out as well.

Body:
I have a project Project.Api that references another project Project.DomainModel. When I build the API project for release by running

dotnet restore && dotnet build -c Release

It builds successfully. However, when I try to publish

 dotnet publish -c Release -o published --no-restore --no-build ./Project.Api

I get this error:

/usr/local/share/dotnet/sdk/2.1.302/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.Publish.targets(168,5): error MSB3030: Could not copy the file "xxxx/Project.DomainModels/bin/Debug/netcoreapp2.1/Project.DomainModels.dll" because it was not found. [xxxx/Project.Api/Project.Api.csproj]

According to the error, it's looking for the referenced project in the Debug directory, but of course it won't find it there because it will be in the Release directory.

Project.Api.csproj file looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="8.0.0" />
  </ItemGroup>
  <ItemGroup>
      <ProjectReference Include="..\Project.DomainModels\Project.DomainModels.csproj" />
  </ItemGroup>
</Project>

Any idea why it is looking in the Debug directory instead of Release?
Getting this on both a Mac and linux machine.

Body:
tl;dr Create a Release publish profile with a <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration> property and also specify the publish profile in the dotnet publish command, i.e.,

dotnet publish -c Release /p:PublishProfile=Release -o published --no-restore --no-build ./Project.Api

I know this is an old question, but in case anyone else runs into it, I had a similar issue, and in my case, the solution was to make sure I had a Release publish profile, or create one if I did not.  The publish profile contains a LastUsedBuildConfiguration property with a value of Release, which seems to be the key issue.

Essentially, dotnet publish -c Release says we will build and then publish the Release build configuration.  When we also specify --no-build, we are saying to skip the build step.  So, we specify a build configuration to use, then tell it not to build.

Enter the LastUsedBuildConfiguration property.  This property can be set in a publish profile, or is set dynamically by MSBuild during the build step.  I haven't delved too far into the SDK, but here's what I suspect is happening.  Since we're skipping the build step, LastUsedBuildConfiguration is not being set and is therefore not available to dotnet publish.  In this case, dotnet publish assumes its default build configuration, which is Debug.

To test this, I ran the following dotnet publish commands:

When I run this command, it looks in bin/Debug (no PublishProfile specified):

dotnet publish -c Release --no-restore --no-build

When I run this command, it looks in bin/Debug (PublishProfile, but no -c Release):

dotnet publish --no-restore --no-build /p:PublishProfile=Release

When I run this command, it finally looks in bin/Release (both -c Release and PublishProfile):

dotnet publish -c Release --no-restore --no-build /p:PublishProfile=Release

Only in the last case, when both -c Release and /p:PublishProfile=Release was dotnet publish using the bin/Release directory.

That sorted it for me, hope it helps someone else out as well.


问:
Copy and rename a file every minute
So I am trying to copy files from a folder to another one. The files in this folder are overwritten every minute by another program. I want to get a copy of each file every minute before it gets overwritten and save it somewhere else. See example structure below:

```<code>Folder 1 # gets overwritten every minute
a.txt
a_backup.txt

Folder 2
a1.txt
a1_backup.txt
a2.txt
a2_backup.txt
a3.txt
a3_backup.txt
a4.txt
a4_backup.txt
</code>```

It would be even better if the files in Folder 2 would contain the date and time of when they were copied in their names.
I came up with the following:

```<code>$Source = 'C:\Users\Source'
$Destination = 'C:\Users\Target'
Do{
Copy-Item $Source\* -Destination $Destination
sleep -s 59
} while($true)

</code>```

However, this does not do the job completely as I am only copying the file once and then copy the same file again when it's overwritten...

Any help is warmly welcome!

答:
New on giving answers but here's my proposal.

Get Content , and out to another file with current time as of writing maybe? Of course include your loop around it

```<code> Get-Content C:\log.txt | Out-File "Log.$([System.Math]::Round((date -UFormat %s),0)).txt""
</code>```

Title: Copy and rename a file every minute

Body:
So I am trying to copy files from a folder to another one. The files in this folder are overwritten every minute by another program. I want to get a copy of each file every minute before it gets overwritten and save it somewhere else. See example structure below:

Folder 1 # gets overwritten every minute
a.txt
a_backup.txt

Folder 2
a1.txt
a1_backup.txt
a2.txt
a2_backup.txt
a3.txt
a3_backup.txt
a4.txt
a4_backup.txt

It would be even better if the files in Folder 2 would contain the date and time of when they were copied in their names.
I came up with the following:

$Source = 'C:\Users\Source'
$Destination = 'C:\Users\Target'
Do{
Copy-Item $Source\* -Destination $Destination
sleep -s 59
} while($true)

However, this does not do the job completely as I am only copying the file once and then copy the same file again when it's overwritten...

Any help is warmly welcome!

Body:
New on giving answers but here's my proposal.

Get Content , and out to another file with current time as of writing maybe? Of course include your loop around it

 Get-Content C:\log.txt | Out-File "Log.$([System.Math]::Round((date -UFormat %s),0)).txt""


答:
```<code>Get-ChildItem -Path $source | % { copy-item $_.FullName -Destination "$Destination\$((Get-Date).ToString("MMddyyyy-hhmmss"))$($_.Name)" }
</code>```

This statement will take care of it but what it will not do is hide the exceptions and failures you will get while the file is being written to.

$_.FullName includes the full path.. can be used as source

$_.Name gives you the filename only (without the path)

(Get-Date).ToString("MMddyyyy-hhmmss") gives you the date in format specified in ToString(). Since the file is updated every minute, you will need to include the minutes and seconds in your filename as well.

Title: Copy and rename a file every minute

Body:
Get-ChildItem -Path $source | % { copy-item $_.FullName -Destination "$Destination\$((Get-Date).ToString("MMddyyyy-hhmmss"))$($_.Name)" }

This statement will take care of it but what it will not do is hide the exceptions and failures you will get while the file is being written to.

$_.FullName includes the full path.. can be used as source

$_.Name gives you the filename only (without the path)

(Get-Date).ToString("MMddyyyy-hhmmss") gives you the date in format specified in ToString(). Since the file is updated every minute, you will need to include the minutes and seconds in your filename as well.


问:
Selenium xpath issue
I am having a very strange issue using selenium and xpath. I am having a page that renders 25 's with nested  tags. I need to get using findElements() all this elements. If i get the page source and search trough the text the following substring: "alt="Expand List"" i get 25 appearances. But when i execute the command let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]")) I get 32 items. I logged the items in google chrome and to the list are added 's that contain images with different alt values. Any ideas? The piece of code:

```<code>    let text = await driver.getPageSource();
    var count = (text.match(/alt="Expand List"/g) || []).length;
    let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]"))
    console.log(count, items.length); //outputs 25, 32
</code>```

And this image with the alt Collapse List appears in a

答:
Your xpath should be more like:

```<code>//a/img[contains(@alt,'Expand List')]
</code>```

One slash indicates it's a child of the parent //a.

I highly recommend getting a brower addon to test xpaths. One that I use almost everyday is ChroPath. You can also test xpaths in the devtools console with something like

```<code>$x('//a/img[contains(@alt,'Expand List')]')
</code>```

Will give output like this:

Title: Selenium xpath issue

Body:
I am having a very strange issue using selenium and xpath. I am having a page that renders 25 's with nested  tags. I need to get using findElements() all this elements. If i get the page source and search trough the text the following substring: "alt="Expand List"" i get 25 appearances. But when i execute the command let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]")) I get 32 items. I logged the items in google chrome and to the list are added 's that contain images with different alt values. Any ideas? The piece of code:

    let text = await driver.getPageSource();
    var count = (text.match(/alt="Expand List"/g) || []).length;
    let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]"))
    console.log(count, items.length); //outputs 25, 32

And this image with the alt Collapse List appears in a

Body:
Your xpath should be more like:

//a/img[contains(@alt,'Expand List')]

One slash indicates it's a child of the parent //a.

I highly recommend getting a brower addon to test xpaths. One that I use almost everyday is ChroPath. You can also test xpaths in the devtools console with something like

$x('//a/img[contains(@alt,'Expand List')]')

Will give output like this:


问:
View version control progress graphically
Is there a software for mac that lets me view the progress of the branches in either git or svn like in this image (from here)

答:
Git Web Access implements a new kind of visualization which is inspired by schacon's drawings in ProGit.

Note: Although not a desktop application, it should work on a Mac (with some help from Safari) ;-)

See below an example:


问:
Is it possible to "disable" the period key in a HTML number field using an Android soft keyboard on an Android Web View html5 app?
When I check the keyCodes on the softKeyboard for .-  , the e.key in JavaScript is "Unidentified" and the e.keyCode is 229 for all of those characters.

The device I am using is a TC52k scanner and the scan trigger has the same key and keyCode... so it can't be completely disabled.

I don't know how many things I tried that didn't work... but I will post some...

This is a dynamic field bound with rivets.js using JSON objects

```<code>$(document).on("keydown", ".qty-input", function(e) {
    let code = e.keyCode;
    if (code == 229 && $(this).val().charAt(str.length - 1) == ".") {
        $(this).val($(this).val().slice(0, -1));
    }
});
</code>```

^Basically, that says that if the last character has the code 229 and the last character of the entered string is a '.', then cut the last character off... but doesn't work correctly.

I also did this that basically says to only accept keys that have keycodes between 48 and 57 which are keys 1-9 on the android soft keyboard.

```<code><input class="qty-input" placeholder="0" type="number" min="0" step="1" onkeypress="return event.charCode >= 48 && event.charCode <= 57 && event.keyCode != 229" pattern="[0-9]*" autofocus>
</code>```

Also didn't work...

Does anyone have experience with this and can help?
I know there's lots of unsolved posts about this online.
It's the last thing I have to do and its keeping my app from being deployed!

Also... I've tried these function using events: keyup, keydown, change, input and keypress...

答:
Here is the best workaround that I found (since 229 also triggers the 'scanner' trigger, I have to detect whether a string includes a barcode and a quantity and will have to separate the two(the keyCode for a [.] again is the same as the keyCode for the scanner trigger))
The 2 conditions determine 2 things:

If the value is longer than 3, then it is not allowed as a quantity because the quantity can not be over '500', so when it has a length longer than 5, it is considered to be a barcode.

```<code>let oldVal = '';
let newVal = '';
let barcode = '';
$(document).on("keydown", "input.received-qty", function(e) {
    let code = e.keyCode || e.which || e.charCode;
    oldVal = $(this).val();
});

$(document).on("keyup", "input.received-qty", function(e) {
    let code = e.keyCode || e.which || e.charCode;
    newVal = $(this).val();
    if (code == 229 && e.target.value.length >= 3) {
        barcode = $(this).val().slice(oldVal.length - 1, -1);
        $(this).val(oldVal);
    } else if (code == 229 && e.target.value.length <= 3) {
        let x = oldVal.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
        $(this).val('');
        $(this).val(x);
    }
    console.log("oldVal : ", "[", oldVal, "]", "newVal : ", "[", $(this).val(), "]");
});
</code>```

This is the best way I've tried so far.

Body:
When I check the keyCodes on the softKeyboard for .-  , the e.key in JavaScript is "Unidentified" and the e.keyCode is 229 for all of those characters.

The device I am using is a TC52k scanner and the scan trigger has the same key and keyCode... so it can't be completely disabled.

I don't know how many things I tried that didn't work... but I will post some...

This is a dynamic field bound with rivets.js using JSON objects

$(document).on("keydown", ".qty-input", function(e) {
    let code = e.keyCode;
    if (code == 229 && $(this).val().charAt(str.length - 1) == ".") {
        $(this).val($(this).val().slice(0, -1));
    }
});

^Basically, that says that if the last character has the code 229 and the last character of the entered string is a '.', then cut the last character off... but doesn't work correctly.

I also did this that basically says to only accept keys that have keycodes between 48 and 57 which are keys 1-9 on the android soft keyboard.

<input class="qty-input" placeholder="0" type="number" min="0" step="1" onkeypress="return event.charCode >= 48 && event.charCode <= 57 && event.keyCode != 229" pattern="[0-9]*" autofocus>

Also didn't work...

Does anyone have experience with this and can help?
I know there's lots of unsolved posts about this online.
It's the last thing I have to do and its keeping my app from being deployed!

Also... I've tried these function using events: keyup, keydown, change, input and keypress...

Body:
Here is the best workaround that I found (since 229 also triggers the 'scanner' trigger, I have to detect whether a string includes a barcode and a quantity and will have to separate the two(the keyCode for a [.] again is the same as the keyCode for the scanner trigger))
The 2 conditions determine 2 things:

If the value is longer than 3, then it is not allowed as a quantity because the quantity can not be over '500', so when it has a length longer than 5, it is considered to be a barcode.

let oldVal = '';
let newVal = '';
let barcode = '';
$(document).on("keydown", "input.received-qty", function(e) {
    let code = e.keyCode || e.which || e.charCode;
    oldVal = $(this).val();
});

$(document).on("keyup", "input.received-qty", function(e) {
    let code = e.keyCode || e.which || e.charCode;
    newVal = $(this).val();
    if (code == 229 && e.target.value.length >= 3) {
        barcode = $(this).val().slice(oldVal.length - 1, -1);
        $(this).val(oldVal);
    } else if (code == 229 && e.target.value.length <= 3) {
        let x = oldVal.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
        $(this).val('');
        $(this).val(x);
    }
    console.log("oldVal : ", "[", oldVal, "]", "newVal : ", "[", $(this).val(), "]");
});

This is the best way I've tried so far.


问:
Phantom compile errors after upgrading NuGet package
I had a Microsoft WebForms report viewer library version 10 referenced in my project, and I decided to remove that reference and add the version 150 NuGet package. However now I get a bunch of compile errors like so:

Error CS0246  The type or namespace name 'LocalReport' could not be found (are you missing a using directive or an assembly reference?)

and other similar errors. The weird thing is, when I open up the files containing the errors, the errors go away, but as soon as I try to build my project, they reappear! What's going on here? How can I compile my project without errors?

答: The problem was that the report viewer library I added the reference to required .NET Framework version 4.6, but my projects were only using version 4.51. Upgrading to v4.7 solved the problem.</p>