问:
How to detect focus on link elements and form input fields when activated with Tab key?
I want to detect when user focuses a link or input field by pressing the Tab key. Does anyone know of a way to do this? I have tried using the onFocus event, but it does not seem to work.

(I am not using jQuery, and I want to detect focus on links as well, so the similar question 16144611 is not the same as this one.)

答:
By combining keyUp and document.activeElement we can see if an element is currently focused.

We then need to look for the Tab key on keyup and you have a reasonable start at a solution.

const els = document.querySelectorAll('a, input');

window.addEventListener('keyup', function(e){
   // check the key code
   const code = (e.keyCode ? e.keyCode : e.which);
   if(code == 9 && els.length){
     checkFocus();
   }

});

function checkFocus(){
   // loop all elements (within our selector at the start) and see if they match the document.activeElement
   for (const el of els) {
     if(document.activeElement == el){
       console.log("focused tag:" + el.tagName);
     }
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Click me for focus, I am not checked</button>
Focused Link
<label for="input1">I am also reported</label>
<input id="input1">
<button>Another button not announced</button></code>```

Note that if you only ever want to check for links and inputs only a more efficient way to check would be:

const els = ['A', 'INPUT'];

window.addEventListener('keyup', function(e){
   // check the key code
   const code = (e.keyCode ? e.keyCode : e.which);
   if(code == 9 && els.length){
     checkFocus();
   }

});

function checkFocus(){
   // by checking the tagName we only have to do 2 loops no matter how many links or inputs there are on a page, which is far more efficient. The downside is it will check **every** link and input on the page. You would access the element with document.activeElelemnt instead if you need to know which item was focused.
   for (const el of els) {
     if(document.activeElement.tagName == el){
       console.log("focused tag:" + document.activeElement.tagName);
     }
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Click me for focus, I am not checked</button>
Focused Link
<label for="input1">I am also reported</label>
<input id="input1">
<button>Another button not announced</button></code>```

Body:
By combining keyUp and document.activeElement we can see if an element is currently focused.

We then need to look for the Tab key on keyup and you have a reasonable start at a solution.

const els = document.querySelectorAll('a, input');

window.addEventListener('keyup', function(e){
   // check the key code
   const code = (e.keyCode ? e.keyCode : e.which);
   if(code == 9 && els.length){
     checkFocus();
   }

});

function checkFocus(){
   // loop all elements (within our selector at the start) and see if they match the document.activeElement
   for (const el of els) {
     if(document.activeElement == el){
       console.log("focused tag:" + el.tagName);
     }
   }
}

<button>Click me for focus, I am not checked</button>
<a href="#">Focused Link</a>
<label for="input1">I am also reported</label>
<input id="input1">
<button>Another button not announced</button>

Note that if you only ever want to check for links and inputs only a more efficient way to check would be:

const els = ['A', 'INPUT'];

window.addEventListener('keyup', function(e){
   // check the key code
   const code = (e.keyCode ? e.keyCode : e.which);
   if(code == 9 && els.length){
     checkFocus();
   }

});

function checkFocus(){
   // by checking the tagName we only have to do 2 loops no matter how many links or inputs there are on a page, which is far more efficient. The downside is it will check **every** link and input on the page. You would access the element with document.activeElelemnt instead if you need to know which item was focused.
   for (const el of els) {
     if(document.activeElement.tagName == el){
       console.log("focused tag:" + document.activeElement.tagName);
     }
   }
}

<button>Click me for focus, I am not checked</button>
<a href="#">Focused Link</a>
<label for="input1">I am also reported</label>
<input id="input1">
<button>Another button not announced</button>


来源: stackexchange

问:
Constructor signature is changed if I define case class in spark-shell (scala-shell)
I define case class in spark-shell or scala-shell, and found its constructor signature is changed, there's one extra parameter $iw added, what is that? why that happens? This issue caused me unable to create new instance via its constructor in reflection

```<code>scala> case class People(id:Int, name: String)
class People

scala> classOf[People].getDeclaredConstructors.head
val res0: java.lang.reflect.Constructor[_] = public People($iw,int,java.lang.String)
</code>```

答:
This is expected behavior in both scala-shell and spark-shell after scala 2.12. If you just use spark-shell for quick experiments, you could try spark 2.4 which relies on scala 2.11. For prod, you still can build your package by using relection on case case contructors.

For more details, please refer

snakeyaml and spark results in an inability to construct objects

Spark adds hidden parameter to constructor of a Scala class

ContentLicense: CC BY-SA 4.0

Body:
I define case class in spark-shell or scala-shell, and found its constructor signature is changed, there's one extra parameter $iw added, what is that? why that happens? This issue caused me unable to create new instance via its constructor in reflection

scala> case class People(id:Int, name: String)
class People

scala> classOf[People].getDeclaredConstructors.head
val res0: java.lang.reflect.Constructor[_] = public People($iw,int,java.lang.String)


问:
Developing Unity Game VR and non-VR
I'm new to Unity and I am confused about how to develop a game for both VR and FPS-desktop at the same time. How can I handle this?</p>

答:
this article about VR inm Unity can help you.
The good thing about Unity is that you can develop one game and deploy it on multiple diffrent plattforms without major changes.</p>

Title: Developing Unity Game VR and non-VR


问:
How to get ONLY Second line with SED
How can I get second line in a file using SED

```<code>@SRR005108.1 :3:1:643:216
GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
+
IIIIII/III*IIIIIIIIII+IIIII;IIAIII%>
</code>```

With the data that looks like above I want only to get

```<code> GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
</code>```

答:
This will print the second line of every file:

```<code>awk 'FNR==2'
</code>```

and this one only the second line of the first file:

```<code>awk 'NR==2'
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get ONLY Second line with SED

Body:
How can I get second line in a file using SED

@SRR005108.1 :3:1:643:216
GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
+
IIIIII/III*IIIIIIIIII+IIIII;IIAIII%>

With the data that looks like above I want only to get

 GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC

Body:
This will print the second line of every file:

awk 'FNR==2'

and this one only the second line of the first file:

awk 'NR==2'


问:
Unable to view Data base in data base inspector in android
Check bottom left its showing database is closed but I am still running my app</p>

答:
Weird behavior.

If I use Room (https://developer.android.com/training/data-storage/room ) to query the database, the database inspector works fine.

But if I use SQLiteDatabase to query it, the database inspector shows "closed".

By the way, you can also use Facebook's Stetho libray to show the database content in the browser. http://facebook.github.io/stetho/


问:
Delete a lot of files from Google Disk using Python
So I've downloaded a huge dataset (6GB) for training models, and I want to decrease the number of photos in each folder by 9 times (train, test and validation folders include 2 folders: MSIMUT, MSS).
I tried this code:

```<code>files = os.chdir('/content/drive/MyDrive/Kaggle_Data/tcga_coad_msi_mss/train/MSIMUT')
for file in files[:53334]:   # error
  os.remove(file)
</code>```

But it gives me an error:

TypeError: 'NoneType' object is not subscriptable

I could download all of that and remove photos manually, but downloading folders from Google disk takes like eternity, so there's no way I could use this option...

答:
NelsonGon's comment is the correct answer.  You want to do something like</p>
```<code>import os
path = '/content/drive/MyDrive/Kaggle_Data/tcga_coad_msi_mss/train/MSIMUT/'
for file in os.listdir(path)[:53334]:
    os.remove(path+file)
</code>```

Body:
So I've downloaded a huge dataset (6GB) for training models, and I want to decrease the number of photos in each folder by 9 times (train, test and validation folders include 2 folders: MSIMUT, MSS).
I tried this code:

files = os.chdir('/content/drive/MyDrive/Kaggle_Data/tcga_coad_msi_mss/train/MSIMUT')
for file in files[:53334]:   # error
  os.remove(file)

But it gives me an error:

TypeError: 'NoneType' object is not subscriptable

I could download all of that and remove photos manually, but downloading folders from Google disk takes like eternity, so there's no way I could use this option...

Body:
NelsonGon's comment is the correct answer.  You want to do something like

import os
path = '/content/drive/MyDrive/Kaggle_Data/tcga_coad_msi_mss/train/MSIMUT/'
for file in os.listdir(path)[:53334]:
    os.remove(path+file)


问:
Data frame columns Difference
I have a data frame with 3 column  FIRST, SECOND ,THIRD. i want to find the difference of first column and combination of SECOND and THIRD. and create the values in Final column.

DF1=

```<code>   FIRST                         SECOND       THIRD

  "NEWYORK" IS NICE CITY             NICE      IS CITY
  "LONDON" WINTER MUCHBETTER         LONDON     WINTER
  "CANADA" IS EVEN MORECOLDER        CANADA     IS EVEN
  "PARIS" IS  MOREBEAUTIFUL      MOREBEAUTIFUL  IS
</code>```

i want my Data frame to to look like this :

DF1=

```<code>     FIRST                         SECOND       THIRD                            FINAL
  "NEWYORK" IS NICE CITY             NICE       IS CITY                            NEWYORK
  "LONDON" WINTER MUCHBETTER         LONDON     WINTER                             MUCHBETTER
  "CANADA" IS EVEN MORECOLDER        CANADA     IS EVEN                           MORECOLDER
  "PARIS" IS  MOREBEAUTIFUL      MOREBEAUTIFUL    IS                                  PARIS
</code>```

答:
You can do this by:

```<code>import pandas as pd

# Creating the dataframe
columns = ['FIRST','SECOND','THIRD']
data = [
    ['NEWYORK IS NICE CITY', 'NICE', 'IS CITY'],
    ['LONDON WINTER MUCHBETTER', 'LONDON', 'WINTER'],
    ['CANADA IS EVEN MORECOLDER', 'CANADA', 'IS EVEN']
]

df = pd.DataFrame(data=data,columns=columns)

# Creating FINAL column
df['FINAL'] = df[['SECOND', 'THIRD']].agg(' '.join, axis=1).str.split(' ')
df['FINAL'] = df.apply(lambda x: ''.join(set(x['FIRST'].split(' ')) - set(x['FINAL'])), axis=1)
</code>```

Here what is happening is that you are first creating the FINAL column joining the SECOND and THIRD columns. Then you create a set from the FIRST column splitted by space and subtract a set created from the recently created FINAL column, which will return a set with the only word contained in FIRST but not in SECOND or THIRD.

Then all you have to do is get a string from the set, using join.

Title: Data frame columns Difference

Body:
I have a data frame with 3 column  FIRST, SECOND ,THIRD. i want to find the difference of first column and combination of SECOND and THIRD. and create the values in Final column.

DF1=

   FIRST                         SECOND       THIRD

  "NEWYORK" IS NICE CITY             NICE      IS CITY
  "LONDON" WINTER MUCHBETTER         LONDON     WINTER
  "CANADA" IS EVEN MORECOLDER        CANADA     IS EVEN
  "PARIS" IS  MOREBEAUTIFUL      MOREBEAUTIFUL  IS

i want my Data frame to to look like this :

DF1=

     FIRST                         SECOND       THIRD                            FINAL
  "NEWYORK" IS NICE CITY             NICE       IS CITY                            NEWYORK
  "LONDON" WINTER MUCHBETTER         LONDON     WINTER                             MUCHBETTER
  "CANADA" IS EVEN MORECOLDER        CANADA     IS EVEN                           MORECOLDER
  "PARIS" IS  MOREBEAUTIFUL      MOREBEAUTIFUL    IS                                  PARIS

Body:
You can do this by:

import pandas as pd

# Creating the dataframe
columns = ['FIRST','SECOND','THIRD']
data = [
    ['NEWYORK IS NICE CITY', 'NICE', 'IS CITY'],
    ['LONDON WINTER MUCHBETTER', 'LONDON', 'WINTER'],
    ['CANADA IS EVEN MORECOLDER', 'CANADA', 'IS EVEN']
]

df = pd.DataFrame(data=data,columns=columns)

# Creating FINAL column
df['FINAL'] = df[['SECOND', 'THIRD']].agg(' '.join, axis=1).str.split(' ')
df['FINAL'] = df.apply(lambda x: ''.join(set(x['FIRST'].split(' ')) - set(x['FINAL'])), axis=1)

Here what is happening is that you are first creating the FINAL column joining the SECOND and THIRD columns. Then you create a set from the FIRST column splitted by space and subtract a set created from the recently created FINAL column, which will return a set with the only word contained in FIRST but not in SECOND or THIRD.

Then all you have to do is get a string from the set, using join.


问:
Access last element of a TypeScript array
Is there a notation to access the last element of an array in TypeScript? In Ruby I can say: array[-1]. Is there something similar?

Body:
const arr = [1, 3, 6, 2];
console.log(...arr.slice(-1)); // 2


问:
django form queryset filter using request user
I want to filter queryset using current user data but it's return only a Nonetype
Suppose When I remove None its shows the error  user can't recognize

In Forms.py

```<code>class oldenquiryForm(forms.ModelForm):
    class Meta:
        model=enquiry
        fields=['product','type','created_at']
        widgets={
            'created_at':forms.DateInput(attrs={'type':'date'}),
        }
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        user = kwargs.pop('user', None)
        super(oldenquiryForm, self).__init__(*args, **kwargs)
        employee = emp.objects.filter(branch=user.admin.branch_name).values_list('firstname',flat=True)
        print (employee)
        self.fields['created_by'].queryset=emp.objects.filter(branch=user.admin.branch_name).values_list('firstname',flat=True)
</code>```

views.py

I want to get the emp data is similar to admin branch

```<code>def enquirys(request):
    if request.method=='POST':
        form=oldenquiryForm(request.POST)
        if form.is_valid():
            form.save()
    else:
         return render(request,'enquirys.html',{'form':form})
</code>```

models.py

I have linked the admin,emp to user model

```<code>class admin(models.Model):
user=models.OneToOneField(User,null=True,on_delete=models.CASCADE)
firstname=models.CharField(default='',max_length=100,null=False)
created_by=models.CharField(default='',max_length=100)
phonenumber=models.TextField(default='',null=False,unique=True)
photo=models.ImageField(upload_to='admin_photo/',default='user.jpg')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(default=timezone.now)
branch= models.ForeignKey(branch,null=True,on_delete=models.CASCADE)
branch_name= models.CharField(default='',max_length=100)
def __str__(self):
 return self.firstname

class emp(models.Model):
    user=models.OneToOneField(User,null=True,on_delete=models.CASCADE)
    firstname=models.CharField(default='',max_length=100,null=False)
    lastname=models.CharField(default='',max_length=100,null=False)
    gender=(
        ('M','Male'),
        ('F','Female'),
        ('O','Others'),
        )
    gender=models.CharField(choices=gender, default='',max_length=10)
    dob=models.DateField(default=datetime.now)
    created_by=models.CharField(default='',max_length=100)
    phonenumber=models.TextField(default='',null=False,unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(default=timezone.now)
    branch=models.CharField(default='',max_length=100)
</code>```

答:
You should call the super constructor without the user field, so removing it from the named parameters before, for example by adding user=None to the signature:

```<code>class OldEnquiryForm(forms.ModelForm):
    def __init__(self,*args, user=None, **kwargs):
        super(oldenquiryForm, self).__init__(*args, **kwargs)
        if user is not None:
            self.fields['created_by'].queryset = emp.objects.filter(branch=user.admin.branch_name)

    class Meta:
        model=enquiry
        fields=['product','type','created_at']
        widgets={
            'created_at':forms.DateInput(attrs={'type':'date'}),
        }</code>```

Then in the view, you construct the form with the logged in user as user:

```<code>from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def enquirys(request):
    if request.method == 'POST':
        form = OldEnquiryForm(request.POST, request.FILES<strong>, user=request.user</strong>)
        if form.is_valid():
            form.save()
            return redirect('<em>name-of-some-view</em>')
    else:
        form = OldEnquiryForm(<strong>user=request.user</strong>)
    return render(request,'enquirys.html',{'form':form})</code>```

Probably you should also construct a model for the branch and use a ForeignKey to implement database normalization [wiki].

Note: You can limit views to a view to authenticated users with the
@login_required decorator [Django-doc].

Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

Body:
I want to filter queryset using current user data but it's return only a Nonetype
Suppose When I remove None its shows the error  user can't recognize

In Forms.py

class oldenquiryForm(forms.ModelForm):
    class Meta:
        model=enquiry
        fields=['product','type','created_at']
        widgets={
            'created_at':forms.DateInput(attrs={'type':'date'}),
        }
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        user = kwargs.pop('user', None)
        super(oldenquiryForm, self).__init__(*args, **kwargs)
        employee = emp.objects.filter(branch=user.admin.branch_name).values_list('firstname',flat=True)
        print (employee)
        self.fields['created_by'].queryset=emp.objects.filter(branch=user.admin.branch_name).values_list('firstname',flat=True)

views.py

I want to get the emp data is similar to admin branch

def enquirys(request):
    if request.method=='POST':
        form=oldenquiryForm(request.POST)
        if form.is_valid():
            form.save()
    else:
         return render(request,'enquirys.html',{'form':form})

models.py

I have linked the admin,emp to user model

class admin(models.Model):
user=models.OneToOneField(User,null=True,on_delete=models.CASCADE)
firstname=models.CharField(default='',max_length=100,null=False)
created_by=models.CharField(default='',max_length=100)
phonenumber=models.TextField(default='',null=False,unique=True)
photo=models.ImageField(upload_to='admin_photo/',default='user.jpg')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(default=timezone.now)
branch= models.ForeignKey(branch,null=True,on_delete=models.CASCADE)
branch_name= models.CharField(default='',max_length=100)
def __str__(self):
 return self.firstname

class emp(models.Model):
    user=models.OneToOneField(User,null=True,on_delete=models.CASCADE)
    firstname=models.CharField(default='',max_length=100,null=False)
    lastname=models.CharField(default='',max_length=100,null=False)
    gender=(
        ('M','Male'),
        ('F','Female'),
        ('O','Others'),
        )
    gender=models.CharField(choices=gender, default='',max_length=10)
    dob=models.DateField(default=datetime.now)
    created_by=models.CharField(default='',max_length=100)
    phonenumber=models.TextField(default='',null=False,unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(default=timezone.now)
    branch=models.CharField(default='',max_length=100)

Body:
You should call the super constructor without the user field, so removing it from the named parameters before, for example by adding user=None to the signature:

class OldEnquiryForm(forms.ModelForm):
    def __init__(self,*args, user=None, **kwargs):
        super(oldenquiryForm, self).__init__(*args, **kwargs)
        if user is not None:
            self.fields['created_by'].queryset = emp.objects.filter(branch=user.admin.branch_name)

    class Meta:
        model=enquiry
        fields=['product','type','created_at']
        widgets={
            'created_at':forms.DateInput(attrs={'type':'date'}),
        }

Then in the view, you construct the form with the logged in user as user:

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def enquirys(request):
    if request.method == 'POST':
        form = OldEnquiryForm(request.POST, request.FILES, user=request.user)
        if form.is_valid():
            form.save()
            return redirect('name-of-some-view')
    else:
        form = OldEnquiryForm(user=request.user)
    return render(request,'enquirys.html',{'form':form})

Probably you should also construct a model for the branch and use a ForeignKey to implement database normalization [wiki].

Note: You can limit views to a view to authenticated users with the
@login_required decorator [Django-doc].

Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.


问:
Why can't I vectorize Python's datetime.utcfromtimestamp()?
I have an array of Unix timestamps.  I can run datetime.utcfromtimestamp on each entry individually, but I cannot run them all from a numpy array.  Why does that happen?

MWE

import numpy as np
from datetime import datetime

times = np.array((1524967210, 1524967211, 1524967212))

# Works
for i in times:
    print(datetime.utcfromtimestamp(times[i]))

# Does not work
print(datetime.utcfromtimestamp(times[:]))
```

The second example issues: TypeError: only integer scalar arrays can be converted to a scalar index rather than an array of times.  A Unix timestamp conversion seems straightforward to implement as a vectorized operation (see source code here), so why does it not work here?  Is there something I can do to alter this which will enable vectorized operation?

答:
You can use np.vectorize() to create a vecorized version of the function which does what you want:

import numpy as np
from datetime import datetime

times = np.array((1524967210, 1524967211, 1524967212))
func = np.vectorize(datetime.utcfromtimestamp)

print(func(times[:]))
# or
print(func(times))
```

Body:
I have an array of Unix timestamps.  I can run datetime.utcfromtimestamp on each entry individually, but I cannot run them all from a numpy array.  Why does that happen?

MWE

import numpy as np
from datetime import datetime

times = np.array((1524967210, 1524967211, 1524967212))

# Works
for i in times:
    print(datetime.utcfromtimestamp(times[i]))

# Does not work
print(datetime.utcfromtimestamp(times[:]))

The second example issues: TypeError: only integer scalar arrays can be converted to a scalar index rather than an array of times.  A Unix timestamp conversion seems straightforward to implement as a vectorized operation (see source code here), so why does it not work here?  Is there something I can do to alter this which will enable vectorized operation?


问:
Replace the first 2 lines containing a string with a specific line with a bash script
I need to replace the first 2 occurrences of:

```<code>"<version>*"
</code>```

with

```<code>"<version>$NEW_VERSION</version>"
</code>```

within an already existing xml file.

Original:

```<code><groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.0-SNAPSHOT</version>
<version>1.3.0-SNAPSHOT</version>
</code>```

Desired result:

```<code><groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>
<version>1.3.1-SNAPSHOT</version>
</code>```

I've tried for a while now and this:

```<code>sed -i -e '0,/<version>*/s/<version>*/<version>1.3.1-SNAPSHOT<\/version>/' pom.xml
</code>```

gets close, but the resulting string is:

```<code><groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>1.3.0-SNAPSHOT</version>
</code>```

答:
With awk:

```<code>$ awk -v new_version="1.3.1-SNAPSHOT" 'BEGIN {matches = 0} /^<version>/ && matches < 2 {print "<version>" new_version "</version>"; matches++; next} 1' pom.xml
<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>
<version>1.3.1-SNAPSHOT</version>
</code>```

If you have whitespaces before <version> lines like that:

```<code><groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
      <version>1.3.0-SNAPSHOT</version>
   <version>1.3.0-SNAPSHOT</version>
 <version>1.3.0-SNAPSHOT</version>
</code>```

and you want to save them:

```<code>$ awk -v new_version="1.3.1-SNAPSHOT" 'BEGIN {matches = 0} /^( *)<version>/ && matches < 2 { match($0, "^ *"); print substr($0, RSTART, RLENGTH) "<version>" new_version "</version>"; matches++; next} 1' pom.xml
<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
      <version>1.3.1-SNAPSHOT</version>
   <version>1.3.1-SNAPSHOT</version>
 <version>1.3.0-SNAPSHOT</version>
</code>```

Body:
I need to replace the first 2 occurrences of:

"<version>*"

with

"<version>$NEW_VERSION</version>"

within an already existing xml file.

Original:

<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.0-SNAPSHOT</version>
<version>1.3.0-SNAPSHOT</version>

Desired result:

<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>
<version>1.3.1-SNAPSHOT</version>

I've tried for a while now and this:

sed -i -e '0,/<version>*/s/<version>*/<version>1.3.1-SNAPSHOT<\/version>/' pom.xml

gets close, but the resulting string is:

<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>1.3.0-SNAPSHOT</version>

Body:
With awk:

$ awk -v new_version="1.3.1-SNAPSHOT" 'BEGIN {matches = 0} /^<version>/ && matches < 2 {print "<version>" new_version "</version>"; matches++; next} 1' pom.xml
<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
<version>1.3.1-SNAPSHOT</version>
<version>1.3.1-SNAPSHOT</version>

If you have whitespaces before <version> lines like that:

<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
      <version>1.3.0-SNAPSHOT</version>
   <version>1.3.0-SNAPSHOT</version>
 <version>1.3.0-SNAPSHOT</version>

and you want to save them:

$ awk -v new_version="1.3.1-SNAPSHOT" 'BEGIN {matches = 0} /^( *)<version>/ && matches < 2 { match($0, "^ *"); print substr($0, RSTART, RLENGTH) "<version>" new_version "</version>"; matches++; next} 1' pom.xml
<groupId>my.test.group</groupId>
<artifactId>maven-parent</artifactId>
      <version>1.3.1-SNAPSHOT</version>
   <version>1.3.1-SNAPSHOT</version>
 <version>1.3.0-SNAPSHOT</version>


问:
How can I set Google_application_credentials in ec2 instance?
I just installed google-cloud-vision in my ec2-instance.
To run my code, I just noticed that I sould set GOOGLE_APPLICATION_CREDENTIALS.  (error told me to set it. DefaultcredntialsError)

But I don't know how to get a json credentials and set it within my ec2.
There's a JSON key in my real computer, but how can I move it to my virtual computer?

答:
Copy the service account JSON key file to the EC2 instance using SSH file copy. Set the environment variable to the full path to the file. Make sure you understand the security risks with service account keys.

For advanced users, use Workload Identity Federation to use federate AWS credentials to Google Cloud credentials so that a service account JSON key is not required.


问:
How to ensure devenv.exe is not running when my msi is installed
I am writing a VSPackage for Visual Studio 2008, and am deploying it with a WiX generated Msi.  As the end of the install, I am running "devenv.exe /setup" as required to get VS to notice my package.  However, this command will not succeed if there are any copies of Visual Studio running.

Currently, I tell people they have to close all copies of Visual Studio before installing, but I would prefer it be foolproof.  How can I check when someone runs my .msi if any copies of Visual Studio (devenv.exe) are running, and block them from installing my project?

答: You can create an installer class in your project and let it enumerate Running Processes</p>

OwnerDisplayName: jpobst

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Akash Kava


问:
How to upload an image from a remote website, by using javascript?
Is there any way I can do that? For example, I have an

```<code><input type="file" id="upload_file" />
</code>```

Obviously I can't just

```<code>$('#upload_file').val('http://www.site.com/path/to/image.jpg').parent().submit();
</code>```

答: I can't see how you will get this to work. What server side language are you using? Would it not be better to just make a direct request for the remote file from the server?</p>

Body:
Is there any way I can do that? For example, I have an

<input type="file" id="upload_file" />

Obviously I can't just

$('#upload_file').val('http://www.site.com/path/to/image.jpg').parent().submit();


问:
How to use Regex to select multiple line
I have the following string in form of HTML Text -

```<code>=09=09=09=09=09=09=09=09=09href=3D"https://web.company.net/#/set-passwor=
d?token=3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk&region=3D"=09=09=09=09=09=09=09=09=09style=3D"height: 40px; v-text-anchor: middle; wi=
</code>```

dth: 300px"

The following string(dynamic token) needs to be extracted-

```<code>3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk
</code>```

How can this be done using Regex?

Actively looking forward to some suggestions.

Thank you

答:
A variation of @CodeMonkey answer without the need of re.MULTILINE

```<code>import re

html = '''
=09=09=09=09=09=09=09=09=09href=3D"https://web.company.net/#/set-passwor=
d?token=3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk&region=3D"=09=09=09=09=09=09=09=09=09style=3D"height: 40px; v-text-anchor: middle; wi=
dth: 300px"
'''

m = re.search(r'token=([.\s\S]+?(?=&))', html, re.+)
if m:
    print(m.group(1))
</code>```

Body:
I have the following string in form of HTML Text -

=09=09=09=09=09=09=09=09=09href=3D"https://web.company.net/#/set-passwor=
d?token=3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk&region=3D"=09=09=09=09=09=09=09=09=09style=3D"height: 40px; v-text-anchor: middle; wi=

dth: 300px"

The following string(dynamic token) needs to be extracted-

3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk

How can this be done using Regex?

Actively looking forward to some suggestions.

Thank you

Body:
A variation of @CodeMonkey answer without the need of re.MULTILINE

import re

html = '''
=09=09=09=09=09=09=09=09=09href=3D"https://web.company.net/#/set-passwor=
d?token=3DeyJ0eFtehgeRs1QiLLKDHDSiOiJIUzI1NiJ9.eyJ1dWlkIjoiZTM4ZTMwMGItNWM5=
Zi00MTg1LThhY2EtNTVkYWEwYzE1ZjIzIiwidGVybXNfYWNjZXBBDHSdndsuOIiwiaWF0IjoxNjQ=
0MzI0NDk3LCJleHAiOjE2NDQ0OTcyOTcsIm5iZiI6MTY0NDMyNDU1N30.lRetwJcg9Gf6upQYx6_=
RonwGWjAcxvkE3szhj5Akxbrk&region=3D"=09=09=09=09=09=09=09=09=09style=3D"height: 40px; v-text-anchor: middle; wi=
dth: 300px"
'''

m = re.search(r'token=([.\s\S]+?(?=&))', html, re.+)
if m:
    print(m.group(1))


问:
ImportError: Missing optional dependency 'openpyxl' still doesn't work after instllation
ubuntu 18.04, python3.8 and using pycharm.

Interpreter path in pychamr is correctly set.

while trying to read specific sheet in excel, using openpyxl it keeps on giving me ImportError.
ImportError: Missing optional dependency 'openpyxl'.  Use pip or conda to install openpyxl.

I've installed using pip3 install openpyxl and it say requirement is already satisfied.
However when I run it again in pycharm it still outputs same error.

```<code>Requirement already satisfied: openpyxl mycomp/.local/lib/python3.8/site-packages (3.0.7)
Requirement already satisfied: et-xmlfile in mycomp/.local/lib/python3.8/site-packages (from openpyxl) (1.0.1)
</code>```

My guess is since I am using venv it is not getting installed correctly in venv because when I look at the path upon install it is not where venv is.

When I do pip3 freeze on venv and after deactivating venv it looks like it has same installation.

答:
for me worked typing the following inside an interactive session:</p>
```<code>import pip
pip.main(["install", "openpyxl"])
</code>```

Body:
ubuntu 18.04, python3.8 and using pycharm.

Interpreter path in pychamr is correctly set.

while trying to read specific sheet in excel, using openpyxl it keeps on giving me ImportError.
ImportError: Missing optional dependency 'openpyxl'.  Use pip or conda to install openpyxl.

I've installed using pip3 install openpyxl and it say requirement is already satisfied.
However when I run it again in pycharm it still outputs same error.

Requirement already satisfied: openpyxl mycomp/.local/lib/python3.8/site-packages (3.0.7)
Requirement already satisfied: et-xmlfile in mycomp/.local/lib/python3.8/site-packages (from openpyxl) (1.0.1)

My guess is since I am using venv it is not getting installed correctly in venv because when I look at the path upon install it is not where venv is.

When I do pip3 freeze on venv and after deactivating venv it looks like it has same installation.

Body:
for me worked typing the following inside an interactive session:

import pip
pip.main(["install", "openpyxl"])


问:
Telethon check if user has privacy settings enabled
I am using telethon to scrape members from a group, I can filter out active and non-active members but when adding members to another group I mostly get UserPrivacyRestrictedError.

because of that I usually get PeerFloodError after few request. is there a way to get participants that does not have privacy enabled?

答: No. You can only find that out by trying to perform that action.</p>


问:
My code keeps reapting it self I don't how i will stop it so it can move on and do the other things i want it to do
So here is the code if run  the begin function it will just run option1 and not print the other stuff like i want to make this login thing work but it won't work for some reseon.</p>
```<code>def login():
    print ("You are now logged in")

def reg():
   file = open ("User_details","a")
   file.write("\n"+"Ussername"+","+"Password"+","+"Age"+","+"Real_name"+","+"Last_name"+","+"Email")
   file.close

def Access(option):
    if option == "login":
        input ("Ussername: ")
        input ("Password: ")
        input ("Age: ")
        input ("Real name: ")
        input ("Last name: ")
        input ("Email: ")
        login()
    else:
        print ("Enter all the info we will be asking you to register")
        input ("Ussername: ")
        input ("Password: ")
        input ("Age: ")
        input ("Real name: ")
        input ("Last name: ")
        input ("Email: ")
        reg()

def begin():

    print ("Hi my name is Steve would you like to register or login")
    option1 = input ("Login or Register: ")
    if option1 != "login" and "register":
        begin()
    if option1 == "register":
        Access()
    if option1 == "login":
        login()
begin()
Access()
</code>```

答:
This is because your first conditional will always be True. For example, let's see how an example input would work:

>>> option1 = "unknown input"
>>> if option1 != "login" and "register": print("TRUE")
TRUE

# If we split the statement into pieces, we can see why
>>> option1 != "login"
True
# The part after the `and` isn't testing anything, and is always True!
>>> bool("register")
True
# Your `if` statement effectively tests option1 != "login"
>>> True and "register"
True
```
<p>To fix this, you want to make sure that <code>option1</code> isn't either of the strings. You probably want to clean up the input value a bit too, by stripping any whitespace.</p>
<pre class="lang-py prettyprint-override"><code>option1 = input("Login or Register: ")
option1 = option1.strip()  # remove accidental whitespace from the ends

# The fixed `if` statement
if option1 != "login" and option1 != "register":
    begin()
</code>```

Body:
So here is the code if run  the begin function it will just run option1 and not print the other stuff like i want to make this login thing work but it won't work for some reseon.

def login():
    print ("You are now logged in")

def reg():
   file = open ("User_details","a")
   file.write("\n"+"Ussername"+","+"Password"+","+"Age"+","+"Real_name"+","+"Last_name"+","+"Email")
   file.close

def Access(option):
    if option == "login":
        input ("Ussername: ")
        input ("Password: ")
        input ("Age: ")
        input ("Real name: ")
        input ("Last name: ")
        input ("Email: ")
        login()
    else:
        print ("Enter all the info we will be asking you to register")
        input ("Ussername: ")
        input ("Password: ")
        input ("Age: ")
        input ("Real name: ")
        input ("Last name: ")
        input ("Email: ")
        reg()

def begin():

    print ("Hi my name is Steve would you like to register or login")
    option1 = input ("Login or Register: ")
    if option1 != "login" and "register":
        begin()
    if option1 == "register":
        Access()
    if option1 == "login":
        login()
begin()
Access()

Body:
This is because your first conditional will always be True. For example, let's see how an example input would work:

>>> option1 = "unknown input"
>>> if option1 != "login" and "register": print("TRUE")
TRUE

# If we split the statement into pieces, we can see why
>>> option1 != "login"
True
# The part after the `and` isn't testing anything, and is always True!
>>> bool("register")
True
# Your `if` statement effectively tests option1 != "login"
>>> True and "register"
True

To fix this, you want to make sure that option1 isn't either of the strings. You probably want to clean up the input value a bit too, by stripping any whitespace.

option1 = input("Login or Register: ")
option1 = option1.strip()  # remove accidental whitespace from the ends

# The fixed `if` statement
if option1 != "login" and option1 != "register":
    begin()


问:
EditText maxLines not working - user can still input more lines than set
```<code><EditText
    android:id="@+id/editText2"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:maxLines="5"
    android:lines="5">
</EditText>
</code>```

User can input more than 5 lines, by pressing enter/next row key. How can I limit user input to fixed amount of rows with EditText?

答:
@Cedekasem you are right, there isn't a built in "row limiter". But I did built one my self, so if anyone is interested the code is below. Cheers.</p>

```<code>et.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            // if enter is pressed start calculating
            if (keyCode == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_UP) {

                // get EditText text
                String text = ((EditText) v).getText().toString();

                // find how many rows it cointains
                int editTextRowCount = text.split("\\n").length;

                // user has input more than limited - lets do something
                // about that
                if (editTextRowCount >= 7) {

                    // find the last break
                    int lastBreakIndex = text.lastIndexOf("\n");

                    // compose new text
                    String newText = text.substring(0, lastBreakIndex);

                    // add new text - delete old one and append new one
                    // (append because I want the cursor to be at the end)
                    ((EditText) v).setText("");
                    ((EditText) v).append(newText);

                }
            }

            return false;
        }
});
</code>```

Body:
<EditText
    android:id="@+id/editText2"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:maxLines="5"
    android:lines="5">
</EditText>

User can input more than 5 lines, by pressing enter/next row key. How can I limit user input to fixed amount of rows with EditText?

Body:
@Cedekasem you are right, there isn't a built in "row limiter". But I did built one my self, so if anyone is interested the code is below. Cheers.

et.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            // if enter is pressed start calculating
            if (keyCode == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_UP) {

                // get EditText text
                String text = ((EditText) v).getText().toString();

                // find how many rows it cointains
                int editTextRowCount = text.split("\\n").length;

                // user has input more than limited - lets do something
                // about that
                if (editTextRowCount >= 7) {

                    // find the last break
                    int lastBreakIndex = text.lastIndexOf("\n");

                    // compose new text
                    String newText = text.substring(0, lastBreakIndex);

                    // add new text - delete old one and append new one
                    // (append because I want the cursor to be at the end)
                    ((EditText) v).setText("");
                    ((EditText) v).append(newText);

                }
            }

            return false;
        }
});


问:
Insert multiple entries to SQL Server with Node.js
I am rewriting an old API for which I am trying to insert multiple values at once into a MSSQL-Server (2008) database using the node module mssql. Now, I am capable of doing this somehow, but I want to this following best practices. I've done my research and tried a lot of things to accomplish my target. However, I was not able to find a single solution which works just right.

Before

You may wonder:

Well, you are rewriting this API, so there must be a way this has been done before and that was working?

Sure, you're right, it was working before, but... not in a way I'd feel comfortable with using in the rewrite. Let me show you how it was done before (little bit of abstraction added of course):

```<code>const request = new sql.Request(connection);
let query = "INSERT INTO tbl (col1, col2, col3, col4) VALUES ";
for (/*basic for loop w/ counter variable i*/) {
    query += "(1, @col2" + [i] + ", @col3" + [i] + ", (SELECT x FROM y WHERE z = @someParam" + [i] + "))";
    // a check whether to add a comma or not
    request.input("col2" + [i], sql.Int(), values[i]);
    // ...
}
request.query(query, function(err, recordset) {
    // ...
}
</code>```

While this is working, again, I don't quite think this could be called anything like 'best practice'. Also this shows the biggest problem: a subselect is used to insert a value.

What I tried so far

The easy way

At first I tried the probably easiest thing:

```<code>// simplified
const sQuery = "INSERT INTO tbl (col1, col2, col3, col4) VALUES (1, @col2, @col3, (SELECT x FROM y WHERE z = @col4));";
oPool.request().then(oRequest => {
    return oRequest
        .input("col2", sql.Int(), aValues.map(oValue => oValue.col2))
        .input("col3", sql.Int(), aValues.map(oValue => oValue.col3))
        .input("col4", sql.Int(), aValues.map(oValue => oValue.col4))
        .query(sQuery);
});
</code>```

I'd say, this was a pretty good guess and actually working relative fine.
Except for the part, that ignores every item after the first one... which makes this pretty useless. So, I tried...

Request.multiple = true

...and I thought, it would do the job. But - surprise - it doesn't, still only the first item is inserted.

Using '?' for parameters

At this point I really started the search for a solution, as the second one was only a quick search in the modules documentation.
I stumbled upon this answer and tried it immediately.
Didn't take long for my terminal to spit out a

RequestError: Incorrect syntax near '?'.

So much for that.

Bulk inserting

Some further research led to bulk inserting.
Pretty interesting, cool feature and excellent updating of the question with the solution by the OP!
I had some struggle getting started here, but eventually it looked really good: Multiple records were inserted and the values seemed okay.

Until I added the subquery. Using it as value for a column declared didn't cause any error, however when checking the values of the table, it simply displayed a ```0``` as value for this column. Not a big surprise at all, but everybody can dream, right?

The lazy way

I don't really know what to think about this:

```<code>// simplified
Promise.all(aValues.map(oValue => {
    return oPool.request().then(oRequest =>
        oRequest
            .input("col2", sql.Int, oValue.col2)
            .input("col3", sql.Int, oValue.col3)
            .input("col4", sql.Int, oValue.col4)
            .query(sQuery);
    });
});
</code>```

It does the job, but if any of the request fails for whichever reason, the other, non-failing inserts, will still be executed, even though this should not be possible.

Lazy + Transaction

As continuing even if some fail was the major problem with the last method, I tried building a transaction around it. All querys are successful? Good, commit. Any query has an errpr? Well, just rollback than. So I build a transaction, moved my Promise.all construct into it and tried again.
Aaand the next error pops up in my terminal:

```<code>TransactionError: Can't acquire connection for the request. There is another request in progress.
</code>```

If you came this far, I don't need to tell you what the problem is.

Summary

What I didn't try yet (and I don't think I will try this) is using the transaction way and calling the statements sequentially. I do not believe that this is be the way to go.

And I also don't think the lazy way is the one that should be used, as it uses single requests for every record to insert, when this could somehow be done using only one request. It's just that this somehow is, I don't know, not in my head right now. So please, if you have anything that could help me, tell me.

Also, if you see anything else that's wrong with my code, feel free to point it out. I am not considering myself as a beginner, but I also don't think that learning will ever end. :)

答:
The way I solved this was using PQueue library with concurrency 1. Its slow due to concurrency of one but it works with thousands of queries:

    const transaction = sql.transaction();
    const request = transaction.request();
    const queue = new PQueue({ concurrency: 1 });

    // being transaction
    await transaction.begin();

    for (const query of queries) {
      queue.add(async () => {
        try {
          await request.query(query);
        } catch (err) {
          // stop pending transactions
          await queue.clear();
          await queue.onIdle();
          // rollback transaction
          await transaction.rollback();
          // throw error
          throw err;
        }
      });
    }
    // await queue
    await queue.onIdle();
    // comit transaction
    await transaction.commit();
```

Body:
I am rewriting an old API for which I am trying to insert multiple values at once into a MSSQL-Server (2008) database using the node module mssql. Now, I am capable of doing this somehow, but I want to this following best practices. I've done my research and tried a lot of things to accomplish my target. However, I was not able to find a single solution which works just right.

Before

You may wonder:

Well, you are rewriting this API, so there must be a way this has been done before and that was working?

Sure, you're right, it was working before, but... not in a way I'd feel comfortable with using in the rewrite. Let me show you how it was done before (little bit of abstraction added of course):

const request = new sql.Request(connection);
let query = "INSERT INTO tbl (col1, col2, col3, col4) VALUES ";
for (/*basic for loop w/ counter variable i*/) {
    query += "(1, @col2" + [i] + ", @col3" + [i] + ", (SELECT x FROM y WHERE z = @someParam" + [i] + "))";
    // a check whether to add a comma or not
    request.input("col2" + [i], sql.Int(), values[i]);
    // ...
}
request.query(query, function(err, recordset) {
    // ...
}

While this is working, again, I don't quite think this could be called anything like 'best practice'. Also this shows the biggest problem: a subselect is used to insert a value.

What I tried so far

The easy way

At first I tried the probably easiest thing:

// simplified
const sQuery = "INSERT INTO tbl (col1, col2, col3, col4) VALUES (1, @col2, @col3, (SELECT x FROM y WHERE z = @col4));";
oPool.request().then(oRequest => {
    return oRequest
        .input("col2", sql.Int(), aValues.map(oValue => oValue.col2))
        .input("col3", sql.Int(), aValues.map(oValue => oValue.col3))
        .input("col4", sql.Int(), aValues.map(oValue => oValue.col4))
        .query(sQuery);
});

I'd say, this was a pretty good guess and actually working relative fine.
Except for the part, that ignores every item after the first one... which makes this pretty useless. So, I tried...

Request.multiple = true

...and I thought, it would do the job. But - surprise - it doesn't, still only the first item is inserted.

Using '?' for parameters

At this point I really started the search for a solution, as the second one was only a quick search in the modules documentation.
I stumbled upon this answer and tried it immediately.
Didn't take long for my terminal to spit out a

RequestError: Incorrect syntax near '?'.

So much for that.

Bulk inserting

Some further research led to bulk inserting.
Pretty interesting, cool feature and excellent updating of the question with the solution by the OP!
I had some struggle getting started here, but eventually it looked really good: Multiple records were inserted and the values seemed okay.

Until I added the subquery. Using it as value for a column declared didn't cause any error, however when checking the values of the table, it simply displayed a
0
 as value for this column. Not a big surprise at all, but everybody can dream, right?

The lazy way

I don't really know what to think about this:

// simplified
Promise.all(aValues.map(oValue => {
    return oPool.request().then(oRequest =>
        oRequest
            .input("col2", sql.Int, oValue.col2)
            .input("col3", sql.Int, oValue.col3)
            .input("col4", sql.Int, oValue.col4)
            .query(sQuery);
    });
});

It does the job, but if any of the request fails for whichever reason, the other, non-failing inserts, will still be executed, even though this should not be possible.

Lazy + Transaction

As continuing even if some fail was the major problem with the last method, I tried building a transaction around it. All querys are successful? Good, commit. Any query has an errpr? Well, just rollback than. So I build a transaction, moved my Promise.all construct into it and tried again.
Aaand the next error pops up in my terminal:

TransactionError: Can't acquire connection for the request. There is another request in progress.

If you came this far, I don't need to tell you what the problem is.

Summary

What I didn't try yet (and I don't think I will try this) is using the transaction way and calling the statements sequentially. I do not believe that this is be the way to go.

And I also don't think the lazy way is the one that should be used, as it uses single requests for every record to insert, when this could somehow be done using only one request. It's just that this somehow is, I don't know, not in my head right now. So please, if you have anything that could help me, tell me.

Also, if you see anything else that's wrong with my code, feel free to point it out. I am not considering myself as a beginner, but I also don't think that learning will ever end. :)


