问:
Jupyter notebook load updated package
When I update a basic pack on cmd:

```<code>pip install --upgrade a=1.0.7
</code>```

But when I run the code:

```<code>import a
print(a.__version__)
</code>```

outputs:

```<code>1.0.8
</code>```

It doesn't have any change even if I refresh this notebook unless I reboot. But it will give up all my data in flush. Do you have any method help?

答:
Does reloading the module help?

See https://www.geeksforgeeks.org/reloading-modules-python/ for info how to do it depending on your python version. Up to date documentation https://docs.python.org/3/library/importlib.html#importlib.reload on the python site.

Title: Jupyter notebook load updated package

Body:
When I update a basic pack on cmd:

pip install --upgrade a=1.0.7

But when I run the code:

import a
print(a.__version__)

outputs:

1.0.8

It doesn't have any change even if I refresh this notebook unless I reboot. But it will give up all my data in flush. Do you have any method help?


来源: stackexchange

问:
Swift segue not doing what it is supposed to do
I am having a little problem with a segue in my application.
When I try to push a segue so that it has a navbar it shows up correctly in the storyboard but not when I try it on my iPhone.

This is an overview of a couple of view controllers where my problem lays.

This is supposed to be the segue, so you can see that it has a navigation bar and is correctly positioned on the storyboard.

This is the view on the iPhone. No navigation bar or nothing. I tried everything but can't seem to find a solution to this problem.

Does anyone what the problem could be?

A little extra side information:
I don't know if may have something to do with the problem but the navigation view controller is not always present only when the user is logged in the app. this is decided on a log in screen if the user is not logged in the user will see a normal login screen. Else it will go to navigation view controller with a view did appear function and self.present.

Here is the code that handles that action.

```<code> // Sees if the user is logged, If yes --> go to the account detail page else go to the account view.
    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let data = UserDefaults.standard.data(forKey: "User") {
            do {
                // Create JSON Decoder
                let decoder = JSONDecoder()
                // Decode Note
                _ = try decoder.decode(User.self, from: data)
                guard let loginVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier:
                        "AccountDetailViewController") as? AccountDetailViewController else { return }
                loginVC.modalPresentationStyle = .overCurrentContext
                self.present(loginVC, animated: false, completion: {})
            } catch {
                print("Unable to Decode Note (\(error))")
            }
        }
    }
</code>```

答:
After succesful login, you are presenting AccountDetailViewController without adding it in a navigation controller. I would suggest you to use these extensions that i created.

```<code>extension UIViewController {

    func pushVC(vcName : String) {
        let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: vcName)
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func pushVC(storyboardName : String, vcName : String)  {
        let vc = UIStoryboard.init(name: storyboardName, bundle: Bundle.main).instantiateViewController(withIdentifier: vcName)
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func popVC() {
        self.navigationController?.popViewController(animated: true)
    }

    func makeRootVC(storyBoardName : String, vcName : String) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
         let vc = UIStoryboard(name: storyBoardName, bundle: Bundle.main).instantiateViewController(withIdentifier: vcName)
         let nav = UINavigationController(rootViewController: vc)
         nav.navigationBar.isHidden = true
         appDelegate.window?.rootViewController = nav // If using XCode 11 and above, copy var window : UIWindow? in your appDelegate file
         let options: UIView.AnimationOptions = .transitionCrossDissolve
         let duration: TimeInterval = 0.6
         UIView.transition(with: appDelegate.window!, duration: duration, options: options, animations: {}, completion: nil)
     }
}
</code>```

Now in your case, when a user logs in, you should change your root view controller to AccountDetailViewController. So first, copy paste the above extension anywhere in your file and then use it like this:

```<code> // Sees if the user is logged, If yes --> go to the account detail page else go to the account view.
    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let data = UserDefaults.standard.data(forKey: "User") {
            do {
                // Create JSON Decoder
                let decoder = JSONDecoder()
                // Decode Note
                _ = try decoder.decode(User.self, from: data)
                self.makeRootVC(storyBoardName : "Main", vcName :"AccountDetailViewController")
            } catch {
                print("Unable to Decode Note (\(error))")
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having a little problem with a segue in my application.
When I try to push a segue so that it has a navbar it shows up correctly in the storyboard but not when I try it on my iPhone.

This is an overview of a couple of view controllers where my problem lays.

This is supposed to be the segue, so you can see that it has a navigation bar and is correctly positioned on the storyboard.

This is the view on the iPhone. No navigation bar or nothing. I tried everything but can't seem to find a solution to this problem.

Does anyone what the problem could be?

A little extra side information:
I don't know if may have something to do with the problem but the navigation view controller is not always present only when the user is logged in the app. this is decided on a log in screen if the user is not logged in the user will see a normal login screen. Else it will go to navigation view controller with a view did appear function and self.present.

Here is the code that handles that action.

 // Sees if the user is logged, If yes --> go to the account detail page else go to the account view.
    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let data = UserDefaults.standard.data(forKey: "User") {
            do {
                // Create JSON Decoder
                let decoder = JSONDecoder()
                // Decode Note
                _ = try decoder.decode(User.self, from: data)
                guard let loginVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier:
                        "AccountDetailViewController") as? AccountDetailViewController else { return }
                loginVC.modalPresentationStyle = .overCurrentContext
                self.present(loginVC, animated: false, completion: {})
            } catch {
                print("Unable to Decode Note (\(error))")
            }
        }
    }

Body:
After succesful login, you are presenting AccountDetailViewController without adding it in a navigation controller. I would suggest you to use these extensions that i created.

extension UIViewController {

    func pushVC(vcName : String) {
        let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: vcName)
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func pushVC(storyboardName : String, vcName : String)  {
        let vc = UIStoryboard.init(name: storyboardName, bundle: Bundle.main).instantiateViewController(withIdentifier: vcName)
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func popVC() {
        self.navigationController?.popViewController(animated: true)
    }

    func makeRootVC(storyBoardName : String, vcName : String) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
         let vc = UIStoryboard(name: storyBoardName, bundle: Bundle.main).instantiateViewController(withIdentifier: vcName)
         let nav = UINavigationController(rootViewController: vc)
         nav.navigationBar.isHidden = true
         appDelegate.window?.rootViewController = nav // If using XCode 11 and above, copy var window : UIWindow? in your appDelegate file
         let options: UIView.AnimationOptions = .transitionCrossDissolve
         let duration: TimeInterval = 0.6
         UIView.transition(with: appDelegate.window!, duration: duration, options: options, animations: {}, completion: nil)
     }
}

Now in your case, when a user logs in, you should change your root view controller to AccountDetailViewController. So first, copy paste the above extension anywhere in your file and then use it like this:

 // Sees if the user is logged, If yes --> go to the account detail page else go to the account view.
    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let data = UserDefaults.standard.data(forKey: "User") {
            do {
                // Create JSON Decoder
                let decoder = JSONDecoder()
                // Decode Note
                _ = try decoder.decode(User.self, from: data)
                self.makeRootVC(storyBoardName : "Main", vcName :"AccountDetailViewController")
            } catch {
                print("Unable to Decode Note (\(error))")
            }
        }
    }


问:
GCC warning: non-pic addressing form not suitible for pic code
The following code compiles fine in MSVC, but GCC gives a warning, which really bugs me: non-pic addressing form not suitible for pic code.

Can you please tell me the cause of this warning and how to fix it if it really is a potential problem? I am using -fasm-blocks compiler option to enable intel style assembly, adding -fpic argument makes no difference.

```<code>unsigned short dataMask[] = {0x0ffff, 0x07bef, 0x039e7, 0x018e3, 0x0861, 0x020, 0,0};

void test
{
    _asm
    {
        xor     ecx, ecx // ecx == 0
        //...
        // value in ecx may change
        //...
        mov     bx, [dataMask + ecx * 2]
        //...
    };
}
</code>```

答: GCC is trying to tell you that [dataMask + ecx * 2] isn't a valid addressing mode. This is due to the PIC's nature: it is a RISC, and you're writing RISC code with CISC syntax, not a good idea IMO. Basically, the x86 has a way more complete (and complicated) instruction set, while the PIC's one isn't so extended. I'm quite tired right now, but I hope I was clear ;)</p>

ContentLicense: CC BY-SA 3.0

Body:
The following code compiles fine in MSVC, but GCC gives a warning, which really bugs me: non-pic addressing form not suitible for pic code.

Can you please tell me the cause of this warning and how to fix it if it really is a potential problem? I am using -fasm-blocks compiler option to enable intel style assembly, adding -fpic argument makes no difference.

unsigned short dataMask[] = {0x0ffff, 0x07bef, 0x039e7, 0x018e3, 0x0861, 0x020, 0,0};

void test
{
    _asm
    {
        xor     ecx, ecx // ecx == 0
        //...
        // value in ecx may change
        //...
        mov     bx, [dataMask + ecx * 2]
        //...
    };
}


问:
Need powershell script to enable diagnostic logging for Storage account and Key vault
I'm using below script to create a storage account, Key Vault and ADF. I would also like to enable diagnostic logging on both Storage account and Key Vault. Script runs fine and creates the resources however it does not enable the diagnostic logs for KV and Storage account. Would appreciate if you can help.</p>

```<code>$subscription="Azure subscription 1"
$rgName = "Test"
$location = "eastus"
$storageaccountName = "tempaccountlogs"
$adfName = "tempdpadf"
$department = "Testtemp"
$kvname = "kvnamAkbt"

