问:
Global variable index value inaccessible in a nested function(1 nested function below 2nd nested function). Can't assign a value to that index pos
I'm trying to create a console-based bank management app for my project in school. But I'm stuck when I try to modify account data. Here is my code:

```<code>#Group Activity - Bank Management System
f_names = []
m_names = []
l_names = []
mobiles = []
types = []
passwords = []
balances = []

def main():
    print("                     ===================================================================================")
    print("                                        >>>>>CONSOLE-BASED BANK MANAGEMENT SYSTEM<<<<<")
    print("                     ===================================================================================")
    print("\nWelcome to the console-based Bank Management System.")
    print("\n1. Create New Account\n2. Login")

    action = input("\nInput Action: ")

    if action == '1':
        create_acc()
    elif action == '2':
        login()
    else:
        print("\n\nInvalid Input. Please try again.\n\n")
        main()

def create_acc():
    global f_names
    global m_names
    global l_names
    print("\n                       ===================================================================================")
    print("                                                     >>>>>CREATE ACCOUNT<<<<<")
    print("                       ===================================================================================")

    f_name = input("First Name: ")
    m_name = input("Middle Name: ")
    l_name = input("Surname: ")

    f_name = f_name.title()
    m_name = m_name.title()
    l_name = l_name.title()
    f_names.append(f_name)
    m_names.append(m_name)
    l_names.append(l_name)

    def create_mobile():
        global mobiles
        mobile = input("Enter Mobile Number: ")
        if len(mobile) != 11:
            print("\n\nInvalid Mobile Number. Must be 11 digits, please try again.")
            create_mobile()
        elif mobile in mobiles:
            print("\n\nMobile number already exists. Please try again!")
            create_mobile()

        mobiles.append(mobile)
    create_mobile()

    def create_acc_type():
        global types
        print("\nWhat account type would you like to create?\n1. Personal\n2. Business")
        acc_type = input("Account type: ")

        if acc_type == '1':
            acc_type = 'Personal'
        elif acc_type == '2':
            acc_type = 'Business'
        else:
            print("\nInvalid Input. Please try again.")
            create_acc_type()

        types.append(acc_type)
    create_acc_type()

    def create_deposit():
        global balances
        print("\n")
        deposit = int(input("Initial Deposit: "))
        if deposit < 500:
            print("\nMinimum Initial Deposit must be 500. Please try again.")
            create_deposit()

        balances.append(deposit)
    create_deposit()

    def create_pass():
        global passwords
        password = input("Enter Password: ")
        password_r = input("Re-enter Password: ")

        if len(password) < 8:
            print("\nPassword must be 8 characters long.")
            create_pass()
        elif password != password_r:
            print("\nPasswords don't match. Please try again.")
            create_pass()
        elif password in passwords:
            print("\nPassword already exists. Please try again.")
            create_pass()

        passwords.append(password)

        conf = input("\nAccount Created! Would you like to login? Y/N: ")

        if conf.upper() == 'Y':
            login()
        elif conf.upper() == 'N':
            print("\nThank you for using our service. Hope to see you again!")
            main()
        else:
            print("\nInvalid Input. Redirecting to homepage.")
            main()

    create_pass()

def login():
    print("\n                       ===================================================================================")
    print("                                                           >>>>>LOGIN<<<<<")
    print("                       ===================================================================================")
    mobile = input("\nEnter your mobile number: ")

    if len(str(mobile)) != 11:
        print("\nPlease Enter a valid mobile number.")
        login()

    password = input("Enter your password: ")

    if mobile in mobiles:
        if password in passwords:
            print("Login Success!")
            dashboard(passwords.index(password))
        else:
            print("Password doesn't exist. Please try again.")
            login()
    else:
        print("Mobile Number doesn't exist. Please try again.")
        login()

def dashboard(index_val):
    print("\n                  ===================================================================================")
    print("                                                           >>>>>DASHBOARD<<<<<")
    print("                  ===================================================================================")
    print("\n-----ACCOUNT DETAILS-----")
    print(f"Name: {f_names.pop(index_val)} {m_names.pop(index_val)} {l_names.pop(index_val)}")
    print(f"Account Type: {types.pop(index_val)}")
    print(f"Mobile Number: {mobiles.pop(index_val)}")
    print(f"Balance: {balances.pop(index_val)}")
    print("--------------------------")
    print("\n\n[OPTIONS]")
    print("\n1. Edit Account Details")
    print("2. Balance Inquiry")
    print("3. Withdraw")
    print("4. Deposit")
    print("5. Logout")

    action = int(input("Input Action: "))

    if action == 1:
        print("\n>>>>>EDIT ACCOUNT DETAILS<<<<<")
        f_name = input("First Name: ")
        m_name = input("Middle Name: ")
        l_name = input("Surname: ")

        f_name = f_name.title()
        m_name = m_name.title()
        l_name = l_name.title()
        f_names.insert(index_val, f_name)
        m_names.insert(index_val, m_name)
        l_names.insert(index_val, l_name)

        print("\n")

        def create_mobile():
            global mobiles
            mobile = input("Enter Mobile Number: ")
            if len(mobile) != 11:
                print("\n\nInvalid Mobile Number. Must be 11 digits, please try again.")
                create_mobile()
            elif mobile in mobiles:
                print("\n\nMobile number already exists. Please try again!")
                create_mobile()

            mobiles.insert(index_val, mobile)
        create_mobile()

        def create_acc_type():
            global types
            print("\nSelect Account Type:\n1. Personal\n2. Business")
            acc_type = input("Account type: ")

            if acc_type == '1':
                acc_type = 'Personal'
            elif acc_type == '2':
                acc_type = 'Business'
            else:
                print("\nInvalid Input. Please try again.")
                create_acc_type()

            types.insert(index_val, acc_type)

        create_acc_type()

        def create_pass():
            global passwords
            password = input("Enter Password: ")
            password_r = input("Re-enter Password: ")

            if len(password) < 8:
                print("\nPassword must be 8 characters long.")
                create_pass()
            elif password != password_r:
                print("\nPasswords don't match. Please try again.")
                create_pass()
            elif password in passwords:
                print("\nPassword already exists. Please try again.")
                create_pass()

            passwords.insert(index_val, password)

        create_pass()

        def create_deposit():
            global balances
            print("\n")
            deposit = int(input("Deposit: "))

            balances[index_val] = balances[index_val] + deposit

        create_deposit()

        conf = input("\nAccount Successfully updated! Would you like to login? Y/N: ")

        if conf.upper() == 'Y':
            login()
        elif conf.upper() == 'N':
            print("\nThank you for using our service. Hope to see you again!")
            main()
        else:
            print("\nInvalid Input. Redirecting to homepage.")
            main()

        dashboard(index_val)

    #elif action == 2:

main()
</code>```

Error message

It should add the new deposit to the previous one, but the function can't seem to access the index value of the global variable I created for it. It might be the same for the other variables since I'm not using "append" on the "balances" variable. What I've noticed is that the functions that are below the second nested function or the 3rd layer nested function can't seem to access global variable data, even though I've already used the global keyword.

Body:
I'm trying to create a console-based bank management app for my project in school. But I'm stuck when I try to modify account data. Here is my code:

#Group Activity - Bank Management System
f_names = []
m_names = []
l_names = []
mobiles = []
types = []
passwords = []
balances = []

def main():
    print("                     ===================================================================================")
    print("                                        >>>>>CONSOLE-BASED BANK MANAGEMENT SYSTEM<<<<<")
    print("                     ===================================================================================")
    print("\nWelcome to the console-based Bank Management System.")
    print("\n1. Create New Account\n2. Login")

    action = input("\nInput Action: ")

    if action == '1':
        create_acc()
    elif action == '2':
        login()
    else:
        print("\n\nInvalid Input. Please try again.\n\n")
        main()

def create_acc():
    global f_names
    global m_names
    global l_names
    print("\n                       ===================================================================================")
    print("                                                     >>>>>CREATE ACCOUNT<<<<<")
    print("                       ===================================================================================")

    f_name = input("First Name: ")
    m_name = input("Middle Name: ")
    l_name = input("Surname: ")

    f_name = f_name.title()
    m_name = m_name.title()
    l_name = l_name.title()
    f_names.append(f_name)
    m_names.append(m_name)
    l_names.append(l_name)

    def create_mobile():
        global mobiles
        mobile = input("Enter Mobile Number: ")
        if len(mobile) != 11:
            print("\n\nInvalid Mobile Number. Must be 11 digits, please try again.")
            create_mobile()
        elif mobile in mobiles:
            print("\n\nMobile number already exists. Please try again!")
            create_mobile()

        mobiles.append(mobile)
    create_mobile()

    def create_acc_type():
        global types
        print("\nWhat account type would you like to create?\n1. Personal\n2. Business")
        acc_type = input("Account type: ")

        if acc_type == '1':
            acc_type = 'Personal'
        elif acc_type == '2':
            acc_type = 'Business'
        else:
            print("\nInvalid Input. Please try again.")
            create_acc_type()

        types.append(acc_type)
    create_acc_type()

    def create_deposit():
        global balances
        print("\n")
        deposit = int(input("Initial Deposit: "))
        if deposit < 500:
            print("\nMinimum Initial Deposit must be 500. Please try again.")
            create_deposit()

        balances.append(deposit)
    create_deposit()

    def create_pass():
        global passwords
        password = input("Enter Password: ")
        password_r = input("Re-enter Password: ")

        if len(password) < 8:
            print("\nPassword must be 8 characters long.")
            create_pass()
        elif password != password_r:
            print("\nPasswords don't match. Please try again.")
            create_pass()
        elif password in passwords:
            print("\nPassword already exists. Please try again.")
            create_pass()

        passwords.append(password)

        conf = input("\nAccount Created! Would you like to login? Y/N: ")

        if conf.upper() == 'Y':
            login()
        elif conf.upper() == 'N':
            print("\nThank you for using our service. Hope to see you again!")
            main()
        else:
            print("\nInvalid Input. Redirecting to homepage.")
            main()

    create_pass()

