问:
TestCafe - How Do I Use Roles with auth0 login
I have an app with an auth0 login. I haven't been able to figure out how to make t.useRole in this scenario.

Fortunately, this is easy to reproduce. auth0 (the application) uses the same process. It fails the exact same way as my app.

Expected Outcome

 - User logs in

 - User goes to dashboard

 - User remains log in

 - User goes to dashboard again (second test)

Actual

 - User logs in

 - User goes to dashboard

 - User is no longer authenticated

 - User goes to login page

import { Role, Selector, ClientFunction } from 'testcafe';

const getPageUrl = ClientFunction(() => window.location.href.toString());

const exampleRole: Role = Role('https://auth0.com/auth/login', async t => {
    const userNameInput = Selector('input').withAttribute('name', 'email');
    const passwordInput = Selector('input').withAttribute('name', 'password');
    const loginButton = Selector('button').withAttribute('name', 'submit');

    await t
        .wait(5000)
        .click(userNameInput)
        .typeText(userNameInput, userName)
        .click(passwordInput)
        .typeText(passwordInput, password)
        .click(loginButton);
})

fixture(`SAMPLE`)
    .page('https://manage.auth0.com/dashboard')
    .beforeEach(async t => {
        await t.useRole(exampleRole)
    })

test('My first test', async t => {
    await t
        .expect(getPageUrl()).contains('dashboard')
});

test('My next test', async t => {
    await t
        .expect(getPageUrl()).contains('dashboard')
})
```

<p><strong>Output</strong>  </p>

``` SAMPLE
 √ My first test
 × My next test

   1) AssertionError: expected

   'https://auth0.auth0.com/login?state=***&client=***&protocol=oauth2&response_type=code&redirect_uri=https%3A%2F%2Fmanage.auth0.com%2Fcallback&scope=openid%20profile%20name%20email%20nickname%20created_at'
      to include 'dashboard'
    ```
</code>```

答:
I had a similar issue reported here: Testcafe: Is there a way to keep the logged-in session intact between pages?

The workaround was to add a wait after .click(loginButton) in the Role block and set presreveUrl to true.

```<code>const exampleRole: Role = Role('https://auth0.com/auth/login', async t => {
    const userNameInput = Selector('input').withAttribute('name', 'email');
    const passwordInput = Selector('input').withAttribute('name', 'password');
    const loginButton = Selector('button').withAttribute('name', 'submit');

    await t
        .wait(5000)
        .click(userNameInput)
        .typeText(userNameInput, userName)
        .click(passwordInput)
        .typeText(passwordInput, password)
        .click(loginButton);
        .wait(10000);
}, { preserveUrl: true });
</code>```

**Edited to include preserveUrl: true. Thanks @dapperdan1985.

Body:
I have an app with an auth0 login. I haven't been able to figure out how to make t.useRole in this scenario.

Fortunately, this is easy to reproduce. auth0 (the application) uses the same process. It fails the exact same way as my app.

Expected Outcome

 - User logs in

 - User goes to dashboard

 - User remains log in

 - User goes to dashboard again (second test)

Actual

 - User logs in

 - User goes to dashboard

 - User is no longer authenticated

 - User goes to login page

import { Role, Selector, ClientFunction } from 'testcafe';

const getPageUrl = ClientFunction(() => window.location.href.toString());

const exampleRole: Role = Role('https://auth0.com/auth/login', async t => {
    const userNameInput = Selector('input').withAttribute('name', 'email');
    const passwordInput = Selector('input').withAttribute('name', 'password');
    const loginButton = Selector('button').withAttribute('name', 'submit');

    await t
        .wait(5000)
        .click(userNameInput)
        .typeText(userNameInput, userName)
        .click(passwordInput)
        .typeText(passwordInput, password)
        .click(loginButton);
})

fixture(`SAMPLE`)
    .page('https://manage.auth0.com/dashboard')
    .beforeEach(async t => {
        await t.useRole(exampleRole)
    })

test('My first test', async t => {
    await t
        .expect(getPageUrl()).contains('dashboard')
});

test('My next test', async t => {
    await t
        .expect(getPageUrl()).contains('dashboard')
})