问:
How to get the value of a ConstantExpression which uses a local variable?
I created an ExpressionVisitor implementation that overrides VisitConstant.  However, when I create an expression that utilizes a local variable I can't seem to get the actual value of the variable.

```<code>public class Person
{
  public string FirstName { get; set; }
}

string name = "Michael";

Expression<Func<Person, object>> exp = p => p.FirstName == name;
</code>```

How in the world do I get the value of the variable "name" from the ConstantExpression?
The only thing that I can think of is this:

```<code>string fieldValue = value.GetType().GetFields().First().GetValue(value).ToString();
</code>```

Obviously this doesn't lend itself to being very flexible though....

A slightly more complicated example would be the following:

```<code>Person localPerson = new Person { FirstName = "Michael" };
Expression<Func<Person, object>> exp = p => p.FirstName == localPerson.FirstName;
</code>```

答:
Here another solution without DynamicInvoke
Because the tree is traversed recursively, no stack is requried. If a member of a constant or of a static method is accessed, the value is evaluated after traversing the child nodes.

This replaces expressions like

```<code>var myFoo = new Foo{ OtherObjects = new List<OtherObjec>{ new OtherObject {Prop = 5 }};
var expression = () => myFoo.OtherObjects[0].Prop
--->
var expression = () => 5
</code>```

