问:
Laravel Breeze not generating migrations
Im following
Laravel Breeze Guide from Laravel's oficial page and after installing Breeze package I don't see any new migration

these are the lines i executed

```<code>curl -s https://laravel.build/prueba | bash

cd example-app

php artisan migrate
</code>```

at this point I have created a new Laravel application and  php artisan migrate create tables correctly in my DB

```<code>composer require laravel/breeze --dev

php artisan breeze:install

npm install
npm run dev
php artisan migrate
</code>```

at this point I have all the views for the authentication generated thanks to Breeze. but when php artisan migrate is executed the response I get is

What am I doing wrong?

答:
Check migration exists in the migration folder if yes then try
check your database connection
php artisan migrate:refresh

Body:
Im following
Laravel Breeze Guide from Laravel's oficial page and after installing Breeze package I don't see any new migration

these are the lines i executed

curl -s https://laravel.build/prueba | bash

cd example-app

php artisan migrate

at this point I have created a new Laravel application and  php artisan migrate create tables correctly in my DB

composer require laravel/breeze --dev

php artisan breeze:install

npm install
npm run dev
php artisan migrate

at this point I have all the views for the authentication generated thanks to Breeze. but when php artisan migrate is executed the response I get is

What am I doing wrong?


来源: stackexchange

问:
What is the alternative to using the Deprecated Hamcrest method is()?
I use the following code at the moment to assert on a boolean value, however the method org.hamcrest.Matchers.is() is deprecated.

```<code>assertThat(someValue, is(false));
</code>```

Is there a simple alternative syntax to test for boolean values without resorting to assertTrue() which gives you poor failure messages like "java.lang.AssertionError"

Edit after receiving comments/answers

My initial concerns were raised because Eclipse shows the following import statement as deprecated

On viewing the Hamcrest API docs there are 3 overloaded variations of the is() method, only one of which is deprecated.

Therefore, to clarify the comment from @mark and the answer from @matt, the use of is() that I have posted above is valid and not deprecated.

答:
This is deprecated:

```<code>import static org.junit.Assert.assertThat;
</code>```

We can use this instead:

```<code>import static org.hamcrest.MatcherAssert.assertThat;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use the following code at the moment to assert on a boolean value, however the method org.hamcrest.Matchers.is() is deprecated.

assertThat(someValue, is(false));

Is there a simple alternative syntax to test for boolean values without resorting to assertTrue() which gives you poor failure messages like "java.lang.AssertionError"

Edit after receiving comments/answers

My initial concerns were raised because Eclipse shows the following import statement as deprecated

On viewing the Hamcrest API docs there are 3 overloaded variations of the is() method, only one of which is deprecated.

Therefore, to clarify the comment from @mark and the answer from @matt, the use of is() that I have posted above is valid and not deprecated.

Body:
This is deprecated:

import static org.junit.Assert.assertThat;

We can use this instead:

import static org.hamcrest.MatcherAssert.assertThat;

ContentLicense: CC BY-SA 4.0


问:
Showing all odd numbers instead of prime numbers
```<code>def prime_num_gen():

    try:
        r = int(input('Type in the number till which you want to generate your prime numbers : '))

        if r <= 2:
             print('There is no prime number smaller than 2, 2 is the smallest prime number')

        #A list to store primes
        #Storing 2 already, because I need a number to start with
        prime_num = [2]

        #Counter
        #Counter will be divided and if it's a prime; will append it
        x = 3

        #Starting with 3 cus 2 is already considered
        #Having a jump of 2, cus no even num is prime, so considering only odd nums
        while x <= r:
            for num in range(3,x,2):

                if num % x == 0:
                    x += 2
                    break

            else:
                prime_num.append(x)
                x += 2

        print(prime_num)

    except:
        print('Please only give input as a number!\nTry again')
</code>```

For some reason, this code is including all odd numbers as prime numbers. I am complete a novice in coding and even if this seems like a pretty obvious mistake, please tell me so .

Any help will be appreciated!!

答:
Here is a slightly different implementation that can be faster in different ranges.  The basic algorithm is quite simple.

```<code>def isprime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i == 0:
            return False
    return True
for i in range (1,100):
    if isprime(i) == True:
        print(i)
</code>```

It takes O(N log (log N)) time to find all prime numbers less than N.

Body:
def prime_num_gen():

    try:
        r = int(input('Type in the number till which you want to generate your prime numbers : '))

        if r <= 2:
             print('There is no prime number smaller than 2, 2 is the smallest prime number')

        #A list to store primes
        #Storing 2 already, because I need a number to start with
        prime_num = [2]

        #Counter
        #Counter will be divided and if it's a prime; will append it
        x = 3

        #Starting with 3 cus 2 is already considered
        #Having a jump of 2, cus no even num is prime, so considering only odd nums
        while x <= r:
            for num in range(3,x,2):

                if num % x == 0:
                    x += 2
                    break

            else:
                prime_num.append(x)
                x += 2

        print(prime_num)

    except:
        print('Please only give input as a number!\nTry again')

For some reason, this code is including all odd numbers as prime numbers. I am complete a novice in coding and even if this seems like a pretty obvious mistake, please tell me so .

Any help will be appreciated!!

Body:
Here is a slightly different implementation that can be faster in different ranges.  The basic algorithm is quite simple.

def isprime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i == 0:
            return False
    return True
for i in range (1,100):
    if isprime(i) == True:
        print(i)

It takes O(N log (log N)) time to find all prime numbers less than N.


问:
What does the keyword ref mean in C#?
Below is my code please explain what is ref cboListType.</p>

```<code>Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}
</code>```

答:
Refer to the same DropDownList that was passed into the method.

Here for more details.

Title: What does the keyword ref mean in C#?

Body:
Below is my code please explain what is ref cboListType.

Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}


问:
Cypress installtion halts in between
I am trying to install cypress on windows 10 with node v12.16.1 and npm 6.13.4.
Cypress getting installed is having version 9.4.1. it hangs as shown in image. nothing happens after this point

enter image description here

installation window

答: It's because cypress app while installing needs internet connection, corporate proxy was blocking. version 9.0 printed clear message about this but 9.4.1 which is the latest one not printing anything on console</p>

Title: Cypress installtion halts in between


问:
Is there a way to export code to HTML in Eclipse?
I know NetBeans has this feature, but I can't find it in Eclipse. A quick search for plugins was not successful.</p>

答:
Hackish way:

On Windows at least, when you do Ctrl-A (Select all), Ctrl+C (Copy) what actually gets copied to the clipboard is formatted text (with all the colors and fonts). Then you can paste (Ctrl-V) it to something that can accept formatted text, say Microsoft Word or even Wordpad and save it to whatever format you wish.

OwnerDisplayName: Thomasz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

OwnerDisplayName: shoosh


问:
Push different view with no tab bar in UINavigation [like Photos app]
I have a UITabbarController with UItableViewController for each tabs, when I navigate down in a tableview Tab bar still there, but I want to make detail view with no tab bar (just like photos app when you click on a photo tab bar disappear and replace with tool bar). How can I implement this kind of behavior ?</p>

答: Have you tried self.hidesBottomBarWhenPushed = YES; where self is your DetailViewController? Try it before pushing the DetailViewController.


问:
How to get result from other application using Intent registerForActivityResult(ActivityResultContracts.StartActivityForResult())?
I have 2 application, one application need to get setResult(Activity.RESULT_OK) callback from second application with bundle data. I tried with new approach but not getting the callback to first application. Someone please help.

App1: MainActivity

```<code>private val getResult =
        registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()) {
            Log.d("Result","${it.resultCode}")
            if(it.resultCode == Activity.RESULT_OK){
                val value = it.data?.getStringExtra("input")
            }
        }
</code>```

Click on button->

```<code> val pm = packageManager
  val appStartIntent = pm.getLaunchIntentForPackage("com.example.yourtest")
  getResult.launch(appStartIntent)
</code>```

call above method  Log.d("Result","${it.resultCode}") printing Result: 0 RESULT_CANCELED value

Manifest file

```<code><queries>
        <package android:name="com.example.yourtest"/>
    </queries>