Output

 SAMPLE
 √ My first test
 × My next test

   1) AssertionError: expected

   'https://auth0.auth0.com/login?state=***&client=***&protocol=oauth2&response_type=code&redirect_uri=https%3A%2F%2Fmanage.auth0.com%2Fcallback&scope=openid%20profile%20name%20email%20nickname%20created_at'
      to include 'dashboard'
    ```

Body:
I had a similar issue reported here: Testcafe: Is there a way to keep the logged-in session intact between pages?

The workaround was to add a wait after .click(loginButton) in the Role block and set presreveUrl to true.

const exampleRole: Role = Role('https://auth0.com/auth/login', async t => {
    const userNameInput = Selector('input').withAttribute('name', 'email');
    const passwordInput = Selector('input').withAttribute('name', 'password');
    const loginButton = Selector('button').withAttribute('name', 'submit');

    await t
        .wait(5000)
        .click(userNameInput)
        .typeText(userNameInput, userName)
        .click(passwordInput)
        .typeText(passwordInput, password)
        .click(loginButton);
        .wait(10000);
}, { preserveUrl: true });

**Edited to include preserveUrl: true. Thanks @dapperdan1985.


来源: stackexchange

问:
How to render images from an array using the map() method?
I'm trying to render my images that I stored in my array by using the map() method. Unfortunately I'm getting error when I'm trying to render the image from array but without using mapping I could render the images but I need to write the codes line by line. Could anyone help me with the solution?

```<code>const CardList = ({robots}) => {
const cardComponent = robots.map((user, i) => {
    return <Card src={robots[i].src} id={robots[i].id} name={robots[i].name} email={robots[i].email}/>
})
return(
    <div>
    {cardComponent}
    </div>
);
</code>```

My CardList Component

```<code>const Card = ({name, email, id, src}) => {

return(
   <div className='bg-light-green dib br3 pa3 ma2 grow bw db w-20'>
         <img className='personal ' alt='robots' src={require(`${src}`)}/>
        <div>
             <h1>{name}</h1>
            <p>{email}</p>
        </div>
    </div>
)
</code>```

My Card Component
i feel there is something wrong with src={require(${src})}

and this is the error that i'm getting from react DOM:

答:
TLDR;

```<code>// All of these works

const fileNameExt = 'foo.jpg'
<img src={require('../images/' + fileNameExt)} />
<img src={require(`../images/${fileNameExt}`)} />

const fileName = 'foo'
<img src={require('../images/' + fileName + '.jpg')} />
<img src={require(`../images/${fileName}.jpg`)} />

// These does not work:

const myPathVariable1 = '../images/' + 'foo' + '.jpg'
<img src={require(myPathVariable1)} />

const myPathVariable2 = '../images/' + 'foo.jpg'
<img src={require(myPathVariable2)} />
</code>```

Explanation: You can not pass a variable name as argument to require because webpack doesn't do program flow analysis to know the variable value.

Webpack can not know which module it should load as it is unable to extract (guess) any information (path) about the module you provided in a variable. Hence, it fails to load when the argument is a variable.

But, webpack can require with expression because it can extract some information about the path if you provide it correctly.

For example, let's say this is the directory structure:

```<code>example_directory
│
└───template
│   │   table.ejs
│   │   table-row.ejs
│   │
│   └───directory
│       │   another.ejs
</code>```

Method 1: Using variable (would not work):

```<code>var myPath = './template/table-row.ejs'
require(myPath)
// will not work as webpack can't extract anything path or file as myPath is just a variable
</code>```

Method 2: Using expression (would work; involves some pattern webpack can understand):

```<code>var myPath = 'table'
require("./template/" + name + ".ejs")
</code>```

Webpack can parse and generate below context from the expression in Method 2:

```<code>Directory: ./template            // webpack understand that there is this directory
Regular expression: /^.*\.ejs$/  // and this regex about the modules
</code>```

So, it will load all the matching modules:

```<code>./template/table.ejs
./template/table-row.ejs
./template/directory/another.ejs
// Note that it will load all matching even if we provide --> var myPath = 'table' shown above
</code>```

So, whenever webpack see an "expression" (not the variable) in require. It loads all matching modules and generates a "Context Module" which has information of all such loaded modules as a result of above expression.

So, you need to provide an expression which webpack can understand and make context module by loading all matches.

This means dynamic requires are supported but will cause all matching modules to be included in the bundle. (And might increase your bundle size so you need to be careful when using the expression inside require)

Answer to your question:

To make this work:

```<code><img className='personal' alt='robots' src={require(`${src}`)}/>
</code>```

You need to do:

```<code><img className='personal' alt='robots' src={require("../images/" + src)}/>
// loads everyting inside "../images/"
</code>```

or, better:

```<code><img className='personal' alt='robots' src={require("../images/" + src + ".png")}/>
// loads everything inside "../images/" ending with ".png"
</code>```

You can use backticks i.e. template literals too:

```<code>`../images/${src}.png`
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to render my images that I stored in my array by using the map() method. Unfortunately I'm getting error when I'm trying to render the image from array but without using mapping I could render the images but I need to write the codes line by line. Could anyone help me with the solution?

const CardList = ({robots}) => {
const cardComponent = robots.map((user, i) => {
    return <Card src={robots[i].src} id={robots[i].id} name={robots[i].name} email={robots[i].email}/>
})
return(

    {cardComponent}

);

My CardList Component

const Card = ({name, email, id, src}) => {

return(

         <img className='personal ' alt='robots' src={require(`${src}`)}/>

{name}

{email}

)

My Card Component
i feel there is something wrong with src={require(${src})}

and this is the error that i'm getting from react DOM:

Body:
TLDR;

// All of these works

const fileNameExt = 'foo.jpg'
<img src={require('../images/' + fileNameExt)} />
<img src={require(`../images/${fileNameExt}`)} />

const fileName = 'foo'
<img src={require('../images/' + fileName + '.jpg')} />
<img src={require(`../images/${fileName}.jpg`)} />

// These does not work:

const myPathVariable1 = '../images/' + 'foo' + '.jpg'
<img src={require(myPathVariable1)} />

const myPathVariable2 = '../images/' + 'foo.jpg'
<img src={require(myPathVariable2)} />

Explanation: You can not pass a variable name as argument to require because webpack doesn't do program flow analysis to know the variable value.

Webpack can not know which module it should load as it is unable to extract (guess) any information (path) about the module you provided in a variable. Hence, it fails to load when the argument is a variable.

But, webpack can require with expression because it can extract some information about the path if you provide it correctly.

For example, let's say this is the directory structure:

example_directory
│
└───template
│   │   table.ejs
│   │   table-row.ejs
│   │
│   └───directory
│       │   another.ejs

Method 1: Using variable (would not work):

var myPath = './template/table-row.ejs'
require(myPath)
// will not work as webpack can't extract anything path or file as myPath is just a variable

Method 2: Using expression (would work; involves some pattern webpack can understand):

var myPath = 'table'
require("./template/" + name + ".ejs")

Webpack can parse and generate below context from the expression in Method 2:

Directory: ./template            // webpack understand that there is this directory
Regular expression: /^.*\.ejs$/  // and this regex about the modules

So, it will load all the matching modules:

./template/table.ejs
./template/table-row.ejs
./template/directory/another.ejs
// Note that it will load all matching even if we provide --> var myPath = 'table' shown above

So, whenever webpack see an "expression" (not the variable) in require. It loads all matching modules and generates a "Context Module" which has information of all such loaded modules as a result of above expression.

So, you need to provide an expression which webpack can understand and make context module by loading all matches.

This means dynamic requires are supported but will cause all matching modules to be included in the bundle. (And might increase your bundle size so you need to be careful when using the expression inside require)

Answer to your question:

To make this work:

<img className='personal' alt='robots' src={require(`${src}`)}/>

You need to do:

<img className='personal' alt='robots' src={require("../images/" + src)}/>
// loads everyting inside "../images/"

or, better:

<img className='personal' alt='robots' src={require("../images/" + src + ".png")}/>
// loads everything inside "../images/" ending with ".png"

You can use backticks i.e. template literals too:

`../images/${src}.png`


问:
TFS 2015 Export collection all projects source code
I need some help with how to clone all projects in my TFS 2015 (Update 3) collection at once (git). I found this powershell script below for a newer version, and I tried changing to API version from 4.0 to 2.0 but then it gets the error "Method invocation failed because [System.Management.Automation.PSCustomObject] doesn't contain a method named 'ForEach'."

Having trouble finding an example of how to do this clone in TFS 2015 API or any other way to do it.

```<code>$collection = "http://myserver:8080/tfs/DefaultCollection"

$projectsUrl = "$collection/_apis/projects?api-version=4.0"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -UseDefaultCredentials -ContentType application/json

$projects.value.ForEach({

  $reposUrl = "$collectionurl/$($_.name)/_apis/git/repositories?api-version=4.0"
  $repos = Invoke-RestMethod -Uri $reposUrl -Method Get -UseDefaultCredentials -ContentType application/json
  $repos.value.ForEach({
    git clone $_.remoteUrl --branch master --single-branch

  })
})
</code>```

答:
I got it working. The first issue was that I needed to install a newer version of powershell.

After that it was just fixing a few issues in the script, here is the working script below.

```<code>$collection = "http://myserver:8080/tfs/DefaultCollection"

$projectsUrl = "$collection/_apis/projects?api-version=2.3-preview"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -UseDefaultCredentials -ContentType application/json -AllowUnencryptedAuthentication

$projects.value.ForEach({

  $reposUrl = "$collection/$($_.name)/_apis/git/repositories?api-version=2.3-preview"
  $repos = Invoke-RestMethod -Uri $reposUrl -Method Get -UseDefaultCredentials -ContentType application/json -AllowUnencryptedAuthentication
  $repos.value.ForEach({
    git clone $_.remoteUrl --branch master --single-branch

  })
})
</code>```

Body:
I need some help with how to clone all projects in my TFS 2015 (Update 3) collection at once (git). I found this powershell script below for a newer version, and I tried changing to API version from 4.0 to 2.0 but then it gets the error "Method invocation failed because [System.Management.Automation.PSCustomObject] doesn't contain a method named 'ForEach'."

Having trouble finding an example of how to do this clone in TFS 2015 API or any other way to do it.

$collection = "http://myserver:8080/tfs/DefaultCollection"

$projectsUrl = "$collection/_apis/projects?api-version=4.0"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -UseDefaultCredentials -ContentType application/json

$projects.value.ForEach({

  $reposUrl = "$collectionurl/$($_.name)/_apis/git/repositories?api-version=4.0"
  $repos = Invoke-RestMethod -Uri $reposUrl -Method Get -UseDefaultCredentials -ContentType application/json
  $repos.value.ForEach({
    git clone $_.remoteUrl --branch master --single-branch

  })
})

Body:
I got it working. The first issue was that I needed to install a newer version of powershell.

After that it was just fixing a few issues in the script, here is the working script below.

$collection = "http://myserver:8080/tfs/DefaultCollection"

$projectsUrl = "$collection/_apis/projects?api-version=2.3-preview"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -UseDefaultCredentials -ContentType application/json -AllowUnencryptedAuthentication

$projects.value.ForEach({

  $reposUrl = "$collection/$($_.name)/_apis/git/repositories?api-version=2.3-preview"
  $repos = Invoke-RestMethod -Uri $reposUrl -Method Get -UseDefaultCredentials -ContentType application/json -AllowUnencryptedAuthentication
  $repos.value.ForEach({
    git clone $_.remoteUrl --branch master --single-branch

  })
})


问:
In Java, how would I code a pyramid of asterisks by using nested for loops?
I am working on an assignment where I have to use nested loops to program a pyramid of asterisks that is on its side.
The output of this program should look like this:

```<code>*
**
***
****
***
**
*
</code>```

When I run my program, it only displays the final four lines of the code. I don't know why the first three don't show up.
Here is my code:

```<code>public class Main
{
    public static void main(String[] args) {

        for(int a = 0; a < 8; a++) //1
        {
            if(a < 4){
                for(int b = a; b < 4; b++)
                {
                    System.out.print("*");
                }

            }
            if(a >= 4)
                for(int c = a; c < 4; c++)
                {
                    System.out.print("*");
                }

            System.out.println();
        } //loop 1

    }
}
</code>```

And here is my output:

```<code>****
***
**
*
</code>```

(There is some empty space after the output that I did not include. This is caused by the outer for loop iterating eight times.) How would I make my program correctly display all of the code, instead of just the last four lines?

Any help would be greatly appreciated.

答:
You're close. Try something like this:</p>

```<code>int size = 4;

for(int line = 1; line < size * 2; line++) {
  if(line <= size) {
    for(int i = 0; i < line; i++) {
      System.out.print("*");
    }
  }
  else {
    for(int i = 0; i < size * 2 - line; i++) {
      System.out.print("*");
    }
  }
  System.out.println();
}
</code>```

Body:
I am working on an assignment where I have to use nested loops to program a pyramid of asterisks that is on its side.
The output of this program should look like this:

*
**
***
****
***
**
*

When I run my program, it only displays the final four lines of the code. I don't know why the first three don't show up.
Here is my code:

public class Main
{
    public static void main(String[] args) {

        for(int a = 0; a < 8; a++) //1
        {
            if(a < 4){
                for(int b = a; b < 4; b++)
                {
                    System.out.print("*");
                }

            }
            if(a >= 4)
                for(int c = a; c < 4; c++)
                {
                    System.out.print("*");
                }

            System.out.println();
        } //loop 1

    }
}

And here is my output:

****
***
**
*

(There is some empty space after the output that I did not include. This is caused by the outer for loop iterating eight times.) How would I make my program correctly display all of the code, instead of just the last four lines?

Any help would be greatly appreciated.

Body:
You're close. Try something like this:

int size = 4;

for(int line = 1; line < size * 2; line++) {
  if(line <= size) {
    for(int i = 0; i < line; i++) {
      System.out.print("*");
    }
  }
  else {
    for(int i = 0; i < size * 2 - line; i++) {
      System.out.print("*");
    }
  }
  System.out.println();
}


问:
In .NET Core, ASP.NET Core - What is the relationship between Package, Reference, NuGet Package, DLL file, Namespace
The IT industry loves to create buzzwords, some new, some are new twists on old things.  In .NET Core I read about Packages, References, NuGet Packages, DLL files and Namespaces.  I understand the simple basics/steps, but is there a consistent relationship between some/all of the above words?

Does a single Reference ALWAYS point to a single Package?

Is one Package ALWAYS made of one DLL?

Is NuGet Package same as a Package?

What is the relationship between DLL file and Packages?  1 to 1, 1 to many?  None?

Creating a Reference - is doing what?  Is it pointing to ONE Package or Many?

When I use "Using ABC.123.DEF;", am I creating a new Reference?  If not, would I already have created a Reference to that?  What does Creating a Reference do, includes the DLLs (other files) in my project, or just tells the compiler to do so at compile time?

Finally, what form does MetaPackage take in Core 3?  Is it a NuGet Package?

答:
DLL File

A .dll (Dynamic Linked Library) file is a library that contains code and data that can be used by more than one program, each project that uses it adds a reference to it

Nuget Packages

Put simply, a NuGet package is a single ZIP file with the .nupkg extension that contains compiled code (DLLs), when you use Nuget pckage manager console to add packages. if i write a library that would be usefull to other developers, i can publish it to Nuget as a nuget package

Read more about nuget packages

Package Reference

A reference is essentially an entry in a project file that contains the information that Visual Studio needs to locate the component or the service.

for example, if you want to use EntityFramework in your project, you need to install it with the following command

```<code>Install-Package EntityFramework
</code>```

This adds a package reference in the .csproj file

```<code><PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
</code>```

Note: versions may vary

Body:
DLL File

A .dll (Dynamic Linked Library) file is a library that contains code and data that can be used by more than one program, each project that uses it adds a reference to it

Nuget Packages

Put simply, a NuGet package is a single ZIP file with the .nupkg extension that contains compiled code (DLLs), when you use Nuget pckage manager console to add packages. if i write a library that would be usefull to other developers, i can publish it to Nuget as a nuget package

Read more about nuget packages

Package Reference

A reference is essentially an entry in a project file that contains the information that Visual Studio needs to locate the component or the service.

for example, if you want to use EntityFramework in your project, you need to install it with the following command

Install-Package EntityFramework

This adds a package reference in the .csproj file

<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />

Note: versions may vary


问:
C Programming-Enter 3 Characters and print in reverse order
I'm having some trouble with this program. I think I have it almost right, besides the fact that it prints garbage to the screen :(</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define strsize 30

typedef struct member
{
    int number;
    char fname[strsize];
    struct member *next;
} RECORD;

RECORD* insert (RECORD *it);
RECORD* print(RECORD *it, int j);

int main (void)
{
    int i, result;
    RECORD *head, *p;
    head=NULL;
    printf("Enter the number of characters: ");
    scanf("%d", &result);

    for (i=1; i<=result; i++)
        head=insert (head);

    print (head, result);

    return 0;
}

RECORD* insert (RECORD *it)
{
    RECORD *cur, *q;
    int num;
    char junk;
    char first[strsize];
    printf("Enter a character:");
    scanf("%c", &first);

    cur=(RECORD *) malloc(sizeof(RECORD));

    strcpy(cur->fname, first);
    cur->next=NULL;

    if (it==NULL)
        it=cur;
    else
    {
        q=it;

        while (q->next!=NULL)
            q=q->next;

        q->next=cur;
    }

    return (it);
}

RECORD* print(RECORD *it, int j)
{
    RECORD *cur;
    cur=it;
    int i;

    for(i=1;i<=j;i++)
    {
        printf("%c \n", cur->fname);
        cur=cur->next;
    }

    return;
}
</code>```

答:
Take a quick step back; I'd like to suggest some general programming guidelines based on what I see from your code:

```<code>RECORD* insert (RECORD *it)
{
    RECORD *cur, *q;
    int num;
    char junk;
    char first[strsize];
    printf("Enter a character:");
    scanf("%c", &first);

    cur=(RECORD *) malloc(sizeof(RECORD));
</code>```

An insert() routine on records suitable for complex datastructures is not usually expected / allowed / desired to perform user interaction; you are mingling user interface with internal business logic. (While business logic is a high-falutin phrase, I don't know a better way to say "the things your program has to do in order to justify its existence" or "the essential requirements the program must satisfy". Replacement suggestions welcomed. :)

Consider this pseudo-code as a replacement algorithm:

```<code>while we need more characters
    prompt user for another character
    store character in datastructure
print datastructure in reverse
</code>```

Separate all the code for the datastructure from the interaction with the human. (This separation of presentation from logic is often formalized as
Model View Controller, but it is important to recognize that it is not limited to user interfaces -- you want your stack, list, or queue to be useful in your next programming project, so build generic routines that only operate on the stack, list, or queue, and you can reuse them in the next project.)

Update

Write a program that creates a linked
  list of 10 characters, then creates a
  copy of the list in reverse order. The
  user should be prompted to input the
  characters and the program should have
  a print function that prints out the
  original list and then prints out the
  list in reverse order

Now this is more like it. While I appreciate what your teacher is trying to do, a linked list isn't the datastructure I'd select for this problem. (I would pick an array if the problem size was bounded, a stack if the problem size was unbounded.) It's solvable with a linked list, and there are three possible approaches that come to mind immediately:

Write a recursive output function that works like this:

```<code>void print_output(RECORD *r) {
    if this is the last RECORD in the chain
        print the data
    else
        print_output(next record in the chain)
}
</code>```

This uses the call stack to reverse the output. Clever trick, but sometimes wastes memory compared to other approaches.

Write your lists with doubly-linked list elements. Use both next and prev pointers, and manage them all carefully to allow you to traverse the list in either direction. This requires subtle coding and carefully thinking things through. Or copying the correct order of operations from a published source such as Knuth or your favorite algorithms text. :)

Actually reverse your singly-linked list. Also requires subtle, careful coding or thoughtful copying. :)

Body:
I'm having some trouble with this program. I think I have it almost right, besides the fact that it prints garbage to the screen :(

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define strsize 30

typedef struct member
{
    int number;
    char fname[strsize];
    struct member *next;
} RECORD;

RECORD* insert (RECORD *it);
RECORD* print(RECORD *it, int j);

int main (void)
{
    int i, result;
    RECORD *head, *p;
    head=NULL;
    printf("Enter the number of characters: ");
    scanf("%d", &result);

    for (i=1; i<=result; i++)
        head=insert (head);

    print (head, result);

    return 0;
}

RECORD* insert (RECORD *it)
{
    RECORD *cur, *q;
    int num;
    char junk;
    char first[strsize];
    printf("Enter a character:");
    scanf("%c", &first);

    cur=(RECORD *) malloc(sizeof(RECORD));

    strcpy(cur->fname, first);
    cur->next=NULL;

    if (it==NULL)
        it=cur;
    else
    {
        q=it;

        while (q->next!=NULL)
            q=q->next;

        q->next=cur;
    }

    return (it);
}

RECORD* print(RECORD *it, int j)
{
    RECORD *cur;
    cur=it;
    int i;

    for(i=1;i<=j;i++)
    {
        printf("%c \n", cur->fname);
        cur=cur->next;
    }

    return;
}

Body:
Take a quick step back; I'd like to suggest some general programming guidelines based on what I see from your code:

RECORD* insert (RECORD *it)
{
    RECORD *cur, *q;
    int num;
    char junk;
    char first[strsize];
    printf("Enter a character:");
    scanf("%c", &first);

    cur=(RECORD *) malloc(sizeof(RECORD));

An insert() routine on records suitable for complex datastructures is not usually expected / allowed / desired to perform user interaction; you are mingling user interface with internal business logic. (While business logic is a high-falutin phrase, I don't know a better way to say "the things your program has to do in order to justify its existence" or "the essential requirements the program must satisfy". Replacement suggestions welcomed. :)

Consider this pseudo-code as a replacement algorithm:

while we need more characters
    prompt user for another character
    store character in datastructure
print datastructure in reverse

Separate all the code for the datastructure from the interaction with the human. (This separation of presentation from logic is often formalized as
Model View Controller, but it is important to recognize that it is not limited to user interfaces -- you want your stack, list, or queue to be useful in your next programming project, so build generic routines that only operate on the stack, list, or queue, and you can reuse them in the next project.)

Update

Write a program that creates a linked
  list of 10 characters, then creates a
  copy of the list in reverse order. The
  user should be prompted to input the
  characters and the program should have
  a print function that prints out the
  original list and then prints out the
  list in reverse order

Now this is more like it. While I appreciate what your teacher is trying to do, a linked list isn't the datastructure I'd select for this problem. (I would pick an array if the problem size was bounded, a stack if the problem size was unbounded.) It's solvable with a linked list, and there are three possible approaches that come to mind immediately:

Write a recursive output function that works like this:

void print_output(RECORD *r) {
    if this is the last RECORD in the chain
        print the data
    else
        print_output(next record in the chain)
}

This uses the call stack to reverse the output. Clever trick, but sometimes wastes memory compared to other approaches.

Write your lists with doubly-linked list elements. Use both next and prev pointers, and manage them all carefully to allow you to traverse the list in either direction. This requires subtle coding and carefully thinking things through. Or copying the correct order of operations from a published source such as Knuth or your favorite algorithms text. :)

Actually reverse your singly-linked list. Also requires subtle, careful coding or thoughtful copying. :)

ContentLicense: CC BY-SA 3.0


问:
How to handle too many SQL Connections?
I’m trying to develop a server for a mobile game which should be able to withstand 1000 simultaneous connections. The Server is connected to a MySQL Database and each time I am looking to access the database I enclose my SQLConnection Cmd and Reader with a using statement so that they are all opened briefly and closed afterwards:

```<code>using (MySqlConnection SQLToUse = CreateSQLConnection()) {
   MySqlCommand cmd = new MySqlCommand(query, SQLToUse);
   ...
}
</code>```

I had problems with readers which is why I had to do this.
Theoretically, if say 1000 users were to open SQL Connections simultaneously, the maximum amount of SQL connections (151 to my knowledge) would stop me from creating any more connections and throw an error. This hasn’t happened yet because the highest number of users the server ever had at once was 10, but i am asking how to prevent it.
Thank you for reading this all the way through and for your help in advance

答:
What you need to do is to create a service part that keep the connection(s) open and then the other part of the game make requests to this part. (sort of how you use a library)

I would also suggest you add a stack and each time a query is done it can check the stack for another query to run. Each time something is added to the stack, check if there is any connections available, if there are activate a connection that will pick up the new line in the stack.

Very hard to describe the code with no information on what languages is used but this should get you in the right direction.

Title: How to handle too many SQL Connections?

Body:
I’m trying to develop a server for a mobile game which should be able to withstand 1000 simultaneous connections. The Server is connected to a MySQL Database and each time I am looking to access the database I enclose my SQLConnection Cmd and Reader with a using statement so that they are all opened briefly and closed afterwards:

using (MySqlConnection SQLToUse = CreateSQLConnection()) {
   MySqlCommand cmd = new MySqlCommand(query, SQLToUse);
   ...
}

I had problems with readers which is why I had to do this.
Theoretically, if say 1000 users were to open SQL Connections simultaneously, the maximum amount of SQL connections (151 to my knowledge) would stop me from creating any more connections and throw an error. This hasn’t happened yet because the highest number of users the server ever had at once was 10, but i am asking how to prevent it.
Thank you for reading this all the way through and for your help in advance


问:
Scraping tracks' links from YouTube playlist with Beautiful Soup
I am trying to scrape all links for tracks from my playlist.

This is my code

```<code>from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re

playlist = 'minimal_house'

url = 'https://www.youtube.com/channel/UCt2GxiTBN_RiE-cbP0cmk5Q/playlists'
html = urlopen(url)
soup = BeautifulSoup(html , 'html.parser')
tracks = soup.find(title = playlist).get('href')

print(tracks)

url = url + tracks
print(url)

html = urlopen(url)

soup = BeautifulSoup(html, 'html.parser')

links = soup.find_all('a',attrs={'class':'yt-simple-endpoint style-scope ytd-playlist-panel-video-renderer'})

print(links)
</code>```

I couldn't scrape 'a'; nor by id; nor by class name.

答:
it's my messy code that works for me:

```<code>from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re

playlist = 'minimal_house'

url = 'https://www.youtube.com/channel/UCt2GxiTBN_RiE-cbP0cmk5Q/playlists'
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
tracks = soup.find('a', attrs={'title': playlist}).get('href')

print(tracks)

url = 'https://www.youtube.com' + str(tracks)
print(url)

html = urlopen(url)

soup = BeautifulSoup(html, 'html.parser')

links = soup.find_all('a')
links = set([link.get('href') for link in links if link.get('href').count('watch')])

print(links)
</code>```

since class names change base on device request, it's better to get all links in this case.
and you need to use selenium to scroll down to fetch all the list.

Body:
I am trying to scrape all links for tracks from my playlist.

This is my code

from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re

playlist = 'minimal_house'

url = 'https://www.youtube.com/channel/UCt2GxiTBN_RiE-cbP0cmk5Q/playlists'
html = urlopen(url)
soup = BeautifulSoup(html , 'html.parser')
tracks = soup.find(title = playlist).get('href')

print(tracks)

url = url + tracks
print(url)

html = urlopen(url)

soup = BeautifulSoup(html, 'html.parser')

links = soup.find_all('a',attrs={'class':'yt-simple-endpoint style-scope ytd-playlist-panel-video-renderer'})

print(links)

I couldn't scrape 'a'; nor by id; nor by class name.

Body:
it's my messy code that works for me:

from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re

playlist = 'minimal_house'

url = 'https://www.youtube.com/channel/UCt2GxiTBN_RiE-cbP0cmk5Q/playlists'
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
tracks = soup.find('a', attrs={'title': playlist}).get('href')

print(tracks)

url = 'https://www.youtube.com' + str(tracks)
print(url)

html = urlopen(url)

soup = BeautifulSoup(html, 'html.parser')

links = soup.find_all('a')
links = set([link.get('href') for link in links if link.get('href').count('watch')])

print(links)

since class names change base on device request, it's better to get all links in this case.
and you need to use selenium to scroll down to fetch all the list.


问:
How to take the 5th power python
I want to find the 5th power of a number given by the user. Can i do this without typing:

```<code>ans = n * n * n * n * n
</code>```

and can it be used for higher powers?

答:
An alternative to the ** operator is to use the math library functions.

```<code>import math
math.pow(x, y)
</code>```

Note that this returns a floating point value, while the ** operator will return an int or float based on the type of x.

Title: How to take the 5th power python

Body:
I want to find the 5th power of a number given by the user. Can i do this without typing:

ans = n * n * n * n * n

and can it be used for higher powers?

Body:
An alternative to the ** operator is to use the math library functions.

import math
math.pow(x, y)

Note that this returns a floating point value, while the ** operator will return an int or float based on the type of x.


问:
php artisan migrate error: nodename nor servname provided or not know
I'm in trouble with my laradock project: i have downloaded and installed docker and i have successfully completed the setup of my laravel project with laradock. I use php 7, laravel(5.5.14) and the latest version of laradock. I start my project writing in shell:

```<code>docker-compose up -d nginx mysql
</code>```

and all services starts. My env file is:

```<code>DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=root
DB_PASSWORD=root
</code>```

But when i try to use the migration with

```<code>php artisan migrate
</code>```

i receive this error:

```<code>SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known (SQL: select * from information_schema.tables where table_schema = homestead and table_name = migrations)
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known
PDO::__construct(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known
</code>```

My db called homestead is created and it works. In my laravel project, under the migration folder i have 3 files php: create_user_table, create_password_reset_table and create_customer_table( i have wrote this file). I need to create a table in my db called customer with some colums:

```<code>Schema::create('customers', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->boolean('azienda');
        $table->string('iva');
        $table->string('ds');
        $table->boolean('fatres');
        $table->string('cf');
        $table->string('mail');
        $table->string('telefono');
        $table->integer('sponsor');
        $table->string('indinst');
        $table->string('civinst');
        $table->string('cityInst');
        $table->string('capinst');
        $table->string('provinst');
        $table->string('indf');
        $table->string('civf');
        $table->string('capf');
        $table->string('provf');
        $table->string('cityFatt');
        $table->timestamps();
    });
</code>```

How can i complete the migration and create the table? Thank you for answer!

答:
@Stefano Zaniboni answered this in a comment but to expand:

I ran across this issue because I'm used to running php artisan commands in my local directory rather than in a virtualbox / vagrant box / docker container.

The Laravel Docs mention that you need to run the php artisan migrate command from within your virtual machine.

If you're using docker, you can get your container id using docker ps.  Then to ssh into the container use docker exec -it <containerId> /bin/bash.  Then just cd into your project directory and run php artisan migrate.

Body:
I'm in trouble with my laradock project: i have downloaded and installed docker and i have successfully completed the setup of my laravel project with laradock. I use php 7, laravel(5.5.14) and the latest version of laradock. I start my project writing in shell:

docker-compose up -d nginx mysql

and all services starts. My env file is:

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=root
DB_PASSWORD=root

But when i try to use the migration with

php artisan migrate

i receive this error:

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known (SQL: select * from information_schema.tables where table_schema = homestead and table_name = migrations)
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known
PDO::__construct(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known

My db called homestead is created and it works. In my laravel project, under the migration folder i have 3 files php: create_user_table, create_password_reset_table and create_customer_table( i have wrote this file). I need to create a table in my db called customer with some colums:

Schema::create('customers', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->boolean('azienda');
        $table->string('iva');
        $table->string('ds');
        $table->boolean('fatres');
        $table->string('cf');
        $table->string('mail');
        $table->string('telefono');
        $table->integer('sponsor');
        $table->string('indinst');
        $table->string('civinst');
        $table->string('cityInst');
        $table->string('capinst');
        $table->string('provinst');
        $table->string('indf');
        $table->string('civf');
        $table->string('capf');
        $table->string('provf');
        $table->string('cityFatt');
        $table->timestamps();
    });

How can i complete the migration and create the table? Thank you for answer!


问:
Publishing .NET Core 3.1 React application on IIS 8.5 results in API routes not being respected
I'm currently trying to mount a .NET Core 3.1 MVC application created with dotnet new react. The application works perfectly fine when running it via Visual Studio Code. However, when publishing with dotnet publish -c Release -r win81-x64 and mounting the application in IIS 8.5, the routes for the APIs stop working, sending all requests to the React page.

Currently my configuration in Startup.cs looks like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSpaStaticFiles();

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller}/{action=Index}/{id?}");
    });

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
}
```

<p>And the code in a test controller I made looks like this:</p>

<pre class="lang-cs prettyprint-override"><code>namespace Application.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase {

        private readonly ILogger<TestController> _logger;

        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public async Task<ActionResult<string>> GetTest()
        {
            return "Test";
        }
    }
}
</code>```

I also tried creating a new React project and mounting it, and that does seem to work. However, the Startup.cs file has the exact same configuration, so I can't find anything to modify on my application.

答: I figured it out. Turns out the first version I uploaded had some issues that prevented routes from working properly, and while I immediately fixed it, the Service Worker that the default .NET project has cached the broken API point as part of the site. Apparently this bypasses having the 'Disable Cache' tick box in developer tools.</p>

Body:
I'm currently trying to mount a .NET Core 3.1 MVC application created with dotnet new react. The application works perfectly fine when running it via Visual Studio Code. However, when publishing with dotnet publish -c Release -r win81-x64 and mounting the application in IIS 8.5, the routes for the APIs stop working, sending all requests to the React page.

Currently my configuration in Startup.cs looks like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSpaStaticFiles();

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller}/{action=Index}/{id?}");
    });

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
}

And the code in a test controller I made looks like this:

namespace Application.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase {

        private readonly ILogger<TestController> _logger;

        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public async Task<ActionResult<string>> GetTest()
        {
            return "Test";
        }
    }
}

I also tried creating a new React project and mounting it, and that does seem to work. However, the Startup.cs file has the exact same configuration, so I can't find anything to modify on my application.


问:
How to extract numbers from a string in Python?
I would like to extract all the numbers contained in a string. Which is better suited for the purpose, regular expressions or the isdigit() method?

Example:

```<code>line = "hello 12 hi 89"
</code>```

Result:

```<code>[12, 89]
</code>```

答:
For phone numbers you can simply exclude all non-digit characters with \D in regex:

import re

phone_number = "(619) 459-3635"
phone_number = re.sub(r"\D", "", phone_number)
print(phone_number)
```

The r in r"\D" stands for raw string. It is necessary. Without it, Python will consider \D as an escape character.

Body:
I would like to extract all the numbers contained in a string. Which is better suited for the purpose, regular expressions or the isdigit() method?

Example:

line = "hello 12 hi 89"

Result:

[12, 89]

Body:
For phone numbers you can simply exclude all non-digit characters with \D in regex:

import re

phone_number = "(619) 459-3635"
phone_number = re.sub(r"\D", "", phone_number)
print(phone_number)

The r in r"\D" stands for raw string. It is necessary. Without it, Python will consider \D as an escape character.


问:
SQL Statement with "dynamic" where clause

Possible Duplicate:

  Howto build a SQL statement with using IDs that might not be available in the table?

Hello together, I try to build a SQL statement with some unknown variables.
I would like to select the province, district, commune and village out of table dbo.pmd.
As there are only the IDs stored, I need to read the name out of the value table.
This is no problem for province and district as they will always be filled in table dbo.pmd. Anyhow the commune and village is not mandatory and might therefor be not filled.
This is where it comes to a problem if I compare the IDs between dbo.pmd and dbo.vhcs (communes) and dbo.pmd and dbo.vhv (villages) if there is no value stored in the dbo.pmd table.

The tables look like this:

table: dbo.pmd

fields: province, district, commune, village (stored value is the ID number)

table: dbo.vhp

fields: country_id, province_id, province_en (name of province)

table: dbo.vhd

fields: province_id, district_id, district_en (name of district)

table: dbo.vhc2

fields: district_id, commune_id, commune_en (name of commune)

table: dbo.vhv

fields: commune_id, village_id, village_en (name of commune)

My current statement looks like this:

```<code>SELECT pmd.patient_code, pmd.last_name, pmd.first_name, pmd.age, pmd.sex, pmd.province, pmd.district, pmd.commune, pmd.village
FROM dbo.pmd AS pmd
INNER JOIN dbo.vhp AS vhp
ON pmd.province = vhp.province_id
INNER JOIN dbo.vhd AS vhd
ON pmd.district = vhd.district_id
INNER JOIN dbo.vhc2 AS vhc2
ON (pmd.commune is NULL OR (pmd.commune = vhc2.commune_id))
INNER JOIN dbo.vhv AS vhv
ON (pmd.village is NULL OR (pmd.village = vhv.village_id))
ORDER BY pmd.last_name
</code>```

I have two entries in my database. One entry with commune_id and village_id = NULL and one with commune_id and village_id = some ID number.

I have stopped the execution of this statement after ~2minutes and there are: 8273612 rows all with the same values, showing only the entry with commund_id and village_id equals NULL.

I am using Microsoft SQL Server 2008.

答:
Those two is null checks on join are causing the issue. I think you are looking for left join

```<code>SELECT pmd.patient_code, pmd.last_name, pmd.first_name, pmd.age, pmd.sex, pmd.province, pmd.district, pmd.commune, pmd.village
FROM dbo.pmd AS pmd
    INNER JOIN dbo.vhp AS vhp
        ON pmd.province = vhp.province_id
    INNER JOIN dbo.vhd AS vhd
        ON pmd.district = vhd.district_id
    LEFT JOIN dbo.vhc2 AS vhc2
        ON pmd.commune = vhc2.commune_id
    LEFT JOIN dbo.vhv AS vhv
        ON pmd.village = vhv.village_id
ORDER BY pmd.last_name
</code>```

Side note: you might want to revisit table namings - very difficult to understand the db design.

Body:
Possible Duplicate:

  Howto build a SQL statement with using IDs that might not be available in the table?

Hello together, I try to build a SQL statement with some unknown variables.
I would like to select the province, district, commune and village out of table dbo.pmd.
As there are only the IDs stored, I need to read the name out of the value table.
This is no problem for province and district as they will always be filled in table dbo.pmd. Anyhow the commune and village is not mandatory and might therefor be not filled.
This is where it comes to a problem if I compare the IDs between dbo.pmd and dbo.vhcs (communes) and dbo.pmd and dbo.vhv (villages) if there is no value stored in the dbo.pmd table.

The tables look like this:

table: dbo.pmd

fields: province, district, commune, village (stored value is the ID number)

table: dbo.vhp

fields: country_id, province_id, province_en (name of province)

table: dbo.vhd

fields: province_id, district_id, district_en (name of district)

table: dbo.vhc2

fields: district_id, commune_id, commune_en (name of commune)

table: dbo.vhv

fields: commune_id, village_id, village_en (name of commune)

My current statement looks like this:

SELECT pmd.patient_code, pmd.last_name, pmd.first_name, pmd.age, pmd.sex, pmd.province, pmd.district, pmd.commune, pmd.village
FROM dbo.pmd AS pmd
INNER JOIN dbo.vhp AS vhp
ON pmd.province = vhp.province_id
INNER JOIN dbo.vhd AS vhd
ON pmd.district = vhd.district_id
INNER JOIN dbo.vhc2 AS vhc2
ON (pmd.commune is NULL OR (pmd.commune = vhc2.commune_id))
INNER JOIN dbo.vhv AS vhv
ON (pmd.village is NULL OR (pmd.village = vhv.village_id))
ORDER BY pmd.last_name

I have two entries in my database. One entry with commune_id and village_id = NULL and one with commune_id and village_id = some ID number.

I have stopped the execution of this statement after ~2minutes and there are: 8273612 rows all with the same values, showing only the entry with commund_id and village_id equals NULL.

I am using Microsoft SQL Server 2008.

Body:
Those two is null checks on join are causing the issue. I think you are looking for left join

SELECT pmd.patient_code, pmd.last_name, pmd.first_name, pmd.age, pmd.sex, pmd.province, pmd.district, pmd.commune, pmd.village
FROM dbo.pmd AS pmd
    INNER JOIN dbo.vhp AS vhp
        ON pmd.province = vhp.province_id
    INNER JOIN dbo.vhd AS vhd
        ON pmd.district = vhd.district_id
    LEFT JOIN dbo.vhc2 AS vhc2
        ON pmd.commune = vhc2.commune_id
    LEFT JOIN dbo.vhv AS vhv
        ON pmd.village = vhv.village_id
ORDER BY pmd.last_name

Side note: you might want to revisit table namings - very difficult to understand the db design.


问:
Detecting change in folder view mode
Is there a way to hook or sink the change in an IFolderView's view mode (e.g., details, icons, etc.)?

I see a DISPID_VIEWMODECHANGED, but I don't understand which sink that belongs to.  I don't think it belongs to DShellFolderViewEvents.

Also, I don't believe that DWebBrowserEvents2's DISPID_DOCUMENTCOMPLETE fires when the view mode changes.

Thank you for any input.

答:
It's indeed DISPID_VIEWMODECHANGED for DShellFolderViewEvents, but it's quite complex to get it.

Here is a Console App sample code that monitors all view mode changes for all currently open Explorer views. So to test it you must:

open some Explorer view(s);

run the program. When you change any of the opened folder view mode, you should see the event printed.

Some reference links:

Receiving a notification any time the selection changes in an Explorer window

Dispatch interfaces as connection point interfaces

```<code>int main()
{
  CoInitialize(NULL);
  {
    CComPtr<IShellWindows> windows;
    windows.CoCreateInstance(CLSID_ShellWindows);

    long count = 0;
    windows->get_Count(&count);

    // array to remember one sink for one view
    CAtlArray<CComPtr<CShellFolderViewEventsSink>> sinks;
    for (int i = 0; i < count; i++)
    {
      // get window #i
      CComPtr<IDispatch> disp;
      windows->Item(CComVariant(i), &disp);
      if (disp)
      {
        // get top level browser
        CComPtr<IShellBrowser> browser;
        CComQIPtr<IServiceProvider>(disp)->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&browser));
        if (browser)
        {
          // get shell view
          CComPtr<IShellView> view;
          browser->QueryActiveShellView(&view);
          if (view)
          {
            // get the ShellViewFolder (scripting) object
            CComPtr<IDispatch> viewDisp;
            view->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&viewDisp));
            if (viewDisp)
            {
              CComPtr<IShellFolderViewDual> fview;
              viewDisp->QueryInterface(&fview);
              if (fview)
              {
                CComPtr<CShellFolderViewEventsSink> sink;
                sink.Attach(new CShellFolderViewEventsSink());
                sinks.Add(sink);
                sink->Connect(fview);
              }
            }
          }
        }
      }
    }

    // wait for user input (and pump messages)
    MessageBox(nullptr, L"Click to stop listening", L"View Events", MB_OK);
    for (int i = 0; i < sinks.GetCount(); i++)
    {
      sinks.GetAt(i)->Disconnect();
    }
  }
  CoUninitialize();
  return 0;
}

// class that checks for DISPID_VIEWMODECHANGED
class CShellFolderViewEventsSink : public CDispInterfaceBase<DShellFolderViewEvents>
{
public:
  CShellFolderViewEventsSink() { }
  HRESULT Invoke( DISPID dispid, DISPPARAMS* pdispparams, VARIANT* pvarResult)
  {
    switch (dispid)
    {
    case DISPID_VIEWMODECHANGED:
      printf("DISPID_VIEWMODECHANGED called\n");
      break;
    }
    return S_OK;
  }
};

// support class to hook IDispatch events
template<typename DispInterface>
class CDispInterfaceBase : public DispInterface
{
  LONG m_cRef;
  CComPtr<IConnectionPoint> m_spcp;
  DWORD m_dwCookie;

public:
  CDispInterfaceBase() : m_cRef(1), m_dwCookie(0) { }

  // IDispatch
  IFACEMETHODIMP QueryInterface(REFIID riid, void** ppv)
  {
    *ppv = nullptr;
    HRESULT hr = E_NOINTERFACE;
    if (riid == IID_IUnknown || riid == IID_IDispatch || riid == __uuidof(DispInterface))
    {
      *ppv = static_cast<DispInterface*>(static_cast<IDispatch*>(this));
      AddRef();
      hr = S_OK;
    }
    return hr;
  }

  IFACEMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&m_cRef); }
  IFACEMETHODIMP_(ULONG) Release() { LONG cRef = InterlockedDecrement(&m_cRef); if (!cRef) delete this; return cRef; }

  // IDispatch
  IFACEMETHODIMP GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 0; return E_NOTIMPL; }
  IFACEMETHODIMP GetTypeInfo(UINT iTInfo, LCID lcid, ITypeInfo** ppTInfo) { *ppTInfo = nullptr; return E_NOTIMPL; }
  IFACEMETHODIMP GetIDsOfNames(REFIID, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgDispId) { return E_NOTIMPL; }
  IFACEMETHODIMP Invoke(DISPID dispid, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr)
  {
    if (pvarResult) VariantInit(pvarResult);
    return Invoke(dispid, pdispparams, pvarResult);
  }

  virtual HRESULT Invoke(DISPID dispid, DISPPARAMS* pdispparams, VARIANT* pvarResult) = 0;

public:
  HRESULT Connect(IUnknown* punk)
  {
    CComPtr<IConnectionPointContainer> spcpc;
    HRESULT  hr = punk->QueryInterface(IID_PPV_ARGS(&spcpc));
    if (SUCCEEDED(hr)) hr = spcpc->FindConnectionPoint(__uuidof(DispInterface), &m_spcp);
    if (SUCCEEDED(hr)) hr = m_spcp->Advise(this, &m_dwCookie);
    return hr;
  }

  void Disconnect()
  {
    if (m_dwCookie)
    {
      m_spcp->Unadvise(m_dwCookie);
      m_spcp.Release();
      m_dwCookie = 0;
    }
  }
};
</code>```

Title: Detecting change in folder view mode

Body:
It's indeed DISPID_VIEWMODECHANGED for DShellFolderViewEvents, but it's quite complex to get it.

Here is a Console App sample code that monitors all view mode changes for all currently open Explorer views. So to test it you must:

open some Explorer view(s);

run the program. When you change any of the opened folder view mode, you should see the event printed.

Some reference links:

Receiving a notification any time the selection changes in an Explorer window

Dispatch interfaces as connection point interfaces

int main()
{
  CoInitialize(NULL);
  {
    CComPtr<IShellWindows> windows;
    windows.CoCreateInstance(CLSID_ShellWindows);

    long count = 0;
    windows->get_Count(&count);

    // array to remember one sink for one view
    CAtlArray<CComPtr<CShellFolderViewEventsSink>> sinks;
    for (int i = 0; i < count; i++)
    {
      // get window #i
      CComPtr<IDispatch> disp;
      windows->Item(CComVariant(i), &disp);
      if (disp)
      {
        // get top level browser
        CComPtr<IShellBrowser> browser;
        CComQIPtr<IServiceProvider>(disp)->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&browser));
        if (browser)
        {
          // get shell view
          CComPtr<IShellView> view;
          browser->QueryActiveShellView(&view);
          if (view)
          {
            // get the ShellViewFolder (scripting) object
            CComPtr<IDispatch> viewDisp;
            view->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&viewDisp));
            if (viewDisp)
            {
              CComPtr<IShellFolderViewDual> fview;
              viewDisp->QueryInterface(&fview);
              if (fview)
              {
                CComPtr<CShellFolderViewEventsSink> sink;
                sink.Attach(new CShellFolderViewEventsSink());
                sinks.Add(sink);
                sink->Connect(fview);
              }
            }
          }
        }
      }
    }

    // wait for user input (and pump messages)
    MessageBox(nullptr, L"Click to stop listening", L"View Events", MB_OK);
    for (int i = 0; i < sinks.GetCount(); i++)
    {
      sinks.GetAt(i)->Disconnect();
    }
  }
  CoUninitialize();
  return 0;
}