This method is not complete, and does not handle all complicated cases but it can be a good start for other looking for a solution to this problem

```<code>public class ReplaceConstantVisitor : ExpressionVisitor
{
    private int m_memberAccessDepth = 0;
    private object m_constantValue;
    private bool m_constantOnStack = false;

    public ReplaceConstantVisitor()
    {
        m_constantValue = null;
    }

    protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
    {
        var result = base.VisitMethodCall(methodCallExpression);
        if (m_constantOnStack)
        {
            var reducedArguments = methodCallExpression.Arguments.OfType<ConstantExpression>().ToList();
            if (reducedArguments.Count() == methodCallExpression.Arguments.Count)
            {
                m_constantValue = methodCallExpression.Method.Invoke(m_constantValue, reducedArguments.Select(x => x.Value).ToArray());
            }
            else
            {
                m_constantOnStack = false;
            }
        }
        return result;
    }

    protected override Expression VisitMember(MemberExpression memberExpression)
    {
        m_memberAccessDepth++;
        var result = base.VisitMember(memberExpression);
        m_memberAccessDepth--;

        // initial condition to do replacement
        switch (memberExpression.Expression)
        {
            // replace constant member access
            case ConstantExpression constantExpression:
                m_constantOnStack = true;
                m_constantValue = constantExpression.Value;
                break;
            // replace static member access
            case null when memberExpression.Member.IsStatic():
                m_constantOnStack = true;
                break;
        }

        if (m_constantOnStack)
        {
            switch (memberExpression.Member)
            {
                case PropertyInfo propertyInfo:
                    m_constantValue = propertyInfo.GetValue(m_constantValue);
                    break;
                case FieldInfo fieldInfo:
                    m_constantValue = fieldInfo.GetValue(m_constantValue);
                    break;
                default:
                    m_constantOnStack = false; // error case abort replacement
                    break;
            }
        }

        if (m_constantOnStack && m_memberAccessDepth == 0)
        {
            m_constantOnStack = false;
            var constant = m_constantValue;
            m_constantValue = null;
            return Expression.Constant(constant);
        }
        return result;
    }
}
</code>```