$sa = New-AzStorageAccount -ResourceGroupName $rgName -AccountName $storageaccountName -Location $location -SkuName Standard_LRS -Kind BlobStorage -AccessTier Hot -Tag @{department=$department}
$DataFactory = Set-AzDataFactoryV2 -Name $adfName -ResourceGroupName $rgName -Location $location -Tag @{chargecode=$chargeCode;department=$department;environment=$environment;project=$project}
$kv = New-AzKeyVault -VaultName $kvname -ResourceGroupName $rgName -Location $location

set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Categories AuditEvent
set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -RetentionEnabled $true -RetentionInDays 90
</code>```

答:
You should include -WorkspaceId parameter in the cmd. See reference here.

My example which runs successfully:

```<code>set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Category AuditEvent -WorkspaceId {resource id of the Log Analytics workspace}
</code>```

For how to create a Log Analytics workspace, please refer to Create workspace.

Update:

For how to enable diagnostic logs for ADF, please refer to this sample:

```<code>$ws = Get-AzOperationalInsightsWorkspace -Name "testLAW" -ResourceGroupName "test"
$DataFactory = Set-AzDataFactoryV2 -ResourceGroupName "test" -Name "testADF" -Location "WestUS"
set-AzDiagnosticSetting -ResourceId $DataFactory.DataFactoryId  -Enabled $true -WorkspaceId $ws.ResourceId
</code>```

Body:
I'm using below script to create a storage account, Key Vault and ADF. I would also like to enable diagnostic logging on both Storage account and Key Vault. Script runs fine and creates the resources however it does not enable the diagnostic logs for KV and Storage account. Would appreciate if you can help.

$subscription="Azure subscription 1"
$rgName = "Test"
$location = "eastus"
$storageaccountName = "tempaccountlogs"
$adfName = "tempdpadf"
$department = "Testtemp"
$kvname = "kvnamAkbt"

$sa = New-AzStorageAccount -ResourceGroupName $rgName -AccountName $storageaccountName -Location $location -SkuName Standard_LRS -Kind BlobStorage -AccessTier Hot -Tag @{department=$department}
$DataFactory = Set-AzDataFactoryV2 -Name $adfName -ResourceGroupName $rgName -Location $location -Tag @{chargecode=$chargeCode;department=$department;environment=$environment;project=$project}
$kv = New-AzKeyVault -VaultName $kvname -ResourceGroupName $rgName -Location $location

set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Categories AuditEvent
set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -RetentionEnabled $true -RetentionInDays 90

Body:
You should include -WorkspaceId parameter in the cmd. See reference here.

My example which runs successfully:

set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Category AuditEvent -WorkspaceId {resource id of the Log Analytics workspace}

For how to create a Log Analytics workspace, please refer to Create workspace.

Update:

For how to enable diagnostic logs for ADF, please refer to this sample:

$ws = Get-AzOperationalInsightsWorkspace -Name "testLAW" -ResourceGroupName "test"
$DataFactory = Set-AzDataFactoryV2 -ResourceGroupName "test" -Name "testADF" -Location "WestUS"
set-AzDiagnosticSetting -ResourceId $DataFactory.DataFactoryId  -Enabled $true -WorkspaceId $ws.ResourceId


问:
Python script only downloads the first video from the url list
I made a python script to download some videos using youtube-dl. When I run the script , it downloads the first video and then keeps printing video already downloaded for all other videos.

Here is the script:

```<code>import re , os
formula = re.compile(r'https.+')

os.chdir('/home/ubuntu/Desktop/TO MASTER THIS VACATION')
urls = []
with open('Python necessary videos.txt' , 'r') as f:
    for line in f:
        mo = formula.findall(line)
        if mo:
            urls.append(mo[0])
cmd = 'youtube-dl -f 22 '
for i in urls:
    print("Video url : "+str(i))
    cmd = cmd + str(i)
    os.system(cmd)