// class that checks for DISPID_VIEWMODECHANGED
class CShellFolderViewEventsSink : public CDispInterfaceBase<DShellFolderViewEvents>
{
public:
  CShellFolderViewEventsSink() { }
  HRESULT Invoke( DISPID dispid, DISPPARAMS* pdispparams, VARIANT* pvarResult)
  {
    switch (dispid)
    {
    case DISPID_VIEWMODECHANGED:
      printf("DISPID_VIEWMODECHANGED called\n");
      break;
    }
    return S_OK;
  }
};

// support class to hook IDispatch events
template<typename DispInterface>
class CDispInterfaceBase : public DispInterface
{
  LONG m_cRef;
  CComPtr<IConnectionPoint> m_spcp;
  DWORD m_dwCookie;

public:
  CDispInterfaceBase() : m_cRef(1), m_dwCookie(0) { }

  // IDispatch
  IFACEMETHODIMP QueryInterface(REFIID riid, void** ppv)
  {
    *ppv = nullptr;
    HRESULT hr = E_NOINTERFACE;
    if (riid == IID_IUnknown || riid == IID_IDispatch || riid == __uuidof(DispInterface))
    {
      *ppv = static_cast<DispInterface*>(static_cast<IDispatch*>(this));
      AddRef();
      hr = S_OK;
    }
    return hr;
  }

  IFACEMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&m_cRef); }
  IFACEMETHODIMP_(ULONG) Release() { LONG cRef = InterlockedDecrement(&m_cRef); if (!cRef) delete this; return cRef; }

  // IDispatch
  IFACEMETHODIMP GetTypeInfoCount(UINT* pctinfo) { *pctinfo = 0; return E_NOTIMPL; }
  IFACEMETHODIMP GetTypeInfo(UINT iTInfo, LCID lcid, ITypeInfo** ppTInfo) { *ppTInfo = nullptr; return E_NOTIMPL; }
  IFACEMETHODIMP GetIDsOfNames(REFIID, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgDispId) { return E_NOTIMPL; }
  IFACEMETHODIMP Invoke(DISPID dispid, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr)
  {
    if (pvarResult) VariantInit(pvarResult);
    return Invoke(dispid, pdispparams, pvarResult);
  }

  virtual HRESULT Invoke(DISPID dispid, DISPPARAMS* pdispparams, VARIANT* pvarResult) = 0;

public:
  HRESULT Connect(IUnknown* punk)
  {
    CComPtr<IConnectionPointContainer> spcpc;
    HRESULT  hr = punk->QueryInterface(IID_PPV_ARGS(&spcpc));
    if (SUCCEEDED(hr)) hr = spcpc->FindConnectionPoint(__uuidof(DispInterface), &m_spcp);
    if (SUCCEEDED(hr)) hr = m_spcp->Advise(this, &m_dwCookie);
    return hr;
  }

  void Disconnect()
  {
    if (m_dwCookie)
    {
      m_spcp->Unadvise(m_dwCookie);
      m_spcp.Release();
      m_dwCookie = 0;
    }
  }
};