Body:
I created an ExpressionVisitor implementation that overrides VisitConstant.  However, when I create an expression that utilizes a local variable I can't seem to get the actual value of the variable.

public class Person
{
  public string FirstName { get; set; }
}

string name = "Michael";

Expression<Func<Person, object>> exp = p => p.FirstName == name;

How in the world do I get the value of the variable "name" from the ConstantExpression?
The only thing that I can think of is this:

string fieldValue = value.GetType().GetFields().First().GetValue(value).ToString();

Obviously this doesn't lend itself to being very flexible though....

A slightly more complicated example would be the following:

Person localPerson = new Person { FirstName = "Michael" };
Expression<Func<Person, object>> exp = p => p.FirstName == localPerson.FirstName;

Body:
Here another solution without DynamicInvoke
Because the tree is traversed recursively, no stack is requried. If a member of a constant or of a static method is accessed, the value is evaluated after traversing the child nodes.

This replaces expressions like

var myFoo = new Foo{ OtherObjects = new List<OtherObjec>{ new OtherObject {Prop = 5 }};
var expression = () => myFoo.OtherObjects[0].Prop
--->
var expression = () => 5

This method is not complete, and does not handle all complicated cases but it can be a good start for other looking for a solution to this problem

public class ReplaceConstantVisitor : ExpressionVisitor
{
    private int m_memberAccessDepth = 0;
    private object m_constantValue;
    private bool m_constantOnStack = false;

    public ReplaceConstantVisitor()
    {
        m_constantValue = null;
    }

    protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
    {
        var result = base.VisitMethodCall(methodCallExpression);
        if (m_constantOnStack)
        {
            var reducedArguments = methodCallExpression.Arguments.OfType<ConstantExpression>().ToList();
            if (reducedArguments.Count() == methodCallExpression.Arguments.Count)
            {
                m_constantValue = methodCallExpression.Method.Invoke(m_constantValue, reducedArguments.Select(x => x.Value).ToArray());
            }
            else
            {
                m_constantOnStack = false;
            }
        }
        return result;
    }

    protected override Expression VisitMember(MemberExpression memberExpression)
    {
        m_memberAccessDepth++;
        var result = base.VisitMember(memberExpression);
        m_memberAccessDepth--;

        // initial condition to do replacement
        switch (memberExpression.Expression)
        {
            // replace constant member access
            case ConstantExpression constantExpression:
                m_constantOnStack = true;
                m_constantValue = constantExpression.Value;
                break;
            // replace static member access
            case null when memberExpression.Member.IsStatic():
                m_constantOnStack = true;
                break;
        }

        if (m_constantOnStack)
        {
            switch (memberExpression.Member)
            {
                case PropertyInfo propertyInfo:
                    m_constantValue = propertyInfo.GetValue(m_constantValue);
                    break;
                case FieldInfo fieldInfo:
                    m_constantValue = fieldInfo.GetValue(m_constantValue);
                    break;
                default:
                    m_constantOnStack = false; // error case abort replacement
                    break;
            }
        }

        if (m_constantOnStack && m_memberAccessDepth == 0)
        {
            m_constantOnStack = false;
            var constant = m_constantValue;
            m_constantValue = null;
            return Expression.Constant(constant);
        }
        return result;
    }
}


问:
GET request works in browser but not in POSTMAN or SOAPUI
I have the following endpoint:
http://millennium.iwise.com.br:6017/api/millenium_eco/Tabelas_preco.lista

If I try to open via browser, it asks me credentials and then works fine - as seen on image below.

user: OData

password: 0d@t@123

If I send the same GET request using POSTMAN or SOAPUI I get 401 Unauthorized.

What I am missing here? Thank you in advance.

UPDATE:

I took the browser's header request and used the same in POSTMAN and I'm still receiving 401 Unauthorized. Is there a possibility of the endpoint's server is configured to reject all but browser's request?

答:
Download the Postman desktop app and try from there.  The Postman website sending requests to localhost:5001 won't route correctly.  You could setup a port forward on your router to your local machine, but easier to get the desktop software.

I had the same issue above and this this approach worked.


问:
Continuous loop with while in Python in IIoT device
I found a solution for this online but just don't like it, see following code:

```<code>try:
    while True:
        # code here
    except KeyboardInterrupt:
         break
</code>```

The continuous is to be run in an IIoT device that has as OS Linux but with limited memory and capabilities.
I could just do
pip install
keyboard to use any other characters than ctrl + c,
let said "s" for stop but the package may not install in the device. I tested some code with curses to not avail. Please advice.

答:
It might be possible that you have no other choice that get the keyboard lib.
the other but very complicated solution is to use the serial

get the serial port your keyboard is connected to the IOT device.
configure it with the right params
and listen to messages.
If you collect any type of message, it means you pressed a key

Here is the doc for pyserial

You can also try to compile the keyboard library with Cython to optimise space

Body:
I found a solution for this online but just don't like it, see following code:

try:
    while True:
        # code here
    except KeyboardInterrupt:
         break

The continuous is to be run in an IIoT device that has as OS Linux but with limited memory and capabilities.
I could just do
pip install
keyboard to use any other characters than ctrl + c,
let said "s" for stop but the package may not install in the device. I tested some code with curses to not avail. Please advice.


问:
how to get and set the value of a cell in WPF DataGrid by providing columnidnex and row index?
Can you please tell ,  how to get and set the value of a cell in WPF  DataGrid by providing columnidnex and row index

Thanks

答: This is not as easy as it should be in WPF, it is all about selecting visual children (the WPF 'Visual' object type). This blog post explains quite well how to accomplish it. Google it and you will probably find a lot more.</p>


问:
Extracting a part of message from Yopmail using Python Selenium
I want to Extract a Specific part in  Python Selenium. I have done it with Pyautogui but I want to do it without that is it possible?

```<code>https://yopmail.com/
</code>```

put in inbox tab

```<code>jenniferwilks09182
</code>```

I want to extract exactly this code it is in a separate div

答:
The element with the code is within an  so you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be visible.

You can use either of the following Locator Strategies:

Using XPATH and following:

```<code>WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='ifmail']")))
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[.='Your code is:']//following::div[1]"))).text)
</code>```

Using XPATH and following-sibling:

```<code>WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='ifmail']")))
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[.='Your code is:']//following-sibling::div[1]"))).text)
</code>```

Note : You have to add the following imports :

```<code> from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.common.by import By
 from selenium.webdriver.support import expected_conditions as EC
</code>```

Reference

You can find a couple of relevant discussions in:

Switch to an iframe through Selenium and python

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium

selenium in python : NoSuchElementException: Message: no such element: Unable to locate element

Body:
I want to Extract a Specific part in  Python Selenium. I have done it with Pyautogui but I want to do it without that is it possible?

https://yopmail.com/

put in inbox tab

jenniferwilks09182

I want to extract exactly this code it is in a separate div

Body:
The element with the code is within an <iframe> so you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be visible.

You can use either of the following Locator Strategies:

Using XPATH and following:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='ifmail']")))
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[.='Your code is:']//following::div[1]"))).text)