def login():
    print("\n                       ===================================================================================")
    print("                                                           >>>>>LOGIN<<<<<")
    print("                       ===================================================================================")
    mobile = input("\nEnter your mobile number: ")

    if len(str(mobile)) != 11:
        print("\nPlease Enter a valid mobile number.")
        login()

    password = input("Enter your password: ")

    if mobile in mobiles:
        if password in passwords:
            print("Login Success!")
            dashboard(passwords.index(password))
        else:
            print("Password doesn't exist. Please try again.")
            login()
    else:
        print("Mobile Number doesn't exist. Please try again.")
        login()

def dashboard(index_val):
    print("\n                  ===================================================================================")
    print("                                                           >>>>>DASHBOARD<<<<<")
    print("                  ===================================================================================")
    print("\n-----ACCOUNT DETAILS-----")
    print(f"Name: {f_names.pop(index_val)} {m_names.pop(index_val)} {l_names.pop(index_val)}")
    print(f"Account Type: {types.pop(index_val)}")
    print(f"Mobile Number: {mobiles.pop(index_val)}")
    print(f"Balance: {balances.pop(index_val)}")
    print("--------------------------")
    print("\n\n[OPTIONS]")
    print("\n1. Edit Account Details")
    print("2. Balance Inquiry")
    print("3. Withdraw")
    print("4. Deposit")
    print("5. Logout")

    action = int(input("Input Action: "))

    if action == 1:
        print("\n>>>>>EDIT ACCOUNT DETAILS<<<<<")
        f_name = input("First Name: ")
        m_name = input("Middle Name: ")
        l_name = input("Surname: ")

        f_name = f_name.title()
        m_name = m_name.title()
        l_name = l_name.title()
        f_names.insert(index_val, f_name)
        m_names.insert(index_val, m_name)
        l_names.insert(index_val, l_name)

        print("\n")

        def create_mobile():
            global mobiles
            mobile = input("Enter Mobile Number: ")
            if len(mobile) != 11:
                print("\n\nInvalid Mobile Number. Must be 11 digits, please try again.")
                create_mobile()
            elif mobile in mobiles:
                print("\n\nMobile number already exists. Please try again!")
                create_mobile()

            mobiles.insert(index_val, mobile)
        create_mobile()

        def create_acc_type():
            global types
            print("\nSelect Account Type:\n1. Personal\n2. Business")
            acc_type = input("Account type: ")

            if acc_type == '1':
                acc_type = 'Personal'
            elif acc_type == '2':
                acc_type = 'Business'
            else:
                print("\nInvalid Input. Please try again.")
                create_acc_type()

            types.insert(index_val, acc_type)

        create_acc_type()

        def create_pass():
            global passwords
            password = input("Enter Password: ")
            password_r = input("Re-enter Password: ")

            if len(password) < 8:
                print("\nPassword must be 8 characters long.")
                create_pass()
            elif password != password_r:
                print("\nPasswords don't match. Please try again.")
                create_pass()
            elif password in passwords:
                print("\nPassword already exists. Please try again.")
                create_pass()

            passwords.insert(index_val, password)

        create_pass()

        def create_deposit():
            global balances
            print("\n")
            deposit = int(input("Deposit: "))

            balances[index_val] = balances[index_val] + deposit

        create_deposit()

        conf = input("\nAccount Successfully updated! Would you like to login? Y/N: ")

        if conf.upper() == 'Y':
            login()
        elif conf.upper() == 'N':
            print("\nThank you for using our service. Hope to see you again!")
            main()
        else:
            print("\nInvalid Input. Redirecting to homepage.")
            main()

        dashboard(index_val)

    #elif action == 2:

main()

Error message

It should add the new deposit to the previous one, but the function can't seem to access the index value of the global variable I created for it. It might be the same for the other variables since I'm not using "append" on the "balances" variable. What I've noticed is that the functions that are below the second nested function or the 3rd layer nested function can't seem to access global variable data, even though I've already used the global keyword.


来源: stackexchange

问:
Fabric Interconnect network is default - can't I choose a certain project?
I have purchased a dual Fabric connection from Equinix Data Centers in order to connect to your Google Cloud and when I am going to setup the connection the network choice is default. I was wondering if that means that all projects would go into this fabric connection or is there a was to choose a specific project?

I only want the FCM production project to be under the Fabric connection as the Tradovate.com connection has their own servers and shouldn't be part of this connection. Can you please help clear this up?

ContentLicense: CC BY-SA 4.0


问:
C# - Calculate relative angle(0-180) between 2 angles(0-360 and 0-360)?
Im trying to find the relative angle between 2 given angles:

For example:
Angle A: 280degrees
Angle B: 80degrees

Relative angle = 160 degrees

OR

Angle A: 200degrees
Angle B: 010Degrees

relative angle:170degrees

Always finding the signed angle, not going the long way around.

This is what I came up with, but it doesnt work somehow.

```<code>float GetRelativeAngle(float mainAngle, float secondaryAngle)
{
    float rel = ((secondaryAngle - mainAngle + 180) % 360) - 180;

    if (rel < -180)
    {
        rel += 360;
    }
    return rel;
}
</code>```

Im trying to calculate the relative angle between my ship heading Angle A and the wind direction Angle B.

```<code>public float GetSpeedFromWindAngle(float mastAngle, bool isSquare)
{
    float angle = GetRelativeAngle(mastAngle, _windAngle);
    float absAngle = Mathf.Abs(angle);
    float magnitudeAngle = absAngle / 180;
    float speedfromAngle = 0f;
    if (isSquare)
        speedfromAngle = _speedFromWindAngleCurveSquares.Evaluate(magnitudeAngle);
    else speedfromAngle = _speedFromWindAngleCurveStays.Evaluate(magnitudeAngle);

    return speedfromAngle;
}
</code>```

magnitudeAngle should be between 0 and 1, so I can use it to evaluate a curve and get a speed from the curve using that magnitude. This also means I dont care if the angle is -150 or +150 so I always use Absolute.

Thank you.

Edit: The script works fine actually all angles debug correctly now and I didnt even change anything :/

Body:
Im trying to find the relative angle between 2 given angles:

For example:
Angle A: 280degrees
Angle B: 80degrees

Relative angle = 160 degrees

OR

Angle A: 200degrees
Angle B: 010Degrees

relative angle:170degrees

Always finding the signed angle, not going the long way around.

This is what I came up with, but it doesnt work somehow.

float GetRelativeAngle(float mainAngle, float secondaryAngle)
{
    float rel = ((secondaryAngle - mainAngle + 180) % 360) - 180;

    if (rel < -180)
    {
        rel += 360;
    }
    return rel;
}

Im trying to calculate the relative angle between my ship heading Angle A and the wind direction Angle B.

public float GetSpeedFromWindAngle(float mastAngle, bool isSquare)
{
    float angle = GetRelativeAngle(mastAngle, _windAngle);
    float absAngle = Mathf.Abs(angle);
    float magnitudeAngle = absAngle / 180;
    float speedfromAngle = 0f;
    if (isSquare)
        speedfromAngle = _speedFromWindAngleCurveSquares.Evaluate(magnitudeAngle);
    else speedfromAngle = _speedFromWindAngleCurveStays.Evaluate(magnitudeAngle);

    return speedfromAngle;
}

magnitudeAngle should be between 0 and 1, so I can use it to evaluate a curve and get a speed from the curve using that magnitude. This also means I dont care if the angle is -150 or +150 so I always use Absolute.

Thank you.

Edit: The script works fine actually all angles debug correctly now and I didnt even change anything :/


问:
Set notification in the Angular PWA and receive it in given time
I am trying to do a notification in my Angular PWA and haven't found anything close to my use case.

Users of the app should have the option to set a notification for a BUS departure at a given time; for example, 10 minutes before the departure, I want the app to send them a notification (if set).