问:
Merging two arrays without using extra space
I have 2 sorted arrays, a1 and a2, of lengths l1 and l2, respectively.  The array a2 has empty space at the end of length l1, so it can hold all of the elements of a1 in addition to its own elements.  Now, I want to merge a1 into a2 so that a2 will contain all the elements of a1 and a2 in sorted order.  Ideally this should use O(1) auxiliary storage space.  I have the following cod,e but something is going wrong:

```<code> public static int[] merge(int []a1,int a2[],int l1, int l2){

         System.out.println("l1 =" +l1 + " l2=" +l2);
         int es = l2-l1;
         int fs = l2-es;

         System.out.println("es= " +es);
         System.out.println("fs = " + fs);
         int j=0;

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

             if(j<fs){
                // System.out.println("i= " + i + "a1[i]=" + a1[i]);
                // System.out.println("j= " + j + "a2[j]=" + a2[j]);
                 if(a1[i]<a2[j]){
                     add(a2,j,a1[i],l2);
                     //i++;
                     fs++;
                 }
             }else{
                 System.out.println("***");
                 a2[j]=a1[i];
             }

             j++;
         }

         return a2;
     }

    public static void add(int []a,int p,int key,int l){

        for(int i=l-1;i>p;i--){
              a[i]= a[i-1];
        }
        a[p]= key;
    }
</code>```