Using XPATH and following-sibling:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='ifmail']")))
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[.='Your code is:']//following-sibling::div[1]"))).text)

Note : You have to add the following imports :

 from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.common.by import By
 from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a couple of relevant discussions in:

Switch to an iframe through Selenium and python

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium

selenium in python : NoSuchElementException: Message: no such element: Unable to locate element


问:
Webstorm code completion does not show bootstrap classes
What do I have to change in my webstorm IDE that the bootstrap classes are recognized when I do:

```<code><a class="btn btn-primary" />
</code>```

At the moment I have always to re-check the class names by looking into the bootstrap css files. Thats not so nice...

答:
To add stylesheets to your global JS libraries:

Open the IDE Preferences menu and go to Languages & Frameworks > JavaScript > Libraries

Select the library you wish to add a stylesheet to and click Edit... on the right-hand side

Click the + button just above Documentation URLs and select Attach Files...

Find and select the stylesheet you wish to add, then click OK to close the Edit Library dialogue window

The stylesheet is now attached to the global JS library, so you will get CSS code completions/recommendations from the stylesheet whenever you include the JS library for a project in the IDE.

Body:
What do I have to change in my webstorm IDE that the bootstrap classes are recognized when I do:

At the moment I have always to re-check the class names by looking into the bootstrap css files. Thats not so nice...