</code>```

App2: MainActivity
Button click:

```<code>val resultIntent = Intent()
         resultIntent.putExtra("input", "test)
        setResult(Activity.RESULT_OK, resultIntent )
</code>```

After calling setResult from App2 not firing getResult callback from App1.

Manifest

```<code><queries>
        <package android:name="com.example.mytest"/>
    </queries>
</code>```

答:
ActivityResultContracts.StartActivityForResult()

You shoukd register onActivityResult() instead.

Body:
I have 2 application, one application need to get setResult(Activity.RESULT_OK) callback from second application with bundle data. I tried with new approach but not getting the callback to first application. Someone please help.

App1: MainActivity

private val getResult =
        registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()) {
            Log.d("Result","${it.resultCode}")
            if(it.resultCode == Activity.RESULT_OK){
                val value = it.data?.getStringExtra("input")
            }
        }

Click on button->

 val pm = packageManager
  val appStartIntent = pm.getLaunchIntentForPackage("com.example.yourtest")
  getResult.launch(appStartIntent)

call above method  Log.d("Result","${it.resultCode}") printing Result: 0 RESULT_CANCELED value

Manifest file

<queries>
        <package android:name="com.example.yourtest"/>
    </queries>

App2: MainActivity
Button click:

val resultIntent = Intent()
         resultIntent.putExtra("input", "test)
        setResult(Activity.RESULT_OK, resultIntent )

After calling setResult from App2 not firing getResult callback from App1.

Manifest

<queries>
        <package android:name="com.example.mytest"/>
    </queries>


问:
Name: Where ran code in Intelliji is displayed?
I was pondering about the name of the area where the System.out.println(“”)is displayed in Intelliji so I could more effectively express ideas to my coding colleagues

答:
The Run tool window displays output generated by your application. If
you are running multiple applications, each one is displayed in a tab
named after the run/debug configuration applied.

If you re-runan application, the new output overwrites the contents of
the tab. To preserve the output of an application, even if you re-run
it, pin the output tab.

Press Ctrl + Shift + F10 key to run your code. Intellij Idea will open run tool window to display the output use Alt + 6 to view the errors  and Alt + 4 to see the output of your code and press Esc key to come to your code window.

Please visit this this link of jetbrains.


问:
Java, converting string to integers then add all the integers together
I need to add 8 numbers together from a string.E.g. If someone enters say 1234 it will add the numbers together  1 + 2 + 3 + 4 = 10 then 1 + 1 = 2. I have done this so far. I cannot figure out how to add these numbers up using a for loop.</p>

```<code>String num2;
String num3;
num2 = (jTextField1.getText());
num3 = num2.replaceAll("[/:.,-0]", "");

String[] result = num3.split("");

int inte = Integer.parseInt(num3);

for (int i = 0; i < 8; i++){

// Stuck

}
</code>```

答:
```<code>public static int addAll(String str) {
    str = str.replaceAll("[^1-9]", "");
    if (str.length() == 0)
        return 0;
    char[] c = str.toCharArray();
    Integer result = c[0] - 48;
    while (c.length > 1) {
        result = 0;
        for (int i = 0; i < c.length; i++) {
            result += c[i] - 48;
        }
        c = result.toString().toCharArray();
    }
    return result;
}
</code>```

Body:
I need to add 8 numbers together from a string.E.g. If someone enters say 1234 it will add the numbers together  1 + 2 + 3 + 4 = 10 then 1 + 1 = 2. I have done this so far. I cannot figure out how to add these numbers up using a for loop.

String num2;
String num3;
num2 = (jTextField1.getText());
num3 = num2.replaceAll("[/:.,-0]", "");

String[] result = num3.split("");

int inte = Integer.parseInt(num3);

for (int i = 0; i < 8; i++){

// Stuck

}


问:
useState typescript predefined string error?
how to set predefined string (enum) in react's useState? I tried:

```<code>const [color, setColor] =
    React.useState<"red | blue">("blue");
</code>```

but I got error of

```<code>Argument of type '"blue"' is not assignable to parameter of type '"red | blue" | (() => "red | blue")'.ts(2345)
</code>```

demo https://codesandbox.io/s/react-typescript-forked-jmj6c?file=/src/App.tsx:85-148

答:
You are missing two double quotations in your type.

Instead of

```<code>"red | blue"
</code>```

it should be

```<code>"red" | "blue"
</code>```

Body:
how to set predefined string (enum) in react's useState? I tried:

const [color, setColor] =
    React.useState<"red | blue">("blue");

but I got error of

Argument of type '"blue"' is not assignable to parameter of type '"red | blue" | (() => "red | blue")'.ts(2345)

demo https://codesandbox.io/s/react-typescript-forked-jmj6c?file=/src/App.tsx:85-148

Body:
You are missing two double quotations in your type.

Instead of

"red | blue"

it should be

"red" | "blue"


问:
Fontawesome 6 throwing errors in Vue 3
I'm trying to upgrade from fontawesome 5 to 6 in my vue 3 project but when I try to load an icon, it throws these errors:

```<code>Vue warn]: Unhandled error during execution of render function
  at <FontAwesomeIcon class="icon" icon= Array(2) >
  at <Benefits>
  at <App>
warn @ app.js:29973
app.js:30153 Uncaught TypeError: Cannot read properties of undefined (reading 'icon')
    at Proxy.render (app.js:12923:26)
    at renderComponentRoot (app.js:23853:44)
    at ReactiveEffect.componentUpdateFn [as fn] (app.js:27701:57)
    at ReactiveEffect.run (app.js:22221:29)
    at setupRenderEffect (app.js:27827:9)
    at mountComponent (app.js:27610:9)
    at processComponent (app.js:27568:17)
    at patch (app.js:27169:21)
    at mountChildren (app.js:27356:13)
    at mountElement (app.js:27265:17)
app.js:29973 [Vue warn]: Unhandled error during execution of mounted hook
  at <SvgProgressLine>
  at <App>
warn @ app.js:29973
2app.js:35773 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'getTotalLength')
    at app.js:35773:29
    at callWithErrorHandling (app.js:30090:22)
    at callWithAsyncErrorHandling (app.js:30099:21)
    at Array.hook.__weh.hook.__weh (app.js:25359:29)
    at flushPostFlushCbs (app.js:30288:47)
    at flushJobs (app.js:30333:9)
</code>```

I have followed the docs and installed these versions in packages.json:

```<code>"@fortawesome/fontawesome-svg-core": "^1.3.0-beta3",
"@fortawesome/free-brands-svg-icons": "^6.0.0-beta3",
"@fortawesome/free-regular-svg-icons": "^6.0.0-beta3",
"@fortawesome/free-solid-svg-icons": "^6.0.0-beta3",
"@fortawesome/vue-fontawesome": "^2.0.6",
</code>```

They are imported in app.js like so:

```<code>import {library} from '@fortawesome/fontawesome-svg-core'
import {FontAwesomeIcon} from '@fortawesome/vue-fontawesome'
import {faEnvelope, faCog, faGlobe, faServer, faKey, faSearch, faWrench, faCommentDollar, faHandsHelping, faChartBar, faExclamationTriangle, faLandmark, faUserCheck} from '@fortawesome/free-solid-svg-icons'

library.add(faEnvelope, faCog, faGlobe, faServer, faKey, faSearch, faWrench, faCommentDollar, faHandsHelping, faChartBar, faExclamationTriangle, faLandmark, faUserCheck);

createApp(app)
    .component('fa', FontAwesomeIcon)
    .use(VueSmoothScroll)
    .use(i18n)
    .mount("#app");
</code>```

And displayed in the vue file like so:

```<code><fa class="icon" :icon="[ 'fa', 'landmark' ]"></fa>
</code>```

What am I doing wrong?

答:
Looks like Vue 3 is not supported yet:

https://fontawesome.com/v6/docs/web/use-with/vue/troubleshoot#using-vue-3

Title: Fontawesome 6 throwing errors in Vue 3

Body:
I'm trying to upgrade from fontawesome 5 to 6 in my vue 3 project but when I try to load an icon, it throws these errors:

Vue warn]: Unhandled error during execution of render function
  at <FontAwesomeIcon class="icon" icon= Array(2) >
  at <Benefits>
  at <App>
warn @ app.js:29973
app.js:30153 Uncaught TypeError: Cannot read properties of undefined (reading 'icon')
    at Proxy.render (app.js:12923:26)
    at renderComponentRoot (app.js:23853:44)
    at ReactiveEffect.componentUpdateFn [as fn] (app.js:27701:57)
    at ReactiveEffect.run (app.js:22221:29)
    at setupRenderEffect (app.js:27827:9)
    at mountComponent (app.js:27610:9)
    at processComponent (app.js:27568:17)
    at patch (app.js:27169:21)
    at mountChildren (app.js:27356:13)
    at mountElement (app.js:27265:17)
app.js:29973 [Vue warn]: Unhandled error during execution of mounted hook
  at <SvgProgressLine>
  at <App>
warn @ app.js:29973
2app.js:35773 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'getTotalLength')
    at app.js:35773:29
    at callWithErrorHandling (app.js:30090:22)
    at callWithAsyncErrorHandling (app.js:30099:21)
    at Array.hook.__weh.hook.__weh (app.js:25359:29)
    at flushPostFlushCbs (app.js:30288:47)
    at flushJobs (app.js:30333:9)

I have followed the docs and installed these versions in packages.json:

"@fortawesome/fontawesome-svg-core": "^1.3.0-beta3",
"@fortawesome/free-brands-svg-icons": "^6.0.0-beta3",
"@fortawesome/free-regular-svg-icons": "^6.0.0-beta3",
"@fortawesome/free-solid-svg-icons": "^6.0.0-beta3",
"@fortawesome/vue-fontawesome": "^2.0.6",

They are imported in app.js like so:

import {library} from '@fortawesome/fontawesome-svg-core'
import {FontAwesomeIcon} from '@fortawesome/vue-fontawesome'
import {faEnvelope, faCog, faGlobe, faServer, faKey, faSearch, faWrench, faCommentDollar, faHandsHelping, faChartBar, faExclamationTriangle, faLandmark, faUserCheck} from '@fortawesome/free-solid-svg-icons'

library.add(faEnvelope, faCog, faGlobe, faServer, faKey, faSearch, faWrench, faCommentDollar, faHandsHelping, faChartBar, faExclamationTriangle, faLandmark, faUserCheck);

createApp(app)
    .component('fa', FontAwesomeIcon)
    .use(VueSmoothScroll)
    .use(i18n)
    .mount("#app");

And displayed in the vue file like so:

<fa class="icon" :icon="[ 'fa', 'landmark' ]"></fa>

What am I doing wrong?


问:
How to check if a port (input) is high? PIC16 C program
I cannot understand why my code won't work.  It works when I set the condition PORTA == 0x00 but not when PORTA == 0x01. How do you check if a bit is high? Below is my code and my schematic (Crystal frequency is 4MHz).

#include<xc.h>

void main(){
    int cnt;
    int delay_cnt;
    TRISA = 1;                 // PortA as input
    TRISB = 0;                // PortB as output
    PORTB = 0x00;            // Initialize LED as off

    for(;;){                // Infinite loop
        if(PORTA == 0x01){
            for(cnt=0;cnt<3;cnt++){
                PORTB = 0x01; // Turns on LED
                for(delay_cnt=0;delay_cnt<10000;delay_cnt++);
                PORTB = 0x00; // Turns off LED
                for(delay_cnt=0;delay_cnt<10000;delay_cnt++);
            }
        }
    }
}
```

答:
In this case if (PORTA == 0x01), you are checking the whole port (8 bit).

If you want to check just bit 0 from the port use this:

```<code>if (PORTAbits.RA0 == 1){
</code>```

or

```<code>if (PORTA & 0x01){
</code>```

Body:
In this case if (PORTA == 0x01), you are checking the whole port (8 bit).

If you want to check just bit 0 from the port use this:

if (PORTAbits.RA0 == 1){

or

if (PORTA & 0x01){


问:
React router v6 useNavigate does not work with redux dispatch
In my React app, I am trying to navigate to a new page after I dispatch an redux action. This needs to happen on my form onSubmit.

The submit works as intended and the redux action is dispatched successfully, but the react router does not navigate to the given page after the redux action is dispatched. If I remove the redux dispatch, it navigates successfully. I'm using the useNavigate hook from react-router-dom.

My form is used as per my UI library Mantine. https://mantine.dev/hooks/use-form/

What is wrong here?

The useNavigate hook definition:

```<code>const navigate = useNavigate();
</code>```

The onSubmit function:

```<code>const handlerAddShipping = (values: any) => {

      dispatch(saveShippingAddress(values)); //if removed, navigate works.

      navigate("/payment"); //does not navigate with the previous line.

};
</code>```

How routes are defined in my index.tsx

```<code> <Provider store={store}>
          <BrowserRouter>
            <Routes>
              <Route path="/" element={<App />} />
              <Route path="/shipping" element={<Shipping />} />
              <Route path="/payment" element={<Payment />} />
            </Routes>
          </BrowserRouter>
    </Provider>
</code>```

The useForm hook from my UI library Mantine:

```<code>  const form = useForm({
    initialValues: {
      address: "",
      city: "",
      postalCode: "",
      country: "",
    },
    validationRules: {
      address: (value) => value.trim().length >= 2,
      city: (value) => value.trim().length >= 2,
      postalCode: (value) => value.trim().length >= 2,
      country: (value) => value.trim().length >= 2,
    },
    errorMessages: {
      address: "Address is not valid",
      city: "City is not valid",
      postalCode: "Postal Code is not valid",
      country: "Country is not valid",
    },
  });
</code>```

The form:

```<code><form onSubmit={form.onSubmit((values) =>
      handlerAddShipping(values))}>
      <Grid sx={{ marginTop: "2rem" }}>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your Address"
            {...form.getInputProps("address")}
            error={form.errors.address}
            label="Address"
          />
        </Col>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your City"
            {...form.getInputProps("city")}
            error={form.errors.city}
            label="City"
          />
        </Col>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your Postal Code"
            {...form.getInputProps("postalCode")}
            error={form.errors.postalCode}
            label="Postal Code"
          />
        </Col>
        <Col span={12}>
          <TextInput
            placeholder="Your Country"
            {...form.getInputProps("country")}
            error={form.errors.country}
            label="Country"
          />
        </Col>
        <Col span={12}>
          <Button
            type="submit">
            Continue
          </Button>
        </Col>
      </Grid>
    </form>
</code>```

React router version :
"react-router-dom": "^6.2.1"

答:
By doing more research, I was able to make the navigate work.

```<code>  const handlerAddShipping = (values: any) => {

    //swapped the below 2 lines.

    navigate("/payment");

    //dispatch after navigate
    dispatch(saveShippingAddress(values));

  };
</code>```

I moved my navigate using useNavigate hook usage over the redux action dispatch, which gave me the intended behaviour.

Body:
In my React app, I am trying to navigate to a new page after I dispatch an redux action. This needs to happen on my form onSubmit.

The submit works as intended and the redux action is dispatched successfully, but the react router does not navigate to the given page after the redux action is dispatched. If I remove the redux dispatch, it navigates successfully. I'm using the useNavigate hook from react-router-dom.

My form is used as per my UI library Mantine. https://mantine.dev/hooks/use-form/

What is wrong here?

The useNavigate hook definition:

const navigate = useNavigate();

The onSubmit function:

const handlerAddShipping = (values: any) => {

      dispatch(saveShippingAddress(values)); //if removed, navigate works.

      navigate("/payment"); //does not navigate with the previous line.

};

How routes are defined in my index.tsx

 <Provider store={store}>
          <BrowserRouter>
            <Routes>
              <Route path="/" element={<App />} />
              <Route path="/shipping" element={<Shipping />} />
              <Route path="/payment" element={<Payment />} />
            </Routes>
          </BrowserRouter>
    </Provider>

The useForm hook from my UI library Mantine:

  const form = useForm({
    initialValues: {
      address: "",
      city: "",
      postalCode: "",
      country: "",
    },
    validationRules: {
      address: (value) => value.trim().length >= 2,
      city: (value) => value.trim().length >= 2,
      postalCode: (value) => value.trim().length >= 2,
      country: (value) => value.trim().length >= 2,
    },
    errorMessages: {
      address: "Address is not valid",
      city: "City is not valid",
      postalCode: "Postal Code is not valid",
      country: "Country is not valid",
    },
  });

The form:

<form onSubmit={form.onSubmit((values) =>
      handlerAddShipping(values))}>
      <Grid sx={{ marginTop: "2rem" }}>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your Address"
            {...form.getInputProps("address")}
            error={form.errors.address}
            label="Address"
          />
        </Col>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your City"
            {...form.getInputProps("city")}
            error={form.errors.city}
            label="City"
          />
        </Col>
        <Col span={12}>
          <TextInput
            radius="xl"
            placeholder="Your Postal Code"
            {...form.getInputProps("postalCode")}
            error={form.errors.postalCode}
            label="Postal Code"
          />
        </Col>
        <Col span={12}>
          <TextInput
            placeholder="Your Country"
            {...form.getInputProps("country")}
            error={form.errors.country}
            label="Country"
          />
        </Col>
        <Col span={12}>
          <Button
            type="submit">
            Continue
          </Button>
        </Col>
      </Grid>
    </form>

React router version :
"react-router-dom": "^6.2.1"

Body:
By doing more research, I was able to make the navigate work.

  const handlerAddShipping = (values: any) => {

    //swapped the below 2 lines.

    navigate("/payment");

    //dispatch after navigate
    dispatch(saveShippingAddress(values));

  };

I moved my navigate using useNavigate hook usage over the redux action dispatch, which gave me the intended behaviour.


答:
From MSDN

The ref method parameter keyword on a method parameter causes a method
  to refer to the same variable that was passed into the method. Any
  changes made to the parameter in the method will be reflected in that
  variable when control passes back to the calling method.

Title: What does the keyword ref mean in C#?


问:
How to account for all whitespace (spaces, tabs, new lines) in regexp_substr() method?
I have the following code snippet in SQL to select the next piece of text after ABC DEF that's of variable length:

SELECT trim('ABC DEF ' FROM regexp_substr(my_field, 'ABC DEF ([^ ]+)')) FROM my_table

Sample Data:

```<code>'{random text here}           ABC DEF          {my_variable_length_keyword} {random text here}'
</code>```

Expected Output:
{my_variable_length_keyword}

While this works, it only accounts for cases where there is one space after ABC DEF. How would I deal with cases where there are tabs, new lines, or multiple spaces before the next word?

I've tried:

SELECT trim('ABC DEF ' FROM regexp_substr(my_field, 'ABC DEF\s+([^ ]+)')) FROM my_table

But this doesn't yield any result.

Can someone please help me out with this? Thank you!

答:
(?<=ABC DEF)\s+\S+ or (?<=ABC DEF)\\s+\\S+ for string literal used in other language.

Trim the leading whitespaces, then you'll get the final output.

Some notes:

(?<=pattern) is positive lookbehind, it works like normal regex but won't be put into match result, place it before strings that you want to match.

in most platform, pattern in lookbehind doesn't support * and +. For example, (?<=ABC DEF\s+) is unsupported in most cases, you need to move \s+ outside to match whitespaces and trim them later, check Important Notes About Lookbehind

Don't know what pattern {my_variable_length_keyword} has though, but it seems it doesn't contain whitespaces, \S can match one non-whitespace character.

Body:
I have the following code snippet in SQL to select the next piece of text after ABC DEF that's of variable length:

SELECT trim('ABC DEF ' FROM regexp_substr(my_field, 'ABC DEF ([^ ]+)')) FROM my_table

Sample Data:

'{random text here}           ABC DEF          {my_variable_length_keyword} {random text here}'

Expected Output:
{my_variable_length_keyword}

While this works, it only accounts for cases where there is one space after ABC DEF. How would I deal with cases where there are tabs, new lines, or multiple spaces before the next word?

I've tried:

SELECT trim('ABC DEF ' FROM regexp_substr(my_field, 'ABC DEF\s+([^ ]+)')) FROM my_table

But this doesn't yield any result.

Can someone please help me out with this? Thank you!


问:
how to login wandb with another acount using colab?
For example, I have A, B acounts.

First, I log in Google Colab with A account.
and I want to log in wandb with B acounts. ( using !wandb login )
is it possible??

答:
You can you the following commands to force a relogin:

from terminal

```<code>wandb login --relogin
</code>```

Using the API:

```<code>import wandb
wandb.login(relogin=True)
</code>```

Body:
You can you the following commands to force a relogin:

from terminal

wandb login --relogin

Using the API:

import wandb
wandb.login(relogin=True)


问:
Angular 5 services are initialized before APP_INITIALIZER is done
I am converting an AngularJS 1.6 app to Angular 5, and I'm trying to figure out why my services are being initialized before the APP_INITIALIZER is done.

Context:

I need to fetch the app config using httpClient before initializing the app

All http requests need the app ID from the config fetched in order to resolve

In AngularJS 1.6:

Here I do an HTTP request to get the app config, and I store in a .value() so I can inject it in all of my app after bootstrapping it.

```<code>function getApp(): ng.IHttpPromise<Application> {
  const injector = angular.injector(['ng']);
  const $http: ng.IHttpService = injector.get('$http');
  const appSlug: string = window.location.pathname.split('/')[1];

  return $http.get(`/v3/app/${appSlug}`, { headers: { 'Cache-Control': 'no-cache' } });
}

getApp()
  .then((application) => {
    angular.module(app)
      .value('APP_CONFIG', angular.extend({}, application.data, ENV));

    bootstrap();
  })
  .catch((error) => {
    alert('There was an error starting the app. Please try refreshing your browser.');
  });
</code>```

In Angular 5:

Current behaviour:

The news.service.ts class constructor is executed (this is where I need the app ID)

The APP_INITIALIZER factory resolves (this is where I assign the app id to the app.provider.ts)

The news.component.ts ngOnInit is called as expected (after the APP_INITIALIZER is done)

What is the strategy to achieve the same behaviour as my AngularJS 1.6 app?

Code:

app.module.ts

```<code>export function startupServiceFactory(appProvider: AppProvider): Function {
  return () => appProvider.load();
}

@NgModule({
  declarations: [
    AppComponent,
  ],

  imports: [
    BrowserModule,
    CommonModule,
    HttpClientModule,
    CoreModule,
    ColumnViewModule,

    NavBarModule,
    SideMenuModule,
    NewsModule,

    UIRouterModule.forRoot({ states: STATES }),
  ],

  providers: [
    AppProvider,
    { provide: APP_INITIALIZER, useFactory: startupServiceFactory, deps: [AppProvider], multi: true },
    SideMenuService,
  ],

  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.provider.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { IApplicationConfig } from './app.interface';

@Injectable()
export class AppProvider {
  public APP_CONFIG: IApplicationConfig;

  constructor(private http: HttpClient) {}

  public getAppConfig() {
    return this.APP_CONFIG;
  }

  public load(): Promise<any> {
    const appSlug: string = window.location.pathname.split('/')[1];

    return new Promise((resolve, reject) => {
      this.http
        .get(`/v3/app/rca-dev-test`)
        .subscribe((response: IApplicationConfig) => {
          this.APP_CONFIG = response;
          resolve(true);
        });
    });
  }
}
</code>```

答:
This is how I do it:

Store your settings as a JSON file in your assets folder.

EG:

```<code>{
  "apiUrl": "https://localhost:9001/api/v1"
}
</code>```

startupServiceFactory.ts

```<code>export const startupServiceFactory = (appProvider: AppProvider) => () =>
  new Promise(async (resolve) => {
    await appProvider.load();
    resolve(true);
  });
</code>```

relevant code in appProvider.ts

```<code>  public async load(): Promise<any> {
    this.appConfig = await this.http
    .get('assets/appSettings/appSettings.json')
    .pipe(shareReplay(1))
    .toPromise();
  }
</code>```

Make sure to import shareReplay from rxjs/operators in appProvider.ts:

```<code>import { shareReplay } from 'rxjs/operators';
</code>```

Your app.module.ts can stay the same, just import the startupServiceFactory.

Body:
I am converting an AngularJS 1.6 app to Angular 5, and I'm trying to figure out why my services are being initialized before the APP_INITIALIZER is done.

Context:

I need to fetch the app config using httpClient before initializing the app

All http requests need the app ID from the config fetched in order to resolve

In AngularJS 1.6:

Here I do an HTTP request to get the app config, and I store in a .value() so I can inject it in all of my app after bootstrapping it.

function getApp(): ng.IHttpPromise<Application> {
  const injector = angular.injector(['ng']);
  const $http: ng.IHttpService = injector.get('$http');
  const appSlug: string = window.location.pathname.split('/')[1];

  return $http.get(`/v3/app/${appSlug}`, { headers: { 'Cache-Control': 'no-cache' } });
}

getApp()
  .then((application) => {
    angular.module(app)
      .value('APP_CONFIG', angular.extend({}, application.data, ENV));

    bootstrap();
  })
  .catch((error) => {
    alert('There was an error starting the app. Please try refreshing your browser.');
  });

In Angular 5:

Current behaviour:

The news.service.ts class constructor is executed (this is where I need the app ID)

The APP_INITIALIZER factory resolves (this is where I assign the app id to the app.provider.ts)

The news.component.ts ngOnInit is called as expected (after the APP_INITIALIZER is done)

What is the strategy to achieve the same behaviour as my AngularJS 1.6 app?

Code:

app.module.ts

export function startupServiceFactory(appProvider: AppProvider): Function {
  return () => appProvider.load();
}

@NgModule({
  declarations: [
    AppComponent,
  ],

  imports: [
    BrowserModule,
    CommonModule,
    HttpClientModule,
    CoreModule,
    ColumnViewModule,

    NavBarModule,
    SideMenuModule,
    NewsModule,

    UIRouterModule.forRoot({ states: STATES }),
  ],

  providers: [
    AppProvider,
    { provide: APP_INITIALIZER, useFactory: startupServiceFactory, deps: [AppProvider], multi: true },
    SideMenuService,
  ],

  bootstrap: [AppComponent]
})
export class AppModule { }

app.provider.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { IApplicationConfig } from './app.interface';

@Injectable()
export class AppProvider {
  public APP_CONFIG: IApplicationConfig;

  constructor(private http: HttpClient) {}

  public getAppConfig() {
    return this.APP_CONFIG;
  }

  public load(): Promise<any> {
    const appSlug: string = window.location.pathname.split('/')[1];

    return new Promise((resolve, reject) => {
      this.http
        .get(`/v3/app/rca-dev-test`)
        .subscribe((response: IApplicationConfig) => {
          this.APP_CONFIG = response;
          resolve(true);
        });
    });
  }
}

Body:
This is how I do it:

Store your settings as a JSON file in your assets folder.

EG:

{
  "apiUrl": "https://localhost:9001/api/v1"
}

startupServiceFactory.ts

export const startupServiceFactory = (appProvider: AppProvider) => () =>
  new Promise(async (resolve) => {
    await appProvider.load();
    resolve(true);
  });

relevant code in appProvider.ts

  public async load(): Promise<any> {
    this.appConfig = await this.http
    .get('assets/appSettings/appSettings.json')
    .pipe(shareReplay(1))
    .toPromise();
  }

Make sure to import shareReplay from rxjs/operators in appProvider.ts:

import { shareReplay } from 'rxjs/operators';

Your app.module.ts can stay the same, just import the startupServiceFactory.


问:
How to add a white space between function name and open bracket in VS Code
In the JavaScript editor of Visual Studio Code, I would like to add a white space between the function name and the open bracket (when function is defined).

```<code>function name ()   // <- whitespace before brackets
{
   ...
}
</code>```

But when I press [Enter] the white space is automatically removed.

Is it possible to keep it (or to auto-instert one white space), without disabling the auto-formatter?

I know I can use [Ctrk + Z] to remove the last auto-formatting but I'd like to avoid that.

答:
Add this to your settings.json and format the file using Shift + Alt + F

```<code>"javascript.format.insertSpaceBeforeFunctionParenthesis": true
</code>```

Or set it in settings menu

Works in VSCode 1.64

Body:
In the JavaScript editor of Visual Studio Code, I would like to add a white space between the function name and the open bracket (when function is defined).

function name ()   // <- whitespace before brackets
{
   ...
}

But when I press [Enter] the white space is automatically removed.

Is it possible to keep it (or to auto-instert one white space), without disabling the auto-formatter?

I know I can use [Ctrk + Z] to remove the last auto-formatting but I'd like to avoid that.

Body:
Add this to your settings.json and format the file using Shift + Alt + F

"javascript.format.insertSpaceBeforeFunctionParenthesis": true

Or set it in settings menu

Works in VSCode 1.64


问:
How to use condition for lambda environment variables
I am writing a CloudFormation template. My use case is to pass different values for AWS lambda environment.

```<code>   Environment:
    Variables:
      databaseName: lambda-dev
      databaseUser: admin-dev
      databaseName: lambda-prod
      databaseUser: admin-prod
</code>```

I want to keep a condition in environment variables like if(env==dev) then use these values, if (env==prod) then use last two.

答:
My YAML is not the best, but you want something like this:</p>
```<code>Conditions:
  ProductionCondition:
      Fn::Equals:
      - Ref: StageParameter
      - 'production'
Environment:
    Variables:
      databaseName: Fn::If: [ProductionCondition, 'lambda-prod', 'lambda-dev']       databaseUser: admin-dev
      databaseUser: ....
</code>```

Body:
I am writing a CloudFormation template. My use case is to pass different values for AWS lambda environment.

   Environment:
    Variables:
      databaseName: lambda-dev
      databaseUser: admin-dev
      databaseName: lambda-prod
      databaseUser: admin-prod

I want to keep a condition in environment variables like if(env==dev) then use these values, if (env==prod) then use last two.

Body:
My YAML is not the best, but you want something like this:

Conditions:
  ProductionCondition:
      Fn::Equals:
      - Ref: StageParameter
      - 'production'
Environment:
    Variables:
      databaseName: Fn::If: [ProductionCondition, 'lambda-prod', 'lambda-dev']       databaseUser: admin-dev
      databaseUser: ....


问:
Target a button with its content
I've two buttons with same class but different content

```<code><a class="button ordrViewBtn">Sold Out</a>
<a class="button ordrViewBtn">Re-Sell</a>
</code>```

I would like to change color of Sold Out button. is it possible to target a button with its content?

答:
You can do like this

Updated Code;

CASE-1 :If you want only all button to be colored

const buttons = document.querySelectorAll("a.ordrViewBtn");

for (let i = 0; i < buttons.length; i++) {
  buttons[i].style.color = "green";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      Sold Out
      Re-Sell
      Button3
      Button4</code>```

CASE-2 :If you want only Sold Out buttons to be colored

const buttons = document.querySelectorAll("a.ordrViewBtn");

for (let i = 0; i < buttons.length; i++) {

  if (buttons[i].innerHTML === "Sold Out")
{
  buttons[i].style.color = "green";
  buttons[i].style.backgroundColor = "yellow";
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Sold Out
      Re-Sell
      Sold Out
      Re-Sell
      Sold Out
      Re-Sell
      Sold Out</code>```

Title: Target a button with its content

Body:
I've two buttons with same class but different content

Sold Out
Re-Sell

I would like to change color of Sold Out button. is it possible to target a button with its content?

Body:
You can do like this

Updated Code;

CASE-1 :If you want only all button to be colored

const buttons = document.querySelectorAll("a.ordrViewBtn");

for (let i = 0; i < buttons.length; i++) {
  buttons[i].style.color = "green";
}

      <a class="button ordrViewBtn">Sold Out</a>
      <a class="button ordrViewBtn">Re-Sell</a>
      <a class="button ordrViewBtn">Button3</a>
      <a class="button ordrViewBtn">Button4</a>

CASE-2 :If you want only Sold Out buttons to be colored

const buttons = document.querySelectorAll("a.ordrViewBtn");

for (let i = 0; i < buttons.length; i++) {

  if (buttons[i].innerHTML === "Sold Out")
{
  buttons[i].style.color = "green";
  buttons[i].style.backgroundColor = "yellow";
}
}

<a class="button ordrViewBtn">Sold Out</a>
      <a class="button ordrViewBtn">Re-Sell</a>
      <a class="button ordrViewBtn">Sold Out</a>
      <a class="button ordrViewBtn">Re-Sell</a>
      <a class="button ordrViewBtn">Sold Out</a>
      <a class="button ordrViewBtn">Re-Sell</a>
      <a class="button ordrViewBtn">Sold Out</a>


问:
RxJs: concat two observables as options for material select
I am having problems trying to concat two different observables and show the results into a Material Select component.

On this example (built using the tool from Material docs) there is a simple example simulating what I want to do. Options are not being shown.

In my current code (on my machine), the problem I see is: the first Observable that is passed to the concat operator is subscribed and all items are shown in the Select. But I belive that the first Observable never completes. It looks like material-select is not "completing" the first Observable and, because of that, concat won't subscribe to the next Observable while the first one never completes, as it says in its docs:

Note that if some input Observable never completes, concat will also never complete and Observables following the one that did not complete will never be subscribed.

What I need is this: taking two different Observables (with different data in each one), concat them (or any other operation), and, in the end, show all their data combined as options of a single select component.

Just as a reference, I'll copy the code here also, so it won't be lost in the future:

// Component:
import { Component, Input } from '@angular/core';
import { from } from 'rxjs';
import { concatWith } from 'rxjs/operators';

interface Option {
  value: number;
  label: string;
}

@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
})
export class SelectOverviewExample {
  @Input()
  options$: any;

  constructor() {}
  ngOnInit() {
    // Let's pretend this data comes from API 1
    const sourceA$ = from([
      { value: 1, label: 'Value 1' },
      { value: 2, label: 'Value 2' },
      { value: 3, label: 'Value 3' },
    ]);

    // And these ones comes from API 2
    const sourceB$ = from([
      { value: 4, label: 'Value 4' },
      { value: 5, label: 'Value 5' },
      { value: 6, label: 'Value 6' },
    ]);

    // Now, concat the data from both observables and display all of them as options in a Select component:
    this.options$ = concatWith(sourceA$, sourceB$);
  }
}
```
<p>And the template:</p>
<pre class="lang-html prettyprint-override"><code><h4>Basic mat-select</h4>
<mat-form-field appearance="fill">
  <mat-label>Select some value:</mat-label>
  <mat-select>
    <mat-option
      *ngFor="let option of (options$ | async)"
      [value]="option.value"
    >
      {{option.label}}
    </mat-option>
  </mat-select>
</mat-form-field>
</code>```

答:
Using forkJoin and then merge the two array should be a good and clean option:

this.options$ = forkJoin([sourceA$, sourceB$]).pipe( // runs both parallel
  map(res => {
    const sA = res[0];
    const sB = res[1];
    return [...sA, ...sB]; // merges two array using the spread operator
  })
);
```

Body:
I am having problems trying to concat two different observables and show the results into a Material Select component.

On this example (built using the tool from Material docs) there is a simple example simulating what I want to do. Options are not being shown.

In my current code (on my machine), the problem I see is: the first Observable that is passed to the concat operator is subscribed and all items are shown in the Select. But I belive that the first Observable never completes. It looks like material-select is not "completing" the first Observable and, because of that, concat won't subscribe to the next Observable while the first one never completes, as it says in its docs:

Note that if some input Observable never completes, concat will also never complete and Observables following the one that did not complete will never be subscribed.

What I need is this: taking two different Observables (with different data in each one), concat them (or any other operation), and, in the end, show all their data combined as options of a single select component.

Just as a reference, I'll copy the code here also, so it won't be lost in the future:

// Component:
import { Component, Input } from '@angular/core';
import { from } from 'rxjs';
import { concatWith } from 'rxjs/operators';

interface Option {
  value: number;
  label: string;
}

@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
})
export class SelectOverviewExample {
  @Input()
  options$: any;

  constructor() {}
  ngOnInit() {
    // Let's pretend this data comes from API 1
    const sourceA$ = from([
      { value: 1, label: 'Value 1' },
      { value: 2, label: 'Value 2' },
      { value: 3, label: 'Value 3' },
    ]);

    // And these ones comes from API 2
    const sourceB$ = from([
      { value: 4, label: 'Value 4' },
      { value: 5, label: 'Value 5' },
      { value: 6, label: 'Value 6' },
    ]);

    // Now, concat the data from both observables and display all of them as options in a Select component:
    this.options$ = concatWith(sourceA$, sourceB$);
  }
}

And the template:

Basic mat-select

<mat-form-field appearance="fill">
  <mat-label>Select some value:</mat-label>
  <mat-select>
    <mat-option
      *ngFor="let option of (options$ | async)"
      [value]="option.value"
    >
      {{option.label}}
    </mat-option>
  </mat-select>
</mat-form-field>


问:
Efficient way to get indexes of matched items using Lists
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

```<code>ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}
</code>```

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.

答: Using Apache CollectionUtils, there are plenty of options</p>

Body:
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:

ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
   int element = listB.get(i);
   for(int j=0; j<listA.size(); j++) {
      if(listA.get(j) == element) listC.add(j);
   }
}

I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.


问:
(Gatsby-Strapi) Error: Request failed with status code 404
I want to follow the instruction :https://strapi.io/blog/building-a-static-website-using-gatsby-and-strapi#allowaccess

But encounter Error: Request failed with status code 404

Node.js version:
v10.13.0
npm version:
6.14.6
Strapi version:
3.1.0-alpha.5
Operating system:
mac

Which example is causing problem?
strapi.io/blog/building-a-static-website-using-gatsby-and-strapi#allowaccess

What is the current behavior?
Graphql Query doesn't work.

the steps to reproduce the problem:

```<code>$ gatsby develop
success open and validate gatsby-configs
success load plugins - 2.011s
success onPreInit - 0.004s
success initialize cache - 0.018s
success copy gatsby files - 0.102s
success onPreBootstrap - 0.017s
success createSchemaCustomization -
info Starting to fetch data from Strapi
info Starting to fetch data from Strapi
info Starting to fetch data from Strapi