</code>```

What am I doing wrong??

P.S.

As it was asked to share some lines of "Python necessary videos.txt". Here I am sharing few of those lines...

Python Tutorial1
https://youtu.be/*$!@&_

Python Tutorial2
https://youtu.be/@#@$>?

Note that here I've changed the original urls.

答:
```<code>cmd = cmd + str(i)
</code>```

You keep appending new URLs to the command, so in the first iteration you call

```<code>youtube-dl -f 22 url1
</code>```

and in the next iteration

```<code>youtube-dl -f 22 url1 url2
</code>```

and so on.

You should use a different variable name for the base command so that cmd is created new each time, instead of reusing the previous URLs.

For example:

```<code>base_cmd = 'youtube-dl -f 22 '
# ...
cmd = base_cmd + str(i)
</code>```

Body:
I made a python script to download some videos using youtube-dl. When I run the script , it downloads the first video and then keeps printing video already downloaded for all other videos.

Here is the script:

import re , os
formula = re.compile(r'https.+')

os.chdir('/home/ubuntu/Desktop/TO MASTER THIS VACATION')
urls = []
with open('Python necessary videos.txt' , 'r') as f:
    for line in f:
        mo = formula.findall(line)
        if mo:
            urls.append(mo[0])
cmd = 'youtube-dl -f 22 '
for i in urls:
    print("Video url : "+str(i))
    cmd = cmd + str(i)
    os.system(cmd)

What am I doing wrong??

P.S.

As it was asked to share some lines of "Python necessary videos.txt". Here I am sharing few of those lines...

Python Tutorial1
https://youtu.be/*$!@&_

Python Tutorial2
https://youtu.be/@#@$>?

Note that here I've changed the original urls.

Body:
cmd = cmd + str(i)

You keep appending new URLs to the command, so in the first iteration you call

youtube-dl -f 22 url1

and in the next iteration

youtube-dl -f 22 url1 url2

and so on.

You should use a different variable name for the base command so that cmd is created new each time, instead of reusing the previous URLs.

For example:

base_cmd = 'youtube-dl -f 22 '
# ...
cmd = base_cmd + str(i)


问:
How to convert JSON Object into key value pair in JS?
```<code>{"1":"val1","2":"val2","3":"val3"}
</code>```

i want it to converted like this:

```<code>{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
</code>```

little Help Please would be much appricated

答:
You cannot do this. Object is a unique key value pair.

```<code>{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}
</code>```

Suppose you want to merge two object and What if both the object has same key, it simply merge the last objects value and have only one key value.

Body:
{"1":"val1","2":"val2","3":"val3"}

i want it to converted like this:

{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}

little Help Please would be much appricated

Body:
You cannot do this. Object is a unique key value pair.

{"Id":"1","value":"val1","Id":"2","value":"val2","Id":"3","value":"val3"}

Suppose you want to merge two object and What if both the object has same key, it simply merge the last objects value and have only one key value.


问:
Check WooCommerce User Role and Payment Gateway and if they match - Apply fee
I'm struggling with applying a fee for an array of user roles if and when a specific payment gateway is selected.

The code I've written works fine if I do not check the user role, but once I try and do that, it does not.

I've removed (commented) the user role if statement in the code and I'm asking for help making it work.

I need to check if the user role match my array and if it does, check the payment gateway. If the payment gateway match too, apply the fee.

This is my code:

add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 20, 1 );
function custom_fee ($cart){

    if (is_admin() && !defined('DOING_AJAX')) return;

    if (!is_user_logged_in()) return;

    if (!is_checkout() && !is_wc_endpoint_url()) return;

    $customer_role = wp_get_current_user();
    $roles_to_check = array( 'vendor', 'external' );
    $payment_method = WC()->session->get('chosen_payment_method');

        // if (!in_array($roles_to_check, $customer_role->roles)) return;

    if ('bacs' == $payment_method){
        $payment_fee = $cart->subtotal * 0.05;
            $cart->add_fee( 'Payment Fee', $payment_fee, true );
    }
}
```

答:
You could use the following, explanation with comments added in the code

Conditions that must be met in this code are:

only for certain user roles

checks on payment method

function custom_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page

    if ( ! is_user_logged_in())
        return;

    // Get current WP_User Object
    $user = wp_get_current_user();

    // User roles
    $roles = ( array ) $user->roles;

    // Roles to check
    $roles_to_check = array( 'vendor', 'external', 'administrator' );

    // Compare
    $compare = array_diff( $roles, $roles_to_check );

    // Result is empty
    if ( empty ( $compare ) ) {
        // Payment method
        $payment_method = WC()->session->get('chosen_payment_method');

        // Condition equal to
        if ( $payment_method == 'bacs' ) {
            // Calculate
            $payment_fee = $cart->subtotal * 0.05;

            // Add fee
            $cart->add_fee( 'Payment Fee', $payment_fee, true );
        }
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 10, 1 );
```

EDIT

To complete my answer, see the answer from @LoicTheAztec

Body:
You could use the following, explanation with comments added in the code

Conditions that must be met in this code are:

only for certain user roles

checks on payment method

function custom_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page

    if ( ! is_user_logged_in())
        return;

    // Get current WP_User Object
    $user = wp_get_current_user();

    // User roles
    $roles = ( array ) $user->roles;

    // Roles to check
    $roles_to_check = array( 'vendor', 'external', 'administrator' );

    // Compare
    $compare = array_diff( $roles, $roles_to_check );

    // Result is empty
    if ( empty ( $compare ) ) {
        // Payment method
        $payment_method = WC()->session->get('chosen_payment_method');

        // Condition equal to
        if ( $payment_method == 'bacs' ) {
            // Calculate
            $payment_fee = $cart->subtotal * 0.05;

            // Add fee
            $cart->add_fee( 'Payment Fee', $payment_fee, true );
        }
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 10, 1 );

EDIT

To complete my answer, see the answer from @LoicTheAztec


问:
npm install ->Failed at the node-sass@4.5.0 postinstall script
I'm trying to do npm install and an error appears :

```<code>Failed at the node-sass@4.5.0 postinstall script.
</code>```

I tried to delete node_modules and then reinstall it, same error appears.
what will be the solution?

node v8.9.3

npm v5.4.2

ionic 3.19.0

答:
Sometime unable to download file win32-x64-79_binding.node due to your proxy restrict  to download so plase follow this below link set them manually.
https://github.com/sass/node-sass/issues/2773</p>

Body:
I'm trying to do npm install and an error appears :

Failed at the node-sass@4.5.0 postinstall script.

I tried to delete node_modules and then reinstall it, same error appears.
what will be the solution?

node v8.9.3

npm v5.4.2

ionic 3.19.0


问:
Help with a regular expression - Python
Lets assume I have the following string:

```<code>string = "xxx abc123 xxx"
</code>```

I want the regular expression to replace the digits in the string that begin with 'abc'. I have tried the following, but with no luck:

```<code>re.sub(r'\d{1,3}\babc','456',string)
</code>```

Thanks.

Title: Help with a regular expression - Python

Body:
Lets assume I have the following string:

string = "xxx abc123 xxx"

I want the regular expression to replace the digits in the string that begin with 'abc'. I have tried the following, but with no luck:

re.sub(r'\d{1,3}\babc','456',string)

Thanks.

Body: re.sub(r'(?<=abc)\d{1,3}', '456', string)


问:
Is there a built in function for string natural sort?
I have a list of strings for which I would like to perform a natural alphabetical sort.

For instance, the following list is naturally sorted (what I want):

```<code>['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
</code>```

And here's the "sorted" version of the above list (what I get using sorted()):

```<code>['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
</code>```

I'm looking for a sort function which behaves like the first one.

答:
Let me submit my own take on this need:

from typing import Tuple, Union, Optional, Generator

StrOrInt = Union[str, int]

# On Python 3.6, string concatenation is REALLY fast
# Tested myself, and this fella also tested:
# https://blog.ganssle.io/articles/2019/11/string-concat.html
def griter(s: str) -> Generator[StrOrInt, None, None]:
    last_was_digit: Optional[bool] = None
    cluster: str = ""
    for c in s:
        if last_was_digit is None:
            last_was_digit = c.isdigit()
            cluster += c
            continue
        if c.isdigit() != last_was_digit:
            if last_was_digit:
                yield int(cluster)
            else:
                yield cluster
            last_was_digit = c.isdigit()
            cluster = ""
        cluster += c
    if last_was_digit:
        yield int(cluster)
    else:
        yield cluster
    return

def grouper(s: str) -> Tuple[StrOrInt, ...]:
    return tuple(griter(s))
```

<p>Now if we have the list like such:</p>

<pre class="lang-py prettyprint-override"><code>filelist = [
    'File3', 'File007', 'File3a', 'File10', 'File11', 'File1', 'File4', 'File5',
    'File9', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File6'
]
</code>```

We can simply use the key= kwarg to do a natural sort:

>>> sorted(filelist, key=grouper)
['File1', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File007', 'File8',
'File8b1', 'File8b2', 'File8b11', 'File9', 'File10', 'File11']
```

The drawback here is of course, as it is now, the function will sort uppercase letters before lowercase letters.

I'll leave the implementation of a case-insenstive grouper to the reader :-)

Body:
I have a list of strings for which I would like to perform a natural alphabetical sort.

For instance, the following list is naturally sorted (what I want):

['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']

And here's the "sorted" version of the above list (what I get using sorted()):

['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']

I'm looking for a sort function which behaves like the first one.

Body:
Let me submit my own take on this need:

from typing import Tuple, Union, Optional, Generator

StrOrInt = Union[str, int]

# On Python 3.6, string concatenation is REALLY fast
# Tested myself, and this fella also tested:
# https://blog.ganssle.io/articles/2019/11/string-concat.html
def griter(s: str) -> Generator[StrOrInt, None, None]:
    last_was_digit: Optional[bool] = None
    cluster: str = ""
    for c in s:
        if last_was_digit is None:
            last_was_digit = c.isdigit()
            cluster += c
            continue
        if c.isdigit() != last_was_digit:
            if last_was_digit:
                yield int(cluster)
            else:
                yield cluster
            last_was_digit = c.isdigit()
            cluster = ""
        cluster += c
    if last_was_digit:
        yield int(cluster)
    else:
        yield cluster
    return

def grouper(s: str) -> Tuple[StrOrInt, ...]:
    return tuple(griter(s))

Now if we have the list like such:

filelist = [
    'File3', 'File007', 'File3a', 'File10', 'File11', 'File1', 'File4', 'File5',
    'File9', 'File8', 'File8b1', 'File8b2', 'File8b11', 'File6'
]

We can simply use the key= kwarg to do a natural sort:

>>> sorted(filelist, key=grouper)
['File1', 'File3', 'File3a', 'File4', 'File5', 'File6', 'File007', 'File8',
'File8b1', 'File8b2', 'File8b11', 'File9', 'File10', 'File11']

The drawback here is of course, as it is now, the function will sort uppercase letters before lowercase letters.

I'll leave the implementation of a case-insenstive grouper to the reader :-)


问:
Issue with URL encoding
I have a query string that will return data successfully if I run it in Postman but if I pull the data via Python3 (http.client.HTTPSConnection), the target returns 'bad request'.

The problem:

/v4_6_release/apis/3.0/service/tickets?customFieldConditions=caption="Escalated To" AND value ="Cloud Operations"

I have tried putting +AND+ or %20and%20 or %20AND%20 instead of AND but no success. For example:

/v4_6_release/apis/3.0/service/tickets?customFieldConditions=caption="Escalated To"%20AND%20value="Cloud Operations"

^ This works fine in postman but returns

HTTP Error 400. The request is badly formed.
 when via Python3.

Is there anything else wrong with the url encoding here?

答: You have to encode all whitespaces in you URL. So the URL should be /v4_6_release/apis/3.0/service/tickets?customFieldConditions=caption="Escalated%20To"%20AND%20value="Cloud%20Operations"

Title: Issue with URL encoding


问:
Why do I get Syntax error while assigning dictionary by single line for loop?
I tried to assign 'False' to dic[0] to dic[49] like this.

```<code>>>> dic = {}
>>> [ dic[i] = False for i in range(50)]
</code>```

but, I got this error msg.

```<code>  File "<stdin>", line 1
    [ dic[i] = False for i in range(50)]
             ^
SyntaxError: invalid syntax
</code>```

It worked by this way.

```<code>for i in range(50):
    dic[i] = False

</code>```

Why can't I use single line for loop for assigning dictionary?

答:
This [dic[i] = False for i in range(50)] is not single for loop, this is a list comprehension to collect values.

What you need is dict comprehension (at the end of the Dict section)

```<code>dic = {i: False for i in range(50)}
</code>```

Body:
I tried to assign 'False' to dic[0] to dic[49] like this.

>>> dic = {}
>>> [ dic[i] = False for i in range(50)]

but, I got this error msg.

  File "<stdin>", line 1
    [ dic[i] = False for i in range(50)]
             ^
SyntaxError: invalid syntax

It worked by this way.

for i in range(50):
    dic[i] = False

Why can't I use single line for loop for assigning dictionary?

Body:
This [dic[i] = False for i in range(50)] is not single for loop, this is a list comprehension to collect values.

What you need is dict comprehension (at the end of the Dict section)

dic = {i: False for i in range(50)}


问:
Python dependency on Gnome Builder
I am learning how to create GTK applications in python and I am using Gnome Builder IDE installed through flatpak.
I wanted to use the python package requests in my application, so I added:

```<code>{
    "name": "pip-install",
    "buildsystem": "simple",
    "build-options": {
      "build-args": [
        "--share=network"
      ]
    },
    "build-commands": [
        "pip3 install requests"
    ]
}
</code>```

To my modules list inside the flatpak .json file of the project.
When I try to build the project I get the following error when the command runs pip:

```<code>ERROR: Could not install packages due to an EnvironmentError: [Errno 30] Read-only file system: '/usr/lib/python3.7/site-packages/idna-2.9.dist-info'
</code>```

One solution would be the dependency being installed on user space, but how to do that?

答:
I've successfully used this snippet before:

```<code>    {
        "name": "requests",
        "buildsystem": "simple",
        "build-options": {
          "build-args": [
            "--share=network"
          ]
        },
        "build-commands": [
            "pip3 install --prefix=/app --no-cache-dir requests"
        ]
    }
</code>```

The /app directory is writable and the rest of your application should be there as well.

Title: Python dependency on Gnome Builder

Body:
I am learning how to create GTK applications in python and I am using Gnome Builder IDE installed through flatpak.
I wanted to use the python package requests in my application, so I added:

{
    "name": "pip-install",
    "buildsystem": "simple",
    "build-options": {
      "build-args": [
        "--share=network"
      ]
    },
    "build-commands": [
        "pip3 install requests"
    ]
}

To my modules list inside the flatpak .json file of the project.
When I try to build the project I get the following error when the command runs pip:

ERROR: Could not install packages due to an EnvironmentError: [Errno 30] Read-only file system: '/usr/lib/python3.7/site-packages/idna-2.9.dist-info'

One solution would be the dependency being installed on user space, but how to do that?

Body:
I've successfully used this snippet before:

    {
        "name": "requests",
        "buildsystem": "simple",
        "build-options": {
          "build-args": [
            "--share=network"
          ]
        },
        "build-commands": [
            "pip3 install --prefix=/app --no-cache-dir requests"
        ]
    }

The /app directory is writable and the rest of your application should be there as well.


问:
Detect Route Change with react-router
I have to implement some business logic depending on browsing history.

What I want to do is something like this:

```<code>reactRouter.onUrlChange(url => {
   this.history.push(url);
});
</code>```

Is there any way to receive a callback from react-router when the URL gets updated?

答:
React Router V5

If you want the pathName as a string ('/' or 'users'), you can use the following:

```<code>  // React Hooks: React Router DOM
  let history = useHistory();
  const location = useLocation();
  const pathName = location.pathname;
</code>```

Title: Detect Route Change with react-router

Body:
I have to implement some business logic depending on browsing history.

What I want to do is something like this:

reactRouter.onUrlChange(url => {
   this.history.push(url);
});

Is there any way to receive a callback from react-router when the URL gets updated?

Body:
React Router V5

If you want the pathName as a string ('/' or 'users'), you can use the following:

  // React Hooks: React Router DOM
  let history = useHistory();
  const location = useLocation();
  const pathName = location.pathname;


问:
AXIS1: How to personalize the "binding name"
We had the following generated webservices with axis1 tools:

```<code>  <wsdl:binding name="WSExamplePortSoapBinding" type="impl:WSExamplePortType">
  <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
  <wsdl:operation name="TestMethod">
  <wsdlsoap:operation soapAction="http://localhost/Example/wsdl/Example?wsdl#TestMethod" />
  <wsdl:input name="TestMethodRequest">
  <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://localhost/Example/wsdl/Example?wsdl" use="encoded" />
  </wsdl:input>
  <wsdl:output name="TestMethodResponse">
  <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://localhost/Example/wsdl/Example" use="encoded" />
  </wsdl:output>
  </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="WSExample">
  <wsdl:port binding="impl:WSExamplePortSoapBinding" name="WSExamplePort">
  <wsdlsoap:address location="http://localhost:8082/Example/wsdl/Example" />
  </wsdl:port>
  </wsdl:service>
</code>```

and the client want to us change the line:

```<code><wsdl:binding name="WSExamplePortSoapBinding" type="impl:WSExamplePortType">
</code>```

for:

```<code><binding name="WSExampleBinding" type="impl:WSExamplePortType">
</code>```

Q: How we can change that word? (WSExamplePortSoapBinding to WSExampleBinding).

We had searched on the axis source code, but we can't find were is generated that name.

Thanks for the help,

答:
I solved this issue like this:

In the server-config.wsdd file:

```<code><parameter name="wsdlServicePort" value="ExamplePort"/>
</code>```

I have to replace to:

```<code><parameter name="wsdlServicePort" value="Example"/>
</code>```

Then I have to modify the axis-1.4 source code like this:

```<code>setBindingName(getServicePortName() + "SoapBinding");
</code>```

I have to replace to:

```<code>setBindingName(getServicePortName() + "Binding");
</code>```

Then I have to make the JAR with ant and copy the new JAR to the source of the library.

Body:
We had the following generated webservices with axis1 tools:

  <wsdl:binding name="WSExamplePortSoapBinding" type="impl:WSExamplePortType">
  <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
  <wsdl:operation name="TestMethod">
  <wsdlsoap:operation soapAction="http://localhost/Example/wsdl/Example?wsdl#TestMethod" />
  <wsdl:input name="TestMethodRequest">
  <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://localhost/Example/wsdl/Example?wsdl" use="encoded" />
  </wsdl:input>
  <wsdl:output name="TestMethodResponse">
  <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://localhost/Example/wsdl/Example" use="encoded" />
  </wsdl:output>
  </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="WSExample">
  <wsdl:port binding="impl:WSExamplePortSoapBinding" name="WSExamplePort">
  <wsdlsoap:address location="http://localhost:8082/Example/wsdl/Example" />
  </wsdl:port>
  </wsdl:service>

and the client want to us change the line:

<wsdl:binding name="WSExamplePortSoapBinding" type="impl:WSExamplePortType">

for:

<binding name="WSExampleBinding" type="impl:WSExamplePortType">

Q: How we can change that word? (WSExamplePortSoapBinding to WSExampleBinding).

We had searched on the axis source code, but we can't find were is generated that name.

Thanks for the help,

Body:
I solved this issue like this:

In the server-config.wsdd file:

<parameter name="wsdlServicePort" value="ExamplePort"/>

I have to replace to:

<parameter name="wsdlServicePort" value="Example"/>

Then I have to modify the axis-1.4 source code like this:

setBindingName(getServicePortName() + "SoapBinding");

I have to replace to:

setBindingName(getServicePortName() + "Binding");

Then I have to make the JAR with ant and copy the new JAR to the source of the library.


问:
python apply a function after checking if variable is single list or list of lists
I intend to apply a function to a variable. I do not know beforehand if the incoming variable will be a list of list or a single list. e.g

```<code>var_name = [a, b, c]
or
var_name = [[a,b,c], [d,e,f], [h,i,j]]
</code>```

The list of list could contain as many lists as possible. How do I go about verifying if the variable is a list or list of lists. I intend to apply a function depending on the type. I tried to use len(var_name) but the length for list will be the number of items in single list while for list of lists, it is the number of lists in the list of lists.

what I am trying to achieve is this:

```<code>#function for list
def apply_val(lst):
    do something with single list
#function for list of list
def apply_val2(lst):
    do something with list of lists

var_name = single_list or list_of_lists
if var_name == single list
    apply_val(single_list)
else:
    apply_val(list_of_lists)
</code>```

How do I check if the var_name is a list or list of lists?

答:
Try this</p>

```<code>def check_list(test_list):
    if type(test_list[0]) == list:
        return True
    else:
        return False
</code>```

Body:
I intend to apply a function to a variable. I do not know beforehand if the incoming variable will be a list of list or a single list. e.g

var_name = [a, b, c]
or
var_name = [[a,b,c], [d,e,f], [h,i,j]]

The list of list could contain as many lists as possible. How do I go about verifying if the variable is a list or list of lists. I intend to apply a function depending on the type. I tried to use len(var_name) but the length for list will be the number of items in single list while for list of lists, it is the number of lists in the list of lists.

what I am trying to achieve is this:

#function for list
def apply_val(lst):
    do something with single list
#function for list of list
def apply_val2(lst):
    do something with list of lists

var_name = single_list or list_of_lists
if var_name == single list
    apply_val(single_list)
else:
    apply_val(list_of_lists)

How do I check if the var_name is a list or list of lists?

Body:
Try this

def check_list(test_list):
    if type(test_list[0]) == list:
        return True
    else:
        return False


问:
How to speed-up k-means from Scikit learn?
On my project I have used k-means to classify data between groups, but I have a problem with the computation of the k-means from Scikit-learn - it was very slow. I need to boost it.

I have tried to change the number of n_jobs to -1, but still very slow!

Any suggestions how to speed up?

答:
scikit-learn 0.23+ now comes with an optimized implementation with a new way to parallelize work across CPUs:

https://scikit-learn.fondation-inria.fr/implementing-a-faster-kmeans-in-scikit-learn-0-23/


问:
Flexbox won't align horizontally
Based on everyhting I've googled, flexbox should be displaying in a horizontal row by default, but I feel like I've tried everything and can't get this to work. I will post the code below. If you remove the "display: flex;" from the css it looks similar to how I want it to look, but I want the heights of the 3 divs to all be even, which is why I want to use flexbox. Any help would be appreciated.

/*PARENT*/
form fieldset{
    display: flex;
    flex-direction: row;
    padding: 5px 0px;
    border: 0;
}

/*CHILDREN*/
form fieldset > div{
    display: inline-block;
    width: 25%;
    text-align: center;
    border: solid thin black;
}

/*STYLES*/
form fieldset:first-of-type > div > p{
    text-decoration: underline;
    font-size: 1.2em;
}

form fieldset:first-of-type > div > div{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    font-size: 0.9em;
}

form fieldset:first-of-type div p{
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <link rel="stylesheet" href="temp_css.css">
</head>
<body>
    <form action="temp.html">
        <fieldset id="fieldset">
            <div id="movie">
                <p>Movie or TV Show?</p>
                <div>
                    <label for="movie">Movie</label>
                    <input type="radio" name="tv_or_movie" id="movie">
                    <label for="tv">TV Show</label>
                    <input type="radio" name="tv_or_movie" id="tv">
                </div>
            </div>
            <div id="animated">
                <p>Is It Animated?</p>
                <div>
                    <label for="animated_yes">Yes</label>
                    <input type="radio" name="animated" id="animated_yes">
                    <label for="animated_no">No</label>
                    <input type="radio" name="animated" id="animated_no">
                </div>
            </div>
            <div id="favorites">
                <p>Would You Consider it One of Your Favorites?</p>
                <div>
                    <label for="favorites_yes">Yes</label>
                    <input type="radio" name="favorite" id="favorites_yes">
                    <label for="favorites_no">No</label>
                    <input type="radio" name="favorite" id="favorites_no">
                </div>
            </div>
        </fieldset>
    </form>
</body>
</html></code>```

答:
Its fieldset tag that is not respond to flex container , you should use other element if you want flex to be worked. i have used below section tag to solve you are free to try other tags.

/*PARENT*/
form fieldset{
    display: flex;
    flex-direction: row;
    padding: 5px 0px;
    border: 0;
}

/*CHILDREN*/
form section > div{
    display: inline-block;
    width: 25%;
    text-align: center;
    border: solid thin black;
}

/*STYLES*/
form fieldset:first-of-type > div > p{
    text-decoration: underline;
    font-size: 1.2em;
}

form fieldset:first-of-type > div > div{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    font-size: 0.9em;
}

form fieldset:first-of-type div p{
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <link rel="stylesheet" href="temp_css.css">
</head>
<body>
    <form action="temp.html">
        <section id="fieldset">
            <div id="movie">
                <p>Movie or TV Show?</p>
                <div>
                    <label for="movie">Movie</label>
                    <input type="radio" name="tv_or_movie" id="movie">
                    <label for="tv">TV Show</label>
                    <input type="radio" name="tv_or_movie" id="tv">
                </div>
            </div>
            <div id="animated">
                <p>Is It Animated?</p>
                <div>
                    <label for="animated_yes">Yes</label>
                    <input type="radio" name="animated" id="animated_yes">
                    <label for="animated_no">No</label>
                    <input type="radio" name="animated" id="animated_no">
                </div>
            </div>
            <div id="favorites">
                <p>Would You Consider it One of Your Favorites?</p>
                <div>
                    <label for="favorites_yes">Yes</label>
                    <input type="radio" name="favorite" id="favorites_yes">
                    <label for="favorites_no">No</label>
                    <input type="radio" name="favorite" id="favorites_no">
                </div>
            </div>
        </section>
    </form>
</body>
</html></code>```

Title: Flexbox won't align horizontally

Body:
Based on everyhting I've googled, flexbox should be displaying in a horizontal row by default, but I feel like I've tried everything and can't get this to work. I will post the code below. If you remove the "display: flex;" from the css it looks similar to how I want it to look, but I want the heights of the 3 divs to all be even, which is why I want to use flexbox. Any help would be appreciated.

/*PARENT*/
form fieldset{
    display: flex;
    flex-direction: row;
    padding: 5px 0px;
    border: 0;
}

/*CHILDREN*/
form fieldset > div{
    display: inline-block;
    width: 25%;
    text-align: center;
    border: solid thin black;
}

/*STYLES*/
form fieldset:first-of-type > div > p{
    text-decoration: underline;
    font-size: 1.2em;
}

form fieldset:first-of-type > div > div{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    font-size: 0.9em;
}

form fieldset:first-of-type div p{
    text-align: center;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <link rel="stylesheet" href="temp_css.css">

    <form action="temp.html">
        <fieldset id="fieldset">

Movie or TV Show?

                    Movie
                    <input type="radio" name="tv_or_movie" id="movie">
                    TV Show
                    <input type="radio" name="tv_or_movie" id="tv">

Is It Animated?

                    Yes
                    <input type="radio" name="animated" id="animated_yes">
                    No
                    <input type="radio" name="animated" id="animated_no">

Would You Consider it One of Your Favorites?

                    Yes
                    <input type="radio" name="favorite" id="favorites_yes">
                    No
                    <input type="radio" name="favorite" id="favorites_no">

        </fieldset>
    </form>

Body:
Its fieldset tag that is not respond to flex container , you should use other element if you want flex to be worked. i have used below section tag to solve you are free to try other tags.

/*PARENT*/
form fieldset{
    display: flex;
    flex-direction: row;
    padding: 5px 0px;
    border: 0;
}

/*CHILDREN*/
form section > div{
    display: inline-block;
    width: 25%;
    text-align: center;
    border: solid thin black;
}

/*STYLES*/
form fieldset:first-of-type > div > p{
    text-decoration: underline;
    font-size: 1.2em;
}

form fieldset:first-of-type > div > div{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    font-size: 0.9em;
}

form fieldset:first-of-type div p{
    text-align: center;
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <link rel="stylesheet" href="temp_css.css">
</head>
<body>
    <form action="temp.html">
        <section id="fieldset">
            <div id="movie">
                <p>Movie or TV Show?</p>
                <div>
                    <label for="movie">Movie</label>
                    <input type="radio" name="tv_or_movie" id="movie">
                    <label for="tv">TV Show</label>
                    <input type="radio" name="tv_or_movie" id="tv">
                </div>
            </div>
            <div id="animated">
                <p>Is It Animated?</p>
                <div>
                    <label for="animated_yes">Yes</label>
                    <input type="radio" name="animated" id="animated_yes">
                    <label for="animated_no">No</label>
                    <input type="radio" name="animated" id="animated_no">
                </div>
            </div>
            <div id="favorites">
                <p>Would You Consider it One of Your Favorites?</p>
                <div>
                    <label for="favorites_yes">Yes</label>
                    <input type="radio" name="favorite" id="favorites_yes">
                    <label for="favorites_no">No</label>
                    <input type="radio" name="favorite" id="favorites_no">
                </div>
            </div>
        </section>
    </form>
</body>
</html>


问:
How do I write text to the username/password input controls of a 3rd party page using ASP.NET?
My title is pretty much the question: "How do I write text to the username/password input controls of a 3rd party web page using ASP.NET?"

Just for examples sake, if I wanted to write an ASP.NET page that would initially authenticate  a user on my end, and then redirect to a 3rd party site and log into it using the fields displayed with credentials my app has within it (encypted obviously), how can I do this?

If you had ever seen the old Microsoft FingerPrint reader USB control, it used to do this. The software would allow you to highlight fields on a web page, and then store the credentials you provide it, and auto write to the fields upon visiting the site and using your fingerprint. I don't want the finger print reader, just the similar functionality.

It will be a static 3rd party site and does not have to account for any site visited. I should be able to look at the source of the site I need to log into to if this helps.

Anyone know how to go about this? Thanks!!

答:
You want to control the user's browser on a 3rd party site on a different domain.  This is not possible due to browser security restrictions.  You could try to open an IFRAME to a 3rd party site from your webpage, but you won't be able to do anything on the user's behalf.

See MSDN: Cross Frame Scripting Security


问:
action is not a function react-redux
login undefined

I am getting login as undefined, whenever I click the login button it was working fine before I created AppRoutes.js and moved some of the routes into that file.

TypeError: login is not a function

here is the code structure.

this is the main file where app is started and login route is put here inside the AppRoutes component.

app.js

```<code>import React, { Fragment, useEffect } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import Navbar from './components/layout/Navbar'
import Landing from './components/layout/Landing'
import Alert from './components/layout/Alert'
import { loadUser } from './actions/auth'
import { Provider } from 'react-redux'
import setAuthToken from './utils/setAuthToken'
import store from './store'
import './App.css'
import AppRoutes from './components/routing/AppRoutes'
if (localStorage.token) {
  setAuthToken(localStorage.token)
}
const App = () => {
  useEffect(() => {
    store.dispatch(loadUser())
  }, [])
  return (
    <Provider store={store}>
      <Router >
        <Fragment>
          <Navbar />
          <Alert />
          <Switch>
            <Route exact path='/' component={Landing} />
            <Route component={AppRoutes} />
          </Switch>

        </Fragment>
      </Router>
    </Provider>
  )
}

export default App
</code>```

2.AppRoutes.js

```<code>import React, { Fragment } from 'react'
import { Register } from '../auth/Register'
import { Login } from '../auth/Login'
import Dashboard from '../dashboard/Dashboard'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import PrivateRoute from './PrivateRoute'
import { NotFound } from '../layout/NotFound'
import store from '../../store'
import { Provider } from 'react-redux'
const AppRoutes = () => {
    return (<Fragment>
        <Switch>
            <Route exact path='/register' component={Register} />
            <Route exact path='/login' component={Login} />
            <PrivateRoute path='/dashboard' component={Dashboard} >
            </PrivateRoute>
            <Route component={NotFound} />
        </Switch>
    </Fragment>
    )
}

export default AppRoutes
</code>```

auth.js

```<code>export const login = (email, password) => async dispatch => {
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    }

    const body = JSON.stringify({ email, password })
    try {
        const res = await axios.post('/api/auth', body, config)
        if (res?.data?.token) {
            dispatch({
                type: LOGIN_SUCCESS,
                payload: res.data
            })
            dispatch(loadUser())
        }
        else {
            dispatch(setAlert(res.data.msg, 'success'))
        }
    } catch (error) {
        const errors = error.response.data.errors
        if (errors) {
            errors.forEach(error => dispatch(setAlert(error.msg, 'danger')))
        }
        dispatch({
            type: LOGIN_FAIL
        })
    }
}
</code>```

4.Login.js

```<code>import React, { Fragment, useState } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { login } from '../../actions/auth'
import { Link, Redirect } from 'react-router-dom'
import store from '../../store'

export const Login = ({ isAuthenticated, login }) => {
    const [formData, setFormData] = useState({

        email: '',
        password: ''

    })

    const { email, password } = formData

    const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value })

    const onSubmit = e => {
        e.preventDefault()
        console.log(typeof login)
        login(email, password)
    }

    //redirect if logged in

    if (isAuthenticated) {
        return <Redirect to='/dashboard' />
    }

    return (
        <Fragment>
            <div className="m-5">
                <div className="row justify-content-center">
                    <div className="col-md-4">
                        <div className="card shadow-lg o-hidden border-0 my-5">
                            <div className="card-body p-0">
                                <div>
                                    <div className="p-5">
                                        <div className="text-center">
                                            <h4 className="text-dark mb-4">Welcome Back!</h4>
                                        </div>
                                        <form className="user" onSubmit={e => onSubmit(e)}>
                                            <div className="form-group">
                                                <input className="form-control form-control-user" type="email" placeholder="Email Address" name="email" value={email} onChange={e => onChange(e)} required />
                                            </div>
                                            <div className="form-group">
                                                <input className="form-control form-control-user" type="password"
                                                    placeholder="Password"
                                                    name="password"
                                                    minLength="6"
                                                    value={password} onChange={e => onChange(e)}
                                                />
                                            </div>
                                            <div className="form-group">
                                                <div className="custom-control custom-checkbox small">
                                                    <div className="form-check">
                                                        <input className="form-check-input custom-control-input" type="checkbox" id="formCheck-1" />
                                                        <label className="form-check-label custom-control-label" htmlFor="formCheck-1">Remember Me</label>
                                                    </div>
                                                </div>
                                            </div><button className="btn btn-dark btn-block text-white btn-user" type="submit">Login</button>
                                            <hr />
                                        </form>
                                        <div className="text-center"><Link to="/register" className="small" href="register.html">Create an Account!</Link></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </Fragment >
    )
}
Login.propTypes = {
    login: PropTypes.func.isRequired,
    isAuthenticated: PropTypes.bool
}

const mapStateToProps = state => ({
    isAuthenticated: state.auth.isAuthenticated

})

export default connect(mapStateToProps, { login })(Login)
</code>```

I am not able to figure out whether it is related to the route structure that i changed or is there a bigger problem that I am missing out on.

答:
You have imported Login a named import in AppRoutes, whereas the connected component with Login was a default export which is why you see the issue

Change

```<code>import { Login } from '../auth/Login'
</code>```

to

```<code>import Login from '../auth/Login'
</code>```

Title: action is not a function react-redux

Body:
login undefined

I am getting login as undefined, whenever I click the login button it was working fine before I created AppRoutes.js and moved some of the routes into that file.

TypeError: login is not a function

here is the code structure.

this is the main file where app is started and login route is put here inside the AppRoutes component.

app.js

import React, { Fragment, useEffect } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import Navbar from './components/layout/Navbar'
import Landing from './components/layout/Landing'
import Alert from './components/layout/Alert'
import { loadUser } from './actions/auth'
import { Provider } from 'react-redux'
import setAuthToken from './utils/setAuthToken'
import store from './store'
import './App.css'
import AppRoutes from './components/routing/AppRoutes'
if (localStorage.token) {
  setAuthToken(localStorage.token)
}
const App = () => {
  useEffect(() => {
    store.dispatch(loadUser())
  }, [])
  return (
    <Provider store={store}>
      <Router >
        <Fragment>
          <Navbar />
          <Alert />
          <Switch>
            <Route exact path='/' component={Landing} />
            <Route component={AppRoutes} />
          </Switch>

        </Fragment>
      </Router>
    </Provider>
  )
}

export default App

2.AppRoutes.js

import React, { Fragment } from 'react'
import { Register } from '../auth/Register'
import { Login } from '../auth/Login'
import Dashboard from '../dashboard/Dashboard'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import PrivateRoute from './PrivateRoute'
import { NotFound } from '../layout/NotFound'
import store from '../../store'
import { Provider } from 'react-redux'
const AppRoutes = () => {
    return (<Fragment>
        <Switch>
            <Route exact path='/register' component={Register} />
            <Route exact path='/login' component={Login} />
            <PrivateRoute path='/dashboard' component={Dashboard} >
            </PrivateRoute>
            <Route component={NotFound} />
        </Switch>
    </Fragment>
    )
}

export default AppRoutes

auth.js

export const login = (email, password) => async dispatch => {
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    }

    const body = JSON.stringify({ email, password })
    try {
        const res = await axios.post('/api/auth', body, config)
        if (res?.data?.token) {
            dispatch({
                type: LOGIN_SUCCESS,
                payload: res.data
            })
            dispatch(loadUser())
        }
        else {
            dispatch(setAlert(res.data.msg, 'success'))
        }
    } catch (error) {
        const errors = error.response.data.errors
        if (errors) {
            errors.forEach(error => dispatch(setAlert(error.msg, 'danger')))
        }
        dispatch({
            type: LOGIN_FAIL
        })
    }
}

4.Login.js

import React, { Fragment, useState } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { login } from '../../actions/auth'
import { Link, Redirect } from 'react-router-dom'
import store from '../../store'

export const Login = ({ isAuthenticated, login }) => {
    const [formData, setFormData] = useState({

        email: '',
        password: ''

    })

    const { email, password } = formData

    const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value })

    const onSubmit = e => {
        e.preventDefault()
        console.log(typeof login)
        login(email, password)
    }

    //redirect if logged in

    if (isAuthenticated) {
        return <Redirect to='/dashboard' />
    }

    return (
        <Fragment>

Welcome Back!

                                        <form className="user" onSubmit={e => onSubmit(e)}>

                                                <input className="form-control form-control-user" type="email" placeholder="Email Address" name="email" value={email} onChange={e => onChange(e)} required />

                                                <input className="form-control form-control-user" type="password"
                                                    placeholder="Password"
                                                    name="password"
                                                    minLength="6"
                                                    value={password} onChange={e => onChange(e)}
                                                />

                                                        <input className="form-check-input custom-control-input" type="checkbox" id="formCheck-1" />
                                                        Remember Me

<button className="btn btn-dark btn-block text-white btn-user" type="submit">Login</button>

                                        </form>

<Link to="/register" className="small" href="register.html">Create an Account!</Link>

        </Fragment >
    )
}
Login.propTypes = {
    login: PropTypes.func.isRequired,
    isAuthenticated: PropTypes.bool
}

const mapStateToProps = state => ({
    isAuthenticated: state.auth.isAuthenticated

})

export default connect(mapStateToProps, { login })(Login)

I am not able to figure out whether it is related to the route structure that i changed or is there a bigger problem that I am missing out on.

Body:
You have imported Login a named import in AppRoutes, whereas the connected component with Login was a default export which is why you see the issue

Change

import { Login } from '../auth/Login'

to

import Login from '../auth/Login'


问:
React hook that runs AFTER the DOM updates
I have a React app where I am hiding/showing an element based on state, and want to do some  calculations on that DOM element after the state variable changes.

I've tried using useLayoutEffect, but this still runs before the DOM has updated, so my calculations aren't useful. Is my understanding of useLayoutEffect wrong? Am I using it incorrectly?

Here's what I have

const myComponent = () => {

  const elem = useRef()
  const [isElemVisible, setIElemVisible] = useState(false)

  useLayoutEffect(() => {
    // I want this to run AFTER the element is added/removed from the DOM
    // Instead this is run before the element is actually modified in the DOM (but the ref itself has changed)

    elem.current.getBoundingClientRect() // do something with this object if it exists
  }, [elem.current])

  return (

    { isElemVisible && (

    )}

  )
}
```

答:
You can try to pass a function as ref and do stuff in that function:

```<code>const myComponent = () => {

  // other component code

  const elemRef = useCallback((node) => {
    if (node !== null) {
      // do stuff here
    }
  }, [])

  return (
   <div id="base-element">
    { isElemVisible && (
      <div id="element" ref={elemRef}></div>
    )}
   </div>
  )
}
</code>```

Check out this https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node

Body:
You can try to pass a function as ref and do stuff in that function:

const myComponent = () => {

  // other component code

  const elemRef = useCallback((node) => {
    if (node !== null) {
      // do stuff here
    }
  }, [])

  return (
   <div id="base-element">
    { isElemVisible && (
      <div id="element" ref={elemRef}></div>
    )}
   </div>
  )
}

Check out this https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node


问:
Using Httprequest to get pictures from given URL
I'm trying to get pictures from webcams. There is a php-python web service to get the pictures from webcams and serve them: it serves the picture like http://ip/jpeg/camera=1.

```<code>private HttpWebRequest request;
private HttpWebResponse response;
private CookieContainer container;
private Uri uri;
private string _user;
private string _pass;
private string _ip;
//Login code as seen in the previous section should be here
//GetImages is meant to run as a separate thread
private void GetImages(string camNo)
{
//create the GET request for the JPEG snapshot (found at /jpeg on the IP Camera)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + deviceIP + "/jpeg/camera"+camNo);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = container;

//attempt to get a response from the IP110, event if error

try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
    ConnectionError(new ConnectionErrorEventArgs(e.Message));
}

//Get the stream containing the JPEG image.
Stream stream = response.GetResponseStream();

//Read the stream to memory.
byte[] buffer = new byte[100000];
int read, total = 0;

while ((read = stream.Read(buffer, total, 1000)) != 0)
{
    total += read;
}

//create a BMP image from the stream
Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0, total));

//send the bmp image to where you would like to display it.
 }