问:
How To Convert base64 String to PDF in React.js
I have a base 64 string that is coming from an API call. I am testing with a sample base64 string and I am trying to convert it to pdf or an image to view in my react.js website.

I've tried many solutions, but nothing seems to work. I found a react js package that is called base64topdf I installed it and tried to decode the base64 string to PDF, but it gives me this error "TypeError: fs.writeFileSync is not a function"

I don't know what i am doing wrong.

How can I convert a base64 string to a PDF or an image in reactjs?

Documentation to the package https://www.npmjs.com/package/base64topdf

Here is my code:

```<code> const base64 = require('base64topdf');

 const base64STR = "JVBERi0xLjQKJeLjz9M...." //base64 string

 const decodedBase64 = base64.base64Decode(base64STR, 'waybill');

 console.log(decodedBase64)
</code>```

答:
You cannot use this package, since it is written for Node.js not for web development. If you go inside the package source code you will see that it is using the fs module or file system.

https://github.com/rpsankar001/base64topdf/blob/master/index.js#L3

For the web, you can use something like this:

function downloadPDF(pdf) {
    const linkSource = `data:application/pdf;base64,${pdf}`;
    const downloadLink = document.createElement("a");
    const fileName = "file.pdf";

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();
}
```

Worth mentioning, React has an upcoming feature called Server Components, that will allow you to use server-side code with React. It seems that in the near future you will be able to use the package.

See: https://reactjs.org/blog/2020/12/21/data-fetching-with-react-server-components.html

Body:
I have a base 64 string that is coming from an API call. I am testing with a sample base64 string and I am trying to convert it to pdf or an image to view in my react.js website.

I've tried many solutions, but nothing seems to work. I found a react js package that is called base64topdf I installed it and tried to decode the base64 string to PDF, but it gives me this error "TypeError: fs.writeFileSync is not a function"

I don't know what i am doing wrong.

How can I convert a base64 string to a PDF or an image in reactjs?

Documentation to the package https://www.npmjs.com/package/base64topdf

Here is my code:

 const base64 = require('base64topdf');

 const base64STR = "JVBERi0xLjQKJeLjz9M...." //base64 string

 const decodedBase64 = base64.base64Decode(base64STR, 'waybill');

 console.log(decodedBase64)

Body:
You cannot use this package, since it is written for Node.js not for web development. If you go inside the package source code you will see that it is using the fs module or file system.

https://github.com/rpsankar001/base64topdf/blob/master/index.js#L3

For the web, you can use something like this:

function downloadPDF(pdf) {
    const linkSource = `data:application/pdf;base64,${pdf}`;
    const downloadLink = document.createElement("a");
    const fileName = "file.pdf";

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();
}

Worth mentioning, React has an upcoming feature called Server Components, that will allow you to use server-side code with React. It seems that in the near future you will be able to use the package.

See: https://reactjs.org/blog/2020/12/21/data-fetching-with-react-server-components.html


问:
Apify - error in configuration of generated actor
I'm trying to run Apify locally, after installing all the packages, creating the actor and running it I got this:

```<code>Warning: You are not logged in with your Apify Account. Some features like Apify Proxy will not work. Call "apify login" to fix that.
Run: npm start