ERROR #11321 PLUGIN

"gatsby-source-strapi" threw an error while running the sourceNodes lifecycle:

Request failed with status code 404

Error: Request failed with status code 404

createError.js:16 createError
[portfolio_v4]/[gatsby-source-strapi ]/[axios]/lib/core/createError.js:16 :15

settle.js:18 settle
[portfolio_v4]/[gatsby-source-strapi ]/[axios]/lib/core/settle.js:18:12

http.js:202 IncomingMessage.handleSt reamEnd
[portfolio_v4]/[gatsby-source-strapi ]/[axios]/lib/adapters/http.js:202:1 1

task_queues.js:84 processTicksAndRej ections
internal/process/task_queues.js:84:2 1
</code>```

What is the expected behavior?
What is the expected behavior?

Doesn't work when I try to get from gatsby
http://localhost:8000/___graphql

There is no method allStrapiblogs on http://localhost:8000/___graphql

答:
When added "${DOMAIN}/api" on apiURL it worked for me with strapi v4

apiURL: "http://localhost:1337/api",

```<code>{
  resolve: "gatsby-source-strapi",
  options: {
    apiURL: "http://localhost:1337/api",
    collectionTypes: [`messages`],
    // Extract images from markdown fields.
    markdownImages: {
      typesToParse: {
        Article: ["body"],
        ComponentBlockBody: ["text"],
      },
    },
    // Only include specific locale.
    locale: "en", // default to all
    // Include drafts in build.
    preview: true, // defaults to false
    // Use application token.
    token: "token",
    // Add additional headers.
    headers: {},
  },
},
</code>```

Body:
I want to follow the instruction :https://strapi.io/blog/building-a-static-website-using-gatsby-and-strapi#allowaccess

But encounter Error: Request failed with status code 404

Node.js version:
v10.13.0
npm version:
6.14.6
Strapi version:
3.1.0-alpha.5
Operating system:
mac

Which example is causing problem?
strapi.io/blog/building-a-static-website-using-gatsby-and-strapi#allowaccess

What is the current behavior?
Graphql Query doesn't work.

the steps to reproduce the problem:

$ gatsby develop
success open and validate gatsby-configs
success load plugins - 2.011s
success onPreInit - 0.004s
success initialize cache - 0.018s
success copy gatsby files - 0.102s
success onPreBootstrap - 0.017s
success createSchemaCustomization -
info Starting to fetch data from Strapi
info Starting to fetch data from Strapi
info Starting to fetch data from Strapi

ERROR #11321 PLUGIN

"gatsby-source-strapi" threw an error while running the sourceNodes lifecycle:

Request failed with status code 404

Error: Request failed with status code 404

createError.js:16 createError
[portfolio_v4]/[gatsby-source-strapi ]/[axios]/lib/core/createError.js:16 :15

settle.js:18 settle
[portfolio_v4]/[gatsby-source-strapi ]/[axios]/lib/core/settle.js:18:12

http.js:202 IncomingMessage.handleSt reamEnd
[portfolio_v4]/[gatsby-source-strapi ]/[axios]/lib/adapters/http.js:202:1 1

task_queues.js:84 processTicksAndRej ections
internal/process/task_queues.js:84:2 1

What is the expected behavior?
What is the expected behavior?

Doesn't work when I try to get from gatsby
http://localhost:8000/___graphql

There is no method allStrapiblogs on http://localhost:8000/___graphql

Body:
When added "${DOMAIN}/api" on apiURL it worked for me with strapi v4

apiURL: "http://localhost:1337/api",

{
  resolve: "gatsby-source-strapi",
  options: {
    apiURL: "http://localhost:1337/api",
    collectionTypes: [`messages`],
    // Extract images from markdown fields.
    markdownImages: {
      typesToParse: {
        Article: ["body"],
        ComponentBlockBody: ["text"],
      },
    },
    // Only include specific locale.
    locale: "en", // default to all
    // Include drafts in build.
    preview: true, // defaults to false
    // Use application token.
    token: "token",
    // Add additional headers.
    headers: {},
  },
},


答:
const [color, setColor] = React.useState<"red" | "blue">("blue");

or:

```<code>type Color = "red" | "blue";
const [color, setColor] = React.useState<Color>("blue");
</code>```

Title: useState typescript predefined string error?

Body:
how to set predefined string (enum) in react's useState? I tried:

const [color, setColor] =
    React.useState<"red | blue">("blue");

but I got error of

Argument of type '"blue"' is not assignable to parameter of type '"red | blue" | (() => "red | blue")'.ts(2345)

demo https://codesandbox.io/s/react-typescript-forked-jmj6c?file=/src/App.tsx:85-148

Body:
const [color, setColor] = React.useState<"red" | "blue">("blue");

or:

type Color = "red" | "blue";
const [color, setColor] = React.useState<Color>("blue");


问:
how to set up default_qty_value using user input value in pine script?
basically I want to dynamically change the size of leverage position using user input, I have variable LEVERAGE in default_qty_value as shown below:

```<code>//@version=5
LEVERAGE = input.int(1, minval=1, step=1)