Does anyone have any ideas on how to fix this?  I used following data to run the code:

```<code>int a1[]= new int[]{-1,0,7,8};
int a2[]= new int[7];
a2[0]=1;
a2[1]=3;
a2[2]=9;
</code>```

Output is

```<code>l1 =4 l2=7
es= 3
fs = 4
-1
0
1
3
9
0
0
</code>```

答:
The better way to solve the question is used to Insertion sort for merging two sorted arrays in O(1) auxiliary space. </p>

<p>/* as we have to merge the 2 sorted arrays in array2. we begin from the end of array2 and insert the array element at its correct position acc. to insertion sort*/</p>

```<code>public static int[] merge(int []a1,int a2[],int l1, int l2){

     int len2=l2-l1;
      for(int i=l1-1;i>=0;i--){
        int j=len2-1;

          for(;j>=0 && j+1<l2 && a2[j]>a[i];j--){
             a2[j+1]=a2[j];
           }
          a2[j+1]=a1[i];
            len2++;
         }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have 2 sorted arrays, a1 and a2, of lengths l1 and l2, respectively.  The array a2 has empty space at the end of length l1, so it can hold all of the elements of a1 in addition to its own elements.  Now, I want to merge a1 into a2 so that a2 will contain all the elements of a1 and a2 in sorted order.  Ideally this should use O(1) auxiliary storage space.  I have the following cod,e but something is going wrong:

 public static int[] merge(int []a1,int a2[],int l1, int l2){

         System.out.println("l1 =" +l1 + " l2=" +l2);
         int es = l2-l1;
         int fs = l2-es;

         System.out.println("es= " +es);
         System.out.println("fs = " + fs);
         int j=0;

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

             if(j<fs){
                // System.out.println("i= " + i + "a1[i]=" + a1[i]);
                // System.out.println("j= " + j + "a2[j]=" + a2[j]);
                 if(a1[i]<a2[j]){
                     add(a2,j,a1[i],l2);
                     //i++;
                     fs++;
                 }
             }else{
                 System.out.println("***");
                 a2[j]=a1[i];
             }

             j++;
         }

         return a2;
     }

    public static void add(int []a,int p,int key,int l){

        for(int i=l-1;i>p;i--){
              a[i]= a[i-1];
        }
        a[p]= key;
    }

Does anyone have any ideas on how to fix this?  I used following data to run the code:

int a1[]= new int[]{-1,0,7,8};
int a2[]= new int[7];
a2[0]=1;
a2[1]=3;
a2[2]=9;

Output is

l1 =4 l2=7
es= 3
fs = 4
-1
0
1
3
9
0
0

Body:
The better way to solve the question is used to Insertion sort for merging two sorted arrays in O(1) auxiliary space.

/* as we have to merge the 2 sorted arrays in array2. we begin from the end of array2 and insert the array element at its correct position acc. to insertion sort*/

public static int[] merge(int []a1,int a2[],int l1, int l2){

     int len2=l2-l1;
      for(int i=l1-1;i>=0;i--){
        int j=len2-1;

          for(;j>=0 && j+1<l2 && a2[j]>a[i];j--){
             a2[j+1]=a2[j];
           }
          a2[j+1]=a1[i];
            len2++;
         }
}


问:
Optimise loading multiple tables, transforming and applying operations
I am reading data from about 20 different tables in Pyspark. Here is the pseudo code.

```<code>    initialise empty list of data frame.

    For each table{

            read the table
                apply some transformation (renaming, filtering, standardise
                   fields...)
                append the transformed table to my list of data frame
           }

    Make a union from list of dataframes
    Carry out actions (such as group by sum)
    Export output