</code>```

... then I store that bitmap as a jpeg to a folder.  My problem starts here; I want to do that process as fast as possible.  I want to take pictures from 50 webcams using that code and store as jpeg, and it has to be fast - I mean every 10 seconds I have to get new pictures from 50 cams.

I used timercontrol, and give it 500 ms every 500ms program use that code above up to camera
number and save the jpeg, but it work one after another so performance gets low!

50ms x 500cams = 25000 ms (25sec), if I arrange timer control's interval 100 ms program freeze.
When I use the code above I get bitmap bmp in 200 ms but when it tries to write as jpeg on disc it takes a long time.

What can I do to write to disk faster? I looked for memory mapped - would it help? I want to store jpegs on disc becouse I will serve these pictures on a web site and share them with people. Can I use memory mapped and serve it publicly via a web site?

UPDATE:
I also used WebClient class for async works,
http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=571

The result was: To get a picture like 300 ms and writing it to disk about 700ms
So I have to find a solution to write to disk as much as possible.

Which one is better? To write the pictures to disk or to send images to database?
I tried to store the pictures to make them ready for serve, because on the website people have to see updated pictures. Which one is better for thousands of client query? To store them on disk or store them on database as binary?

答:
The code to fetch the images is synchronous. I would suggest modifying your code to use HttpWebRequest.BeginGetResponse() to fetch your images as detailed in this answer.

So when your (single) timer fires, begin the async requests to your cams, then (as they complete) the callback will fire for each completed request, and you can save off the returned image.

If you need to optimize further, then you could delegate saving the image to disk to a background ThreadPool work item.

Body:
I'm trying to get pictures from webcams. There is a php-python web service to get the pictures from webcams and serve them: it serves the picture like http://ip/jpeg/camera=1.

private HttpWebRequest request;
private HttpWebResponse response;
private CookieContainer container;
private Uri uri;
private string _user;
private string _pass;
private string _ip;
//Login code as seen in the previous section should be here
//GetImages is meant to run as a separate thread
private void GetImages(string camNo)
{
//create the GET request for the JPEG snapshot (found at /jpeg on the IP Camera)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + deviceIP + "/jpeg/camera"+camNo);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = container;

//attempt to get a response from the IP110, event if error

try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
    ConnectionError(new ConnectionErrorEventArgs(e.Message));
}

//Get the stream containing the JPEG image.
Stream stream = response.GetResponseStream();

//Read the stream to memory.
byte[] buffer = new byte[100000];
int read, total = 0;

while ((read = stream.Read(buffer, total, 1000)) != 0)
{
    total += read;
}

//create a BMP image from the stream
Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0, total));

//send the bmp image to where you would like to display it.
 }

... then I store that bitmap as a jpeg to a folder.  My problem starts here; I want to do that process as fast as possible.  I want to take pictures from 50 webcams using that code and store as jpeg, and it has to be fast - I mean every 10 seconds I have to get new pictures from 50 cams.

I used timercontrol, and give it 500 ms every 500ms program use that code above up to camera
number and save the jpeg, but it work one after another so performance gets low!

50ms x 500cams = 25000 ms (25sec), if I arrange timer control's interval 100 ms program freeze.
When I use the code above I get bitmap bmp in 200 ms but when it tries to write as jpeg on disc it takes a long time.

What can I do to write to disk faster? I looked for memory mapped - would it help? I want to store jpegs on disc becouse I will serve these pictures on a web site and share them with people. Can I use memory mapped and serve it publicly via a web site?

UPDATE:
I also used WebClient class for async works,
http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=571

The result was: To get a picture like 300 ms and writing it to disk about 700ms
So I have to find a solution to write to disk as much as possible.

Which one is better? To write the pictures to disk or to send images to database?
I tried to store the pictures to make them ready for serve, because on the website people have to see updated pictures. Which one is better for thousands of client query? To store them on disk or store them on database as binary?


问:
Select the first visible cell in every sheet with a loop in VBA
I use the below VBA to select the first visible cell in a filtered range:

```<code>Sub Postioning_Option_01()
Sheet1.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
End Sub
</code>```

Now, instead of only applying this VBA to Sheet1 I want to loop through all sheets.

Therefore, I tried to go with this VBA:

```<code>Sub Postioning_Option_02()
Dim b As Worksheet
For Each b In Worksheets
b.Select
b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
Next b
End Sub
</code>```

When I run this VBA I get error Object variable or With block variable not set.

What do I need to change in the VBA to make it work?

答:
This will skip sheets with no autofilter:</p>

```<code>Sub Postioning_Option_02()

    Dim b As Worksheet
    For Each b In Worksheets
        If b.AutoFilterMode Then
            b.Select
            b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
        End If
    Next b