strategy('YTStrategy', overlay=true, margin_long=1, default_qty_type=strategy.percent_of_equity, default_qty_value=LEVERAGE*100, currency=currency.USD, process_orders_on_close=true)
</code>```

the compiler keeps reporting error :

Cannot call 'strategy' with argument 'default_qty_value'='call
'operator *' (input int)'. An argument of 'input int' type was used
but a 'const float' is expected

答:
The value of default_qty_value must be known at compile time. You cannot use a user input for that.

You can change your variable into a regular one:

```<code>LEVERAGE = 1.0
</code>```

Or use the strategy settings to configure those options.

Body:
basically I want to dynamically change the size of leverage position using user input, I have variable LEVERAGE in default_qty_value as shown below:

//@version=5
LEVERAGE = input.int(1, minval=1, step=1)

strategy('YTStrategy', overlay=true, margin_long=1, default_qty_type=strategy.percent_of_equity, default_qty_value=LEVERAGE*100, currency=currency.USD, process_orders_on_close=true)

the compiler keeps reporting error :

Cannot call 'strategy' with argument 'default_qty_value'='call
'operator *' (input int)'. An argument of 'input int' type was used
but a 'const float' is expected

Body:
The value of default_qty_value must be known at compile time. You cannot use a user input for that.

You can change your variable into a regular one:

LEVERAGE = 1.0

Or use the strategy settings to configure those options.


问:
Asking the user to re-enter year of birth until birth year < current year
I have a problem that how to keep show a prompt until user enter their birth year is always smaller than the current year. Here is my code I try using loop but now  i struggle. I hope someone can help me, I appreciate it.</p>
```<code><body>
<p id= "age"></p>
<button onclick=" notify()">Try it</button>
<script>
function notify(){
let age = prompt("Your birth year");
        const year = new Date().getFullYear();
        do {
          document.getElementById("age").innerHTML =
            age + " is a good year";
        } while (age < year && age != null);
}
</script>
</body>
</code>```

答:
Two things to check:

the test for "if age greater or equal to current year continue looping" appear to be around the wrong way. Try >= instead of < as the age/year comparison operator.

Make sure to call prompt again if the year entered is unacceptable.

Show the snippet to see a working version:

function notify(){
        let age;
        const year = new Date().getFullYear();
        do {
          age = prompt("Your birth year");
        } while (age >= year && age != null);
        document.getElementById("age").innerHTML =
            age + " is a good year";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id= "age"></p>
<button onclick=" notify()">Try it</button></code>```