> test2@0.0.1 start
> node main.js

/home/a/test2/node_modules/apify/build/configuration.js:91
        const envKey = Configuration.ENV_MAP_REVERSED[key] ?? key;
                                                            ^

SyntaxError: Unexpected token '?'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/a/test2/node_modules/apify/build/events.js:10:25)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
npm ERR! code 1
npm ERR! path /home/a/test2
npm ERR! command failed
npm ERR! command sh -c node main.js

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/a/.npm/_logs/2022-02-08T18_28_58_177Z-debug.log
Error: npm exited with code 1
</code>```

the version of npm is v12.22.5
Any ideas how to generate the correct config file? Thanks

答: You need Node.js 16+ for the latest SDK to work</p>

Body:
I'm trying to run Apify locally, after installing all the packages, creating the actor and running it I got this:

Warning: You are not logged in with your Apify Account. Some features like Apify Proxy will not work. Call "apify login" to fix that.
Run: npm start

> test2@0.0.1 start
> node main.js

/home/a/test2/node_modules/apify/build/configuration.js:91
        const envKey = Configuration.ENV_MAP_REVERSED[key] ?? key;
                                                            ^

SyntaxError: Unexpected token '?'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/a/test2/node_modules/apify/build/events.js:10:25)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
npm ERR! code 1
npm ERR! path /home/a/test2
npm ERR! command failed
npm ERR! command sh -c node main.js

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/a/.npm/_logs/2022-02-08T18_28_58_177Z-debug.log
Error: npm exited with code 1

the version of npm is v12.22.5
Any ideas how to generate the correct config file? Thanks


问:
Android Camera Intent and Geotag
Programmatically I turn on the GPS to get lat/lon and I want to use default android camera Intent to take geotagged photos.

Is there any extra param to pass to the default image capture Intent to enable geotag?

Thanks in advance.

答: I've solved the problem simply by getting the image and later programmatically editing the exif datas of the image.</p>

Title: Android Camera Intent and Geotag


问:
Delete post method returns null
I am following a beginner tutorial on how to make a simple store with asp.net mvc, and in tutorial there is no problem when doing exact same steps.
I am currently trying to perform a basic CRUD operations on my category page, but i am stuck when trying to delete categories. I get not found page because id is null, but i don't have problem  for Edit method when passing the same id parameter.
I was looking for an answer and some people suggest that there might be caching problem, but not sure how to even try to fix that.
Here is my controller for delete operations

```<code> // GET-DELETE
        public IActionResult Delete(int? id)
        {

            if (id == null || id == 0)
            {
                return NotFound();
            }

            Category obj = _db.Category.Find(id);

         if (obj == null)
            {
                return NotFound();
            }

            return View(obj);
        }

        //POST-DELETE
        [HttpPost]
        [ValidateAntiForgeryToken]

        public IActionResult DeletePost(int? id)
        {
            Category obj = _db.Category.Find(id);

            if (id == null)
            {
                return NotFound();
            }

            _db.Category.Remove(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");

        }
</code>```

and here is my View

```<code>@model RockyWebsite.Models.Category

<form method="post" asp-action="DeletePost">
    @Html.HiddenFor(id => id.CategoryId)
    <input asp-for="CategoryId" hidden />

    <div class="border p-3">

        <div class="form-group row">
            <h2 class="text-info pl-3">Delete Category</h2>
        </div>
        <div class="row">
            <div class="col-8">
                <div class="form-group row">
                    <div class="col-4">
                        <label asp-for="CategoryName"></label>
                    </div>
                    <div class="col-8">
                        <input asp-for="CategoryName" disabled class="form-control" />

                    </div>

                </div>
                <div class="form-group row">
                    <div class="col-4">
                        <label asp-for="DisplayOrder"></label>
                    </div>
                    <div class="col-8">
                        <input asp-for="DisplayOrder" disabled class="form-control" />

                    </div>

                </div>
                <div class="form-group row">
                    <div class="col-8 offset-4 row">

                        <div class="col">
                            <input type="submit" class="btn btn-danger w-100" value="Delete" />
                        </div>
                        <div class="col">
                            <a asp-action="Index" class="btn btn-success w-100"><i class="fas fa-sign-out-alt"></i> Back</a>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-4">
                @* Keep this empty *@
            </div>
        </div>
    </div>

</form>
</code>```

Any help or suggestion would be very appreciated, thanks!

答:
replace your form tag with this one

```<code>@Html.BeginForm("DeletePost", "controllerName", FormMethod.Post,
 new {id="@Model.CategoryId"})
{
@Html.AntiForgeryToken()
</code>```

and action

```<code>[HttpPost("{id}")]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int id)
</code>```

Title: Delete post method returns null

Body:
I am following a beginner tutorial on how to make a simple store with asp.net mvc, and in tutorial there is no problem when doing exact same steps.
I am currently trying to perform a basic CRUD operations on my category page, but i am stuck when trying to delete categories. I get not found page because id is null, but i don't have problem  for Edit method when passing the same id parameter.
I was looking for an answer and some people suggest that there might be caching problem, but not sure how to even try to fix that.
Here is my controller for delete operations

 // GET-DELETE
        public IActionResult Delete(int? id)
        {

            if (id == null || id == 0)
            {
                return NotFound();
            }

            Category obj = _db.Category.Find(id);

         if (obj == null)
            {
                return NotFound();
            }

            return View(obj);
        }

        //POST-DELETE
        [HttpPost]
        [ValidateAntiForgeryToken]

        public IActionResult DeletePost(int? id)
        {
            Category obj = _db.Category.Find(id);

            if (id == null)
            {
                return NotFound();
            }

            _db.Category.Remove(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");

        }

and here is my View

@model RockyWebsite.Models.Category

<form method="post" asp-action="DeletePost">
    @Html.HiddenFor(id => id.CategoryId)
    <input asp-for="CategoryId" hidden />

Delete Category

                        <input asp-for="CategoryName" disabled class="form-control" />

                        <input asp-for="DisplayOrder" disabled class="form-control" />

                            <input type="submit" class="btn btn-danger w-100" value="Delete" />

                             Back

                @* Keep this empty *@

</form>

Any help or suggestion would be very appreciated, thanks!

Body:
replace your form tag with this one

@Html.BeginForm("DeletePost", "controllerName", FormMethod.Post,
 new {id="@Model.CategoryId"})
{
@Html.AntiForgeryToken()

and action

[HttpPost("{id}")]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int id)


问:
Where to put the .join in this function in order to rejoin the separated strings of an array
Problem to solve is to capitlize the first letter of each word in a string using '.split' '.map' and 'join'. Currently implemented split and map to get the word capitlised and rejoined it, but confused as to where I need to put the .join.

```<code>Expected: "The Lord Of The Rings"
Received: ["The", "Lord", "Of", "The", "Rings"]
</code>```

function titleCase(string) {
  return string.split(' ').map(word => word.charAt(0).toUpperCase() + word.substr(1))

}```

答:
First: split the string

Second: Capitalize word

Third: Join  words

```<code>return string.split(' ').map(word => word.charAt(0).toUpperCase() + word.substr(1)).join(' ');
</code>```

Body:
Problem to solve is to capitlize the first letter of each word in a string using '.split' '.map' and 'join'. Currently implemented split and map to get the word capitlised and rejoined it, but confused as to where I need to put the .join.

Expected: "The Lord Of The Rings"
Received: ["The", "Lord", "Of", "The", "Rings"]

function titleCase(string) {
  return string.split(' ').map(word => word.charAt(0).toUpperCase() + word.substr(1))

}

Body:
First: split the string

Second: Capitalize word

Third: Join  words

return string.split(' ').map(word => word.charAt(0).toUpperCase() + word.substr(1)).join(' ');


问:
Upgrading Qt version to the latest
hopefully everyone will be doing great.
I wanted to ask if the existing version of Qt (not Qt Creator) be upgraded to the latest version? Rather than downloading it separately from Maintenance Tool, and Migrating the Project to the Newer versions manually.

Like, currently I have Qt 6.2.2, and I want to upgrade to Qt 6.2.3 (as, there's a fix I need). To update, I have to download the whole package from the Maintenance Tool, do all the selections all over again, and migrate my existing projects to the newer version.
Is there exist a convenient way? As Visual Studio provides.

答: The way i do is conan package menager. You have Qt and other great packages there. You can check https://www.qt.io/blog/installing-qt-via-conan-package-manager how to setup or use some existing starter project with it like https://github.com/cpp-best-practices/cpp_starter_project/blob/master/cmake/Conan.cmake#L28 or maybe even https://github.com/conan-io/cmake-conan when you setup your project with conan changing version required you to change for example qt/6.2.2 to qt/6.2.3 and rerun CMake if you using it of course. It will require you to setup conan in your project and that can be tricky. But after that you will see all pros of using conan. Worked great for me.

Title: Upgrading Qt version to the latest


问:
DBConnect to open SQLite in read-only mode in R
I'm working on converting a simple Python script to R to act as a template for connecting up to SQLite files. The data is on a NFS mount, and we've run into a few snags in setting up the original Python template (namely, IO errors), but we were able to work around them by connecting with read-only mode and setting the VFS to unix-none, e.g.:

```<code># Python version
path = "file///mnt_nfs/examplepath.edu/path/file.db"
connect = sqlite3.connect(path + "?mode=ro&vfs=unix-none", uri = True)
cur = connect.cursor()
</code>```

While we know this is far from a perfect solution, it's acting as an interim solution while we set up a more robust database (so our users can still connect to their data in the meantime). However, most of our students are more familiar with R than Python, and I'm having difficulty finding how to recreate the workarounds in R. Is there some way to set dbConnect to include the read-only and unix-none arguments (or equivalent)?
I have the basics, but it's throwing a similar disk IO Error as the Python code was before we added the arguments. I can't seem to find any info on it in the DBI documentation.

```<code>connect <- dbConnect(RSQLite::SQLite(), path)
</code>```

答:
I think it is

```<code>dbConnect(SQLite(), dbname=path, flags=SQLITE_RO, vfs="unix-none")
</code>```

documented at

```<code>library(RSQLite)
?`dbConnect,SQLiteDriver-method`
</code>```

Body:
I'm working on converting a simple Python script to R to act as a template for connecting up to SQLite files. The data is on a NFS mount, and we've run into a few snags in setting up the original Python template (namely, IO errors), but we were able to work around them by connecting with read-only mode and setting the VFS to unix-none, e.g.:

# Python version
path = "file///mnt_nfs/examplepath.edu/path/file.db"
connect = sqlite3.connect(path + "?mode=ro&vfs=unix-none", uri = True)
cur = connect.cursor()

While we know this is far from a perfect solution, it's acting as an interim solution while we set up a more robust database (so our users can still connect to their data in the meantime). However, most of our students are more familiar with R than Python, and I'm having difficulty finding how to recreate the workarounds in R. Is there some way to set dbConnect to include the read-only and unix-none arguments (or equivalent)?
I have the basics, but it's throwing a similar disk IO Error as the Python code was before we added the arguments. I can't seem to find any info on it in the DBI documentation.

connect <- dbConnect(RSQLite::SQLite(), path)

Body:
I think it is

dbConnect(SQLite(), dbname=path, flags=SQLITE_RO, vfs="unix-none")

documented at

library(RSQLite)
?`dbConnect,SQLiteDriver-method`


问:
Flex: Prevent scrollbar from covering content when automatically displayed
I have a canvas in Flex that shall be able only to be scrolled in vertical direction, so I set the attributes of the canvas as follows:

```<code>verticalScrollPolicy="auto" horizontalScrollPolicy="off"
</code>```

The problem here is that the vertical scrollbar covers the content when it appears - altough there is enough horizontal room left. I would have expected that the content size would have been automatically adjusted.

When setting the vertical scroll policy to "on", no content is covered also.

In case I set both scroll policies to 'auto' I also get a horizontal scroll bar just for scrolling to the area that is covered by the vertical scroll bar.

Is there a workaround how I can relayout the content of the canvas when the vertical scroll bar is shown so that it does not cover any content?

答:
on vbox or another component based on Container, i solved that problem like that.

Wrong:

```<code><mx:VBox width="100%" height="100%"
      verticalScrollPolicy="auto" horizontalScrollPolicy="off">
     <mx:Repeater dataProvider="{hede}">
          <custom:RenderItem ........../>
     </mx:Repeater>
</mx:VBox>
</code>```

there is no scroll bar

Working version:

```<code><mx:VBox width="100%" height="100%"
    **minHeight="1"** horizontalScrollPolicy="off">
    <mx:Repeater dataProvider="{hede}">
        <custom:RenderItem ........../>
    </mx:Repeater>
</mx:VBox>
</code>```

OwnerDisplayName: Yaba

Body:
I have a canvas in Flex that shall be able only to be scrolled in vertical direction, so I set the attributes of the canvas as follows:

verticalScrollPolicy="auto" horizontalScrollPolicy="off"

The problem here is that the vertical scrollbar covers the content when it appears - altough there is enough horizontal room left. I would have expected that the content size would have been automatically adjusted.

When setting the vertical scroll policy to "on", no content is covered also.

In case I set both scroll policies to 'auto' I also get a horizontal scroll bar just for scrolling to the area that is covered by the vertical scroll bar.

Is there a workaround how I can relayout the content of the canvas when the vertical scroll bar is shown so that it does not cover any content?

Body:
on vbox or another component based on Container, i solved that problem like that.

Wrong:

<mx:VBox width="100%" height="100%"
      verticalScrollPolicy="auto" horizontalScrollPolicy="off">
     <mx:Repeater dataProvider="{hede}">
          <custom:RenderItem ........../>
     </mx:Repeater>
</mx:VBox>

there is no scroll bar

Working version:

<mx:VBox width="100%" height="100%"
    **minHeight="1"** horizontalScrollPolicy="off">
    <mx:Repeater dataProvider="{hede}">
        <custom:RenderItem ........../>
    </mx:Repeater>
</mx:VBox>