End Sub
</code>```

Body:
I use the below VBA to select the first visible cell in a filtered range:

Sub Postioning_Option_01()
Sheet1.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
End Sub

Now, instead of only applying this VBA to Sheet1 I want to loop through all sheets.

Therefore, I tried to go with this VBA:

Sub Postioning_Option_02()
Dim b As Worksheet
For Each b In Worksheets
b.Select
b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
Next b
End Sub

When I run this VBA I get error Object variable or With block variable not set.

What do I need to change in the VBA to make it work?

Body:
This will skip sheets with no autofilter:

Sub Postioning_Option_02()

    Dim b As Worksheet
    For Each b In Worksheets
        If b.AutoFilterMode Then
            b.Select
            b.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
        End If
    Next b

End Sub


问:
How to run Tizen Certificate Manager from Visual Studio
I use Visual Studio Community 2019 Version 16.6 with Visual Studio Tools for Tizen (3.1.0.0).
Tizen projects can be built and run on a Tizen Emulator but when I try to open Tizen Certificate Manager from Tools > Tizen > Tizen Certificate Manager it doesn't open anything. The only thing I see when Visual Studio runs without administrator rights is a window to allow certificate-manager.exe to make changes on device.

How to run the Tizen Certificate Manager properly?

答:
First of all, plz, check new UPDATE of Tizen-SDK via Tools > Tizen > Tizen Package Manager
Recommend to use latest SDK environment.</p>


问:
How to export JavaScript array info to csv (on client side)?
I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which looks like this:

```<code>[["name1", "city_name1", ...]["name2", "city_name2", ...]]
</code>```

Any idea how I can export this to CSV on the client side?

答:
If you are looking for a really quick solution you can also give a chance to this small library which will create and download CSV file for you: https://github.com/mbrn/filefy

Usage is very simple:

```<code>import { CsvBuilder } from 'filefy';