I thought that I can somehow set this notification on the client-side, so that I can schedule it and the service worker will take care of it when the time comes, but I haven't found anything so I am not sure, if this approach is correct. I tried some implementations of the https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API Notification API, but this does not work on phones, on desktops it was fine.

Or should I use a firebase for this? It's worth mentioning that there are no user accounts or logins in the application, so I cannot store it in the DB that easily with specified times.

Thanks a lot for your help


问:
Retrieve Unprocessed items from BatchWriteItemRequest
I have got an operation that inserts items to dynamodb in batch. I have seen plenty of posts where people handle unprocessed items by making subsequent requests. In my scenario I want something a bit different. I want to be able to extract the Items from the unprocessedItems list to then log them into Kibana.

```<code>List<List<Item>> batchItems = Lists.partition(items, 25);

    var promises = batchItems.stream().map(itemsList -> Blocking.get(() -> {
        TableWriteItems tableWriteItems = new TableWriteItems(table.getTableName());
        tableWriteItems.withItemsToPut(itemsList);
        BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems);
        final int status = outcome.getBatchWriteItemResult().getSdkHttpMetadata().getHttpStatusCode();
        return outcome.getUnprocessedItems().values();
    })).collect(Collectors.toList());
</code>```

That is the current logic I have, to sum up, I will have an array of promises that may or may not have unprocessed items.

```<code>ParallelPromises.yieldAll(promises).map((List<? extends ExecResult<Collection<List<WriteRequest>>>> results) -> {
//from results I want to extract the Item/Items
//that failed but currently I only have the WriteRequest that failed. Can I convert it to an Item somehow?
}
</code>```

My core question is in the comment of the block of code above, thank you

Body:
I have got an operation that inserts items to dynamodb in batch. I have seen plenty of posts where people handle unprocessed items by making subsequent requests. In my scenario I want something a bit different. I want to be able to extract the Items from the unprocessedItems list to then log them into Kibana.

List<List<Item>> batchItems = Lists.partition(items, 25);

    var promises = batchItems.stream().map(itemsList -> Blocking.get(() -> {
        TableWriteItems tableWriteItems = new TableWriteItems(table.getTableName());
        tableWriteItems.withItemsToPut(itemsList);
        BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(tableWriteItems);
        final int status = outcome.getBatchWriteItemResult().getSdkHttpMetadata().getHttpStatusCode();
        return outcome.getUnprocessedItems().values();
    })).collect(Collectors.toList());

That is the current logic I have, to sum up, I will have an array of promises that may or may not have unprocessed items.