</code>```

I am looking for a method that instead of reading the tables one by one in the loop (it's about 10 minutes per table), allows me to perform my operations in parallel and then carry out the union.

答:
I think you can use Fair Scheduler Pools . Please do through this ask , it may helpyou .

How to read many tables from the same database and save them to their own CSV file?

Body:
I am reading data from about 20 different tables in Pyspark. Here is the pseudo code.

    initialise empty list of data frame.

    For each table{

            read the table
                apply some transformation (renaming, filtering, standardise
                   fields...)
                append the transformed table to my list of data frame
           }

    Make a union from list of dataframes
    Carry out actions (such as group by sum)
    Export output

I am looking for a method that instead of reading the tables one by one in the loop (it's about 10 minutes per table), allows me to perform my operations in parallel and then carry out the union.


问:
How do I set a default file for `models.FileField()`?
How do I set a default file for  models.FileField()?

```<code>class MyModel(models.Model):
    myfile = models.FileField(upload_to='mydocs', default=???)
</code>```

The answer would appear to be:

```<code>myfile=models.FileField(upload_to='mydocs', default='mydocs/myfile.pdf')
</code>```

However this does not result in the desired behaviour when creating a new object.

Whereas for other fields like CharField the default= value is displayed on a new form as the widget value. However for FileField it is not, it still results in "no file chosen":

So how does one set a default? Should we try to create a new FieldFile instance? Do we need to create a file object?

答:
it might be that you didn't define the default MEDIA_ROOT in your django settings. Try to define it like that:

```<code>def get_default(self):
    if self.myfile:
        return self.myfile
    else:
        return settings.MEDIA_ROOT + '/mydocs/myfile.pdf'

myfile=models.FileField(upload_to='mydocs', default=get_default)
</code>```

in your settings.py, add:

```<code>MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code>```

in your urls.py, add to the end:

```<code>urlpatterns += static(settings.MEDIA_URL,
                      document_root=settings.MEDIA_ROOT)
</code>```

Body:
How do I set a default file for  models.FileField()?

class MyModel(models.Model):
    myfile = models.FileField(upload_to='mydocs', default=???)

The answer would appear to be:

myfile=models.FileField(upload_to='mydocs', default='mydocs/myfile.pdf')

However this does not result in the desired behaviour when creating a new object.

Whereas for other fields like CharField the default= value is displayed on a new form as the widget value. However for FileField it is not, it still results in "no file chosen":

So how does one set a default? Should we try to create a new FieldFile instance? Do we need to create a file object?

Body:
it might be that you didn't define the default MEDIA_ROOT in your django settings. Try to define it like that:

def get_default(self):
    if self.myfile:
        return self.myfile
    else:
        return settings.MEDIA_ROOT + '/mydocs/myfile.pdf'

myfile=models.FileField(upload_to='mydocs', default=get_default)

in your settings.py, add:

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

in your urls.py, add to the end:

urlpatterns += static(settings.MEDIA_URL,
                      document_root=settings.MEDIA_ROOT)


问:
Filter array of objects by nested array of object value
Suppose I have an array of objects, each of which contains a nested array of objects likes:

```<code>[
  {
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 01, username: 'mike' },
      { id: 02, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 03, username: 'steve' },
      { id: 04, username: 'mike' },
      { id: 05, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 06, username: 'brad' },
      { id: 07, username: 'cameron' },
      { id: 08, username: 'liam' }
    ]
  }
]
</code>```

How can I filter the outer array by the username value inside its items nested array? Let's say output the items that contains in its inner arrays objects with property username: 'mike'?

答:
Use filter and some functions:

const input = [{
    id: 1,
    title: "Lorem",
    private: false,
    likes: [{
      id: 1,
      username: "mike"
    }, {
      id: 2,
      username: "john"
    }]
  },
  {
    id: 2,
    title: "Ipsum",
    private: true,
    likes: [{
        id: 3,
        username: "steve"
      },
      {
        id: 4,
        username: "mike"
      },
      {
        id: 5,
        username: "sara"
      }
    ]
  },
  {
    id: 3,
    title: "Dolor",
    private: false,
    likes: [{
        id: 6,
        username: "brad"
      },
      {
        id: 7,
        username: "cameron"
      },
      {
        id: 8,
        username: "liam"
      }
    ]
  }
];

const criteria = {
  username: "mike"
};

const result = input.filter(x =>
  x.likes.some(y => y.username === criteria.username)
);
console.log(result);```

Body:
Suppose I have an array of objects, each of which contains a nested array of objects likes:

[
  {
    id: 1,
    title: 'Lorem',
    private: false,
    likes: [
      { id: 01, username: 'mike' },
      { id: 02, username: 'john' }
    ]
  },
  {
    id: 2,
    title: 'Ipsum',
    private: true,
    likes: [
      { id: 03, username: 'steve' },
      { id: 04, username: 'mike' },
      { id: 05, username: 'sara' }
    ]
  },
  {
    id: 3,
    title: 'Dolor',
    private: false,
    likes: [
      { id: 06, username: 'brad' },
      { id: 07, username: 'cameron' },
      { id: 08, username: 'liam' }
    ]
  }
]

How can I filter the outer array by the username value inside its items nested array? Let's say output the items that contains in its inner arrays objects with property username: 'mike'?


问:
Windows 10 can't connect to Ubuntu 16.04 samba
I reinstall Ubuntu 16.04 Desktop 32bit on an old laptop and setup samba as https://tutorials.ubuntu.com/tutorial/install-and-configure-samba#0 mentions. When I try to connect from a Windows 10 or Windows 7 machine I get the following:
Windows can't communicate with the device or resource(192.168.1.50)
The resource is available but is not responding to connection attempts.

any suggestion?

答:
In /etc/samba/smb.conf should add this

```<code>[global]
    client min protocol = SMB3
    client max protocol = SMB3
</code>```

In windows 10 should edit this
enter in Local Group Policy Editor (search in windows) Computer Configuration -> Administrative Templates -> Network -> Lanman Workstation -> Enable Insecure Guest Logon - Enabled

Body:
In /etc/samba/smb.conf should add this

[global]
    client min protocol = SMB3
    client max protocol = SMB3

In windows 10 should edit this
enter in Local Group Policy Editor (search in windows) Computer Configuration -> Administrative Templates -> Network -> Lanman Workstation -> Enable Insecure Guest Logon - Enabled


问:
Misuning simpler regex format?
So I am working on a fraction class for school and am using a regex pattern and matcher for user input. I found this online so i'll admit im not exactly sure what does what, but the following pattern finds each digit, middle operation, and allows spaces and tabs between all characters of the user's input(a fraction expression).

```<code>String fractionPattern = "\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*\\/\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*([-+*/])\\s*\\t*\\\\*t(\\d+)\\s*\\t*\\\\*t*\\/\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*";
</code>```

I've tried researching java regex metacharacters and symbol meanings, but I am sort of struggling. Can someone offer me an explanation on each character? Or possibly a simpler way of accomplishing the same thing.

答:
So you're looking to match fractions? Like "2 / 3" or whatever, and allow spaces? If so, you want to match (and capture) some string of digits, then a '/' character, then match and capture another string of digits. Without considering spaces, this is just:

```<code>"(\\d+)/(\\d+)"
</code>```

\d in a regex matches any digit (0-9), but since we specify regexes with Strings, we have to escape the backslash itself. That is, the Java string literal "\" results in a String object with one backslash character.
The + means "one or more", and the parentheses capture it. Then the slash is just a literal slash.
To make it allow spaces, match and discard any space. \s matches any type of space (space, tab, newline), and again we have to escape the backslash:

```<code>"(\\d+)\\s*/\\s*(\\d+)"
</code>```

* means "zero or more". So from left to right, this means:

One or more digits, which are captured

Zero or more spaces

A literal slash

Zero or more spaces

One or more digits, which are captured

To handle whitespace on the ends, either match space there, or
trim() the string first.

Title: Misuning simpler regex format?

Body:
So I am working on a fraction class for school and am using a regex pattern and matcher for user input. I found this online so i'll admit im not exactly sure what does what, but the following pattern finds each digit, middle operation, and allows spaces and tabs between all characters of the user's input(a fraction expression).

String fractionPattern = "\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*\\/\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*([-+*/])\\s*\\t*\\\\*t(\\d+)\\s*\\t*\\\\*t*\\/\\s*\\t*\\\\*t*(-?\\d+)\\s*\\t*\\\\*t*";

I've tried researching java regex metacharacters and symbol meanings, but I am sort of struggling. Can someone offer me an explanation on each character? Or possibly a simpler way of accomplishing the same thing.

Body:
So you're looking to match fractions? Like "2 / 3" or whatever, and allow spaces? If so, you want to match (and capture) some string of digits, then a '/' character, then match and capture another string of digits. Without considering spaces, this is just:

"(\\d+)/(\\d+)"

\d in a regex matches any digit (0-9), but since we specify regexes with Strings, we have to escape the backslash itself. That is, the Java string literal "\" results in a String object with one backslash character.
The + means "one or more", and the parentheses capture it. Then the slash is just a literal slash.
To make it allow spaces, match and discard any space. \s matches any type of space (space, tab, newline), and again we have to escape the backslash:

"(\\d+)\\s*/\\s*(\\d+)"

* means "zero or more". So from left to right, this means:

One or more digits, which are captured

Zero or more spaces

A literal slash

Zero or more spaces

One or more digits, which are captured

To handle whitespace on the ends, either match space there, or
trim() the string first.