var csvBuilder = new CsvBuilder("user_list.csv")
  .setColumns(["name", "surname"])
  .addRow(["Eve", "Holt"])
  .addRows([
    ["Charles", "Morris"],
    ["Tracey", "Ramos"]
  ])
  .exportFile();
</code>```

Body:
I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which looks like this:

[["name1", "city_name1", ...]["name2", "city_name2", ...]]

Any idea how I can export this to CSV on the client side?

Body:
If you are looking for a really quick solution you can also give a chance to this small library which will create and download CSV file for you: https://github.com/mbrn/filefy

Usage is very simple:

import { CsvBuilder } from 'filefy';

var csvBuilder = new CsvBuilder("user_list.csv")
  .setColumns(["name", "surname"])
  .addRow(["Eve", "Holt"])
  .addRows([
    ["Charles", "Morris"],
    ["Tracey", "Ramos"]
  ])
  .exportFile();


问:
What is the best way to make clickable text in java?
This is for an application so I don't want a hyperlink. I first tried using a Jbutton without all of border/background stuff and then hooking up an actionListener to it but I couldn't get it to the point where I thought it looked nice.  I also tried using a JLabel and hooking up a mouse listener to that but I also couldn't get it to look right.

Basically I would like a way using swing to make a button exactly like a url link in an application.  What is the standard way of doing this?

答:
It is a rather heavy hammer to use, but SwingX has a JXHyperLink control that is probably exactly what you want. The source is at http://java.net/projects/swingx/sources/svn/content/trunk/swingx-core/src/main/java/org/jdesktop/swingx/JXHyperlink.java?rev=4027 and you can see an article about it at http://www.javalobby.org/java/forums/t18617.html.

It is old, but SwingX continues to do good things.


问:
why is my menu not showing an inside list brand?
HTML
This is my HTML source code where I want to make a menu list with flexbox and grid.

```<code><!DOCTYPE html>
<html>
<head>
    <title>dmghdfjb</title>
    <link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>

    <header>
      <div id="brand">
            <a href="index.html"><img src="images/22.jpg"></a>
        <ul class="menulist">
          <li class="list"><a href="index.html">Home</a></li>
          <li class="list square"><a href=entry.html>Booking</a></li>
          <li class="list square"><a href="#">Resturant</a></li>
          <li class="list square"><a href="over.html">Overview</a></li>
          <li class="list square"><a href="signup">Login</a></li>
        </ul>
      </div>
    </header>