ParallelPromises.yieldAll(promises).map((List<? extends ExecResult<Collection<List<WriteRequest>>>> results) -> {
//from results I want to extract the Item/Items
//that failed but currently I only have the WriteRequest that failed. Can I convert it to an Item somehow?
}

My core question is in the comment of the block of code above, thank you


问:
Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: Can't find stylesheet to import: @use '@angular/material' as mat;
hey guys i have no clue why i cant use this stylesheet. i have read other threads about this issue but none of the solutions worked for me. i am a newb to angular and pulling my hair out. keep getting Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: Can't find stylesheet to import: @use '@angular/material' as mat; no matter what i do. here is my .scss and angular.json files:

// Custom Theming for Angular Material
// For more information: https://material.angular.io/guide/theming
@use '@angular/material' as mat;
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat.core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$theme-primary: mat.define-palette(mat.$indigo-palette);
$theme-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

// The warn palette is optional (defaults to red).
$theme-warn: mat.define-palette(mat.$red-palette);

// Create the theme object. A theme consists of configurations for individual
// theming systems such as "color" or "typography".
$theme: mat.define-light-theme((
  color: (
    primary: $theme-primary,
    accent: $theme-accent,
    warn: $theme-warn,
  ),
  typography: mat.define-typography-config(),
));

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include mat.all-component-themes($theme);
```
<pre class="lang-json prettyprint-override"><code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "movieSearch": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        },
        "@schematics/angular:application": {
          "strict": true
        }

      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "progress": false,
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "inlineStyleLanguage": "scss",
            "aot": true,
            "assets": [
              "src/assets"
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.scss"

            ],
            "stylePreprocessorOptions": {
              "includePaths": [ "node_modules/" ]
            },
            "scripts": []
          },
          "configurations": {
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]

            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "movieSearch:build:production"
            },
            "development": {
              "browserTarget": "movieSearch:build:development",
              "proxyConfig": "proxy.conf.js"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "movieSearch:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist-server",
            "main": "src/main.ts",
            "tsConfig": "tsconfig.server.json"
          },
          "configurations": {
            "dev": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": true
            },
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false
            }
          }
        }
      }
    }
  },
  "defaultProject": "movieSearch",
  "cli": {
    "analytics": false
  }
}
</code>```

package.json:

{
  "name": "moviesearch",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "prestart": "node aspnetcore-https",
    "start": "run-script-os",
    "start:windows": "ng serve --port 44400 --ssl --ssl-cert %APPDATA%\\ASP.NET\\https\\%npm_package_name%.pem --ssl-key %APPDATA%\\ASP.NET\\https\\%npm_package_name%.key",
    "start:default": "ng serve --port 44400 --ssl --ssl-cert $HOME/.aspnet/https/${npm_package_name}.pem --ssl-key $HOME/.aspnet/https/${npm_package_name}.key",
    "build": "ng build",
    "build:ssr": "ng run movieSearch:server:dev",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {

    "@angular/platform-server": "^15.0.4",

    "bootstrap": "^5.1.3",
    "jquery": "^3.6.0",
    "oidc-client": "^1.11.5",
    "popper.js": "^1.16.0",
    "run-script-os": "^1.1.6",
    "@angular/animations": "~15.0.0",
    "@angular/cdk": "15.0.3",
    "@angular/common": "~15.0.0",
    "@angular/compiler": "~15.0.0",
    "@angular/core": "~15.0.0",
    "@angular/forms": "~15.0.0",
    "@angular/material": "15.0.3",
    "@angular/material-moment-adapter": "15.0.3",
    "@angular/platform-browser": "~15.0.0",
    "@angular/platform-browser-dynamic": "~15.0.0",
    "@angular/router": "~15.0.0",
    "moment": "^2.18.1",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.5"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.0.4",
    "@angular/cli": "^15.0.4",
    "@angular/compiler-cli": "^15.0.4",
    "@types/jasmine": "~4.0.3",
    "@types/jasminewd2": "~2.0.10",
    "@types/node": "^18.0.0",
    "jasmine-core": "~4.2.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.1",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "^2.0.0",
    "typescript": "~4.8.4"
  },
  "overrides": {
    "autoprefixer": "10.4.5"
  }
}

```

have tried ng updates all day, using different options in angular.json etc. feel like I'm missing the tiniest thing but its hard to find.

Body:
hey guys i have no clue why i cant use this stylesheet. i have read other threads about this issue but none of the solutions worked for me. i am a newb to angular and pulling my hair out. keep getting Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: Can't find stylesheet to import: @use '@angular/material' as mat; no matter what i do. here is my .scss and angular.json files:

// Custom Theming for Angular Material
// For more information: https://material.angular.io/guide/theming
@use '@angular/material' as mat;
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat.core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$theme-primary: mat.define-palette(mat.$indigo-palette);
$theme-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

// The warn palette is optional (defaults to red).
$theme-warn: mat.define-palette(mat.$red-palette);

// Create the theme object. A theme consists of configurations for individual
// theming systems such as "color" or "typography".
$theme: mat.define-light-theme((
  color: (
    primary: $theme-primary,
    accent: $theme-accent,
    warn: $theme-warn,
  ),
  typography: mat.define-typography-config(),
));

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include mat.all-component-themes($theme);

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "movieSearch": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        },
        "@schematics/angular:application": {
          "strict": true
        }

      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "progress": false,
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "inlineStyleLanguage": "scss",
            "aot": true,
            "assets": [
              "src/assets"
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.scss"

            ],
            "stylePreprocessorOptions": {
              "includePaths": [ "node_modules/" ]
            },
            "scripts": []
          },
          "configurations": {
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]

            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "movieSearch:build:production"
            },
            "development": {
              "browserTarget": "movieSearch:build:development",
              "proxyConfig": "proxy.conf.js"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "movieSearch:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist-server",
            "main": "src/main.ts",
            "tsConfig": "tsconfig.server.json"
          },
          "configurations": {
            "dev": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": true
            },
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false
            }
          }
        }
      }
    }
  },
  "defaultProject": "movieSearch",
  "cli": {
    "analytics": false
  }
}

package.json:

{
  "name": "moviesearch",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "prestart": "node aspnetcore-https",
    "start": "run-script-os",
    "start:windows": "ng serve --port 44400 --ssl --ssl-cert %APPDATA%\\ASP.NET\\https\\%npm_package_name%.pem --ssl-key %APPDATA%\\ASP.NET\\https\\%npm_package_name%.key",
    "start:default": "ng serve --port 44400 --ssl --ssl-cert $HOME/.aspnet/https/${npm_package_name}.pem --ssl-key $HOME/.aspnet/https/${npm_package_name}.key",
    "build": "ng build",
    "build:ssr": "ng run movieSearch:server:dev",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {

    "@angular/platform-server": "^15.0.4",

    "bootstrap": "^5.1.3",
    "jquery": "^3.6.0",
    "oidc-client": "^1.11.5",
    "popper.js": "^1.16.0",
    "run-script-os": "^1.1.6",
    "@angular/animations": "~15.0.0",
    "@angular/cdk": "15.0.3",
    "@angular/common": "~15.0.0",
    "@angular/compiler": "~15.0.0",
    "@angular/core": "~15.0.0",
    "@angular/forms": "~15.0.0",
    "@angular/material": "15.0.3",
    "@angular/material-moment-adapter": "15.0.3",
    "@angular/platform-browser": "~15.0.0",
    "@angular/platform-browser-dynamic": "~15.0.0",
    "@angular/router": "~15.0.0",
    "moment": "^2.18.1",
    "rxjs": "~7.4.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.5"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.0.4",
    "@angular/cli": "^15.0.4",
    "@angular/compiler-cli": "^15.0.4",
    "@types/jasmine": "~4.0.3",
    "@types/jasminewd2": "~2.0.10",
    "@types/node": "^18.0.0",
    "jasmine-core": "~4.2.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.1",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "^2.0.0",
    "typescript": "~4.8.4"
  },
  "overrides": {
    "autoprefixer": "10.4.5"
  }
}

have tried ng updates all day, using different options in angular.json etc. feel like I'm missing the tiniest thing but its hard to find.


问:
How to override/ bypass a mock decorator in Python?
Most of our external services are mocked for testing. Now I built test cases for the external services (Stripe in the example) and I would like to use the actual methods for only those tests. I could just decorate all the other tests, but those are a lot of tests and the likelihood of errors high. Also the mocks are done in our test runner, so they cascade though to all the tests. This is our runner function (it is decorated with a lot of similar mocks, reduced it to the minimal reproducible example)

```<code>@mock.patch('services.Stripe.sync_customers', side_effect=mock_sync_customers)
def run_tests(self, test_labels, extra_tests=None, *args, **kwargs):
    return super().run_tests(test_labels, extra_tests, **kwargs)
</code>```

This is the test case where I would like to use the actual methods instead of the mocks:

```<code>def test_customers(self):
    Company.objects.create(**customer_data) # This should invoke the actual API calls
</code>```

Is there a way to exclude this or overwrite the mocks with the actual methods cleanly? I tried overriding it with a similar decorator as on the run_tests, which didn't work because the function on the Stripe class is not callable. I tried mocking the entire class, which also didn't work.

Body:
Most of our external services are mocked for testing. Now I built test cases for the external services (Stripe in the example) and I would like to use the actual methods for only those tests. I could just decorate all the other tests, but those are a lot of tests and the likelihood of errors high. Also the mocks are done in our test runner, so they cascade though to all the tests. This is our runner function (it is decorated with a lot of similar mocks, reduced it to the minimal reproducible example)

@mock.patch('services.Stripe.sync_customers', side_effect=mock_sync_customers)
def run_tests(self, test_labels, extra_tests=None, *args, **kwargs):
    return super().run_tests(test_labels, extra_tests, **kwargs)

This is the test case where I would like to use the actual methods instead of the mocks:

def test_customers(self):
    Company.objects.create(**customer_data) # This should invoke the actual API calls

Is there a way to exclude this or overwrite the mocks with the actual methods cleanly? I tried overriding it with a similar decorator as on the run_tests, which didn't work because the function on the Stripe class is not callable. I tried mocking the entire class, which also didn't work.


问:
Ajax content-disposition returns null, while network show correct information
I got a download working, but I am unable to get the content disposition. It keeps returning null, but in the network I can see it is available:

enter image description here

Then I have the code:

enter image description here

And the download goes correct, but when I look at the console, i see no content-disposition and therefor I cannot determine the original filename:

enter image description here

I have tried multiple things, case sensitive, different browsers etc, but I am unable to get the content-disposition. I remains returning null. Any idea if I am missing something?

Also I checked multiple sites and solution through search, but unable to get it working!

Thanks in advance!


问:
docker: failed to create shim task with containers
I have Docker Desktop for Windows and I am trying to run the official Ubuntu image interactively:

```<code>docker run ubuntu:22.10 -it
</code>```

This gives me the following error:

```<code>docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "-i": executable file not found in $PATH: unknown.
</code>```

which is not very informative for me.

On top of that, I noticed that the downloaded image is a mere 70 MB, which I doubt is correct -- but I may be wrong.

I want to point out that I am unable to run images that I was able to run few weeks ago (always the same error). I really don't know what is going on and any help is appreciated.

Body:
I have Docker Desktop for Windows and I am trying to run the official Ubuntu image interactively:

docker run ubuntu:22.10 -it

This gives me the following error:

docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "-i": executable file not found in $PATH: unknown.

which is not very informative for me.

On top of that, I noticed that the downloaded image is a mere 70 MB, which I doubt is correct -- but I may be wrong.

I want to point out that I am unable to run images that I was able to run few weeks ago (always the same error). I really don't know what is going on and any help is appreciated.


问:
AWS EKS Node Group nodes fail to join the cluster
I am trying to add a Node Group to an EKS Cluster, but no matter what I try, creation of the Node Group fails.

NodeCreationFailure:  Instances failed to join the kubernetes cluster

In CloudTrail there are no errors for the AWS::EKS::Cluster, AWS::EKS::Nodegroup and AWS::EC2::Instance resources created by the CloudFormation template.

And in CloudWatch, there there are no errors in any of the EKS logs. All logs (api, audit, authenticator, controllerManager and scheduler) are on.

I've followed the troubleshooting guide, but I don't believe that my issue lies with any of the topics covered there.

I've also attempted to run the AWSSupport-TroubleshootEKSWorkerNode runbook, but that fails, saying that my cluster doesn't exists, although it does and is healthy.

Is anyone able to suggest a resolution?

Troubleshooting

Nodes fail to join cluster

The aws-auth-cm.yaml file doesn't have the correct IAM role ARN for your nodes.

The Node IAM role contains the permissions as described in the documentation, and I have confirmed that the role has been added to the aws-auth config map.

The ClusterName in your node AWS CloudFormation template doesn't exactly match the name of the cluster you want your nodes to join.

I'm using ClusterName: !Ref EksCluster to set the name of the cluster. It exactly matches.

The node is not tagged as being owned by the cluster.

The node group successfully creates and Auto Scaling Group, which successfully starts an EC2 instance (all status checks pass). The instance has the tag kubernetes.io/cluster/my-cluster = owned applied to it.

The nodes may not be able to access the cluster using a public IP address.

The EKS cluster has EndpointPrivateAccess = true and EndpointPublicAccess = false.

The EC2 instance is associated with an Elastic Network Interface in a private subnet that is in the same Availability Zone.

There is a NAT Gateway in the same AZ as the private subnet.

A route from the private subnet to the NAT Gateway exists.

The STS endpoint for the AWS Region that you're deploying the nodes to is not enabled for your account.

The STS endpoint for the region is enabled.

The worker node doesn't have a private DNS entry

The DHCP Options Set used by the VPC has values domain-name:<region>.compute.internal and domain-name-servers:AmazonProvidedDNS.

Managed node group errors

NodeCreationFailure

As mentioned above, the Node IAM role contains the permissions as described in the documentation.

Additionally, the private subnet that the node resides in has outbound access to the internet.


问:
How to Download Photo Album,s from Picasa or Flickr using iPhone SDK...?
I am trying to get the albums from Picasa or Flickr. I was unable found useful information from google. What exactly I needed is upon giving the login credentials, we need to download the albums and then display the images as albums in the Application.</p>

ContentLicense: CC BY-SA 3.0


问:
Transform a JSON array of objects with MySQL 5.7 (map)
I'm stuck with MySQL 5.7 and to reduce the amount of data retrieved I need to transform a JSON array within a SQL query.

My column is JSON and with a value structured like that:

{
  "foo": [{
    "bar" : "BAR1",
    "baz" : "BAZ1",
    "qux" : "QUX1"
  }, {
    "bar" : "BAR2",
    "baz" : "BAZ2",
    "qux" : "QUX2"
  }]
}
```
<p>I don't know how many items are in the array.
I want the result to be structured like that:</p>
<pre class="lang-json prettyprint-override"><code>{
  "foo" : [
    ["BAR1", "BAZ1"],
    ["BAR2", "BAZ2"]
  ]
}
</code>```

Basically I need to transform item objects to arrays (and skip qux).

Unfortunately JSON_REMOVE does not allow wildcard:

An error occurs if [...] any path argument is not a valid path expression or contains a * or ** wildcard.

Is it possible to pass JSON_SEARCH results as JSON_ARRAY or JSON_REMOVE arguments?

Body:
I'm stuck with MySQL 5.7 and to reduce the amount of data retrieved I need to transform a JSON array within a SQL query.

My column is JSON and with a value structured like that:

{
  "foo": [{
    "bar" : "BAR1",
    "baz" : "BAZ1",
    "qux" : "QUX1"
  }, {
    "bar" : "BAR2",
    "baz" : "BAZ2",
    "qux" : "QUX2"
  }]
}

I don't know how many items are in the array.
I want the result to be structured like that:

{
  "foo" : [
    ["BAR1", "BAZ1"],
    ["BAR2", "BAZ2"]
  ]
}

Basically I need to transform item objects to arrays (and skip qux).

Unfortunately JSON_REMOVE does not allow wildcard:

An error occurs if [...] any path argument is not a valid path expression or contains a * or ** wildcard.

Is it possible to pass JSON_SEARCH results as JSON_ARRAY or JSON_REMOVE arguments?


问:
Rust STM32F4 rtic button no input
Right now I'm working with an STM32F429 nucleo board and I'm trying to program it using rust.

In order to learn it, I try getting the rust stm32 examples to work. The example uses rtic, which I don't really understand, but for me that is a task for later.

In this case I modified it for my board and added an LED blinking, which works fine, but I just can't get an button input.

Does anyone have an idea why this doesn´t work?

```<code>#![deny(unsafe_code)]
//#![deny(warnings)]
#![no_main]
#![no_std]

use panic_halt as _;

#[rtic::app(device = stm32f4xx_hal::pac, peripherals = true, dispatchers = [SPI5, SPI6])]
mod app {
    use stm32f4xx_hal::{
        gpio::{gpiob::PB7, gpioc::PC13, Edge, Input, Output, PushPull},
        prelude::*,
    };
    use rtt_target::{rtt_init_print, rprintln};
    use systick_monotonic::{fugit::Duration, Systick};

    const SYSFREQ: u32 = 72_000_000;
    // Shared resources go here
    #[shared]
    struct Shared {
        led: PB7<Output<PushPull>>,
    }

    // Local resources go here
    #[local]
    struct Local {
        button: PC13<Input>,
    }

    #[monotonic(binds = SysTick, default = true)]
    type MonoTimer = Systick<1000>;

    #[init]
    fn init(mut ctx: init::Context) -> (Shared, Local, init::Monotonics) {
        // enable printing
        rtt_init_print!();
        rprintln!("starting init task");
        let mono = Systick::new(ctx.core.SYST, SYSFREQ);

        // syscfg
        let mut syscfg = ctx.device.SYSCFG.constrain();
        // clocks
        let rcc = ctx.device.RCC.constrain();
        let _clocks = rcc.cfgr.sysclk(SYSFREQ.Hz()).use_hse(25.MHz()).freeze();
        // gpio ports B and C
        let gpioc = ctx.device.GPIOC.split();
        let gpiob = ctx.device.GPIOB.split();
        // button
        let mut button = gpioc.pc13.into_pull_up_input();
        button.make_interrupt_source(&mut syscfg);
        button.enable_interrupt(&mut ctx.device.EXTI);
        button.trigger_on_edge(&mut ctx.device.EXTI, Edge::Falling);
        // led
        let led = gpiob.pb7.into_push_pull_output();

        blink_led::spawn();

        (
            Shared {
               // Initialization of shared resources go here
               led,
            },
            Local {
                // Initialization of local resources go here
                button,
            },
            init::Monotonics(mono),
        )
    }

    // Optional idle, can be removed if not needed.
    #[idle]
    fn idle(_: idle::Context) -> ! {
        loop {
            continue;
        }
    }

    #[task ( shared = [led])]
    fn blink_led (mut ctx: blink_led::Context){
        rprintln!("starting blink_led task");
        ctx.shared.led.lock(|led| led.toggle());

        blink_led::spawn_after(Duration::<u64, 1, 1000>::from_ticks(1000));
        }

    #[task(binds = EXTI15_10, shared = [led], local = [button])]
    fn button_click(mut ctx: button_click::Context) {
        rprintln!("starting button click task");
        ctx.local.button.clear_interrupt_pending_bit();
        ctx.shared.led.lock(|led| led.toggle());
        }
    }
}
</code>```

I researched about rtic, which is not easy to understand for me, but didn't get it to work.

Title: Rust STM32F4 rtic button no input

Body:
Right now I'm working with an STM32F429 nucleo board and I'm trying to program it using rust.

In order to learn it, I try getting the rust stm32 examples to work. The example uses rtic, which I don't really understand, but for me that is a task for later.

In this case I modified it for my board and added an LED blinking, which works fine, but I just can't get an button input.

Does anyone have an idea why this doesn´t work?

#![deny(unsafe_code)]
//#![deny(warnings)]
#![no_main]
#![no_std]

use panic_halt as _;

#[rtic::app(device = stm32f4xx_hal::pac, peripherals = true, dispatchers = [SPI5, SPI6])]
mod app {
    use stm32f4xx_hal::{
        gpio::{gpiob::PB7, gpioc::PC13, Edge, Input, Output, PushPull},
        prelude::*,
    };
    use rtt_target::{rtt_init_print, rprintln};
    use systick_monotonic::{fugit::Duration, Systick};

    const SYSFREQ: u32 = 72_000_000;
    // Shared resources go here
    #[shared]
    struct Shared {
        led: PB7<Output<PushPull>>,
    }

    // Local resources go here
    #[local]
    struct Local {
        button: PC13<Input>,
    }

    #[monotonic(binds = SysTick, default = true)]
    type MonoTimer = Systick<1000>;

    #[init]
    fn init(mut ctx: init::Context) -> (Shared, Local, init::Monotonics) {
        // enable printing
        rtt_init_print!();
        rprintln!("starting init task");
        let mono = Systick::new(ctx.core.SYST, SYSFREQ);

        // syscfg
        let mut syscfg = ctx.device.SYSCFG.constrain();
        // clocks
        let rcc = ctx.device.RCC.constrain();
        let _clocks = rcc.cfgr.sysclk(SYSFREQ.Hz()).use_hse(25.MHz()).freeze();
        // gpio ports B and C
        let gpioc = ctx.device.GPIOC.split();
        let gpiob = ctx.device.GPIOB.split();
        // button
        let mut button = gpioc.pc13.into_pull_up_input();
        button.make_interrupt_source(&mut syscfg);
        button.enable_interrupt(&mut ctx.device.EXTI);
        button.trigger_on_edge(&mut ctx.device.EXTI, Edge::Falling);
        // led
        let led = gpiob.pb7.into_push_pull_output();

        blink_led::spawn();

        (
            Shared {
               // Initialization of shared resources go here
               led,
            },
            Local {
                // Initialization of local resources go here
                button,
            },
            init::Monotonics(mono),
        )
    }

    // Optional idle, can be removed if not needed.
    #[idle]
    fn idle(_: idle::Context) -> ! {
        loop {
            continue;
        }
    }

    #[task ( shared = [led])]
    fn blink_led (mut ctx: blink_led::Context){
        rprintln!("starting blink_led task");
        ctx.shared.led.lock(|led| led.toggle());

        blink_led::spawn_after(Duration::<u64, 1, 1000>::from_ticks(1000));
        }

    #[task(binds = EXTI15_10, shared = [led], local = [button])]
    fn button_click(mut ctx: button_click::Context) {
        rprintln!("starting button click task");
        ctx.local.button.clear_interrupt_pending_bit();
        ctx.shared.led.lock(|led| led.toggle());
        }
    }
}

I researched about rtic, which is not easy to understand for me, but didn't get it to work.


问:
How to better pass a javascript dictionary to Django view without using AJAX
I would like to pass a dictionary I formed in jQuery (without AJAX) to Django via a hidden input field that will be sent when the form is submitted.

The js script:

```<code>$("#add_prod_button").click(function(){
        var prod_value = $("#id_product_list option:selected").text();
        var prod_code = $("#id_product_list option:selected").val();
        var prod_qty = $("#id_prod_qty").val();

        dictionary.push({
          "product_code": prod_code,
          "qty" : prod_qty
        });

        $("#prods_recom").val(JSON.stringify(dictionary))  // This is the hidden input field's id
      });