Body:
I have a problem that how to keep show a prompt until user enter their birth year is always smaller than the current year. Here is my code I try using loop but now  i struggle. I hope someone can help me, I appreciate it.

<button onclick=" notify()">Try it</button>

Body:
Two things to check:

the test for "if age greater or equal to current year continue looping" appear to be around the wrong way. Try >= instead of < as the age/year comparison operator.

Make sure to call prompt again if the year entered is unacceptable.

Show the snippet to see a working version:

function notify(){
        let age;
        const year = new Date().getFullYear();
        do {
          age = prompt("Your birth year");
        } while (age >= year && age != null);
        document.getElementById("age").innerHTML =
            age + " is a good year";
}

<p id= "age"></p>
<button onclick=" notify()">Try it</button>


问:
Gradle getting error - HMS Core-Analytics Kit
Getting below error in gradle file after adding HMS analytics dependency.

Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://dl.bintray.com/populov/maven/com/huawei/agconnect/agcp/1.5.2.305/agcp-1.5.2.305.pom'. Received status code 502 from server: Bad Gateway

答:
Please check your build.gradle/settings.gradle file and move

maven { url'https://developer.huawei.com/repo/ '} to the top in repositories block as shown below:


问:
Is there a way to truncate text using liquid markups
I am looking to use liquid markups to truncate text of a product name. I know you can truncate through character count or word count, but I am looking to truncate a product name, almost like text to columns.

For example, if a product name is "Electric Guitar - Sky Blue", I want to truncate the product name only, so it just says "Electric Guitar". Every product name contains the " - ", so this would be consistent across the product set.

Any ideas? Thanks!

答:
You can split product title with - and first name is print

Example:  {{ product.title | split:'-' | first }}
it will split from - and print Electric Guitar.


问:
Find all possible subarrays of an array and sum them
Let's suppose the array is A={1,2,3} , now get all subarrays for this array. For each sub-array find the minimum in that sub-array, also find the sum of items in that sub-array. Finally add all these values. The input cannot be sorted as I want all possible subarrays.

Example:

Possible sub-arrays are:

```<code>{1} - min = 1, sum = 1 => min* sum = 1
{1,2} - min = 1, sum = 3 => min* sum = 3
{1,2,3} - min = 1, sum = 6 => min* sum = 6
{2} - min = 2, sum = 2 => min* sum = 4
{2,3} - min = 2, sum = 5 => min* sum = 10
{3} - min = 3, sum = 3 => min* sum = 9
</code>```

Finally add all these values to get the result = 1 + 3 + 6 + 4 + 10 + 9 = 33.

constraints: array elements can range from 1 to 1000_000_000. Array size from 1 to 100_000. Return output as module 7+1000_000_000.

Here is my program with O(n^2). I want a better algorithm with lesser time complexity.

```<code>public int program(int[] A, int n) {
    int M = 7 + 1000_000_000;
    long total = 0;
    for (int i = 0; i < n; i++) {
        long sum = 0;
        int min = A[i];
        for (int j = i; j < n; j++) {
            int a = A[j];
            sum= (sum + a) % M;
            min = Math.min(min, a);
            total = (total + (min * sum) % M) % M;
        }
    }
    return (int) total;
}
</code>```

Input range:

```<code>n range is 1 to 10^6
elements in array range is 1 to 10^9
</code>```

答:
This problem can be solved in O(n) time and space.

The technique is to use the algorithm for all nearest smaller values to find the largest array whose minimum element is x, for all elements x. This first step has been asked before as a separate post; the method and explanations here are partially borrowed from my answer there.

To avoid problems with duplicates, we'll say that x is the minimum element of a subarray when it's the leftmost minimum, i.e. there is no previous element as small as x nor any future element strictly smaller than x within its subarray.

Using the algorithm for all nearest smaller values, for each index i with 0 <= i < n, we compute the index of the previous smaller or equal value to A[i] (or -1 if none exists), and the index of the next smaller value to A[i] (or n if none exists). This is equivalent to assuming that we've prepended -infinity and appended +infinity to A, so I'll assume we've done so (without actually modifying A).

Now, we have to compute each element's individual contribution to the total sum. We will break this into two pieces: the contribution of A[i] from subarrays whose minimum is located at or left of i, and the contribution of A[i] from subarrays whose minimum is located strictly after i.

```<code> 1. For each position i in the array A,
    let M = (m_0, m_1, ... m_r) be the indices of the
    ordered sequence of (weak) minima we see, starting
    with m_0 = -1 and ending at m_r = i.
</code>```
```<code>For example, if
A = (5, 3, 9, 4, 6, 8, 10, 1, 2, 7)

then the sequence for A[5]==8 would be:
M = -1, 1, 3, 4, 5

corresponding to the minima
-infinity, 3, 4, 6, 8

seen walking left from A[5]==8.
</code>```
```<code> 2. Let C(m_j, i), 1 <= j <= r, be the count of
    subarrays of A that have m_j as their minimum
    and contain A[i]. We can also let D(m_j, i) be
    this count of arrays times the shared minimum
    of the arrays: D(m_j, i) = A[m_j]*C(m_j, i).
</code>```
```<code> 3. The contribution of A[i] to the total sum
    from subarrays whose minimum is located
    at or before i is the
    sum over j, 1 <= j <= r, of D(m_j, i)*A[i].
    Note that this sum excludes the
    fake minimum of -infinity
</code>```

If the indices of the next_smaller element and previous_smaller_or_equal element to i have been computed, then

```<code>C(i, i) = (next_smaller[i] - i)
        * (i - previous_smaller_or_equal[i]).
</code>```

Now, what I've described so far is still an O(n^2) algorithm. The trick is that we can compute C(m_j, i+1) from C(m_j, i), and that we don't need to actually compute the individual values of C for previous minima; only the sum mentioned at the end of (3) in an above code block.

```<code>C(m_j, i+1) = C(m_j, i) - (m_j-m_{j-1})
                     if A[i+1] >= A[m_j], and

            = 0
                     if A[i+1] < A[m_j].
</code>```

This means that the values of our C function decrease at a fixed, linear rate independent of i until we reach a strictly smaller number than A[m_j], at which point the sum contribution from m_j has decreased to zero.

That suggests that we should keep a (weakly) monotonic stack as we scan through A, storing the (weak) minima we've seen from left to right together with the fixed linear rate at which its contribution to our D(m_j, i) function sum is decreasing. At A[i], we perform the linear decrease to our running sum, pop all elements from the top of the stack that are strictly greater than A[i] (also removing their contribution to the running sum's decrease), add A[i] * running sum to our total, and push A[i] on top of the stack.

Since each element of A is added and removed from the stack at most once, this runs in O(n) time.

The contribution of A[i] to the total sum from subarrays whose minimum is located strictly after i is computed completely analogously going right-to-left, except we keep a strictly monotonic stack, and don't count the contribution of A[i] from subarrays which have A[i] as a minimum; these have already been counted.

Here's the full code in Java. To deal with integer overflow (since individual terms of the sum can be as large as max(A)**2 * n, or 10**24 here), I've converted all arithmetic to use BigInteger. I'm not a Java expert, so there may be a better fix or ways to use arbitrary-precision integers with less overhead.

import java.math.BigInteger;
import java.util.*;