</body>
</html>
</code>```

CSS

```<code>*{
    margin: 0;
    padding: 0;
}
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
header{
    width: 100%;
    background-color: #EC8C01;
    height: 100px;
    display: flex;
    align-content: center;
}
#brand{
    width: 200px;
    height: 98px;
}
#brand > a > img{
    width: 100%;
    height: 100%;
}
#menu{
    display: flex;
}
.menulist{
    background-color: red;
    list-style: none;
    padding: 5px;
    text-align: center;
    display: inline-grid;
    grid-template-columns: repeat(5,100px);
    grid-gap: 5px;
    justify-content: end;
}
.list{
    background-color: green;
    padding: 10px;
    border-radius: 40px;
}
</code>```

In the above code, My menu list not showing in the brand area. I want to make a menu list that is fixed inside ` without using position property of CSS. How to fix it?

答:
HTML

   *{
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    header{
        width: 100%;
        background-color: #EC8C01;
        height: 100px;
        display: flex;
        align-content: center;
    }
    #brand{
        width: 200px;
        height: 98px;
    }
    #brand > a > img{
        width: 100%;
        height: 100%;
    }
    .menu-wrapper{
        margin-top: 24px;
    }
    #menu{
        display: flex;
    }
    .menulist{
        background-color: red;
        list-style: none;
        padding: 5px;
        text-align: center;
        display: inline-grid;
        grid-template-columns: repeat(5,100px);
        grid-gap: 5px;
        justify-content: end;
        /*float: right;*/
        margin-right: 34px;
    }
    .list{
        background-color: green;
        padding: 10px;
        border-radius: 40px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>
    <html>
    <head>
        <title>dmghdfjb</title>
        <link rel="stylesheet" type="text/css" href="index.css">
        <style type="text/css">

        </style>

    </head>
    <body>

        <header>
          <div id="brand">
                <img src="https://www.internetkatta.com/wp-content/uploads/2015/04/logo350.png">

          </div>
          <div class="menu-wrapper">
               <ul class="menulist">
              <li class="list">Home</li>
              <li class="list square">Booking</li>
              <li class="list square">Resturant</li>
              <li class="list square">Overview</li>
              <li class="list square">Login</li>
            </ul>
          </div>
        </header>
    </body>
    </html></code>```

Here is no use of float:right;
@aviboy.

Body:
HTML
This is my HTML source code where I want to make a menu list with flexbox and grid.

<!DOCTYPE html>

    <title>dmghdfjb</title>
    <link rel="stylesheet" type="text/css" href="index.css">

Home

Booking

Resturant

Overview

Login

CSS

*{
    margin: 0;
    padding: 0;
}
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
header{
    width: 100%;
    background-color: #EC8C01;
    height: 100px;
    display: flex;
    align-content: center;
}
#brand{
    width: 200px;
    height: 98px;
}
#brand > a > img{
    width: 100%;
    height: 100%;
}
#menu{
    display: flex;
}
.menulist{
    background-color: red;
    list-style: none;
    padding: 5px;
    text-align: center;
    display: inline-grid;
    grid-template-columns: repeat(5,100px);
    grid-gap: 5px;
    justify-content: end;
}
.list{
    background-color: green;
    padding: 10px;
    border-radius: 40px;
}

In the above code, My menu list not showing in the brand area. I want to make a menu list that is fixed inside ` without using position property of CSS. How to fix it?

Body:
HTML

   *{
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    header{
        width: 100%;
        background-color: #EC8C01;
        height: 100px;
        display: flex;
        align-content: center;
    }
    #brand{
        width: 200px;
        height: 98px;
    }
    #brand > a > img{
        width: 100%;
        height: 100%;
    }
    .menu-wrapper{
        margin-top: 24px;
    }
    #menu{
        display: flex;
    }
    .menulist{
        background-color: red;
        list-style: none;
        padding: 5px;
        text-align: center;
        display: inline-grid;
        grid-template-columns: repeat(5,100px);
        grid-gap: 5px;
        justify-content: end;
        /*float: right;*/
        margin-right: 34px;
    }
    .list{
        background-color: green;
        padding: 10px;
        border-radius: 40px;
    }

 <!DOCTYPE html>
    <html>
    <head>
        <title>dmghdfjb</title>
        <link rel="stylesheet" type="text/css" href="index.css">
        <style type="text/css">

        </style>

    </head>
    <body>

        <header>
          <div id="brand">
                <a href="index.html"><img src="https://www.internetkatta.com/wp-content/uploads/2015/04/logo350.png"></a>

          </div>
          <div class="menu-wrapper">
               <ul class="menulist">
              <li class="list"><a href="index.html">Home</a></li>
              <li class="list square"><a href=entry.html>Booking</a></li>
              <li class="list square"><a href="#">Resturant</a></li>
              <li class="list square"><a href="over.html">Overview</a></li>
              <li class="list square"><a href="signup">Login</a></li>
            </ul>
          </div>
        </header>
    </body>
    </html>