</code>```

And in my views.py:

```<code>  if request.method == 'POST':
    products_selected = request.POST.get('prods_reco')
    print(products_selected) // checking the contents of the POST

</code>```

print(products_selected) gives me a string like such:
[{"product_code":"42801128101PH","qty":"1"},{"product_code":"42801128101PH","qty":"1"}]

But when I use json.loads(products_selected), it gives me an error that it only accepts strings and not list. If the value of the hidden field is being passed as a string (because of JSON.stringify), then why is the Django view still treating it as a list? And if Django is treating it as a list, how do I get the key-value pairs on the "string" that is being passed?

I tried accessing the list by using

```<code>for product_code, qty in products_selected[0].items():
      print(f"{product_code}, {qty}")
</code>```

But Django is throwing an error that strings do not have the attribute items. And if Django is treating it as a list, how do I get the key-value pairs on the "string" that is being passed?

Thank you in advance!

Body:
I would like to pass a dictionary I formed in jQuery (without AJAX) to Django via a hidden input field that will be sent when the form is submitted.

The js script:

$("#add_prod_button").click(function(){
        var prod_value = $("#id_product_list option:selected").text();
        var prod_code = $("#id_product_list option:selected").val();
        var prod_qty = $("#id_prod_qty").val();

        dictionary.push({
          "product_code": prod_code,
          "qty" : prod_qty
        });

        $("#prods_recom").val(JSON.stringify(dictionary))  // This is the hidden input field's id
      });

And in my views.py:

  if request.method == 'POST':
    products_selected = request.POST.get('prods_reco')
    print(products_selected) // checking the contents of the POST

print(products_selected) gives me a string like such:
[{"product_code":"42801128101PH","qty":"1"},{"product_code":"42801128101PH","qty":"1"}]

But when I use json.loads(products_selected), it gives me an error that it only accepts strings and not list. If the value of the hidden field is being passed as a string (because of JSON.stringify), then why is the Django view still treating it as a list? And if Django is treating it as a list, how do I get the key-value pairs on the "string" that is being passed?

I tried accessing the list by using

for product_code, qty in products_selected[0].items():
      print(f"{product_code}, {qty}")

But Django is throwing an error that strings do not have the attribute items. And if Django is treating it as a list, how do I get the key-value pairs on the "string" that is being passed?

Thank you in advance!


问:
What is the proper variable encapsulation in zabbix_sender for variable as host?
I'm trying to iterate over a list with ip addresses in conjunction with zabbix_sender like so:

```<code>#!/bin/bash
cat list.txt | while read card
do
echo $card
zabbix_sender -z 10.160.0.121 -s $card -k receive.power1 -o $rx1
zabbix_sender -z 10.160.0.121 -s 172.16.1.116 -k receive.power1 -o $rx1
done
</code>```

The list.txt just consists of:
172.16.1.116
172.16.1.117
172.16.1.118
172.16.1.119
etc.

Upon executing the script, the response is as follows:

172.16.1.116 (from echo $card just for checking proper content)

info from server: "processed: 0; failed: 1; total: 1; seconds spent: 0.0022" sent:1; skipped:0; total:1
info from server: "processed: 1; failed: 0; total: 1; seconds spent: 0.0065" sent:1; skipped:0; total:1

So zabbix_sender with variable $card fails and zabbix_sender with plain IP address works.
Could someone enlighten me on how to encapsulate this variable properly if bare $card variable in the zabbix_sender syntax is not working?

I've tried $("card"), ${"card"}, ($card), "($card)"
The manual does not describe in any way shape or form the use of variables in zabbix_sender, oddly enough the -o $rx1 as variable works like a charm and is correctly called as such.
I've omitted how i obtain the value for $rx1 since that works and for clarity.

Body:
I'm trying to iterate over a list with ip addresses in conjunction with zabbix_sender like so:

#!/bin/bash
cat list.txt | while read card
do
echo $card
zabbix_sender -z 10.160.0.121 -s $card -k receive.power1 -o $rx1
zabbix_sender -z 10.160.0.121 -s 172.16.1.116 -k receive.power1 -o $rx1
done

The list.txt just consists of:
172.16.1.116
172.16.1.117
172.16.1.118
172.16.1.119
etc.

Upon executing the script, the response is as follows:

172.16.1.116 (from echo $card just for checking proper content)

info from server: "processed: 0; failed: 1; total: 1; seconds spent: 0.0022" sent:1; skipped:0; total:1
info from server: "processed: 1; failed: 0; total: 1; seconds spent: 0.0065" sent:1; skipped:0; total:1

So zabbix_sender with variable $card fails and zabbix_sender with plain IP address works.
Could someone enlighten me on how to encapsulate this variable properly if bare $card variable in the zabbix_sender syntax is not working?

I've tried $("card"), ${"card"}, ($card), "($card)"
The manual does not describe in any way shape or form the use of variables in zabbix_sender, oddly enough the -o $rx1 as variable works like a charm and is correctly called as such.
I've omitted how i obtain the value for $rx1 since that works and for clarity.


问:
expected START_TAG or END_TAG not TEXT
i´v tryed to get and maven project with an spring module and an angular module to run. but as i edited the poms(like shown here https://dzone.com/articles/simplified-building-web-application-using-spring-b), it gives me the error in the title. im programming in IntelliJ Communety

the poms are:
main project:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <modules>media-backend</modules>
   <modules>media-frontend</modules>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.0.0</version>
      <relativePath/>
   </parent>
   <groupId>neyt</groupId>
   <artifactId>media</artifactId>
   <version>1.0-SNAPSHOT</version>
   <name>Mediathek</name>
   <description>MediathekProject</description>
   <properties>
      <java.version>17</java.version>
      <node.version>v18.12.1</node.version>
      <npm.version>9.2.0</npm.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-actuator</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-validation</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.flywaydb</groupId>
         <artifactId>flyway-core</artifactId>
      </dependency>
      <dependency>
         <groupId>org.flywaydb</groupId>
         <artifactId>flyway-mysql</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>com.mysql</groupId>
         <artifactId>mysql-connector-j</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>

</code>```