问:
C++: Stroustrup iterator_traits example not compiling?
I'm trying to compile the code from Stroustrups C++ 4th Ed Page 124 and 125, section Iterator Traits.  Unfortunately, the compilation results in numerous errors which look like they are in the template system.  Does anyone know whats wrong with this code?

Thanks

```<code>#include <iostream>
#include <iterator>
#include <algorithm>
#include <forward_list>
#include <vector>
using namespace std;

template<typename Ran>
void sort_helper(Ran beg, Ran end, random_access_iterator_tag)
{
    sort(beg, end);
}

template<typename For>
void sort_helper(For beg, For end, forward_iterator_tag)
{
    vector<decltype(*beg)> v {beg, end};
    sort(v.begin(), v.end());
    copy(v.begin(), v.end(), beg);
}

template<typename C>
using Iterator_type = typename C::iterator;

template<typename Iter>
using Iterator_category = typename std::iterator_traits<Iter>::iterator_category;

template<typename C> void sort(C& c)
{
    using Iter = Iterator_type<C>; // ex. vector<int>::iterator
    sort_helper(c.begin(), c.end(), Iterator_category<Iter>{});
}

int main(int argc, char *argv[])
{
    forward_list<int> fl = {2, 1, 0};
    vector<int> v = {2, 1, 0};

    sort(fl); // this line causes compilation error
    sort(v);

    return 0;
}
</code>```

Errors:

```<code>In file included from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/x86_64-linux-gnu/bits/c++allocator.h:33,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/allocator.h:46,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/string:41,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/locale_classes.h:40,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/ios_base.h:41,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ios:42,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ostream:38,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/iostream:39,
                 from <source>:1:
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ext/new_allocator.h: In instantiation of 'class __gnu_cxx::new_allocator<int&>':
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/allocator.h:116:11:   required from 'class std::allocator<int&>'
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_vector.h:87:21:   required from 'struct std::_Vector_base<int&, std::allocator<int&> >'
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_vector.h:389:11:   required from 'class std::vector<int&, std::allocator<int&> >'
<source>:17:28:   required from 'void sort_helper(For, For, std::forward_iterator_tag) [with For = std::_Fwd_list_iterator<int>]'
<source>:31:16:   required from 'void sort(C&) [with C = std::forward_list<int>]'
<source>:39:12:   required from here
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ext/new_allocator.h:62:26: error: forming pointer to reference type 'int&'
   62 |       typedef _Tp*       pointer;
      |                          ^~~~~~~
... and more ...
</code>```

答:
This is a known error in the book.

From http://www.stroustrup.com/4th_printing3.html:

pg 125: s/decltype(*beg)/Value_type<For>/ reparing the use of decltype would take more space than I have here.

Body:
I'm trying to compile the code from Stroustrups C++ 4th Ed Page 124 and 125, section Iterator Traits.  Unfortunately, the compilation results in numerous errors which look like they are in the template system.  Does anyone know whats wrong with this code?

Thanks

#include <iostream>
#include <iterator>
#include <algorithm>
#include <forward_list>
#include <vector>
using namespace std;

template<typename Ran>
void sort_helper(Ran beg, Ran end, random_access_iterator_tag)
{
    sort(beg, end);
}

template<typename For>
void sort_helper(For beg, For end, forward_iterator_tag)
{
    vector<decltype(*beg)> v {beg, end};
    sort(v.begin(), v.end());
    copy(v.begin(), v.end(), beg);
}

template<typename C>
using Iterator_type = typename C::iterator;

template<typename Iter>
using Iterator_category = typename std::iterator_traits<Iter>::iterator_category;

template<typename C> void sort(C& c)
{
    using Iter = Iterator_type<C>; // ex. vector<int>::iterator
    sort_helper(c.begin(), c.end(), Iterator_category<Iter>{});
}

int main(int argc, char *argv[])
{
    forward_list<int> fl = {2, 1, 0};
    vector<int> v = {2, 1, 0};

    sort(fl); // this line causes compilation error
    sort(v);

    return 0;
}

Errors:

In file included from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/x86_64-linux-gnu/bits/c++allocator.h:33,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/allocator.h:46,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/string:41,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/locale_classes.h:40,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/ios_base.h:41,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ios:42,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ostream:38,
                 from /opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/iostream:39,
                 from <source>:1:
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ext/new_allocator.h: In instantiation of 'class __gnu_cxx::new_allocator<int&>':
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/allocator.h:116:11:   required from 'class std::allocator<int&>'
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_vector.h:87:21:   required from 'struct std::_Vector_base<int&, std::allocator<int&> >'
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/bits/stl_vector.h:389:11:   required from 'class std::vector<int&, std::allocator<int&> >'
<source>:17:28:   required from 'void sort_helper(For, For, std::forward_iterator_tag) [with For = std::_Fwd_list_iterator<int>]'
<source>:31:16:   required from 'void sort(C&) [with C = std::forward_list<int>]'
<source>:39:12:   required from here
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/ext/new_allocator.h:62:26: error: forming pointer to reference type 'int&'
   62 |       typedef _Tp*       pointer;
      |                          ^~~~~~~
... and more ...


问:
Execute javascript when another function exists
I'm writing two scripts in an web environment where I don't have control over the order in which they are loaded.  Let's say the two scripts are called MyUtil and DoSomething.

MyUtil contains utilities that I will bind to the window object using window.myUtil = myUtil.  I'm then going to call methods of myUtil from within DoSomething.

If MyUtil is loaded first, everything will work. If it's loaded second, window.myUtil will be undefined.

How can I modify the code in DoSomething (and/or MyUtil) to wait until window.myUtil exists before DoSomething executes its code?

NB: I'm using jQuery 1.2.3.

答:
Would something like this work? </p>

```<code> function function1(callback){
        var params={
            type: "POST",
            url: "./ajax/doSomethingSlow.php",
            data: "",
            success: function(msg){
                callback(msg);
            },
            error: function(){
                callback('');
            }
        };
        var result=$.ajax(params).responseText;
    }

function1(function(){
   //call function2 here:
   function2();
});
</code>```

Body:
Would something like this work?

 function function1(callback){
        var params={
            type: "POST",
            url: "./ajax/doSomethingSlow.php",
            data: "",
            success: function(msg){
                callback(msg);
            },
            error: function(){
                callback('');
            }
        };
        var result=$.ajax(params).responseText;
    }

function1(function(){
   //call function2 here:
   function2();
});


问:
How do you sum a range of cells?
Is there a way to use sheet functions like SUM, SUMIF, COUNTIF, COUNA etc in Google Apps Scripts to automate ?</p>

答:
It's rather easy to combine them all into your scripts since it just requires a little logic.  You can play with this by selecting a range and then executing the function and the results are displayed on a toast.</p>

```<code>function sumandcount() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var rg=sh.getActiveRange();
  var values=rg.getValues();
  var sumifgtr5=0;
  var countifgtr5=0
  values.forEach(function(r,i){
    r.forEach(function(c,j){
      if(c>5) {
        sumifgtr5+=c;
        countifgtr5+=1;
      }
    })
  });
  var obj={count:countifgtr5,sum:sumifgtr5};
  ss.toast(obj.count, obj.sum);
}
</code>```

Title: How do you sum a range of cells?

Body:
It's rather easy to combine them all into your scripts since it just requires a little logic.  You can play with this by selecting a range and then executing the function and the results are displayed on a toast.

function sumandcount() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var rg=sh.getActiveRange();
  var values=rg.getValues();
  var sumifgtr5=0;
  var countifgtr5=0
  values.forEach(function(r,i){
    r.forEach(function(c,j){
      if(c>5) {
        sumifgtr5+=c;
        countifgtr5+=1;
      }
    })
  });
  var obj={count:countifgtr5,sum:sumifgtr5};
  ss.toast(obj.count, obj.sum);
}


问:
R Markdown: Remove tabset configuration when rendering
I have the following question: I am creating an HTML document using RMD and html_document. I use tabset and tabset-pills to structure the content. My question now is:

Can I render the same RMD document but do not interprete the tabset settings?

To provide an example: Can I render this RMD file resulting in the two different outputs below?

```<code>---
output: html_document
---

# Headline 1

## Headline 2 {.tabset}

### Headline 3 in a tab

### Headline 4 in a tab

### Headline 5 in a tab
</code>```

Thanks
Stephan

答:
You can use a parameterized document and inline code:

```<code>---
title: Hello
output: html_document
params:
  intab: TRUE
---

# Headline 1

## Headline 2 `r if (isTRUE(params$intab)) "{.tabset}"`

### Headline 3 in a tab

### Headline 4 in a tab

### Headline 5 in a tab
</code>```

Rscript.exe -e "rmarkdown::render('62095186.Rmd')"                            # default
# Rscript.exe -e "rmarkdown::render('62095186.Rmd', params=list(intab=TRUE))" # same
Rscript.exe -e "rmarkdown::render('62095186.Rmd', params=list(intab=FALSE))"  # by exception
```

Body:
I have the following question: I am creating an HTML document using RMD and html_document. I use tabset and tabset-pills to structure the content. My question now is:

Can I render the same RMD document but do not interprete the tabset settings?

To provide an example: Can I render this RMD file resulting in the two different outputs below?

---
output: html_document
---

# Headline 1

## Headline 2 {.tabset}

### Headline 3 in a tab

### Headline 4 in a tab

### Headline 5 in a tab

Thanks
Stephan

Body:
You can use a parameterized document and inline code:

---
title: Hello
output: html_document
params:
  intab: TRUE
---

# Headline 1

## Headline 2 `r if (isTRUE(params$intab)) "{.tabset}"`

### Headline 3 in a tab

### Headline 4 in a tab

### Headline 5 in a tab

Rscript.exe -e "rmarkdown::render('62095186.Rmd')"                            # default
# Rscript.exe -e "rmarkdown::render('62095186.Rmd', params=list(intab=TRUE))" # same
Rscript.exe -e "rmarkdown::render('62095186.Rmd', params=list(intab=FALSE))"  # by exception