public static int sub_sums(int[] A, int n) {
    /* Given an array of integers A, compute the
    sum over all subarrays B of min(B)*sum(B)
    by using nearest smaller values

    Run-time: O(n), and O(n) extra space
    */

    ArrayList<BigInteger> nums = new ArrayList<BigInteger>(n);
    for (int i = 0; i < n; i++){
        nums.add(BigInteger.valueOf(A[i]));
    }

    BigInteger big_n = BigInteger.valueOf(n);

    BigInteger MOD = BigInteger.valueOf(7 + 1000_000_000);

    var previous_smaller_or_equal = new int[n];
    var next_smaller = new int[n];

    for (int i = 0; i < n; i++) {
        previous_smaller_or_equal[i] = i;
        int j = i-1;
        while (j >= 0 && A[j] > A[i]){
            j = previous_smaller_or_equal[j];
        }
        previous_smaller_or_equal[i] = j;
    }

    for (int i = n-1; i >= 0; i--) {
        next_smaller[i] = i;
        int j = i+1;
        while (j < n && A[j] >= A[i]){
            j = next_smaller[j];
        }
        next_smaller[i] = j;
    }

    BigInteger total = BigInteger.ZERO;
    BigInteger running_sum = BigInteger.ZERO;
    BigInteger running_sum_decrease = BigInteger.ZERO;

    var s = new Stack<Integer>();

    for (int i = 0; i < n; i++) {

        // Contributions of this element as minimum
        BigInteger term_1 = BigInteger.valueOf(next_smaller[i] - i);
        BigInteger term_2 = BigInteger.valueOf(i - previous_smaller_or_equal[i]);

        running_sum = running_sum.add(nums.get(i).multiply(term_1).multiply(term_2));

        running_sum = running_sum.subtract(running_sum_decrease);

        while (!s.empty() && A[s.peek()] > A[i]){
            var last = s.pop();
            BigInteger term_3 = nums.get(last).multiply(BigInteger.valueOf(last- previous_smaller_or_equal[last]));
            running_sum_decrease = running_sum_decrease.subtract(term_3);
        }

        total = total.add(nums.get(i).multiply(running_sum));

        running_sum_decrease = running_sum_decrease.add(term_2.multiply(nums.get(i)));

        s.push(i);
    }

    s.clear();
    running_sum = BigInteger.ZERO;
    running_sum_decrease = BigInteger.ZERO;

    for (int i = n-1; i >= 0; i--) {

        running_sum = running_sum.subtract(running_sum_decrease);
        total = total.add(nums.get(i).multiply(running_sum));

        // Contributions of this element as minimum
        // Added afterwards now, since forward-pass already counted once

        BigInteger term_1 = BigInteger.valueOf(next_smaller[i] - i);
        BigInteger term_2 = BigInteger.valueOf(i - previous_smaller_or_equal[i]);

        running_sum = running_sum.add(nums.get(i).multiply(term_1).multiply(term_2));

        while (!s.empty() && A[s.peek()] >= A[i]){
            var last = s.pop();
            BigInteger term_3 = nums.get(last).multiply(BigInteger.valueOf(next_smaller[last]- last));
            running_sum_decrease = running_sum_decrease.subtract(term_3);
        }

        running_sum_decrease = running_sum_decrease.add(term_1.multiply(nums.get(i)));

        s.push(i);
    }

    return (total.mod(MOD)).intValue();
}
```
<p>Example usage:</p>
<pre class="lang-java prettyprint-override"><code>int[] d = {1, 2, 3};
System.out.println(sub_sums(d, 3));  // Returns 33
int[] c = {3, 2, 1, 4};
System.out.println(sub_sums(c, 4));  // Returns 71
</code>```

Body:
Let's suppose the array is A={1,2,3} , now get all subarrays for this array. For each sub-array find the minimum in that sub-array, also find the sum of items in that sub-array. Finally add all these values. The input cannot be sorted as I want all possible subarrays.

Example:

Possible sub-arrays are:

{1} - min = 1, sum = 1 => min* sum = 1
{1,2} - min = 1, sum = 3 => min* sum = 3
{1,2,3} - min = 1, sum = 6 => min* sum = 6
{2} - min = 2, sum = 2 => min* sum = 4
{2,3} - min = 2, sum = 5 => min* sum = 10
{3} - min = 3, sum = 3 => min* sum = 9

Finally add all these values to get the result = 1 + 3 + 6 + 4 + 10 + 9 = 33.

constraints: array elements can range from 1 to 1000_000_000. Array size from 1 to 100_000. Return output as module 7+1000_000_000.

Here is my program with O(n^2). I want a better algorithm with lesser time complexity.

public int program(int[] A, int n) {
    int M = 7 + 1000_000_000;
    long total = 0;
    for (int i = 0; i < n; i++) {
        long sum = 0;
        int min = A[i];
        for (int j = i; j < n; j++) {
            int a = A[j];
            sum= (sum + a) % M;
            min = Math.min(min, a);
            total = (total + (min * sum) % M) % M;
        }
    }
    return (int) total;
}

Input range:

n range is 1 to 10^6
elements in array range is 1 to 10^9

Body:
This problem can be solved in O(n) time and space.

The technique is to use the algorithm for all nearest smaller values to find the largest array whose minimum element is x, for all elements x. This first step has been asked before as a separate post; the method and explanations here are partially borrowed from my answer there.

To avoid problems with duplicates, we'll say that x is the minimum element of a subarray when it's the leftmost minimum, i.e. there is no previous element as small as x nor any future element strictly smaller than x within its subarray.

Using the algorithm for all nearest smaller values, for each index i with 0 <= i < n, we compute the index of the previous smaller or equal value to A[i] (or -1 if none exists), and the index of the next smaller value to A[i] (or n if none exists). This is equivalent to assuming that we've prepended -infinity and appended +infinity to A, so I'll assume we've done so (without actually modifying A).

Now, we have to compute each element's individual contribution to the total sum. We will break this into two pieces: the contribution of A[i] from subarrays whose minimum is located at or left of i, and the contribution of A[i] from subarrays whose minimum is located strictly after i.

 1. For each position i in the array A,
    let M = (m_0, m_1, ... m_r) be the indices of the
    ordered sequence of (weak) minima we see, starting
    with m_0 = -1 and ending at m_r = i.

For example, if
A = (5, 3, 9, 4, 6, 8, 10, 1, 2, 7)

then the sequence for A[5]==8 would be:
M = -1, 1, 3, 4, 5

corresponding to the minima
-infinity, 3, 4, 6, 8

seen walking left from A[5]==8.

 2. Let C(m_j, i), 1 <= j <= r, be the count of
    subarrays of A that have m_j as their minimum
    and contain A[i]. We can also let D(m_j, i) be
    this count of arrays times the shared minimum
    of the arrays: D(m_j, i) = A[m_j]*C(m_j, i).

 3. The contribution of A[i] to the total sum
    from subarrays whose minimum is located
    at or before i is the
    sum over j, 1 <= j <= r, of D(m_j, i)*A[i].
    Note that this sum excludes the
    fake minimum of -infinity

If the indices of the next_smaller element and previous_smaller_or_equal element to i have been computed, then

C(i, i) = (next_smaller[i] - i)
        * (i - previous_smaller_or_equal[i]).

Now, what I've described so far is still an O(n^2) algorithm. The trick is that we can compute C(m_j, i+1) from C(m_j, i), and that we don't need to actually compute the individual values of C for previous minima; only the sum mentioned at the end of (3) in an above code block.

C(m_j, i+1) = C(m_j, i) - (m_j-m_{j-1})
                     if A[i+1] >= A[m_j], and

            = 0
                     if A[i+1] < A[m_j].

This means that the values of our C function decrease at a fixed, linear rate independent of i until we reach a strictly smaller number than A[m_j], at which point the sum contribution from m_j has decreased to zero.

That suggests that we should keep a (weakly) monotonic stack as we scan through A, storing the (weak) minima we've seen from left to right together with the fixed linear rate at which its contribution to our D(m_j, i) function sum is decreasing. At A[i], we perform the linear decrease to our running sum, pop all elements from the top of the stack that are strictly greater than A[i] (also removing their contribution to the running sum's decrease), add A[i] * running sum to our total, and push A[i] on top of the stack.

Since each element of A is added and removed from the stack at most once, this runs in O(n) time.

The contribution of A[i] to the total sum from subarrays whose minimum is located strictly after i is computed completely analogously going right-to-left, except we keep a strictly monotonic stack, and don't count the contribution of A[i] from subarrays which have A[i] as a minimum; these have already been counted.

Here's the full code in Java. To deal with integer overflow (since individual terms of the sum can be as large as max(A)**2 * n, or 10**24 here), I've converted all arithmetic to use BigInteger. I'm not a Java expert, so there may be a better fix or ways to use arbitrary-precision integers with less overhead.

import java.math.BigInteger;
import java.util.*;

public static int sub_sums(int[] A, int n) {
    /* Given an array of integers A, compute the
    sum over all subarrays B of min(B)*sum(B)
    by using nearest smaller values

    Run-time: O(n), and O(n) extra space
    */

    ArrayList<BigInteger> nums = new ArrayList<BigInteger>(n);
    for (int i = 0; i < n; i++){
        nums.add(BigInteger.valueOf(A[i]));
    }

    BigInteger big_n = BigInteger.valueOf(n);

    BigInteger MOD = BigInteger.valueOf(7 + 1000_000_000);

    var previous_smaller_or_equal = new int[n];
    var next_smaller = new int[n];

    for (int i = 0; i < n; i++) {
        previous_smaller_or_equal[i] = i;
        int j = i-1;
        while (j >= 0 && A[j] > A[i]){
            j = previous_smaller_or_equal[j];
        }
        previous_smaller_or_equal[i] = j;
    }

    for (int i = n-1; i >= 0; i--) {
        next_smaller[i] = i;
        int j = i+1;
        while (j < n && A[j] >= A[i]){
            j = next_smaller[j];
        }
        next_smaller[i] = j;
    }

    BigInteger total = BigInteger.ZERO;
    BigInteger running_sum = BigInteger.ZERO;
    BigInteger running_sum_decrease = BigInteger.ZERO;

    var s = new Stack<Integer>();

    for (int i = 0; i < n; i++) {

        // Contributions of this element as minimum
        BigInteger term_1 = BigInteger.valueOf(next_smaller[i] - i);
        BigInteger term_2 = BigInteger.valueOf(i - previous_smaller_or_equal[i]);

        running_sum = running_sum.add(nums.get(i).multiply(term_1).multiply(term_2));

        running_sum = running_sum.subtract(running_sum_decrease);

        while (!s.empty() && A[s.peek()] > A[i]){
            var last = s.pop();
            BigInteger term_3 = nums.get(last).multiply(BigInteger.valueOf(last- previous_smaller_or_equal[last]));
            running_sum_decrease = running_sum_decrease.subtract(term_3);
        }

        total = total.add(nums.get(i).multiply(running_sum));

        running_sum_decrease = running_sum_decrease.add(term_2.multiply(nums.get(i)));

        s.push(i);
    }

    s.clear();
    running_sum = BigInteger.ZERO;
    running_sum_decrease = BigInteger.ZERO;

    for (int i = n-1; i >= 0; i--) {

        running_sum = running_sum.subtract(running_sum_decrease);
        total = total.add(nums.get(i).multiply(running_sum));

        // Contributions of this element as minimum
        // Added afterwards now, since forward-pass already counted once

        BigInteger term_1 = BigInteger.valueOf(next_smaller[i] - i);
        BigInteger term_2 = BigInteger.valueOf(i - previous_smaller_or_equal[i]);

        running_sum = running_sum.add(nums.get(i).multiply(term_1).multiply(term_2));

        while (!s.empty() && A[s.peek()] >= A[i]){
            var last = s.pop();
            BigInteger term_3 = nums.get(last).multiply(BigInteger.valueOf(next_smaller[last]- last));
            running_sum_decrease = running_sum_decrease.subtract(term_3);
        }

        running_sum_decrease = running_sum_decrease.add(term_1.multiply(nums.get(i)));

        s.push(i);
    }

    return (total.mod(MOD)).intValue();
}