Here is no use of float:right;
@aviboy.


问:
unable to insert dynamic rows into table using mysql and nodejs
I am trying to insert array of objects into the SQL but getting the following error

```<code>  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?,?)' at line 1",
  sqlState: '42000',
  index: 0,
  sql: 'INSERT INTO orderedproducts (order_id, product_id, quantity) VALUES ((19, 10, 2),?,?)'
</code>```

This my testing array of object

```<code>var testData = [
                  {
                     productId: 10,
                     quantity: 2
                  }
               ]
</code>```

I want to insert this object data into sql.

My current written code which is returning above error

```<code>let lastId = results.insertId

                    let orderedProductSql = 'INSERT INTO orderedproducts (order_id, product_id, quantity) VALUES (?,?,?)'

                    var testData = [
                        {
                            productId: 10,
                            quantity: 2
                        }
                    ]

                    let values = testData.reduce((o, a) => {
                        let ini = []
                        ini.push(lastId)
                        ini.push(a.productId)
                        ini.push(a.quantity)
                        o.push(ini)
                        return o
                    }, [])

                    connection.query(orderedProductSql, [values], (err, results) => {
                        if (err) {
                            return connection.rollback(_ => {
                                throw err
                            })
                        }
                        connection.commit(err => {
                            if (err) {
                                connection.rollback(_ => {
                                    throw err
                                })
                            }
                            connection.release()
                            callBack(null, results)
                        })
                    })
</code>```

How can I solve this ??

答:
Try doing something like this:

```<code>connection.query( "INSERT INTO orderedproducts SET order_id=?, product_id=?, quantity=?" , [lastid, productid, quantity] ,
  function(err, result) {
     if(err) throw err;
     });
</code>```

You need to use SET to insert data into your mysql database.

Body:
I am trying to insert array of objects into the SQL but getting the following error

  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?,?)' at line 1",
  sqlState: '42000',
  index: 0,
  sql: 'INSERT INTO orderedproducts (order_id, product_id, quantity) VALUES ((19, 10, 2),?,?)'

This my testing array of object

var testData = [
                  {
                     productId: 10,
                     quantity: 2
                  }
               ]

I want to insert this object data into sql.

My current written code which is returning above error

let lastId = results.insertId

                    let orderedProductSql = 'INSERT INTO orderedproducts (order_id, product_id, quantity) VALUES (?,?,?)'

                    var testData = [
                        {
                            productId: 10,
                            quantity: 2
                        }
                    ]

                    let values = testData.reduce((o, a) => {
                        let ini = []
                        ini.push(lastId)
                        ini.push(a.productId)
                        ini.push(a.quantity)
                        o.push(ini)
                        return o
                    }, [])

                    connection.query(orderedProductSql, [values], (err, results) => {
                        if (err) {
                            return connection.rollback(_ => {
                                throw err
                            })
                        }
                        connection.commit(err => {
                            if (err) {
                                connection.rollback(_ => {
                                    throw err
                                })
                            }
                            connection.release()
                            callBack(null, results)
                        })
                    })

How can I solve this ??

Body:
Try doing something like this:

connection.query( "INSERT INTO orderedproducts SET order_id=?, product_id=?, quantity=?" , [lastid, productid, quantity] ,
  function(err, result) {
     if(err) throw err;
     });

You need to use SET to insert data into your mysql database.