backend:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <parent>
      <artifactId>media</artifactId>
      <groupId>neyt</groupId>
      <version>1.0-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <packaging>jar</packaging>
   <dependencies>
      <dependency>
         <groupId>org.jetbrains</groupId>
         <artifactId>annotations</artifactId>
         <version>23.0.0</version>
         <scope>compile</scope>
      </dependency>
   </dependencies>
   <artifactId>media-backend</artifactId>
   <properties>
      <maven.compiler.source>17</maven.compiler.source>
      <maven.compiler.target>17</maven.compiler.target>
   </properties>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.projectlombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>
</code>```

frontend:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 <parent>
  <artifactId>media</artifactId>
  <groupId>neyt</groupId>
  <version>1.0-SNAPSHOT</version>
 </parent>
 <modelVersion>4.0.0</modelVersion>
 <packaging>jar</packaging>
 <artifactId>media-frontend</artifactId>
 <build>
  <plugins>
   <plugin>
    <groupId>com.github.eirslett</groupId>
    <artifactId>frontend-maven-plugin</artifactId>
    <version>1.12.1</version>
    <configuration>
     <workingDirectory>./</workingDirectory>
     <nodeVersion>${node.version}</nodeVersion>
     <npmVersion>${npm.version}</npmVersion>
     <nodeDownloadRoot>http://nodejs.org/dist/</nodeDownloadRoot>
     <npmDownloadRoot>http://registry.npmjs.org/npm/-/</npmDownloadRoot>
     <installDirectory>./</installDirectory>
    </configuration>
    <executions>
     <execution>
      <id>install node and npm</id>
      <goals>
       <goal>install-node-and-npm</goal>
      </goals>
      <phase>generate-resources</phase>
     </execution>
     <execution>
      <id>npm install</id>
      <goals>
       <goal>npm</goal>
      </goals>
      <phase>generate-resources</phase>
      <configuration>
       <arguments>ci --loglevel=error</arguments>
      </configuration>
     </execution>
     <execution>
      <id>build frontend</id>
      <phase>prepare-package</phase>
      <goals>
       <goal>npm</goal>
      </goals>
      <configuration>
       <arguments>run-script build</arguments>
      </configuration>
     </execution>
    </executions>
   </plugin>
  </plugins>
 </build>
</project>
</code>```

moduls
Artefacts

dose anyone know whats wrong?

Title: expected START_TAG or END_TAG not TEXT