Example usage:

int[] d = {1, 2, 3};
System.out.println(sub_sums(d, 3));  // Returns 33
int[] c = {3, 2, 1, 4};
System.out.println(sub_sums(c, 4));  // Returns 71


问:
Setting up naming rules for Web API model classes using Swagger
Good afternoon.
I have the following controller method:

```<code>/// <summary>
/// Метод создания вида работ
/// </summary>
/// <param name="name">Название вида работ</param>
/// <param name="workUnitId">ИД единицы вида работ</param>
/// <returns>Результат создания вида работ</returns>
[Route(nameof(CreateWorkType))]
[HttpPost]
public async Task<ActionResult<DtoResult<DtoWorkType>>> CreateWorkType(string name, Guid? workUnitId = null)
{
     try
     {

          var result = await _workTypeService.CreateWorkType(name, workUnitId).ConfigureAwait(false);

          return Ok(result);
     }
     catch
     {
          return BadRequest($"Ошибка при выполнении создания вида работ с именем \"{name}\" и ИД единицы работ \"{workUnitId}\"");
     }
}
</code>```

The method used is the generic class DtoResult:

```<code>/// <summary>
/// Класс результат
/// </summary>
/// <typeparam name="T">Тип данных сущности</typeparam>
public class DtoResult<T> where T : class, new()
{
    #region Свойства

    /// <summary>
    /// Результат проверки сущности типа данных <see cref="T"/>
    /// </summary>
    public DtoValidationResult Validation { get; set; } = new DtoValidationResult();

    /// <summary>
    /// Данные сущности типа данных <see cref="T"/>
    /// </summary>
    public T Data { get; set; } = new T();

    #endregion
}
</code>```

"Business" сlass DtoWorkType:

```<code> /// <summary>
/// Класс вида работ
/// </summary>
public class DtoWorkType
{
    #region Свойства

    /// <summary>
    /// ИД вида работ
    /// </summary>
    public Guid Id { get; set; }

    /// <summary>
    /// Название вида работ
    /// </summary>
    public string Name { get; set; } = string.Empty;

    /// <summary>
    /// Единица работ для вида работ
    /// </summary>
    public DtoWorkUnit WorkUnit { get; set; } = new DtoWorkUnit();

    #endregion
}
</code>```

Using Swagger, a class named DtoWorkTypeDtoResult was automatically created.

Question:
Is it possible to use the SWAGGER configuration tools or other mechanisms to determine the name of the class, for example, using the following algorithm:

```<code>$"{nameof(T)}Result"
</code>```

for the class to have the following name: DtoWorkTypeResult

not like now: DtoWorkTypeDtoResult

答:
You can use the method CustomSchemaIds to configure the swagger:

```<code> services.AddSwaggerGen(c =>
        {
            //other code
            c.CustomSchemaIds(p => p.Name);

        });
</code>```

Body:
Good afternoon.
I have the following controller method:

///
/// Метод создания вида работ
///
/// <param name="name">Название вида работ</param>
/// <param name="workUnitId">ИД единицы вида работ</param>
/// <returns>Результат создания вида работ</returns>
[Route(nameof(CreateWorkType))]
[HttpPost]
public async Task<ActionResult<DtoResult<DtoWorkType>>> CreateWorkType(string name, Guid? workUnitId = null)
{
     try
     {

          var result = await _workTypeService.CreateWorkType(name, workUnitId).ConfigureAwait(false);

          return Ok(result);
     }
     catch
     {
          return BadRequest($"Ошибка при выполнении создания вида работ с именем \"{name}\" и ИД единицы работ \"{workUnitId}\"");
     }
}

The method used is the generic class DtoResult:

///
/// Класс результат
///
/// <typeparam name="T">Тип данных сущности</typeparam>
public class DtoResult<T> where T : class, new()
{
    #region Свойства

    ///
    /// Результат проверки сущности типа данных <see cref="T"/>
    ///
    public DtoValidationResult Validation { get; set; } = new DtoValidationResult();

    ///
    /// Данные сущности типа данных <see cref="T"/>
    ///
    public T Data { get; set; } = new T();

    #endregion
}

"Business" сlass DtoWorkType:

 ///
/// Класс вида работ
///
public class DtoWorkType
{
    #region Свойства

    ///
    /// ИД вида работ
    ///
    public Guid Id { get; set; }

    ///
    /// Название вида работ
    ///
    public string Name { get; set; } = string.Empty;

    ///
    /// Единица работ для вида работ
    ///
    public DtoWorkUnit WorkUnit { get; set; } = new DtoWorkUnit();

    #endregion
}

Using Swagger, a class named DtoWorkTypeDtoResult was automatically created.

Question:
Is it possible to use the SWAGGER configuration tools or other mechanisms to determine the name of the class, for example, using the following algorithm:

$"{nameof(T)}Result"

for the class to have the following name: DtoWorkTypeResult

not like now: DtoWorkTypeDtoResult

Body:
You can use the method CustomSchemaIds to configure the swagger:

 services.AddSwaggerGen(c =>
        {
            //other code
            c.CustomSchemaIds(p => p.Name);

        });


问:
aiohttp terminate web.app_run

from aiohttp import web

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

app = web.Application()
app.add_routes([web.get('/', handle),
                web.get('/{name}', handle)])

if __name__ == '__main__':
    web.run_app(app)
```
<p>The above example is from oficial documentation.</p>
<p>The question is how can i terminate the <code>web.run_app(app)</code> operations with no <code>KeyBoardInterrupt</code> (Ctrl+C)?</p>
<p>I am looking something like:</p>
```await app.shutdown()
await app.cleanup()
```

but i don't know where can i put this code and how can i use it.

答:
From the source, it looks response for KeyboardInterrupt and GracefulExit:

```<code>try:
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main_task)
except (GracefulExit, KeyboardInterrupt):  # pragma: no cover
    pass
finally:
    _cancel_tasks({main_task}, loop)
    _cancel_tasks(asyncio.all_tasks(loop), loop)
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()
    asyncio.set_event_loop(None)
</code>```

As you don't want to stop in manual, you could raise GracefulExit in your own code, something like next:

test.py:

```<code>import signal
from aiohttp import web
from aiohttp.web_runner import GracefulExit

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

async def shutdown(request):
    print("will shutdown now")
    raise GracefulExit()

app = web.Application()
app.add_routes([web.get('/shutdown', shutdown),
                web.get('/', handle),
                web.get('/{name}', handle)])

if __name__ == '__main__':
    web.run_app(app)
</code>```

Once you want to close the server, you could send http://ip:8080/shutdown to server.

Additional, if you want to exit the server directly after receive a request, you may also use signal.alarm(3), then you no need to define a handler with /shutdown. This means send a alarm to program after 3 seconds after receive any request (aiohttp internal already register a signal handler with loop.add_signal_handler(signal.SIGINT, _raise_graceful_exit)):

```<code>async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    signal.alarm(3)
    return web.Response(text=text)
</code>```

Anyway, the way to close the server is either raise GracefulExit or send signal, but the timing to exit the server depends on your scenario.

Title: aiohttp terminate web.app_run

Body:
from aiohttp import web

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

app = web.Application()
app.add_routes([web.get('/', handle),
                web.get('/{name}', handle)])

if __name__ == '__main__':
    web.run_app(app)

The above example is from oficial documentation.

The question is how can i terminate the web.run_app(app) operations with no KeyBoardInterrupt (Ctrl+C)?

I am looking something like:

await app.shutdown()
await app.cleanup()

but i don't know where can i put this code and how can i use it.

Body:
From the source, it looks response for KeyboardInterrupt and GracefulExit:

try:
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main_task)
except (GracefulExit, KeyboardInterrupt):  # pragma: no cover
    pass
finally:
    _cancel_tasks({main_task}, loop)
    _cancel_tasks(asyncio.all_tasks(loop), loop)
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()
    asyncio.set_event_loop(None)

As you don't want to stop in manual, you could raise GracefulExit in your own code, something like next:

test.py:

import signal
from aiohttp import web
from aiohttp.web_runner import GracefulExit

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)

async def shutdown(request):
    print("will shutdown now")
    raise GracefulExit()

app = web.Application()
app.add_routes([web.get('/shutdown', shutdown),
                web.get('/', handle),
                web.get('/{name}', handle)])

if __name__ == '__main__':
    web.run_app(app)

Once you want to close the server, you could send http://ip:8080/shutdown to server.

Additional, if you want to exit the server directly after receive a request, you may also use signal.alarm(3), then you no need to define a handler with /shutdown. This means send a alarm to program after 3 seconds after receive any request (aiohttp internal already register a signal handler with loop.add_signal_handler(signal.SIGINT, _raise_graceful_exit)):

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    signal.alarm(3)
    return web.Response(text=text)

Anyway, the way to close the server is either raise GracefulExit or send signal, but the timing to exit the server depends on your scenario.