Body:
i´v tryed to get and maven project with an spring module and an angular module to run. but as i edited the poms(like shown here https://dzone.com/articles/simplified-building-web-application-using-spring-b), it gives me the error in the title. im programming in IntelliJ Communety

the poms are:
main project:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <modules>media-backend</modules>
   <modules>media-frontend</modules>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.0.0</version>
      <relativePath/>
   </parent>
   <groupId>neyt</groupId>
   <artifactId>media</artifactId>
   <version>1.0-SNAPSHOT</version>
   <name>Mediathek</name>
   <description>MediathekProject</description>
   <properties>
      <java.version>17</java.version>
      <node.version>v18.12.1</node.version>
      <npm.version>9.2.0</npm.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-actuator</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-validation</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.flywaydb</groupId>
         <artifactId>flyway-core</artifactId>
      </dependency>
      <dependency>
         <groupId>org.flywaydb</groupId>
         <artifactId>flyway-mysql</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>com.mysql</groupId>
         <artifactId>mysql-connector-j</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>

backend:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <parent>
      <artifactId>media</artifactId>
      <groupId>neyt</groupId>
      <version>1.0-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <packaging>jar</packaging>
   <dependencies>
      <dependency>
         <groupId>org.jetbrains</groupId>
         <artifactId>annotations</artifactId>
         <version>23.0.0</version>
         <scope>compile</scope>
      </dependency>
   </dependencies>
   <artifactId>media-backend</artifactId>
   <properties>
      <maven.compiler.source>17</maven.compiler.source>
      <maven.compiler.target>17</maven.compiler.target>
   </properties>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
               <excludes>
                  <exclude>
                     <groupId>org.projectlombok</groupId>
                     <artifactId>lombok</artifactId>
                  </exclude>
               </excludes>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

frontend:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 <parent>
  <artifactId>media</artifactId>
  <groupId>neyt</groupId>
  <version>1.0-SNAPSHOT</version>
 </parent>
 <modelVersion>4.0.0</modelVersion>
 <packaging>jar</packaging>
 <artifactId>media-frontend</artifactId>
 <build>
  <plugins>
   <plugin>
    <groupId>com.github.eirslett</groupId>
    <artifactId>frontend-maven-plugin</artifactId>
    <version>1.12.1</version>
    <configuration>
     <workingDirectory>./</workingDirectory>
     <nodeVersion>${node.version}</nodeVersion>
     <npmVersion>${npm.version}</npmVersion>
     <nodeDownloadRoot>http://nodejs.org/dist/</nodeDownloadRoot>
     <npmDownloadRoot>http://registry.npmjs.org/npm/-/</npmDownloadRoot>
     <installDirectory>./</installDirectory>
    </configuration>
    <executions>
     <execution>
      <id>install node and npm</id>
      <goals>
       <goal>install-node-and-npm</goal>
      </goals>
      <phase>generate-resources</phase>
     </execution>
     <execution>
      <id>npm install</id>
      <goals>
       <goal>npm</goal>
      </goals>
      <phase>generate-resources</phase>
      <configuration>
       <arguments>ci --loglevel=error</arguments>
      </configuration>
     </execution>
     <execution>
      <id>build frontend</id>
      <phase>prepare-package</phase>
      <goals>
       <goal>npm</goal>
      </goals>
      <configuration>
       <arguments>run-script build</arguments>
      </configuration>
     </execution>
    </executions>
   </plugin>
  </plugins>
 </build>
</project>

moduls
Artefacts

dose anyone know whats wrong?


问:
How to remove the required validator from the FormBuilderTextField based on a selection from a FormBuilderDropdown
I have an FormBuilderDropdown and based on what is selected I would like to remove the FormBuilderTextField required validator based on what gets selected for example.

if United States is selected I need to remove the ZipCode to not be required.

```<code>FormBuilder(
                      key: _formKey,
                      autovalidateMode: AutovalidateMode.disabled,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(
                                bottom: kDefaultPadding * 2.0),
                            child: Theme(
                              data: themeData.copyWith(
                                // canvasColor: Colors.amber,
                                splashColor: Colors.amber,
                              ),
                              child: FormBuilderDropdown(
                                key: _countryCode,
                                name: 'country_code',
                                onChanged: (val) {
                                  if (val != 'United States') {
                                    print(val);
                                  }
                                },
                                decoration: const InputDecoration(
                                  labelText: 'Country',
                                  border: OutlineInputBorder(),
                                  hoverColor: Colors.transparent,
                                  focusColor: Colors.transparent,
                                ),
                                allowClear: true,
                                focusColor: Colors.transparent,
                                hint: const Text('Select Country'),
                                validator: FormBuilderValidators.required(),
                                items: ['United States', 'Canada', 'Mexico']
                                    .map((e) => DropdownMenuItem(
                                        value: e, child: Text(e)))
                                    .toList(),
                              ),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(
                                bottom: kDefaultPadding * 2.0),
                            child: FormBuilderTextField(
                              key: _zipCode,
                              name: 'zip_code',
                              decoration: const InputDecoration(
                                labelText: 'Zipcode',
                                hintText: 'Zipcode',
                                //helperText: 'Helper text',
                                border: OutlineInputBorder(),
                                floatingLabelBehavior:
                                    FloatingLabelBehavior.always,
                              ),
                              validator: FormBuilderValidators.required(),
                            ),
                          ),
</code>```

Body:
I have an FormBuilderDropdown and based on what is selected I would like to remove the FormBuilderTextField required validator based on what gets selected for example.

if United States is selected I need to remove the ZipCode to not be required.

FormBuilder(
                      key: _formKey,
                      autovalidateMode: AutovalidateMode.disabled,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(
                                bottom: kDefaultPadding * 2.0),
                            child: Theme(
                              data: themeData.copyWith(
                                // canvasColor: Colors.amber,
                                splashColor: Colors.amber,
                              ),
                              child: FormBuilderDropdown(
                                key: _countryCode,
                                name: 'country_code',
                                onChanged: (val) {
                                  if (val != 'United States') {
                                    print(val);
                                  }
                                },
                                decoration: const InputDecoration(
                                  labelText: 'Country',
                                  border: OutlineInputBorder(),
                                  hoverColor: Colors.transparent,
                                  focusColor: Colors.transparent,
                                ),
                                allowClear: true,
                                focusColor: Colors.transparent,
                                hint: const Text('Select Country'),
                                validator: FormBuilderValidators.required(),
                                items: ['United States', 'Canada', 'Mexico']
                                    .map((e) => DropdownMenuItem(
                                        value: e, child: Text(e)))
                                    .toList(),
                              ),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(
                                bottom: kDefaultPadding * 2.0),
                            child: FormBuilderTextField(
                              key: _zipCode,
                              name: 'zip_code',
                              decoration: const InputDecoration(
                                labelText: 'Zipcode',
                                hintText: 'Zipcode',
                                //helperText: 'Helper text',
                                border: OutlineInputBorder(),
                                floatingLabelBehavior:
                                    FloatingLabelBehavior.always,
                              ),
                              validator: FormBuilderValidators.required(),
                            ),
                          ),


问:
Importing RSA Key from file
Getting an error "Safe handle has been closed" while try to Importing RSA Keys from file.

The following command I have used in Visual Studio 2022 command prompt

aspnet_regiis -pi "keyname" "C:\keyfile.xml"

Anyone know how to resolve?

Title: Importing RSA Key from file


问:
Split string inside an xml attribute
I have an xml file with a tag looking like this:

```<code><d:var name="path" value="${env_var:MY_ENV_VAR}\folderName">
</code>```

MY_ENV_VAR is looking like this:

```<code>somePath\someName.Debug
</code>```

My goal is to retrieve only the end of MY_ENV_VAR string (in this case "debug"). Is there a way to split MY_ENV_VAR directly inside the value attribute of my tag to retrieve only the end of the string?

In the end I want my value attribute to refer to Debug\folderName instead of somePath\someName.Debug\folderName .

In other cases I would have generated the xml file with a script or created another environment variable, but here it's not possible due to project constraints, that's why I'm asking if a string can be somehow modified inside an xml file.

Title: Split string inside an xml attribute

Body:
I have an xml file with a tag looking like this:

<d:var name="path" value="${env_var:MY_ENV_VAR}\folderName">

MY_ENV_VAR is looking like this:

somePath\someName.Debug

My goal is to retrieve only the end of MY_ENV_VAR string (in this case "debug"). Is there a way to split MY_ENV_VAR directly inside the value attribute of my tag to retrieve only the end of the string?

In the end I want my value attribute to refer to Debug\folderName instead of somePath\someName.Debug\folderName .

In other cases I would have generated the xml file with a script or created another environment variable, but here it's not possible due to project constraints, that's why I'm asking if a string can be somehow modified inside an xml file.


问:
How to read .dmp file in node.js
I am trying to read the .dmp file using nodejs Filesystem but it is not working.
Can someone please help me

```<code>fs = require('fs')
fs.readFile('test.dmp', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  console.log(data.toString());
});
</code>```

I have tried ascii, base64 decoding and toString() method too.

Title: How to read .dmp file in node.js

Body:
I am trying to read the .dmp file using nodejs Filesystem but it is not working.
Can someone please help me

fs = require('fs')
fs.readFile('test.dmp', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  console.log(data.toString());
});

I have tried ascii, base64 decoding and toString() method too.


问:
Dropdown menu disappears when moving mouse to the dropdown options
so the issue I am having with my nav bar is that once I start dragging my mouse through the options that show up once I hover my mouse over the titles, the dropdown menu disappears once I reach the 4th row/option.

There also seems to be a gap between the nav bar and the main title sheet

Any input or help will be greatly appreciated, Thank you!

Here is the HTML:

```<code><!DOCTYPE HTML>
<!--
-->
<html>
    <head>
        <title>MACS</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <link rel="stylesheet" href="assets/css/main.css" />
    </head>
    <body class="is-preload">

        <!-- Wrapper -->
        <div id="wrapper">

                <nav>
                    <ul>
                        <li><a href = "">Center</a>
                            <ul>
                                <li><a href = "">Central</a></li>
                                <li><a href = "">sphere</a></li>
                            </ul>
                        </li>
                        <li><a href = "">Hub</a>
                            <ul>
                                <li><a href = "">Training</a></li>
                                <li><a href = "">lyst</a></li>
                                <li><a href = "">BIT</a></li>
                                <li><a href = "">watch</a></li>
                                <li><a href = "">Query</a></li>
                                <li><a href = "">MPR</a></li>
                                <li><a href = "">Lawsuit Reporting</a></li>
                                <li><a href = "">Sample Reports</a></li>
                                <li><a href = "">Access Request and Support</a></li>
                                <li><a href = "">Other Apps</a></li>
                            </ul>
                        </li>
                        <li><a href = "">Client Support</a>
                            <ul>
                                <li><a href = "">Service Catalog</a></li>
                                <li><a href = "">Placeholder</a></li>
                            </ul>
                        </li>
                        <li><a href = "">Peer Benchmarking</a>
                            <ul>
                                <li><a href = "">Peer Information and Reporting</a></li>
                                <li><a href = "">Benchmarking Guide</a></li>
                                <li><a href = "">Plan Design Summary</a></li>
                                <li><a href = "">Training</a></li>
                                <li><a href = "">FAQ</a></li>
                            </ul>
                        </li>
                        <li><a href = "">Consultant Support</a>
                            <ul>
                                <li><a href = "">Consultant Templates</a></li>
                                <li><a href = "">Consultant Template Catalog</a></li>
                                <li><a href = "">Consultant Dashboard</a></li>
                            </ul>
                        </li>
                        <li><a href = "">Prospect Analytics</a>
                            <ul>
                                <li><a href = "">Reference Guide</a></li>
                                <li><a href = "">Priority Log</a></li>
                                <li><a href = "">Implementation</a></li>
                                <li><a href = "">FAQ</a></li>
                            </ul>
                        </li>
                        <li><a href = "">Book of Business</a>
                            <ul>
                                <li><a href = "">Business Management Reporting</a></li>
                                <li><a href = "">Trend</a></li>
                                <li><a href = "">Plan Monitor Report</a></li>
                                <li><a href = "">Client Master Table</a></li>
                            </ul>
                        </li>
                        <li><a href = "">Lawsuit</a>
                            <ul>
                                <li><a href = "">Legal Resources</a></li>
                            </ul>
                        </li>
                        <li><a href = "">Rebates and Compliance</a>
                            <ul>
                                <li><a href = "">Rebate Invoicing Solution Center</a></li>
                                <li><a href = "">Rebates Invoicing Activity Application</a></li>
                                <li><a href = "">Rebates Invoicing User Guide</a></li>
                            </ul>
                        </li>
                        <li><a href = "">Resources</a>
                            <ul>
                                <li><a href = "">Alation</a></li>
                                <li><a href = "">Field Solution Portal</a></li>
                                <li><a href = "">Polaris</a></li>
                                <li><a href = "">Operational Analytics Request Form</a></li>
                                <li><a href = "">Requesting an Escalation for Polaris case</a></li>
                                <li><a href = "">Claims Available for Reporting</a></li>
                                <li><a href = "">Submitting Cases via Polaris</a></li>
                                <li><a href = "">Data Use Policy</a></li>
                                <li><a href = "">Operating Model</a></li>
                                <li><a href = "">Knowledge Solution</a></li>
                                <li><a href = "">Insight Delivery</a></li>
                            </ul>
                        </li>
                    </ul>
                </nav>

                <!-- Intro -->
                <section class="intro">
                    <header>
                        <h1>Market Analytics Client Support</h1>
                        <p>Market Analytics is the trusted advisor for analysis and reporting. </p>

                    </header>
                    <div class="content">
                        <!-- <span class="image fill" data-position="center"><img src="images/pic01.jpg" alt="" /></span> -->
                    </div>
                </section>

    </body>
</html>
</code>```

And here is the CSS:

Since the code had too many rows this is the link for it:

https://raw.githubusercontent.com/Mauliklm10/Sharepoint-Site/main/Sharepoint_Overhaul/assets/css/main.css

Or if the link does not work:

https://github.com/Mauliklm10/Sharepoint-Site.git

Sharepoint_Overhaul -> assets -> css -> main

Body:
so the issue I am having with my nav bar is that once I start dragging my mouse through the options that show up once I hover my mouse over the titles, the dropdown menu disappears once I reach the 4th row/option.

There also seems to be a gap between the nav bar and the main title sheet

Any input or help will be greatly appreciated, Thank you!

Here is the HTML:

<!DOCTYPE HTML>

        <title>MACS</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <link rel="stylesheet" href="assets/css/main.css" />

Center

Central

sphere

Hub

Training

lyst

BIT

watch

Query

MPR

Lawsuit Reporting

Sample Reports

Access Request and Support

Other Apps

Client Support

Service Catalog

Placeholder

Peer Benchmarking

Peer Information and Reporting

Benchmarking Guide

Plan Design Summary

Training

FAQ

Consultant Support

Consultant Templates

Consultant Template Catalog

Consultant Dashboard

Prospect Analytics

Reference Guide

Priority Log

Implementation

FAQ

Book of Business

Business Management Reporting

Trend

Plan Monitor Report

Client Master Table

Lawsuit

Legal Resources

Rebates and Compliance

Rebate Invoicing Solution Center

Rebates Invoicing Activity Application

Rebates Invoicing User Guide

Resources

Alation

Field Solution Portal

Polaris

Operational Analytics Request Form

Requesting an Escalation for Polaris case

Claims Available for Reporting

Submitting Cases via Polaris

Data Use Policy

Operating Model

Knowledge Solution

Insight Delivery

Market Analytics Client Support

Market Analytics is the trusted advisor for analysis and reporting.

And here is the CSS:

Since the code had too many rows this is the link for it:

https://raw.githubusercontent.com/Mauliklm10/Sharepoint-Site/main/Sharepoint_Overhaul/assets/css/main.css

Or if the link does not work:

https://github.com/Mauliklm10/Sharepoint-Site.git

Sharepoint_Overhaul -> assets -> css -> main


问:
How to set up mocks for a test in a separate file with Vitest/Jest and Testing Library?
I have the following files in a React app with Vitest (which has the same API as Jest):

```<code>// hooks/useEntities/useEntities.ts

return useEntities() {
    // this hooks send api requests so I will mock it in the test file.
}
</code>```

```<code>// SomeComponent.tsx
import useEntities from 'hooks/useEntities/useEntities'

function SomeComponent () {
    const entities = useEntities()

    return <div>...</div>
}
</code>```

```<code>// SomeComponent.test.tsx

vi.mock('hooks/useEntities/useEntities', () => ({ // this mocking seems to work
    default: [...]
}))

describe(...) {
    it(...) {
        render(<SomeComponent />)
    }
}
</code>```

Because I mock a lot of hooks this way. I want to separate the mocking part to a different file, so it can be reused. I've tried to following ways without a success:

```<code>// init.ts

vi.mock('hooks/useEntities/useEntities', () => ({
    default: [...]
}))
</code>```

```<code>// SomeComponent.test.tsx => this mocking seems to work

await init()

describe(...) {
    it(...) {
        render(<SomeComponent />)
    }
}
</code>```

also tried this way:

```<code>// init.ts

vi.mock('hooks/useEntities/useEntities', () => ({
    default: [...]
}))
</code>```

```<code>// SomeComponent.test.tsx => this mocking seems to work

describe(...) {
    beforeAll(async () => {
        await init()
        await init(vi) // tried the same thing with passing the vi instance to the init function in the separate file
    })
    it(...) {
        render(<SomeComponent />)
    }
}
</code>```

Body:
I have the following files in a React app with Vitest (which has the same API as Jest):

// hooks/useEntities/useEntities.ts

return useEntities() {
    // this hooks send api requests so I will mock it in the test file.
}

// SomeComponent.tsx
import useEntities from 'hooks/useEntities/useEntities'

function SomeComponent () {
    const entities = useEntities()

    return
...

}

// SomeComponent.test.tsx

vi.mock('hooks/useEntities/useEntities', () => ({ // this mocking seems to work
    default: [...]
}))

describe(...) {
    it(...) {
        render(<SomeComponent />)
    }
}

Because I mock a lot of hooks this way. I want to separate the mocking part to a different file, so it can be reused. I've tried to following ways without a success:

// init.ts

vi.mock('hooks/useEntities/useEntities', () => ({
    default: [...]
}))

// SomeComponent.test.tsx => this mocking seems to work

await init()

describe(...) {
    it(...) {
        render(<SomeComponent />)
    }
}

also tried this way:

// init.ts

vi.mock('hooks/useEntities/useEntities', () => ({
    default: [...]
}))

// SomeComponent.test.tsx => this mocking seems to work

describe(...) {
    beforeAll(async () => {
        await init()
        await init(vi) // tried the same thing with passing the vi instance to the init function in the separate file
    })
    it(...) {
        render(<SomeComponent />)
    }
}